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) {
963 if (subtype == VSLENGTH)
974 switch (subtype & VSTYPE) {
1000 case VSTRIMRIGHTMAX:
1007 out1fmt("<subtype %d>", subtype);
1014 case CTLBACKQ|CTLQUOTE:
1017 shtree(bqlist->n, -1, NULL, fp);
1028 shcmd(union node *cmd, FILE *fp)
1036 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1042 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1046 switch (np->nfile.type) {
1047 case NTO: s = ">>"+1; dftfd = 1; break;
1048 case NCLOBBER: s = ">|"; dftfd = 1; break;
1049 case NAPPEND: s = ">>"; dftfd = 1; break;
1050 #if ENABLE_ASH_BASH_COMPAT
1053 case NTOFD: s = ">&"; dftfd = 1; break;
1054 case NFROM: s = "<"; break;
1055 case NFROMFD: s = "<&"; break;
1056 case NFROMTO: s = "<>"; break;
1057 default: s = "*error*"; break;
1059 if (np->nfile.fd != dftfd)
1060 fprintf(fp, "%d", np->nfile.fd);
1062 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1063 fprintf(fp, "%d", np->ndup.dupfd);
1065 sharg(np->nfile.fname, fp);
1072 shtree(union node *n, int ind, char *pfx, FILE *fp)
1074 struct nodelist *lp;
1080 indent(ind, pfx, fp);
1082 if (n == NODE_EOF) {
1097 shtree(n->nbinary.ch1, ind, NULL, fp);
1100 shtree(n->nbinary.ch2, ind, NULL, fp);
1108 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1109 shtree(lp->n, 0, NULL, fp);
1113 if (n->npipe.pipe_backgnd)
1119 fprintf(fp, "<node type %d>", n->type);
1127 showtree(union node *n)
1129 trace_puts("showtree called\n");
1130 shtree(n, 1, NULL, stderr);
1136 /* ============ Parser data */
1139 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1142 struct strlist *next;
1149 struct strpush *prev; /* preceding string on stack */
1151 int prev_left_in_line;
1152 #if ENABLE_ASH_ALIAS
1153 struct alias *ap; /* if push was associated with an alias */
1155 char *string; /* remember the string since it may change */
1159 struct parsefile *prev; /* preceding file on stack */
1160 int linno; /* current line */
1161 int pf_fd; /* file descriptor (or -1 if string) */
1162 int left_in_line; /* number of chars left in this line */
1163 int left_in_buffer; /* number of chars left in this buffer past the line */
1164 char *next_to_pgetc; /* next char in buffer */
1165 char *buf; /* input buffer */
1166 struct strpush *strpush; /* for pushing strings at this level */
1167 struct strpush basestrpush; /* so pushing one is fast */
1170 static struct parsefile basepf; /* top level input file */
1171 static struct parsefile *g_parsefile = &basepf; /* current input file */
1172 static int startlinno; /* line # where last token started */
1173 static char *commandname; /* currently executing command */
1174 static struct strlist *cmdenviron; /* environment for builtin command */
1175 static uint8_t exitstatus; /* exit status of last command */
1178 /* ============ Message printing */
1181 ash_vmsg(const char *msg, va_list ap)
1183 fprintf(stderr, "%s: ", arg0);
1185 if (strcmp(arg0, commandname))
1186 fprintf(stderr, "%s: ", commandname);
1187 if (!iflag || g_parsefile->pf_fd > 0)
1188 fprintf(stderr, "line %d: ", startlinno);
1190 vfprintf(stderr, msg, ap);
1191 outcslow('\n', stderr);
1195 * Exverror is called to raise the error exception. If the second argument
1196 * is not NULL then error prints an error message using printf style
1197 * formatting. It then raises the error exception.
1199 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1201 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1205 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1207 TRACE(("\") pid=%d\n", getpid()));
1209 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1214 flush_stdout_stderr();
1215 raise_exception(cond);
1219 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1221 ash_msg_and_raise_error(const char *msg, ...)
1226 ash_vmsg_and_raise(EXERROR, msg, ap);
1231 static void raise_error_syntax(const char *) NORETURN;
1233 raise_error_syntax(const char *msg)
1235 ash_msg_and_raise_error("syntax error: %s", msg);
1239 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1241 ash_msg_and_raise(int cond, const char *msg, ...)
1246 ash_vmsg_and_raise(cond, msg, ap);
1252 * error/warning routines for external builtins
1255 ash_msg(const char *fmt, ...)
1265 * Return a string describing an error. The returned string may be a
1266 * pointer to a static buffer that will be overwritten on the next call.
1267 * Action describes the operation that got the error.
1270 errmsg(int e, const char *em)
1272 if (e == ENOENT || e == ENOTDIR) {
1279 /* ============ Memory allocation */
1282 /* I consider these wrappers nearly useless:
1283 * ok, they return you to nearest exception handler, but
1284 * how much memory do you leak in the process, making
1285 * memory starvation worse?
1288 ckrealloc(void * p, size_t nbytes)
1290 p = realloc(p, nbytes);
1292 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1297 ckmalloc(size_t nbytes)
1299 return ckrealloc(NULL, nbytes);
1303 ckzalloc(size_t nbytes)
1305 return memset(ckmalloc(nbytes), 0, nbytes);
1309 ckstrdup(const char *s)
1311 char *p = strdup(s);
1313 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1317 /* Using bbox equivalents. They exit if out of memory */
1318 # define ckrealloc xrealloc
1319 # define ckmalloc xmalloc
1320 # define ckzalloc xzalloc
1321 # define ckstrdup xstrdup
1325 * It appears that grabstackstr() will barf with such alignments
1326 * because stalloc() will return a string allocated in a new stackblock.
1328 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1330 /* Most machines require the value returned from malloc to be aligned
1331 * in some way. The following macro will get this right
1332 * on many machines. */
1333 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1334 /* Minimum size of a block */
1335 MINSIZE = SHELL_ALIGN(504),
1338 struct stack_block {
1339 struct stack_block *prev;
1340 char space[MINSIZE];
1344 struct stack_block *stackp;
1347 struct stackmark *marknext;
1351 struct globals_memstack {
1352 struct stack_block *g_stackp; // = &stackbase;
1353 struct stackmark *markp;
1354 char *g_stacknxt; // = stackbase.space;
1355 char *sstrend; // = stackbase.space + MINSIZE;
1356 size_t g_stacknleft; // = MINSIZE;
1357 int herefd; // = -1;
1358 struct stack_block stackbase;
1360 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1361 #define G_memstack (*ash_ptr_to_globals_memstack)
1362 #define g_stackp (G_memstack.g_stackp )
1363 #define markp (G_memstack.markp )
1364 #define g_stacknxt (G_memstack.g_stacknxt )
1365 #define sstrend (G_memstack.sstrend )
1366 #define g_stacknleft (G_memstack.g_stacknleft)
1367 #define herefd (G_memstack.herefd )
1368 #define stackbase (G_memstack.stackbase )
1369 #define INIT_G_memstack() do { \
1370 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1372 g_stackp = &stackbase; \
1373 g_stacknxt = stackbase.space; \
1374 g_stacknleft = MINSIZE; \
1375 sstrend = stackbase.space + MINSIZE; \
1380 #define stackblock() ((void *)g_stacknxt)
1381 #define stackblocksize() g_stacknleft
1384 * Parse trees for commands are allocated in lifo order, so we use a stack
1385 * to make this more efficient, and also to avoid all sorts of exception
1386 * handling code to handle interrupts in the middle of a parse.
1388 * The size 504 was chosen because the Ultrix malloc handles that size
1392 stalloc(size_t nbytes)
1397 aligned = SHELL_ALIGN(nbytes);
1398 if (aligned > g_stacknleft) {
1401 struct stack_block *sp;
1403 blocksize = aligned;
1404 if (blocksize < MINSIZE)
1405 blocksize = MINSIZE;
1406 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1407 if (len < blocksize)
1408 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1411 sp->prev = g_stackp;
1412 g_stacknxt = sp->space;
1413 g_stacknleft = blocksize;
1414 sstrend = g_stacknxt + blocksize;
1419 g_stacknxt += aligned;
1420 g_stacknleft -= aligned;
1425 stzalloc(size_t nbytes)
1427 return memset(stalloc(nbytes), 0, nbytes);
1434 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1435 write(STDERR_FILENO, "stunalloc\n", 10);
1439 g_stacknleft += g_stacknxt - (char *)p;
1444 * Like strdup but works with the ash stack.
1447 ststrdup(const char *p)
1449 size_t len = strlen(p) + 1;
1450 return memcpy(stalloc(len), p, len);
1454 setstackmark(struct stackmark *mark)
1456 mark->stackp = g_stackp;
1457 mark->stacknxt = g_stacknxt;
1458 mark->stacknleft = g_stacknleft;
1459 mark->marknext = markp;
1464 popstackmark(struct stackmark *mark)
1466 struct stack_block *sp;
1472 markp = mark->marknext;
1473 while (g_stackp != mark->stackp) {
1475 g_stackp = sp->prev;
1478 g_stacknxt = mark->stacknxt;
1479 g_stacknleft = mark->stacknleft;
1480 sstrend = mark->stacknxt + mark->stacknleft;
1485 * When the parser reads in a string, it wants to stick the string on the
1486 * stack and only adjust the stack pointer when it knows how big the
1487 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1488 * of space on top of the stack and stackblocklen returns the length of
1489 * this block. Growstackblock will grow this space by at least one byte,
1490 * possibly moving it (like realloc). Grabstackblock actually allocates the
1491 * part of the block that has been used.
1494 growstackblock(void)
1498 newlen = g_stacknleft * 2;
1499 if (newlen < g_stacknleft)
1500 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1504 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1505 struct stack_block *oldstackp;
1506 struct stackmark *xmark;
1507 struct stack_block *sp;
1508 struct stack_block *prevstackp;
1512 oldstackp = g_stackp;
1514 prevstackp = sp->prev;
1515 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1516 sp = ckrealloc(sp, grosslen);
1517 sp->prev = prevstackp;
1519 g_stacknxt = sp->space;
1520 g_stacknleft = newlen;
1521 sstrend = sp->space + newlen;
1524 * Stack marks pointing to the start of the old block
1525 * must be relocated to point to the new block
1528 while (xmark != NULL && xmark->stackp == oldstackp) {
1529 xmark->stackp = g_stackp;
1530 xmark->stacknxt = g_stacknxt;
1531 xmark->stacknleft = g_stacknleft;
1532 xmark = xmark->marknext;
1536 char *oldspace = g_stacknxt;
1537 size_t oldlen = g_stacknleft;
1538 char *p = stalloc(newlen);
1540 /* free the space we just allocated */
1541 g_stacknxt = memcpy(p, oldspace, oldlen);
1542 g_stacknleft += newlen;
1547 grabstackblock(size_t len)
1549 len = SHELL_ALIGN(len);
1551 g_stacknleft -= len;
1555 * The following routines are somewhat easier to use than the above.
1556 * The user declares a variable of type STACKSTR, which may be declared
1557 * to be a register. The macro STARTSTACKSTR initializes things. Then
1558 * the user uses the macro STPUTC to add characters to the string. In
1559 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1560 * grown as necessary. When the user is done, she can just leave the
1561 * string there and refer to it using stackblock(). Or she can allocate
1562 * the space for it using grabstackstr(). If it is necessary to allow
1563 * someone else to use the stack temporarily and then continue to grow
1564 * the string, the user should use grabstack to allocate the space, and
1565 * then call ungrabstr(p) to return to the previous mode of operation.
1567 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1568 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1569 * is space for at least one character.
1574 size_t len = stackblocksize();
1575 if (herefd >= 0 && len >= 1024) {
1576 full_write(herefd, stackblock(), len);
1577 return stackblock();
1580 return (char *)stackblock() + len;
1584 * Called from CHECKSTRSPACE.
1587 makestrspace(size_t newlen, char *p)
1589 size_t len = p - g_stacknxt;
1590 size_t size = stackblocksize();
1595 size = stackblocksize();
1597 if (nleft >= newlen)
1601 return (char *)stackblock() + len;
1605 stack_nputstr(const char *s, size_t n, char *p)
1607 p = makestrspace(n, p);
1608 p = (char *)memcpy(p, s, n) + n;
1613 stack_putstr(const char *s, char *p)
1615 return stack_nputstr(s, strlen(s), p);
1619 _STPUTC(int c, char *p)
1627 #define STARTSTACKSTR(p) ((p) = stackblock())
1628 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1629 #define CHECKSTRSPACE(n, p) do { \
1632 size_t m = sstrend - q; \
1634 (p) = makestrspace(l, q); \
1636 #define USTPUTC(c, p) (*(p)++ = (c))
1637 #define STACKSTRNUL(p) do { \
1638 if ((p) == sstrend) \
1639 (p) = growstackstr(); \
1642 #define STUNPUTC(p) (--(p))
1643 #define STTOPC(p) ((p)[-1])
1644 #define STADJUST(amount, p) ((p) += (amount))
1646 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1647 #define ungrabstackstr(s, p) stunalloc(s)
1648 #define stackstrend() ((void *)sstrend)
1651 /* ============ String helpers */
1654 * prefix -- see if pfx is a prefix of string.
1657 prefix(const char *string, const char *pfx)
1660 if (*pfx++ != *string++)
1663 return (char *) string;
1667 * Check for a valid number. This should be elsewhere.
1670 is_number(const char *p)
1675 } while (*++p != '\0');
1680 * Convert a string of digits to an integer, printing an error message on
1684 number(const char *s)
1687 ash_msg_and_raise_error(msg_illnum, s);
1692 * Produce a possibly single quoted string suitable as input to the shell.
1693 * The return string is allocated on the stack.
1696 single_quote(const char *s)
1706 len = strchrnul(s, '\'') - s;
1708 q = p = makestrspace(len + 3, p);
1711 q = (char *)memcpy(q, s, len) + len;
1720 do len++; while (*++s == '\'');
1722 q = p = makestrspace(len + 3, p);
1725 q = (char *)memcpy(q, s - len, len) + len;
1733 return stackblock();
1737 /* ============ nextopt */
1739 static char **argptr; /* argument list for builtin commands */
1740 static char *optionarg; /* set by nextopt (like getopt) */
1741 static char *optptr; /* used by nextopt */
1744 * XXX - should get rid of. Have all builtins use getopt(3).
1745 * The library getopt must have the BSD extension static variable
1746 * "optreset", otherwise it can't be used within the shell safely.
1748 * Standard option processing (a la getopt) for builtin routines.
1749 * The only argument that is passed to nextopt is the option string;
1750 * the other arguments are unnecessary. It returns the character,
1751 * or '\0' on end of input.
1754 nextopt(const char *optstring)
1761 if (p == NULL || *p == '\0') {
1762 /* We ate entire "-param", take next one */
1768 if (*++p == '\0') /* just "-" ? */
1771 if (LONE_DASH(p)) /* "--" ? */
1773 /* p => next "-param" */
1775 /* p => some option char in the middle of a "-param" */
1777 for (q = optstring; *q != c;) {
1779 ash_msg_and_raise_error("illegal option -%c", c);
1787 ash_msg_and_raise_error("no arg for -%c option", c);
1797 /* ============ Shell variables */
1800 * The parsefile structure pointed to by the global variable parsefile
1801 * contains information about the current file being read.
1804 int nparam; /* # of positional parameters (without $0) */
1805 #if ENABLE_ASH_GETOPTS
1806 int optind; /* next parameter to be processed by getopts */
1807 int optoff; /* used by getopts */
1809 unsigned char malloced; /* if parameter list dynamically allocated */
1810 char **p; /* parameter list */
1814 * Free the list of positional parameters.
1817 freeparam(volatile struct shparam *param)
1819 if (param->malloced) {
1821 ap = ap1 = param->p;
1828 #if ENABLE_ASH_GETOPTS
1829 static void FAST_FUNC getoptsreset(const char *value);
1833 struct var *next; /* next entry in hash list */
1834 int flags; /* flags are defined above */
1835 const char *var_text; /* name=value */
1836 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1837 /* the variable gets set/unset */
1841 struct localvar *next; /* next local variable in list */
1842 struct var *vp; /* the variable that was made local */
1843 int flags; /* saved flags */
1844 const char *text; /* saved text */
1848 #define VEXPORT 0x01 /* variable is exported */
1849 #define VREADONLY 0x02 /* variable cannot be modified */
1850 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1851 #define VTEXTFIXED 0x08 /* text is statically allocated */
1852 #define VSTACK 0x10 /* text is allocated on the stack */
1853 #define VUNSET 0x20 /* the variable is not set */
1854 #define VNOFUNC 0x40 /* don't call the callback function */
1855 #define VNOSET 0x80 /* do not set variable - just readonly test */
1856 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1857 #if ENABLE_ASH_RANDOM_SUPPORT
1858 # define VDYNAMIC 0x200 /* dynamic variable */
1864 /* Need to be before varinit_data[] */
1865 #if ENABLE_LOCALE_SUPPORT
1866 static void FAST_FUNC
1867 change_lc_all(const char *value)
1869 if (value && *value != '\0')
1870 setlocale(LC_ALL, value);
1872 static void FAST_FUNC
1873 change_lc_ctype(const char *value)
1875 if (value && *value != '\0')
1876 setlocale(LC_CTYPE, value);
1880 static void chkmail(void);
1881 static void changemail(const char *) FAST_FUNC;
1883 static void changepath(const char *) FAST_FUNC;
1884 #if ENABLE_ASH_RANDOM_SUPPORT
1885 static void change_random(const char *) FAST_FUNC;
1888 static const struct {
1890 const char *var_text;
1891 void (*var_func)(const char *) FAST_FUNC;
1892 } varinit_data[] = {
1893 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1895 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1896 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1898 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1899 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1900 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1901 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1902 #if ENABLE_ASH_GETOPTS
1903 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1905 #if ENABLE_ASH_RANDOM_SUPPORT
1906 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1908 #if ENABLE_LOCALE_SUPPORT
1909 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1910 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1912 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1913 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1919 struct globals_var {
1920 struct shparam shellparam; /* $@ current positional parameters */
1921 struct redirtab *redirlist;
1923 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1924 struct var *vartab[VTABSIZE];
1925 struct var varinit[ARRAY_SIZE(varinit_data)];
1927 extern struct globals_var *const ash_ptr_to_globals_var;
1928 #define G_var (*ash_ptr_to_globals_var)
1929 #define shellparam (G_var.shellparam )
1930 //#define redirlist (G_var.redirlist )
1931 #define g_nullredirs (G_var.g_nullredirs )
1932 #define preverrout_fd (G_var.preverrout_fd)
1933 #define vartab (G_var.vartab )
1934 #define varinit (G_var.varinit )
1935 #define INIT_G_var() do { \
1937 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1939 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1940 varinit[i].flags = varinit_data[i].flags; \
1941 varinit[i].var_text = varinit_data[i].var_text; \
1942 varinit[i].var_func = varinit_data[i].var_func; \
1946 #define vifs varinit[0]
1948 # define vmail (&vifs)[1]
1949 # define vmpath (&vmail)[1]
1950 # define vpath (&vmpath)[1]
1952 # define vpath (&vifs)[1]
1954 #define vps1 (&vpath)[1]
1955 #define vps2 (&vps1)[1]
1956 #define vps4 (&vps2)[1]
1957 #if ENABLE_ASH_GETOPTS
1958 # define voptind (&vps4)[1]
1959 # if ENABLE_ASH_RANDOM_SUPPORT
1960 # define vrandom (&voptind)[1]
1963 # if ENABLE_ASH_RANDOM_SUPPORT
1964 # define vrandom (&vps4)[1]
1969 * The following macros access the values of the above variables.
1970 * They have to skip over the name. They return the null string
1971 * for unset variables.
1973 #define ifsval() (vifs.var_text + 4)
1974 #define ifsset() ((vifs.flags & VUNSET) == 0)
1976 # define mailval() (vmail.var_text + 5)
1977 # define mpathval() (vmpath.var_text + 9)
1978 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1980 #define pathval() (vpath.var_text + 5)
1981 #define ps1val() (vps1.var_text + 4)
1982 #define ps2val() (vps2.var_text + 4)
1983 #define ps4val() (vps4.var_text + 4)
1984 #if ENABLE_ASH_GETOPTS
1985 # define optindval() (voptind.var_text + 7)
1988 #if ENABLE_ASH_GETOPTS
1989 static void FAST_FUNC
1990 getoptsreset(const char *value)
1992 shellparam.optind = number(value);
1993 shellparam.optoff = -1;
1997 /* math.h has these, otherwise define our private copies */
1998 #if !ENABLE_SH_MATH_SUPPORT
1999 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
2000 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
2002 * Return the pointer to the first char which is not part of a legal variable name
2003 * (a letter or underscore followed by letters, underscores, and digits).
2006 endofname(const char *name)
2008 if (!is_name(*name))
2011 if (!is_in_name(*name))
2019 * Compares two strings up to the first = or '\0'. The first
2020 * string must be terminated by '='; the second may be terminated by
2021 * either '=' or '\0'.
2024 varcmp(const char *p, const char *q)
2028 while ((c = *p) == (d = *q)) {
2043 * Find the appropriate entry in the hash table from the name.
2045 static struct var **
2046 hashvar(const char *p)
2050 hashval = ((unsigned char) *p) << 4;
2051 while (*p && *p != '=')
2052 hashval += (unsigned char) *p++;
2053 return &vartab[hashval % VTABSIZE];
2057 vpcmp(const void *a, const void *b)
2059 return varcmp(*(const char **)a, *(const char **)b);
2063 * This routine initializes the builtin variables.
2073 * PS1 depends on uid
2075 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2076 vps1.var_text = "PS1=\\w \\$ ";
2079 vps1.var_text = "PS1=# ";
2082 end = vp + ARRAY_SIZE(varinit);
2084 vpp = hashvar(vp->var_text);
2087 } while (++vp < end);
2090 static struct var **
2091 findvar(struct var **vpp, const char *name)
2093 for (; *vpp; vpp = &(*vpp)->next) {
2094 if (varcmp((*vpp)->var_text, name) == 0) {
2102 * Find the value of a variable. Returns NULL if not set.
2104 static const char* FAST_FUNC
2105 lookupvar(const char *name)
2109 v = *findvar(hashvar(name), name);
2111 #if ENABLE_ASH_RANDOM_SUPPORT
2113 * Dynamic variables are implemented roughly the same way they are
2114 * in bash. Namely, they're "special" so long as they aren't unset.
2115 * As soon as they're unset, they're no longer dynamic, and dynamic
2116 * lookup will no longer happen at that point. -- PFM.
2118 if (v->flags & VDYNAMIC)
2121 if (!(v->flags & VUNSET))
2122 return var_end(v->var_text);
2128 * Search the environment of a builtin command.
2131 bltinlookup(const char *name)
2135 for (sp = cmdenviron; sp; sp = sp->next) {
2136 if (varcmp(sp->text, name) == 0)
2137 return var_end(sp->text);
2139 return lookupvar(name);
2143 * Same as setvar except that the variable and value are passed in
2144 * the first argument as name=value. Since the first argument will
2145 * be actually stored in the table, it should not be a string that
2147 * Called with interrupts off.
2150 setvareq(char *s, int flags)
2152 struct var *vp, **vpp;
2155 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2156 vp = *findvar(vpp, s);
2158 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2161 if (flags & VNOSAVE)
2164 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2170 if (vp->var_func && !(flags & VNOFUNC))
2171 vp->var_func(var_end(s));
2173 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2174 free((char*)vp->var_text);
2176 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2178 /* variable s is not found */
2181 vp = ckzalloc(sizeof(*vp));
2183 /*vp->func = NULL; - ckzalloc did it */
2186 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2193 * Set the value of a variable. The flags argument is ored with the
2194 * flags of the variable. If val is NULL, the variable is unset.
2197 setvar(const char *name, const char *val, int flags)
2205 q = endofname(name);
2206 p = strchrnul(q, '=');
2208 if (!namelen || p != q)
2209 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2214 vallen = strlen(val);
2218 nameeq = ckmalloc(namelen + vallen + 2);
2219 p = memcpy(nameeq, name, namelen) + namelen;
2222 p = memcpy(p, val, vallen) + vallen;
2225 setvareq(nameeq, flags | VNOSAVE);
2229 static void FAST_FUNC
2230 setvar2(const char *name, const char *val)
2232 setvar(name, val, 0);
2235 #if ENABLE_ASH_GETOPTS
2237 * Safe version of setvar, returns 1 on success 0 on failure.
2240 setvarsafe(const char *name, const char *val, int flags)
2243 volatile int saveint;
2244 struct jmploc *volatile savehandler = exception_handler;
2245 struct jmploc jmploc;
2248 if (setjmp(jmploc.loc))
2251 exception_handler = &jmploc;
2252 setvar(name, val, flags);
2255 exception_handler = savehandler;
2256 RESTORE_INT(saveint);
2262 * Unset the specified variable.
2265 unsetvar(const char *s)
2271 vpp = findvar(hashvar(s), s);
2275 int flags = vp->flags;
2278 if (flags & VREADONLY)
2280 #if ENABLE_ASH_RANDOM_SUPPORT
2281 vp->flags &= ~VDYNAMIC;
2285 if ((flags & VSTRFIXED) == 0) {
2287 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2288 free((char*)vp->var_text);
2294 vp->flags &= ~VEXPORT;
2304 * Process a linked list of variable assignments.
2307 listsetvar(struct strlist *list_set_var, int flags)
2309 struct strlist *lp = list_set_var;
2315 setvareq(lp->text, flags);
2322 * Generate a list of variables satisfying the given conditions.
2325 listvars(int on, int off, char ***end)
2336 for (vp = *vpp; vp; vp = vp->next) {
2337 if ((vp->flags & mask) == on) {
2338 if (ep == stackstrend())
2339 ep = growstackstr();
2340 *ep++ = (char*)vp->var_text;
2343 } while (++vpp < vartab + VTABSIZE);
2344 if (ep == stackstrend())
2345 ep = growstackstr();
2349 return grabstackstr(ep);
2353 /* ============ Path search helper
2355 * The variable path (passed by reference) should be set to the start
2356 * of the path before the first call; path_advance will update
2357 * this value as it proceeds. Successive calls to path_advance will return
2358 * the possible path expansions in sequence. If an option (indicated by
2359 * a percent sign) appears in the path entry then the global variable
2360 * pathopt will be set to point to it; otherwise pathopt will be set to
2363 static const char *pathopt; /* set by path_advance */
2366 path_advance(const char **path, const char *name)
2376 for (p = start; *p && *p != ':' && *p != '%'; p++)
2378 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2379 while (stackblocksize() < len)
2383 memcpy(q, start, p - start);
2391 while (*p && *p != ':')
2398 return stalloc(len);
2402 /* ============ Prompt */
2404 static smallint doprompt; /* if set, prompt the user */
2405 static smallint needprompt; /* true if interactive and at start of line */
2407 #if ENABLE_FEATURE_EDITING
2408 static line_input_t *line_input_state;
2409 static const char *cmdedit_prompt;
2411 putprompt(const char *s)
2413 if (ENABLE_ASH_EXPAND_PRMT) {
2414 free((char*)cmdedit_prompt);
2415 cmdedit_prompt = ckstrdup(s);
2422 putprompt(const char *s)
2428 #if ENABLE_ASH_EXPAND_PRMT
2429 /* expandstr() needs parsing machinery, so it is far away ahead... */
2430 static const char *expandstr(const char *ps);
2432 #define expandstr(s) s
2436 setprompt_if(smallint do_set, int whichprompt)
2439 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2446 switch (whichprompt) {
2456 #if ENABLE_ASH_EXPAND_PRMT
2457 setstackmark(&smark);
2458 stalloc(stackblocksize());
2460 putprompt(expandstr(prompt));
2461 #if ENABLE_ASH_EXPAND_PRMT
2462 popstackmark(&smark);
2467 /* ============ The cd and pwd commands */
2469 #define CD_PHYSICAL 1
2479 while ((i = nextopt("LP")) != '\0') {
2481 flags ^= CD_PHYSICAL;
2490 * Update curdir (the name of the current directory) in response to a
2494 updatepwd(const char *dir)
2501 cdcomppath = ststrdup(dir);
2504 if (curdir == nullstr)
2506 new = stack_putstr(curdir, new);
2508 new = makestrspace(strlen(dir) + 2, new);
2509 lim = (char *)stackblock() + 1;
2513 if (new > lim && *lim == '/')
2518 if (dir[1] == '/' && dir[2] != '/') {
2524 p = strtok(cdcomppath, "/");
2528 if (p[1] == '.' && p[2] == '\0') {
2540 new = stack_putstr(p, new);
2548 return stackblock();
2552 * Find out what the current directory is. If we already know the current
2553 * directory, this routine returns immediately.
2558 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2559 return dir ? dir : nullstr;
2563 setpwd(const char *val, int setold)
2567 oldcur = dir = curdir;
2570 setvar("OLDPWD", oldcur, VEXPORT);
2573 if (physdir != nullstr) {
2574 if (physdir != oldcur)
2578 if (oldcur == val || !val) {
2584 dir = ckstrdup(val);
2585 if (oldcur != dir && oldcur != nullstr) {
2590 setvar("PWD", dir, VEXPORT);
2593 static void hashcd(void);
2596 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2597 * know that the current directory has changed.
2600 docd(const char *dest, int flags)
2602 const char *dir = NULL;
2605 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2608 if (!(flags & CD_PHYSICAL)) {
2609 dir = updatepwd(dest);
2623 static int FAST_FUNC
2624 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2636 dest = bltinlookup("HOME");
2637 else if (LONE_DASH(dest)) {
2638 dest = bltinlookup("OLDPWD");
2660 path = bltinlookup("CDPATH");
2669 p = path_advance(&path, dest);
2670 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2674 if (!docd(p, flags))
2679 ash_msg_and_raise_error("can't cd to %s", dest);
2682 if (flags & CD_PRINT)
2683 out1fmt("%s\n", curdir);
2687 static int FAST_FUNC
2688 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2691 const char *dir = curdir;
2695 if (physdir == nullstr)
2699 out1fmt("%s\n", dir);
2704 /* ============ ... */
2707 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2709 /* Syntax classes */
2710 #define CWORD 0 /* character is nothing special */
2711 #define CNL 1 /* newline character */
2712 #define CBACK 2 /* a backslash character */
2713 #define CSQUOTE 3 /* single quote */
2714 #define CDQUOTE 4 /* double quote */
2715 #define CENDQUOTE 5 /* a terminating quote */
2716 #define CBQUOTE 6 /* backwards single quote */
2717 #define CVAR 7 /* a dollar sign */
2718 #define CENDVAR 8 /* a '}' character */
2719 #define CLP 9 /* a left paren in arithmetic */
2720 #define CRP 10 /* a right paren in arithmetic */
2721 #define CENDFILE 11 /* end of file */
2722 #define CCTL 12 /* like CWORD, except it must be escaped */
2723 #define CSPCL 13 /* these terminate a word */
2724 #define CIGN 14 /* character should be ignored */
2727 #if ENABLE_ASH_ALIAS
2731 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2733 #if ENABLE_SH_MATH_SUPPORT
2734 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2736 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2738 static const uint16_t S_I_T[] = {
2739 #if ENABLE_ASH_ALIAS
2740 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2742 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2743 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2744 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2745 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2746 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2747 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2748 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2749 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2750 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2751 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2752 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2753 #if !USE_SIT_FUNCTION
2754 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2755 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2756 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2760 /* Constants below must match table above */
2762 #if ENABLE_ASH_ALIAS
2763 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2765 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2766 CNL_CNL_CNL_CNL , /* 2 */
2767 CWORD_CCTL_CCTL_CWORD , /* 3 */
2768 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2769 CVAR_CVAR_CWORD_CVAR , /* 5 */
2770 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2771 CSPCL_CWORD_CWORD_CLP , /* 7 */
2772 CSPCL_CWORD_CWORD_CRP , /* 8 */
2773 CBACK_CBACK_CCTL_CBACK , /* 9 */
2774 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2775 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2776 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2777 CWORD_CWORD_CWORD_CWORD , /* 13 */
2778 CCTL_CCTL_CCTL_CCTL , /* 14 */
2781 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2782 * caller must ensure proper cast on it if c is *char_ptr!
2784 /* Values for syntax param */
2785 #define BASESYNTAX 0 /* not in quotes */
2786 #define DQSYNTAX 1 /* in double quotes */
2787 #define SQSYNTAX 2 /* in single quotes */
2788 #define ARISYNTAX 3 /* in arithmetic */
2789 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2791 #if USE_SIT_FUNCTION
2794 SIT(int c, int syntax)
2796 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2797 # if ENABLE_ASH_ALIAS
2798 static const uint8_t syntax_index_table[] ALIGN1 = {
2799 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2800 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2801 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2805 static const uint8_t syntax_index_table[] ALIGN1 = {
2806 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2807 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2808 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2817 # if ENABLE_ASH_ALIAS
2823 /* Cast is purely for paranoia here,
2824 * just in case someone passed signed char to us */
2825 if ((unsigned char)c >= CTL_FIRST
2826 && (unsigned char)c <= CTL_LAST
2830 s = strchrnul(spec_symbls, c);
2833 indx = syntax_index_table[s - spec_symbls];
2835 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2838 #else /* !USE_SIT_FUNCTION */
2840 static const uint8_t syntax_index_table[] = {
2841 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2842 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2852 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2853 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2875 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2876 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2877 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2878 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2879 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2881 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2882 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2883 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2884 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2885 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2886 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2887 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2888 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2889 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2890 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2891 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2901 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2902 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2903 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2904 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2905 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2906 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2934 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2935 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2936 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2939 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2967 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2968 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2969 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2970 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2972 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2973 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2974 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2975 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2976 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2977 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2978 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2979 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3098 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3099 # if ENABLE_ASH_ALIAS
3100 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3104 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3106 #endif /* !USE_SIT_FUNCTION */
3109 /* ============ Alias handling */
3111 #if ENABLE_ASH_ALIAS
3113 #define ALIASINUSE 1
3124 static struct alias **atab; // [ATABSIZE];
3125 #define INIT_G_alias() do { \
3126 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3130 static struct alias **
3131 __lookupalias(const char *name) {
3132 unsigned int hashval;
3139 ch = (unsigned char)*p;
3143 ch = (unsigned char)*++p;
3145 app = &atab[hashval % ATABSIZE];
3147 for (; *app; app = &(*app)->next) {
3148 if (strcmp(name, (*app)->name) == 0) {
3156 static struct alias *
3157 lookupalias(const char *name, int check)
3159 struct alias *ap = *__lookupalias(name);
3161 if (check && ap && (ap->flag & ALIASINUSE))
3166 static struct alias *
3167 freealias(struct alias *ap)
3171 if (ap->flag & ALIASINUSE) {
3172 ap->flag |= ALIASDEAD;
3184 setalias(const char *name, const char *val)
3186 struct alias *ap, **app;
3188 app = __lookupalias(name);
3192 if (!(ap->flag & ALIASINUSE)) {
3195 ap->val = ckstrdup(val);
3196 ap->flag &= ~ALIASDEAD;
3199 ap = ckzalloc(sizeof(struct alias));
3200 ap->name = ckstrdup(name);
3201 ap->val = ckstrdup(val);
3202 /*ap->flag = 0; - ckzalloc did it */
3203 /*ap->next = NULL;*/
3210 unalias(const char *name)
3214 app = __lookupalias(name);
3218 *app = freealias(*app);
3229 struct alias *ap, **app;
3233 for (i = 0; i < ATABSIZE; i++) {
3235 for (ap = *app; ap; ap = *app) {
3236 *app = freealias(*app);
3246 printalias(const struct alias *ap)
3248 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3252 * TODO - sort output
3254 static int FAST_FUNC
3255 aliascmd(int argc UNUSED_PARAM, char **argv)
3264 for (i = 0; i < ATABSIZE; i++) {
3265 for (ap = atab[i]; ap; ap = ap->next) {
3271 while ((n = *++argv) != NULL) {
3272 v = strchr(n+1, '=');
3273 if (v == NULL) { /* n+1: funny ksh stuff */
3274 ap = *__lookupalias(n);
3276 fprintf(stderr, "%s: %s not found\n", "alias", n);
3289 static int FAST_FUNC
3290 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3294 while ((i = nextopt("a")) != '\0') {
3300 for (i = 0; *argptr; argptr++) {
3301 if (unalias(*argptr)) {
3302 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3310 #endif /* ASH_ALIAS */
3313 /* ============ jobs.c */
3315 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3318 #define FORK_NOJOB 2
3320 /* mode flags for showjob(s) */
3321 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3322 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3323 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3326 * A job structure contains information about a job. A job is either a
3327 * single process or a set of processes contained in a pipeline. In the
3328 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3332 pid_t ps_pid; /* process id */
3333 int ps_status; /* last process status from wait() */
3334 char *ps_cmd; /* text of command being run */
3338 struct procstat ps0; /* status of process */
3339 struct procstat *ps; /* status or processes when more than one */
3341 int stopstatus; /* status of a stopped job */
3344 nprocs: 16, /* number of processes */
3346 #define JOBRUNNING 0 /* at least one proc running */
3347 #define JOBSTOPPED 1 /* all procs are stopped */
3348 #define JOBDONE 2 /* all procs are completed */
3350 sigint: 1, /* job was killed by SIGINT */
3351 jobctl: 1, /* job running under job control */
3353 waited: 1, /* true if this entry has been waited for */
3354 used: 1, /* true if this entry is in used */
3355 changed: 1; /* true if status has changed */
3356 struct job *prev_job; /* previous job */
3359 static struct job *makejob(/*union node *,*/ int);
3360 static int forkshell(struct job *, union node *, int);
3361 static int waitforjob(struct job *);
3364 enum { doing_jobctl = 0 };
3365 #define setjobctl(on) do {} while (0)
3367 static smallint doing_jobctl; //references:8
3368 static void setjobctl(int);
3375 ignoresig(int signo)
3377 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3378 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3379 /* No, need to do it */
3380 signal(signo, SIG_IGN);
3382 sigmode[signo - 1] = S_HARD_IGN;
3386 * Only one usage site - in setsignal()
3389 signal_handler(int signo)
3391 gotsig[signo - 1] = 1;
3393 if (signo == SIGINT && !trap[SIGINT]) {
3394 if (!suppress_int) {
3396 raise_interrupt(); /* does not return */
3400 pending_sig = signo;
3405 * Set the signal handler for the specified signal. The routine figures
3406 * out what it should be set to.
3409 setsignal(int signo)
3412 char cur_act, new_act;
3413 struct sigaction act;
3417 if (t != NULL) { /* trap for this sig is set */
3419 if (t[0] == '\0') /* trap is "": ignore this sig */
3423 if (rootshell && new_act == S_DFL) {
3426 if (iflag || minusc || sflag == 0)
3435 * "In all cases, bash ignores SIGQUIT. Non-builtin
3436 * commands run by bash have signal handlers
3437 * set to the values inherited by the shell
3438 * from its parent". */
3454 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3455 //whereas we have to restore it to what shell got on entry
3456 //from the parent. See comment above
3458 t = &sigmode[signo - 1];
3461 /* current setting is not yet known */
3462 if (sigaction(signo, NULL, &act)) {
3463 /* pretend it worked; maybe we should give a warning,
3464 * but other shells don't. We don't alter sigmode,
3465 * so we retry every time.
3466 * btw, in Linux it never fails. --vda */
3469 if (act.sa_handler == SIG_IGN) {
3470 cur_act = S_HARD_IGN;
3472 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3474 cur_act = S_IGN; /* don't hard ignore these */
3478 if (cur_act == S_HARD_IGN || cur_act == new_act)
3481 act.sa_handler = SIG_DFL;
3484 act.sa_handler = signal_handler;
3485 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3486 sigfillset(&act.sa_mask); /* ditto */
3489 act.sa_handler = SIG_IGN;
3492 sigaction_set(signo, &act);
3497 /* mode flags for set_curjob */
3498 #define CUR_DELETE 2
3499 #define CUR_RUNNING 1
3500 #define CUR_STOPPED 0
3502 /* mode flags for dowait */
3503 #define DOWAIT_NONBLOCK WNOHANG
3504 #define DOWAIT_BLOCK 0
3507 /* pgrp of shell on invocation */
3508 static int initialpgrp; //references:2
3509 static int ttyfd = -1; //5
3512 static struct job *jobtab; //5
3514 static unsigned njobs; //4
3516 static struct job *curjob; //lots
3517 /* number of presumed living untracked jobs */
3518 static int jobless; //4
3521 set_curjob(struct job *jp, unsigned mode)
3524 struct job **jpp, **curp;
3526 /* first remove from list */
3527 jpp = curp = &curjob;
3532 jpp = &jp1->prev_job;
3534 *jpp = jp1->prev_job;
3536 /* Then re-insert in correct position */
3544 /* job being deleted */
3547 /* newly created job or backgrounded job,
3548 put after all stopped jobs. */
3552 if (!jp1 || jp1->state != JOBSTOPPED)
3555 jpp = &jp1->prev_job;
3561 /* newly stopped job - becomes curjob */
3562 jp->prev_job = *jpp;
3570 jobno(const struct job *jp)
3572 return jp - jobtab + 1;
3577 * Convert a job name to a job structure.
3580 #define getjob(name, getctl) getjob(name)
3583 getjob(const char *name, int getctl)
3587 const char *err_msg = "%s: no such job";
3591 char *(*match)(const char *, const char *);
3606 if (c == '+' || c == '%') {
3608 err_msg = "No current job";
3614 err_msg = "No previous job";
3625 jp = jobtab + num - 1;
3640 if (match(jp->ps[0].ps_cmd, p)) {
3644 err_msg = "%s: ambiguous";
3654 err_msg = "job %s not created under job control";
3655 if (getctl && jp->jobctl == 0)
3660 ash_msg_and_raise_error(err_msg, name);
3664 * Mark a job structure as unused.
3667 freejob(struct job *jp)
3669 struct procstat *ps;
3673 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3674 if (ps->ps_cmd != nullstr)
3677 if (jp->ps != &jp->ps0)
3680 set_curjob(jp, CUR_DELETE);
3686 xtcsetpgrp(int fd, pid_t pgrp)
3688 if (tcsetpgrp(fd, pgrp))
3689 ash_msg_and_raise_error("can't set tty process group (%m)");
3693 * Turn job control on and off.
3695 * Note: This code assumes that the third arg to ioctl is a character
3696 * pointer, which is true on Berkeley systems but not System V. Since
3697 * System V doesn't have job control yet, this isn't a problem now.
3699 * Called with interrupts off.
3707 if (on == doing_jobctl || rootshell == 0)
3711 ofd = fd = open(_PATH_TTY, O_RDWR);
3713 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3714 * That sometimes helps to acquire controlling tty.
3715 * Obviously, a workaround for bugs when someone
3716 * failed to provide a controlling tty to bash! :) */
3722 fd = fcntl(fd, F_DUPFD, 10);
3727 /* fd is a tty at this point */
3728 close_on_exec_on(fd);
3729 do { /* while we are in the background */
3730 pgrp = tcgetpgrp(fd);
3733 ash_msg("can't access tty; job control turned off");
3737 if (pgrp == getpgrp())
3748 xtcsetpgrp(fd, pgrp);
3750 /* turning job control off */
3753 /* was xtcsetpgrp, but this can make exiting ash
3754 * loop forever if pty is already deleted */
3755 tcsetpgrp(fd, pgrp);
3769 static int FAST_FUNC
3770 killcmd(int argc, char **argv)
3773 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3775 if (argv[i][0] == '%') {
3776 struct job *jp = getjob(argv[i], 0);
3777 unsigned pid = jp->ps[0].ps_pid;
3778 /* Enough space for ' -NNN<nul>' */
3779 argv[i] = alloca(sizeof(int)*3 + 3);
3780 /* kill_main has matching code to expect
3781 * leading space. Needed to not confuse
3782 * negative pids with "kill -SIGNAL_NO" syntax */
3783 sprintf(argv[i], " -%u", pid);
3785 } while (argv[++i]);
3787 return kill_main(argc, argv);
3791 showpipe(struct job *jp /*, FILE *out*/)
3793 struct procstat *ps;
3794 struct procstat *psend;
3796 psend = jp->ps + jp->nprocs;
3797 for (ps = jp->ps + 1; ps < psend; ps++)
3798 printf(" | %s", ps->ps_cmd);
3799 outcslow('\n', stdout);
3800 flush_stdout_stderr();
3805 restartjob(struct job *jp, int mode)
3807 struct procstat *ps;
3813 if (jp->state == JOBDONE)
3815 jp->state = JOBRUNNING;
3816 pgid = jp->ps[0].ps_pid;
3817 if (mode == FORK_FG)
3818 xtcsetpgrp(ttyfd, pgid);
3819 killpg(pgid, SIGCONT);
3823 if (WIFSTOPPED(ps->ps_status)) {
3829 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3834 static int FAST_FUNC
3835 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3841 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3845 jp = getjob(*argv, 1);
3846 if (mode == FORK_BG) {
3847 set_curjob(jp, CUR_RUNNING);
3848 printf("[%d] ", jobno(jp));
3850 out1str(jp->ps[0].ps_cmd);
3851 showpipe(jp /*, stdout*/);
3852 retval = restartjob(jp, mode);
3853 } while (*argv && *++argv);
3859 sprint_status(char *s, int status, int sigonly)
3865 if (!WIFEXITED(status)) {
3867 if (WIFSTOPPED(status))
3868 st = WSTOPSIG(status);
3871 st = WTERMSIG(status);
3873 if (st == SIGINT || st == SIGPIPE)
3876 if (WIFSTOPPED(status))
3881 col = fmtstr(s, 32, strsignal(st));
3882 if (WCOREDUMP(status)) {
3883 col += fmtstr(s + col, 16, " (core dumped)");
3885 } else if (!sigonly) {
3886 st = WEXITSTATUS(status);
3888 col = fmtstr(s, 16, "Done(%d)", st);
3890 col = fmtstr(s, 16, "Done");
3897 dowait(int wait_flags, struct job *job)
3902 struct job *thisjob;
3905 TRACE(("dowait(0x%x) called\n", wait_flags));
3907 /* Do a wait system call. If job control is compiled in, we accept
3908 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3909 * NB: _not_ safe_waitpid, we need to detect EINTR */
3911 wait_flags |= WUNTRACED;
3912 pid = waitpid(-1, &status, wait_flags);
3913 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3914 pid, status, errno, strerror(errno)));
3920 for (jp = curjob; jp; jp = jp->prev_job) {
3921 struct procstat *ps;
3922 struct procstat *psend;
3923 if (jp->state == JOBDONE)
3927 psend = ps + jp->nprocs;
3929 if (ps->ps_pid == pid) {
3930 TRACE(("Job %d: changing status of proc %d "
3931 "from 0x%x to 0x%x\n",
3932 jobno(jp), pid, ps->ps_status, status));
3933 ps->ps_status = status;
3936 if (ps->ps_status == -1)
3939 if (state == JOBRUNNING)
3941 if (WIFSTOPPED(ps->ps_status)) {
3942 jp->stopstatus = ps->ps_status;
3946 } while (++ps < psend);
3951 if (!WIFSTOPPED(status))
3957 if (state != JOBRUNNING) {
3958 thisjob->changed = 1;
3960 if (thisjob->state != state) {
3961 TRACE(("Job %d: changing state from %d to %d\n",
3962 jobno(thisjob), thisjob->state, state));
3963 thisjob->state = state;
3965 if (state == JOBSTOPPED) {
3966 set_curjob(thisjob, CUR_STOPPED);
3975 if (thisjob && thisjob == job) {
3979 len = sprint_status(s, status, 1);
3990 blocking_wait_with_raise_on_sig(void)
3992 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
3993 if (pid <= 0 && pending_sig)
3994 raise_exception(EXSIG);
4000 showjob(FILE *out, struct job *jp, int mode)
4002 struct procstat *ps;
4003 struct procstat *psend;
4010 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4011 /* just output process (group) id of pipeline */
4012 fprintf(out, "%d\n", ps->ps_pid);
4016 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4021 else if (curjob && jp == curjob->prev_job)
4024 if (mode & SHOW_PIDS)
4025 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4027 psend = ps + jp->nprocs;
4029 if (jp->state == JOBRUNNING) {
4030 strcpy(s + col, "Running");
4031 col += sizeof("Running") - 1;
4033 int status = psend[-1].ps_status;
4034 if (jp->state == JOBSTOPPED)
4035 status = jp->stopstatus;
4036 col += sprint_status(s + col, status, 0);
4038 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4040 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4041 * or prints several "PID | <cmdN>" lines,
4042 * depending on SHOW_PIDS bit.
4043 * We do not print status of individual processes
4044 * between PID and <cmdN>. bash does it, but not very well:
4045 * first line shows overall job status, not process status,
4046 * making it impossible to know 1st process status.
4050 /* for each process */
4053 if (mode & SHOW_PIDS)
4054 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4056 fprintf(out, "%s%*c%s%s",
4058 33 - col >= 0 ? 33 - col : 0, ' ',
4059 ps == jp->ps ? "" : "| ",
4062 } while (++ps != psend);
4063 outcslow('\n', out);
4067 if (jp->state == JOBDONE) {
4068 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4074 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4075 * statuses have changed since the last call to showjobs.
4078 showjobs(FILE *out, int mode)
4082 TRACE(("showjobs(0x%x) called\n", mode));
4084 /* Handle all finished jobs */
4085 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4088 for (jp = curjob; jp; jp = jp->prev_job) {
4089 if (!(mode & SHOW_CHANGED) || jp->changed) {
4090 showjob(out, jp, mode);
4095 static int FAST_FUNC
4096 jobscmd(int argc UNUSED_PARAM, char **argv)
4101 while ((m = nextopt("lp")) != '\0') {
4105 mode |= SHOW_ONLY_PGID;
4111 showjob(stdout, getjob(*argv, 0), mode);
4114 showjobs(stdout, mode);
4121 /* Called only on finished or stopped jobs (no members are running) */
4123 getstatus(struct job *job)
4127 struct procstat *ps;
4129 /* Fetch last member's status */
4130 ps = job->ps + job->nprocs - 1;
4131 status = ps->ps_status;
4133 /* "set -o pipefail" mode: use last _nonzero_ status */
4134 while (status == 0 && --ps >= job->ps)
4135 status = ps->ps_status;
4138 retval = WEXITSTATUS(status);
4139 if (!WIFEXITED(status)) {
4141 retval = WSTOPSIG(status);
4142 if (!WIFSTOPPED(status))
4145 /* XXX: limits number of signals */
4146 retval = WTERMSIG(status);
4148 if (retval == SIGINT)
4154 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4155 jobno(job), job->nprocs, status, retval));
4159 static int FAST_FUNC
4160 waitcmd(int argc UNUSED_PARAM, char **argv)
4167 raise_exception(EXSIG);
4174 /* wait for all jobs */
4178 if (!jp) /* no running procs */
4180 if (jp->state == JOBRUNNING)
4185 blocking_wait_with_raise_on_sig();
4187 * "When bash is waiting for an asynchronous command via
4188 * the wait builtin, the reception of a signal for which a trap
4189 * has been set will cause the wait builtin to return immediately
4190 * with an exit status greater than 128, immediately after which
4191 * the trap is executed."
4193 * blocking_wait_with_raise_on_sig raises signal handlers
4194 * if it gets no pid (pid < 0). However,
4195 * if child sends us a signal *and immediately exits*,
4196 * blocking_wait_with_raise_on_sig gets pid > 0
4197 * and does not handle pending_sig. Check this case: */
4199 raise_exception(EXSIG);
4205 if (**argv != '%') {
4206 pid_t pid = number(*argv);
4211 if (job->ps[job->nprocs - 1].ps_pid == pid)
4213 job = job->prev_job;
4216 job = getjob(*argv, 0);
4217 /* loop until process terminated or stopped */
4218 while (job->state == JOBRUNNING)
4219 blocking_wait_with_raise_on_sig();
4221 retval = getstatus(job);
4234 struct job *jp, *jq;
4236 len = njobs * sizeof(*jp);
4238 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4240 offset = (char *)jp - (char *)jq;
4242 /* Relocate pointers */
4245 jq = (struct job *)((char *)jq + l);
4249 #define joff(p) ((struct job *)((char *)(p) + l))
4250 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4251 if (joff(jp)->ps == &jq->ps0)
4252 jmove(joff(jp)->ps);
4253 if (joff(jp)->prev_job)
4254 jmove(joff(jp)->prev_job);
4264 jp = (struct job *)((char *)jp + len);
4268 } while (--jq >= jp);
4273 * Return a new job structure.
4274 * Called with interrupts off.
4277 makejob(/*union node *node,*/ int nprocs)
4282 for (i = njobs, jp = jobtab; ; jp++) {
4289 if (jp->state != JOBDONE || !jp->waited)
4298 memset(jp, 0, sizeof(*jp));
4300 /* jp->jobctl is a bitfield.
4301 * "jp->jobctl |= jobctl" likely to give awful code */
4305 jp->prev_job = curjob;
4310 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4312 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4319 * Return a string identifying a command (to be printed by the
4322 static char *cmdnextc;
4325 cmdputs(const char *s)
4327 static const char vstype[VSTYPE + 1][3] = {
4328 "", "}", "-", "+", "?", "=",
4329 "%", "%%", "#", "##"
4330 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4333 const char *p, *str;
4337 unsigned char subtype = 0;
4341 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4343 while ((c = *p++) != '\0') {
4351 if ((subtype & VSTYPE) == VSLENGTH)
4355 if (!(subtype & VSQUOTE) == !(quoted & 1))
4361 str = "\"}" + !(quoted & 1);
4368 case CTLBACKQ+CTLQUOTE:
4371 #if ENABLE_SH_MATH_SUPPORT
4386 if ((subtype & VSTYPE) != VSNORMAL)
4388 str = vstype[subtype & VSTYPE];
4389 if (subtype & VSNUL)
4398 /* These can only happen inside quotes */
4411 while ((c = *str++) != '\0') {
4414 } /* while *p++ not NUL */
4417 USTPUTC('"', nextc);
4423 /* cmdtxt() and cmdlist() call each other */
4424 static void cmdtxt(union node *n);
4427 cmdlist(union node *np, int sep)
4429 for (; np; np = np->narg.next) {
4433 if (sep && np->narg.next)
4439 cmdtxt(union node *n)
4442 struct nodelist *lp;
4453 lp = n->npipe.cmdlist;
4471 cmdtxt(n->nbinary.ch1);
4487 cmdtxt(n->nif.test);
4489 if (n->nif.elsepart) {
4490 cmdtxt(n->nif.ifpart);
4492 n = n->nif.elsepart;
4510 cmdtxt(n->nbinary.ch1);
4520 cmdputs(n->nfor.var);
4522 cmdlist(n->nfor.args, 1);
4527 cmdputs(n->narg.text);
4531 cmdlist(n->ncmd.args, 1);
4532 cmdlist(n->ncmd.redirect, 0);
4545 cmdputs(n->ncase.expr->narg.text);
4547 for (np = n->ncase.cases; np; np = np->nclist.next) {
4548 cmdtxt(np->nclist.pattern);
4550 cmdtxt(np->nclist.body);
4564 #if ENABLE_ASH_BASH_COMPAT
4579 cmdputs(utoa(n->nfile.fd));
4581 if (n->type == NTOFD || n->type == NFROMFD) {
4582 cmdputs(utoa(n->ndup.dupfd));
4591 commandtext(union node *n)
4595 STARTSTACKSTR(cmdnextc);
4597 name = stackblock();
4598 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4599 name, cmdnextc, cmdnextc));
4600 return ckstrdup(name);
4605 * Fork off a subshell. If we are doing job control, give the subshell its
4606 * own process group. Jp is a job structure that the job is to be added to.
4607 * N is the command that will be evaluated by the child. Both jp and n may
4608 * be NULL. The mode parameter can be one of the following:
4609 * FORK_FG - Fork off a foreground process.
4610 * FORK_BG - Fork off a background process.
4611 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4612 * process group even if job control is on.
4614 * When job control is turned off, background processes have their standard
4615 * input redirected to /dev/null (except for the second and later processes
4618 * Called with interrupts off.
4621 * Clear traps on a fork.
4628 for (tp = trap; tp < &trap[NSIG]; tp++) {
4629 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4631 if (trap_ptr == trap)
4633 /* else: it "belongs" to trap_ptr vector, don't free */
4635 if ((tp - trap) != 0)
4636 setsignal(tp - trap);
4643 /* Lives far away from here, needed for forkchild */
4644 static void closescript(void);
4646 /* Called after fork(), in child */
4647 static NOINLINE void
4648 forkchild(struct job *jp, union node *n, int mode)
4652 TRACE(("Child shell %d\n", getpid()));
4656 /* man bash: "Non-builtin commands run by bash have signal handlers
4657 * set to the values inherited by the shell from its parent".
4658 * Do we do it correctly? */
4662 if (mode == FORK_NOJOB /* is it `xxx` ? */
4663 && n && n->type == NCMD /* is it single cmd? */
4664 /* && n->ncmd.args->type == NARG - always true? */
4665 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4666 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4667 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4669 TRACE(("Trap hack\n"));
4670 /* Awful hack for `trap` or $(trap).
4672 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4673 * contains an example where "trap" is executed in a subshell:
4675 * save_traps=$(trap)
4677 * eval "$save_traps"
4679 * Standard does not say that "trap" in subshell shall print
4680 * parent shell's traps. It only says that its output
4681 * must have suitable form, but then, in the above example
4682 * (which is not supposed to be normative), it implies that.
4684 * bash (and probably other shell) does implement it
4685 * (traps are reset to defaults, but "trap" still shows them),
4686 * but as a result, "trap" logic is hopelessly messed up:
4689 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4690 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4691 * # true | trap <--- trap is in subshell - no output (ditto)
4692 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4693 * trap -- 'echo Ho' SIGWINCH
4694 * # echo `(trap)` <--- in subshell in subshell - output
4695 * trap -- 'echo Ho' SIGWINCH
4696 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4697 * trap -- 'echo Ho' SIGWINCH
4699 * The rules when to forget and when to not forget traps
4700 * get really complex and nonsensical.
4702 * Our solution: ONLY bare $(trap) or `trap` is special.
4704 /* Save trap handler strings for trap builtin to print */
4705 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4706 /* Fall through into clearing traps */
4710 /* do job control only in root shell */
4712 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4715 if (jp->nprocs == 0)
4718 pgrp = jp->ps[0].ps_pid;
4719 /* this can fail because we are doing it in the parent also */
4721 if (mode == FORK_FG)
4722 xtcsetpgrp(ttyfd, pgrp);
4727 if (mode == FORK_BG) {
4728 /* man bash: "When job control is not in effect,
4729 * asynchronous commands ignore SIGINT and SIGQUIT" */
4732 if (jp->nprocs == 0) {
4734 if (open(bb_dev_null, O_RDONLY) != 0)
4735 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4739 if (iflag) { /* why if iflag only? */
4744 * "In all cases, bash ignores SIGQUIT. Non-builtin
4745 * commands run by bash have signal handlers
4746 * set to the values inherited by the shell
4748 * Take care of the second rule: */
4752 if (n && n->type == NCMD
4753 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4755 TRACE(("Job hack\n"));
4756 /* "jobs": we do not want to clear job list for it,
4757 * instead we remove only _its_ own_ job from job list.
4758 * This makes "jobs .... | cat" more useful.
4764 for (jp = curjob; jp; jp = jp->prev_job)
4769 /* Called after fork(), in parent */
4771 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4774 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4776 TRACE(("In parent shell: child = %d\n", pid));
4778 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4784 if (mode != FORK_NOJOB && jp->jobctl) {
4787 if (jp->nprocs == 0)
4790 pgrp = jp->ps[0].ps_pid;
4791 /* This can fail because we are doing it in the child also */
4795 if (mode == FORK_BG) {
4796 backgndpid = pid; /* set $! */
4797 set_curjob(jp, CUR_RUNNING);
4800 struct procstat *ps = &jp->ps[jp->nprocs++];
4803 ps->ps_cmd = nullstr;
4805 if (doing_jobctl && n)
4806 ps->ps_cmd = commandtext(n);
4812 forkshell(struct job *jp, union node *n, int mode)
4816 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4819 TRACE(("Fork failed, errno=%d", errno));
4822 ash_msg_and_raise_error("can't fork");
4825 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4826 forkchild(jp, n, mode);
4828 forkparent(jp, n, mode, pid);
4834 * Wait for job to finish.
4836 * Under job control we have the problem that while a child process
4837 * is running interrupts generated by the user are sent to the child
4838 * but not to the shell. This means that an infinite loop started by
4839 * an interactive user may be hard to kill. With job control turned off,
4840 * an interactive user may place an interactive program inside a loop.
4841 * If the interactive program catches interrupts, the user doesn't want
4842 * these interrupts to also abort the loop. The approach we take here
4843 * is to have the shell ignore interrupt signals while waiting for a
4844 * foreground process to terminate, and then send itself an interrupt
4845 * signal if the child process was terminated by an interrupt signal.
4846 * Unfortunately, some programs want to do a bit of cleanup and then
4847 * exit on interrupt; unless these processes terminate themselves by
4848 * sending a signal to themselves (instead of calling exit) they will
4849 * confuse this approach.
4851 * Called with interrupts off.
4854 waitforjob(struct job *jp)
4858 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4861 while (jp->state == JOBRUNNING) {
4862 /* In non-interactive shells, we _can_ get
4863 * a keyboard signal here and be EINTRed,
4864 * but we just loop back, waiting for command to complete.
4867 * "If bash is waiting for a command to complete and receives
4868 * a signal for which a trap has been set, the trap
4869 * will not be executed until the command completes."
4871 * Reality is that even if trap is not set, bash
4872 * will not act on the signal until command completes.
4873 * Try this. sleep5intoff.c:
4874 * #include <signal.h>
4875 * #include <unistd.h>
4878 * sigemptyset(&set);
4879 * sigaddset(&set, SIGINT);
4880 * sigaddset(&set, SIGQUIT);
4881 * sigprocmask(SIG_BLOCK, &set, NULL);
4885 * $ bash -c './sleep5intoff; echo hi'
4886 * ^C^C^C^C <--- pressing ^C once a second
4888 * $ bash -c './sleep5intoff; echo hi'
4889 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4892 dowait(DOWAIT_BLOCK, jp);
4899 xtcsetpgrp(ttyfd, rootpid);
4901 * This is truly gross.
4902 * If we're doing job control, then we did a TIOCSPGRP which
4903 * caused us (the shell) to no longer be in the controlling
4904 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4905 * intuit from the subprocess exit status whether a SIGINT
4906 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4908 if (jp->sigint) /* TODO: do the same with all signals */
4909 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4911 if (jp->state == JOBDONE)
4918 * return 1 if there are stopped jobs, otherwise 0
4930 if (jp && jp->state == JOBSTOPPED) {
4931 out2str("You have stopped jobs.\n");
4940 /* ============ redir.c
4942 * Code for dealing with input/output redirection.
4945 #define EMPTY -2 /* marks an unused slot in redirtab */
4946 #define CLOSED -3 /* marks a slot of previously-closed fd */
4949 * Open a file in noclobber mode.
4950 * The code was copied from bash.
4953 noclobberopen(const char *fname)
4956 struct stat finfo, finfo2;
4959 * If the file exists and is a regular file, return an error
4962 r = stat(fname, &finfo);
4963 if (r == 0 && S_ISREG(finfo.st_mode)) {
4969 * If the file was not present (r != 0), make sure we open it
4970 * exclusively so that if it is created before we open it, our open
4971 * will fail. Make sure that we do not truncate an existing file.
4972 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4973 * file was not a regular file, we leave O_EXCL off.
4976 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4977 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4979 /* If the open failed, return the file descriptor right away. */
4984 * OK, the open succeeded, but the file may have been changed from a
4985 * non-regular file to a regular file between the stat and the open.
4986 * We are assuming that the O_EXCL open handles the case where FILENAME
4987 * did not exist and is symlinked to an existing file between the stat
4992 * If we can open it and fstat the file descriptor, and neither check
4993 * revealed that it was a regular file, and the file has not been
4994 * replaced, return the file descriptor.
4996 if (fstat(fd, &finfo2) == 0
4997 && !S_ISREG(finfo2.st_mode)
4998 && finfo.st_dev == finfo2.st_dev
4999 && finfo.st_ino == finfo2.st_ino
5004 /* The file has been replaced. badness. */
5011 * Handle here documents. Normally we fork off a process to write the
5012 * data to a pipe. If the document is short, we can stuff the data in
5013 * the pipe without forking.
5015 /* openhere needs this forward reference */
5016 static void expandhere(union node *arg, int fd);
5018 openhere(union node *redir)
5024 ash_msg_and_raise_error("pipe call failed");
5025 if (redir->type == NHERE) {
5026 len = strlen(redir->nhere.doc->narg.text);
5027 if (len <= PIPE_BUF) {
5028 full_write(pip[1], redir->nhere.doc->narg.text, len);
5032 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5035 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5036 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5037 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5038 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5039 signal(SIGPIPE, SIG_DFL);
5040 if (redir->type == NHERE)
5041 full_write(pip[1], redir->nhere.doc->narg.text, len);
5043 expandhere(redir->nhere.doc, pip[1]);
5044 _exit(EXIT_SUCCESS);
5052 openredirect(union node *redir)
5057 switch (redir->nfile.type) {
5059 fname = redir->nfile.expfname;
5060 f = open(fname, O_RDONLY);
5065 fname = redir->nfile.expfname;
5066 f = open(fname, O_RDWR|O_CREAT, 0666);
5071 #if ENABLE_ASH_BASH_COMPAT
5074 /* Take care of noclobber mode. */
5076 fname = redir->nfile.expfname;
5077 f = noclobberopen(fname);
5084 fname = redir->nfile.expfname;
5085 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5090 fname = redir->nfile.expfname;
5091 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5099 /* Fall through to eliminate warning. */
5100 /* Our single caller does this itself */
5107 f = openhere(redir);
5113 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5115 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5119 * Copy a file descriptor to be >= to. Returns -1
5120 * if the source file descriptor is closed, EMPTY if there are no unused
5121 * file descriptors left.
5123 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5124 * old code was doing close(to) prior to copyfd() to achieve the same */
5126 COPYFD_EXACT = (int)~(INT_MAX),
5127 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5130 copyfd(int from, int to)
5134 if (to & COPYFD_EXACT) {
5135 to &= ~COPYFD_EXACT;
5137 newfd = dup2(from, to);
5139 newfd = fcntl(from, F_DUPFD, to);
5142 if (errno == EMFILE)
5144 /* Happens when source fd is not open: try "echo >&99" */
5145 ash_msg_and_raise_error("%d: %m", from);
5150 /* Struct def and variable are moved down to the first usage site */
5155 struct redirtab *next;
5158 struct two_fd_t two_fd[];
5160 #define redirlist (G_var.redirlist)
5162 static int need_to_remember(struct redirtab *rp, int fd)
5166 if (!rp) /* remembering was not requested */
5169 for (i = 0; i < rp->pair_count; i++) {
5170 if (rp->two_fd[i].orig == fd) {
5171 /* already remembered */
5178 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5179 static int is_hidden_fd(struct redirtab *rp, int fd)
5182 struct parsefile *pf;
5186 /* Check open scripts' fds */
5189 /* We skip pf_fd == 0 case because of the following case:
5190 * $ ash # running ash interactively
5192 * and in script.sh: "exec 9>&0".
5193 * Even though top-level pf_fd _is_ 0,
5194 * it's still ok to use it: "read" builtin uses it,
5195 * why should we cripple "exec" builtin?
5197 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5205 /* Check saved fds of redirects */
5206 fd |= COPYFD_RESTORE;
5207 for (i = 0; i < rp->pair_count; i++) {
5208 if (rp->two_fd[i].copy == fd) {
5216 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5217 * old file descriptors are stashed away so that the redirection can be
5218 * undone by calling popredir.
5220 /* flags passed to redirect */
5221 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5222 #define REDIR_SAVEFD2 03 /* set preverrout */
5224 redirect(union node *redir, int flags)
5226 struct redirtab *sv;
5231 int copied_fd2 = -1;
5241 if (flags & REDIR_PUSH) {
5242 union node *tmp = redir;
5245 #if ENABLE_ASH_BASH_COMPAT
5246 if (tmp->nfile.type == NTO2)
5249 tmp = tmp->nfile.next;
5251 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5252 sv->next = redirlist;
5253 sv->pair_count = sv_pos;
5255 sv->nullredirs = g_nullredirs - 1;
5257 while (sv_pos > 0) {
5259 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5265 fd = redir->nfile.fd;
5266 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5267 right_fd = redir->ndup.dupfd;
5268 //bb_error_msg("doing %d > %d", fd, right_fd);
5269 /* redirect from/to same file descriptor? */
5272 /* "echo >&10" and 10 is a fd opened to a sh script? */
5273 if (is_hidden_fd(sv, right_fd)) {
5274 errno = EBADF; /* as if it is closed */
5275 ash_msg_and_raise_error("%d: %m", right_fd);
5279 newfd = openredirect(redir); /* always >= 0 */
5281 /* Descriptor wasn't open before redirect.
5282 * Mark it for close in the future */
5283 if (need_to_remember(sv, fd)) {
5284 goto remember_to_close;
5289 #if ENABLE_ASH_BASH_COMPAT
5292 if (need_to_remember(sv, fd)) {
5293 /* Copy old descriptor */
5294 /* Careful to not accidentally "save"
5295 * to the same fd as right side fd in N>&M */
5296 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5297 i = fcntl(fd, F_DUPFD, minfd);
5298 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5299 * are closed in popredir() in the child, preventing them from leaking
5300 * into child. (popredir() also cleans up the mess in case of failures)
5305 /* Strange error (e.g. "too many files" EMFILE?) */
5309 ash_msg_and_raise_error("%d: %m", fd);
5312 /* EBADF: it is not open - good, remember to close it */
5315 } else { /* fd is open, save its copy */
5316 /* "exec fd>&-" should not close fds
5317 * which point to script file(s).
5318 * Force them to be restored afterwards */
5319 if (is_hidden_fd(sv, fd))
5320 i |= COPYFD_RESTORE;
5324 sv->two_fd[sv_pos].orig = fd;
5325 sv->two_fd[sv_pos].copy = i;
5329 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5330 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5331 /* Don't want to trigger debugging */
5335 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5337 } else if (fd != newfd) { /* move newfd to fd */
5338 copyfd(newfd, fd | COPYFD_EXACT);
5339 #if ENABLE_ASH_BASH_COMPAT
5340 if (!(redir->nfile.type == NTO2 && fd == 2))
5344 #if ENABLE_ASH_BASH_COMPAT
5345 if (redir->nfile.type == NTO2 && fd == 1) {
5346 /* We already redirected it to fd 1, now copy it to 2 */
5352 } while ((redir = redir->nfile.next) != NULL);
5355 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5356 preverrout_fd = copied_fd2;
5360 * Undo the effects of the last redirection.
5363 popredir(int drop, int restore)
5365 struct redirtab *rp;
5368 if (--g_nullredirs >= 0)
5372 for (i = 0; i < rp->pair_count; i++) {
5373 int fd = rp->two_fd[i].orig;
5374 int copy = rp->two_fd[i].copy;
5375 if (copy == CLOSED) {
5380 if (copy != EMPTY) {
5381 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5382 copy &= ~COPYFD_RESTORE;
5384 copyfd(copy, fd | COPYFD_EXACT);
5386 close(copy & ~COPYFD_RESTORE);
5389 redirlist = rp->next;
5390 g_nullredirs = rp->nullredirs;
5396 * Undo all redirections. Called on error or interrupt.
5400 * Discard all saved file descriptors.
5403 clearredir(int drop)
5409 popredir(drop, /*restore:*/ 0);
5414 redirectsafe(union node *redir, int flags)
5417 volatile int saveint;
5418 struct jmploc *volatile savehandler = exception_handler;
5419 struct jmploc jmploc;
5422 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5423 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5425 exception_handler = &jmploc;
5426 redirect(redir, flags);
5428 exception_handler = savehandler;
5429 if (err && exception_type != EXERROR)
5430 longjmp(exception_handler->loc, 1);
5431 RESTORE_INT(saveint);
5436 /* ============ Routines to expand arguments to commands
5438 * We have to deal with backquotes, shell variables, and file metacharacters.
5441 #if ENABLE_SH_MATH_SUPPORT
5443 ash_arith(const char *s)
5445 arith_state_t math_state;
5448 math_state.lookupvar = lookupvar;
5449 math_state.setvar = setvar2;
5450 //math_state.endofname = endofname;
5453 result = arith(&math_state, s);
5454 if (math_state.errmsg)
5455 ash_msg_and_raise_error(math_state.errmsg);
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_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 ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
6007 p = exptilde(p, q, flags);
6010 startloc = expdest - (char *)stackblock();
6014 length += strcspn(p + length, reject);
6018 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6020 /* c == '=' || c == ':' || c == CTLENDARI */
6026 expdest = stack_nputstr(p, length, expdest);
6027 newloc = expdest - (char *)stackblock();
6028 if (breakall && !inquotes && newloc > startloc) {
6029 recordregion(startloc, newloc, 0);
6040 if (flags & EXP_VARTILDE2) {
6044 flags |= EXP_VARTILDE2;
6049 * sort of a hack - expand tildes in variable
6050 * assignments (after the first '=' and after ':'s).
6059 case CTLENDVAR: /* ??? */
6062 /* "$@" syntax adherence hack */
6064 && memcmp(p, dolatstr, 4) == 0
6065 && ( p[4] == (char)CTLQUOTEMARK
6066 || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
6069 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
6072 inquotes = !inquotes;
6085 p = evalvar(p, flags, var_str_list);
6089 case CTLBACKQ|CTLQUOTE:
6090 expbackq(argbackq->n, c, quotes);
6091 argbackq = argbackq->next;
6093 #if ENABLE_SH_MATH_SUPPORT
6105 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6106 char *pattern, int quotes, int zero)
6115 const char *s = loc2;
6122 match = pmatch(pattern, s);
6127 if (quotes && (unsigned char)*loc == CTLESC)
6136 scanright(char *startp, char *rmesc, char *rmescend,
6137 char *pattern, int quotes, int match_at_start)
6139 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6140 int try2optimize = match_at_start;
6146 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6147 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6148 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6150 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6151 * and on each iteration they go back two/one char until they reach the beginning.
6152 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6154 /* TODO: document in what other circumstances we are called. */
6156 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6159 const char *s = loc2;
6160 if (match_at_start) {
6164 match = pmatch(pattern, s);
6165 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6169 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6171 /* Maybe we can optimize this:
6172 * if pattern ends with unescaped *, we can avoid checking
6173 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6174 * it wont match truncated "raw_value_of_" strings too.
6176 unsigned plen = strlen(pattern);
6177 /* Does it end with "*"? */
6178 if (plen != 0 && pattern[--plen] == '*') {
6179 /* "xxxx*" is not escaped */
6180 /* "xxx\*" is escaped */
6181 /* "xx\\*" is not escaped */
6182 /* "x\\\*" is escaped */
6184 while (plen != 0 && pattern[--plen] == '\\')
6187 break; /* ends with unescaped "*" */
6195 esc = esclen(startp, loc);
6206 static void varunset(const char *, const char *, const char *, int) NORETURN;
6208 varunset(const char *end, const char *var, const char *umsg, int varflags)
6214 msg = "parameter not set";
6216 if ((unsigned char)*end == CTLENDVAR) {
6217 if (varflags & VSNUL)
6223 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6226 #if ENABLE_ASH_BASH_COMPAT
6228 parse_sub_pattern(char *arg, int varflags)
6230 char *idx, *repl = NULL;
6233 //char *org_arg = arg;
6234 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
6241 /* Only the first '/' seen is our separator */
6250 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6251 * The result is a_\_z_c (not a\_\_z_c)!
6253 * Enable debug prints in this function and you'll see:
6254 * ash: arg:'\\b/_\\_z_' varflags:d
6255 * ash: pattern:'\\b' repl:'_\_z_'
6256 * That is, \\b is interpreted as \\b, but \\_ as \_!
6257 * IOW: search pattern and replace string treat backslashes
6258 * differently! That is the reason why we check repl below:
6260 if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
6261 arg++; /* skip both '\', not just first one */
6264 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
6268 #endif /* ENABLE_ASH_BASH_COMPAT */
6271 subevalvar(char *p, char *varname, int strloc, int subtype,
6272 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6274 struct nodelist *saveargbackq = argbackq;
6277 char *rmesc, *rmescend;
6279 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
6280 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6281 int saveherefd = herefd;
6282 int amount, workloc, resetloc;
6284 char *(*scan)(char*, char*, char*, char*, int, int);
6286 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6287 // p, varname, strloc, subtype, startloc, varflags, quotes);
6290 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6292 STPUTC('\0', expdest);
6293 herefd = saveherefd;
6294 argbackq = saveargbackq;
6295 startp = (char *)stackblock() + startloc;
6299 setvar(varname, startp, 0);
6300 amount = startp - expdest;
6301 STADJUST(amount, expdest);
6305 varunset(p, varname, startp, varflags);
6308 #if ENABLE_ASH_BASH_COMPAT
6310 loc = str = stackblock() + strloc;
6311 /* Read POS in ${var:POS:LEN} */
6312 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6313 len = str - startp - 1;
6315 /* *loc != '\0', guaranteed by parser */
6319 /* Adjust the length by the number of escapes */
6320 for (ptr = startp; ptr < (str - 1); ptr++) {
6321 if ((unsigned char)*ptr == CTLESC) {
6329 if (*loc++ == ':') {
6333 /* Skip POS in ${var:POS:LEN} */
6335 while (*loc && *loc != ':') {
6337 * bash complains on: var=qwe; echo ${var:1a:123}
6339 ash_msg_and_raise_error(msg_illnum, str);
6343 if (*loc++ == ':') {
6347 if (pos >= orig_len) {
6351 if (len > (orig_len - pos))
6352 len = orig_len - pos;
6354 for (str = startp; pos; str++, pos--) {
6355 if (quotes && (unsigned char)*str == CTLESC)
6358 for (loc = startp; len; len--) {
6359 if (quotes && (unsigned char)*str == CTLESC)
6364 amount = loc - expdest;
6365 STADJUST(amount, expdest);
6370 resetloc = expdest - (char *)stackblock();
6372 /* We'll comeback here if we grow the stack while handling
6373 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6374 * stack will need rebasing, and we'll need to remove our work
6377 IF_ASH_BASH_COMPAT(restart:)
6379 amount = expdest - ((char *)stackblock() + resetloc);
6380 STADJUST(-amount, expdest);
6381 startp = (char *)stackblock() + startloc;
6384 rmescend = (char *)stackblock() + strloc;
6386 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6387 if (rmesc != startp) {
6389 startp = (char *)stackblock() + startloc;
6393 str = (char *)stackblock() + strloc;
6394 preglob(str, varflags & VSQUOTE, 0);
6395 workloc = expdest - (char *)stackblock();
6397 #if ENABLE_ASH_BASH_COMPAT
6398 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6402 repl = parse_sub_pattern(str, varflags);
6403 //bb_error_msg("repl:'%s'", repl);
6408 /* If there's no pattern to match, return the expansion unmolested */
6417 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6418 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6420 /* No match, advance */
6421 char *restart_detect = stackblock();
6423 STPUTC(*idx, expdest);
6424 if (quotes && (unsigned char)*idx == CTLESC) {
6427 STPUTC(*idx, expdest);
6429 if (stackblock() != restart_detect)
6434 /* continue; - prone to quadratic behavior, smarter code: */
6437 if (str[0] == '*') {
6438 /* Pattern is "*foo". If "*foo" does not match "long_string",
6439 * it would never match "ong_string" etc, no point in trying.
6446 if (subtype == VSREPLACEALL) {
6448 if (quotes && (unsigned char)*idx == CTLESC)
6457 //bb_error_msg("repl:'%s'", repl);
6458 for (loc = (char*)repl; *loc; loc++) {
6459 char *restart_detect = stackblock();
6460 if (quotes && *loc == '\\') {
6461 STPUTC(CTLESC, expdest);
6464 STPUTC(*loc, expdest);
6465 if (stackblock() != restart_detect)
6470 if (subtype == VSREPLACE) {
6471 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6473 char *restart_detect = stackblock();
6474 STPUTC(*idx, expdest);
6475 if (stackblock() != restart_detect)
6484 /* We've put the replaced text into a buffer at workloc, now
6485 * move it to the right place and adjust the stack.
6487 STPUTC('\0', expdest);
6488 startp = (char *)stackblock() + startloc;
6489 memmove(startp, (char *)stackblock() + workloc, len + 1);
6490 //bb_error_msg("startp:'%s'", startp);
6491 amount = expdest - (startp + len);
6492 STADJUST(-amount, expdest);
6495 #endif /* ENABLE_ASH_BASH_COMPAT */
6497 subtype -= VSTRIMRIGHT;
6499 if (subtype < 0 || subtype > 7)
6502 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6503 zero = subtype >> 1;
6504 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6505 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6507 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6510 memmove(startp, loc, str - loc);
6511 loc = startp + (str - loc) - 1;
6514 amount = loc - expdest;
6515 STADJUST(amount, expdest);
6521 * Add the value of a specialized variable to the stack string.
6522 * name parameter (examples):
6523 * ash -c 'echo $1' name:'1='
6524 * ash -c 'echo $qwe' name:'qwe='
6525 * ash -c 'echo $$' name:'$='
6526 * ash -c 'echo ${$}' name:'$='
6527 * ash -c 'echo ${$##q}' name:'$=q'
6528 * ash -c 'echo ${#$}' name:'$='
6529 * note: examples with bad shell syntax:
6530 * ash -c 'echo ${#$1}' name:'$=1'
6531 * ash -c 'echo ${#1#}' name:'1=#'
6533 static NOINLINE ssize_t
6534 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6541 int subtype = varflags & VSTYPE;
6542 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6543 int quoted = varflags & VSQUOTE;
6544 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6554 num = shellparam.nparam;
6562 goto check_1char_name;
6564 expdest = makestrspace(NOPTS, expdest);
6565 for (i = NOPTS - 1; i >= 0; i--) {
6567 USTPUTC(optletters(i), expdest);
6573 /* handles cases similar to ${#$1} */
6574 if (name[2] != '\0')
6575 raise_error_syntax("bad substitution");
6582 if (quoted && (flags & EXP_FULL)) {
6583 /* note: this is not meant as PEOF value */
6584 sep = 1 << CHAR_BIT;
6589 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6590 i = SIT(sep, syntax);
6591 if (quotes && (i == CCTL || i == CBACK))
6597 while ((p = *ap++) != NULL) {
6600 partlen = strlen(p);
6603 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6604 memtodest(p, partlen, syntax, quotes);
6610 if (subtype == VSPLUS || subtype == VSLENGTH) {
6616 /* note: may put NUL despite sep != 0
6617 * (see sep = 1 << CHAR_BIT above) */
6623 } /* case '@' and '*' */
6634 num = atoi(name); /* number(name) fails on ${N#str} etc */
6635 if (num < 0 || num > shellparam.nparam)
6637 p = num ? shellparam.p[num - 1] : arg0;
6640 /* NB: name has form "VAR=..." */
6642 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6643 * which should be considered before we check variables. */
6645 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6649 str = var_str_list->text;
6650 eq = strchr(str, '=');
6651 if (!eq) /* stop at first non-assignment */
6654 if (name_len == (unsigned)(eq - str)
6655 && strncmp(str, name, name_len) == 0
6658 /* goto value; - WRONG! */
6659 /* think "A=1 A=2 B=$A" */
6661 var_str_list = var_str_list->next;
6662 } while (var_str_list);
6666 p = lookupvar(name);
6672 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6673 memtodest(p, len, syntax, quotes);
6677 if (subtype == VSPLUS || subtype == VSLENGTH)
6678 STADJUST(-len, expdest);
6683 * Expand a variable, and return a pointer to the next character in the
6687 evalvar(char *p, int flags, struct strlist *var_str_list)
6698 varflags = (unsigned char) *p++;
6699 subtype = varflags & VSTYPE;
6700 quoted = varflags & VSQUOTE;
6702 easy = (!quoted || (*var == '@' && shellparam.nparam));
6703 startloc = expdest - (char *)stackblock();
6704 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6707 varlen = varvalue(var, varflags, flags, var_str_list);
6708 if (varflags & VSNUL)
6711 if (subtype == VSPLUS) {
6712 varlen = -1 - varlen;
6716 if (subtype == VSMINUS) {
6721 flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
6731 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6733 if (subevalvar(p, var, /* strloc: */ 0,
6734 subtype, startloc, varflags,
6740 * Remove any recorded regions beyond
6743 removerecordregions(startloc);
6753 if (varlen < 0 && uflag)
6754 varunset(p, var, 0, 0);
6756 if (subtype == VSLENGTH) {
6757 cvtnum(varlen > 0 ? varlen : 0);
6761 if (subtype == VSNORMAL) {
6772 case VSTRIMRIGHTMAX:
6773 #if ENABLE_ASH_BASH_COMPAT
6786 * Terminate the string and start recording the pattern
6789 STPUTC('\0', expdest);
6790 patloc = expdest - (char *)stackblock();
6791 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6793 //TODO: | EXP_REDIR too? All other such places do it too
6794 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6797 int amount = expdest - (
6798 (char *)stackblock() + patloc - 1
6800 STADJUST(-amount, expdest);
6802 /* Remove any recorded regions beyond start of variable */
6803 removerecordregions(startloc);
6805 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6809 if (subtype != VSNORMAL) { /* skip to end of alternative */
6812 unsigned char c = *p++;
6815 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6817 argbackq = argbackq->next;
6818 } else if (c == CTLVAR) {
6819 if ((*p++ & VSTYPE) != VSNORMAL)
6821 } else if (c == CTLENDVAR) {
6831 * Break the argument string into pieces based upon IFS and add the
6832 * strings to the argument list. The regions of the string to be
6833 * searched for IFS characters have been stored by recordregion.
6836 ifsbreakup(char *string, struct arglist *arglist)
6838 struct ifsregion *ifsp;
6843 const char *ifs, *realifs;
6848 if (ifslastp != NULL) {
6851 realifs = ifsset() ? ifsval() : defifs;
6854 p = string + ifsp->begoff;
6855 nulonly = ifsp->nulonly;
6856 ifs = nulonly ? nullstr : realifs;
6858 while (p < string + ifsp->endoff) {
6860 if ((unsigned char)*p == CTLESC)
6862 if (!strchr(ifs, *p)) {
6867 ifsspc = (strchr(defifs, *p) != NULL);
6868 /* Ignore IFS whitespace at start */
6869 if (q == start && ifsspc) {
6875 sp = stzalloc(sizeof(*sp));
6877 *arglist->lastp = sp;
6878 arglist->lastp = &sp->next;
6882 if (p >= string + ifsp->endoff) {
6886 if ((unsigned char)*p == CTLESC)
6888 if (strchr(ifs, *p) == NULL) {
6892 if (strchr(defifs, *p) == NULL) {
6907 } while (ifsp != NULL);
6916 sp = stzalloc(sizeof(*sp));
6918 *arglist->lastp = sp;
6919 arglist->lastp = &sp->next;
6925 struct ifsregion *p;
6930 struct ifsregion *ifsp;
6936 ifsfirst.next = NULL;
6941 * Add a file name to the list.
6944 addfname(const char *name)
6948 sp = stzalloc(sizeof(*sp));
6949 sp->text = ststrdup(name);
6951 exparg.lastp = &sp->next;
6955 * Do metacharacter (i.e. *, ?, [...]) expansion.
6958 expmeta(char *expdir, char *enddir, char *name)
6973 for (p = name; *p; p++) {
6974 if (*p == '*' || *p == '?')
6976 else if (*p == '[') {
6983 if (*q == '/' || *q == '\0')
6990 } else if (*p == '\\')
6992 else if (*p == '/') {
6999 if (metaflag == 0) { /* we've reached the end of the file name */
7000 if (enddir != expdir)
7008 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7019 } while (p < start);
7021 if (enddir == expdir) {
7023 } else if (enddir == expdir + 1 && *expdir == '/') {
7032 if (enddir != expdir)
7034 if (*endname == 0) {
7046 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7047 if (dp->d_name[0] == '.' && !matchdot)
7049 if (pmatch(start, dp->d_name)) {
7051 strcpy(enddir, dp->d_name);
7054 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7057 expmeta(expdir, p, endname);
7066 static struct strlist *
7067 msort(struct strlist *list, int len)
7069 struct strlist *p, *q = NULL;
7070 struct strlist **lpp;
7078 for (n = half; --n >= 0;) {
7082 q->next = NULL; /* terminate first half of list */
7083 q = msort(list, half); /* sort first half of list */
7084 p = msort(p, len - half); /* sort second half */
7087 #if ENABLE_LOCALE_SUPPORT
7088 if (strcoll(p->text, q->text) < 0)
7090 if (strcmp(p->text, q->text) < 0)
7114 * Sort the results of file name expansion. It calculates the number of
7115 * strings to sort and then calls msort (short for merge sort) to do the
7118 static struct strlist *
7119 expsort(struct strlist *str)
7125 for (sp = str; sp; sp = sp->next)
7127 return msort(str, len);
7131 expandmeta(struct strlist *str /*, int flag*/)
7133 static const char metachars[] ALIGN1 = {
7136 /* TODO - EXP_REDIR */
7140 struct strlist **savelastp;
7146 if (!strpbrk(str->text, metachars))
7148 savelastp = exparg.lastp;
7151 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7153 int i = strlen(str->text);
7154 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7156 expmeta(expdir, expdir, p);
7161 if (exparg.lastp == savelastp) {
7166 *exparg.lastp = str;
7167 rmescapes(str->text, 0);
7168 exparg.lastp = &str->next;
7170 *exparg.lastp = NULL;
7171 *savelastp = sp = expsort(*savelastp);
7172 while (sp->next != NULL)
7174 exparg.lastp = &sp->next;
7181 * Perform variable substitution and command substitution on an argument,
7182 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7183 * perform splitting and file name expansion. When arglist is NULL, perform
7184 * here document expansion.
7187 expandarg(union node *arg, struct arglist *arglist, int flag)
7192 argbackq = arg->narg.backquote;
7193 STARTSTACKSTR(expdest);
7194 ifsfirst.next = NULL;
7196 argstr(arg->narg.text, flag,
7197 /* var_str_list: */ arglist ? arglist->list : NULL);
7198 p = _STPUTC('\0', expdest);
7200 if (arglist == NULL) {
7201 return; /* here document expanded */
7203 p = grabstackstr(p);
7204 exparg.lastp = &exparg.list;
7208 if (flag & EXP_FULL) {
7209 ifsbreakup(p, &exparg);
7210 *exparg.lastp = NULL;
7211 exparg.lastp = &exparg.list;
7212 expandmeta(exparg.list /*, flag*/);
7214 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7216 sp = stzalloc(sizeof(*sp));
7219 exparg.lastp = &sp->next;
7223 *exparg.lastp = NULL;
7225 *arglist->lastp = exparg.list;
7226 arglist->lastp = exparg.lastp;
7231 * Expand shell variables and backquotes inside a here document.
7234 expandhere(union node *arg, int fd)
7237 expandarg(arg, (struct arglist *)NULL, 0);
7238 full_write(fd, stackblock(), expdest - (char *)stackblock());
7242 * Returns true if the pattern matches the string.
7245 patmatch(char *pattern, const char *string)
7247 return pmatch(preglob(pattern, 0, 0), string);
7251 * See if a pattern matches in a case statement.
7254 casematch(union node *pattern, char *val)
7256 struct stackmark smark;
7259 setstackmark(&smark);
7260 argbackq = pattern->narg.backquote;
7261 STARTSTACKSTR(expdest);
7263 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7264 /* var_str_list: */ NULL);
7265 STACKSTRNUL(expdest);
7266 result = patmatch(stackblock(), val);
7267 popstackmark(&smark);
7272 /* ============ find_command */
7276 int (*builtin)(int, char **) FAST_FUNC;
7277 /* unsigned flags; */
7279 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7280 /* "regular" builtins always take precedence over commands,
7281 * regardless of PATH=....%builtin... position */
7282 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7283 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7286 smallint cmdtype; /* CMDxxx */
7289 /* index >= 0 for commands without path (slashes) */
7290 /* (TODO: what exactly does the value mean? PATH position?) */
7291 /* index == -1 for commands with slashes */
7292 /* index == (-2 - applet_no) for NOFORK applets */
7293 const struct builtincmd *cmd;
7294 struct funcnode *func;
7297 /* values of cmdtype */
7298 #define CMDUNKNOWN -1 /* no entry in table for command */
7299 #define CMDNORMAL 0 /* command is an executable program */
7300 #define CMDFUNCTION 1 /* command is a shell function */
7301 #define CMDBUILTIN 2 /* command is a shell builtin */
7303 /* action to find_command() */
7304 #define DO_ERR 0x01 /* prints errors */
7305 #define DO_ABS 0x02 /* checks absolute paths */
7306 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7307 #define DO_ALTPATH 0x08 /* using alternate path */
7308 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7310 static void find_command(char *, struct cmdentry *, int, const char *);
7313 /* ============ Hashing commands */
7316 * When commands are first encountered, they are entered in a hash table.
7317 * This ensures that a full path search will not have to be done for them
7318 * on each invocation.
7320 * We should investigate converting to a linear search, even though that
7321 * would make the command name "hash" a misnomer.
7325 struct tblentry *next; /* next entry in hash chain */
7326 union param param; /* definition of builtin function */
7327 smallint cmdtype; /* CMDxxx */
7328 char rehash; /* if set, cd done since entry created */
7329 char cmdname[1]; /* name of command */
7332 static struct tblentry **cmdtable;
7333 #define INIT_G_cmdtable() do { \
7334 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7337 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7341 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7345 #if ENABLE_FEATURE_SH_STANDALONE
7346 if (applet_no >= 0) {
7347 if (APPLET_IS_NOEXEC(applet_no)) {
7351 run_applet_no_and_exit(applet_no, argv);
7353 /* re-exec ourselves with the new arguments */
7354 execve(bb_busybox_exec_path, argv, envp);
7355 /* If they called chroot or otherwise made the binary no longer
7356 * executable, fall through */
7363 execve(cmd, argv, envp);
7364 } while (errno == EINTR);
7366 execve(cmd, argv, envp);
7372 if (errno == ENOEXEC) {
7376 for (ap = argv; *ap; ap++)
7378 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7380 ap[0] = cmd = (char *)DEFAULT_SHELL;
7383 while ((*ap++ = *argv++) != NULL)
7392 * Exec a program. Never returns. If you change this routine, you may
7393 * have to change the find_command routine as well.
7395 static void shellexec(char **, const char *, int) NORETURN;
7397 shellexec(char **argv, const char *path, int idx)
7403 #if ENABLE_FEATURE_SH_STANDALONE
7407 clearredir(/*drop:*/ 1);
7408 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7409 if (strchr(argv[0], '/') != NULL
7410 #if ENABLE_FEATURE_SH_STANDALONE
7411 || (applet_no = find_applet_by_name(argv[0])) >= 0
7414 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7418 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7419 if (--idx < 0 && pathopt == NULL) {
7420 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7421 if (errno != ENOENT && errno != ENOTDIR)
7428 /* Map to POSIX errors */
7440 exitstatus = exerrno;
7441 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7442 argv[0], e, suppress_int));
7443 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7448 printentry(struct tblentry *cmdp)
7454 idx = cmdp->param.index;
7457 name = path_advance(&path, cmdp->cmdname);
7459 } while (--idx >= 0);
7460 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7464 * Clear out command entries. The argument specifies the first entry in
7465 * PATH which has changed.
7468 clearcmdentry(int firstchange)
7470 struct tblentry **tblp;
7471 struct tblentry **pp;
7472 struct tblentry *cmdp;
7475 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7477 while ((cmdp = *pp) != NULL) {
7478 if ((cmdp->cmdtype == CMDNORMAL &&
7479 cmdp->param.index >= firstchange)
7480 || (cmdp->cmdtype == CMDBUILTIN &&
7481 builtinloc >= firstchange)
7494 * Locate a command in the command hash table. If "add" is nonzero,
7495 * add the command to the table if it is not already present. The
7496 * variable "lastcmdentry" is set to point to the address of the link
7497 * pointing to the entry, so that delete_cmd_entry can delete the
7500 * Interrupts must be off if called with add != 0.
7502 static struct tblentry **lastcmdentry;
7504 static struct tblentry *
7505 cmdlookup(const char *name, int add)
7507 unsigned int hashval;
7509 struct tblentry *cmdp;
7510 struct tblentry **pp;
7513 hashval = (unsigned char)*p << 4;
7515 hashval += (unsigned char)*p++;
7517 pp = &cmdtable[hashval % CMDTABLESIZE];
7518 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7519 if (strcmp(cmdp->cmdname, name) == 0)
7523 if (add && cmdp == NULL) {
7524 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7526 /* + 1 - already done because
7527 * tblentry::cmdname is char[1] */);
7528 /*cmdp->next = NULL; - ckzalloc did it */
7529 cmdp->cmdtype = CMDUNKNOWN;
7530 strcpy(cmdp->cmdname, name);
7537 * Delete the command entry returned on the last lookup.
7540 delete_cmd_entry(void)
7542 struct tblentry *cmdp;
7545 cmdp = *lastcmdentry;
7546 *lastcmdentry = cmdp->next;
7547 if (cmdp->cmdtype == CMDFUNCTION)
7548 freefunc(cmdp->param.func);
7554 * Add a new command entry, replacing any existing command entry for
7555 * the same name - except special builtins.
7558 addcmdentry(char *name, struct cmdentry *entry)
7560 struct tblentry *cmdp;
7562 cmdp = cmdlookup(name, 1);
7563 if (cmdp->cmdtype == CMDFUNCTION) {
7564 freefunc(cmdp->param.func);
7566 cmdp->cmdtype = entry->cmdtype;
7567 cmdp->param = entry->u;
7571 static int FAST_FUNC
7572 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7574 struct tblentry **pp;
7575 struct tblentry *cmdp;
7577 struct cmdentry entry;
7580 if (nextopt("r") != '\0') {
7585 if (*argptr == NULL) {
7586 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7587 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7588 if (cmdp->cmdtype == CMDNORMAL)
7596 while ((name = *argptr) != NULL) {
7597 cmdp = cmdlookup(name, 0);
7599 && (cmdp->cmdtype == CMDNORMAL
7600 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7604 find_command(name, &entry, DO_ERR, pathval());
7605 if (entry.cmdtype == CMDUNKNOWN)
7613 * Called when a cd is done. Marks all commands so the next time they
7614 * are executed they will be rehashed.
7619 struct tblentry **pp;
7620 struct tblentry *cmdp;
7622 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7623 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7624 if (cmdp->cmdtype == CMDNORMAL
7625 || (cmdp->cmdtype == CMDBUILTIN
7626 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7636 * Fix command hash table when PATH changed.
7637 * Called before PATH is changed. The argument is the new value of PATH;
7638 * pathval() still returns the old value at this point.
7639 * Called with interrupts off.
7641 static void FAST_FUNC
7642 changepath(const char *new)
7650 firstchange = 9999; /* assume no change */
7656 if ((*old == '\0' && *new == ':')
7657 || (*old == ':' && *new == '\0')
7661 old = new; /* ignore subsequent differences */
7665 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7672 if (builtinloc < 0 && idx_bltin >= 0)
7673 builtinloc = idx_bltin; /* zap builtins */
7674 if (builtinloc >= 0 && idx_bltin < 0)
7676 clearcmdentry(firstchange);
7677 builtinloc = idx_bltin;
7692 #define TENDBQUOTE 12
7709 typedef smallint token_id_t;
7711 /* first char is indicating which tokens mark the end of a list */
7712 static const char *const tokname_array[] = {
7726 #define KWDOFFSET 13
7727 /* the following are keywords */
7746 /* Wrapper around strcmp for qsort/bsearch/... */
7748 pstrcmp(const void *a, const void *b)
7750 return strcmp((char*) a, (*(char**) b) + 1);
7753 static const char *const *
7754 findkwd(const char *s)
7756 return bsearch(s, tokname_array + KWDOFFSET,
7757 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7758 sizeof(tokname_array[0]), pstrcmp);
7762 * Locate and print what a word is...
7765 describe_command(char *command, int describe_command_verbose)
7767 struct cmdentry entry;
7768 struct tblentry *cmdp;
7769 #if ENABLE_ASH_ALIAS
7770 const struct alias *ap;
7772 const char *path = pathval();
7774 if (describe_command_verbose) {
7778 /* First look at the keywords */
7779 if (findkwd(command)) {
7780 out1str(describe_command_verbose ? " is a shell keyword" : command);
7784 #if ENABLE_ASH_ALIAS
7785 /* Then look at the aliases */
7786 ap = lookupalias(command, 0);
7788 if (!describe_command_verbose) {
7793 out1fmt(" is an alias for %s", ap->val);
7797 /* Then check if it is a tracked alias */
7798 cmdp = cmdlookup(command, 0);
7800 entry.cmdtype = cmdp->cmdtype;
7801 entry.u = cmdp->param;
7803 /* Finally use brute force */
7804 find_command(command, &entry, DO_ABS, path);
7807 switch (entry.cmdtype) {
7809 int j = entry.u.index;
7815 p = path_advance(&path, command);
7819 if (describe_command_verbose) {
7821 (cmdp ? " a tracked alias for" : nullstr), p
7830 if (describe_command_verbose) {
7831 out1str(" is a shell function");
7838 if (describe_command_verbose) {
7839 out1fmt(" is a %sshell builtin",
7840 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7841 "special " : nullstr
7849 if (describe_command_verbose) {
7850 out1str(": not found\n");
7859 static int FAST_FUNC
7860 typecmd(int argc UNUSED_PARAM, char **argv)
7866 /* type -p ... ? (we don't bother checking for 'p') */
7867 if (argv[1] && argv[1][0] == '-') {
7872 err |= describe_command(argv[i++], verbose);
7877 #if ENABLE_ASH_CMDCMD
7878 static int FAST_FUNC
7879 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7887 while ((c = nextopt("pvV")) != '\0')
7889 verify |= VERIFY_VERBOSE;
7891 verify |= VERIFY_BRIEF;
7896 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7897 if (verify && (*argptr != NULL)) {
7898 return describe_command(*argptr, verify - VERIFY_BRIEF);
7906 /* ============ eval.c */
7908 static int funcblocksize; /* size of structures in function */
7909 static int funcstringsize; /* size of strings in node */
7910 static void *funcblock; /* block to allocate function from */
7911 static char *funcstring; /* block to allocate strings from */
7913 /* flags in argument to evaltree */
7914 #define EV_EXIT 01 /* exit after evaluating tree */
7915 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7916 #define EV_BACKCMD 04 /* command executing within back quotes */
7918 static const uint8_t nodesize[N_NUMBER] = {
7919 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7920 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7921 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7922 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7923 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7924 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7925 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7926 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7927 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7928 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7929 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7930 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7931 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7932 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7933 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7934 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7935 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7936 #if ENABLE_ASH_BASH_COMPAT
7937 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7939 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7940 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7941 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7942 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7943 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7944 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7945 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7946 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7947 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7950 static void calcsize(union node *n);
7953 sizenodelist(struct nodelist *lp)
7956 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7963 calcsize(union node *n)
7967 funcblocksize += nodesize[n->type];
7970 calcsize(n->ncmd.redirect);
7971 calcsize(n->ncmd.args);
7972 calcsize(n->ncmd.assign);
7975 sizenodelist(n->npipe.cmdlist);
7980 calcsize(n->nredir.redirect);
7981 calcsize(n->nredir.n);
7988 calcsize(n->nbinary.ch2);
7989 calcsize(n->nbinary.ch1);
7992 calcsize(n->nif.elsepart);
7993 calcsize(n->nif.ifpart);
7994 calcsize(n->nif.test);
7997 funcstringsize += strlen(n->nfor.var) + 1;
7998 calcsize(n->nfor.body);
7999 calcsize(n->nfor.args);
8002 calcsize(n->ncase.cases);
8003 calcsize(n->ncase.expr);
8006 calcsize(n->nclist.body);
8007 calcsize(n->nclist.pattern);
8008 calcsize(n->nclist.next);
8012 sizenodelist(n->narg.backquote);
8013 funcstringsize += strlen(n->narg.text) + 1;
8014 calcsize(n->narg.next);
8017 #if ENABLE_ASH_BASH_COMPAT
8024 calcsize(n->nfile.fname);
8025 calcsize(n->nfile.next);
8029 calcsize(n->ndup.vname);
8030 calcsize(n->ndup.next);
8034 calcsize(n->nhere.doc);
8035 calcsize(n->nhere.next);
8038 calcsize(n->nnot.com);
8044 nodeckstrdup(char *s)
8046 char *rtn = funcstring;
8048 strcpy(funcstring, s);
8049 funcstring += strlen(s) + 1;
8053 static union node *copynode(union node *);
8055 static struct nodelist *
8056 copynodelist(struct nodelist *lp)
8058 struct nodelist *start;
8059 struct nodelist **lpp;
8064 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8065 (*lpp)->n = copynode(lp->n);
8067 lpp = &(*lpp)->next;
8074 copynode(union node *n)
8081 funcblock = (char *) funcblock + nodesize[n->type];
8085 new->ncmd.redirect = copynode(n->ncmd.redirect);
8086 new->ncmd.args = copynode(n->ncmd.args);
8087 new->ncmd.assign = copynode(n->ncmd.assign);
8090 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8091 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8096 new->nredir.redirect = copynode(n->nredir.redirect);
8097 new->nredir.n = copynode(n->nredir.n);
8104 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8105 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8108 new->nif.elsepart = copynode(n->nif.elsepart);
8109 new->nif.ifpart = copynode(n->nif.ifpart);
8110 new->nif.test = copynode(n->nif.test);
8113 new->nfor.var = nodeckstrdup(n->nfor.var);
8114 new->nfor.body = copynode(n->nfor.body);
8115 new->nfor.args = copynode(n->nfor.args);
8118 new->ncase.cases = copynode(n->ncase.cases);
8119 new->ncase.expr = copynode(n->ncase.expr);
8122 new->nclist.body = copynode(n->nclist.body);
8123 new->nclist.pattern = copynode(n->nclist.pattern);
8124 new->nclist.next = copynode(n->nclist.next);
8128 new->narg.backquote = copynodelist(n->narg.backquote);
8129 new->narg.text = nodeckstrdup(n->narg.text);
8130 new->narg.next = copynode(n->narg.next);
8133 #if ENABLE_ASH_BASH_COMPAT
8140 new->nfile.fname = copynode(n->nfile.fname);
8141 new->nfile.fd = n->nfile.fd;
8142 new->nfile.next = copynode(n->nfile.next);
8146 new->ndup.vname = copynode(n->ndup.vname);
8147 new->ndup.dupfd = n->ndup.dupfd;
8148 new->ndup.fd = n->ndup.fd;
8149 new->ndup.next = copynode(n->ndup.next);
8153 new->nhere.doc = copynode(n->nhere.doc);
8154 new->nhere.fd = n->nhere.fd;
8155 new->nhere.next = copynode(n->nhere.next);
8158 new->nnot.com = copynode(n->nnot.com);
8161 new->type = n->type;
8166 * Make a copy of a parse tree.
8168 static struct funcnode *
8169 copyfunc(union node *n)
8174 funcblocksize = offsetof(struct funcnode, n);
8177 blocksize = funcblocksize;
8178 f = ckmalloc(blocksize + funcstringsize);
8179 funcblock = (char *) f + offsetof(struct funcnode, n);
8180 funcstring = (char *) f + blocksize;
8187 * Define a shell function.
8190 defun(char *name, union node *func)
8192 struct cmdentry entry;
8195 entry.cmdtype = CMDFUNCTION;
8196 entry.u.func = copyfunc(func);
8197 addcmdentry(name, &entry);
8201 /* Reasons for skipping commands (see comment on breakcmd routine) */
8202 #define SKIPBREAK (1 << 0)
8203 #define SKIPCONT (1 << 1)
8204 #define SKIPFUNC (1 << 2)
8205 #define SKIPFILE (1 << 3)
8206 #define SKIPEVAL (1 << 4)
8207 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8208 static int skipcount; /* number of levels to skip */
8209 static int funcnest; /* depth of function calls */
8210 static int loopnest; /* current loop nesting level */
8212 /* Forward decl way out to parsing code - dotrap needs it */
8213 static int evalstring(char *s, int mask);
8215 /* Called to execute a trap.
8216 * Single callsite - at the end of evaltree().
8217 * If we return non-zero, evaltree raises EXEXIT exception.
8219 * Perhaps we should avoid entering new trap handlers
8220 * while we are executing a trap handler. [is it a TODO?]
8229 savestatus = exitstatus;
8233 TRACE(("dotrap entered\n"));
8234 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8241 /* non-trapped SIGINT is handled separately by raise_interrupt,
8242 * don't upset it by resetting gotsig[SIGINT-1] */
8243 if (sig == SIGINT && !t)
8246 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8250 want_exexit = evalstring(t, SKIPEVAL);
8251 exitstatus = savestatus;
8253 TRACE(("dotrap returns %d\n", want_exexit));
8258 TRACE(("dotrap returns 0\n"));
8262 /* forward declarations - evaluation is fairly recursive business... */
8263 static void evalloop(union node *, int);
8264 static void evalfor(union node *, int);
8265 static void evalcase(union node *, int);
8266 static void evalsubshell(union node *, int);
8267 static void expredir(union node *);
8268 static void evalpipe(union node *, int);
8269 static void evalcommand(union node *, int);
8270 static int evalbltin(const struct builtincmd *, int, char **);
8271 static void prehash(union node *);
8274 * Evaluate a parse tree. The value is left in the global variable
8278 evaltree(union node *n, int flags)
8280 struct jmploc *volatile savehandler = exception_handler;
8281 struct jmploc jmploc;
8283 void (*evalfn)(union node *, int);
8287 SAVE_INT(int_level);
8290 TRACE(("evaltree(NULL) called\n"));
8293 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8295 exception_handler = &jmploc;
8297 int err = setjmp(jmploc.loc);
8299 /* if it was a signal, check for trap handlers */
8300 if (exception_type == EXSIG) {
8301 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8302 exception_type, err));
8305 /* continue on the way out */
8306 TRACE(("exception %d in evaltree, propagating err=%d\n",
8307 exception_type, err));
8308 exception_handler = savehandler;
8309 longjmp(exception_handler->loc, err);
8316 out1fmt("Node type = %d\n", n->type);
8321 evaltree(n->nnot.com, EV_TESTED);
8322 status = !exitstatus;
8325 expredir(n->nredir.redirect);
8326 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8328 evaltree(n->nredir.n, flags & EV_TESTED);
8329 status = exitstatus;
8331 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8334 evalfn = evalcommand;
8336 if (eflag && !(flags & EV_TESTED))
8348 evalfn = evalsubshell;
8361 #error NAND + 1 != NOR
8363 #if NOR + 1 != NSEMI
8364 #error NOR + 1 != NSEMI
8366 unsigned is_or = n->type - NAND;
8369 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8371 if (!exitstatus == is_or)
8384 evaltree(n->nif.test, EV_TESTED);
8387 if (exitstatus == 0) {
8391 if (n->nif.elsepart) {
8392 n = n->nif.elsepart;
8397 defun(n->narg.text, n->narg.next);
8401 exitstatus = status;
8406 exception_handler = savehandler;
8409 /* Order of checks below is important:
8410 * signal handlers trigger before exit caused by "set -e".
8412 if (pending_sig && dotrap())
8414 if (checkexit & exitstatus)
8415 evalskip |= SKIPEVAL;
8417 if (flags & EV_EXIT) {
8419 raise_exception(EXEXIT);
8422 RESTORE_INT(int_level);
8423 TRACE(("leaving evaltree (no interrupts)\n"));
8426 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8429 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8432 evalloop(union node *n, int flags)
8442 evaltree(n->nbinary.ch1, EV_TESTED);
8445 if (evalskip == SKIPCONT && --skipcount <= 0) {
8449 if (evalskip == SKIPBREAK && --skipcount <= 0)
8454 if (n->type != NWHILE)
8458 evaltree(n->nbinary.ch2, flags);
8459 status = exitstatus;
8464 exitstatus = status;
8468 evalfor(union node *n, int flags)
8470 struct arglist arglist;
8473 struct stackmark smark;
8475 setstackmark(&smark);
8476 arglist.list = NULL;
8477 arglist.lastp = &arglist.list;
8478 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8479 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8484 *arglist.lastp = NULL;
8489 for (sp = arglist.list; sp; sp = sp->next) {
8490 setvar(n->nfor.var, sp->text, 0);
8491 evaltree(n->nfor.body, flags);
8493 if (evalskip == SKIPCONT && --skipcount <= 0) {
8497 if (evalskip == SKIPBREAK && --skipcount <= 0)
8504 popstackmark(&smark);
8508 evalcase(union node *n, int flags)
8512 struct arglist arglist;
8513 struct stackmark smark;
8515 setstackmark(&smark);
8516 arglist.list = NULL;
8517 arglist.lastp = &arglist.list;
8518 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8520 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8521 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8522 if (casematch(patp, arglist.list->text)) {
8523 if (evalskip == 0) {
8524 evaltree(cp->nclist.body, flags);
8531 popstackmark(&smark);
8535 * Kick off a subshell to evaluate a tree.
8538 evalsubshell(union node *n, int flags)
8541 int backgnd = (n->type == NBACKGND);
8544 expredir(n->nredir.redirect);
8545 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8548 jp = makejob(/*n,*/ 1);
8549 if (forkshell(jp, n, backgnd) == 0) {
8554 flags &= ~EV_TESTED;
8556 redirect(n->nredir.redirect, 0);
8557 evaltreenr(n->nredir.n, flags);
8562 status = waitforjob(jp);
8563 exitstatus = status;
8568 * Compute the names of the files in a redirection list.
8570 static void fixredir(union node *, const char *, int);
8572 expredir(union node *n)
8576 for (redir = n; redir; redir = redir->nfile.next) {
8580 fn.lastp = &fn.list;
8581 switch (redir->type) {
8585 #if ENABLE_ASH_BASH_COMPAT
8590 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8591 #if ENABLE_ASH_BASH_COMPAT
8594 redir->nfile.expfname = fn.list->text;
8597 case NTOFD: /* >& */
8598 if (redir->ndup.vname) {
8599 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8600 if (fn.list == NULL)
8601 ash_msg_and_raise_error("redir error");
8602 #if ENABLE_ASH_BASH_COMPAT
8603 //FIXME: we used expandarg with different args!
8604 if (!isdigit_str9(fn.list->text)) {
8605 /* >&file, not >&fd */
8606 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8607 ash_msg_and_raise_error("redir error");
8609 goto store_expfname;
8612 fixredir(redir, fn.list->text, 1);
8620 * Evaluate a pipeline. All the processes in the pipeline are children
8621 * of the process creating the pipeline. (This differs from some versions
8622 * of the shell, which make the last process in a pipeline the parent
8626 evalpipe(union node *n, int flags)
8629 struct nodelist *lp;
8634 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8636 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8640 jp = makejob(/*n,*/ pipelen);
8642 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8646 if (pipe(pip) < 0) {
8648 ash_msg_and_raise_error("pipe call failed");
8651 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8664 evaltreenr(lp->n, flags);
8670 /* Don't want to trigger debugging */
8674 if (n->npipe.pipe_backgnd == 0) {
8675 exitstatus = waitforjob(jp);
8676 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8682 * Controls whether the shell is interactive or not.
8685 setinteractive(int on)
8687 static smallint is_interactive;
8689 if (++on == is_interactive)
8691 is_interactive = on;
8695 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8696 if (is_interactive > 1) {
8697 /* Looks like they want an interactive shell */
8698 static smallint did_banner;
8701 /* note: ash and hush share this string */
8702 out1fmt("\n\n%s %s\n"
8703 "Enter 'help' for a list of built-in commands."
8706 "built-in shell (ash)"
8720 setinteractive(iflag);
8722 #if ENABLE_FEATURE_EDITING_VI
8724 line_input_state->flags |= VI_MODE;
8726 line_input_state->flags &= ~VI_MODE;
8728 viflag = 0; /* forcibly keep the option off */
8732 static struct localvar *localvars;
8735 * Called after a function returns.
8736 * Interrupts must be off.
8741 struct localvar *lvp;
8744 while ((lvp = localvars) != NULL) {
8745 localvars = lvp->next;
8747 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8748 if (vp == NULL) { /* $- saved */
8749 memcpy(optlist, lvp->text, sizeof(optlist));
8750 free((char*)lvp->text);
8752 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8753 unsetvar(vp->var_text);
8756 vp->var_func(var_end(lvp->text));
8757 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8758 free((char*)vp->var_text);
8759 vp->flags = lvp->flags;
8760 vp->var_text = lvp->text;
8767 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8769 volatile struct shparam saveparam;
8770 struct localvar *volatile savelocalvars;
8771 struct jmploc *volatile savehandler;
8772 struct jmploc jmploc;
8775 saveparam = shellparam;
8776 savelocalvars = localvars;
8777 e = setjmp(jmploc.loc);
8782 savehandler = exception_handler;
8783 exception_handler = &jmploc;
8785 shellparam.malloced = 0;
8789 shellparam.nparam = argc - 1;
8790 shellparam.p = argv + 1;
8791 #if ENABLE_ASH_GETOPTS
8792 shellparam.optind = 1;
8793 shellparam.optoff = -1;
8795 evaltree(&func->n, flags & EV_TESTED);
8801 localvars = savelocalvars;
8802 freeparam(&shellparam);
8803 shellparam = saveparam;
8804 exception_handler = savehandler;
8806 evalskip &= ~SKIPFUNC;
8810 #if ENABLE_ASH_CMDCMD
8812 parse_command_args(char **argv, const char **path)
8825 if (c == '-' && !*cp) {
8832 *path = bb_default_path;
8835 /* run 'typecmd' for other options */
8846 * Make a variable a local variable. When a variable is made local, it's
8847 * value and flags are saved in a localvar structure. The saved values
8848 * will be restored when the shell function returns. We handle the name
8849 * "-" as a special case.
8854 struct localvar *lvp;
8859 lvp = ckzalloc(sizeof(struct localvar));
8860 if (LONE_DASH(name)) {
8862 p = ckmalloc(sizeof(optlist));
8863 lvp->text = memcpy(p, optlist, sizeof(optlist));
8868 vpp = hashvar(name);
8869 vp = *findvar(vpp, name);
8870 eq = strchr(name, '=');
8873 setvareq(name, VSTRFIXED);
8875 setvar(name, NULL, VSTRFIXED);
8876 vp = *vpp; /* the new variable */
8877 lvp->flags = VUNSET;
8879 lvp->text = vp->var_text;
8880 lvp->flags = vp->flags;
8881 vp->flags |= VSTRFIXED|VTEXTFIXED;
8887 lvp->next = localvars;
8893 * The "local" command.
8895 static int FAST_FUNC
8896 localcmd(int argc UNUSED_PARAM, char **argv)
8901 while ((name = *argv++) != NULL) {
8907 static int FAST_FUNC
8908 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8913 static int FAST_FUNC
8914 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8919 static int FAST_FUNC
8920 execcmd(int argc UNUSED_PARAM, char **argv)
8923 iflag = 0; /* exit on error */
8926 shellexec(argv + 1, pathval(), 0);
8932 * The return command.
8934 static int FAST_FUNC
8935 returncmd(int argc UNUSED_PARAM, char **argv)
8938 * If called outside a function, do what ksh does;
8939 * skip the rest of the file.
8941 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8942 return argv[1] ? number(argv[1]) : exitstatus;
8945 /* Forward declarations for builtintab[] */
8946 static int breakcmd(int, char **) FAST_FUNC;
8947 static int dotcmd(int, char **) FAST_FUNC;
8948 static int evalcmd(int, char **) FAST_FUNC;
8949 static int exitcmd(int, char **) FAST_FUNC;
8950 static int exportcmd(int, char **) FAST_FUNC;
8951 #if ENABLE_ASH_GETOPTS
8952 static int getoptscmd(int, char **) FAST_FUNC;
8954 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8955 static int helpcmd(int, char **) FAST_FUNC;
8957 #if ENABLE_SH_MATH_SUPPORT
8958 static int letcmd(int, char **) FAST_FUNC;
8960 static int readcmd(int, char **) FAST_FUNC;
8961 static int setcmd(int, char **) FAST_FUNC;
8962 static int shiftcmd(int, char **) FAST_FUNC;
8963 static int timescmd(int, char **) FAST_FUNC;
8964 static int trapcmd(int, char **) FAST_FUNC;
8965 static int umaskcmd(int, char **) FAST_FUNC;
8966 static int unsetcmd(int, char **) FAST_FUNC;
8967 static int ulimitcmd(int, char **) FAST_FUNC;
8969 #define BUILTIN_NOSPEC "0"
8970 #define BUILTIN_SPECIAL "1"
8971 #define BUILTIN_REGULAR "2"
8972 #define BUILTIN_SPEC_REG "3"
8973 #define BUILTIN_ASSIGN "4"
8974 #define BUILTIN_SPEC_ASSG "5"
8975 #define BUILTIN_REG_ASSG "6"
8976 #define BUILTIN_SPEC_REG_ASSG "7"
8978 /* Stubs for calling non-FAST_FUNC's */
8979 #if ENABLE_ASH_BUILTIN_ECHO
8980 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8982 #if ENABLE_ASH_BUILTIN_PRINTF
8983 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8985 #if ENABLE_ASH_BUILTIN_TEST
8986 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8989 /* Keep these in proper order since it is searched via bsearch() */
8990 static const struct builtincmd builtintab[] = {
8991 { BUILTIN_SPEC_REG "." , dotcmd },
8992 { BUILTIN_SPEC_REG ":" , truecmd },
8993 #if ENABLE_ASH_BUILTIN_TEST
8994 { BUILTIN_REGULAR "[" , testcmd },
8995 #if ENABLE_ASH_BASH_COMPAT
8996 { BUILTIN_REGULAR "[[" , testcmd },
8999 #if ENABLE_ASH_ALIAS
9000 { BUILTIN_REG_ASSG "alias" , aliascmd },
9003 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9005 { BUILTIN_SPEC_REG "break" , breakcmd },
9006 { BUILTIN_REGULAR "cd" , cdcmd },
9007 { BUILTIN_NOSPEC "chdir" , cdcmd },
9008 #if ENABLE_ASH_CMDCMD
9009 { BUILTIN_REGULAR "command" , commandcmd },
9011 { BUILTIN_SPEC_REG "continue", breakcmd },
9012 #if ENABLE_ASH_BUILTIN_ECHO
9013 { BUILTIN_REGULAR "echo" , echocmd },
9015 { BUILTIN_SPEC_REG "eval" , evalcmd },
9016 { BUILTIN_SPEC_REG "exec" , execcmd },
9017 { BUILTIN_SPEC_REG "exit" , exitcmd },
9018 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9019 { BUILTIN_REGULAR "false" , falsecmd },
9021 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9023 #if ENABLE_ASH_GETOPTS
9024 { BUILTIN_REGULAR "getopts" , getoptscmd },
9026 { BUILTIN_NOSPEC "hash" , hashcmd },
9027 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9028 { BUILTIN_NOSPEC "help" , helpcmd },
9031 { BUILTIN_REGULAR "jobs" , jobscmd },
9032 { BUILTIN_REGULAR "kill" , killcmd },
9034 #if ENABLE_SH_MATH_SUPPORT
9035 { BUILTIN_NOSPEC "let" , letcmd },
9037 { BUILTIN_ASSIGN "local" , localcmd },
9038 #if ENABLE_ASH_BUILTIN_PRINTF
9039 { BUILTIN_REGULAR "printf" , printfcmd },
9041 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9042 { BUILTIN_REGULAR "read" , readcmd },
9043 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9044 { BUILTIN_SPEC_REG "return" , returncmd },
9045 { BUILTIN_SPEC_REG "set" , setcmd },
9046 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9047 #if ENABLE_ASH_BASH_COMPAT
9048 { BUILTIN_SPEC_REG "source" , dotcmd },
9050 #if ENABLE_ASH_BUILTIN_TEST
9051 { BUILTIN_REGULAR "test" , testcmd },
9053 { BUILTIN_SPEC_REG "times" , timescmd },
9054 { BUILTIN_SPEC_REG "trap" , trapcmd },
9055 { BUILTIN_REGULAR "true" , truecmd },
9056 { BUILTIN_NOSPEC "type" , typecmd },
9057 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9058 { BUILTIN_REGULAR "umask" , umaskcmd },
9059 #if ENABLE_ASH_ALIAS
9060 { BUILTIN_REGULAR "unalias" , unaliascmd },
9062 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9063 { BUILTIN_REGULAR "wait" , waitcmd },
9066 /* Should match the above table! */
9067 #define COMMANDCMD (builtintab + \
9069 1 * ENABLE_ASH_BUILTIN_TEST + \
9070 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9071 1 * ENABLE_ASH_ALIAS + \
9072 1 * ENABLE_ASH_JOB_CONTROL + \
9074 #define EXECCMD (builtintab + \
9076 1 * ENABLE_ASH_BUILTIN_TEST + \
9077 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9078 1 * ENABLE_ASH_ALIAS + \
9079 1 * ENABLE_ASH_JOB_CONTROL + \
9081 1 * ENABLE_ASH_CMDCMD + \
9083 ENABLE_ASH_BUILTIN_ECHO + \
9087 * Search the table of builtin commands.
9089 static struct builtincmd *
9090 find_builtin(const char *name)
9092 struct builtincmd *bp;
9095 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9102 * Execute a simple command.
9105 isassignment(const char *p)
9107 const char *q = endofname(p);
9112 static int FAST_FUNC
9113 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9115 /* Preserve exitstatus of a previous possible redirection
9116 * as POSIX mandates */
9117 return back_exitstatus;
9120 evalcommand(union node *cmd, int flags)
9122 static const struct builtincmd null_bltin = {
9123 "\0\0", bltincmd /* why three NULs? */
9125 struct stackmark smark;
9127 struct arglist arglist;
9128 struct arglist varlist;
9131 const struct strlist *sp;
9132 struct cmdentry cmdentry;
9139 struct builtincmd *bcmd;
9140 smallint cmd_is_exec;
9141 smallint pseudovarflag = 0;
9143 /* First expand the arguments. */
9144 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9145 setstackmark(&smark);
9146 back_exitstatus = 0;
9148 cmdentry.cmdtype = CMDBUILTIN;
9149 cmdentry.u.cmd = &null_bltin;
9150 varlist.lastp = &varlist.list;
9151 *varlist.lastp = NULL;
9152 arglist.lastp = &arglist.list;
9153 *arglist.lastp = NULL;
9156 if (cmd->ncmd.args) {
9157 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9158 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9161 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9162 struct strlist **spp;
9164 spp = arglist.lastp;
9165 if (pseudovarflag && isassignment(argp->narg.text))
9166 expandarg(argp, &arglist, EXP_VARTILDE);
9168 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9170 for (sp = *spp; sp; sp = sp->next)
9174 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9175 for (sp = arglist.list; sp; sp = sp->next) {
9176 TRACE(("evalcommand arg: %s\n", sp->text));
9177 *nargv++ = sp->text;
9182 if (iflag && funcnest == 0 && argc > 0)
9183 lastarg = nargv[-1];
9186 expredir(cmd->ncmd.redirect);
9187 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9189 path = vpath.var_text;
9190 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9191 struct strlist **spp;
9194 spp = varlist.lastp;
9195 expandarg(argp, &varlist, EXP_VARTILDE);
9198 * Modify the command lookup path, if a PATH= assignment
9202 if (varcmp(p, path) == 0)
9206 /* Print the command if xflag is set. */
9209 const char *p = " %s" + 1;
9211 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9213 for (n = 0; n < 2; n++) {
9215 fdprintf(preverrout_fd, p, sp->text);
9221 safe_write(preverrout_fd, "\n", 1);
9227 /* Now locate the command. */
9229 const char *oldpath;
9230 int cmd_flag = DO_ERR;
9235 find_command(argv[0], &cmdentry, cmd_flag, path);
9236 if (cmdentry.cmdtype == CMDUNKNOWN) {
9237 flush_stdout_stderr();
9242 /* implement bltin and command here */
9243 if (cmdentry.cmdtype != CMDBUILTIN)
9246 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9247 if (cmdentry.u.cmd == EXECCMD)
9249 #if ENABLE_ASH_CMDCMD
9250 if (cmdentry.u.cmd == COMMANDCMD) {
9252 nargv = parse_command_args(argv, &path);
9255 argc -= nargv - argv;
9257 cmd_flag |= DO_NOFUNC;
9265 /* We have a redirection error. */
9267 raise_exception(EXERROR);
9269 exitstatus = status;
9273 /* Execute the command. */
9274 switch (cmdentry.cmdtype) {
9277 #if ENABLE_FEATURE_SH_NOFORK
9278 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9279 * around run_nofork_applet() call.
9280 * (2) Should this check also be done in forkshell()?
9281 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9283 /* find_command() encodes applet_no as (-2 - applet_no) */
9284 int applet_no = (- cmdentry.u.index - 2);
9285 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9286 listsetvar(varlist.list, VEXPORT|VSTACK);
9287 /* run <applet>_main() */
9288 exitstatus = run_nofork_applet(applet_no, argv);
9292 /* Can we avoid forking off? For example, very last command
9293 * in a script or a subshell does not need forking,
9294 * we can just exec it.
9296 if (!(flags & EV_EXIT) || may_have_traps) {
9297 /* No, forking off a child is necessary */
9299 jp = makejob(/*cmd,*/ 1);
9300 if (forkshell(jp, cmd, FORK_FG) != 0) {
9302 exitstatus = waitforjob(jp);
9304 TRACE(("forked child exited with %d\n", exitstatus));
9309 /* fall through to exec'ing external program */
9311 listsetvar(varlist.list, VEXPORT|VSTACK);
9312 shellexec(argv, path, cmdentry.u.index);
9316 cmdenviron = varlist.list;
9318 struct strlist *list = cmdenviron;
9320 if (spclbltin > 0 || argc == 0) {
9322 if (cmd_is_exec && argc > 1)
9325 listsetvar(list, i);
9327 /* Tight loop with builtins only:
9328 * "while kill -0 $child; do true; done"
9329 * will never exit even if $child died, unless we do this
9330 * to reap the zombie and make kill detect that it's gone: */
9331 dowait(DOWAIT_NONBLOCK, NULL);
9333 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9335 int i = exception_type;
9340 exit_status = 128 + SIGINT;
9342 exit_status = 128 + pending_sig;
9343 exitstatus = exit_status;
9344 if (i == EXINT || spclbltin > 0) {
9346 longjmp(exception_handler->loc, 1);
9353 listsetvar(varlist.list, 0);
9354 /* See above for the rationale */
9355 dowait(DOWAIT_NONBLOCK, NULL);
9356 if (evalfun(cmdentry.u.func, argc, argv, flags))
9363 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9365 /* dsl: I think this is intended to be used to support
9366 * '_' in 'vi' command mode during line editing...
9367 * However I implemented that within libedit itself.
9369 setvar("_", lastarg, 0);
9371 popstackmark(&smark);
9375 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9377 char *volatile savecmdname;
9378 struct jmploc *volatile savehandler;
9379 struct jmploc jmploc;
9382 savecmdname = commandname;
9383 i = setjmp(jmploc.loc);
9386 savehandler = exception_handler;
9387 exception_handler = &jmploc;
9388 commandname = argv[0];
9390 optptr = NULL; /* initialize nextopt */
9391 exitstatus = (*cmd->builtin)(argc, argv);
9392 flush_stdout_stderr();
9394 exitstatus |= ferror(stdout);
9396 commandname = savecmdname;
9397 exception_handler = savehandler;
9403 goodname(const char *p)
9405 return endofname(p)[0] == '\0';
9410 * Search for a command. This is called before we fork so that the
9411 * location of the command will be available in the parent as well as
9412 * the child. The check for "goodname" is an overly conservative
9413 * check that the name will not be subject to expansion.
9416 prehash(union node *n)
9418 struct cmdentry entry;
9420 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9421 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9425 /* ============ Builtin commands
9427 * Builtin commands whose functions are closely tied to evaluation
9428 * are implemented here.
9432 * Handle break and continue commands. Break, continue, and return are
9433 * all handled by setting the evalskip flag. The evaluation routines
9434 * above all check this flag, and if it is set they start skipping
9435 * commands rather than executing them. The variable skipcount is
9436 * the number of loops to break/continue, or the number of function
9437 * levels to return. (The latter is always 1.) It should probably
9438 * be an error to break out of more loops than exist, but it isn't
9439 * in the standard shell so we don't make it one here.
9441 static int FAST_FUNC
9442 breakcmd(int argc UNUSED_PARAM, char **argv)
9444 int n = argv[1] ? number(argv[1]) : 1;
9447 ash_msg_and_raise_error(msg_illnum, argv[1]);
9451 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9458 /* ============ input.c
9460 * This implements the input routines used by the parser.
9464 INPUT_PUSH_FILE = 1,
9465 INPUT_NOFILE_OK = 2,
9468 static smallint checkkwd;
9469 /* values of checkkwd variable */
9470 #define CHKALIAS 0x1
9475 * Push a string back onto the input at this current parsefile level.
9476 * We handle aliases this way.
9478 #if !ENABLE_ASH_ALIAS
9479 #define pushstring(s, ap) pushstring(s)
9482 pushstring(char *s, struct alias *ap)
9489 if (g_parsefile->strpush) {
9490 sp = ckzalloc(sizeof(*sp));
9491 sp->prev = g_parsefile->strpush;
9493 sp = &(g_parsefile->basestrpush);
9495 g_parsefile->strpush = sp;
9496 sp->prev_string = g_parsefile->next_to_pgetc;
9497 sp->prev_left_in_line = g_parsefile->left_in_line;
9498 #if ENABLE_ASH_ALIAS
9501 ap->flag |= ALIASINUSE;
9505 g_parsefile->next_to_pgetc = s;
9506 g_parsefile->left_in_line = len;
9513 struct strpush *sp = g_parsefile->strpush;
9516 #if ENABLE_ASH_ALIAS
9518 if (g_parsefile->next_to_pgetc[-1] == ' '
9519 || g_parsefile->next_to_pgetc[-1] == '\t'
9521 checkkwd |= CHKALIAS;
9523 if (sp->string != sp->ap->val) {
9526 sp->ap->flag &= ~ALIASINUSE;
9527 if (sp->ap->flag & ALIASDEAD) {
9528 unalias(sp->ap->name);
9532 g_parsefile->next_to_pgetc = sp->prev_string;
9533 g_parsefile->left_in_line = sp->prev_left_in_line;
9534 g_parsefile->strpush = sp->prev;
9535 if (sp != &(g_parsefile->basestrpush))
9540 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9541 //it peeks whether it is &>, and then pushes back both chars.
9542 //This function needs to save last *next_to_pgetc to buf[0]
9543 //to make two pungetc() reliable. Currently,
9544 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9549 char *buf = g_parsefile->buf;
9551 g_parsefile->next_to_pgetc = buf;
9552 #if ENABLE_FEATURE_EDITING
9554 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9555 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9557 #if ENABLE_FEATURE_TAB_COMPLETION
9558 line_input_state->path_lookup = pathval();
9560 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9562 /* Ctrl+C pressed */
9571 if (nr < 0 && errno == 0) {
9572 /* Ctrl+D pressed */
9577 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9581 /* nonblock_safe_read() handles this problem */
9583 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9584 int flags = fcntl(0, F_GETFL);
9585 if (flags >= 0 && (flags & O_NONBLOCK)) {
9586 flags &= ~O_NONBLOCK;
9587 if (fcntl(0, F_SETFL, flags) >= 0) {
9588 out2str("sh: turning off NDELAY mode\n");
9599 * Refill the input buffer and return the next input character:
9601 * 1) If a string was pushed back on the input, pop it;
9602 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9603 * or we are reading from a string so we can't refill the buffer,
9605 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9606 * 4) Process input up to the next newline, deleting nul characters.
9608 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9609 #define pgetc_debug(...) ((void)0)
9616 while (g_parsefile->strpush) {
9617 #if ENABLE_ASH_ALIAS
9618 if (g_parsefile->left_in_line == -1
9619 && g_parsefile->strpush->ap
9620 && g_parsefile->next_to_pgetc[-1] != ' '
9621 && g_parsefile->next_to_pgetc[-1] != '\t'
9623 pgetc_debug("preadbuffer PEOA");
9628 /* try "pgetc" now: */
9629 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9630 g_parsefile->left_in_line,
9631 g_parsefile->next_to_pgetc,
9632 g_parsefile->next_to_pgetc);
9633 if (--g_parsefile->left_in_line >= 0)
9634 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9636 /* on both branches above g_parsefile->left_in_line < 0.
9637 * "pgetc" needs refilling.
9640 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9641 * pungetc() may increment it a few times.
9642 * Assuming it won't increment it to less than -90.
9644 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9645 pgetc_debug("preadbuffer PEOF1");
9646 /* even in failure keep left_in_line and next_to_pgetc
9647 * in lock step, for correct multi-layer pungetc.
9648 * left_in_line was decremented before preadbuffer(),
9649 * must inc next_to_pgetc: */
9650 g_parsefile->next_to_pgetc++;
9654 more = g_parsefile->left_in_buffer;
9656 flush_stdout_stderr();
9660 /* don't try reading again */
9661 g_parsefile->left_in_line = -99;
9662 pgetc_debug("preadbuffer PEOF2");
9663 g_parsefile->next_to_pgetc++;
9668 /* Find out where's the end of line.
9669 * Set g_parsefile->left_in_line
9670 * and g_parsefile->left_in_buffer acordingly.
9671 * NUL chars are deleted.
9673 q = g_parsefile->next_to_pgetc;
9681 memmove(q, q + 1, more);
9685 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9691 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9692 if (g_parsefile->left_in_line < 0)
9697 g_parsefile->left_in_buffer = more;
9702 out2str(g_parsefile->next_to_pgetc);
9706 pgetc_debug("preadbuffer at %d:%p'%s'",
9707 g_parsefile->left_in_line,
9708 g_parsefile->next_to_pgetc,
9709 g_parsefile->next_to_pgetc);
9710 return (unsigned char)*g_parsefile->next_to_pgetc++;
9713 #define pgetc_as_macro() \
9714 (--g_parsefile->left_in_line >= 0 \
9715 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9722 pgetc_debug("pgetc_fast at %d:%p'%s'",
9723 g_parsefile->left_in_line,
9724 g_parsefile->next_to_pgetc,
9725 g_parsefile->next_to_pgetc);
9726 return pgetc_as_macro();
9729 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9730 # define pgetc_fast() pgetc()
9732 # define pgetc_fast() pgetc_as_macro()
9735 #if ENABLE_ASH_ALIAS
9737 pgetc_without_PEOA(void)
9741 pgetc_debug("pgetc_fast at %d:%p'%s'",
9742 g_parsefile->left_in_line,
9743 g_parsefile->next_to_pgetc,
9744 g_parsefile->next_to_pgetc);
9746 } while (c == PEOA);
9750 # define pgetc_without_PEOA() pgetc()
9754 * Read a line from the script.
9757 pfgets(char *line, int len)
9763 while (--nleft > 0) {
9764 c = pgetc_without_PEOA();
9779 * Undo the last call to pgetc. Only one character may be pushed back.
9780 * PEOF may be pushed back.
9785 g_parsefile->left_in_line++;
9786 g_parsefile->next_to_pgetc--;
9787 pgetc_debug("pushed back to %d:%p'%s'",
9788 g_parsefile->left_in_line,
9789 g_parsefile->next_to_pgetc,
9790 g_parsefile->next_to_pgetc);
9794 * To handle the "." command, a stack of input files is used. Pushfile
9795 * adds a new entry to the stack and popfile restores the previous level.
9800 struct parsefile *pf;
9802 pf = ckzalloc(sizeof(*pf));
9803 pf->prev = g_parsefile;
9805 /*pf->strpush = NULL; - ckzalloc did it */
9806 /*pf->basestrpush.prev = NULL;*/
9813 struct parsefile *pf = g_parsefile;
9821 g_parsefile = pf->prev;
9827 * Return to top level.
9832 while (g_parsefile != &basepf)
9837 * Close the file(s) that the shell is reading commands from. Called
9838 * after a fork is done.
9844 if (g_parsefile->pf_fd > 0) {
9845 close(g_parsefile->pf_fd);
9846 g_parsefile->pf_fd = 0;
9851 * Like setinputfile, but takes an open file descriptor. Call this with
9855 setinputfd(int fd, int push)
9857 close_on_exec_on(fd);
9860 g_parsefile->buf = NULL;
9862 g_parsefile->pf_fd = fd;
9863 if (g_parsefile->buf == NULL)
9864 g_parsefile->buf = ckmalloc(IBUFSIZ);
9865 g_parsefile->left_in_buffer = 0;
9866 g_parsefile->left_in_line = 0;
9867 g_parsefile->linno = 1;
9871 * Set the input to take input from a file. If push is set, push the
9872 * old input onto the stack first.
9875 setinputfile(const char *fname, int flags)
9881 fd = open(fname, O_RDONLY);
9883 if (flags & INPUT_NOFILE_OK)
9885 ash_msg_and_raise_error("can't open '%s'", fname);
9888 fd2 = copyfd(fd, 10);
9891 ash_msg_and_raise_error("out of file descriptors");
9894 setinputfd(fd, flags & INPUT_PUSH_FILE);
9901 * Like setinputfile, but takes input from a string.
9904 setinputstring(char *string)
9908 g_parsefile->next_to_pgetc = string;
9909 g_parsefile->left_in_line = strlen(string);
9910 g_parsefile->buf = NULL;
9911 g_parsefile->linno = 1;
9916 /* ============ mail.c
9918 * Routines to check for mail.
9923 #define MAXMBOXES 10
9925 /* times of mailboxes */
9926 static time_t mailtime[MAXMBOXES];
9927 /* Set if MAIL or MAILPATH is changed. */
9928 static smallint mail_var_path_changed;
9931 * Print appropriate message(s) if mail has arrived.
9932 * If mail_var_path_changed is set,
9933 * then the value of MAIL has mail_var_path_changed,
9934 * so we just update the values.
9943 struct stackmark smark;
9946 setstackmark(&smark);
9947 mpath = mpathset() ? mpathval() : mailval();
9948 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9949 p = path_advance(&mpath, nullstr);
9954 for (q = p; *q; q++)
9960 q[-1] = '\0'; /* delete trailing '/' */
9961 if (stat(p, &statb) < 0) {
9965 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9968 pathopt ? pathopt : "you have mail"
9971 *mtp = statb.st_mtime;
9973 mail_var_path_changed = 0;
9974 popstackmark(&smark);
9977 static void FAST_FUNC
9978 changemail(const char *val UNUSED_PARAM)
9980 mail_var_path_changed = 1;
9983 #endif /* ASH_MAIL */
9986 /* ============ ??? */
9989 * Set the shell parameters.
9992 setparam(char **argv)
9998 for (nparam = 0; argv[nparam]; nparam++)
10000 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10002 *ap++ = ckstrdup(*argv++);
10005 freeparam(&shellparam);
10006 shellparam.malloced = 1;
10007 shellparam.nparam = nparam;
10008 shellparam.p = newparam;
10009 #if ENABLE_ASH_GETOPTS
10010 shellparam.optind = 1;
10011 shellparam.optoff = -1;
10016 * Process shell options. The global variable argptr contains a pointer
10017 * to the argument list; we advance it past the options.
10019 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10020 * For a non-interactive shell, an error condition encountered
10021 * by a special built-in ... shall cause the shell to write a diagnostic message
10022 * to standard error and exit as shown in the following table:
10023 * Error Special Built-In
10025 * Utility syntax error (option or operand error) Shall exit
10027 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10028 * we see that bash does not do that (set "finishes" with error code 1 instead,
10029 * and shell continues), and people rely on this behavior!
10031 * set -o barfoo 2>/dev/null
10034 * Oh well. Let's mimic that.
10037 plus_minus_o(char *name, int val)
10042 for (i = 0; i < NOPTS; i++) {
10043 if (strcmp(name, optnames(i)) == 0) {
10048 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10051 for (i = 0; i < NOPTS; i++) {
10053 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10055 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10061 setoption(int flag, int val)
10065 for (i = 0; i < NOPTS; i++) {
10066 if (optletters(i) == flag) {
10071 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10075 options(int cmdline)
10083 while ((p = *argptr) != NULL) {
10085 if (c != '-' && c != '+')
10088 val = 0; /* val = 0 if c == '+' */
10091 if (p[0] == '\0' || LONE_DASH(p)) {
10093 /* "-" means turn off -x and -v */
10096 /* "--" means reset params */
10097 else if (*argptr == NULL)
10100 break; /* "-" or "--" terminates options */
10103 /* first char was + or - */
10104 while ((c = *p++) != '\0') {
10105 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10106 if (c == 'c' && cmdline) {
10107 minusc = p; /* command is after shell args */
10108 } else if (c == 'o') {
10109 if (plus_minus_o(*argptr, val)) {
10110 /* it already printed err message */
10111 return 1; /* error */
10115 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10117 /* bash does not accept +-login, we also won't */
10118 } else if (cmdline && val && (c == '-')) { /* long options */
10119 if (strcmp(p, "login") == 0)
10131 * The shift builtin command.
10133 static int FAST_FUNC
10134 shiftcmd(int argc UNUSED_PARAM, char **argv)
10141 n = number(argv[1]);
10142 if (n > shellparam.nparam)
10143 n = 0; /* bash compat, was = shellparam.nparam; */
10145 shellparam.nparam -= n;
10146 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10147 if (shellparam.malloced)
10150 ap2 = shellparam.p;
10151 while ((*ap2++ = *ap1++) != NULL)
10153 #if ENABLE_ASH_GETOPTS
10154 shellparam.optind = 1;
10155 shellparam.optoff = -1;
10162 * POSIX requires that 'set' (but not export or readonly) output the
10163 * variables in lexicographic order - by the locale's collating order (sigh).
10164 * Maybe we could keep them in an ordered balanced binary tree
10165 * instead of hashed lists.
10166 * For now just roll 'em through qsort for printing...
10169 showvars(const char *sep_prefix, int on, int off)
10172 char **ep, **epend;
10174 ep = listvars(on, off, &epend);
10175 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10177 sep = *sep_prefix ? " " : sep_prefix;
10179 for (; ep < epend; ep++) {
10183 p = strchrnul(*ep, '=');
10186 q = single_quote(++p);
10187 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10193 * The set command builtin.
10195 static int FAST_FUNC
10196 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10201 return showvars(nullstr, 0, VUNSET);
10204 if (!options(0)) { /* if no parse error... */
10207 if (*argptr != NULL) {
10215 #if ENABLE_ASH_RANDOM_SUPPORT
10216 static void FAST_FUNC
10217 change_random(const char *value)
10221 if (value == NULL) {
10222 /* "get", generate */
10223 t = next_random(&random_gen);
10224 /* set without recursion */
10225 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10226 vrandom.flags &= ~VNOFUNC;
10229 t = strtoul(value, NULL, 10);
10230 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10235 #if ENABLE_ASH_GETOPTS
10237 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10246 if (*param_optind < 1)
10248 optnext = optfirst + *param_optind - 1;
10250 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10253 p = optnext[-1] + *optoff;
10254 if (p == NULL || *p == '\0') {
10255 /* Current word is done, advance */
10257 if (p == NULL || *p != '-' || *++p == '\0') {
10264 if (LONE_DASH(p)) /* check for "--" */
10269 for (q = optstr; *q != c;) {
10271 if (optstr[0] == ':') {
10274 err |= setvarsafe("OPTARG", s, 0);
10276 fprintf(stderr, "Illegal option -%c\n", c);
10277 unsetvar("OPTARG");
10287 if (*p == '\0' && (p = *optnext) == NULL) {
10288 if (optstr[0] == ':') {
10291 err |= setvarsafe("OPTARG", s, 0);
10294 fprintf(stderr, "No arg for -%c option\n", c);
10295 unsetvar("OPTARG");
10303 err |= setvarsafe("OPTARG", p, 0);
10306 err |= setvarsafe("OPTARG", nullstr, 0);
10308 *optoff = p ? p - *(optnext - 1) : -1;
10309 *param_optind = optnext - optfirst + 1;
10310 fmtstr(s, sizeof(s), "%d", *param_optind);
10311 err |= setvarsafe("OPTIND", s, VNOFUNC);
10314 err |= setvarsafe(optvar, s, 0);
10318 flush_stdout_stderr();
10319 raise_exception(EXERROR);
10325 * The getopts builtin. Shellparam.optnext points to the next argument
10326 * to be processed. Shellparam.optptr points to the next character to
10327 * be processed in the current argument. If shellparam.optnext is NULL,
10328 * then it's the first time getopts has been called.
10330 static int FAST_FUNC
10331 getoptscmd(int argc, char **argv)
10336 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10338 optbase = shellparam.p;
10339 if (shellparam.optind > shellparam.nparam + 1) {
10340 shellparam.optind = 1;
10341 shellparam.optoff = -1;
10344 optbase = &argv[3];
10345 if (shellparam.optind > argc - 2) {
10346 shellparam.optind = 1;
10347 shellparam.optoff = -1;
10351 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10352 &shellparam.optoff);
10354 #endif /* ASH_GETOPTS */
10357 /* ============ Shell parser */
10360 struct heredoc *next; /* next here document in list */
10361 union node *here; /* redirection node */
10362 char *eofmark; /* string indicating end of input */
10363 smallint striptabs; /* if set, strip leading tabs */
10366 static smallint tokpushback; /* last token pushed back */
10367 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10368 static smallint quoteflag; /* set if (part of) last token was quoted */
10369 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10370 static struct heredoc *heredoclist; /* list of here documents to read */
10371 static char *wordtext; /* text of last word returned by readtoken */
10372 static struct nodelist *backquotelist;
10373 static union node *redirnode;
10374 static struct heredoc *heredoc;
10376 static const char *
10377 tokname(char *buf, int tok)
10380 return tokname_array[tok] + 1;
10381 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10385 /* raise_error_unexpected_syntax:
10386 * Called when an unexpected token is read during the parse. The argument
10387 * is the token that is expected, or -1 if more than one type of token can
10388 * occur at this point.
10390 static void raise_error_unexpected_syntax(int) NORETURN;
10392 raise_error_unexpected_syntax(int token)
10398 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10400 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10401 raise_error_syntax(msg);
10405 #define EOFMARKLEN 79
10407 /* parsing is heavily cross-recursive, need these forward decls */
10408 static union node *andor(void);
10409 static union node *pipeline(void);
10410 static union node *parse_command(void);
10411 static void parseheredoc(void);
10412 static char peektoken(void);
10413 static int readtoken(void);
10415 static union node *
10418 union node *n1, *n2, *n3;
10421 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10422 if (nlflag == 2 && peektoken())
10428 if (tok == TBACKGND) {
10429 if (n2->type == NPIPE) {
10430 n2->npipe.pipe_backgnd = 1;
10432 if (n2->type != NREDIR) {
10433 n3 = stzalloc(sizeof(struct nredir));
10435 /*n3->nredir.redirect = NULL; - stzalloc did it */
10438 n2->type = NBACKGND;
10444 n3 = stzalloc(sizeof(struct nbinary));
10446 n3->nbinary.ch1 = n1;
10447 n3->nbinary.ch2 = n2;
10463 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10471 pungetc(); /* push back EOF on input */
10475 raise_error_unexpected_syntax(-1);
10482 static union node *
10485 union node *n1, *n2, *n3;
10493 } else if (t == TOR) {
10499 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10501 n3 = stzalloc(sizeof(struct nbinary));
10503 n3->nbinary.ch1 = n1;
10504 n3->nbinary.ch2 = n2;
10509 static union node *
10512 union node *n1, *n2, *pipenode;
10513 struct nodelist *lp, *prev;
10517 TRACE(("pipeline: entered\n"));
10518 if (readtoken() == TNOT) {
10520 checkkwd = CHKKWD | CHKALIAS;
10523 n1 = parse_command();
10524 if (readtoken() == TPIPE) {
10525 pipenode = stzalloc(sizeof(struct npipe));
10526 pipenode->type = NPIPE;
10527 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10528 lp = stzalloc(sizeof(struct nodelist));
10529 pipenode->npipe.cmdlist = lp;
10533 lp = stzalloc(sizeof(struct nodelist));
10534 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10535 lp->n = parse_command();
10537 } while (readtoken() == TPIPE);
10543 n2 = stzalloc(sizeof(struct nnot));
10551 static union node *
10556 n = stzalloc(sizeof(struct narg));
10558 /*n->narg.next = NULL; - stzalloc did it */
10559 n->narg.text = wordtext;
10560 n->narg.backquote = backquotelist;
10565 fixredir(union node *n, const char *text, int err)
10569 TRACE(("Fix redir %s %d\n", text, err));
10571 n->ndup.vname = NULL;
10573 fd = bb_strtou(text, NULL, 10);
10574 if (!errno && fd >= 0)
10575 n->ndup.dupfd = fd;
10576 else if (LONE_DASH(text))
10577 n->ndup.dupfd = -1;
10580 raise_error_syntax("bad fd number");
10581 n->ndup.vname = makename();
10586 * Returns true if the text contains nothing to expand (no dollar signs
10590 noexpand(const char *text)
10594 while ((c = *text++) != '\0') {
10595 if (c == CTLQUOTEMARK)
10599 else if (SIT(c, BASESYNTAX) == CCTL)
10608 union node *n = redirnode;
10610 if (readtoken() != TWORD)
10611 raise_error_unexpected_syntax(-1);
10612 if (n->type == NHERE) {
10613 struct heredoc *here = heredoc;
10617 if (quoteflag == 0)
10619 TRACE(("Here document %d\n", n->type));
10620 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10621 raise_error_syntax("illegal eof marker for << redirection");
10622 rmescapes(wordtext, 0);
10623 here->eofmark = wordtext;
10625 if (heredoclist == NULL)
10626 heredoclist = here;
10628 for (p = heredoclist; p->next; p = p->next)
10632 } else if (n->type == NTOFD || n->type == NFROMFD) {
10633 fixredir(n, wordtext, 0);
10635 n->nfile.fname = makename();
10639 static union node *
10642 union node *args, **app;
10643 union node *n = NULL;
10644 union node *vars, **vpp;
10645 union node **rpp, *redir;
10647 #if ENABLE_ASH_BASH_COMPAT
10648 smallint double_brackets_flag = 0;
10658 savecheckkwd = CHKALIAS;
10661 checkkwd = savecheckkwd;
10664 #if ENABLE_ASH_BASH_COMPAT
10665 case TAND: /* "&&" */
10666 case TOR: /* "||" */
10667 if (!double_brackets_flag) {
10671 wordtext = (char *) (t == TAND ? "-a" : "-o");
10674 n = stzalloc(sizeof(struct narg));
10676 /*n->narg.next = NULL; - stzalloc did it */
10677 n->narg.text = wordtext;
10678 #if ENABLE_ASH_BASH_COMPAT
10679 if (strcmp("[[", wordtext) == 0)
10680 double_brackets_flag = 1;
10681 else if (strcmp("]]", wordtext) == 0)
10682 double_brackets_flag = 0;
10684 n->narg.backquote = backquotelist;
10685 if (savecheckkwd && isassignment(wordtext)) {
10687 vpp = &n->narg.next;
10690 app = &n->narg.next;
10695 *rpp = n = redirnode;
10696 rpp = &n->nfile.next;
10697 parsefname(); /* read name of redirection file */
10700 if (args && app == &args->narg.next
10703 struct builtincmd *bcmd;
10706 /* We have a function */
10707 if (readtoken() != TRP)
10708 raise_error_unexpected_syntax(TRP);
10709 name = n->narg.text;
10710 if (!goodname(name)
10711 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10713 raise_error_syntax("bad function name");
10716 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10717 n->narg.next = parse_command();
10730 n = stzalloc(sizeof(struct ncmd));
10732 n->ncmd.args = args;
10733 n->ncmd.assign = vars;
10734 n->ncmd.redirect = redir;
10738 static union node *
10739 parse_command(void)
10741 union node *n1, *n2;
10742 union node *ap, **app;
10743 union node *cp, **cpp;
10744 union node *redir, **rpp;
10751 switch (readtoken()) {
10753 raise_error_unexpected_syntax(-1);
10756 n1 = stzalloc(sizeof(struct nif));
10758 n1->nif.test = list(0);
10759 if (readtoken() != TTHEN)
10760 raise_error_unexpected_syntax(TTHEN);
10761 n1->nif.ifpart = list(0);
10763 while (readtoken() == TELIF) {
10764 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10765 n2 = n2->nif.elsepart;
10767 n2->nif.test = list(0);
10768 if (readtoken() != TTHEN)
10769 raise_error_unexpected_syntax(TTHEN);
10770 n2->nif.ifpart = list(0);
10772 if (lasttoken == TELSE)
10773 n2->nif.elsepart = list(0);
10775 n2->nif.elsepart = NULL;
10783 n1 = stzalloc(sizeof(struct nbinary));
10784 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10785 n1->nbinary.ch1 = list(0);
10788 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10789 got == TWORD ? wordtext : ""));
10790 raise_error_unexpected_syntax(TDO);
10792 n1->nbinary.ch2 = list(0);
10797 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10798 raise_error_syntax("bad for loop variable");
10799 n1 = stzalloc(sizeof(struct nfor));
10801 n1->nfor.var = wordtext;
10802 checkkwd = CHKKWD | CHKALIAS;
10803 if (readtoken() == TIN) {
10805 while (readtoken() == TWORD) {
10806 n2 = stzalloc(sizeof(struct narg));
10808 /*n2->narg.next = NULL; - stzalloc did it */
10809 n2->narg.text = wordtext;
10810 n2->narg.backquote = backquotelist;
10812 app = &n2->narg.next;
10815 n1->nfor.args = ap;
10816 if (lasttoken != TNL && lasttoken != TSEMI)
10817 raise_error_unexpected_syntax(-1);
10819 n2 = stzalloc(sizeof(struct narg));
10821 /*n2->narg.next = NULL; - stzalloc did it */
10822 n2->narg.text = (char *)dolatstr;
10823 /*n2->narg.backquote = NULL;*/
10824 n1->nfor.args = n2;
10826 * Newline or semicolon here is optional (but note
10827 * that the original Bourne shell only allowed NL).
10829 if (lasttoken != TNL && lasttoken != TSEMI)
10832 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10833 if (readtoken() != TDO)
10834 raise_error_unexpected_syntax(TDO);
10835 n1->nfor.body = list(0);
10839 n1 = stzalloc(sizeof(struct ncase));
10841 if (readtoken() != TWORD)
10842 raise_error_unexpected_syntax(TWORD);
10843 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10845 /*n2->narg.next = NULL; - stzalloc did it */
10846 n2->narg.text = wordtext;
10847 n2->narg.backquote = backquotelist;
10849 checkkwd = CHKKWD | CHKALIAS;
10850 } while (readtoken() == TNL);
10851 if (lasttoken != TIN)
10852 raise_error_unexpected_syntax(TIN);
10853 cpp = &n1->ncase.cases;
10855 checkkwd = CHKNL | CHKKWD;
10857 while (t != TESAC) {
10858 if (lasttoken == TLP)
10860 *cpp = cp = stzalloc(sizeof(struct nclist));
10862 app = &cp->nclist.pattern;
10864 *app = ap = stzalloc(sizeof(struct narg));
10866 /*ap->narg.next = NULL; - stzalloc did it */
10867 ap->narg.text = wordtext;
10868 ap->narg.backquote = backquotelist;
10869 if (readtoken() != TPIPE)
10871 app = &ap->narg.next;
10874 //ap->narg.next = NULL;
10875 if (lasttoken != TRP)
10876 raise_error_unexpected_syntax(TRP);
10877 cp->nclist.body = list(2);
10879 cpp = &cp->nclist.next;
10881 checkkwd = CHKNL | CHKKWD;
10885 raise_error_unexpected_syntax(TENDCASE);
10892 n1 = stzalloc(sizeof(struct nredir));
10893 n1->type = NSUBSHELL;
10894 n1->nredir.n = list(0);
10895 /*n1->nredir.redirect = NULL; - stzalloc did it */
10905 return simplecmd();
10908 if (readtoken() != t)
10909 raise_error_unexpected_syntax(t);
10912 /* Now check for redirection which may follow command */
10913 checkkwd = CHKKWD | CHKALIAS;
10915 while (readtoken() == TREDIR) {
10916 *rpp = n2 = redirnode;
10917 rpp = &n2->nfile.next;
10923 if (n1->type != NSUBSHELL) {
10924 n2 = stzalloc(sizeof(struct nredir));
10929 n1->nredir.redirect = redir;
10934 #if ENABLE_ASH_BASH_COMPAT
10935 static int decode_dollar_squote(void)
10937 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10943 p = strchr(C_escapes, c);
10948 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10952 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10954 } else if (c == 'x') { /* \xHH */
10958 } while (isxdigit(c) && --cnt);
10960 if (cnt == 3) { /* \x but next char is "bad" */
10964 } else { /* simple seq like \\ or \t */
10969 c = bb_process_escape_sequence((void*)&p);
10970 } else { /* unrecognized "\z": print both chars unless ' or " */
10971 if (c != '\'' && c != '"') {
10973 c |= 0x100; /* "please encode \, then me" */
10981 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10982 * is not NULL, read a here document. In the latter case, eofmark is the
10983 * word which marks the end of the document and striptabs is true if
10984 * leading tabs should be stripped from the document. The argument c
10985 * is the first character of the input token or document.
10987 * Because C does not have internal subroutines, I have simulated them
10988 * using goto's to implement the subroutine linkage. The following macros
10989 * will run code that appears at the end of readtoken1.
10991 #define CHECKEND() {goto checkend; checkend_return:;}
10992 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10993 #define PARSESUB() {goto parsesub; parsesub_return:;}
10994 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10995 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10996 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10998 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11000 /* NB: syntax parameter fits into smallint */
11001 /* c parameter is an unsigned char or PEOF or PEOA */
11004 char line[EOFMARKLEN + 1];
11005 struct nodelist *bqlist;
11009 smallint prevsyntax; /* syntax before arithmetic */
11010 #if ENABLE_ASH_EXPAND_PRMT
11011 smallint pssyntax; /* we are expanding a prompt string */
11013 int varnest; /* levels of variables expansion */
11014 int arinest; /* levels of arithmetic expansion */
11015 int parenlevel; /* levels of parens in arithmetic */
11016 int dqvarnest; /* levels of variables expansion within double quotes */
11018 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11021 /* Avoid longjmp clobbering */
11027 (void) &parenlevel;
11030 (void) &prevsyntax;
11033 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 */
11051 CHECKEND(); /* set c to PEOF if at end of here document */
11052 for (;;) { /* until end of line or end of word */
11053 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11054 switch (SIT(c, syntax)) {
11055 case CNL: /* '\n' */
11056 if (syntax == BASESYNTAX)
11057 goto endword; /* exit outer loop */
11059 g_parsefile->linno++;
11060 setprompt_if(doprompt, 2);
11062 goto loop; /* continue outer loop */
11067 if (eofmark == NULL || dblquote)
11068 USTPUTC(CTLESC, out);
11069 #if ENABLE_ASH_BASH_COMPAT
11070 if (c == '\\' && bash_dollar_squote) {
11071 c = decode_dollar_squote();
11073 USTPUTC('\\', out);
11074 c = (unsigned char)c;
11080 case CBACK: /* backslash */
11081 c = pgetc_without_PEOA();
11083 USTPUTC(CTLESC, out);
11084 USTPUTC('\\', out);
11086 } else if (c == '\n') {
11087 setprompt_if(doprompt, 2);
11089 #if ENABLE_ASH_EXPAND_PRMT
11090 if (c == '$' && pssyntax) {
11091 USTPUTC(CTLESC, out);
11092 USTPUTC('\\', out);
11095 /* Backslash is retained if we are in "str" and next char isn't special */
11100 && (c != '"' || eofmark != NULL)
11102 USTPUTC(CTLESC, out);
11103 USTPUTC('\\', out);
11105 if (SIT(c, SQSYNTAX) == CCTL)
11106 USTPUTC(CTLESC, out);
11114 if (eofmark == NULL) {
11115 USTPUTC(CTLQUOTEMARK, out);
11123 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11124 if (eofmark != NULL && arinest == 0
11129 if (dqvarnest == 0) {
11130 syntax = BASESYNTAX;
11137 case CVAR: /* '$' */
11138 PARSESUB(); /* parse substitution */
11140 case CENDVAR: /* '}' */
11143 if (dqvarnest > 0) {
11150 #if ENABLE_SH_MATH_SUPPORT
11151 case CLP: /* '(' in arithmetic */
11155 case CRP: /* ')' in arithmetic */
11156 if (parenlevel > 0) {
11159 if (pgetc() == ')') {
11160 if (--arinest == 0) {
11161 syntax = prevsyntax;
11162 dblquote = (syntax == DQSYNTAX);
11167 * unbalanced parens
11168 * (don't 2nd guess - no error)
11176 case CBQUOTE: /* '`' */
11180 goto endword; /* exit outer loop */
11184 if (varnest == 0) {
11185 #if ENABLE_ASH_BASH_COMPAT
11187 if (pgetc() == '>')
11188 c = 0x100 + '>'; /* flag &> */
11192 goto endword; /* exit outer loop */
11194 IF_ASH_ALIAS(if (c != PEOA))
11201 #if ENABLE_SH_MATH_SUPPORT
11202 if (syntax == ARISYNTAX)
11203 raise_error_syntax("missing '))'");
11205 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11206 raise_error_syntax("unterminated quoted string");
11207 if (varnest != 0) {
11208 startlinno = g_parsefile->linno;
11210 raise_error_syntax("missing '}'");
11212 USTPUTC('\0', out);
11213 len = out - (char *)stackblock();
11214 out = stackblock();
11215 if (eofmark == NULL) {
11216 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11219 if (isdigit_str9(out)) {
11220 PARSEREDIR(); /* passed as params: out, c */
11221 lasttoken = TREDIR;
11224 /* else: non-number X seen, interpret it
11225 * as "NNNX>file" = "NNNX >file" */
11229 quoteflag = quotef;
11230 backquotelist = bqlist;
11231 grabstackblock(len);
11235 /* end of readtoken routine */
11238 * Check to see whether we are at the end of the here document. When this
11239 * is called, c is set to the first character of the next input line. If
11240 * we are at the end of the here document, this routine sets the c to PEOF.
11244 #if ENABLE_ASH_ALIAS
11246 c = pgetc_without_PEOA();
11249 while (c == '\t') {
11250 c = pgetc_without_PEOA();
11253 if (c == *eofmark) {
11254 if (pfgets(line, sizeof(line)) != NULL) {
11258 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11260 if (*p == '\n' && *q == '\0') {
11262 g_parsefile->linno++;
11263 needprompt = doprompt;
11265 pushstring(line, NULL);
11270 goto checkend_return;
11274 * Parse a redirection operator. The variable "out" points to a string
11275 * specifying the fd to be redirected. The variable "c" contains the
11276 * first character of the redirection operator.
11279 /* out is already checked to be a valid number or "" */
11280 int fd = (*out == '\0' ? -1 : atoi(out));
11283 np = stzalloc(sizeof(struct nfile));
11288 np->type = NAPPEND;
11290 np->type = NCLOBBER;
11293 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11299 #if ENABLE_ASH_BASH_COMPAT
11300 else if (c == 0x100 + '>') { /* this flags &> redirection */
11302 pgetc(); /* this is '>', no need to check */
11306 else { /* c == '<' */
11307 /*np->nfile.fd = 0; - stzalloc did it */
11311 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11312 np = stzalloc(sizeof(struct nhere));
11313 /*np->nfile.fd = 0; - stzalloc did it */
11316 heredoc = stzalloc(sizeof(struct heredoc));
11317 heredoc->here = np;
11320 heredoc->striptabs = 1;
11322 /*heredoc->striptabs = 0; - stzalloc did it */
11328 np->type = NFROMFD;
11332 np->type = NFROMTO;
11344 goto parseredir_return;
11348 * Parse a substitution. At this point, we have read the dollar sign
11349 * and nothing else.
11352 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11353 * (assuming ascii char codes, as the original implementation did) */
11354 #define is_special(c) \
11355 (((unsigned)(c) - 33 < 32) \
11356 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11358 unsigned char subtype;
11363 if (c > 255 /* PEOA or PEOF */
11364 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11366 #if ENABLE_ASH_BASH_COMPAT
11368 bash_dollar_squote = 1;
11373 } else if (c == '(') {
11374 /* $(command) or $((arith)) */
11375 if (pgetc() == '(') {
11376 #if ENABLE_SH_MATH_SUPPORT
11379 raise_error_syntax("you disabled math support for $((arith)) syntax");
11386 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11387 USTPUTC(CTLVAR, out);
11388 typeloc = out - (char *)stackblock();
11389 USTPUTC(VSNORMAL, out);
11390 subtype = VSNORMAL;
11396 c = '#'; /* ${#} - same as $# */
11398 subtype = VSLENGTH; /* ${#VAR} */
11403 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11404 /* $[{[#]]NAME[}] */
11408 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11409 } else if (isdigit(c)) {
11410 /* $[{[#]]NUM[}] */
11414 } while (isdigit(c));
11415 } else if (is_special(c)) {
11416 /* $[{[#]]<specialchar>[}] */
11421 raise_error_syntax("bad substitution");
11423 if (c != '}' && subtype == VSLENGTH) {
11424 /* ${#VAR didn't end with } */
11430 if (subtype == 0) {
11431 /* ${VAR...} but not $VAR or ${#VAR} */
11432 /* c == first char after VAR */
11436 #if ENABLE_ASH_BASH_COMPAT
11437 if (c == ':' || c == '$' || isdigit(c)) {
11438 //TODO: support more general format ${v:EXPR:EXPR},
11439 // where EXPR follows $(()) rules
11440 subtype = VSSUBSTR;
11442 break; /* "goto do_pungetc" is bigger (!) */
11448 static const char types[] ALIGN1 = "}-+?=";
11449 const char *p = strchr(types, c);
11452 subtype = p - types + VSNORMAL;
11458 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11465 #if ENABLE_ASH_BASH_COMPAT
11467 /* ${v/[/]pattern/repl} */
11468 //TODO: encode pattern and repl separately.
11469 // Currently ${v/$var_with_slash/repl} is horribly broken
11470 subtype = VSREPLACE;
11474 subtype++; /* VSREPLACEALL */
11482 if (dblquote || arinest)
11484 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11485 if (subtype != VSNORMAL) {
11487 if (dblquote || arinest) {
11492 goto parsesub_return;
11496 * Called to parse command substitutions. Newstyle is set if the command
11497 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11498 * list of commands (passed by reference), and savelen is the number of
11499 * characters on the top of the stack which must be preserved.
11502 struct nodelist **nlpp;
11505 char *volatile str;
11506 struct jmploc jmploc;
11507 struct jmploc *volatile savehandler;
11509 smallint saveprompt = 0;
11512 (void) &saveprompt;
11514 savepbq = parsebackquote;
11515 if (setjmp(jmploc.loc)) {
11517 parsebackquote = 0;
11518 exception_handler = savehandler;
11519 longjmp(exception_handler->loc, 1);
11523 savelen = out - (char *)stackblock();
11525 str = ckmalloc(savelen);
11526 memcpy(str, stackblock(), savelen);
11528 savehandler = exception_handler;
11529 exception_handler = &jmploc;
11532 /* We must read until the closing backquote, giving special
11533 treatment to some slashes, and then push the string and
11534 reread it as input, interpreting it normally. */
11539 STARTSTACKSTR(pout);
11543 setprompt_if(needprompt, 2);
11552 g_parsefile->linno++;
11553 setprompt_if(doprompt, 2);
11555 * If eating a newline, avoid putting
11556 * the newline into the new character
11557 * stream (via the STPUTC after the
11562 if (pc != '\\' && pc != '`' && pc != '$'
11563 && (!dblquote || pc != '"')
11565 STPUTC('\\', pout);
11567 if (pc <= 255 /* not PEOA or PEOF */) {
11573 IF_ASH_ALIAS(case PEOA:)
11574 startlinno = g_parsefile->linno;
11575 raise_error_syntax("EOF in backquote substitution");
11578 g_parsefile->linno++;
11579 needprompt = doprompt;
11588 STPUTC('\0', pout);
11589 psavelen = pout - (char *)stackblock();
11590 if (psavelen > 0) {
11591 pstr = grabstackstr(pout);
11592 setinputstring(pstr);
11597 nlpp = &(*nlpp)->next;
11598 *nlpp = stzalloc(sizeof(**nlpp));
11599 /* (*nlpp)->next = NULL; - stzalloc did it */
11600 parsebackquote = oldstyle;
11603 saveprompt = doprompt;
11610 doprompt = saveprompt;
11611 else if (readtoken() != TRP)
11612 raise_error_unexpected_syntax(TRP);
11617 * Start reading from old file again, ignoring any pushed back
11618 * tokens left from the backquote parsing
11623 while (stackblocksize() <= savelen)
11625 STARTSTACKSTR(out);
11627 memcpy(out, str, savelen);
11628 STADJUST(savelen, out);
11634 parsebackquote = savepbq;
11635 exception_handler = savehandler;
11636 if (arinest || dblquote)
11637 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11639 USTPUTC(CTLBACKQ, out);
11641 goto parsebackq_oldreturn;
11642 goto parsebackq_newreturn;
11645 #if ENABLE_SH_MATH_SUPPORT
11647 * Parse an arithmetic expansion (indicate start of one and set state)
11650 if (++arinest == 1) {
11651 prevsyntax = syntax;
11652 syntax = ARISYNTAX;
11653 USTPUTC(CTLARI, out);
11660 * we collapse embedded arithmetic expansion to
11661 * parenthesis, which should be equivalent
11665 goto parsearith_return;
11669 } /* end of readtoken */
11672 * Read the next input token.
11673 * If the token is a word, we set backquotelist to the list of cmds in
11674 * backquotes. We set quoteflag to true if any part of the word was
11676 * If the token is TREDIR, then we set redirnode to a structure containing
11678 * In all cases, the variable startlinno is set to the number of the line
11679 * on which the token starts.
11681 * [Change comment: here documents and internal procedures]
11682 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11683 * word parsing code into a separate routine. In this case, readtoken
11684 * doesn't need to have any internal procedures, but parseword does.
11685 * We could also make parseoperator in essence the main routine, and
11686 * have parseword (readtoken1?) handle both words and redirection.]
11688 #define NEW_xxreadtoken
11689 #ifdef NEW_xxreadtoken
11690 /* singles must be first! */
11691 static const char xxreadtoken_chars[7] ALIGN1 = {
11692 '\n', '(', ')', /* singles */
11693 '&', '|', ';', /* doubles */
11697 #define xxreadtoken_singles 3
11698 #define xxreadtoken_doubles 3
11700 static const char xxreadtoken_tokens[] ALIGN1 = {
11701 TNL, TLP, TRP, /* only single occurrence allowed */
11702 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11703 TEOF, /* corresponds to trailing nul */
11704 TAND, TOR, TENDCASE /* if double occurrence */
11716 setprompt_if(needprompt, 2);
11717 startlinno = g_parsefile->linno;
11718 for (;;) { /* until token or start of word found */
11720 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11724 while ((c = pgetc()) != '\n' && c != PEOF)
11727 } else if (c == '\\') {
11728 if (pgetc() != '\n') {
11730 break; /* return readtoken1(...) */
11732 startlinno = ++g_parsefile->linno;
11733 setprompt_if(doprompt, 2);
11737 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11740 g_parsefile->linno++;
11741 needprompt = doprompt;
11744 p = strchr(xxreadtoken_chars, c);
11746 break; /* return readtoken1(...) */
11748 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11750 if (cc == c) { /* double occurrence? */
11751 p += xxreadtoken_doubles + 1;
11754 #if ENABLE_ASH_BASH_COMPAT
11755 if (c == '&' && cc == '>') /* &> */
11756 break; /* return readtoken1(...) */
11761 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11766 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11768 #else /* old xxreadtoken */
11769 #define RETURN(token) return lasttoken = token
11779 setprompt_if(needprompt, 2);
11780 startlinno = g_parsefile->linno;
11781 for (;;) { /* until token or start of word found */
11784 case ' ': case '\t':
11785 IF_ASH_ALIAS(case PEOA:)
11788 while ((c = pgetc()) != '\n' && c != PEOF)
11793 if (pgetc() == '\n') {
11794 startlinno = ++g_parsefile->linno;
11795 setprompt_if(doprompt, 2);
11801 g_parsefile->linno++;
11802 needprompt = doprompt;
11807 if (pgetc() == '&')
11812 if (pgetc() == '|')
11817 if (pgetc() == ';')
11830 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11833 #endif /* old xxreadtoken */
11840 smallint alreadyseen = tokpushback;
11843 #if ENABLE_ASH_ALIAS
11852 if (checkkwd & CHKNL) {
11859 if (t != TWORD || quoteflag) {
11864 * check for keywords
11866 if (checkkwd & CHKKWD) {
11867 const char *const *pp;
11869 pp = findkwd(wordtext);
11871 lasttoken = t = pp - tokname_array;
11872 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11877 if (checkkwd & CHKALIAS) {
11878 #if ENABLE_ASH_ALIAS
11880 ap = lookupalias(wordtext, 1);
11883 pushstring(ap->val, ap);
11893 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11895 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11907 return tokname_array[t][0];
11911 * Read and parse a command. Returns NODE_EOF on end of file.
11912 * (NULL is a valid parse tree indicating a blank line.)
11914 static union node *
11915 parsecmd(int interact)
11920 doprompt = interact;
11921 setprompt_if(doprompt, doprompt);
11933 * Input any here documents.
11938 struct heredoc *here;
11941 here = heredoclist;
11942 heredoclist = NULL;
11945 setprompt_if(needprompt, 2);
11946 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
11947 here->eofmark, here->striptabs);
11948 n = stzalloc(sizeof(struct narg));
11949 n->narg.type = NARG;
11950 /*n->narg.next = NULL; - stzalloc did it */
11951 n->narg.text = wordtext;
11952 n->narg.backquote = backquotelist;
11953 here->here->nhere.doc = n;
11960 * called by editline -- any expansions to the prompt should be added here.
11962 #if ENABLE_ASH_EXPAND_PRMT
11963 static const char *
11964 expandstr(const char *ps)
11968 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11969 * and token processing _can_ alter it (delete NULs etc). */
11970 setinputstring((char *)ps);
11971 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11974 n.narg.type = NARG;
11975 n.narg.next = NULL;
11976 n.narg.text = wordtext;
11977 n.narg.backquote = backquotelist;
11979 expandarg(&n, NULL, 0);
11980 return stackblock();
11985 * Execute a command or commands contained in a string.
11988 evalstring(char *s, int mask)
11991 struct stackmark smark;
11995 setstackmark(&smark);
11998 while ((n = parsecmd(0)) != NODE_EOF) {
12000 popstackmark(&smark);
12013 * The eval command.
12015 static int FAST_FUNC
12016 evalcmd(int argc UNUSED_PARAM, char **argv)
12025 STARTSTACKSTR(concat);
12027 concat = stack_putstr(p, concat);
12031 STPUTC(' ', concat);
12033 STPUTC('\0', concat);
12034 p = grabstackstr(concat);
12036 evalstring(p, ~SKIPEVAL);
12042 * Read and execute commands.
12043 * "Top" is nonzero for the top level command loop;
12044 * it turns on prompting if the shell is interactive.
12050 struct stackmark smark;
12054 TRACE(("cmdloop(%d) called\n", top));
12058 setstackmark(&smark);
12061 showjobs(stderr, SHOW_CHANGED);
12064 if (iflag && top) {
12066 #if ENABLE_ASH_MAIL
12070 n = parsecmd(inter);
12072 if (DEBUG > 2 && debug && (n != NODE_EOF))
12075 if (n == NODE_EOF) {
12076 if (!top || numeof >= 50)
12078 if (!stoppedjobs()) {
12081 out2str("\nUse \"exit\" to leave shell.\n");
12084 } else if (nflag == 0) {
12085 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12090 popstackmark(&smark);
12095 return skip & SKIPEVAL;
12102 * Take commands from a file. To be compatible we should do a path
12103 * search for the file, which is necessary to find sub-commands.
12106 find_dot_file(char *name)
12109 const char *path = pathval();
12112 /* don't try this for absolute or relative paths */
12113 if (strchr(name, '/'))
12116 /* IIRC standards do not say whether . is to be searched.
12117 * And it is even smaller this way, making it unconditional for now:
12119 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12124 while ((fullname = path_advance(&path, name)) != NULL) {
12126 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12128 * Don't bother freeing here, since it will
12129 * be freed by the caller.
12133 if (fullname != name)
12134 stunalloc(fullname);
12137 /* not found in the PATH */
12138 ash_msg_and_raise_error("%s: not found", name);
12142 static int FAST_FUNC
12143 dotcmd(int argc, char **argv)
12146 struct strlist *sp;
12147 volatile struct shparam saveparam;
12149 for (sp = cmdenviron; sp; sp = sp->next)
12150 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12153 /* bash says: "bash: .: filename argument required" */
12154 return 2; /* bash compat */
12157 /* "false; . empty_file; echo $?" should print 0, not 1: */
12160 fullname = find_dot_file(argv[1]);
12164 if (argc) { /* argc > 0, argv[0] != NULL */
12165 saveparam = shellparam;
12166 shellparam.malloced = 0;
12167 shellparam.nparam = argc;
12168 shellparam.p = argv;
12171 setinputfile(fullname, INPUT_PUSH_FILE);
12172 commandname = fullname;
12177 freeparam(&shellparam);
12178 shellparam = saveparam;
12184 static int FAST_FUNC
12185 exitcmd(int argc UNUSED_PARAM, char **argv)
12190 exitstatus = number(argv[1]);
12191 raise_exception(EXEXIT);
12196 * Read a file containing shell functions.
12199 readcmdfile(char *name)
12201 setinputfile(name, INPUT_PUSH_FILE);
12207 /* ============ find_command inplementation */
12210 * Resolve a command name. If you change this routine, you may have to
12211 * change the shellexec routine as well.
12214 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12216 struct tblentry *cmdp;
12223 struct builtincmd *bcmd;
12225 /* If name contains a slash, don't use PATH or hash table */
12226 if (strchr(name, '/') != NULL) {
12227 entry->u.index = -1;
12228 if (act & DO_ABS) {
12229 while (stat(name, &statb) < 0) {
12231 if (errno == EINTR)
12234 entry->cmdtype = CMDUNKNOWN;
12238 entry->cmdtype = CMDNORMAL;
12242 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12244 updatetbl = (path == pathval());
12247 if (strstr(path, "%builtin") != NULL)
12248 act |= DO_ALTBLTIN;
12251 /* If name is in the table, check answer will be ok */
12252 cmdp = cmdlookup(name, 0);
12253 if (cmdp != NULL) {
12256 switch (cmdp->cmdtype) {
12274 } else if (cmdp->rehash == 0)
12275 /* if not invalidated by cd, we're done */
12279 /* If %builtin not in path, check for builtin next */
12280 bcmd = find_builtin(name);
12282 if (IS_BUILTIN_REGULAR(bcmd))
12283 goto builtin_success;
12284 if (act & DO_ALTPATH) {
12285 if (!(act & DO_ALTBLTIN))
12286 goto builtin_success;
12287 } else if (builtinloc <= 0) {
12288 goto builtin_success;
12292 #if ENABLE_FEATURE_SH_STANDALONE
12294 int applet_no = find_applet_by_name(name);
12295 if (applet_no >= 0) {
12296 entry->cmdtype = CMDNORMAL;
12297 entry->u.index = -2 - applet_no;
12303 /* We have to search path. */
12304 prev = -1; /* where to start */
12305 if (cmdp && cmdp->rehash) { /* doing a rehash */
12306 if (cmdp->cmdtype == CMDBUILTIN)
12309 prev = cmdp->param.index;
12315 while ((fullname = path_advance(&path, name)) != NULL) {
12316 stunalloc(fullname);
12317 /* NB: code below will still use fullname
12318 * despite it being "unallocated" */
12321 if (prefix(pathopt, "builtin")) {
12323 goto builtin_success;
12326 if ((act & DO_NOFUNC)
12327 || !prefix(pathopt, "func")
12328 ) { /* ignore unimplemented options */
12332 /* if rehash, don't redo absolute path names */
12333 if (fullname[0] == '/' && idx <= prev) {
12336 TRACE(("searchexec \"%s\": no change\n", name));
12339 while (stat(fullname, &statb) < 0) {
12341 if (errno == EINTR)
12344 if (errno != ENOENT && errno != ENOTDIR)
12348 e = EACCES; /* if we fail, this will be the error */
12349 if (!S_ISREG(statb.st_mode))
12351 if (pathopt) { /* this is a %func directory */
12352 stalloc(strlen(fullname) + 1);
12353 /* NB: stalloc will return space pointed by fullname
12354 * (because we don't have any intervening allocations
12355 * between stunalloc above and this stalloc) */
12356 readcmdfile(fullname);
12357 cmdp = cmdlookup(name, 0);
12358 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12359 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12360 stunalloc(fullname);
12363 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12365 entry->cmdtype = CMDNORMAL;
12366 entry->u.index = idx;
12370 cmdp = cmdlookup(name, 1);
12371 cmdp->cmdtype = CMDNORMAL;
12372 cmdp->param.index = idx;
12377 /* We failed. If there was an entry for this command, delete it */
12378 if (cmdp && updatetbl)
12379 delete_cmd_entry();
12381 ash_msg("%s: %s", name, errmsg(e, "not found"));
12382 entry->cmdtype = CMDUNKNOWN;
12387 entry->cmdtype = CMDBUILTIN;
12388 entry->u.cmd = bcmd;
12392 cmdp = cmdlookup(name, 1);
12393 cmdp->cmdtype = CMDBUILTIN;
12394 cmdp->param.cmd = bcmd;
12398 entry->cmdtype = cmdp->cmdtype;
12399 entry->u = cmdp->param;
12403 /* ============ trap.c */
12406 * The trap builtin.
12408 static int FAST_FUNC
12409 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12413 int signo, exitcode;
12418 for (signo = 0; signo < NSIG; signo++) {
12419 char *tr = trap_ptr[signo];
12421 /* note: bash adds "SIG", but only if invoked
12422 * as "bash". If called as "sh", or if set -o posix,
12423 * then it prints short signal names.
12424 * We are printing short names: */
12425 out1fmt("trap -- %s %s\n",
12427 get_signame(signo));
12428 /* trap_ptr != trap only if we are in special-cased `trap` code.
12429 * In this case, we will exit very soon, no need to free(). */
12430 /* if (trap_ptr != trap && tp[0]) */
12435 if (trap_ptr != trap) {
12448 signo = get_signum(*ap);
12450 /* Mimic bash message exactly */
12451 ash_msg("%s: invalid signal specification", *ap);
12457 if (LONE_DASH(action))
12460 action = ckstrdup(action);
12464 may_have_traps = 1;
12465 trap[signo] = action;
12476 /* ============ Builtins */
12478 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12480 * Lists available builtins
12482 static int FAST_FUNC
12483 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12489 "Built-in commands:\n"
12490 "------------------\n");
12491 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12492 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12493 builtintab[i].name + 1);
12499 #if ENABLE_FEATURE_SH_STANDALONE
12501 const char *a = applet_names;
12503 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12508 a += strlen(a) + 1;
12513 return EXIT_SUCCESS;
12515 #endif /* FEATURE_SH_EXTRA_QUIET */
12518 * The export and readonly commands.
12520 static int FAST_FUNC
12521 exportcmd(int argc UNUSED_PARAM, char **argv)
12527 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12529 if (nextopt("p") != 'p') {
12534 p = strchr(name, '=');
12538 vp = *findvar(hashvar(name), name);
12544 setvar(name, p, flag);
12545 } while ((name = *++aptr) != NULL);
12549 showvars(argv[0], flag, 0);
12554 * Delete a function if it exists.
12557 unsetfunc(const char *name)
12559 struct tblentry *cmdp;
12561 cmdp = cmdlookup(name, 0);
12562 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12563 delete_cmd_entry();
12567 * The unset builtin command. We unset the function before we unset the
12568 * variable to allow a function to be unset when there is a readonly variable
12569 * with the same name.
12571 static int FAST_FUNC
12572 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12579 while ((i = nextopt("vf")) != 0) {
12583 for (ap = argptr; *ap; ap++) {
12596 static const unsigned char timescmd_str[] ALIGN1 = {
12597 ' ', offsetof(struct tms, tms_utime),
12598 '\n', offsetof(struct tms, tms_stime),
12599 ' ', offsetof(struct tms, tms_cutime),
12600 '\n', offsetof(struct tms, tms_cstime),
12603 static int FAST_FUNC
12604 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12606 unsigned long clk_tck, s, t;
12607 const unsigned char *p;
12610 clk_tck = sysconf(_SC_CLK_TCK);
12615 t = *(clock_t *)(((char *) &buf) + p[1]);
12618 out1fmt("%lum%lu.%03lus%c",
12620 (t * 1000) / clk_tck,
12628 #if ENABLE_SH_MATH_SUPPORT
12630 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12631 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12633 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12635 static int FAST_FUNC
12636 letcmd(int argc UNUSED_PARAM, char **argv)
12642 ash_msg_and_raise_error("expression expected");
12644 i = ash_arith(*argv);
12652 * The read builtin. Options:
12653 * -r Do not interpret '\' specially
12654 * -s Turn off echo (tty only)
12655 * -n NCHARS Read NCHARS max
12656 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12657 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12658 * -u FD Read from given FD instead of fd 0
12659 * This uses unbuffered input, which may be avoidable in some cases.
12660 * TODO: bash also has:
12661 * -a ARRAY Read into array[0],[1],etc
12662 * -d DELIM End on DELIM char, not newline
12663 * -e Use line editing (tty only)
12665 static int FAST_FUNC
12666 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12668 char *opt_n = NULL;
12669 char *opt_p = NULL;
12670 char *opt_t = NULL;
12671 char *opt_u = NULL;
12672 int read_flags = 0;
12676 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12685 read_flags |= BUILTIN_READ_SILENT;
12691 read_flags |= BUILTIN_READ_RAW;
12701 r = shell_builtin_read(setvar2,
12703 bltinlookup("IFS"), /* can be NULL */
12711 if ((uintptr_t)r > 1)
12712 ash_msg_and_raise_error(r);
12714 return (uintptr_t)r;
12717 static int FAST_FUNC
12718 umaskcmd(int argc UNUSED_PARAM, char **argv)
12720 static const char permuser[3] ALIGN1 = "ugo";
12721 static const char permmode[3] ALIGN1 = "rwx";
12722 static const short permmask[] ALIGN2 = {
12723 S_IRUSR, S_IWUSR, S_IXUSR,
12724 S_IRGRP, S_IWGRP, S_IXGRP,
12725 S_IROTH, S_IWOTH, S_IXOTH
12728 /* TODO: use bb_parse_mode() instead */
12733 int symbolic_mode = 0;
12735 while (nextopt("S") != '\0') {
12746 if (symbolic_mode) {
12750 for (i = 0; i < 3; i++) {
12753 *p++ = permuser[i];
12755 for (j = 0; j < 3; j++) {
12756 if ((mask & permmask[3 * i + j]) == 0) {
12757 *p++ = permmode[j];
12765 out1fmt("%.4o\n", mask);
12768 if (isdigit((unsigned char) *ap)) {
12771 if (*ap >= '8' || *ap < '0')
12772 ash_msg_and_raise_error(msg_illnum, argv[1]);
12773 mask = (mask << 3) + (*ap - '0');
12774 } while (*++ap != '\0');
12777 mask = ~mask & 0777;
12778 if (!bb_parse_mode(ap, &mask)) {
12779 ash_msg_and_raise_error("illegal mode: %s", ap);
12781 umask(~mask & 0777);
12787 static int FAST_FUNC
12788 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12790 return shell_builtin_ulimit(argv);
12793 /* ============ main() and helpers */
12796 * Called to exit the shell.
12798 static void exitshell(void) NORETURN;
12806 status = exitstatus;
12807 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12808 if (setjmp(loc.loc)) {
12809 if (exception_type == EXEXIT)
12810 /* dash bug: it just does _exit(exitstatus) here
12811 * but we have to do setjobctl(0) first!
12812 * (bug is still not fixed in dash-0.5.3 - if you run dash
12813 * under Midnight Commander, on exit from dash MC is backgrounded) */
12814 status = exitstatus;
12817 exception_handler = &loc;
12824 flush_stdout_stderr();
12834 /* from input.c: */
12835 /* we will never free this */
12836 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12839 signal(SIGCHLD, SIG_DFL);
12840 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12841 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12843 signal(SIGHUP, SIG_DFL);
12849 struct stat st1, st2;
12852 for (envp = environ; envp && *envp; envp++) {
12853 if (strchr(*envp, '=')) {
12854 setvareq(*envp, VEXPORT|VTEXTFIXED);
12858 setvar("PPID", utoa(getppid()), 0);
12860 p = lookupvar("PWD");
12862 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12863 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12870 * Process the shell command line arguments.
12873 procargs(char **argv)
12876 const char *xminusc;
12881 /* if (xargv[0]) - mmm, this is always true! */
12883 for (i = 0; i < NOPTS; i++)
12887 /* it already printed err message */
12888 raise_exception(EXERROR);
12892 if (*xargv == NULL) {
12894 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12897 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12901 for (i = 0; i < NOPTS; i++)
12902 if (optlist[i] == 2)
12907 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12912 } else if (!sflag) {
12913 setinputfile(*xargv, 0);
12916 commandname = arg0;
12919 shellparam.p = xargv;
12920 #if ENABLE_ASH_GETOPTS
12921 shellparam.optind = 1;
12922 shellparam.optoff = -1;
12924 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12926 shellparam.nparam++;
12933 * Read /etc/profile or .profile.
12936 read_profile(const char *name)
12940 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12949 * This routine is called when an error or an interrupt occurs in an
12950 * interactive shell and control is returned to the main command loop.
12958 /* from input.c: */
12959 g_parsefile->left_in_buffer = 0;
12960 g_parsefile->left_in_line = 0; /* clear input buffer */
12962 /* from parser.c: */
12965 /* from redir.c: */
12966 clearredir(/*drop:*/ 0);
12970 static short profile_buf[16384];
12971 extern int etext();
12975 * Main routine. We initialize things, parse the arguments, execute
12976 * profiles if we're a login shell, and then call cmdloop to execute
12977 * commands. The setjmp call sets up the location to jump to when an
12978 * exception occurs. When an exception occurs the variable "state"
12979 * is used to figure out how far we had gotten.
12981 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12982 int ash_main(int argc UNUSED_PARAM, char **argv)
12984 const char *shinit;
12985 volatile smallint state;
12986 struct jmploc jmploc;
12987 struct stackmark smark;
12989 /* Initialize global data */
12993 #if ENABLE_ASH_ALIAS
12999 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13002 #if ENABLE_FEATURE_EDITING
13003 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13006 if (setjmp(jmploc.loc)) {
13012 e = exception_type;
13016 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13020 outcslow('\n', stderr);
13023 popstackmark(&smark);
13024 FORCE_INT_ON; /* enable interrupts */
13033 exception_handler = &jmploc;
13036 TRACE(("Shell args: "));
13037 trace_puts_args(argv);
13039 rootpid = getpid();
13042 setstackmark(&smark);
13045 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13047 const char *hp = lookupvar("HISTFILE");
13050 hp = lookupvar("HOME");
13052 char *defhp = concat_path_file(hp, ".ash_history");
13053 setvar("HISTFILE", defhp, 0);
13059 if (/* argv[0] && */ argv[0][0] == '-')
13063 read_profile("/etc/profile");
13066 read_profile(".profile");
13072 getuid() == geteuid() && getgid() == getegid() &&
13076 shinit = lookupvar("ENV");
13077 if (shinit != NULL && *shinit != '\0') {
13078 read_profile(shinit);
13084 /* evalstring pushes parsefile stack.
13085 * Ensure we don't falsely claim that 0 (stdin)
13086 * is one of stacked source fds.
13087 * Testcase: ash -c 'exec 1>&0' must not complain. */
13088 // if (!sflag) g_parsefile->pf_fd = -1;
13089 // ^^ not necessary since now we special-case fd 0
13090 // in is_hidden_fd() to not be considered "hidden fd"
13091 evalstring(minusc, 0);
13094 if (sflag || minusc == NULL) {
13095 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13097 const char *hp = lookupvar("HISTFILE");
13099 line_input_state->hist_file = hp;
13102 state4: /* XXX ??? - why isn't this before the "if" statement */
13110 extern void _mcleanup(void);
13114 TRACE(("End of main reached\n"));
13121 * Copyright (c) 1989, 1991, 1993, 1994
13122 * The Regents of the University of California. All rights reserved.
13124 * This code is derived from software contributed to Berkeley by
13125 * Kenneth Almquist.
13127 * Redistribution and use in source and binary forms, with or without
13128 * modification, are permitted provided that the following conditions
13130 * 1. Redistributions of source code must retain the above copyright
13131 * notice, this list of conditions and the following disclaimer.
13132 * 2. Redistributions in binary form must reproduce the above copyright
13133 * notice, this list of conditions and the following disclaimer in the
13134 * documentation and/or other materials provided with the distribution.
13135 * 3. Neither the name of the University nor the names of its contributors
13136 * may be used to endorse or promote products derived from this software
13137 * without specific prior written permission.
13139 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13140 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13141 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13142 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13143 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13144 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13145 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13146 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13147 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13148 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF