1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
31 /* Tweak debug output verbosity here */
38 #define JOBS ENABLE_ASH_JOB_CONTROL
43 #include <sys/times.h>
45 #include "busybox.h" /* for applet_names */
48 #include "shell_common.h"
49 #if ENABLE_SH_MATH_SUPPORT
52 #if ENABLE_ASH_RANDOM_SUPPORT
55 # define CLEAR_RANDOM_T(rnd) ((void)0)
58 #include "NUM_APPLETS.h"
60 /* STANDALONE does not make sense, and won't compile */
61 # undef CONFIG_FEATURE_SH_STANDALONE
62 # undef ENABLE_FEATURE_SH_STANDALONE
63 # undef IF_FEATURE_SH_STANDALONE
64 # undef IF_NOT_FEATURE_SH_STANDALONE
65 # define ENABLE_FEATURE_SH_STANDALONE 0
66 # define IF_FEATURE_SH_STANDALONE(...)
67 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
71 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
75 # error "Do not even bother, ash will not run on NOMMU machine"
81 //config: depends on !NOMMU
83 //config: Tha 'ash' shell adds about 60k in the default configuration and is
84 //config: the most complete and most pedantically correct shell included with
85 //config: busybox. This shell is actually a derivative of the Debian 'dash'
86 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
87 //config: (written by Kenneth Almquist) from NetBSD.
89 //config:config ASH_BASH_COMPAT
90 //config: bool "bash-compatible extensions"
92 //config: depends on ASH
94 //config: Enable bash-compatible extensions.
96 //config:config ASH_IDLE_TIMEOUT
97 //config: bool "Idle timeout variable"
99 //config: depends on ASH
101 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
103 //config:config ASH_JOB_CONTROL
104 //config: bool "Job control"
106 //config: depends on ASH
108 //config: Enable job control in the ash shell.
110 //config:config ASH_ALIAS
111 //config: bool "Alias support"
113 //config: depends on ASH
115 //config: Enable alias support in the ash shell.
117 //config:config ASH_GETOPTS
118 //config: bool "Builtin getopt to parse positional parameters"
120 //config: depends on ASH
122 //config: Enable support for getopts builtin in ash.
124 //config:config ASH_BUILTIN_ECHO
125 //config: bool "Builtin version of 'echo'"
127 //config: depends on ASH
129 //config: Enable support for echo builtin in ash.
131 //config:config ASH_BUILTIN_PRINTF
132 //config: bool "Builtin version of 'printf'"
134 //config: depends on ASH
136 //config: Enable support for printf builtin in ash.
138 //config:config ASH_BUILTIN_TEST
139 //config: bool "Builtin version of 'test'"
141 //config: depends on ASH
143 //config: Enable support for test builtin in ash.
145 //config:config ASH_CMDCMD
146 //config: bool "'command' command to override shell builtins"
148 //config: depends on ASH
150 //config: Enable support for the ash 'command' builtin, which allows
151 //config: you to run the specified command with the specified arguments,
152 //config: even when there is an ash builtin command with the same name.
154 //config:config ASH_MAIL
155 //config: bool "Check for new mail on interactive shells"
157 //config: depends on ASH
159 //config: Enable "check for new mail" function in the ash shell.
161 //config:config ASH_OPTIMIZE_FOR_SIZE
162 //config: bool "Optimize for size instead of speed"
164 //config: depends on ASH
166 //config: Compile ash for reduced size at the price of speed.
168 //config:config ASH_RANDOM_SUPPORT
169 //config: bool "Pseudorandom generator and $RANDOM variable"
171 //config: depends on ASH
173 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
174 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
175 //config: You can reset the generator by using a specified start value.
176 //config: After "unset RANDOM" the generator will switch off and this
177 //config: variable will no longer have special treatment.
179 //config:config ASH_EXPAND_PRMT
180 //config: bool "Expand prompt string"
182 //config: depends on ASH
184 //config: "PS#" may contain volatile content, such as backquote commands.
185 //config: This option recreates the prompt string from the environment
186 //config: variable each time it is displayed.
189 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
190 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
191 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
193 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
194 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
197 /* ============ Hash table sizes. Configurable. */
201 #define CMDTABLESIZE 31 /* should be prime */
204 /* ============ Shell options */
206 static const char *const optletters_optnames[] = {
221 #if ENABLE_ASH_BASH_COMPAT
230 #define optletters(n) optletters_optnames[n][0]
231 #define optnames(n) (optletters_optnames[n] + 1)
233 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
236 /* ============ Misc data */
238 #define msg_illnum "Illegal number: %s"
241 * We enclose jmp_buf in a structure so that we can declare pointers to
242 * jump locations. The global variable handler contains the location to
243 * jump to when an exception occurs, and the global variable exception_type
244 * contains a code identifying the exception. To implement nested
245 * exception handlers, the user should save the value of handler on entry
246 * to an inner scope, set handler to point to a jmploc structure for the
247 * inner scope, and restore handler on exit from the scope.
253 struct globals_misc {
254 /* pid of main shell */
256 /* shell level: 0 for the main shell, 1 for its children, and so on */
258 #define rootshell (!shlvl)
259 char *minusc; /* argument to -c option */
261 char *curdir; // = nullstr; /* current working directory */
262 char *physdir; // = nullstr; /* physical working directory */
264 char *arg0; /* value of $0 */
266 struct jmploc *exception_handler;
268 volatile int suppress_int; /* counter */
269 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
270 /* last pending signal */
271 volatile /*sig_atomic_t*/ smallint pending_sig;
272 smallint exception_type; /* kind of exception (0..5) */
274 #define EXINT 0 /* SIGINT received */
275 #define EXERROR 1 /* a generic error */
276 #define EXSHELLPROC 2 /* execute a shell procedure */
277 #define EXEXEC 3 /* command execution failed */
278 #define EXEXIT 4 /* exit the shell */
279 #define EXSIG 5 /* trapped signal in wait(1) */
282 char nullstr[1]; /* zero length string */
285 #define eflag optlist[0]
286 #define fflag optlist[1]
287 #define Iflag optlist[2]
288 #define iflag optlist[3]
289 #define mflag optlist[4]
290 #define nflag optlist[5]
291 #define sflag optlist[6]
292 #define xflag optlist[7]
293 #define vflag optlist[8]
294 #define Cflag optlist[9]
295 #define aflag optlist[10]
296 #define bflag optlist[11]
297 #define uflag optlist[12]
298 #define viflag optlist[13]
299 #if ENABLE_ASH_BASH_COMPAT
300 # define pipefail optlist[14]
305 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
306 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
309 /* trap handler commands */
311 * Sigmode records the current value of the signal handlers for the various
312 * modes. A value of zero means that the current handler is not known.
313 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
315 char sigmode[NSIG - 1];
316 #define S_DFL 1 /* default signal handling (SIG_DFL) */
317 #define S_CATCH 2 /* signal is caught */
318 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
319 #define S_HARD_IGN 4 /* signal is ignored permenantly */
321 /* indicates specified signal received */
322 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
323 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
325 char **trap_ptr; /* used only by "trap hack" */
327 /* Rarely referenced stuff */
328 #if ENABLE_ASH_RANDOM_SUPPORT
331 pid_t backgndpid; /* pid of last background process */
332 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
334 extern struct globals_misc *const ash_ptr_to_globals_misc;
335 #define G_misc (*ash_ptr_to_globals_misc)
336 #define rootpid (G_misc.rootpid )
337 #define shlvl (G_misc.shlvl )
338 #define minusc (G_misc.minusc )
339 #define curdir (G_misc.curdir )
340 #define physdir (G_misc.physdir )
341 #define arg0 (G_misc.arg0 )
342 #define exception_handler (G_misc.exception_handler)
343 #define exception_type (G_misc.exception_type )
344 #define suppress_int (G_misc.suppress_int )
345 #define pending_int (G_misc.pending_int )
346 #define pending_sig (G_misc.pending_sig )
347 #define isloginsh (G_misc.isloginsh )
348 #define nullstr (G_misc.nullstr )
349 #define optlist (G_misc.optlist )
350 #define sigmode (G_misc.sigmode )
351 #define gotsig (G_misc.gotsig )
352 #define may_have_traps (G_misc.may_have_traps )
353 #define trap (G_misc.trap )
354 #define trap_ptr (G_misc.trap_ptr )
355 #define random_gen (G_misc.random_gen )
356 #define backgndpid (G_misc.backgndpid )
357 #define job_warning (G_misc.job_warning)
358 #define INIT_G_misc() do { \
359 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
367 /* ============ DEBUG */
369 static void trace_printf(const char *fmt, ...);
370 static void trace_vprintf(const char *fmt, va_list va);
371 # define TRACE(param) trace_printf param
372 # define TRACEV(param) trace_vprintf param
373 # define close(fd) do { \
375 if (close(dfd) < 0) \
376 bb_error_msg("bug on %d: closing %d(0x%x)", \
377 __LINE__, dfd, dfd); \
380 # define TRACE(param)
381 # define TRACEV(param)
385 /* ============ Utility functions */
386 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
388 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
389 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
391 static int isdigit_str9(const char *str)
393 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
394 while (--maxlen && isdigit(*str))
396 return (*str == '\0');
399 static const char *var_end(const char *var)
408 /* ============ Interrupts / exceptions */
410 static void exitshell(void) NORETURN;
413 * These macros allow the user to suspend the handling of interrupt signals
414 * over a period of time. This is similar to SIGHOLD or to sigblock, but
415 * much more efficient and portable. (But hacking the kernel is so much
416 * more fun than worrying about efficiency and portability. :-))
418 #define INT_OFF do { \
424 * Called to raise an exception. Since C doesn't include exceptions, we
425 * just do a longjmp to the exception handler. The type of exception is
426 * stored in the global variable "exception_type".
428 static void raise_exception(int) NORETURN;
430 raise_exception(int e)
433 if (exception_handler == NULL)
438 longjmp(exception_handler->loc, 1);
441 #define raise_exception(e) do { \
442 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
443 raise_exception(e); \
448 * Called from trap.c when a SIGINT is received. (If the user specifies
449 * that SIGINT is to be trapped or ignored using the trap builtin, then
450 * this routine is not called.) Suppressint is nonzero when interrupts
451 * are held using the INT_OFF macro. (The test for iflag is just
452 * defensive programming.)
454 static void raise_interrupt(void) NORETURN;
456 raise_interrupt(void)
461 /* Signal is not automatically unmasked after it is raised,
462 * do it ourself - unmask all signals */
463 sigprocmask_allsigs(SIG_UNBLOCK);
464 /* pending_sig = 0; - now done in signal_handler() */
467 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
468 if (!(rootshell && iflag)) {
469 /* Kill ourself with SIGINT */
470 signal(SIGINT, SIG_DFL);
475 raise_exception(ex_type);
479 #define raise_interrupt() do { \
480 TRACE(("raising interrupt on line %d\n", __LINE__)); \
485 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
489 if (--suppress_int == 0 && pending_int) {
493 #define INT_ON int_on()
494 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
502 #define FORCE_INT_ON force_int_on()
504 #define SAVE_INT(v) ((v) = suppress_int)
506 #define RESTORE_INT(v) do { \
508 suppress_int = (v); \
509 if (suppress_int == 0 && pending_int) \
514 /* ============ Stdout/stderr output */
517 outstr(const char *p, FILE *file)
525 flush_stdout_stderr(void)
533 outcslow(int c, FILE *dest)
541 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
543 out1fmt(const char *fmt, ...)
550 r = vprintf(fmt, ap);
556 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
558 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
565 ret = vsnprintf(outbuf, length, fmt, ap);
572 out1str(const char *p)
578 out2str(const char *p)
581 flush_stdout_stderr();
585 /* ============ Parser structures */
587 /* control characters in argument strings */
588 #define CTL_FIRST CTLESC
589 #define CTLESC ((unsigned char)'\201') /* escape next character */
590 #define CTLVAR ((unsigned char)'\202') /* variable defn */
591 #define CTLENDVAR ((unsigned char)'\203')
592 #define CTLBACKQ ((unsigned char)'\204')
593 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
594 /* CTLBACKQ | CTLQUOTE == '\205' */
595 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
596 #define CTLENDARI ((unsigned char)'\207')
597 #define CTLQUOTEMARK ((unsigned char)'\210')
598 #define CTL_LAST CTLQUOTEMARK
600 /* variable substitution byte (follows CTLVAR) */
601 #define VSTYPE 0x0f /* type of variable substitution */
602 #define VSNUL 0x10 /* colon--treat the empty string as unset */
603 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
605 /* values of VSTYPE field */
606 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
607 #define VSMINUS 0x2 /* ${var-text} */
608 #define VSPLUS 0x3 /* ${var+text} */
609 #define VSQUESTION 0x4 /* ${var?message} */
610 #define VSASSIGN 0x5 /* ${var=text} */
611 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
612 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
613 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
614 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
615 #define VSLENGTH 0xa /* ${#var} */
616 #if ENABLE_ASH_BASH_COMPAT
617 #define VSSUBSTR 0xc /* ${var:position:length} */
618 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
619 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
622 static const char dolatstr[] ALIGN1 = {
623 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
643 #if ENABLE_ASH_BASH_COMPAT
660 smallint type; /* Nxxxx */
663 union node *redirect;
668 smallint pipe_backgnd;
669 struct nodelist *cmdlist;
675 union node *redirect;
688 union node *elsepart;
715 struct nodelist *backquote;
718 /* nfile and ndup layout must match!
719 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
720 * that it is actually NTO2 (>&file), and change its type.
737 char *_unused_expfname;
756 struct nredir nredir;
757 struct nbinary nbinary;
761 struct nclist nclist;
770 * NODE_EOF is returned by parsecmd when it encounters an end of file.
771 * It must be distinct from NULL.
773 #define NODE_EOF ((union node *) -1L)
776 struct nodelist *next;
789 freefunc(struct funcnode *f)
791 if (f && --f->count < 0)
796 /* ============ Debugging output */
800 static FILE *tracefile;
803 trace_printf(const char *fmt, ...)
810 fprintf(tracefile, "%u ", (int) time(NULL));
812 fprintf(tracefile, "[%u] ", (int) getpid());
814 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
816 vfprintf(tracefile, fmt, va);
821 trace_vprintf(const char *fmt, va_list va)
826 fprintf(tracefile, "%u ", (int) time(NULL));
828 fprintf(tracefile, "[%u] ", (int) getpid());
830 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
831 vfprintf(tracefile, fmt, va);
835 trace_puts(const char *s)
843 trace_puts_quoted(char *s)
850 putc('"', tracefile);
851 for (p = s; *p; p++) {
852 switch ((unsigned char)*p) {
853 case '\n': c = 'n'; goto backslash;
854 case '\t': c = 't'; goto backslash;
855 case '\r': c = 'r'; goto backslash;
856 case '\"': c = '\"'; goto backslash;
857 case '\\': c = '\\'; goto backslash;
858 case CTLESC: c = 'e'; goto backslash;
859 case CTLVAR: c = 'v'; goto backslash;
860 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
861 case CTLBACKQ: c = 'q'; goto backslash;
862 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
864 putc('\\', tracefile);
868 if (*p >= ' ' && *p <= '~')
871 putc('\\', tracefile);
872 putc((*p >> 6) & 03, tracefile);
873 putc((*p >> 3) & 07, tracefile);
874 putc(*p & 07, tracefile);
879 putc('"', tracefile);
883 trace_puts_args(char **ap)
890 trace_puts_quoted(*ap);
892 putc('\n', tracefile);
895 putc(' ', tracefile);
910 /* leave open because libedit might be using it */
913 strcpy(s, "./trace");
915 if (!freopen(s, "a", tracefile)) {
916 fprintf(stderr, "Can't re-open %s\n", s);
921 tracefile = fopen(s, "a");
922 if (tracefile == NULL) {
923 fprintf(stderr, "Can't open %s\n", s);
929 flags = fcntl(fileno(tracefile), F_GETFL);
931 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
933 setlinebuf(tracefile);
934 fputs("\nTracing started.\n", tracefile);
938 indent(int amount, char *pfx, FILE *fp)
942 for (i = 0; i < amount; i++) {
943 if (pfx && i == amount - 1)
949 /* little circular references here... */
950 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
953 sharg(union node *arg, FILE *fp)
956 struct nodelist *bqlist;
957 unsigned char subtype;
959 if (arg->type != NARG) {
960 out1fmt("<node type %d>\n", arg->type);
963 bqlist = arg->narg.backquote;
964 for (p = arg->narg.text; *p; p++) {
965 switch ((unsigned char)*p) {
974 if (subtype == VSLENGTH)
985 switch (subtype & VSTYPE) {
1011 case VSTRIMRIGHTMAX:
1018 out1fmt("<subtype %d>", subtype);
1025 case CTLBACKQ|CTLQUOTE:
1028 shtree(bqlist->n, -1, NULL, fp);
1039 shcmd(union node *cmd, FILE *fp)
1047 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1053 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1057 switch (np->nfile.type) {
1058 case NTO: s = ">>"+1; dftfd = 1; break;
1059 case NCLOBBER: s = ">|"; dftfd = 1; break;
1060 case NAPPEND: s = ">>"; dftfd = 1; break;
1061 #if ENABLE_ASH_BASH_COMPAT
1064 case NTOFD: s = ">&"; dftfd = 1; break;
1065 case NFROM: s = "<"; break;
1066 case NFROMFD: s = "<&"; break;
1067 case NFROMTO: s = "<>"; break;
1068 default: s = "*error*"; break;
1070 if (np->nfile.fd != dftfd)
1071 fprintf(fp, "%d", np->nfile.fd);
1073 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1074 fprintf(fp, "%d", np->ndup.dupfd);
1076 sharg(np->nfile.fname, fp);
1083 shtree(union node *n, int ind, char *pfx, FILE *fp)
1085 struct nodelist *lp;
1091 indent(ind, pfx, fp);
1093 if (n == NODE_EOF) {
1108 shtree(n->nbinary.ch1, ind, NULL, fp);
1111 shtree(n->nbinary.ch2, ind, NULL, fp);
1119 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1120 shtree(lp->n, 0, NULL, fp);
1124 if (n->npipe.pipe_backgnd)
1130 fprintf(fp, "<node type %d>", n->type);
1138 showtree(union node *n)
1140 trace_puts("showtree called\n");
1141 shtree(n, 1, NULL, stderr);
1147 /* ============ Parser data */
1150 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1153 struct strlist *next;
1160 struct strpush *prev; /* preceding string on stack */
1162 int prev_left_in_line;
1163 #if ENABLE_ASH_ALIAS
1164 struct alias *ap; /* if push was associated with an alias */
1166 char *string; /* remember the string since it may change */
1170 struct parsefile *prev; /* preceding file on stack */
1171 int linno; /* current line */
1172 int pf_fd; /* file descriptor (or -1 if string) */
1173 int left_in_line; /* number of chars left in this line */
1174 int left_in_buffer; /* number of chars left in this buffer past the line */
1175 char *next_to_pgetc; /* next char in buffer */
1176 char *buf; /* input buffer */
1177 struct strpush *strpush; /* for pushing strings at this level */
1178 struct strpush basestrpush; /* so pushing one is fast */
1181 static struct parsefile basepf; /* top level input file */
1182 static struct parsefile *g_parsefile = &basepf; /* current input file */
1183 static int startlinno; /* line # where last token started */
1184 static char *commandname; /* currently executing command */
1185 static struct strlist *cmdenviron; /* environment for builtin command */
1186 static uint8_t exitstatus; /* exit status of last command */
1189 /* ============ Message printing */
1192 ash_vmsg(const char *msg, va_list ap)
1194 fprintf(stderr, "%s: ", arg0);
1196 if (strcmp(arg0, commandname))
1197 fprintf(stderr, "%s: ", commandname);
1198 if (!iflag || g_parsefile->pf_fd > 0)
1199 fprintf(stderr, "line %d: ", startlinno);
1201 vfprintf(stderr, msg, ap);
1202 outcslow('\n', stderr);
1206 * Exverror is called to raise the error exception. If the second argument
1207 * is not NULL then error prints an error message using printf style
1208 * formatting. It then raises the error exception.
1210 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1212 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1216 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1218 TRACE(("\") pid=%d\n", getpid()));
1220 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1225 flush_stdout_stderr();
1226 raise_exception(cond);
1230 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1232 ash_msg_and_raise_error(const char *msg, ...)
1237 ash_vmsg_and_raise(EXERROR, msg, ap);
1242 static void raise_error_syntax(const char *) NORETURN;
1244 raise_error_syntax(const char *msg)
1246 ash_msg_and_raise_error("syntax error: %s", msg);
1250 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1252 ash_msg_and_raise(int cond, const char *msg, ...)
1257 ash_vmsg_and_raise(cond, msg, ap);
1263 * error/warning routines for external builtins
1266 ash_msg(const char *fmt, ...)
1276 * Return a string describing an error. The returned string may be a
1277 * pointer to a static buffer that will be overwritten on the next call.
1278 * Action describes the operation that got the error.
1281 errmsg(int e, const char *em)
1283 if (e == ENOENT || e == ENOTDIR) {
1290 /* ============ Memory allocation */
1293 /* I consider these wrappers nearly useless:
1294 * ok, they return you to nearest exception handler, but
1295 * how much memory do you leak in the process, making
1296 * memory starvation worse?
1299 ckrealloc(void * p, size_t nbytes)
1301 p = realloc(p, nbytes);
1303 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1308 ckmalloc(size_t nbytes)
1310 return ckrealloc(NULL, nbytes);
1314 ckzalloc(size_t nbytes)
1316 return memset(ckmalloc(nbytes), 0, nbytes);
1320 ckstrdup(const char *s)
1322 char *p = strdup(s);
1324 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1328 /* Using bbox equivalents. They exit if out of memory */
1329 # define ckrealloc xrealloc
1330 # define ckmalloc xmalloc
1331 # define ckzalloc xzalloc
1332 # define ckstrdup xstrdup
1336 * It appears that grabstackstr() will barf with such alignments
1337 * because stalloc() will return a string allocated in a new stackblock.
1339 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1341 /* Most machines require the value returned from malloc to be aligned
1342 * in some way. The following macro will get this right
1343 * on many machines. */
1344 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1345 /* Minimum size of a block */
1346 MINSIZE = SHELL_ALIGN(504),
1349 struct stack_block {
1350 struct stack_block *prev;
1351 char space[MINSIZE];
1355 struct stack_block *stackp;
1358 struct stackmark *marknext;
1362 struct globals_memstack {
1363 struct stack_block *g_stackp; // = &stackbase;
1364 struct stackmark *markp;
1365 char *g_stacknxt; // = stackbase.space;
1366 char *sstrend; // = stackbase.space + MINSIZE;
1367 size_t g_stacknleft; // = MINSIZE;
1368 int herefd; // = -1;
1369 struct stack_block stackbase;
1371 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1372 #define G_memstack (*ash_ptr_to_globals_memstack)
1373 #define g_stackp (G_memstack.g_stackp )
1374 #define markp (G_memstack.markp )
1375 #define g_stacknxt (G_memstack.g_stacknxt )
1376 #define sstrend (G_memstack.sstrend )
1377 #define g_stacknleft (G_memstack.g_stacknleft)
1378 #define herefd (G_memstack.herefd )
1379 #define stackbase (G_memstack.stackbase )
1380 #define INIT_G_memstack() do { \
1381 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1383 g_stackp = &stackbase; \
1384 g_stacknxt = stackbase.space; \
1385 g_stacknleft = MINSIZE; \
1386 sstrend = stackbase.space + MINSIZE; \
1391 #define stackblock() ((void *)g_stacknxt)
1392 #define stackblocksize() g_stacknleft
1395 * Parse trees for commands are allocated in lifo order, so we use a stack
1396 * to make this more efficient, and also to avoid all sorts of exception
1397 * handling code to handle interrupts in the middle of a parse.
1399 * The size 504 was chosen because the Ultrix malloc handles that size
1403 stalloc(size_t nbytes)
1408 aligned = SHELL_ALIGN(nbytes);
1409 if (aligned > g_stacknleft) {
1412 struct stack_block *sp;
1414 blocksize = aligned;
1415 if (blocksize < MINSIZE)
1416 blocksize = MINSIZE;
1417 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1418 if (len < blocksize)
1419 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1422 sp->prev = g_stackp;
1423 g_stacknxt = sp->space;
1424 g_stacknleft = blocksize;
1425 sstrend = g_stacknxt + blocksize;
1430 g_stacknxt += aligned;
1431 g_stacknleft -= aligned;
1436 stzalloc(size_t nbytes)
1438 return memset(stalloc(nbytes), 0, nbytes);
1445 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1446 write(STDERR_FILENO, "stunalloc\n", 10);
1450 g_stacknleft += g_stacknxt - (char *)p;
1455 * Like strdup but works with the ash stack.
1458 ststrdup(const char *p)
1460 size_t len = strlen(p) + 1;
1461 return memcpy(stalloc(len), p, len);
1465 setstackmark(struct stackmark *mark)
1467 mark->stackp = g_stackp;
1468 mark->stacknxt = g_stacknxt;
1469 mark->stacknleft = g_stacknleft;
1470 mark->marknext = markp;
1475 popstackmark(struct stackmark *mark)
1477 struct stack_block *sp;
1483 markp = mark->marknext;
1484 while (g_stackp != mark->stackp) {
1486 g_stackp = sp->prev;
1489 g_stacknxt = mark->stacknxt;
1490 g_stacknleft = mark->stacknleft;
1491 sstrend = mark->stacknxt + mark->stacknleft;
1496 * When the parser reads in a string, it wants to stick the string on the
1497 * stack and only adjust the stack pointer when it knows how big the
1498 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1499 * of space on top of the stack and stackblocklen returns the length of
1500 * this block. Growstackblock will grow this space by at least one byte,
1501 * possibly moving it (like realloc). Grabstackblock actually allocates the
1502 * part of the block that has been used.
1505 growstackblock(void)
1509 newlen = g_stacknleft * 2;
1510 if (newlen < g_stacknleft)
1511 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1515 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1516 struct stack_block *oldstackp;
1517 struct stackmark *xmark;
1518 struct stack_block *sp;
1519 struct stack_block *prevstackp;
1523 oldstackp = g_stackp;
1525 prevstackp = sp->prev;
1526 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1527 sp = ckrealloc(sp, grosslen);
1528 sp->prev = prevstackp;
1530 g_stacknxt = sp->space;
1531 g_stacknleft = newlen;
1532 sstrend = sp->space + newlen;
1535 * Stack marks pointing to the start of the old block
1536 * must be relocated to point to the new block
1539 while (xmark != NULL && xmark->stackp == oldstackp) {
1540 xmark->stackp = g_stackp;
1541 xmark->stacknxt = g_stacknxt;
1542 xmark->stacknleft = g_stacknleft;
1543 xmark = xmark->marknext;
1547 char *oldspace = g_stacknxt;
1548 size_t oldlen = g_stacknleft;
1549 char *p = stalloc(newlen);
1551 /* free the space we just allocated */
1552 g_stacknxt = memcpy(p, oldspace, oldlen);
1553 g_stacknleft += newlen;
1558 grabstackblock(size_t len)
1560 len = SHELL_ALIGN(len);
1562 g_stacknleft -= len;
1566 * The following routines are somewhat easier to use than the above.
1567 * The user declares a variable of type STACKSTR, which may be declared
1568 * to be a register. The macro STARTSTACKSTR initializes things. Then
1569 * the user uses the macro STPUTC to add characters to the string. In
1570 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1571 * grown as necessary. When the user is done, she can just leave the
1572 * string there and refer to it using stackblock(). Or she can allocate
1573 * the space for it using grabstackstr(). If it is necessary to allow
1574 * someone else to use the stack temporarily and then continue to grow
1575 * the string, the user should use grabstack to allocate the space, and
1576 * then call ungrabstr(p) to return to the previous mode of operation.
1578 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1579 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1580 * is space for at least one character.
1585 size_t len = stackblocksize();
1586 if (herefd >= 0 && len >= 1024) {
1587 full_write(herefd, stackblock(), len);
1588 return stackblock();
1591 return (char *)stackblock() + len;
1595 * Called from CHECKSTRSPACE.
1598 makestrspace(size_t newlen, char *p)
1600 size_t len = p - g_stacknxt;
1601 size_t size = stackblocksize();
1606 size = stackblocksize();
1608 if (nleft >= newlen)
1612 return (char *)stackblock() + len;
1616 stack_nputstr(const char *s, size_t n, char *p)
1618 p = makestrspace(n, p);
1619 p = (char *)memcpy(p, s, n) + n;
1624 stack_putstr(const char *s, char *p)
1626 return stack_nputstr(s, strlen(s), p);
1630 _STPUTC(int c, char *p)
1638 #define STARTSTACKSTR(p) ((p) = stackblock())
1639 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1640 #define CHECKSTRSPACE(n, p) do { \
1643 size_t m = sstrend - q; \
1645 (p) = makestrspace(l, q); \
1647 #define USTPUTC(c, p) (*(p)++ = (c))
1648 #define STACKSTRNUL(p) do { \
1649 if ((p) == sstrend) \
1650 (p) = growstackstr(); \
1653 #define STUNPUTC(p) (--(p))
1654 #define STTOPC(p) ((p)[-1])
1655 #define STADJUST(amount, p) ((p) += (amount))
1657 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1658 #define ungrabstackstr(s, p) stunalloc(s)
1659 #define stackstrend() ((void *)sstrend)
1662 /* ============ String helpers */
1665 * prefix -- see if pfx is a prefix of string.
1668 prefix(const char *string, const char *pfx)
1671 if (*pfx++ != *string++)
1674 return (char *) string;
1678 * Check for a valid number. This should be elsewhere.
1681 is_number(const char *p)
1686 } while (*++p != '\0');
1691 * Convert a string of digits to an integer, printing an error message on
1695 number(const char *s)
1698 ash_msg_and_raise_error(msg_illnum, s);
1703 * Produce a possibly single quoted string suitable as input to the shell.
1704 * The return string is allocated on the stack.
1707 single_quote(const char *s)
1717 len = strchrnul(s, '\'') - s;
1719 q = p = makestrspace(len + 3, p);
1722 q = (char *)memcpy(q, s, len) + len;
1731 do len++; while (*++s == '\'');
1733 q = p = makestrspace(len + 3, p);
1736 q = (char *)memcpy(q, s - len, len) + len;
1744 return stackblock();
1748 /* ============ nextopt */
1750 static char **argptr; /* argument list for builtin commands */
1751 static char *optionarg; /* set by nextopt (like getopt) */
1752 static char *optptr; /* used by nextopt */
1755 * XXX - should get rid of. Have all builtins use getopt(3).
1756 * The library getopt must have the BSD extension static variable
1757 * "optreset", otherwise it can't be used within the shell safely.
1759 * Standard option processing (a la getopt) for builtin routines.
1760 * The only argument that is passed to nextopt is the option string;
1761 * the other arguments are unnecessary. It returns the character,
1762 * or '\0' on end of input.
1765 nextopt(const char *optstring)
1772 if (p == NULL || *p == '\0') {
1773 /* We ate entire "-param", take next one */
1779 if (*++p == '\0') /* just "-" ? */
1782 if (LONE_DASH(p)) /* "--" ? */
1784 /* p => next "-param" */
1786 /* p => some option char in the middle of a "-param" */
1788 for (q = optstring; *q != c;) {
1790 ash_msg_and_raise_error("illegal option -%c", c);
1798 ash_msg_and_raise_error("no arg for -%c option", c);
1808 /* ============ Shell variables */
1811 * The parsefile structure pointed to by the global variable parsefile
1812 * contains information about the current file being read.
1815 int nparam; /* # of positional parameters (without $0) */
1816 #if ENABLE_ASH_GETOPTS
1817 int optind; /* next parameter to be processed by getopts */
1818 int optoff; /* used by getopts */
1820 unsigned char malloced; /* if parameter list dynamically allocated */
1821 char **p; /* parameter list */
1825 * Free the list of positional parameters.
1828 freeparam(volatile struct shparam *param)
1830 if (param->malloced) {
1832 ap = ap1 = param->p;
1839 #if ENABLE_ASH_GETOPTS
1840 static void FAST_FUNC getoptsreset(const char *value);
1844 struct var *next; /* next entry in hash list */
1845 int flags; /* flags are defined above */
1846 const char *var_text; /* name=value */
1847 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1848 /* the variable gets set/unset */
1852 struct localvar *next; /* next local variable in list */
1853 struct var *vp; /* the variable that was made local */
1854 int flags; /* saved flags */
1855 const char *text; /* saved text */
1859 #define VEXPORT 0x01 /* variable is exported */
1860 #define VREADONLY 0x02 /* variable cannot be modified */
1861 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1862 #define VTEXTFIXED 0x08 /* text is statically allocated */
1863 #define VSTACK 0x10 /* text is allocated on the stack */
1864 #define VUNSET 0x20 /* the variable is not set */
1865 #define VNOFUNC 0x40 /* don't call the callback function */
1866 #define VNOSET 0x80 /* do not set variable - just readonly test */
1867 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1868 #if ENABLE_ASH_RANDOM_SUPPORT
1869 # define VDYNAMIC 0x200 /* dynamic variable */
1875 /* Need to be before varinit_data[] */
1876 #if ENABLE_LOCALE_SUPPORT
1877 static void FAST_FUNC
1878 change_lc_all(const char *value)
1880 if (value && *value != '\0')
1881 setlocale(LC_ALL, value);
1883 static void FAST_FUNC
1884 change_lc_ctype(const char *value)
1886 if (value && *value != '\0')
1887 setlocale(LC_CTYPE, value);
1891 static void chkmail(void);
1892 static void changemail(const char *var_value) FAST_FUNC;
1894 # define chkmail() ((void)0)
1896 static void changepath(const char *) FAST_FUNC;
1897 #if ENABLE_ASH_RANDOM_SUPPORT
1898 static void change_random(const char *) FAST_FUNC;
1901 static const struct {
1903 const char *var_text;
1904 void (*var_func)(const char *) FAST_FUNC;
1905 } varinit_data[] = {
1907 * Note: VEXPORT would not work correctly here for NOFORK applets:
1908 * some environment strings may be constant.
1910 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1912 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1913 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1915 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1916 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1917 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1918 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1919 #if ENABLE_ASH_GETOPTS
1920 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1922 #if ENABLE_ASH_RANDOM_SUPPORT
1923 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1925 #if ENABLE_LOCALE_SUPPORT
1926 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1927 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1929 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1930 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1936 struct globals_var {
1937 struct shparam shellparam; /* $@ current positional parameters */
1938 struct redirtab *redirlist;
1940 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1941 struct var *vartab[VTABSIZE];
1942 struct var varinit[ARRAY_SIZE(varinit_data)];
1944 extern struct globals_var *const ash_ptr_to_globals_var;
1945 #define G_var (*ash_ptr_to_globals_var)
1946 #define shellparam (G_var.shellparam )
1947 //#define redirlist (G_var.redirlist )
1948 #define g_nullredirs (G_var.g_nullredirs )
1949 #define preverrout_fd (G_var.preverrout_fd)
1950 #define vartab (G_var.vartab )
1951 #define varinit (G_var.varinit )
1952 #define INIT_G_var() do { \
1954 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1956 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1957 varinit[i].flags = varinit_data[i].flags; \
1958 varinit[i].var_text = varinit_data[i].var_text; \
1959 varinit[i].var_func = varinit_data[i].var_func; \
1963 #define vifs varinit[0]
1965 # define vmail (&vifs)[1]
1966 # define vmpath (&vmail)[1]
1967 # define vpath (&vmpath)[1]
1969 # define vpath (&vifs)[1]
1971 #define vps1 (&vpath)[1]
1972 #define vps2 (&vps1)[1]
1973 #define vps4 (&vps2)[1]
1974 #if ENABLE_ASH_GETOPTS
1975 # define voptind (&vps4)[1]
1976 # if ENABLE_ASH_RANDOM_SUPPORT
1977 # define vrandom (&voptind)[1]
1980 # if ENABLE_ASH_RANDOM_SUPPORT
1981 # define vrandom (&vps4)[1]
1986 * The following macros access the values of the above variables.
1987 * They have to skip over the name. They return the null string
1988 * for unset variables.
1990 #define ifsval() (vifs.var_text + 4)
1991 #define ifsset() ((vifs.flags & VUNSET) == 0)
1993 # define mailval() (vmail.var_text + 5)
1994 # define mpathval() (vmpath.var_text + 9)
1995 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1997 #define pathval() (vpath.var_text + 5)
1998 #define ps1val() (vps1.var_text + 4)
1999 #define ps2val() (vps2.var_text + 4)
2000 #define ps4val() (vps4.var_text + 4)
2001 #if ENABLE_ASH_GETOPTS
2002 # define optindval() (voptind.var_text + 7)
2005 #if ENABLE_ASH_GETOPTS
2006 static void FAST_FUNC
2007 getoptsreset(const char *value)
2009 shellparam.optind = number(value);
2010 shellparam.optoff = -1;
2015 * Compares two strings up to the first = or '\0'. The first
2016 * string must be terminated by '='; the second may be terminated by
2017 * either '=' or '\0'.
2020 varcmp(const char *p, const char *q)
2024 while ((c = *p) == (d = *q)) {
2039 * Find the appropriate entry in the hash table from the name.
2041 static struct var **
2042 hashvar(const char *p)
2046 hashval = ((unsigned char) *p) << 4;
2047 while (*p && *p != '=')
2048 hashval += (unsigned char) *p++;
2049 return &vartab[hashval % VTABSIZE];
2053 vpcmp(const void *a, const void *b)
2055 return varcmp(*(const char **)a, *(const char **)b);
2059 * This routine initializes the builtin variables.
2069 * PS1 depends on uid
2071 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2072 vps1.var_text = "PS1=\\w \\$ ";
2075 vps1.var_text = "PS1=# ";
2078 end = vp + ARRAY_SIZE(varinit);
2080 vpp = hashvar(vp->var_text);
2083 } while (++vp < end);
2086 static struct var **
2087 findvar(struct var **vpp, const char *name)
2089 for (; *vpp; vpp = &(*vpp)->next) {
2090 if (varcmp((*vpp)->var_text, name) == 0) {
2098 * Find the value of a variable. Returns NULL if not set.
2100 static const char* FAST_FUNC
2101 lookupvar(const char *name)
2105 v = *findvar(hashvar(name), name);
2107 #if ENABLE_ASH_RANDOM_SUPPORT
2109 * Dynamic variables are implemented roughly the same way they are
2110 * in bash. Namely, they're "special" so long as they aren't unset.
2111 * As soon as they're unset, they're no longer dynamic, and dynamic
2112 * lookup will no longer happen at that point. -- PFM.
2114 if (v->flags & VDYNAMIC)
2117 if (!(v->flags & VUNSET))
2118 return var_end(v->var_text);
2124 * Search the environment of a builtin command.
2127 bltinlookup(const char *name)
2131 for (sp = cmdenviron; sp; sp = sp->next) {
2132 if (varcmp(sp->text, name) == 0)
2133 return var_end(sp->text);
2135 return lookupvar(name);
2139 * Same as setvar except that the variable and value are passed in
2140 * the first argument as name=value. Since the first argument will
2141 * be actually stored in the table, it should not be a string that
2143 * Called with interrupts off.
2146 setvareq(char *s, int flags)
2148 struct var *vp, **vpp;
2151 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2152 vp = *findvar(vpp, s);
2154 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2157 if (flags & VNOSAVE)
2160 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2166 if (vp->var_func && !(flags & VNOFUNC))
2167 vp->var_func(var_end(s));
2169 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2170 free((char*)vp->var_text);
2172 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2174 /* variable s is not found */
2177 vp = ckzalloc(sizeof(*vp));
2179 /*vp->func = NULL; - ckzalloc did it */
2182 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2189 * Set the value of a variable. The flags argument is ored with the
2190 * flags of the variable. If val is NULL, the variable is unset.
2193 setvar(const char *name, const char *val, int flags)
2201 q = endofname(name);
2202 p = strchrnul(q, '=');
2204 if (!namelen || p != q)
2205 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2210 vallen = strlen(val);
2214 nameeq = ckmalloc(namelen + vallen + 2);
2215 p = memcpy(nameeq, name, namelen) + namelen;
2218 p = memcpy(p, val, vallen) + vallen;
2221 setvareq(nameeq, flags | VNOSAVE);
2225 static void FAST_FUNC
2226 setvar2(const char *name, const char *val)
2228 setvar(name, val, 0);
2231 #if ENABLE_ASH_GETOPTS
2233 * Safe version of setvar, returns 1 on success 0 on failure.
2236 setvarsafe(const char *name, const char *val, int flags)
2239 volatile int saveint;
2240 struct jmploc *volatile savehandler = exception_handler;
2241 struct jmploc jmploc;
2244 if (setjmp(jmploc.loc))
2247 exception_handler = &jmploc;
2248 setvar(name, val, flags);
2251 exception_handler = savehandler;
2252 RESTORE_INT(saveint);
2258 * Unset the specified variable.
2261 unsetvar(const char *s)
2267 vpp = findvar(hashvar(s), s);
2271 int flags = vp->flags;
2274 if (flags & VREADONLY)
2276 #if ENABLE_ASH_RANDOM_SUPPORT
2277 vp->flags &= ~VDYNAMIC;
2281 if ((flags & VSTRFIXED) == 0) {
2283 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2284 free((char*)vp->var_text);
2290 vp->flags &= ~VEXPORT;
2300 * Process a linked list of variable assignments.
2303 listsetvar(struct strlist *list_set_var, int flags)
2305 struct strlist *lp = list_set_var;
2311 setvareq(lp->text, flags);
2318 * Generate a list of variables satisfying the given conditions.
2321 listvars(int on, int off, char ***end)
2332 for (vp = *vpp; vp; vp = vp->next) {
2333 if ((vp->flags & mask) == on) {
2334 if (ep == stackstrend())
2335 ep = growstackstr();
2336 *ep++ = (char*)vp->var_text;
2339 } while (++vpp < vartab + VTABSIZE);
2340 if (ep == stackstrend())
2341 ep = growstackstr();
2345 return grabstackstr(ep);
2349 /* ============ Path search helper
2351 * The variable path (passed by reference) should be set to the start
2352 * of the path before the first call; path_advance will update
2353 * this value as it proceeds. Successive calls to path_advance will return
2354 * the possible path expansions in sequence. If an option (indicated by
2355 * a percent sign) appears in the path entry then the global variable
2356 * pathopt will be set to point to it; otherwise pathopt will be set to
2359 static const char *pathopt; /* set by path_advance */
2362 path_advance(const char **path, const char *name)
2372 for (p = start; *p && *p != ':' && *p != '%'; p++)
2374 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2375 while (stackblocksize() < len)
2379 memcpy(q, start, p - start);
2387 while (*p && *p != ':')
2394 return stalloc(len);
2398 /* ============ Prompt */
2400 static smallint doprompt; /* if set, prompt the user */
2401 static smallint needprompt; /* true if interactive and at start of line */
2403 #if ENABLE_FEATURE_EDITING
2404 static line_input_t *line_input_state;
2405 static const char *cmdedit_prompt;
2407 putprompt(const char *s)
2409 if (ENABLE_ASH_EXPAND_PRMT) {
2410 free((char*)cmdedit_prompt);
2411 cmdedit_prompt = ckstrdup(s);
2418 putprompt(const char *s)
2424 #if ENABLE_ASH_EXPAND_PRMT
2425 /* expandstr() needs parsing machinery, so it is far away ahead... */
2426 static const char *expandstr(const char *ps);
2428 #define expandstr(s) s
2432 setprompt_if(smallint do_set, int whichprompt)
2435 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2442 switch (whichprompt) {
2452 #if ENABLE_ASH_EXPAND_PRMT
2453 setstackmark(&smark);
2454 stalloc(stackblocksize());
2456 putprompt(expandstr(prompt));
2457 #if ENABLE_ASH_EXPAND_PRMT
2458 popstackmark(&smark);
2463 /* ============ The cd and pwd commands */
2465 #define CD_PHYSICAL 1
2475 while ((i = nextopt("LP")) != '\0') {
2477 flags ^= CD_PHYSICAL;
2486 * Update curdir (the name of the current directory) in response to a
2490 updatepwd(const char *dir)
2497 cdcomppath = ststrdup(dir);
2500 if (curdir == nullstr)
2502 new = stack_putstr(curdir, new);
2504 new = makestrspace(strlen(dir) + 2, new);
2505 lim = (char *)stackblock() + 1;
2509 if (new > lim && *lim == '/')
2514 if (dir[1] == '/' && dir[2] != '/') {
2520 p = strtok(cdcomppath, "/");
2524 if (p[1] == '.' && p[2] == '\0') {
2536 new = stack_putstr(p, new);
2544 return stackblock();
2548 * Find out what the current directory is. If we already know the current
2549 * directory, this routine returns immediately.
2554 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2555 return dir ? dir : nullstr;
2559 setpwd(const char *val, int setold)
2563 oldcur = dir = curdir;
2566 setvar("OLDPWD", oldcur, VEXPORT);
2569 if (physdir != nullstr) {
2570 if (physdir != oldcur)
2574 if (oldcur == val || !val) {
2580 dir = ckstrdup(val);
2581 if (oldcur != dir && oldcur != nullstr) {
2586 setvar("PWD", dir, VEXPORT);
2589 static void hashcd(void);
2592 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2593 * know that the current directory has changed.
2596 docd(const char *dest, int flags)
2598 const char *dir = NULL;
2601 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2604 if (!(flags & CD_PHYSICAL)) {
2605 dir = updatepwd(dest);
2619 static int FAST_FUNC
2620 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2632 dest = bltinlookup("HOME");
2633 else if (LONE_DASH(dest)) {
2634 dest = bltinlookup("OLDPWD");
2656 path = bltinlookup("CDPATH");
2665 p = path_advance(&path, dest);
2666 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2670 if (!docd(p, flags))
2675 ash_msg_and_raise_error("can't cd to %s", dest);
2678 if (flags & CD_PRINT)
2679 out1fmt("%s\n", curdir);
2683 static int FAST_FUNC
2684 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2687 const char *dir = curdir;
2691 if (physdir == nullstr)
2695 out1fmt("%s\n", dir);
2700 /* ============ ... */
2703 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2705 /* Syntax classes */
2706 #define CWORD 0 /* character is nothing special */
2707 #define CNL 1 /* newline character */
2708 #define CBACK 2 /* a backslash character */
2709 #define CSQUOTE 3 /* single quote */
2710 #define CDQUOTE 4 /* double quote */
2711 #define CENDQUOTE 5 /* a terminating quote */
2712 #define CBQUOTE 6 /* backwards single quote */
2713 #define CVAR 7 /* a dollar sign */
2714 #define CENDVAR 8 /* a '}' character */
2715 #define CLP 9 /* a left paren in arithmetic */
2716 #define CRP 10 /* a right paren in arithmetic */
2717 #define CENDFILE 11 /* end of file */
2718 #define CCTL 12 /* like CWORD, except it must be escaped */
2719 #define CSPCL 13 /* these terminate a word */
2720 #define CIGN 14 /* character should be ignored */
2723 #if ENABLE_ASH_ALIAS
2727 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2729 #if ENABLE_SH_MATH_SUPPORT
2730 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2732 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2734 static const uint16_t S_I_T[] = {
2735 #if ENABLE_ASH_ALIAS
2736 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2738 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2739 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2740 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2741 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2742 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2743 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2744 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2745 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2746 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2747 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2748 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2749 #if !USE_SIT_FUNCTION
2750 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2751 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2752 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2756 /* Constants below must match table above */
2758 #if ENABLE_ASH_ALIAS
2759 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2761 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2762 CNL_CNL_CNL_CNL , /* 2 */
2763 CWORD_CCTL_CCTL_CWORD , /* 3 */
2764 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2765 CVAR_CVAR_CWORD_CVAR , /* 5 */
2766 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2767 CSPCL_CWORD_CWORD_CLP , /* 7 */
2768 CSPCL_CWORD_CWORD_CRP , /* 8 */
2769 CBACK_CBACK_CCTL_CBACK , /* 9 */
2770 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2771 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2772 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2773 CWORD_CWORD_CWORD_CWORD , /* 13 */
2774 CCTL_CCTL_CCTL_CCTL , /* 14 */
2777 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2778 * caller must ensure proper cast on it if c is *char_ptr!
2780 /* Values for syntax param */
2781 #define BASESYNTAX 0 /* not in quotes */
2782 #define DQSYNTAX 1 /* in double quotes */
2783 #define SQSYNTAX 2 /* in single quotes */
2784 #define ARISYNTAX 3 /* in arithmetic */
2785 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2787 #if USE_SIT_FUNCTION
2790 SIT(int c, int syntax)
2792 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2793 # if ENABLE_ASH_ALIAS
2794 static const uint8_t syntax_index_table[] ALIGN1 = {
2795 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2796 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2797 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2801 static const uint8_t syntax_index_table[] ALIGN1 = {
2802 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2803 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2804 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2813 # if ENABLE_ASH_ALIAS
2819 /* Cast is purely for paranoia here,
2820 * just in case someone passed signed char to us */
2821 if ((unsigned char)c >= CTL_FIRST
2822 && (unsigned char)c <= CTL_LAST
2826 s = strchrnul(spec_symbls, c);
2829 indx = syntax_index_table[s - spec_symbls];
2831 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2834 #else /* !USE_SIT_FUNCTION */
2836 static const uint8_t syntax_index_table[] = {
2837 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2838 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2848 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2849 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2871 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2872 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2873 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2874 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2875 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2876 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2877 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2878 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2879 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2880 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2881 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2883 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2884 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2885 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2886 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2887 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2888 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2889 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2890 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2891 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2897 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2898 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2899 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2900 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2901 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2902 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2904 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2905 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2930 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2931 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2932 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2935 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2963 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2964 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2965 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2966 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2968 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2969 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2970 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2971 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2972 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2973 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2974 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2975 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3094 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3095 # if ENABLE_ASH_ALIAS
3096 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3100 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3102 #endif /* !USE_SIT_FUNCTION */
3105 /* ============ Alias handling */
3107 #if ENABLE_ASH_ALIAS
3109 #define ALIASINUSE 1
3120 static struct alias **atab; // [ATABSIZE];
3121 #define INIT_G_alias() do { \
3122 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3126 static struct alias **
3127 __lookupalias(const char *name) {
3128 unsigned int hashval;
3135 ch = (unsigned char)*p;
3139 ch = (unsigned char)*++p;
3141 app = &atab[hashval % ATABSIZE];
3143 for (; *app; app = &(*app)->next) {
3144 if (strcmp(name, (*app)->name) == 0) {
3152 static struct alias *
3153 lookupalias(const char *name, int check)
3155 struct alias *ap = *__lookupalias(name);
3157 if (check && ap && (ap->flag & ALIASINUSE))
3162 static struct alias *
3163 freealias(struct alias *ap)
3167 if (ap->flag & ALIASINUSE) {
3168 ap->flag |= ALIASDEAD;
3180 setalias(const char *name, const char *val)
3182 struct alias *ap, **app;
3184 app = __lookupalias(name);
3188 if (!(ap->flag & ALIASINUSE)) {
3191 ap->val = ckstrdup(val);
3192 ap->flag &= ~ALIASDEAD;
3195 ap = ckzalloc(sizeof(struct alias));
3196 ap->name = ckstrdup(name);
3197 ap->val = ckstrdup(val);
3198 /*ap->flag = 0; - ckzalloc did it */
3199 /*ap->next = NULL;*/
3206 unalias(const char *name)
3210 app = __lookupalias(name);
3214 *app = freealias(*app);
3225 struct alias *ap, **app;
3229 for (i = 0; i < ATABSIZE; i++) {
3231 for (ap = *app; ap; ap = *app) {
3232 *app = freealias(*app);
3242 printalias(const struct alias *ap)
3244 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3248 * TODO - sort output
3250 static int FAST_FUNC
3251 aliascmd(int argc UNUSED_PARAM, char **argv)
3260 for (i = 0; i < ATABSIZE; i++) {
3261 for (ap = atab[i]; ap; ap = ap->next) {
3267 while ((n = *++argv) != NULL) {
3268 v = strchr(n+1, '=');
3269 if (v == NULL) { /* n+1: funny ksh stuff */
3270 ap = *__lookupalias(n);
3272 fprintf(stderr, "%s: %s not found\n", "alias", n);
3285 static int FAST_FUNC
3286 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3290 while ((i = nextopt("a")) != '\0') {
3296 for (i = 0; *argptr; argptr++) {
3297 if (unalias(*argptr)) {
3298 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3306 #endif /* ASH_ALIAS */
3309 /* ============ jobs.c */
3311 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3314 #define FORK_NOJOB 2
3316 /* mode flags for showjob(s) */
3317 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3318 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3319 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3322 * A job structure contains information about a job. A job is either a
3323 * single process or a set of processes contained in a pipeline. In the
3324 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3328 pid_t ps_pid; /* process id */
3329 int ps_status; /* last process status from wait() */
3330 char *ps_cmd; /* text of command being run */
3334 struct procstat ps0; /* status of process */
3335 struct procstat *ps; /* status or processes when more than one */
3337 int stopstatus; /* status of a stopped job */
3340 nprocs: 16, /* number of processes */
3342 #define JOBRUNNING 0 /* at least one proc running */
3343 #define JOBSTOPPED 1 /* all procs are stopped */
3344 #define JOBDONE 2 /* all procs are completed */
3346 sigint: 1, /* job was killed by SIGINT */
3347 jobctl: 1, /* job running under job control */
3349 waited: 1, /* true if this entry has been waited for */
3350 used: 1, /* true if this entry is in used */
3351 changed: 1; /* true if status has changed */
3352 struct job *prev_job; /* previous job */
3355 static struct job *makejob(/*union node *,*/ int);
3356 static int forkshell(struct job *, union node *, int);
3357 static int waitforjob(struct job *);
3360 enum { doing_jobctl = 0 };
3361 #define setjobctl(on) do {} while (0)
3363 static smallint doing_jobctl; //references:8
3364 static void setjobctl(int);
3371 ignoresig(int signo)
3373 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3374 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3375 /* No, need to do it */
3376 signal(signo, SIG_IGN);
3378 sigmode[signo - 1] = S_HARD_IGN;
3382 * Only one usage site - in setsignal()
3385 signal_handler(int signo)
3387 gotsig[signo - 1] = 1;
3389 if (signo == SIGINT && !trap[SIGINT]) {
3390 if (!suppress_int) {
3392 raise_interrupt(); /* does not return */
3396 pending_sig = signo;
3401 * Set the signal handler for the specified signal. The routine figures
3402 * out what it should be set to.
3405 setsignal(int signo)
3408 char cur_act, new_act;
3409 struct sigaction act;
3413 if (t != NULL) { /* trap for this sig is set */
3415 if (t[0] == '\0') /* trap is "": ignore this sig */
3419 if (rootshell && new_act == S_DFL) {
3422 if (iflag || minusc || sflag == 0)
3431 * "In all cases, bash ignores SIGQUIT. Non-builtin
3432 * commands run by bash have signal handlers
3433 * set to the values inherited by the shell
3434 * from its parent". */
3450 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3451 //whereas we have to restore it to what shell got on entry
3452 //from the parent. See comment above
3454 t = &sigmode[signo - 1];
3457 /* current setting is not yet known */
3458 if (sigaction(signo, NULL, &act)) {
3459 /* pretend it worked; maybe we should give a warning,
3460 * but other shells don't. We don't alter sigmode,
3461 * so we retry every time.
3462 * btw, in Linux it never fails. --vda */
3465 if (act.sa_handler == SIG_IGN) {
3466 cur_act = S_HARD_IGN;
3468 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3470 cur_act = S_IGN; /* don't hard ignore these */
3474 if (cur_act == S_HARD_IGN || cur_act == new_act)
3477 act.sa_handler = SIG_DFL;
3480 act.sa_handler = signal_handler;
3483 act.sa_handler = SIG_IGN;
3487 /* flags and mask matter only if !DFL and !IGN, but we do it
3488 * for all cases for more deterministic behavior:
3491 sigfillset(&act.sa_mask);
3493 sigaction_set(signo, &act);
3498 /* mode flags for set_curjob */
3499 #define CUR_DELETE 2
3500 #define CUR_RUNNING 1
3501 #define CUR_STOPPED 0
3503 /* mode flags for dowait */
3504 #define DOWAIT_NONBLOCK WNOHANG
3505 #define DOWAIT_BLOCK 0
3508 /* pgrp of shell on invocation */
3509 static int initialpgrp; //references:2
3510 static int ttyfd = -1; //5
3513 static struct job *jobtab; //5
3515 static unsigned njobs; //4
3517 static struct job *curjob; //lots
3518 /* number of presumed living untracked jobs */
3519 static int jobless; //4
3522 set_curjob(struct job *jp, unsigned mode)
3525 struct job **jpp, **curp;
3527 /* first remove from list */
3528 jpp = curp = &curjob;
3533 jpp = &jp1->prev_job;
3535 *jpp = jp1->prev_job;
3537 /* Then re-insert in correct position */
3545 /* job being deleted */
3548 /* newly created job or backgrounded job,
3549 * put after all stopped jobs.
3554 if (!jp1 || jp1->state != JOBSTOPPED)
3557 jpp = &jp1->prev_job;
3563 /* newly stopped job - becomes curjob */
3564 jp->prev_job = *jpp;
3572 jobno(const struct job *jp)
3574 return jp - jobtab + 1;
3579 * Convert a job name to a job structure.
3582 #define getjob(name, getctl) getjob(name)
3585 getjob(const char *name, int getctl)
3589 const char *err_msg = "%s: no such job";
3593 char *(*match)(const char *, const char *);
3608 if (c == '+' || c == '%') {
3610 err_msg = "No current job";
3616 err_msg = "No previous job";
3627 jp = jobtab + num - 1;
3642 if (match(jp->ps[0].ps_cmd, p)) {
3646 err_msg = "%s: ambiguous";
3656 err_msg = "job %s not created under job control";
3657 if (getctl && jp->jobctl == 0)
3662 ash_msg_and_raise_error(err_msg, name);
3666 * Mark a job structure as unused.
3669 freejob(struct job *jp)
3671 struct procstat *ps;
3675 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3676 if (ps->ps_cmd != nullstr)
3679 if (jp->ps != &jp->ps0)
3682 set_curjob(jp, CUR_DELETE);
3688 xtcsetpgrp(int fd, pid_t pgrp)
3690 if (tcsetpgrp(fd, pgrp))
3691 ash_msg_and_raise_error("can't set tty process group (%m)");
3695 * Turn job control on and off.
3697 * Note: This code assumes that the third arg to ioctl is a character
3698 * pointer, which is true on Berkeley systems but not System V. Since
3699 * System V doesn't have job control yet, this isn't a problem now.
3701 * Called with interrupts off.
3709 if (on == doing_jobctl || rootshell == 0)
3713 ofd = fd = open(_PATH_TTY, O_RDWR);
3715 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3716 * That sometimes helps to acquire controlling tty.
3717 * Obviously, a workaround for bugs when someone
3718 * failed to provide a controlling tty to bash! :) */
3724 fd = fcntl(fd, F_DUPFD, 10);
3729 /* fd is a tty at this point */
3730 close_on_exec_on(fd);
3731 while (1) { /* while we are in the background */
3732 pgrp = tcgetpgrp(fd);
3735 ash_msg("can't access tty; job control turned off");
3739 if (pgrp == getpgrp())
3750 xtcsetpgrp(fd, pgrp);
3752 /* turning job control off */
3755 /* was xtcsetpgrp, but this can make exiting ash
3756 * loop forever if pty is already deleted */
3757 tcsetpgrp(fd, pgrp);
3771 static int FAST_FUNC
3772 killcmd(int argc, char **argv)
3774 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3777 if (argv[i][0] == '%') {
3779 * "kill %N" - job kill
3780 * Converting to pgrp / pid kill
3786 jp = getjob(argv[i], 0);
3788 * In jobs started under job control, we signal
3789 * entire process group by kill -PGRP_ID.
3790 * This happens, f.e., in interactive shell.
3792 * Otherwise, we signal each child via
3793 * kill PID1 PID2 PID3.
3795 * sh -c 'sleep 1|sleep 1 & kill %1'
3796 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3797 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3799 n = jp->nprocs; /* can't be 0 (I hope) */
3802 dst = alloca(n * sizeof(int)*4);
3804 for (j = 0; j < n; j++) {
3805 struct procstat *ps = &jp->ps[j];
3806 /* Skip non-running and not-stopped members
3807 * (i.e. dead members) of the job
3809 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3812 * kill_main has matching code to expect
3813 * leading space. Needed to not confuse
3814 * negative pids with "kill -SIGNAL_NO" syntax
3816 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3820 } while (argv[++i]);
3822 return kill_main(argc, argv);
3826 showpipe(struct job *jp /*, FILE *out*/)
3828 struct procstat *ps;
3829 struct procstat *psend;
3831 psend = jp->ps + jp->nprocs;
3832 for (ps = jp->ps + 1; ps < psend; ps++)
3833 printf(" | %s", ps->ps_cmd);
3834 outcslow('\n', stdout);
3835 flush_stdout_stderr();
3840 restartjob(struct job *jp, int mode)
3842 struct procstat *ps;
3848 if (jp->state == JOBDONE)
3850 jp->state = JOBRUNNING;
3851 pgid = jp->ps[0].ps_pid;
3852 if (mode == FORK_FG)
3853 xtcsetpgrp(ttyfd, pgid);
3854 killpg(pgid, SIGCONT);
3858 if (WIFSTOPPED(ps->ps_status)) {
3864 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3869 static int FAST_FUNC
3870 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3876 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3880 jp = getjob(*argv, 1);
3881 if (mode == FORK_BG) {
3882 set_curjob(jp, CUR_RUNNING);
3883 printf("[%d] ", jobno(jp));
3885 out1str(jp->ps[0].ps_cmd);
3886 showpipe(jp /*, stdout*/);
3887 retval = restartjob(jp, mode);
3888 } while (*argv && *++argv);
3894 sprint_status(char *s, int status, int sigonly)
3900 if (!WIFEXITED(status)) {
3902 if (WIFSTOPPED(status))
3903 st = WSTOPSIG(status);
3906 st = WTERMSIG(status);
3908 if (st == SIGINT || st == SIGPIPE)
3911 if (WIFSTOPPED(status))
3916 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3917 col = fmtstr(s, 32, strsignal(st));
3918 if (WCOREDUMP(status)) {
3919 col += fmtstr(s + col, 16, " (core dumped)");
3921 } else if (!sigonly) {
3922 st = WEXITSTATUS(status);
3924 col = fmtstr(s, 16, "Done(%d)", st);
3926 col = fmtstr(s, 16, "Done");
3933 dowait(int wait_flags, struct job *job)
3938 struct job *thisjob;
3941 TRACE(("dowait(0x%x) called\n", wait_flags));
3943 /* Do a wait system call. If job control is compiled in, we accept
3944 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3945 * NB: _not_ safe_waitpid, we need to detect EINTR */
3947 wait_flags |= WUNTRACED;
3948 pid = waitpid(-1, &status, wait_flags);
3949 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3950 pid, status, errno, strerror(errno)));
3956 for (jp = curjob; jp; jp = jp->prev_job) {
3957 struct procstat *ps;
3958 struct procstat *psend;
3959 if (jp->state == JOBDONE)
3963 psend = ps + jp->nprocs;
3965 if (ps->ps_pid == pid) {
3966 TRACE(("Job %d: changing status of proc %d "
3967 "from 0x%x to 0x%x\n",
3968 jobno(jp), pid, ps->ps_status, status));
3969 ps->ps_status = status;
3972 if (ps->ps_status == -1)
3975 if (state == JOBRUNNING)
3977 if (WIFSTOPPED(ps->ps_status)) {
3978 jp->stopstatus = ps->ps_status;
3982 } while (++ps < psend);
3987 if (!WIFSTOPPED(status))
3993 if (state != JOBRUNNING) {
3994 thisjob->changed = 1;
3996 if (thisjob->state != state) {
3997 TRACE(("Job %d: changing state from %d to %d\n",
3998 jobno(thisjob), thisjob->state, state));
3999 thisjob->state = state;
4001 if (state == JOBSTOPPED) {
4002 set_curjob(thisjob, CUR_STOPPED);
4011 if (thisjob && thisjob == job) {
4015 len = sprint_status(s, status, 1);
4026 blocking_wait_with_raise_on_sig(void)
4028 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4029 if (pid <= 0 && pending_sig)
4030 raise_exception(EXSIG);
4036 showjob(FILE *out, struct job *jp, int mode)
4038 struct procstat *ps;
4039 struct procstat *psend;
4046 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4047 /* just output process (group) id of pipeline */
4048 fprintf(out, "%d\n", ps->ps_pid);
4052 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4057 else if (curjob && jp == curjob->prev_job)
4060 if (mode & SHOW_PIDS)
4061 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4063 psend = ps + jp->nprocs;
4065 if (jp->state == JOBRUNNING) {
4066 strcpy(s + col, "Running");
4067 col += sizeof("Running") - 1;
4069 int status = psend[-1].ps_status;
4070 if (jp->state == JOBSTOPPED)
4071 status = jp->stopstatus;
4072 col += sprint_status(s + col, status, 0);
4074 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4076 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4077 * or prints several "PID | <cmdN>" lines,
4078 * depending on SHOW_PIDS bit.
4079 * We do not print status of individual processes
4080 * between PID and <cmdN>. bash does it, but not very well:
4081 * first line shows overall job status, not process status,
4082 * making it impossible to know 1st process status.
4086 /* for each process */
4089 if (mode & SHOW_PIDS)
4090 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4092 fprintf(out, "%s%*c%s%s",
4094 33 - col >= 0 ? 33 - col : 0, ' ',
4095 ps == jp->ps ? "" : "| ",
4098 } while (++ps != psend);
4099 outcslow('\n', out);
4103 if (jp->state == JOBDONE) {
4104 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4110 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4111 * statuses have changed since the last call to showjobs.
4114 showjobs(FILE *out, int mode)
4118 TRACE(("showjobs(0x%x) called\n", mode));
4120 /* Handle all finished jobs */
4121 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4124 for (jp = curjob; jp; jp = jp->prev_job) {
4125 if (!(mode & SHOW_CHANGED) || jp->changed) {
4126 showjob(out, jp, mode);
4131 static int FAST_FUNC
4132 jobscmd(int argc UNUSED_PARAM, char **argv)
4137 while ((m = nextopt("lp")) != '\0') {
4141 mode |= SHOW_ONLY_PGID;
4147 showjob(stdout, getjob(*argv, 0), mode);
4150 showjobs(stdout, mode);
4157 /* Called only on finished or stopped jobs (no members are running) */
4159 getstatus(struct job *job)
4163 struct procstat *ps;
4165 /* Fetch last member's status */
4166 ps = job->ps + job->nprocs - 1;
4167 status = ps->ps_status;
4169 /* "set -o pipefail" mode: use last _nonzero_ status */
4170 while (status == 0 && --ps >= job->ps)
4171 status = ps->ps_status;
4174 retval = WEXITSTATUS(status);
4175 if (!WIFEXITED(status)) {
4177 retval = WSTOPSIG(status);
4178 if (!WIFSTOPPED(status))
4181 /* XXX: limits number of signals */
4182 retval = WTERMSIG(status);
4184 if (retval == SIGINT)
4190 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4191 jobno(job), job->nprocs, status, retval));
4195 static int FAST_FUNC
4196 waitcmd(int argc UNUSED_PARAM, char **argv)
4203 raise_exception(EXSIG);
4210 /* wait for all jobs */
4214 if (!jp) /* no running procs */
4216 if (jp->state == JOBRUNNING)
4221 blocking_wait_with_raise_on_sig();
4223 * "When bash is waiting for an asynchronous command via
4224 * the wait builtin, the reception of a signal for which a trap
4225 * has been set will cause the wait builtin to return immediately
4226 * with an exit status greater than 128, immediately after which
4227 * the trap is executed."
4229 * blocking_wait_with_raise_on_sig raises signal handlers
4230 * if it gets no pid (pid < 0). However,
4231 * if child sends us a signal *and immediately exits*,
4232 * blocking_wait_with_raise_on_sig gets pid > 0
4233 * and does not handle pending_sig. Check this case: */
4235 raise_exception(EXSIG);
4241 if (**argv != '%') {
4242 pid_t pid = number(*argv);
4247 if (job->ps[job->nprocs - 1].ps_pid == pid)
4249 job = job->prev_job;
4252 job = getjob(*argv, 0);
4254 /* loop until process terminated or stopped */
4255 while (job->state == JOBRUNNING)
4256 blocking_wait_with_raise_on_sig();
4258 retval = getstatus(job);
4271 struct job *jp, *jq;
4273 len = njobs * sizeof(*jp);
4275 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4277 offset = (char *)jp - (char *)jq;
4279 /* Relocate pointers */
4282 jq = (struct job *)((char *)jq + l);
4286 #define joff(p) ((struct job *)((char *)(p) + l))
4287 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4288 if (joff(jp)->ps == &jq->ps0)
4289 jmove(joff(jp)->ps);
4290 if (joff(jp)->prev_job)
4291 jmove(joff(jp)->prev_job);
4301 jp = (struct job *)((char *)jp + len);
4305 } while (--jq >= jp);
4310 * Return a new job structure.
4311 * Called with interrupts off.
4314 makejob(/*union node *node,*/ int nprocs)
4319 for (i = njobs, jp = jobtab; ; jp++) {
4326 if (jp->state != JOBDONE || !jp->waited)
4335 memset(jp, 0, sizeof(*jp));
4337 /* jp->jobctl is a bitfield.
4338 * "jp->jobctl |= jobctl" likely to give awful code */
4342 jp->prev_job = curjob;
4347 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4349 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4356 * Return a string identifying a command (to be printed by the
4359 static char *cmdnextc;
4362 cmdputs(const char *s)
4364 static const char vstype[VSTYPE + 1][3] = {
4365 "", "}", "-", "+", "?", "=",
4366 "%", "%%", "#", "##"
4367 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4370 const char *p, *str;
4374 unsigned char subtype = 0;
4378 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4380 while ((c = *p++) != '\0') {
4388 if ((subtype & VSTYPE) == VSLENGTH)
4392 if (!(subtype & VSQUOTE) == !(quoted & 1))
4398 str = "\"}" + !(quoted & 1);
4405 case CTLBACKQ+CTLQUOTE:
4408 #if ENABLE_SH_MATH_SUPPORT
4423 if ((subtype & VSTYPE) != VSNORMAL)
4425 str = vstype[subtype & VSTYPE];
4426 if (subtype & VSNUL)
4435 /* These can only happen inside quotes */
4448 while ((c = *str++) != '\0') {
4451 } /* while *p++ not NUL */
4454 USTPUTC('"', nextc);
4460 /* cmdtxt() and cmdlist() call each other */
4461 static void cmdtxt(union node *n);
4464 cmdlist(union node *np, int sep)
4466 for (; np; np = np->narg.next) {
4470 if (sep && np->narg.next)
4476 cmdtxt(union node *n)
4479 struct nodelist *lp;
4490 lp = n->npipe.cmdlist;
4508 cmdtxt(n->nbinary.ch1);
4524 cmdtxt(n->nif.test);
4526 if (n->nif.elsepart) {
4527 cmdtxt(n->nif.ifpart);
4529 n = n->nif.elsepart;
4547 cmdtxt(n->nbinary.ch1);
4557 cmdputs(n->nfor.var);
4559 cmdlist(n->nfor.args, 1);
4564 cmdputs(n->narg.text);
4568 cmdlist(n->ncmd.args, 1);
4569 cmdlist(n->ncmd.redirect, 0);
4582 cmdputs(n->ncase.expr->narg.text);
4584 for (np = n->ncase.cases; np; np = np->nclist.next) {
4585 cmdtxt(np->nclist.pattern);
4587 cmdtxt(np->nclist.body);
4601 #if ENABLE_ASH_BASH_COMPAT
4616 cmdputs(utoa(n->nfile.fd));
4618 if (n->type == NTOFD || n->type == NFROMFD) {
4619 cmdputs(utoa(n->ndup.dupfd));
4628 commandtext(union node *n)
4632 STARTSTACKSTR(cmdnextc);
4634 name = stackblock();
4635 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4636 name, cmdnextc, cmdnextc));
4637 return ckstrdup(name);
4642 * Fork off a subshell. If we are doing job control, give the subshell its
4643 * own process group. Jp is a job structure that the job is to be added to.
4644 * N is the command that will be evaluated by the child. Both jp and n may
4645 * be NULL. The mode parameter can be one of the following:
4646 * FORK_FG - Fork off a foreground process.
4647 * FORK_BG - Fork off a background process.
4648 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4649 * process group even if job control is on.
4651 * When job control is turned off, background processes have their standard
4652 * input redirected to /dev/null (except for the second and later processes
4655 * Called with interrupts off.
4658 * Clear traps on a fork.
4665 for (tp = trap; tp < &trap[NSIG]; tp++) {
4666 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4668 if (trap_ptr == trap)
4670 /* else: it "belongs" to trap_ptr vector, don't free */
4672 if ((tp - trap) != 0)
4673 setsignal(tp - trap);
4680 /* Lives far away from here, needed for forkchild */
4681 static void closescript(void);
4683 /* Called after fork(), in child */
4684 static NOINLINE void
4685 forkchild(struct job *jp, union node *n, int mode)
4689 TRACE(("Child shell %d\n", getpid()));
4693 /* man bash: "Non-builtin commands run by bash have signal handlers
4694 * set to the values inherited by the shell from its parent".
4695 * Do we do it correctly? */
4699 if (mode == FORK_NOJOB /* is it `xxx` ? */
4700 && n && n->type == NCMD /* is it single cmd? */
4701 /* && n->ncmd.args->type == NARG - always true? */
4702 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4703 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4704 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4706 TRACE(("Trap hack\n"));
4707 /* Awful hack for `trap` or $(trap).
4709 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4710 * contains an example where "trap" is executed in a subshell:
4712 * save_traps=$(trap)
4714 * eval "$save_traps"
4716 * Standard does not say that "trap" in subshell shall print
4717 * parent shell's traps. It only says that its output
4718 * must have suitable form, but then, in the above example
4719 * (which is not supposed to be normative), it implies that.
4721 * bash (and probably other shell) does implement it
4722 * (traps are reset to defaults, but "trap" still shows them),
4723 * but as a result, "trap" logic is hopelessly messed up:
4726 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4727 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4728 * # true | trap <--- trap is in subshell - no output (ditto)
4729 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4730 * trap -- 'echo Ho' SIGWINCH
4731 * # echo `(trap)` <--- in subshell in subshell - output
4732 * trap -- 'echo Ho' SIGWINCH
4733 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4734 * trap -- 'echo Ho' SIGWINCH
4736 * The rules when to forget and when to not forget traps
4737 * get really complex and nonsensical.
4739 * Our solution: ONLY bare $(trap) or `trap` is special.
4741 /* Save trap handler strings for trap builtin to print */
4742 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4743 /* Fall through into clearing traps */
4747 /* do job control only in root shell */
4749 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4752 if (jp->nprocs == 0)
4755 pgrp = jp->ps[0].ps_pid;
4756 /* this can fail because we are doing it in the parent also */
4758 if (mode == FORK_FG)
4759 xtcsetpgrp(ttyfd, pgrp);
4764 if (mode == FORK_BG) {
4765 /* man bash: "When job control is not in effect,
4766 * asynchronous commands ignore SIGINT and SIGQUIT" */
4769 if (jp->nprocs == 0) {
4771 if (open(bb_dev_null, O_RDONLY) != 0)
4772 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4776 if (iflag) { /* why if iflag only? */
4781 * "In all cases, bash ignores SIGQUIT. Non-builtin
4782 * commands run by bash have signal handlers
4783 * set to the values inherited by the shell
4785 * Take care of the second rule: */
4789 if (n && n->type == NCMD
4790 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4792 TRACE(("Job hack\n"));
4793 /* "jobs": we do not want to clear job list for it,
4794 * instead we remove only _its_ own_ job from job list.
4795 * This makes "jobs .... | cat" more useful.
4801 for (jp = curjob; jp; jp = jp->prev_job)
4806 /* Called after fork(), in parent */
4808 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4811 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4813 TRACE(("In parent shell: child = %d\n", pid));
4815 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4821 if (mode != FORK_NOJOB && jp->jobctl) {
4824 if (jp->nprocs == 0)
4827 pgrp = jp->ps[0].ps_pid;
4828 /* This can fail because we are doing it in the child also */
4832 if (mode == FORK_BG) {
4833 backgndpid = pid; /* set $! */
4834 set_curjob(jp, CUR_RUNNING);
4837 struct procstat *ps = &jp->ps[jp->nprocs++];
4840 ps->ps_cmd = nullstr;
4842 if (doing_jobctl && n)
4843 ps->ps_cmd = commandtext(n);
4849 forkshell(struct job *jp, union node *n, int mode)
4853 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4856 TRACE(("Fork failed, errno=%d", errno));
4859 ash_msg_and_raise_error("can't fork");
4862 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4863 forkchild(jp, n, mode);
4865 forkparent(jp, n, mode, pid);
4871 * Wait for job to finish.
4873 * Under job control we have the problem that while a child process
4874 * is running interrupts generated by the user are sent to the child
4875 * but not to the shell. This means that an infinite loop started by
4876 * an interactive user may be hard to kill. With job control turned off,
4877 * an interactive user may place an interactive program inside a loop.
4878 * If the interactive program catches interrupts, the user doesn't want
4879 * these interrupts to also abort the loop. The approach we take here
4880 * is to have the shell ignore interrupt signals while waiting for a
4881 * foreground process to terminate, and then send itself an interrupt
4882 * signal if the child process was terminated by an interrupt signal.
4883 * Unfortunately, some programs want to do a bit of cleanup and then
4884 * exit on interrupt; unless these processes terminate themselves by
4885 * sending a signal to themselves (instead of calling exit) they will
4886 * confuse this approach.
4888 * Called with interrupts off.
4891 waitforjob(struct job *jp)
4895 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4898 while (jp->state == JOBRUNNING) {
4899 /* In non-interactive shells, we _can_ get
4900 * a keyboard signal here and be EINTRed,
4901 * but we just loop back, waiting for command to complete.
4904 * "If bash is waiting for a command to complete and receives
4905 * a signal for which a trap has been set, the trap
4906 * will not be executed until the command completes."
4908 * Reality is that even if trap is not set, bash
4909 * will not act on the signal until command completes.
4910 * Try this. sleep5intoff.c:
4911 * #include <signal.h>
4912 * #include <unistd.h>
4915 * sigemptyset(&set);
4916 * sigaddset(&set, SIGINT);
4917 * sigaddset(&set, SIGQUIT);
4918 * sigprocmask(SIG_BLOCK, &set, NULL);
4922 * $ bash -c './sleep5intoff; echo hi'
4923 * ^C^C^C^C <--- pressing ^C once a second
4925 * $ bash -c './sleep5intoff; echo hi'
4926 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4929 dowait(DOWAIT_BLOCK, jp);
4936 xtcsetpgrp(ttyfd, rootpid);
4938 * This is truly gross.
4939 * If we're doing job control, then we did a TIOCSPGRP which
4940 * caused us (the shell) to no longer be in the controlling
4941 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4942 * intuit from the subprocess exit status whether a SIGINT
4943 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4945 if (jp->sigint) /* TODO: do the same with all signals */
4946 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4948 if (jp->state == JOBDONE)
4955 * return 1 if there are stopped jobs, otherwise 0
4967 if (jp && jp->state == JOBSTOPPED) {
4968 out2str("You have stopped jobs.\n");
4977 /* ============ redir.c
4979 * Code for dealing with input/output redirection.
4984 #define EMPTY -2 /* marks an unused slot in redirtab */
4985 #define CLOSED -3 /* marks a slot of previously-closed fd */
4988 * Open a file in noclobber mode.
4989 * The code was copied from bash.
4992 noclobberopen(const char *fname)
4995 struct stat finfo, finfo2;
4998 * If the file exists and is a regular file, return an error
5001 r = stat(fname, &finfo);
5002 if (r == 0 && S_ISREG(finfo.st_mode)) {
5008 * If the file was not present (r != 0), make sure we open it
5009 * exclusively so that if it is created before we open it, our open
5010 * will fail. Make sure that we do not truncate an existing file.
5011 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5012 * file was not a regular file, we leave O_EXCL off.
5015 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5016 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5018 /* If the open failed, return the file descriptor right away. */
5023 * OK, the open succeeded, but the file may have been changed from a
5024 * non-regular file to a regular file between the stat and the open.
5025 * We are assuming that the O_EXCL open handles the case where FILENAME
5026 * did not exist and is symlinked to an existing file between the stat
5031 * If we can open it and fstat the file descriptor, and neither check
5032 * revealed that it was a regular file, and the file has not been
5033 * replaced, return the file descriptor.
5035 if (fstat(fd, &finfo2) == 0
5036 && !S_ISREG(finfo2.st_mode)
5037 && finfo.st_dev == finfo2.st_dev
5038 && finfo.st_ino == finfo2.st_ino
5043 /* The file has been replaced. badness. */
5050 * Handle here documents. Normally we fork off a process to write the
5051 * data to a pipe. If the document is short, we can stuff the data in
5052 * the pipe without forking.
5054 /* openhere needs this forward reference */
5055 static void expandhere(union node *arg, int fd);
5057 openhere(union node *redir)
5063 ash_msg_and_raise_error("pipe call failed");
5064 if (redir->type == NHERE) {
5065 len = strlen(redir->nhere.doc->narg.text);
5066 if (len <= PIPE_BUF) {
5067 full_write(pip[1], redir->nhere.doc->narg.text, len);
5071 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5074 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5075 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5076 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5077 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5078 signal(SIGPIPE, SIG_DFL);
5079 if (redir->type == NHERE)
5080 full_write(pip[1], redir->nhere.doc->narg.text, len);
5082 expandhere(redir->nhere.doc, pip[1]);
5083 _exit(EXIT_SUCCESS);
5091 openredirect(union node *redir)
5096 fname = redir->nfile.expfname;
5097 switch (redir->nfile.type) {
5099 f = open(fname, O_RDONLY);
5104 f = open(fname, O_RDWR|O_CREAT, 0666);
5109 #if ENABLE_ASH_BASH_COMPAT
5112 /* Take care of noclobber mode. */
5114 f = noclobberopen(fname);
5121 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5126 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5134 /* Fall through to eliminate warning. */
5135 /* Our single caller does this itself */
5142 f = openhere(redir);
5148 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5150 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5154 * Copy a file descriptor to be >= to. Returns -1
5155 * if the source file descriptor is closed, EMPTY if there are no unused
5156 * file descriptors left.
5158 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5159 * old code was doing close(to) prior to copyfd() to achieve the same */
5161 COPYFD_EXACT = (int)~(INT_MAX),
5162 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5165 copyfd(int from, int to)
5169 if (to & COPYFD_EXACT) {
5170 to &= ~COPYFD_EXACT;
5172 newfd = dup2(from, to);
5174 newfd = fcntl(from, F_DUPFD, to);
5177 if (errno == EMFILE)
5179 /* Happens when source fd is not open: try "echo >&99" */
5180 ash_msg_and_raise_error("%d: %m", from);
5185 /* Struct def and variable are moved down to the first usage site */
5190 struct redirtab *next;
5193 struct two_fd_t two_fd[];
5195 #define redirlist (G_var.redirlist)
5197 static int need_to_remember(struct redirtab *rp, int fd)
5201 if (!rp) /* remembering was not requested */
5204 for (i = 0; i < rp->pair_count; i++) {
5205 if (rp->two_fd[i].orig == fd) {
5206 /* already remembered */
5213 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5214 static int is_hidden_fd(struct redirtab *rp, int fd)
5217 struct parsefile *pf;
5221 /* Check open scripts' fds */
5224 /* We skip pf_fd == 0 case because of the following case:
5225 * $ ash # running ash interactively
5227 * and in script.sh: "exec 9>&0".
5228 * Even though top-level pf_fd _is_ 0,
5229 * it's still ok to use it: "read" builtin uses it,
5230 * why should we cripple "exec" builtin?
5232 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5240 /* Check saved fds of redirects */
5241 fd |= COPYFD_RESTORE;
5242 for (i = 0; i < rp->pair_count; i++) {
5243 if (rp->two_fd[i].copy == fd) {
5251 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5252 * old file descriptors are stashed away so that the redirection can be
5253 * undone by calling popredir.
5255 /* flags passed to redirect */
5256 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5257 #define REDIR_SAVEFD2 03 /* set preverrout */
5259 redirect(union node *redir, int flags)
5261 struct redirtab *sv;
5266 int copied_fd2 = -1;
5276 if (flags & REDIR_PUSH) {
5277 union node *tmp = redir;
5280 #if ENABLE_ASH_BASH_COMPAT
5281 if (tmp->nfile.type == NTO2)
5284 tmp = tmp->nfile.next;
5286 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5287 sv->next = redirlist;
5288 sv->pair_count = sv_pos;
5290 sv->nullredirs = g_nullredirs - 1;
5292 while (sv_pos > 0) {
5294 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5300 fd = redir->nfile.fd;
5301 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5302 right_fd = redir->ndup.dupfd;
5303 //bb_error_msg("doing %d > %d", fd, right_fd);
5304 /* redirect from/to same file descriptor? */
5307 /* "echo >&10" and 10 is a fd opened to a sh script? */
5308 if (is_hidden_fd(sv, right_fd)) {
5309 errno = EBADF; /* as if it is closed */
5310 ash_msg_and_raise_error("%d: %m", right_fd);
5314 newfd = openredirect(redir); /* always >= 0 */
5316 /* Descriptor wasn't open before redirect.
5317 * Mark it for close in the future */
5318 if (need_to_remember(sv, fd)) {
5319 goto remember_to_close;
5324 #if ENABLE_ASH_BASH_COMPAT
5327 if (need_to_remember(sv, fd)) {
5328 /* Copy old descriptor */
5329 /* Careful to not accidentally "save"
5330 * to the same fd as right side fd in N>&M */
5331 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5332 i = fcntl(fd, F_DUPFD, minfd);
5333 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5334 * are closed in popredir() in the child, preventing them from leaking
5335 * into child. (popredir() also cleans up the mess in case of failures)
5340 /* Strange error (e.g. "too many files" EMFILE?) */
5344 ash_msg_and_raise_error("%d: %m", fd);
5347 /* EBADF: it is not open - good, remember to close it */
5350 } else { /* fd is open, save its copy */
5351 /* "exec fd>&-" should not close fds
5352 * which point to script file(s).
5353 * Force them to be restored afterwards */
5354 if (is_hidden_fd(sv, fd))
5355 i |= COPYFD_RESTORE;
5359 sv->two_fd[sv_pos].orig = fd;
5360 sv->two_fd[sv_pos].copy = i;
5364 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5365 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5366 /* Don't want to trigger debugging */
5370 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5372 } else if (fd != newfd) { /* move newfd to fd */
5373 copyfd(newfd, fd | COPYFD_EXACT);
5374 #if ENABLE_ASH_BASH_COMPAT
5375 if (!(redir->nfile.type == NTO2 && fd == 2))
5379 #if ENABLE_ASH_BASH_COMPAT
5380 if (redir->nfile.type == NTO2 && fd == 1) {
5381 /* We already redirected it to fd 1, now copy it to 2 */
5387 } while ((redir = redir->nfile.next) != NULL);
5390 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5391 preverrout_fd = copied_fd2;
5395 * Undo the effects of the last redirection.
5398 popredir(int drop, int restore)
5400 struct redirtab *rp;
5403 if (--g_nullredirs >= 0)
5407 for (i = 0; i < rp->pair_count; i++) {
5408 int fd = rp->two_fd[i].orig;
5409 int copy = rp->two_fd[i].copy;
5410 if (copy == CLOSED) {
5415 if (copy != EMPTY) {
5416 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5417 copy &= ~COPYFD_RESTORE;
5419 copyfd(copy, fd | COPYFD_EXACT);
5421 close(copy & ~COPYFD_RESTORE);
5424 redirlist = rp->next;
5425 g_nullredirs = rp->nullredirs;
5431 * Undo all redirections. Called on error or interrupt.
5435 * Discard all saved file descriptors.
5438 clearredir(int drop)
5444 popredir(drop, /*restore:*/ 0);
5449 redirectsafe(union node *redir, int flags)
5452 volatile int saveint;
5453 struct jmploc *volatile savehandler = exception_handler;
5454 struct jmploc jmploc;
5457 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5458 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5460 exception_handler = &jmploc;
5461 redirect(redir, flags);
5463 exception_handler = savehandler;
5464 if (err && exception_type != EXERROR)
5465 longjmp(exception_handler->loc, 1);
5466 RESTORE_INT(saveint);
5471 /* ============ Routines to expand arguments to commands
5473 * We have to deal with backquotes, shell variables, and file metacharacters.
5476 #if ENABLE_SH_MATH_SUPPORT
5478 ash_arith(const char *s)
5480 arith_state_t math_state;
5483 math_state.lookupvar = lookupvar;
5484 math_state.setvar = setvar2;
5485 //math_state.endofname = endofname;
5488 result = arith(&math_state, s);
5489 if (math_state.errmsg)
5490 ash_msg_and_raise_error(math_state.errmsg);
5500 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5501 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5502 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5503 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5504 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5505 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5506 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5507 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5508 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5512 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5513 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5514 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5515 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5516 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5519 * Structure specifying which parts of the string should be searched
5520 * for IFS characters.
5523 struct ifsregion *next; /* next region in list */
5524 int begoff; /* offset of start of region */
5525 int endoff; /* offset of end of region */
5526 int nulonly; /* search for nul bytes only */
5530 struct strlist *list;
5531 struct strlist **lastp;
5534 /* output of current string */
5535 static char *expdest;
5536 /* list of back quote expressions */
5537 static struct nodelist *argbackq;
5538 /* first struct in list of ifs regions */
5539 static struct ifsregion ifsfirst;
5540 /* last struct in list */
5541 static struct ifsregion *ifslastp;
5542 /* holds expanded arg list */
5543 static struct arglist exparg;
5548 #if !ENABLE_SH_MATH_SUPPORT
5549 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5550 typedef long arith_t;
5551 # define ARITH_FMT "%ld"
5558 expdest = makestrspace(32, expdest);
5559 len = fmtstr(expdest, 32, ARITH_FMT, num);
5560 STADJUST(len, expdest);
5565 esclen(const char *start, const char *p)
5569 while (p > start && (unsigned char)*--p == CTLESC) {
5576 * Remove any CTLESC characters from a string.
5579 rmescapes(char *str, int flag)
5581 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5585 unsigned protect_against_glob;
5588 p = strpbrk(str, qchars);
5594 if (flag & RMESCAPE_ALLOC) {
5595 size_t len = p - str;
5596 size_t fulllen = len + strlen(p) + 1;
5598 if (flag & RMESCAPE_GROW) {
5599 int strloc = str - (char *)stackblock();
5600 r = makestrspace(fulllen, expdest);
5601 /* p and str may be invalidated by makestrspace */
5602 str = (char *)stackblock() + strloc;
5604 } else if (flag & RMESCAPE_HEAP) {
5605 r = ckmalloc(fulllen);
5607 r = stalloc(fulllen);
5611 q = (char *)memcpy(q, str, len) + len;
5615 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5616 globbing = flag & RMESCAPE_GLOB;
5617 protect_against_glob = globbing;
5619 if ((unsigned char)*p == CTLQUOTEMARK) {
5620 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5621 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5622 // Note: both inquotes and protect_against_glob only affect whether
5623 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5624 inquotes = ~inquotes;
5626 protect_against_glob = globbing;
5630 /* naked back slash */
5631 protect_against_glob = 0;
5634 if ((unsigned char)*p == CTLESC) {
5636 if (protect_against_glob && inquotes && *p != '/') {
5640 protect_against_glob = globbing;
5645 if (flag & RMESCAPE_GROW) {
5647 STADJUST(q - r + 1, expdest);
5651 #define pmatch(a, b) !fnmatch((a), (b), 0)
5654 * Prepare a pattern for a expmeta (internal glob(3)) call.
5656 * Returns an stalloced string.
5659 preglob(const char *pattern, int quoted, int flag)
5661 flag |= RMESCAPE_GLOB;
5663 flag |= RMESCAPE_QUOTED;
5665 return rmescapes((char *)pattern, flag);
5669 * Put a string on the stack.
5672 memtodest(const char *p, size_t len, int syntax, int quotes)
5676 q = makestrspace(quotes ? len * 2 : len, q);
5679 unsigned char c = *p++;
5683 int n = SIT(c, syntax);
5684 if (n == CCTL || n == CBACK)
5694 strtodest(const char *p, int syntax, int quotes)
5696 memtodest(p, strlen(p), syntax, quotes);
5700 * Record the fact that we have to scan this region of the
5701 * string for IFS characters.
5704 recordregion(int start, int end, int nulonly)
5706 struct ifsregion *ifsp;
5708 if (ifslastp == NULL) {
5712 ifsp = ckzalloc(sizeof(*ifsp));
5713 /*ifsp->next = NULL; - ckzalloc did it */
5714 ifslastp->next = ifsp;
5718 ifslastp->begoff = start;
5719 ifslastp->endoff = end;
5720 ifslastp->nulonly = nulonly;
5724 removerecordregions(int endoff)
5726 if (ifslastp == NULL)
5729 if (ifsfirst.endoff > endoff) {
5730 while (ifsfirst.next) {
5731 struct ifsregion *ifsp;
5733 ifsp = ifsfirst.next->next;
5734 free(ifsfirst.next);
5735 ifsfirst.next = ifsp;
5738 if (ifsfirst.begoff > endoff) {
5741 ifslastp = &ifsfirst;
5742 ifsfirst.endoff = endoff;
5747 ifslastp = &ifsfirst;
5748 while (ifslastp->next && ifslastp->next->begoff < endoff)
5749 ifslastp = ifslastp->next;
5750 while (ifslastp->next) {
5751 struct ifsregion *ifsp;
5753 ifsp = ifslastp->next->next;
5754 free(ifslastp->next);
5755 ifslastp->next = ifsp;
5758 if (ifslastp->endoff > endoff)
5759 ifslastp->endoff = endoff;
5763 exptilde(char *startp, char *p, int flags)
5769 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5774 while ((c = *++p) != '\0') {
5781 if (flags & EXP_VARTILDE)
5791 if (*name == '\0') {
5792 home = lookupvar("HOME");
5794 pw = getpwnam(name);
5799 if (!home || !*home)
5802 startloc = expdest - (char *)stackblock();
5803 strtodest(home, SQSYNTAX, quotes);
5804 recordregion(startloc, expdest - (char *)stackblock(), 0);
5812 * Execute a command inside back quotes. If it's a builtin command, we
5813 * want to save its output in a block obtained from malloc. Otherwise
5814 * we fork off a subprocess and get the output of the command via a pipe.
5815 * Should be called with interrupts off.
5817 struct backcmd { /* result of evalbackcmd */
5818 int fd; /* file descriptor to read from */
5819 int nleft; /* number of chars in buffer */
5820 char *buf; /* buffer */
5821 struct job *jp; /* job structure for command */
5824 /* These forward decls are needed to use "eval" code for backticks handling: */
5825 static uint8_t back_exitstatus; /* exit status of backquoted command */
5826 #define EV_EXIT 01 /* exit after evaluating tree */
5827 static void evaltree(union node *, int);
5829 static void FAST_FUNC
5830 evalbackcmd(union node *n, struct backcmd *result)
5841 saveherefd = herefd;
5849 ash_msg_and_raise_error("pipe call failed");
5850 jp = makejob(/*n,*/ 1);
5851 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5856 copyfd(pip[1], 1 | COPYFD_EXACT);
5860 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5864 result->fd = pip[0];
5867 herefd = saveherefd;
5869 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5870 result->fd, result->buf, result->nleft, result->jp));
5874 * Expand stuff in backwards quotes.
5877 expbackq(union node *cmd, int quoted, int quotes)
5885 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5886 struct stackmark smark;
5889 setstackmark(&smark);
5891 startloc = dest - (char *)stackblock();
5893 evalbackcmd(cmd, &in);
5894 popstackmark(&smark);
5901 memtodest(p, i, syntax, quotes);
5905 i = nonblock_immune_read(in.fd, buf, sizeof(buf), /*loop_on_EINTR:*/ 1);
5906 TRACE(("expbackq: read returns %d\n", i));
5915 back_exitstatus = waitforjob(in.jp);
5919 /* Eat all trailing newlines */
5921 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5926 recordregion(startloc, dest - (char *)stackblock(), 0);
5927 TRACE(("evalbackq: size:%d:'%.*s'\n",
5928 (int)((dest - (char *)stackblock()) - startloc),
5929 (int)((dest - (char *)stackblock()) - startloc),
5930 stackblock() + startloc));
5933 #if ENABLE_SH_MATH_SUPPORT
5935 * Expand arithmetic expression. Backup to start of expression,
5936 * evaluate, place result in (backed up) result, adjust string position.
5949 * This routine is slightly over-complicated for
5950 * efficiency. Next we scan backwards looking for the
5951 * start of arithmetic.
5953 start = stackblock();
5960 while ((unsigned char)*p != CTLARI) {
5964 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5969 esc = esclen(start, p);
5979 removerecordregions(begoff);
5986 rmescapes(p + 2, 0);
5988 len = cvtnum(ash_arith(p + 2));
5991 recordregion(begoff, begoff + len, 0);
5995 /* argstr needs it */
5996 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5999 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6000 * characters to allow for further processing. Otherwise treat
6001 * $@ like $* since no splitting will be performed.
6003 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6004 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6005 * for correct expansion of "B=$A" word.
6008 argstr(char *p, int flags, struct strlist *var_str_list)
6010 static const char spclchars[] ALIGN1 = {
6018 CTLBACKQ | CTLQUOTE,
6019 #if ENABLE_SH_MATH_SUPPORT
6024 const char *reject = spclchars;
6025 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
6026 int breakall = flags & EXP_WORD;
6031 if (!(flags & EXP_VARTILDE)) {
6033 } else if (flags & EXP_VARTILDE2) {
6038 if (flags & EXP_TILDE) {
6041 flags &= ~EXP_TILDE;
6044 if ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
6047 p = exptilde(p, q, flags);
6050 startloc = expdest - (char *)stackblock();
6054 length += strcspn(p + length, reject);
6058 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6060 /* c == '=' || c == ':' || c == CTLENDARI */
6066 expdest = stack_nputstr(p, length, expdest);
6067 newloc = expdest - (char *)stackblock();
6068 if (breakall && !inquotes && newloc > startloc) {
6069 recordregion(startloc, newloc, 0);
6080 if (flags & EXP_VARTILDE2) {
6084 flags |= EXP_VARTILDE2;
6089 * sort of a hack - expand tildes in variable
6090 * assignments (after the first '=' and after ':'s).
6099 case CTLENDVAR: /* ??? */
6102 /* "$@" syntax adherence hack */
6104 && memcmp(p, dolatstr, 4) == 0
6105 && ( p[4] == (char)CTLQUOTEMARK
6106 || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
6109 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
6112 inquotes = !inquotes;
6125 TRACE(("argstr: evalvar('%s')\n", p));
6126 p = evalvar(p, flags, var_str_list);
6127 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6131 case CTLBACKQ|CTLQUOTE:
6132 expbackq(argbackq->n, c, quotes);
6133 argbackq = argbackq->next;
6135 #if ENABLE_SH_MATH_SUPPORT
6147 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6148 char *pattern, int quotes, int zero)
6157 const char *s = loc2;
6164 match = pmatch(pattern, s);
6169 if (quotes && (unsigned char)*loc == CTLESC)
6178 scanright(char *startp, char *rmesc, char *rmescend,
6179 char *pattern, int quotes, int match_at_start)
6181 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6182 int try2optimize = match_at_start;
6188 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6189 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6190 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6192 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6193 * and on each iteration they go back two/one char until they reach the beginning.
6194 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6196 /* TODO: document in what other circumstances we are called. */
6198 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6201 const char *s = loc2;
6202 if (match_at_start) {
6206 match = pmatch(pattern, s);
6207 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6211 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6213 /* Maybe we can optimize this:
6214 * if pattern ends with unescaped *, we can avoid checking
6215 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6216 * it wont match truncated "raw_value_of_" strings too.
6218 unsigned plen = strlen(pattern);
6219 /* Does it end with "*"? */
6220 if (plen != 0 && pattern[--plen] == '*') {
6221 /* "xxxx*" is not escaped */
6222 /* "xxx\*" is escaped */
6223 /* "xx\\*" is not escaped */
6224 /* "x\\\*" is escaped */
6226 while (plen != 0 && pattern[--plen] == '\\')
6229 break; /* ends with unescaped "*" */
6237 esc = esclen(startp, loc);
6248 static void varunset(const char *, const char *, const char *, int) NORETURN;
6250 varunset(const char *end, const char *var, const char *umsg, int varflags)
6256 msg = "parameter not set";
6258 if ((unsigned char)*end == CTLENDVAR) {
6259 if (varflags & VSNUL)
6265 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6268 #if ENABLE_ASH_BASH_COMPAT
6270 parse_sub_pattern(char *arg, int varflags)
6272 char *idx, *repl = NULL;
6275 //char *org_arg = arg;
6276 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
6283 /* Only the first '/' seen is our separator */
6292 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6293 * The result is a_\_z_c (not a\_\_z_c)!
6295 * Enable debug prints in this function and you'll see:
6296 * ash: arg:'\\b/_\\_z_' varflags:d
6297 * ash: pattern:'\\b' repl:'_\_z_'
6298 * That is, \\b is interpreted as \\b, but \\_ as \_!
6299 * IOW: search pattern and replace string treat backslashes
6300 * differently! That is the reason why we check repl below:
6302 if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
6303 arg++; /* skip both '\', not just first one */
6306 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
6310 #endif /* ENABLE_ASH_BASH_COMPAT */
6313 subevalvar(char *p, char *varname, int strloc, int subtype,
6314 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6316 struct nodelist *saveargbackq = argbackq;
6319 char *rmesc, *rmescend;
6321 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
6322 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6323 int saveherefd = herefd;
6324 int amount, resetloc;
6325 IF_ASH_BASH_COMPAT(int workloc;)
6327 char *(*scan)(char*, char*, char*, char*, int, int);
6329 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6330 // p, varname, strloc, subtype, startloc, varflags, quotes);
6333 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6335 STPUTC('\0', expdest);
6336 herefd = saveherefd;
6337 argbackq = saveargbackq;
6338 startp = (char *)stackblock() + startloc;
6342 setvar2(varname, startp);
6343 amount = startp - expdest;
6344 STADJUST(amount, expdest);
6348 varunset(p, varname, startp, varflags);
6351 #if ENABLE_ASH_BASH_COMPAT
6353 loc = str = stackblock() + strloc;
6354 /* Read POS in ${var:POS:LEN} */
6355 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6356 len = str - startp - 1;
6358 /* *loc != '\0', guaranteed by parser */
6362 /* Adjust the length by the number of escapes */
6363 for (ptr = startp; ptr < (str - 1); ptr++) {
6364 if ((unsigned char)*ptr == CTLESC) {
6372 if (*loc++ == ':') {
6376 /* Skip POS in ${var:POS:LEN} */
6378 while (*loc && *loc != ':') {
6380 * bash complains on: var=qwe; echo ${var:1a:123}
6382 ash_msg_and_raise_error(msg_illnum, str);
6386 if (*loc++ == ':') {
6390 if (pos >= orig_len) {
6394 if (len > (orig_len - pos))
6395 len = orig_len - pos;
6397 for (str = startp; pos; str++, pos--) {
6398 if (quotes && (unsigned char)*str == CTLESC)
6401 for (loc = startp; len; len--) {
6402 if (quotes && (unsigned char)*str == CTLESC)
6407 amount = loc - expdest;
6408 STADJUST(amount, expdest);
6413 resetloc = expdest - (char *)stackblock();
6415 /* We'll comeback here if we grow the stack while handling
6416 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6417 * stack will need rebasing, and we'll need to remove our work
6420 IF_ASH_BASH_COMPAT(restart:)
6422 amount = expdest - ((char *)stackblock() + resetloc);
6423 STADJUST(-amount, expdest);
6424 startp = (char *)stackblock() + startloc;
6427 rmescend = (char *)stackblock() + strloc;
6429 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6430 if (rmesc != startp) {
6432 startp = (char *)stackblock() + startloc;
6436 str = (char *)stackblock() + strloc;
6437 preglob(str, varflags & VSQUOTE, 0);
6439 #if ENABLE_ASH_BASH_COMPAT
6440 workloc = expdest - (char *)stackblock();
6441 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6445 repl = parse_sub_pattern(str, varflags);
6446 //bb_error_msg("repl:'%s'", repl);
6451 /* If there's no pattern to match, return the expansion unmolested */
6460 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6461 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6463 /* No match, advance */
6464 char *restart_detect = stackblock();
6466 STPUTC(*idx, expdest);
6467 if (quotes && (unsigned char)*idx == CTLESC) {
6470 STPUTC(*idx, expdest);
6472 if (stackblock() != restart_detect)
6477 /* continue; - prone to quadratic behavior, smarter code: */
6480 if (str[0] == '*') {
6481 /* Pattern is "*foo". If "*foo" does not match "long_string",
6482 * it would never match "ong_string" etc, no point in trying.
6489 if (subtype == VSREPLACEALL) {
6491 if (quotes && (unsigned char)*idx == CTLESC)
6500 //bb_error_msg("repl:'%s'", repl);
6501 for (loc = (char*)repl; *loc; loc++) {
6502 char *restart_detect = stackblock();
6503 if (quotes && *loc == '\\') {
6504 STPUTC(CTLESC, expdest);
6507 STPUTC(*loc, expdest);
6508 if (stackblock() != restart_detect)
6513 if (subtype == VSREPLACE) {
6514 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6516 char *restart_detect = stackblock();
6517 STPUTC(*idx, expdest);
6518 if (stackblock() != restart_detect)
6527 /* We've put the replaced text into a buffer at workloc, now
6528 * move it to the right place and adjust the stack.
6530 STPUTC('\0', expdest);
6531 startp = (char *)stackblock() + startloc;
6532 memmove(startp, (char *)stackblock() + workloc, len + 1);
6533 //bb_error_msg("startp:'%s'", startp);
6534 amount = expdest - (startp + len);
6535 STADJUST(-amount, expdest);
6538 #endif /* ENABLE_ASH_BASH_COMPAT */
6540 subtype -= VSTRIMRIGHT;
6542 if (subtype < 0 || subtype > 7)
6545 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6546 zero = subtype >> 1;
6547 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6548 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6550 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6553 memmove(startp, loc, str - loc);
6554 loc = startp + (str - loc) - 1;
6557 amount = loc - expdest;
6558 STADJUST(amount, expdest);
6564 * Add the value of a specialized variable to the stack string.
6565 * name parameter (examples):
6566 * ash -c 'echo $1' name:'1='
6567 * ash -c 'echo $qwe' name:'qwe='
6568 * ash -c 'echo $$' name:'$='
6569 * ash -c 'echo ${$}' name:'$='
6570 * ash -c 'echo ${$##q}' name:'$=q'
6571 * ash -c 'echo ${#$}' name:'$='
6572 * note: examples with bad shell syntax:
6573 * ash -c 'echo ${#$1}' name:'$=1'
6574 * ash -c 'echo ${#1#}' name:'1=#'
6576 static NOINLINE ssize_t
6577 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6584 int subtype = varflags & VSTYPE;
6585 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6586 int quoted = varflags & VSQUOTE;
6587 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6597 num = shellparam.nparam;
6605 goto check_1char_name;
6607 expdest = makestrspace(NOPTS, expdest);
6608 for (i = NOPTS - 1; i >= 0; i--) {
6610 USTPUTC(optletters(i), expdest);
6616 /* handles cases similar to ${#$1} */
6617 if (name[2] != '\0')
6618 raise_error_syntax("bad substitution");
6625 if (quoted && (flags & EXP_FULL)) {
6626 /* note: this is not meant as PEOF value */
6627 sep = 1 << CHAR_BIT;
6632 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6633 i = SIT(sep, syntax);
6634 if (quotes && (i == CCTL || i == CBACK))
6640 while ((p = *ap++) != NULL) {
6643 partlen = strlen(p);
6646 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6647 memtodest(p, partlen, syntax, quotes);
6653 if (subtype == VSPLUS || subtype == VSLENGTH) {
6659 /* note: may put NUL despite sep != 0
6660 * (see sep = 1 << CHAR_BIT above) */
6666 } /* case '@' and '*' */
6677 num = atoi(name); /* number(name) fails on ${N#str} etc */
6678 if (num < 0 || num > shellparam.nparam)
6680 p = num ? shellparam.p[num - 1] : arg0;
6683 /* NB: name has form "VAR=..." */
6685 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6686 * which should be considered before we check variables. */
6688 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6692 str = var_str_list->text;
6693 eq = strchr(str, '=');
6694 if (!eq) /* stop at first non-assignment */
6697 if (name_len == (unsigned)(eq - str)
6698 && strncmp(str, name, name_len) == 0
6701 /* goto value; - WRONG! */
6702 /* think "A=1 A=2 B=$A" */
6704 var_str_list = var_str_list->next;
6705 } while (var_str_list);
6709 p = lookupvar(name);
6715 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6716 memtodest(p, len, syntax, quotes);
6720 if (subtype == VSPLUS || subtype == VSLENGTH)
6721 STADJUST(-len, expdest);
6726 * Expand a variable, and return a pointer to the next character in the
6730 evalvar(char *p, int flags, struct strlist *var_str_list)
6741 varflags = (unsigned char) *p++;
6742 subtype = varflags & VSTYPE;
6743 quoted = varflags & VSQUOTE;
6745 easy = (!quoted || (*var == '@' && shellparam.nparam));
6746 startloc = expdest - (char *)stackblock();
6747 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6750 varlen = varvalue(var, varflags, flags, var_str_list);
6751 if (varflags & VSNUL)
6754 if (subtype == VSPLUS) {
6755 varlen = -1 - varlen;
6759 if (subtype == VSMINUS) {
6764 flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
6774 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6776 if (subevalvar(p, var, /* strloc: */ 0,
6777 subtype, startloc, varflags,
6783 * Remove any recorded regions beyond
6786 removerecordregions(startloc);
6796 if (varlen < 0 && uflag)
6797 varunset(p, var, 0, 0);
6799 if (subtype == VSLENGTH) {
6800 cvtnum(varlen > 0 ? varlen : 0);
6804 if (subtype == VSNORMAL) {
6815 case VSTRIMRIGHTMAX:
6816 #if ENABLE_ASH_BASH_COMPAT
6829 * Terminate the string and start recording the pattern
6832 STPUTC('\0', expdest);
6833 patloc = expdest - (char *)stackblock();
6834 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6836 /* quotes: */ flags & (EXP_FULL | EXP_CASE | EXP_REDIR),
6839 int amount = expdest - (
6840 (char *)stackblock() + patloc - 1
6842 STADJUST(-amount, expdest);
6844 /* Remove any recorded regions beyond start of variable */
6845 removerecordregions(startloc);
6847 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6851 if (subtype != VSNORMAL) { /* skip to end of alternative */
6854 unsigned char c = *p++;
6857 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6859 argbackq = argbackq->next;
6860 } else if (c == CTLVAR) {
6861 if ((*p++ & VSTYPE) != VSNORMAL)
6863 } else if (c == CTLENDVAR) {
6873 * Break the argument string into pieces based upon IFS and add the
6874 * strings to the argument list. The regions of the string to be
6875 * searched for IFS characters have been stored by recordregion.
6878 ifsbreakup(char *string, struct arglist *arglist)
6880 struct ifsregion *ifsp;
6885 const char *ifs, *realifs;
6890 if (ifslastp != NULL) {
6893 realifs = ifsset() ? ifsval() : defifs;
6896 p = string + ifsp->begoff;
6897 nulonly = ifsp->nulonly;
6898 ifs = nulonly ? nullstr : realifs;
6900 while (p < string + ifsp->endoff) {
6902 if ((unsigned char)*p == CTLESC)
6904 if (!strchr(ifs, *p)) {
6909 ifsspc = (strchr(defifs, *p) != NULL);
6910 /* Ignore IFS whitespace at start */
6911 if (q == start && ifsspc) {
6917 sp = stzalloc(sizeof(*sp));
6919 *arglist->lastp = sp;
6920 arglist->lastp = &sp->next;
6924 if (p >= string + ifsp->endoff) {
6928 if ((unsigned char)*p == CTLESC)
6930 if (strchr(ifs, *p) == NULL) {
6934 if (strchr(defifs, *p) == NULL) {
6949 } while (ifsp != NULL);
6958 sp = stzalloc(sizeof(*sp));
6960 *arglist->lastp = sp;
6961 arglist->lastp = &sp->next;
6967 struct ifsregion *p;
6972 struct ifsregion *ifsp;
6978 ifsfirst.next = NULL;
6983 * Add a file name to the list.
6986 addfname(const char *name)
6990 sp = stzalloc(sizeof(*sp));
6991 sp->text = ststrdup(name);
6993 exparg.lastp = &sp->next;
6997 * Do metacharacter (i.e. *, ?, [...]) expansion.
7000 expmeta(char *expdir, char *enddir, char *name)
7015 for (p = name; *p; p++) {
7016 if (*p == '*' || *p == '?')
7018 else if (*p == '[') {
7025 if (*q == '/' || *q == '\0')
7032 } else if (*p == '\\')
7034 else if (*p == '/') {
7041 if (metaflag == 0) { /* we've reached the end of the file name */
7042 if (enddir != expdir)
7050 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7061 } while (p < start);
7063 if (enddir == expdir) {
7065 } else if (enddir == expdir + 1 && *expdir == '/') {
7074 if (enddir != expdir)
7076 if (*endname == 0) {
7088 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7089 if (dp->d_name[0] == '.' && !matchdot)
7091 if (pmatch(start, dp->d_name)) {
7093 strcpy(enddir, dp->d_name);
7096 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7099 expmeta(expdir, p, endname);
7108 static struct strlist *
7109 msort(struct strlist *list, int len)
7111 struct strlist *p, *q = NULL;
7112 struct strlist **lpp;
7120 for (n = half; --n >= 0;) {
7124 q->next = NULL; /* terminate first half of list */
7125 q = msort(list, half); /* sort first half of list */
7126 p = msort(p, len - half); /* sort second half */
7129 #if ENABLE_LOCALE_SUPPORT
7130 if (strcoll(p->text, q->text) < 0)
7132 if (strcmp(p->text, q->text) < 0)
7156 * Sort the results of file name expansion. It calculates the number of
7157 * strings to sort and then calls msort (short for merge sort) to do the
7160 static struct strlist *
7161 expsort(struct strlist *str)
7167 for (sp = str; sp; sp = sp->next)
7169 return msort(str, len);
7173 expandmeta(struct strlist *str /*, int flag*/)
7175 static const char metachars[] ALIGN1 = {
7178 /* TODO - EXP_REDIR */
7182 struct strlist **savelastp;
7188 if (!strpbrk(str->text, metachars))
7190 savelastp = exparg.lastp;
7193 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7195 int i = strlen(str->text);
7196 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7198 expmeta(expdir, expdir, p);
7203 if (exparg.lastp == savelastp) {
7208 *exparg.lastp = str;
7209 rmescapes(str->text, 0);
7210 exparg.lastp = &str->next;
7212 *exparg.lastp = NULL;
7213 *savelastp = sp = expsort(*savelastp);
7214 while (sp->next != NULL)
7216 exparg.lastp = &sp->next;
7223 * Perform variable substitution and command substitution on an argument,
7224 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7225 * perform splitting and file name expansion. When arglist is NULL, perform
7226 * here document expansion.
7229 expandarg(union node *arg, struct arglist *arglist, int flag)
7234 argbackq = arg->narg.backquote;
7235 STARTSTACKSTR(expdest);
7236 ifsfirst.next = NULL;
7238 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7239 argstr(arg->narg.text, flag,
7240 /* var_str_list: */ arglist ? arglist->list : NULL);
7241 p = _STPUTC('\0', expdest);
7243 if (arglist == NULL) {
7244 return; /* here document expanded */
7246 p = grabstackstr(p);
7247 TRACE(("expandarg: p:'%s'\n", p));
7248 exparg.lastp = &exparg.list;
7252 if (flag & EXP_FULL) {
7253 ifsbreakup(p, &exparg);
7254 *exparg.lastp = NULL;
7255 exparg.lastp = &exparg.list;
7256 expandmeta(exparg.list /*, flag*/);
7258 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7260 TRACE(("expandarg: rmescapes:'%s'\n", p));
7262 sp = stzalloc(sizeof(*sp));
7265 exparg.lastp = &sp->next;
7269 *exparg.lastp = NULL;
7271 *arglist->lastp = exparg.list;
7272 arglist->lastp = exparg.lastp;
7277 * Expand shell variables and backquotes inside a here document.
7280 expandhere(union node *arg, int fd)
7283 expandarg(arg, (struct arglist *)NULL, 0);
7284 full_write(fd, stackblock(), expdest - (char *)stackblock());
7288 * Returns true if the pattern matches the string.
7291 patmatch(char *pattern, const char *string)
7293 return pmatch(preglob(pattern, 0, 0), string);
7297 * See if a pattern matches in a case statement.
7300 casematch(union node *pattern, char *val)
7302 struct stackmark smark;
7305 setstackmark(&smark);
7306 argbackq = pattern->narg.backquote;
7307 STARTSTACKSTR(expdest);
7309 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7310 /* var_str_list: */ NULL);
7311 STACKSTRNUL(expdest);
7312 result = patmatch(stackblock(), val);
7313 popstackmark(&smark);
7318 /* ============ find_command */
7322 int (*builtin)(int, char **) FAST_FUNC;
7323 /* unsigned flags; */
7325 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7326 /* "regular" builtins always take precedence over commands,
7327 * regardless of PATH=....%builtin... position */
7328 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7329 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7332 smallint cmdtype; /* CMDxxx */
7335 /* index >= 0 for commands without path (slashes) */
7336 /* (TODO: what exactly does the value mean? PATH position?) */
7337 /* index == -1 for commands with slashes */
7338 /* index == (-2 - applet_no) for NOFORK applets */
7339 const struct builtincmd *cmd;
7340 struct funcnode *func;
7343 /* values of cmdtype */
7344 #define CMDUNKNOWN -1 /* no entry in table for command */
7345 #define CMDNORMAL 0 /* command is an executable program */
7346 #define CMDFUNCTION 1 /* command is a shell function */
7347 #define CMDBUILTIN 2 /* command is a shell builtin */
7349 /* action to find_command() */
7350 #define DO_ERR 0x01 /* prints errors */
7351 #define DO_ABS 0x02 /* checks absolute paths */
7352 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7353 #define DO_ALTPATH 0x08 /* using alternate path */
7354 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7356 static void find_command(char *, struct cmdentry *, int, const char *);
7359 /* ============ Hashing commands */
7362 * When commands are first encountered, they are entered in a hash table.
7363 * This ensures that a full path search will not have to be done for them
7364 * on each invocation.
7366 * We should investigate converting to a linear search, even though that
7367 * would make the command name "hash" a misnomer.
7371 struct tblentry *next; /* next entry in hash chain */
7372 union param param; /* definition of builtin function */
7373 smallint cmdtype; /* CMDxxx */
7374 char rehash; /* if set, cd done since entry created */
7375 char cmdname[1]; /* name of command */
7378 static struct tblentry **cmdtable;
7379 #define INIT_G_cmdtable() do { \
7380 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7383 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7387 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7389 #if ENABLE_FEATURE_SH_STANDALONE
7390 if (applet_no >= 0) {
7391 if (APPLET_IS_NOEXEC(applet_no)) {
7395 run_applet_no_and_exit(applet_no, argv);
7397 /* re-exec ourselves with the new arguments */
7398 execve(bb_busybox_exec_path, argv, envp);
7399 /* If they called chroot or otherwise made the binary no longer
7400 * executable, fall through */
7407 execve(cmd, argv, envp);
7408 } while (errno == EINTR);
7410 execve(cmd, argv, envp);
7412 if (cmd == (char*) bb_busybox_exec_path) {
7413 /* We already visited ENOEXEC branch below, don't do it again */
7414 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7418 if (errno == ENOEXEC) {
7419 /* Run "cmd" as a shell script:
7420 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7421 * "If the execve() function fails with ENOEXEC, the shell
7422 * shall execute a command equivalent to having a shell invoked
7423 * with the command name as its first operand,
7424 * with any remaining arguments passed to the new shell"
7426 * That is, do not use $SHELL, user's shell, or /bin/sh;
7427 * just call ourselves.
7429 * Note that bash reads ~80 chars of the file, and if it sees
7430 * a zero byte before it sees newline, it doesn't try to
7431 * interpret it, but fails with "cannot execute binary file"
7432 * message and exit code 126. For one, this prevents attempts
7433 * to interpret foreign ELF binaries as shell scripts.
7438 for (ap = argv; *ap; ap++)
7440 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7441 new[0] = (char*) "ash";
7444 while ((*ap++ = *++argv) != NULL)
7446 cmd = (char*) bb_busybox_exec_path;
7453 * Exec a program. Never returns. If you change this routine, you may
7454 * have to change the find_command routine as well.
7456 static void shellexec(char **, const char *, int) NORETURN;
7458 shellexec(char **argv, const char *path, int idx)
7464 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7466 clearredir(/*drop:*/ 1);
7467 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7468 if (strchr(argv[0], '/') != NULL
7469 #if ENABLE_FEATURE_SH_STANDALONE
7470 || (applet_no = find_applet_by_name(argv[0])) >= 0
7473 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7474 if (applet_no >= 0) {
7475 /* We tried execing ourself, but it didn't work.
7476 * Maybe /proc/self/exe doesn't exist?
7485 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7486 if (--idx < 0 && pathopt == NULL) {
7487 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7488 if (errno != ENOENT && errno != ENOTDIR)
7495 /* Map to POSIX errors */
7507 exitstatus = exerrno;
7508 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7509 argv[0], e, suppress_int));
7510 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7515 printentry(struct tblentry *cmdp)
7521 idx = cmdp->param.index;
7524 name = path_advance(&path, cmdp->cmdname);
7526 } while (--idx >= 0);
7527 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7531 * Clear out command entries. The argument specifies the first entry in
7532 * PATH which has changed.
7535 clearcmdentry(int firstchange)
7537 struct tblentry **tblp;
7538 struct tblentry **pp;
7539 struct tblentry *cmdp;
7542 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7544 while ((cmdp = *pp) != NULL) {
7545 if ((cmdp->cmdtype == CMDNORMAL &&
7546 cmdp->param.index >= firstchange)
7547 || (cmdp->cmdtype == CMDBUILTIN &&
7548 builtinloc >= firstchange)
7561 * Locate a command in the command hash table. If "add" is nonzero,
7562 * add the command to the table if it is not already present. The
7563 * variable "lastcmdentry" is set to point to the address of the link
7564 * pointing to the entry, so that delete_cmd_entry can delete the
7567 * Interrupts must be off if called with add != 0.
7569 static struct tblentry **lastcmdentry;
7571 static struct tblentry *
7572 cmdlookup(const char *name, int add)
7574 unsigned int hashval;
7576 struct tblentry *cmdp;
7577 struct tblentry **pp;
7580 hashval = (unsigned char)*p << 4;
7582 hashval += (unsigned char)*p++;
7584 pp = &cmdtable[hashval % CMDTABLESIZE];
7585 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7586 if (strcmp(cmdp->cmdname, name) == 0)
7590 if (add && cmdp == NULL) {
7591 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7593 /* + 1 - already done because
7594 * tblentry::cmdname is char[1] */);
7595 /*cmdp->next = NULL; - ckzalloc did it */
7596 cmdp->cmdtype = CMDUNKNOWN;
7597 strcpy(cmdp->cmdname, name);
7604 * Delete the command entry returned on the last lookup.
7607 delete_cmd_entry(void)
7609 struct tblentry *cmdp;
7612 cmdp = *lastcmdentry;
7613 *lastcmdentry = cmdp->next;
7614 if (cmdp->cmdtype == CMDFUNCTION)
7615 freefunc(cmdp->param.func);
7621 * Add a new command entry, replacing any existing command entry for
7622 * the same name - except special builtins.
7625 addcmdentry(char *name, struct cmdentry *entry)
7627 struct tblentry *cmdp;
7629 cmdp = cmdlookup(name, 1);
7630 if (cmdp->cmdtype == CMDFUNCTION) {
7631 freefunc(cmdp->param.func);
7633 cmdp->cmdtype = entry->cmdtype;
7634 cmdp->param = entry->u;
7638 static int FAST_FUNC
7639 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7641 struct tblentry **pp;
7642 struct tblentry *cmdp;
7644 struct cmdentry entry;
7647 if (nextopt("r") != '\0') {
7652 if (*argptr == NULL) {
7653 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7654 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7655 if (cmdp->cmdtype == CMDNORMAL)
7663 while ((name = *argptr) != NULL) {
7664 cmdp = cmdlookup(name, 0);
7666 && (cmdp->cmdtype == CMDNORMAL
7667 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7671 find_command(name, &entry, DO_ERR, pathval());
7672 if (entry.cmdtype == CMDUNKNOWN)
7680 * Called when a cd is done. Marks all commands so the next time they
7681 * are executed they will be rehashed.
7686 struct tblentry **pp;
7687 struct tblentry *cmdp;
7689 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7690 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7691 if (cmdp->cmdtype == CMDNORMAL
7692 || (cmdp->cmdtype == CMDBUILTIN
7693 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7703 * Fix command hash table when PATH changed.
7704 * Called before PATH is changed. The argument is the new value of PATH;
7705 * pathval() still returns the old value at this point.
7706 * Called with interrupts off.
7708 static void FAST_FUNC
7709 changepath(const char *new)
7717 firstchange = 9999; /* assume no change */
7723 if ((*old == '\0' && *new == ':')
7724 || (*old == ':' && *new == '\0')
7728 old = new; /* ignore subsequent differences */
7732 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7739 if (builtinloc < 0 && idx_bltin >= 0)
7740 builtinloc = idx_bltin; /* zap builtins */
7741 if (builtinloc >= 0 && idx_bltin < 0)
7743 clearcmdentry(firstchange);
7744 builtinloc = idx_bltin;
7759 #define TENDBQUOTE 12
7776 typedef smallint token_id_t;
7778 /* first char is indicating which tokens mark the end of a list */
7779 static const char *const tokname_array[] = {
7793 #define KWDOFFSET 13
7794 /* the following are keywords */
7813 /* Wrapper around strcmp for qsort/bsearch/... */
7815 pstrcmp(const void *a, const void *b)
7817 return strcmp((char*) a, (*(char**) b) + 1);
7820 static const char *const *
7821 findkwd(const char *s)
7823 return bsearch(s, tokname_array + KWDOFFSET,
7824 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7825 sizeof(tokname_array[0]), pstrcmp);
7829 * Locate and print what a word is...
7832 describe_command(char *command, int describe_command_verbose)
7834 struct cmdentry entry;
7835 struct tblentry *cmdp;
7836 #if ENABLE_ASH_ALIAS
7837 const struct alias *ap;
7839 const char *path = pathval();
7841 if (describe_command_verbose) {
7845 /* First look at the keywords */
7846 if (findkwd(command)) {
7847 out1str(describe_command_verbose ? " is a shell keyword" : command);
7851 #if ENABLE_ASH_ALIAS
7852 /* Then look at the aliases */
7853 ap = lookupalias(command, 0);
7855 if (!describe_command_verbose) {
7860 out1fmt(" is an alias for %s", ap->val);
7864 /* Then check if it is a tracked alias */
7865 cmdp = cmdlookup(command, 0);
7867 entry.cmdtype = cmdp->cmdtype;
7868 entry.u = cmdp->param;
7870 /* Finally use brute force */
7871 find_command(command, &entry, DO_ABS, path);
7874 switch (entry.cmdtype) {
7876 int j = entry.u.index;
7882 p = path_advance(&path, command);
7886 if (describe_command_verbose) {
7888 (cmdp ? " a tracked alias for" : nullstr), p
7897 if (describe_command_verbose) {
7898 out1str(" is a shell function");
7905 if (describe_command_verbose) {
7906 out1fmt(" is a %sshell builtin",
7907 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7908 "special " : nullstr
7916 if (describe_command_verbose) {
7917 out1str(": not found\n");
7926 static int FAST_FUNC
7927 typecmd(int argc UNUSED_PARAM, char **argv)
7933 /* type -p ... ? (we don't bother checking for 'p') */
7934 if (argv[1] && argv[1][0] == '-') {
7939 err |= describe_command(argv[i++], verbose);
7944 #if ENABLE_ASH_CMDCMD
7945 static int FAST_FUNC
7946 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7954 while ((c = nextopt("pvV")) != '\0')
7956 verify |= VERIFY_VERBOSE;
7958 verify |= VERIFY_BRIEF;
7963 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7964 if (verify && (*argptr != NULL)) {
7965 return describe_command(*argptr, verify - VERIFY_BRIEF);
7973 /* ============ eval.c */
7975 static int funcblocksize; /* size of structures in function */
7976 static int funcstringsize; /* size of strings in node */
7977 static void *funcblock; /* block to allocate function from */
7978 static char *funcstring; /* block to allocate strings from */
7980 /* flags in argument to evaltree */
7981 #define EV_EXIT 01 /* exit after evaluating tree */
7982 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7983 #define EV_BACKCMD 04 /* command executing within back quotes */
7985 static const uint8_t nodesize[N_NUMBER] = {
7986 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7987 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7988 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7989 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7990 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7991 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7992 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7993 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7994 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7995 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7996 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7997 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7998 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7999 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8000 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8001 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8002 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8003 #if ENABLE_ASH_BASH_COMPAT
8004 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8006 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8007 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8008 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8009 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8010 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8011 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8012 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8013 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8014 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8017 static void calcsize(union node *n);
8020 sizenodelist(struct nodelist *lp)
8023 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8030 calcsize(union node *n)
8034 funcblocksize += nodesize[n->type];
8037 calcsize(n->ncmd.redirect);
8038 calcsize(n->ncmd.args);
8039 calcsize(n->ncmd.assign);
8042 sizenodelist(n->npipe.cmdlist);
8047 calcsize(n->nredir.redirect);
8048 calcsize(n->nredir.n);
8055 calcsize(n->nbinary.ch2);
8056 calcsize(n->nbinary.ch1);
8059 calcsize(n->nif.elsepart);
8060 calcsize(n->nif.ifpart);
8061 calcsize(n->nif.test);
8064 funcstringsize += strlen(n->nfor.var) + 1;
8065 calcsize(n->nfor.body);
8066 calcsize(n->nfor.args);
8069 calcsize(n->ncase.cases);
8070 calcsize(n->ncase.expr);
8073 calcsize(n->nclist.body);
8074 calcsize(n->nclist.pattern);
8075 calcsize(n->nclist.next);
8079 sizenodelist(n->narg.backquote);
8080 funcstringsize += strlen(n->narg.text) + 1;
8081 calcsize(n->narg.next);
8084 #if ENABLE_ASH_BASH_COMPAT
8091 calcsize(n->nfile.fname);
8092 calcsize(n->nfile.next);
8096 calcsize(n->ndup.vname);
8097 calcsize(n->ndup.next);
8101 calcsize(n->nhere.doc);
8102 calcsize(n->nhere.next);
8105 calcsize(n->nnot.com);
8111 nodeckstrdup(char *s)
8113 char *rtn = funcstring;
8115 strcpy(funcstring, s);
8116 funcstring += strlen(s) + 1;
8120 static union node *copynode(union node *);
8122 static struct nodelist *
8123 copynodelist(struct nodelist *lp)
8125 struct nodelist *start;
8126 struct nodelist **lpp;
8131 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8132 (*lpp)->n = copynode(lp->n);
8134 lpp = &(*lpp)->next;
8141 copynode(union node *n)
8148 funcblock = (char *) funcblock + nodesize[n->type];
8152 new->ncmd.redirect = copynode(n->ncmd.redirect);
8153 new->ncmd.args = copynode(n->ncmd.args);
8154 new->ncmd.assign = copynode(n->ncmd.assign);
8157 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8158 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8163 new->nredir.redirect = copynode(n->nredir.redirect);
8164 new->nredir.n = copynode(n->nredir.n);
8171 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8172 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8175 new->nif.elsepart = copynode(n->nif.elsepart);
8176 new->nif.ifpart = copynode(n->nif.ifpart);
8177 new->nif.test = copynode(n->nif.test);
8180 new->nfor.var = nodeckstrdup(n->nfor.var);
8181 new->nfor.body = copynode(n->nfor.body);
8182 new->nfor.args = copynode(n->nfor.args);
8185 new->ncase.cases = copynode(n->ncase.cases);
8186 new->ncase.expr = copynode(n->ncase.expr);
8189 new->nclist.body = copynode(n->nclist.body);
8190 new->nclist.pattern = copynode(n->nclist.pattern);
8191 new->nclist.next = copynode(n->nclist.next);
8195 new->narg.backquote = copynodelist(n->narg.backquote);
8196 new->narg.text = nodeckstrdup(n->narg.text);
8197 new->narg.next = copynode(n->narg.next);
8200 #if ENABLE_ASH_BASH_COMPAT
8207 new->nfile.fname = copynode(n->nfile.fname);
8208 new->nfile.fd = n->nfile.fd;
8209 new->nfile.next = copynode(n->nfile.next);
8213 new->ndup.vname = copynode(n->ndup.vname);
8214 new->ndup.dupfd = n->ndup.dupfd;
8215 new->ndup.fd = n->ndup.fd;
8216 new->ndup.next = copynode(n->ndup.next);
8220 new->nhere.doc = copynode(n->nhere.doc);
8221 new->nhere.fd = n->nhere.fd;
8222 new->nhere.next = copynode(n->nhere.next);
8225 new->nnot.com = copynode(n->nnot.com);
8228 new->type = n->type;
8233 * Make a copy of a parse tree.
8235 static struct funcnode *
8236 copyfunc(union node *n)
8241 funcblocksize = offsetof(struct funcnode, n);
8244 blocksize = funcblocksize;
8245 f = ckmalloc(blocksize + funcstringsize);
8246 funcblock = (char *) f + offsetof(struct funcnode, n);
8247 funcstring = (char *) f + blocksize;
8254 * Define a shell function.
8257 defun(char *name, union node *func)
8259 struct cmdentry entry;
8262 entry.cmdtype = CMDFUNCTION;
8263 entry.u.func = copyfunc(func);
8264 addcmdentry(name, &entry);
8268 /* Reasons for skipping commands (see comment on breakcmd routine) */
8269 #define SKIPBREAK (1 << 0)
8270 #define SKIPCONT (1 << 1)
8271 #define SKIPFUNC (1 << 2)
8272 #define SKIPFILE (1 << 3)
8273 #define SKIPEVAL (1 << 4)
8274 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8275 static int skipcount; /* number of levels to skip */
8276 static int funcnest; /* depth of function calls */
8277 static int loopnest; /* current loop nesting level */
8279 /* Forward decl way out to parsing code - dotrap needs it */
8280 static int evalstring(char *s, int mask);
8282 /* Called to execute a trap.
8283 * Single callsite - at the end of evaltree().
8284 * If we return non-zero, evaltree raises EXEXIT exception.
8286 * Perhaps we should avoid entering new trap handlers
8287 * while we are executing a trap handler. [is it a TODO?]
8296 savestatus = exitstatus;
8300 TRACE(("dotrap entered\n"));
8301 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8308 /* non-trapped SIGINT is handled separately by raise_interrupt,
8309 * don't upset it by resetting gotsig[SIGINT-1] */
8310 if (sig == SIGINT && !t)
8313 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8317 want_exexit = evalstring(t, SKIPEVAL);
8318 exitstatus = savestatus;
8320 TRACE(("dotrap returns %d\n", want_exexit));
8325 TRACE(("dotrap returns 0\n"));
8329 /* forward declarations - evaluation is fairly recursive business... */
8330 static void evalloop(union node *, int);
8331 static void evalfor(union node *, int);
8332 static void evalcase(union node *, int);
8333 static void evalsubshell(union node *, int);
8334 static void expredir(union node *);
8335 static void evalpipe(union node *, int);
8336 static void evalcommand(union node *, int);
8337 static int evalbltin(const struct builtincmd *, int, char **);
8338 static void prehash(union node *);
8341 * Evaluate a parse tree. The value is left in the global variable
8345 evaltree(union node *n, int flags)
8347 struct jmploc *volatile savehandler = exception_handler;
8348 struct jmploc jmploc;
8350 void (*evalfn)(union node *, int);
8354 SAVE_INT(int_level);
8357 TRACE(("evaltree(NULL) called\n"));
8360 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8362 exception_handler = &jmploc;
8364 int err = setjmp(jmploc.loc);
8366 /* if it was a signal, check for trap handlers */
8367 if (exception_type == EXSIG) {
8368 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8369 exception_type, err));
8372 /* continue on the way out */
8373 TRACE(("exception %d in evaltree, propagating err=%d\n",
8374 exception_type, err));
8375 exception_handler = savehandler;
8376 longjmp(exception_handler->loc, err);
8383 out1fmt("Node type = %d\n", n->type);
8388 evaltree(n->nnot.com, EV_TESTED);
8389 status = !exitstatus;
8392 expredir(n->nredir.redirect);
8393 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8395 evaltree(n->nredir.n, flags & EV_TESTED);
8396 status = exitstatus;
8398 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8401 evalfn = evalcommand;
8403 if (eflag && !(flags & EV_TESTED))
8415 evalfn = evalsubshell;
8428 #error NAND + 1 != NOR
8430 #if NOR + 1 != NSEMI
8431 #error NOR + 1 != NSEMI
8433 unsigned is_or = n->type - NAND;
8436 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8438 if (!exitstatus == is_or)
8451 evaltree(n->nif.test, EV_TESTED);
8454 if (exitstatus == 0) {
8458 if (n->nif.elsepart) {
8459 n = n->nif.elsepart;
8464 defun(n->narg.text, n->narg.next);
8468 exitstatus = status;
8473 exception_handler = savehandler;
8476 /* Order of checks below is important:
8477 * signal handlers trigger before exit caused by "set -e".
8479 if (pending_sig && dotrap())
8481 if (checkexit & exitstatus)
8482 evalskip |= SKIPEVAL;
8484 if (flags & EV_EXIT) {
8486 raise_exception(EXEXIT);
8489 RESTORE_INT(int_level);
8490 TRACE(("leaving evaltree (no interrupts)\n"));
8493 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8496 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8499 evalloop(union node *n, int flags)
8509 evaltree(n->nbinary.ch1, EV_TESTED);
8512 if (evalskip == SKIPCONT && --skipcount <= 0) {
8516 if (evalskip == SKIPBREAK && --skipcount <= 0)
8521 if (n->type != NWHILE)
8525 evaltree(n->nbinary.ch2, flags);
8526 status = exitstatus;
8531 exitstatus = status;
8535 evalfor(union node *n, int flags)
8537 struct arglist arglist;
8540 struct stackmark smark;
8542 setstackmark(&smark);
8543 arglist.list = NULL;
8544 arglist.lastp = &arglist.list;
8545 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8546 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8551 *arglist.lastp = NULL;
8556 for (sp = arglist.list; sp; sp = sp->next) {
8557 setvar2(n->nfor.var, sp->text);
8558 evaltree(n->nfor.body, flags);
8560 if (evalskip == SKIPCONT && --skipcount <= 0) {
8564 if (evalskip == SKIPBREAK && --skipcount <= 0)
8571 popstackmark(&smark);
8575 evalcase(union node *n, int flags)
8579 struct arglist arglist;
8580 struct stackmark smark;
8582 setstackmark(&smark);
8583 arglist.list = NULL;
8584 arglist.lastp = &arglist.list;
8585 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8587 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8588 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8589 if (casematch(patp, arglist.list->text)) {
8590 if (evalskip == 0) {
8591 evaltree(cp->nclist.body, flags);
8598 popstackmark(&smark);
8602 * Kick off a subshell to evaluate a tree.
8605 evalsubshell(union node *n, int flags)
8608 int backgnd = (n->type == NBACKGND);
8611 expredir(n->nredir.redirect);
8612 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8615 jp = makejob(/*n,*/ 1);
8616 if (forkshell(jp, n, backgnd) == 0) {
8621 flags &= ~EV_TESTED;
8623 redirect(n->nredir.redirect, 0);
8624 evaltreenr(n->nredir.n, flags);
8629 status = waitforjob(jp);
8630 exitstatus = status;
8635 * Compute the names of the files in a redirection list.
8637 static void fixredir(union node *, const char *, int);
8639 expredir(union node *n)
8643 for (redir = n; redir; redir = redir->nfile.next) {
8647 fn.lastp = &fn.list;
8648 switch (redir->type) {
8652 #if ENABLE_ASH_BASH_COMPAT
8657 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8658 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8659 #if ENABLE_ASH_BASH_COMPAT
8663 // By the design of stack allocator, the loop of this kind:
8664 // while true; do while true; do break; done </dev/null; done
8665 // will look like a memory leak: ash plans to free expfname's
8666 // of "/dev/null" as soon as it finishes running the loop
8667 // (in this case, never).
8668 // This "fix" is wrong:
8669 if (redir->nfile.expfname)
8670 stunalloc(redir->nfile.expfname);
8671 // It results in corrupted state of stacked allocations.
8673 redir->nfile.expfname = fn.list->text;
8676 case NTOFD: /* >& */
8677 if (redir->ndup.vname) {
8678 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8679 if (fn.list == NULL)
8680 ash_msg_and_raise_error("redir error");
8681 #if ENABLE_ASH_BASH_COMPAT
8682 //FIXME: we used expandarg with different args!
8683 if (!isdigit_str9(fn.list->text)) {
8684 /* >&file, not >&fd */
8685 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8686 ash_msg_and_raise_error("redir error");
8688 goto store_expfname;
8691 fixredir(redir, fn.list->text, 1);
8699 * Evaluate a pipeline. All the processes in the pipeline are children
8700 * of the process creating the pipeline. (This differs from some versions
8701 * of the shell, which make the last process in a pipeline the parent
8705 evalpipe(union node *n, int flags)
8708 struct nodelist *lp;
8713 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8715 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8719 jp = makejob(/*n,*/ pipelen);
8721 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8725 if (pipe(pip) < 0) {
8727 ash_msg_and_raise_error("pipe call failed");
8730 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8743 evaltreenr(lp->n, flags);
8749 /* Don't want to trigger debugging */
8753 if (n->npipe.pipe_backgnd == 0) {
8754 exitstatus = waitforjob(jp);
8755 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8761 * Controls whether the shell is interactive or not.
8764 setinteractive(int on)
8766 static smallint is_interactive;
8768 if (++on == is_interactive)
8770 is_interactive = on;
8774 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8775 if (is_interactive > 1) {
8776 /* Looks like they want an interactive shell */
8777 static smallint did_banner;
8780 /* note: ash and hush share this string */
8781 out1fmt("\n\n%s %s\n"
8782 "Enter 'help' for a list of built-in commands."
8785 "built-in shell (ash)"
8799 setinteractive(iflag);
8801 #if ENABLE_FEATURE_EDITING_VI
8803 line_input_state->flags |= VI_MODE;
8805 line_input_state->flags &= ~VI_MODE;
8807 viflag = 0; /* forcibly keep the option off */
8811 static struct localvar *localvars;
8814 * Called after a function returns.
8815 * Interrupts must be off.
8820 struct localvar *lvp;
8823 while ((lvp = localvars) != NULL) {
8824 localvars = lvp->next;
8826 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8827 if (vp == NULL) { /* $- saved */
8828 memcpy(optlist, lvp->text, sizeof(optlist));
8829 free((char*)lvp->text);
8831 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8832 unsetvar(vp->var_text);
8835 vp->var_func(var_end(lvp->text));
8836 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8837 free((char*)vp->var_text);
8838 vp->flags = lvp->flags;
8839 vp->var_text = lvp->text;
8846 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8848 volatile struct shparam saveparam;
8849 struct localvar *volatile savelocalvars;
8850 struct jmploc *volatile savehandler;
8851 struct jmploc jmploc;
8854 saveparam = shellparam;
8855 savelocalvars = localvars;
8856 e = setjmp(jmploc.loc);
8861 savehandler = exception_handler;
8862 exception_handler = &jmploc;
8864 shellparam.malloced = 0;
8868 shellparam.nparam = argc - 1;
8869 shellparam.p = argv + 1;
8870 #if ENABLE_ASH_GETOPTS
8871 shellparam.optind = 1;
8872 shellparam.optoff = -1;
8874 evaltree(&func->n, flags & EV_TESTED);
8880 localvars = savelocalvars;
8881 freeparam(&shellparam);
8882 shellparam = saveparam;
8883 exception_handler = savehandler;
8885 evalskip &= ~SKIPFUNC;
8889 #if ENABLE_ASH_CMDCMD
8891 parse_command_args(char **argv, const char **path)
8904 if (c == '-' && !*cp) {
8911 *path = bb_default_path;
8914 /* run 'typecmd' for other options */
8925 * Make a variable a local variable. When a variable is made local, it's
8926 * value and flags are saved in a localvar structure. The saved values
8927 * will be restored when the shell function returns. We handle the name
8928 * "-" as a special case.
8933 struct localvar *lvp;
8938 lvp = ckzalloc(sizeof(struct localvar));
8939 if (LONE_DASH(name)) {
8941 p = ckmalloc(sizeof(optlist));
8942 lvp->text = memcpy(p, optlist, sizeof(optlist));
8947 vpp = hashvar(name);
8948 vp = *findvar(vpp, name);
8949 eq = strchr(name, '=');
8952 setvareq(name, VSTRFIXED);
8954 setvar(name, NULL, VSTRFIXED);
8955 vp = *vpp; /* the new variable */
8956 lvp->flags = VUNSET;
8958 lvp->text = vp->var_text;
8959 lvp->flags = vp->flags;
8960 vp->flags |= VSTRFIXED|VTEXTFIXED;
8966 lvp->next = localvars;
8972 * The "local" command.
8974 static int FAST_FUNC
8975 localcmd(int argc UNUSED_PARAM, char **argv)
8980 while ((name = *argv++) != NULL) {
8986 static int FAST_FUNC
8987 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8992 static int FAST_FUNC
8993 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8998 static int FAST_FUNC
8999 execcmd(int argc UNUSED_PARAM, char **argv)
9002 iflag = 0; /* exit on error */
9005 shellexec(argv + 1, pathval(), 0);
9011 * The return command.
9013 static int FAST_FUNC
9014 returncmd(int argc UNUSED_PARAM, char **argv)
9017 * If called outside a function, do what ksh does;
9018 * skip the rest of the file.
9020 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
9021 return argv[1] ? number(argv[1]) : exitstatus;
9024 /* Forward declarations for builtintab[] */
9025 static int breakcmd(int, char **) FAST_FUNC;
9026 static int dotcmd(int, char **) FAST_FUNC;
9027 static int evalcmd(int, char **) FAST_FUNC;
9028 static int exitcmd(int, char **) FAST_FUNC;
9029 static int exportcmd(int, char **) FAST_FUNC;
9030 #if ENABLE_ASH_GETOPTS
9031 static int getoptscmd(int, char **) FAST_FUNC;
9033 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9034 static int helpcmd(int, char **) FAST_FUNC;
9037 static int historycmd(int, char **) FAST_FUNC;
9039 #if ENABLE_SH_MATH_SUPPORT
9040 static int letcmd(int, char **) FAST_FUNC;
9042 static int readcmd(int, char **) FAST_FUNC;
9043 static int setcmd(int, char **) FAST_FUNC;
9044 static int shiftcmd(int, char **) FAST_FUNC;
9045 static int timescmd(int, char **) FAST_FUNC;
9046 static int trapcmd(int, char **) FAST_FUNC;
9047 static int umaskcmd(int, char **) FAST_FUNC;
9048 static int unsetcmd(int, char **) FAST_FUNC;
9049 static int ulimitcmd(int, char **) FAST_FUNC;
9051 #define BUILTIN_NOSPEC "0"
9052 #define BUILTIN_SPECIAL "1"
9053 #define BUILTIN_REGULAR "2"
9054 #define BUILTIN_SPEC_REG "3"
9055 #define BUILTIN_ASSIGN "4"
9056 #define BUILTIN_SPEC_ASSG "5"
9057 #define BUILTIN_REG_ASSG "6"
9058 #define BUILTIN_SPEC_REG_ASSG "7"
9060 /* Stubs for calling non-FAST_FUNC's */
9061 #if ENABLE_ASH_BUILTIN_ECHO
9062 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9064 #if ENABLE_ASH_BUILTIN_PRINTF
9065 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9067 #if ENABLE_ASH_BUILTIN_TEST
9068 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9071 /* Keep these in proper order since it is searched via bsearch() */
9072 static const struct builtincmd builtintab[] = {
9073 { BUILTIN_SPEC_REG "." , dotcmd },
9074 { BUILTIN_SPEC_REG ":" , truecmd },
9075 #if ENABLE_ASH_BUILTIN_TEST
9076 { BUILTIN_REGULAR "[" , testcmd },
9077 #if ENABLE_ASH_BASH_COMPAT
9078 { BUILTIN_REGULAR "[[" , testcmd },
9081 #if ENABLE_ASH_ALIAS
9082 { BUILTIN_REG_ASSG "alias" , aliascmd },
9085 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9087 { BUILTIN_SPEC_REG "break" , breakcmd },
9088 { BUILTIN_REGULAR "cd" , cdcmd },
9089 { BUILTIN_NOSPEC "chdir" , cdcmd },
9090 #if ENABLE_ASH_CMDCMD
9091 { BUILTIN_REGULAR "command" , commandcmd },
9093 { BUILTIN_SPEC_REG "continue", breakcmd },
9094 #if ENABLE_ASH_BUILTIN_ECHO
9095 { BUILTIN_REGULAR "echo" , echocmd },
9097 { BUILTIN_SPEC_REG "eval" , evalcmd },
9098 { BUILTIN_SPEC_REG "exec" , execcmd },
9099 { BUILTIN_SPEC_REG "exit" , exitcmd },
9100 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9101 { BUILTIN_REGULAR "false" , falsecmd },
9103 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9105 #if ENABLE_ASH_GETOPTS
9106 { BUILTIN_REGULAR "getopts" , getoptscmd },
9108 { BUILTIN_NOSPEC "hash" , hashcmd },
9109 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9110 { BUILTIN_NOSPEC "help" , helpcmd },
9113 { BUILTIN_NOSPEC "history" , historycmd },
9116 { BUILTIN_REGULAR "jobs" , jobscmd },
9117 { BUILTIN_REGULAR "kill" , killcmd },
9119 #if ENABLE_SH_MATH_SUPPORT
9120 { BUILTIN_NOSPEC "let" , letcmd },
9122 { BUILTIN_ASSIGN "local" , localcmd },
9123 #if ENABLE_ASH_BUILTIN_PRINTF
9124 { BUILTIN_REGULAR "printf" , printfcmd },
9126 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9127 { BUILTIN_REGULAR "read" , readcmd },
9128 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9129 { BUILTIN_SPEC_REG "return" , returncmd },
9130 { BUILTIN_SPEC_REG "set" , setcmd },
9131 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9132 #if ENABLE_ASH_BASH_COMPAT
9133 { BUILTIN_SPEC_REG "source" , dotcmd },
9135 #if ENABLE_ASH_BUILTIN_TEST
9136 { BUILTIN_REGULAR "test" , testcmd },
9138 { BUILTIN_SPEC_REG "times" , timescmd },
9139 { BUILTIN_SPEC_REG "trap" , trapcmd },
9140 { BUILTIN_REGULAR "true" , truecmd },
9141 { BUILTIN_NOSPEC "type" , typecmd },
9142 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9143 { BUILTIN_REGULAR "umask" , umaskcmd },
9144 #if ENABLE_ASH_ALIAS
9145 { BUILTIN_REGULAR "unalias" , unaliascmd },
9147 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9148 { BUILTIN_REGULAR "wait" , waitcmd },
9151 /* Should match the above table! */
9152 #define COMMANDCMD (builtintab + \
9154 1 * ENABLE_ASH_BUILTIN_TEST + \
9155 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9156 1 * ENABLE_ASH_ALIAS + \
9157 1 * ENABLE_ASH_JOB_CONTROL + \
9159 #define EXECCMD (builtintab + \
9161 1 * ENABLE_ASH_BUILTIN_TEST + \
9162 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9163 1 * ENABLE_ASH_ALIAS + \
9164 1 * ENABLE_ASH_JOB_CONTROL + \
9166 1 * ENABLE_ASH_CMDCMD + \
9168 ENABLE_ASH_BUILTIN_ECHO + \
9172 * Search the table of builtin commands.
9174 static struct builtincmd *
9175 find_builtin(const char *name)
9177 struct builtincmd *bp;
9180 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9187 * Execute a simple command.
9190 isassignment(const char *p)
9192 const char *q = endofname(p);
9197 static int FAST_FUNC
9198 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9200 /* Preserve exitstatus of a previous possible redirection
9201 * as POSIX mandates */
9202 return back_exitstatus;
9205 evalcommand(union node *cmd, int flags)
9207 static const struct builtincmd null_bltin = {
9208 "\0\0", bltincmd /* why three NULs? */
9210 struct stackmark smark;
9212 struct arglist arglist;
9213 struct arglist varlist;
9216 const struct strlist *sp;
9217 struct cmdentry cmdentry;
9224 struct builtincmd *bcmd;
9225 smallint cmd_is_exec;
9226 smallint pseudovarflag = 0;
9228 /* First expand the arguments. */
9229 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9230 setstackmark(&smark);
9231 back_exitstatus = 0;
9233 cmdentry.cmdtype = CMDBUILTIN;
9234 cmdentry.u.cmd = &null_bltin;
9235 varlist.lastp = &varlist.list;
9236 *varlist.lastp = NULL;
9237 arglist.lastp = &arglist.list;
9238 *arglist.lastp = NULL;
9241 if (cmd->ncmd.args) {
9242 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9243 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9246 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9247 struct strlist **spp;
9249 spp = arglist.lastp;
9250 if (pseudovarflag && isassignment(argp->narg.text))
9251 expandarg(argp, &arglist, EXP_VARTILDE);
9253 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9255 for (sp = *spp; sp; sp = sp->next)
9259 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9260 for (sp = arglist.list; sp; sp = sp->next) {
9261 TRACE(("evalcommand arg: %s\n", sp->text));
9262 *nargv++ = sp->text;
9267 if (iflag && funcnest == 0 && argc > 0)
9268 lastarg = nargv[-1];
9271 expredir(cmd->ncmd.redirect);
9272 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9274 path = vpath.var_text;
9275 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9276 struct strlist **spp;
9279 spp = varlist.lastp;
9280 expandarg(argp, &varlist, EXP_VARTILDE);
9283 * Modify the command lookup path, if a PATH= assignment
9287 if (varcmp(p, path) == 0)
9291 /* Print the command if xflag is set. */
9294 const char *p = " %s" + 1;
9296 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9298 for (n = 0; n < 2; n++) {
9300 fdprintf(preverrout_fd, p, sp->text);
9306 safe_write(preverrout_fd, "\n", 1);
9312 /* Now locate the command. */
9314 int cmd_flag = DO_ERR;
9315 #if ENABLE_ASH_CMDCMD
9316 const char *oldpath = path + 5;
9320 find_command(argv[0], &cmdentry, cmd_flag, path);
9321 if (cmdentry.cmdtype == CMDUNKNOWN) {
9322 flush_stdout_stderr();
9327 /* implement bltin and command here */
9328 if (cmdentry.cmdtype != CMDBUILTIN)
9331 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9332 if (cmdentry.u.cmd == EXECCMD)
9334 #if ENABLE_ASH_CMDCMD
9335 if (cmdentry.u.cmd == COMMANDCMD) {
9337 nargv = parse_command_args(argv, &path);
9340 argc -= nargv - argv;
9342 cmd_flag |= DO_NOFUNC;
9350 /* We have a redirection error. */
9352 raise_exception(EXERROR);
9354 exitstatus = status;
9358 /* Execute the command. */
9359 switch (cmdentry.cmdtype) {
9362 #if ENABLE_FEATURE_SH_NOFORK
9363 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9364 * around run_nofork_applet() call.
9365 * (2) Should this check also be done in forkshell()?
9366 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9368 /* find_command() encodes applet_no as (-2 - applet_no) */
9369 int applet_no = (- cmdentry.u.index - 2);
9370 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9371 listsetvar(varlist.list, VEXPORT|VSTACK);
9372 /* run <applet>_main() */
9373 exitstatus = run_nofork_applet(applet_no, argv);
9377 /* Can we avoid forking off? For example, very last command
9378 * in a script or a subshell does not need forking,
9379 * we can just exec it.
9381 if (!(flags & EV_EXIT) || may_have_traps) {
9382 /* No, forking off a child is necessary */
9384 jp = makejob(/*cmd,*/ 1);
9385 if (forkshell(jp, cmd, FORK_FG) != 0) {
9387 exitstatus = waitforjob(jp);
9389 TRACE(("forked child exited with %d\n", exitstatus));
9394 /* fall through to exec'ing external program */
9396 listsetvar(varlist.list, VEXPORT|VSTACK);
9397 shellexec(argv, path, cmdentry.u.index);
9401 cmdenviron = varlist.list;
9403 struct strlist *list = cmdenviron;
9405 if (spclbltin > 0 || argc == 0) {
9407 if (cmd_is_exec && argc > 1)
9410 listsetvar(list, i);
9412 /* Tight loop with builtins only:
9413 * "while kill -0 $child; do true; done"
9414 * will never exit even if $child died, unless we do this
9415 * to reap the zombie and make kill detect that it's gone: */
9416 dowait(DOWAIT_NONBLOCK, NULL);
9418 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9420 int i = exception_type;
9425 exit_status = 128 + SIGINT;
9427 exit_status = 128 + pending_sig;
9428 exitstatus = exit_status;
9429 if (i == EXINT || spclbltin > 0) {
9431 longjmp(exception_handler->loc, 1);
9438 listsetvar(varlist.list, 0);
9439 /* See above for the rationale */
9440 dowait(DOWAIT_NONBLOCK, NULL);
9441 if (evalfun(cmdentry.u.func, argc, argv, flags))
9448 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9450 /* dsl: I think this is intended to be used to support
9451 * '_' in 'vi' command mode during line editing...
9452 * However I implemented that within libedit itself.
9454 setvar2("_", lastarg);
9456 popstackmark(&smark);
9460 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9462 char *volatile savecmdname;
9463 struct jmploc *volatile savehandler;
9464 struct jmploc jmploc;
9467 savecmdname = commandname;
9468 i = setjmp(jmploc.loc);
9471 savehandler = exception_handler;
9472 exception_handler = &jmploc;
9473 commandname = argv[0];
9475 optptr = NULL; /* initialize nextopt */
9476 exitstatus = (*cmd->builtin)(argc, argv);
9477 flush_stdout_stderr();
9479 exitstatus |= ferror(stdout);
9481 commandname = savecmdname;
9482 exception_handler = savehandler;
9488 goodname(const char *p)
9490 return endofname(p)[0] == '\0';
9495 * Search for a command. This is called before we fork so that the
9496 * location of the command will be available in the parent as well as
9497 * the child. The check for "goodname" is an overly conservative
9498 * check that the name will not be subject to expansion.
9501 prehash(union node *n)
9503 struct cmdentry entry;
9505 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9506 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9510 /* ============ Builtin commands
9512 * Builtin commands whose functions are closely tied to evaluation
9513 * are implemented here.
9517 * Handle break and continue commands. Break, continue, and return are
9518 * all handled by setting the evalskip flag. The evaluation routines
9519 * above all check this flag, and if it is set they start skipping
9520 * commands rather than executing them. The variable skipcount is
9521 * the number of loops to break/continue, or the number of function
9522 * levels to return. (The latter is always 1.) It should probably
9523 * be an error to break out of more loops than exist, but it isn't
9524 * in the standard shell so we don't make it one here.
9526 static int FAST_FUNC
9527 breakcmd(int argc UNUSED_PARAM, char **argv)
9529 int n = argv[1] ? number(argv[1]) : 1;
9532 ash_msg_and_raise_error(msg_illnum, argv[1]);
9536 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9543 /* ============ input.c
9545 * This implements the input routines used by the parser.
9549 INPUT_PUSH_FILE = 1,
9550 INPUT_NOFILE_OK = 2,
9553 static smallint checkkwd;
9554 /* values of checkkwd variable */
9555 #define CHKALIAS 0x1
9560 * Push a string back onto the input at this current parsefile level.
9561 * We handle aliases this way.
9563 #if !ENABLE_ASH_ALIAS
9564 #define pushstring(s, ap) pushstring(s)
9567 pushstring(char *s, struct alias *ap)
9574 if (g_parsefile->strpush) {
9575 sp = ckzalloc(sizeof(*sp));
9576 sp->prev = g_parsefile->strpush;
9578 sp = &(g_parsefile->basestrpush);
9580 g_parsefile->strpush = sp;
9581 sp->prev_string = g_parsefile->next_to_pgetc;
9582 sp->prev_left_in_line = g_parsefile->left_in_line;
9583 #if ENABLE_ASH_ALIAS
9586 ap->flag |= ALIASINUSE;
9590 g_parsefile->next_to_pgetc = s;
9591 g_parsefile->left_in_line = len;
9598 struct strpush *sp = g_parsefile->strpush;
9601 #if ENABLE_ASH_ALIAS
9603 if (g_parsefile->next_to_pgetc[-1] == ' '
9604 || g_parsefile->next_to_pgetc[-1] == '\t'
9606 checkkwd |= CHKALIAS;
9608 if (sp->string != sp->ap->val) {
9611 sp->ap->flag &= ~ALIASINUSE;
9612 if (sp->ap->flag & ALIASDEAD) {
9613 unalias(sp->ap->name);
9617 g_parsefile->next_to_pgetc = sp->prev_string;
9618 g_parsefile->left_in_line = sp->prev_left_in_line;
9619 g_parsefile->strpush = sp->prev;
9620 if (sp != &(g_parsefile->basestrpush))
9625 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9626 //it peeks whether it is &>, and then pushes back both chars.
9627 //This function needs to save last *next_to_pgetc to buf[0]
9628 //to make two pungetc() reliable. Currently,
9629 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9634 char *buf = g_parsefile->buf;
9636 g_parsefile->next_to_pgetc = buf;
9637 #if ENABLE_FEATURE_EDITING
9639 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9640 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1, /*loop_on_EINTR:*/ 1);
9643 # if ENABLE_ASH_IDLE_TIMEOUT
9645 const char *tmout_var = lookupvar("TMOUT");
9647 timeout = atoi(tmout_var) * 1000;
9653 # if ENABLE_FEATURE_TAB_COMPLETION
9654 line_input_state->path_lookup = pathval();
9656 /* Unicode support should be activated even if LANG is set
9657 * _during_ shell execution, not only if it was set when
9658 * shell was started. Therefore, re-check LANG every time:
9661 const char *s = lookupvar("LC_ALL");
9662 if (!s) s = lookupvar("LC_CTYPE");
9663 if (!s) s = lookupvar("LANG");
9666 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9668 /* Ctrl+C pressed */
9679 /* Ctrl+D pressed */
9682 # if ENABLE_ASH_IDLE_TIMEOUT
9683 else if (errno == EAGAIN && timeout > 0) {
9684 printf("\007timed out waiting for input: auto-logout\n");
9691 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1, /*loop_on_EINTR:*/ 1);
9694 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9696 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9697 int flags = fcntl(0, F_GETFL);
9698 if (flags >= 0 && (flags & O_NONBLOCK)) {
9699 flags &= ~O_NONBLOCK;
9700 if (fcntl(0, F_SETFL, flags) >= 0) {
9701 out2str("sh: turning off NDELAY mode\n");
9712 * Refill the input buffer and return the next input character:
9714 * 1) If a string was pushed back on the input, pop it;
9715 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9716 * or we are reading from a string so we can't refill the buffer,
9718 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9719 * 4) Process input up to the next newline, deleting nul characters.
9721 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9722 #define pgetc_debug(...) ((void)0)
9729 while (g_parsefile->strpush) {
9730 #if ENABLE_ASH_ALIAS
9731 if (g_parsefile->left_in_line == -1
9732 && g_parsefile->strpush->ap
9733 && g_parsefile->next_to_pgetc[-1] != ' '
9734 && g_parsefile->next_to_pgetc[-1] != '\t'
9736 pgetc_debug("preadbuffer PEOA");
9741 /* try "pgetc" now: */
9742 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9743 g_parsefile->left_in_line,
9744 g_parsefile->next_to_pgetc,
9745 g_parsefile->next_to_pgetc);
9746 if (--g_parsefile->left_in_line >= 0)
9747 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9749 /* on both branches above g_parsefile->left_in_line < 0.
9750 * "pgetc" needs refilling.
9753 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9754 * pungetc() may increment it a few times.
9755 * Assuming it won't increment it to less than -90.
9757 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9758 pgetc_debug("preadbuffer PEOF1");
9759 /* even in failure keep left_in_line and next_to_pgetc
9760 * in lock step, for correct multi-layer pungetc.
9761 * left_in_line was decremented before preadbuffer(),
9762 * must inc next_to_pgetc: */
9763 g_parsefile->next_to_pgetc++;
9767 more = g_parsefile->left_in_buffer;
9769 flush_stdout_stderr();
9773 /* don't try reading again */
9774 g_parsefile->left_in_line = -99;
9775 pgetc_debug("preadbuffer PEOF2");
9776 g_parsefile->next_to_pgetc++;
9781 /* Find out where's the end of line.
9782 * Set g_parsefile->left_in_line
9783 * and g_parsefile->left_in_buffer acordingly.
9784 * NUL chars are deleted.
9786 q = g_parsefile->next_to_pgetc;
9794 memmove(q, q + 1, more);
9798 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9804 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9805 if (g_parsefile->left_in_line < 0)
9810 g_parsefile->left_in_buffer = more;
9815 out2str(g_parsefile->next_to_pgetc);
9819 pgetc_debug("preadbuffer at %d:%p'%s'",
9820 g_parsefile->left_in_line,
9821 g_parsefile->next_to_pgetc,
9822 g_parsefile->next_to_pgetc);
9823 return (unsigned char)*g_parsefile->next_to_pgetc++;
9826 #define pgetc_as_macro() \
9827 (--g_parsefile->left_in_line >= 0 \
9828 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9835 pgetc_debug("pgetc_fast at %d:%p'%s'",
9836 g_parsefile->left_in_line,
9837 g_parsefile->next_to_pgetc,
9838 g_parsefile->next_to_pgetc);
9839 return pgetc_as_macro();
9842 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9843 # define pgetc_fast() pgetc()
9845 # define pgetc_fast() pgetc_as_macro()
9848 #if ENABLE_ASH_ALIAS
9850 pgetc_without_PEOA(void)
9854 pgetc_debug("pgetc_fast at %d:%p'%s'",
9855 g_parsefile->left_in_line,
9856 g_parsefile->next_to_pgetc,
9857 g_parsefile->next_to_pgetc);
9859 } while (c == PEOA);
9863 # define pgetc_without_PEOA() pgetc()
9867 * Read a line from the script.
9870 pfgets(char *line, int len)
9876 while (--nleft > 0) {
9877 c = pgetc_without_PEOA();
9892 * Undo the last call to pgetc. Only one character may be pushed back.
9893 * PEOF may be pushed back.
9898 g_parsefile->left_in_line++;
9899 g_parsefile->next_to_pgetc--;
9900 pgetc_debug("pushed back to %d:%p'%s'",
9901 g_parsefile->left_in_line,
9902 g_parsefile->next_to_pgetc,
9903 g_parsefile->next_to_pgetc);
9907 * To handle the "." command, a stack of input files is used. Pushfile
9908 * adds a new entry to the stack and popfile restores the previous level.
9913 struct parsefile *pf;
9915 pf = ckzalloc(sizeof(*pf));
9916 pf->prev = g_parsefile;
9918 /*pf->strpush = NULL; - ckzalloc did it */
9919 /*pf->basestrpush.prev = NULL;*/
9926 struct parsefile *pf = g_parsefile;
9934 g_parsefile = pf->prev;
9940 * Return to top level.
9945 while (g_parsefile != &basepf)
9950 * Close the file(s) that the shell is reading commands from. Called
9951 * after a fork is done.
9957 if (g_parsefile->pf_fd > 0) {
9958 close(g_parsefile->pf_fd);
9959 g_parsefile->pf_fd = 0;
9964 * Like setinputfile, but takes an open file descriptor. Call this with
9968 setinputfd(int fd, int push)
9970 close_on_exec_on(fd);
9973 g_parsefile->buf = NULL;
9975 g_parsefile->pf_fd = fd;
9976 if (g_parsefile->buf == NULL)
9977 g_parsefile->buf = ckmalloc(IBUFSIZ);
9978 g_parsefile->left_in_buffer = 0;
9979 g_parsefile->left_in_line = 0;
9980 g_parsefile->linno = 1;
9984 * Set the input to take input from a file. If push is set, push the
9985 * old input onto the stack first.
9988 setinputfile(const char *fname, int flags)
9994 fd = open(fname, O_RDONLY);
9996 if (flags & INPUT_NOFILE_OK)
9998 ash_msg_and_raise_error("can't open '%s'", fname);
10001 fd2 = copyfd(fd, 10);
10004 ash_msg_and_raise_error("out of file descriptors");
10007 setinputfd(fd, flags & INPUT_PUSH_FILE);
10014 * Like setinputfile, but takes input from a string.
10017 setinputstring(char *string)
10021 g_parsefile->next_to_pgetc = string;
10022 g_parsefile->left_in_line = strlen(string);
10023 g_parsefile->buf = NULL;
10024 g_parsefile->linno = 1;
10029 /* ============ mail.c
10031 * Routines to check for mail.
10034 #if ENABLE_ASH_MAIL
10036 #define MAXMBOXES 10
10038 /* times of mailboxes */
10039 static time_t mailtime[MAXMBOXES];
10040 /* Set if MAIL or MAILPATH is changed. */
10041 static smallint mail_var_path_changed;
10044 * Print appropriate message(s) if mail has arrived.
10045 * If mail_var_path_changed is set,
10046 * then the value of MAIL has mail_var_path_changed,
10047 * so we just update the values.
10056 struct stackmark smark;
10059 setstackmark(&smark);
10060 mpath = mpathset() ? mpathval() : mailval();
10061 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
10062 p = path_advance(&mpath, nullstr);
10067 for (q = p; *q; q++)
10073 q[-1] = '\0'; /* delete trailing '/' */
10074 if (stat(p, &statb) < 0) {
10078 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
10081 pathopt ? pathopt : "you have mail"
10084 *mtp = statb.st_mtime;
10086 mail_var_path_changed = 0;
10087 popstackmark(&smark);
10090 static void FAST_FUNC
10091 changemail(const char *val UNUSED_PARAM)
10093 mail_var_path_changed = 1;
10096 #endif /* ASH_MAIL */
10099 /* ============ ??? */
10102 * Set the shell parameters.
10105 setparam(char **argv)
10111 for (nparam = 0; argv[nparam]; nparam++)
10113 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10115 *ap++ = ckstrdup(*argv++);
10118 freeparam(&shellparam);
10119 shellparam.malloced = 1;
10120 shellparam.nparam = nparam;
10121 shellparam.p = newparam;
10122 #if ENABLE_ASH_GETOPTS
10123 shellparam.optind = 1;
10124 shellparam.optoff = -1;
10129 * Process shell options. The global variable argptr contains a pointer
10130 * to the argument list; we advance it past the options.
10132 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10133 * For a non-interactive shell, an error condition encountered
10134 * by a special built-in ... shall cause the shell to write a diagnostic message
10135 * to standard error and exit as shown in the following table:
10136 * Error Special Built-In
10138 * Utility syntax error (option or operand error) Shall exit
10140 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10141 * we see that bash does not do that (set "finishes" with error code 1 instead,
10142 * and shell continues), and people rely on this behavior!
10144 * set -o barfoo 2>/dev/null
10147 * Oh well. Let's mimic that.
10150 plus_minus_o(char *name, int val)
10155 for (i = 0; i < NOPTS; i++) {
10156 if (strcmp(name, optnames(i)) == 0) {
10161 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10164 for (i = 0; i < NOPTS; i++) {
10166 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10168 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10174 setoption(int flag, int val)
10178 for (i = 0; i < NOPTS; i++) {
10179 if (optletters(i) == flag) {
10184 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10188 options(int cmdline)
10196 while ((p = *argptr) != NULL) {
10198 if (c != '-' && c != '+')
10201 val = 0; /* val = 0 if c == '+' */
10204 if (p[0] == '\0' || LONE_DASH(p)) {
10206 /* "-" means turn off -x and -v */
10209 /* "--" means reset params */
10210 else if (*argptr == NULL)
10213 break; /* "-" or "--" terminates options */
10216 /* first char was + or - */
10217 while ((c = *p++) != '\0') {
10218 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10219 if (c == 'c' && cmdline) {
10220 minusc = p; /* command is after shell args */
10221 } else if (c == 'o') {
10222 if (plus_minus_o(*argptr, val)) {
10223 /* it already printed err message */
10224 return 1; /* error */
10228 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10230 /* bash does not accept +-login, we also won't */
10231 } else if (cmdline && val && (c == '-')) { /* long options */
10232 if (strcmp(p, "login") == 0)
10244 * The shift builtin command.
10246 static int FAST_FUNC
10247 shiftcmd(int argc UNUSED_PARAM, char **argv)
10254 n = number(argv[1]);
10255 if (n > shellparam.nparam)
10256 n = 0; /* bash compat, was = shellparam.nparam; */
10258 shellparam.nparam -= n;
10259 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10260 if (shellparam.malloced)
10263 ap2 = shellparam.p;
10264 while ((*ap2++ = *ap1++) != NULL)
10266 #if ENABLE_ASH_GETOPTS
10267 shellparam.optind = 1;
10268 shellparam.optoff = -1;
10275 * POSIX requires that 'set' (but not export or readonly) output the
10276 * variables in lexicographic order - by the locale's collating order (sigh).
10277 * Maybe we could keep them in an ordered balanced binary tree
10278 * instead of hashed lists.
10279 * For now just roll 'em through qsort for printing...
10282 showvars(const char *sep_prefix, int on, int off)
10285 char **ep, **epend;
10287 ep = listvars(on, off, &epend);
10288 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10290 sep = *sep_prefix ? " " : sep_prefix;
10292 for (; ep < epend; ep++) {
10296 p = strchrnul(*ep, '=');
10299 q = single_quote(++p);
10300 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10306 * The set command builtin.
10308 static int FAST_FUNC
10309 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10314 return showvars(nullstr, 0, VUNSET);
10317 retval = options(/*cmdline:*/ 0);
10318 if (retval == 0) { /* if no parse error... */
10320 if (*argptr != NULL) {
10328 #if ENABLE_ASH_RANDOM_SUPPORT
10329 static void FAST_FUNC
10330 change_random(const char *value)
10334 if (value == NULL) {
10335 /* "get", generate */
10336 t = next_random(&random_gen);
10337 /* set without recursion */
10338 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10339 vrandom.flags &= ~VNOFUNC;
10342 t = strtoul(value, NULL, 10);
10343 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10348 #if ENABLE_ASH_GETOPTS
10350 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10359 if (*param_optind < 1)
10361 optnext = optfirst + *param_optind - 1;
10363 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10366 p = optnext[-1] + *optoff;
10367 if (p == NULL || *p == '\0') {
10368 /* Current word is done, advance */
10370 if (p == NULL || *p != '-' || *++p == '\0') {
10377 if (LONE_DASH(p)) /* check for "--" */
10382 for (q = optstr; *q != c;) {
10384 if (optstr[0] == ':') {
10387 err |= setvarsafe("OPTARG", s, 0);
10389 fprintf(stderr, "Illegal option -%c\n", c);
10390 unsetvar("OPTARG");
10400 if (*p == '\0' && (p = *optnext) == NULL) {
10401 if (optstr[0] == ':') {
10404 err |= setvarsafe("OPTARG", s, 0);
10407 fprintf(stderr, "No arg for -%c option\n", c);
10408 unsetvar("OPTARG");
10416 err |= setvarsafe("OPTARG", p, 0);
10419 err |= setvarsafe("OPTARG", nullstr, 0);
10421 *optoff = p ? p - *(optnext - 1) : -1;
10422 *param_optind = optnext - optfirst + 1;
10423 fmtstr(s, sizeof(s), "%d", *param_optind);
10424 err |= setvarsafe("OPTIND", s, VNOFUNC);
10427 err |= setvarsafe(optvar, s, 0);
10431 flush_stdout_stderr();
10432 raise_exception(EXERROR);
10438 * The getopts builtin. Shellparam.optnext points to the next argument
10439 * to be processed. Shellparam.optptr points to the next character to
10440 * be processed in the current argument. If shellparam.optnext is NULL,
10441 * then it's the first time getopts has been called.
10443 static int FAST_FUNC
10444 getoptscmd(int argc, char **argv)
10449 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10451 optbase = shellparam.p;
10452 if (shellparam.optind > shellparam.nparam + 1) {
10453 shellparam.optind = 1;
10454 shellparam.optoff = -1;
10457 optbase = &argv[3];
10458 if (shellparam.optind > argc - 2) {
10459 shellparam.optind = 1;
10460 shellparam.optoff = -1;
10464 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10465 &shellparam.optoff);
10467 #endif /* ASH_GETOPTS */
10470 /* ============ Shell parser */
10473 struct heredoc *next; /* next here document in list */
10474 union node *here; /* redirection node */
10475 char *eofmark; /* string indicating end of input */
10476 smallint striptabs; /* if set, strip leading tabs */
10479 static smallint tokpushback; /* last token pushed back */
10480 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10481 static smallint quoteflag; /* set if (part of) last token was quoted */
10482 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10483 static struct heredoc *heredoclist; /* list of here documents to read */
10484 static char *wordtext; /* text of last word returned by readtoken */
10485 static struct nodelist *backquotelist;
10486 static union node *redirnode;
10487 static struct heredoc *heredoc;
10489 static const char *
10490 tokname(char *buf, int tok)
10493 return tokname_array[tok] + 1;
10494 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10498 /* raise_error_unexpected_syntax:
10499 * Called when an unexpected token is read during the parse. The argument
10500 * is the token that is expected, or -1 if more than one type of token can
10501 * occur at this point.
10503 static void raise_error_unexpected_syntax(int) NORETURN;
10505 raise_error_unexpected_syntax(int token)
10511 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10513 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10514 raise_error_syntax(msg);
10518 #define EOFMARKLEN 79
10520 /* parsing is heavily cross-recursive, need these forward decls */
10521 static union node *andor(void);
10522 static union node *pipeline(void);
10523 static union node *parse_command(void);
10524 static void parseheredoc(void);
10525 static char peektoken(void);
10526 static int readtoken(void);
10528 static union node *
10531 union node *n1, *n2, *n3;
10534 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10535 if (nlflag == 2 && peektoken())
10541 if (tok == TBACKGND) {
10542 if (n2->type == NPIPE) {
10543 n2->npipe.pipe_backgnd = 1;
10545 if (n2->type != NREDIR) {
10546 n3 = stzalloc(sizeof(struct nredir));
10548 /*n3->nredir.redirect = NULL; - stzalloc did it */
10551 n2->type = NBACKGND;
10557 n3 = stzalloc(sizeof(struct nbinary));
10559 n3->nbinary.ch1 = n1;
10560 n3->nbinary.ch2 = n2;
10576 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10584 pungetc(); /* push back EOF on input */
10588 raise_error_unexpected_syntax(-1);
10595 static union node *
10598 union node *n1, *n2, *n3;
10606 } else if (t == TOR) {
10612 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10614 n3 = stzalloc(sizeof(struct nbinary));
10616 n3->nbinary.ch1 = n1;
10617 n3->nbinary.ch2 = n2;
10622 static union node *
10625 union node *n1, *n2, *pipenode;
10626 struct nodelist *lp, *prev;
10630 TRACE(("pipeline: entered\n"));
10631 if (readtoken() == TNOT) {
10633 checkkwd = CHKKWD | CHKALIAS;
10636 n1 = parse_command();
10637 if (readtoken() == TPIPE) {
10638 pipenode = stzalloc(sizeof(struct npipe));
10639 pipenode->type = NPIPE;
10640 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10641 lp = stzalloc(sizeof(struct nodelist));
10642 pipenode->npipe.cmdlist = lp;
10646 lp = stzalloc(sizeof(struct nodelist));
10647 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10648 lp->n = parse_command();
10650 } while (readtoken() == TPIPE);
10656 n2 = stzalloc(sizeof(struct nnot));
10664 static union node *
10669 n = stzalloc(sizeof(struct narg));
10671 /*n->narg.next = NULL; - stzalloc did it */
10672 n->narg.text = wordtext;
10673 n->narg.backquote = backquotelist;
10678 fixredir(union node *n, const char *text, int err)
10682 TRACE(("Fix redir %s %d\n", text, err));
10684 n->ndup.vname = NULL;
10686 fd = bb_strtou(text, NULL, 10);
10687 if (!errno && fd >= 0)
10688 n->ndup.dupfd = fd;
10689 else if (LONE_DASH(text))
10690 n->ndup.dupfd = -1;
10693 raise_error_syntax("bad fd number");
10694 n->ndup.vname = makename();
10699 * Returns true if the text contains nothing to expand (no dollar signs
10703 noexpand(const char *text)
10707 while ((c = *text++) != '\0') {
10708 if (c == CTLQUOTEMARK)
10712 else if (SIT(c, BASESYNTAX) == CCTL)
10721 union node *n = redirnode;
10723 if (readtoken() != TWORD)
10724 raise_error_unexpected_syntax(-1);
10725 if (n->type == NHERE) {
10726 struct heredoc *here = heredoc;
10730 if (quoteflag == 0)
10732 TRACE(("Here document %d\n", n->type));
10733 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10734 raise_error_syntax("illegal eof marker for << redirection");
10735 rmescapes(wordtext, 0);
10736 here->eofmark = wordtext;
10738 if (heredoclist == NULL)
10739 heredoclist = here;
10741 for (p = heredoclist; p->next; p = p->next)
10745 } else if (n->type == NTOFD || n->type == NFROMFD) {
10746 fixredir(n, wordtext, 0);
10748 n->nfile.fname = makename();
10752 static union node *
10755 union node *args, **app;
10756 union node *n = NULL;
10757 union node *vars, **vpp;
10758 union node **rpp, *redir;
10760 #if ENABLE_ASH_BASH_COMPAT
10761 smallint double_brackets_flag = 0;
10771 savecheckkwd = CHKALIAS;
10774 checkkwd = savecheckkwd;
10777 #if ENABLE_ASH_BASH_COMPAT
10778 case TAND: /* "&&" */
10779 case TOR: /* "||" */
10780 if (!double_brackets_flag) {
10784 wordtext = (char *) (t == TAND ? "-a" : "-o");
10787 n = stzalloc(sizeof(struct narg));
10789 /*n->narg.next = NULL; - stzalloc did it */
10790 n->narg.text = wordtext;
10791 #if ENABLE_ASH_BASH_COMPAT
10792 if (strcmp("[[", wordtext) == 0)
10793 double_brackets_flag = 1;
10794 else if (strcmp("]]", wordtext) == 0)
10795 double_brackets_flag = 0;
10797 n->narg.backquote = backquotelist;
10798 if (savecheckkwd && isassignment(wordtext)) {
10800 vpp = &n->narg.next;
10803 app = &n->narg.next;
10808 *rpp = n = redirnode;
10809 rpp = &n->nfile.next;
10810 parsefname(); /* read name of redirection file */
10813 if (args && app == &args->narg.next
10816 struct builtincmd *bcmd;
10819 /* We have a function */
10820 if (readtoken() != TRP)
10821 raise_error_unexpected_syntax(TRP);
10822 name = n->narg.text;
10823 if (!goodname(name)
10824 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10826 raise_error_syntax("bad function name");
10829 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10830 n->narg.next = parse_command();
10843 n = stzalloc(sizeof(struct ncmd));
10845 n->ncmd.args = args;
10846 n->ncmd.assign = vars;
10847 n->ncmd.redirect = redir;
10851 static union node *
10852 parse_command(void)
10854 union node *n1, *n2;
10855 union node *ap, **app;
10856 union node *cp, **cpp;
10857 union node *redir, **rpp;
10864 switch (readtoken()) {
10866 raise_error_unexpected_syntax(-1);
10869 n1 = stzalloc(sizeof(struct nif));
10871 n1->nif.test = list(0);
10872 if (readtoken() != TTHEN)
10873 raise_error_unexpected_syntax(TTHEN);
10874 n1->nif.ifpart = list(0);
10876 while (readtoken() == TELIF) {
10877 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10878 n2 = n2->nif.elsepart;
10880 n2->nif.test = list(0);
10881 if (readtoken() != TTHEN)
10882 raise_error_unexpected_syntax(TTHEN);
10883 n2->nif.ifpart = list(0);
10885 if (lasttoken == TELSE)
10886 n2->nif.elsepart = list(0);
10888 n2->nif.elsepart = NULL;
10896 n1 = stzalloc(sizeof(struct nbinary));
10897 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10898 n1->nbinary.ch1 = list(0);
10901 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10902 got == TWORD ? wordtext : ""));
10903 raise_error_unexpected_syntax(TDO);
10905 n1->nbinary.ch2 = list(0);
10910 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10911 raise_error_syntax("bad for loop variable");
10912 n1 = stzalloc(sizeof(struct nfor));
10914 n1->nfor.var = wordtext;
10915 checkkwd = CHKKWD | CHKALIAS;
10916 if (readtoken() == TIN) {
10918 while (readtoken() == TWORD) {
10919 n2 = stzalloc(sizeof(struct narg));
10921 /*n2->narg.next = NULL; - stzalloc did it */
10922 n2->narg.text = wordtext;
10923 n2->narg.backquote = backquotelist;
10925 app = &n2->narg.next;
10928 n1->nfor.args = ap;
10929 if (lasttoken != TNL && lasttoken != TSEMI)
10930 raise_error_unexpected_syntax(-1);
10932 n2 = stzalloc(sizeof(struct narg));
10934 /*n2->narg.next = NULL; - stzalloc did it */
10935 n2->narg.text = (char *)dolatstr;
10936 /*n2->narg.backquote = NULL;*/
10937 n1->nfor.args = n2;
10939 * Newline or semicolon here is optional (but note
10940 * that the original Bourne shell only allowed NL).
10942 if (lasttoken != TNL && lasttoken != TSEMI)
10945 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10946 if (readtoken() != TDO)
10947 raise_error_unexpected_syntax(TDO);
10948 n1->nfor.body = list(0);
10952 n1 = stzalloc(sizeof(struct ncase));
10954 if (readtoken() != TWORD)
10955 raise_error_unexpected_syntax(TWORD);
10956 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10958 /*n2->narg.next = NULL; - stzalloc did it */
10959 n2->narg.text = wordtext;
10960 n2->narg.backquote = backquotelist;
10962 checkkwd = CHKKWD | CHKALIAS;
10963 } while (readtoken() == TNL);
10964 if (lasttoken != TIN)
10965 raise_error_unexpected_syntax(TIN);
10966 cpp = &n1->ncase.cases;
10968 checkkwd = CHKNL | CHKKWD;
10970 while (t != TESAC) {
10971 if (lasttoken == TLP)
10973 *cpp = cp = stzalloc(sizeof(struct nclist));
10975 app = &cp->nclist.pattern;
10977 *app = ap = stzalloc(sizeof(struct narg));
10979 /*ap->narg.next = NULL; - stzalloc did it */
10980 ap->narg.text = wordtext;
10981 ap->narg.backquote = backquotelist;
10982 if (readtoken() != TPIPE)
10984 app = &ap->narg.next;
10987 //ap->narg.next = NULL;
10988 if (lasttoken != TRP)
10989 raise_error_unexpected_syntax(TRP);
10990 cp->nclist.body = list(2);
10992 cpp = &cp->nclist.next;
10994 checkkwd = CHKNL | CHKKWD;
10998 raise_error_unexpected_syntax(TENDCASE);
11005 n1 = stzalloc(sizeof(struct nredir));
11006 n1->type = NSUBSHELL;
11007 n1->nredir.n = list(0);
11008 /*n1->nredir.redirect = NULL; - stzalloc did it */
11018 return simplecmd();
11021 if (readtoken() != t)
11022 raise_error_unexpected_syntax(t);
11025 /* Now check for redirection which may follow command */
11026 checkkwd = CHKKWD | CHKALIAS;
11028 while (readtoken() == TREDIR) {
11029 *rpp = n2 = redirnode;
11030 rpp = &n2->nfile.next;
11036 if (n1->type != NSUBSHELL) {
11037 n2 = stzalloc(sizeof(struct nredir));
11042 n1->nredir.redirect = redir;
11047 #if ENABLE_ASH_BASH_COMPAT
11048 static int decode_dollar_squote(void)
11050 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11056 p = strchr(C_escapes, c);
11061 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11065 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11067 } else if (c == 'x') { /* \xHH */
11071 } while (isxdigit(c) && --cnt);
11073 if (cnt == 3) { /* \x but next char is "bad" */
11077 } else { /* simple seq like \\ or \t */
11082 c = bb_process_escape_sequence((void*)&p);
11083 } else { /* unrecognized "\z": print both chars unless ' or " */
11084 if (c != '\'' && c != '"') {
11086 c |= 0x100; /* "please encode \, then me" */
11094 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11095 * is not NULL, read a here document. In the latter case, eofmark is the
11096 * word which marks the end of the document and striptabs is true if
11097 * leading tabs should be stripped from the document. The argument c
11098 * is the first character of the input token or document.
11100 * Because C does not have internal subroutines, I have simulated them
11101 * using goto's to implement the subroutine linkage. The following macros
11102 * will run code that appears at the end of readtoken1.
11104 #define CHECKEND() {goto checkend; checkend_return:;}
11105 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11106 #define PARSESUB() {goto parsesub; parsesub_return:;}
11107 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11108 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11109 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11111 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11113 /* NB: syntax parameter fits into smallint */
11114 /* c parameter is an unsigned char or PEOF or PEOA */
11117 char line[EOFMARKLEN + 1];
11118 struct nodelist *bqlist;
11122 smallint prevsyntax; /* syntax before arithmetic */
11123 #if ENABLE_ASH_EXPAND_PRMT
11124 smallint pssyntax; /* we are expanding a prompt string */
11126 int varnest; /* levels of variables expansion */
11127 int arinest; /* levels of arithmetic expansion */
11128 int parenlevel; /* levels of parens in arithmetic */
11129 int dqvarnest; /* levels of variables expansion within double quotes */
11131 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11134 /* Avoid longjmp clobbering */
11140 (void) &parenlevel;
11143 (void) &prevsyntax;
11146 startlinno = g_parsefile->linno;
11150 #if ENABLE_ASH_EXPAND_PRMT
11151 pssyntax = (syntax == PSSYNTAX);
11155 dblquote = (syntax == DQSYNTAX);
11161 STARTSTACKSTR(out);
11163 /* For each line, until end of word */
11164 CHECKEND(); /* set c to PEOF if at end of here document */
11165 for (;;) { /* until end of line or end of word */
11166 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11167 switch (SIT(c, syntax)) {
11168 case CNL: /* '\n' */
11169 if (syntax == BASESYNTAX)
11170 goto endword; /* exit outer loop */
11172 g_parsefile->linno++;
11173 setprompt_if(doprompt, 2);
11175 goto loop; /* continue outer loop */
11180 if (eofmark == NULL || dblquote)
11181 USTPUTC(CTLESC, out);
11182 #if ENABLE_ASH_BASH_COMPAT
11183 if (c == '\\' && bash_dollar_squote) {
11184 c = decode_dollar_squote();
11186 USTPUTC('\\', out);
11187 c = (unsigned char)c;
11193 case CBACK: /* backslash */
11194 c = pgetc_without_PEOA();
11196 USTPUTC(CTLESC, out);
11197 USTPUTC('\\', out);
11199 } else if (c == '\n') {
11200 setprompt_if(doprompt, 2);
11202 #if ENABLE_ASH_EXPAND_PRMT
11203 if (c == '$' && pssyntax) {
11204 USTPUTC(CTLESC, out);
11205 USTPUTC('\\', out);
11208 /* Backslash is retained if we are in "str" and next char isn't special */
11213 && (c != '"' || eofmark != NULL)
11215 USTPUTC(CTLESC, out);
11216 USTPUTC('\\', out);
11218 if (SIT(c, SQSYNTAX) == CCTL)
11219 USTPUTC(CTLESC, out);
11227 if (eofmark == NULL) {
11228 USTPUTC(CTLQUOTEMARK, out);
11236 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11237 if (eofmark != NULL && arinest == 0
11242 if (dqvarnest == 0) {
11243 syntax = BASESYNTAX;
11250 case CVAR: /* '$' */
11251 PARSESUB(); /* parse substitution */
11253 case CENDVAR: /* '}' */
11256 if (dqvarnest > 0) {
11263 #if ENABLE_SH_MATH_SUPPORT
11264 case CLP: /* '(' in arithmetic */
11268 case CRP: /* ')' in arithmetic */
11269 if (parenlevel > 0) {
11272 if (pgetc() == ')') {
11273 if (--arinest == 0) {
11274 syntax = prevsyntax;
11275 dblquote = (syntax == DQSYNTAX);
11280 * unbalanced parens
11281 * (don't 2nd guess - no error)
11289 case CBQUOTE: /* '`' */
11293 goto endword; /* exit outer loop */
11297 if (varnest == 0) {
11298 #if ENABLE_ASH_BASH_COMPAT
11300 if (pgetc() == '>')
11301 c = 0x100 + '>'; /* flag &> */
11305 goto endword; /* exit outer loop */
11307 IF_ASH_ALIAS(if (c != PEOA))
11314 #if ENABLE_SH_MATH_SUPPORT
11315 if (syntax == ARISYNTAX)
11316 raise_error_syntax("missing '))'");
11318 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11319 raise_error_syntax("unterminated quoted string");
11320 if (varnest != 0) {
11321 startlinno = g_parsefile->linno;
11323 raise_error_syntax("missing '}'");
11325 USTPUTC('\0', out);
11326 len = out - (char *)stackblock();
11327 out = stackblock();
11328 if (eofmark == NULL) {
11329 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11332 if (isdigit_str9(out)) {
11333 PARSEREDIR(); /* passed as params: out, c */
11334 lasttoken = TREDIR;
11337 /* else: non-number X seen, interpret it
11338 * as "NNNX>file" = "NNNX >file" */
11342 quoteflag = quotef;
11343 backquotelist = bqlist;
11344 grabstackblock(len);
11348 /* end of readtoken routine */
11351 * Check to see whether we are at the end of the here document. When this
11352 * is called, c is set to the first character of the next input line. If
11353 * we are at the end of the here document, this routine sets the c to PEOF.
11357 #if ENABLE_ASH_ALIAS
11359 c = pgetc_without_PEOA();
11362 while (c == '\t') {
11363 c = pgetc_without_PEOA();
11366 if (c == *eofmark) {
11367 if (pfgets(line, sizeof(line)) != NULL) {
11371 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11373 if (*p == '\n' && *q == '\0') {
11375 g_parsefile->linno++;
11376 needprompt = doprompt;
11378 pushstring(line, NULL);
11383 goto checkend_return;
11387 * Parse a redirection operator. The variable "out" points to a string
11388 * specifying the fd to be redirected. The variable "c" contains the
11389 * first character of the redirection operator.
11392 /* out is already checked to be a valid number or "" */
11393 int fd = (*out == '\0' ? -1 : atoi(out));
11396 np = stzalloc(sizeof(struct nfile));
11401 np->type = NAPPEND;
11403 np->type = NCLOBBER;
11406 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11412 #if ENABLE_ASH_BASH_COMPAT
11413 else if (c == 0x100 + '>') { /* this flags &> redirection */
11415 pgetc(); /* this is '>', no need to check */
11419 else { /* c == '<' */
11420 /*np->nfile.fd = 0; - stzalloc did it */
11424 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11425 np = stzalloc(sizeof(struct nhere));
11426 /*np->nfile.fd = 0; - stzalloc did it */
11429 heredoc = stzalloc(sizeof(struct heredoc));
11430 heredoc->here = np;
11433 heredoc->striptabs = 1;
11435 /*heredoc->striptabs = 0; - stzalloc did it */
11441 np->type = NFROMFD;
11445 np->type = NFROMTO;
11457 goto parseredir_return;
11461 * Parse a substitution. At this point, we have read the dollar sign
11462 * and nothing else.
11465 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11466 * (assuming ascii char codes, as the original implementation did) */
11467 #define is_special(c) \
11468 (((unsigned)(c) - 33 < 32) \
11469 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11471 unsigned char subtype;
11476 if (c > 255 /* PEOA or PEOF */
11477 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11479 #if ENABLE_ASH_BASH_COMPAT
11481 bash_dollar_squote = 1;
11486 } else if (c == '(') {
11487 /* $(command) or $((arith)) */
11488 if (pgetc() == '(') {
11489 #if ENABLE_SH_MATH_SUPPORT
11492 raise_error_syntax("you disabled math support for $((arith)) syntax");
11499 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11500 USTPUTC(CTLVAR, out);
11501 typeloc = out - (char *)stackblock();
11502 USTPUTC(VSNORMAL, out);
11503 subtype = VSNORMAL;
11509 c = '#'; /* ${#} - same as $# */
11511 subtype = VSLENGTH; /* ${#VAR} */
11516 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11517 /* $[{[#]]NAME[}] */
11521 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11522 } else if (isdigit(c)) {
11523 /* $[{[#]]NUM[}] */
11527 } while (isdigit(c));
11528 } else if (is_special(c)) {
11529 /* $[{[#]]<specialchar>[}] */
11534 raise_error_syntax("bad substitution");
11536 if (c != '}' && subtype == VSLENGTH) {
11537 /* ${#VAR didn't end with } */
11543 if (subtype == 0) {
11544 /* ${VAR...} but not $VAR or ${#VAR} */
11545 /* c == first char after VAR */
11549 #if ENABLE_ASH_BASH_COMPAT
11550 if (c == ':' || c == '$' || isdigit(c)) {
11551 //TODO: support more general format ${v:EXPR:EXPR},
11552 // where EXPR follows $(()) rules
11553 subtype = VSSUBSTR;
11555 break; /* "goto do_pungetc" is bigger (!) */
11561 static const char types[] ALIGN1 = "}-+?=";
11562 const char *p = strchr(types, c);
11565 subtype = p - types + VSNORMAL;
11571 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11578 #if ENABLE_ASH_BASH_COMPAT
11580 /* ${v/[/]pattern/repl} */
11581 //TODO: encode pattern and repl separately.
11582 // Currently ${v/$var_with_slash/repl} is horribly broken
11583 subtype = VSREPLACE;
11587 subtype++; /* VSREPLACEALL */
11595 if (dblquote || arinest)
11597 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11598 if (subtype != VSNORMAL) {
11600 if (dblquote || arinest) {
11605 goto parsesub_return;
11609 * Called to parse command substitutions. Newstyle is set if the command
11610 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11611 * list of commands (passed by reference), and savelen is the number of
11612 * characters on the top of the stack which must be preserved.
11615 struct nodelist **nlpp;
11618 char *volatile str;
11619 struct jmploc jmploc;
11620 struct jmploc *volatile savehandler;
11622 smallint saveprompt = 0;
11625 (void) &saveprompt;
11627 savepbq = parsebackquote;
11628 if (setjmp(jmploc.loc)) {
11630 parsebackquote = 0;
11631 exception_handler = savehandler;
11632 longjmp(exception_handler->loc, 1);
11636 savelen = out - (char *)stackblock();
11638 str = ckmalloc(savelen);
11639 memcpy(str, stackblock(), savelen);
11641 savehandler = exception_handler;
11642 exception_handler = &jmploc;
11645 /* We must read until the closing backquote, giving special
11646 * treatment to some slashes, and then push the string and
11647 * reread it as input, interpreting it normally.
11653 STARTSTACKSTR(pout);
11657 setprompt_if(needprompt, 2);
11666 g_parsefile->linno++;
11667 setprompt_if(doprompt, 2);
11669 * If eating a newline, avoid putting
11670 * the newline into the new character
11671 * stream (via the STPUTC after the
11676 if (pc != '\\' && pc != '`' && pc != '$'
11677 && (!dblquote || pc != '"')
11679 STPUTC('\\', pout);
11681 if (pc <= 255 /* not PEOA or PEOF */) {
11687 IF_ASH_ALIAS(case PEOA:)
11688 startlinno = g_parsefile->linno;
11689 raise_error_syntax("EOF in backquote substitution");
11692 g_parsefile->linno++;
11693 needprompt = doprompt;
11702 STPUTC('\0', pout);
11703 psavelen = pout - (char *)stackblock();
11704 if (psavelen > 0) {
11705 pstr = grabstackstr(pout);
11706 setinputstring(pstr);
11711 nlpp = &(*nlpp)->next;
11712 *nlpp = stzalloc(sizeof(**nlpp));
11713 /* (*nlpp)->next = NULL; - stzalloc did it */
11714 parsebackquote = oldstyle;
11717 saveprompt = doprompt;
11724 doprompt = saveprompt;
11725 else if (readtoken() != TRP)
11726 raise_error_unexpected_syntax(TRP);
11731 * Start reading from old file again, ignoring any pushed back
11732 * tokens left from the backquote parsing
11737 while (stackblocksize() <= savelen)
11739 STARTSTACKSTR(out);
11741 memcpy(out, str, savelen);
11742 STADJUST(savelen, out);
11748 parsebackquote = savepbq;
11749 exception_handler = savehandler;
11750 if (arinest || dblquote)
11751 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11753 USTPUTC(CTLBACKQ, out);
11755 goto parsebackq_oldreturn;
11756 goto parsebackq_newreturn;
11759 #if ENABLE_SH_MATH_SUPPORT
11761 * Parse an arithmetic expansion (indicate start of one and set state)
11764 if (++arinest == 1) {
11765 prevsyntax = syntax;
11766 syntax = ARISYNTAX;
11767 USTPUTC(CTLARI, out);
11774 * we collapse embedded arithmetic expansion to
11775 * parenthesis, which should be equivalent
11779 goto parsearith_return;
11783 } /* end of readtoken */
11786 * Read the next input token.
11787 * If the token is a word, we set backquotelist to the list of cmds in
11788 * backquotes. We set quoteflag to true if any part of the word was
11790 * If the token is TREDIR, then we set redirnode to a structure containing
11792 * In all cases, the variable startlinno is set to the number of the line
11793 * on which the token starts.
11795 * [Change comment: here documents and internal procedures]
11796 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11797 * word parsing code into a separate routine. In this case, readtoken
11798 * doesn't need to have any internal procedures, but parseword does.
11799 * We could also make parseoperator in essence the main routine, and
11800 * have parseword (readtoken1?) handle both words and redirection.]
11802 #define NEW_xxreadtoken
11803 #ifdef NEW_xxreadtoken
11804 /* singles must be first! */
11805 static const char xxreadtoken_chars[7] ALIGN1 = {
11806 '\n', '(', ')', /* singles */
11807 '&', '|', ';', /* doubles */
11811 #define xxreadtoken_singles 3
11812 #define xxreadtoken_doubles 3
11814 static const char xxreadtoken_tokens[] ALIGN1 = {
11815 TNL, TLP, TRP, /* only single occurrence allowed */
11816 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11817 TEOF, /* corresponds to trailing nul */
11818 TAND, TOR, TENDCASE /* if double occurrence */
11830 setprompt_if(needprompt, 2);
11831 startlinno = g_parsefile->linno;
11832 for (;;) { /* until token or start of word found */
11834 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11838 while ((c = pgetc()) != '\n' && c != PEOF)
11841 } else if (c == '\\') {
11842 if (pgetc() != '\n') {
11844 break; /* return readtoken1(...) */
11846 startlinno = ++g_parsefile->linno;
11847 setprompt_if(doprompt, 2);
11851 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11854 g_parsefile->linno++;
11855 needprompt = doprompt;
11858 p = strchr(xxreadtoken_chars, c);
11860 break; /* return readtoken1(...) */
11862 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11864 if (cc == c) { /* double occurrence? */
11865 p += xxreadtoken_doubles + 1;
11868 #if ENABLE_ASH_BASH_COMPAT
11869 if (c == '&' && cc == '>') /* &> */
11870 break; /* return readtoken1(...) */
11875 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11880 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11882 #else /* old xxreadtoken */
11883 #define RETURN(token) return lasttoken = token
11893 setprompt_if(needprompt, 2);
11894 startlinno = g_parsefile->linno;
11895 for (;;) { /* until token or start of word found */
11898 case ' ': case '\t':
11899 IF_ASH_ALIAS(case PEOA:)
11902 while ((c = pgetc()) != '\n' && c != PEOF)
11907 if (pgetc() == '\n') {
11908 startlinno = ++g_parsefile->linno;
11909 setprompt_if(doprompt, 2);
11915 g_parsefile->linno++;
11916 needprompt = doprompt;
11921 if (pgetc() == '&')
11926 if (pgetc() == '|')
11931 if (pgetc() == ';')
11944 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11947 #endif /* old xxreadtoken */
11954 smallint alreadyseen = tokpushback;
11957 #if ENABLE_ASH_ALIAS
11966 if (checkkwd & CHKNL) {
11973 if (t != TWORD || quoteflag) {
11978 * check for keywords
11980 if (checkkwd & CHKKWD) {
11981 const char *const *pp;
11983 pp = findkwd(wordtext);
11985 lasttoken = t = pp - tokname_array;
11986 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11991 if (checkkwd & CHKALIAS) {
11992 #if ENABLE_ASH_ALIAS
11994 ap = lookupalias(wordtext, 1);
11997 pushstring(ap->val, ap);
12007 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12009 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12021 return tokname_array[t][0];
12025 * Read and parse a command. Returns NODE_EOF on end of file.
12026 * (NULL is a valid parse tree indicating a blank line.)
12028 static union node *
12029 parsecmd(int interact)
12034 doprompt = interact;
12035 setprompt_if(doprompt, doprompt);
12047 * Input any here documents.
12052 struct heredoc *here;
12055 here = heredoclist;
12056 heredoclist = NULL;
12059 setprompt_if(needprompt, 2);
12060 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12061 here->eofmark, here->striptabs);
12062 n = stzalloc(sizeof(struct narg));
12063 n->narg.type = NARG;
12064 /*n->narg.next = NULL; - stzalloc did it */
12065 n->narg.text = wordtext;
12066 n->narg.backquote = backquotelist;
12067 here->here->nhere.doc = n;
12074 * called by editline -- any expansions to the prompt should be added here.
12076 #if ENABLE_ASH_EXPAND_PRMT
12077 static const char *
12078 expandstr(const char *ps)
12082 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12083 * and token processing _can_ alter it (delete NULs etc). */
12084 setinputstring((char *)ps);
12085 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12088 n.narg.type = NARG;
12089 n.narg.next = NULL;
12090 n.narg.text = wordtext;
12091 n.narg.backquote = backquotelist;
12093 expandarg(&n, NULL, 0);
12094 return stackblock();
12099 * Execute a command or commands contained in a string.
12102 evalstring(char *s, int mask)
12105 struct stackmark smark;
12109 setstackmark(&smark);
12112 while ((n = parsecmd(0)) != NODE_EOF) {
12114 popstackmark(&smark);
12127 * The eval command.
12129 static int FAST_FUNC
12130 evalcmd(int argc UNUSED_PARAM, char **argv)
12139 STARTSTACKSTR(concat);
12141 concat = stack_putstr(p, concat);
12145 STPUTC(' ', concat);
12147 STPUTC('\0', concat);
12148 p = grabstackstr(concat);
12150 evalstring(p, ~SKIPEVAL);
12156 * Read and execute commands.
12157 * "Top" is nonzero for the top level command loop;
12158 * it turns on prompting if the shell is interactive.
12164 struct stackmark smark;
12168 TRACE(("cmdloop(%d) called\n", top));
12172 setstackmark(&smark);
12175 showjobs(stderr, SHOW_CHANGED);
12178 if (iflag && top) {
12182 n = parsecmd(inter);
12184 if (DEBUG > 2 && debug && (n != NODE_EOF))
12187 if (n == NODE_EOF) {
12188 if (!top || numeof >= 50)
12190 if (!stoppedjobs()) {
12193 out2str("\nUse \"exit\" to leave shell.\n");
12196 } else if (nflag == 0) {
12197 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12202 popstackmark(&smark);
12207 return skip & SKIPEVAL;
12214 * Take commands from a file. To be compatible we should do a path
12215 * search for the file, which is necessary to find sub-commands.
12218 find_dot_file(char *name)
12221 const char *path = pathval();
12224 /* don't try this for absolute or relative paths */
12225 if (strchr(name, '/'))
12228 /* IIRC standards do not say whether . is to be searched.
12229 * And it is even smaller this way, making it unconditional for now:
12231 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12236 while ((fullname = path_advance(&path, name)) != NULL) {
12238 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12240 * Don't bother freeing here, since it will
12241 * be freed by the caller.
12245 if (fullname != name)
12246 stunalloc(fullname);
12249 /* not found in the PATH */
12250 ash_msg_and_raise_error("%s: not found", name);
12254 static int FAST_FUNC
12255 dotcmd(int argc, char **argv)
12258 struct strlist *sp;
12259 volatile struct shparam saveparam;
12261 for (sp = cmdenviron; sp; sp = sp->next)
12262 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12265 /* bash says: "bash: .: filename argument required" */
12266 return 2; /* bash compat */
12269 /* "false; . empty_file; echo $?" should print 0, not 1: */
12272 /* This aborts if file isn't found, which is POSIXly correct.
12273 * bash returns exitcode 1 instead.
12275 fullname = find_dot_file(argv[1]);
12278 if (argc) { /* argc > 0, argv[0] != NULL */
12279 saveparam = shellparam;
12280 shellparam.malloced = 0;
12281 shellparam.nparam = argc;
12282 shellparam.p = argv;
12285 /* This aborts if file can't be opened, which is POSIXly correct.
12286 * bash returns exitcode 1 instead.
12288 setinputfile(fullname, INPUT_PUSH_FILE);
12289 commandname = fullname;
12294 freeparam(&shellparam);
12295 shellparam = saveparam;
12301 static int FAST_FUNC
12302 exitcmd(int argc UNUSED_PARAM, char **argv)
12307 exitstatus = number(argv[1]);
12308 raise_exception(EXEXIT);
12313 * Read a file containing shell functions.
12316 readcmdfile(char *name)
12318 setinputfile(name, INPUT_PUSH_FILE);
12324 /* ============ find_command inplementation */
12327 * Resolve a command name. If you change this routine, you may have to
12328 * change the shellexec routine as well.
12331 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12333 struct tblentry *cmdp;
12340 struct builtincmd *bcmd;
12342 /* If name contains a slash, don't use PATH or hash table */
12343 if (strchr(name, '/') != NULL) {
12344 entry->u.index = -1;
12345 if (act & DO_ABS) {
12346 while (stat(name, &statb) < 0) {
12348 if (errno == EINTR)
12351 entry->cmdtype = CMDUNKNOWN;
12355 entry->cmdtype = CMDNORMAL;
12359 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12361 updatetbl = (path == pathval());
12364 if (strstr(path, "%builtin") != NULL)
12365 act |= DO_ALTBLTIN;
12368 /* If name is in the table, check answer will be ok */
12369 cmdp = cmdlookup(name, 0);
12370 if (cmdp != NULL) {
12373 switch (cmdp->cmdtype) {
12391 } else if (cmdp->rehash == 0)
12392 /* if not invalidated by cd, we're done */
12396 /* If %builtin not in path, check for builtin next */
12397 bcmd = find_builtin(name);
12399 if (IS_BUILTIN_REGULAR(bcmd))
12400 goto builtin_success;
12401 if (act & DO_ALTPATH) {
12402 if (!(act & DO_ALTBLTIN))
12403 goto builtin_success;
12404 } else if (builtinloc <= 0) {
12405 goto builtin_success;
12409 #if ENABLE_FEATURE_SH_STANDALONE
12411 int applet_no = find_applet_by_name(name);
12412 if (applet_no >= 0) {
12413 entry->cmdtype = CMDNORMAL;
12414 entry->u.index = -2 - applet_no;
12420 /* We have to search path. */
12421 prev = -1; /* where to start */
12422 if (cmdp && cmdp->rehash) { /* doing a rehash */
12423 if (cmdp->cmdtype == CMDBUILTIN)
12426 prev = cmdp->param.index;
12432 while ((fullname = path_advance(&path, name)) != NULL) {
12433 stunalloc(fullname);
12434 /* NB: code below will still use fullname
12435 * despite it being "unallocated" */
12438 if (prefix(pathopt, "builtin")) {
12440 goto builtin_success;
12443 if ((act & DO_NOFUNC)
12444 || !prefix(pathopt, "func")
12445 ) { /* ignore unimplemented options */
12449 /* if rehash, don't redo absolute path names */
12450 if (fullname[0] == '/' && idx <= prev) {
12453 TRACE(("searchexec \"%s\": no change\n", name));
12456 while (stat(fullname, &statb) < 0) {
12458 if (errno == EINTR)
12461 if (errno != ENOENT && errno != ENOTDIR)
12465 e = EACCES; /* if we fail, this will be the error */
12466 if (!S_ISREG(statb.st_mode))
12468 if (pathopt) { /* this is a %func directory */
12469 stalloc(strlen(fullname) + 1);
12470 /* NB: stalloc will return space pointed by fullname
12471 * (because we don't have any intervening allocations
12472 * between stunalloc above and this stalloc) */
12473 readcmdfile(fullname);
12474 cmdp = cmdlookup(name, 0);
12475 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12476 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12477 stunalloc(fullname);
12480 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12482 entry->cmdtype = CMDNORMAL;
12483 entry->u.index = idx;
12487 cmdp = cmdlookup(name, 1);
12488 cmdp->cmdtype = CMDNORMAL;
12489 cmdp->param.index = idx;
12494 /* We failed. If there was an entry for this command, delete it */
12495 if (cmdp && updatetbl)
12496 delete_cmd_entry();
12498 ash_msg("%s: %s", name, errmsg(e, "not found"));
12499 entry->cmdtype = CMDUNKNOWN;
12504 entry->cmdtype = CMDBUILTIN;
12505 entry->u.cmd = bcmd;
12509 cmdp = cmdlookup(name, 1);
12510 cmdp->cmdtype = CMDBUILTIN;
12511 cmdp->param.cmd = bcmd;
12515 entry->cmdtype = cmdp->cmdtype;
12516 entry->u = cmdp->param;
12520 /* ============ trap.c */
12523 * The trap builtin.
12525 static int FAST_FUNC
12526 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12530 int signo, exitcode;
12535 for (signo = 0; signo < NSIG; signo++) {
12536 char *tr = trap_ptr[signo];
12538 /* note: bash adds "SIG", but only if invoked
12539 * as "bash". If called as "sh", or if set -o posix,
12540 * then it prints short signal names.
12541 * We are printing short names: */
12542 out1fmt("trap -- %s %s\n",
12544 get_signame(signo));
12545 /* trap_ptr != trap only if we are in special-cased `trap` code.
12546 * In this case, we will exit very soon, no need to free(). */
12547 /* if (trap_ptr != trap && tp[0]) */
12552 if (trap_ptr != trap) {
12565 signo = get_signum(*ap);
12567 /* Mimic bash message exactly */
12568 ash_msg("%s: invalid signal specification", *ap);
12574 if (LONE_DASH(action))
12577 action = ckstrdup(action);
12581 may_have_traps = 1;
12582 trap[signo] = action;
12593 /* ============ Builtins */
12595 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12597 * Lists available builtins
12599 static int FAST_FUNC
12600 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12606 "Built-in commands:\n"
12607 "------------------\n");
12608 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12609 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12610 builtintab[i].name + 1);
12616 #if ENABLE_FEATURE_SH_STANDALONE
12618 const char *a = applet_names;
12620 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12625 a += strlen(a) + 1;
12630 return EXIT_SUCCESS;
12632 #endif /* FEATURE_SH_EXTRA_QUIET */
12635 static int FAST_FUNC
12636 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12638 show_history(line_input_state);
12639 return EXIT_SUCCESS;
12644 * The export and readonly commands.
12646 static int FAST_FUNC
12647 exportcmd(int argc UNUSED_PARAM, char **argv)
12657 /* "readonly" in bash accepts, but ignores -n.
12658 * We do the same: it saves a conditional in nextopt's param.
12661 while ((opt = nextopt("np")) != '\0') {
12663 flag_off = VEXPORT;
12666 if (argv[0][0] == 'r') {
12668 flag_off = 0; /* readonly ignores -n */
12670 flag_off = ~flag_off;
12672 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12678 p = strchr(name, '=');
12682 vp = *findvar(hashvar(name), name);
12684 vp->flags = ((vp->flags | flag) & flag_off);
12688 setvar(name, p, (flag & flag_off));
12689 } while ((name = *++aptr) != NULL);
12694 /* No arguments. Show the list of exported or readonly vars.
12697 showvars(argv[0], flag, 0);
12702 * Delete a function if it exists.
12705 unsetfunc(const char *name)
12707 struct tblentry *cmdp;
12709 cmdp = cmdlookup(name, 0);
12710 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12711 delete_cmd_entry();
12715 * The unset builtin command. We unset the function before we unset the
12716 * variable to allow a function to be unset when there is a readonly variable
12717 * with the same name.
12719 static int FAST_FUNC
12720 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12727 while ((i = nextopt("vf")) != 0) {
12731 for (ap = argptr; *ap; ap++) {
12744 static const unsigned char timescmd_str[] ALIGN1 = {
12745 ' ', offsetof(struct tms, tms_utime),
12746 '\n', offsetof(struct tms, tms_stime),
12747 ' ', offsetof(struct tms, tms_cutime),
12748 '\n', offsetof(struct tms, tms_cstime),
12751 static int FAST_FUNC
12752 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12754 unsigned long clk_tck, s, t;
12755 const unsigned char *p;
12758 clk_tck = sysconf(_SC_CLK_TCK);
12763 t = *(clock_t *)(((char *) &buf) + p[1]);
12766 out1fmt("%lum%lu.%03lus%c",
12768 (t * 1000) / clk_tck,
12776 #if ENABLE_SH_MATH_SUPPORT
12778 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12779 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12781 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12783 static int FAST_FUNC
12784 letcmd(int argc UNUSED_PARAM, char **argv)
12790 ash_msg_and_raise_error("expression expected");
12792 i = ash_arith(*argv);
12800 * The read builtin. Options:
12801 * -r Do not interpret '\' specially
12802 * -s Turn off echo (tty only)
12803 * -n NCHARS Read NCHARS max
12804 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12805 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12806 * -u FD Read from given FD instead of fd 0
12807 * This uses unbuffered input, which may be avoidable in some cases.
12808 * TODO: bash also has:
12809 * -a ARRAY Read into array[0],[1],etc
12810 * -d DELIM End on DELIM char, not newline
12811 * -e Use line editing (tty only)
12813 static int FAST_FUNC
12814 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12816 char *opt_n = NULL;
12817 char *opt_p = NULL;
12818 char *opt_t = NULL;
12819 char *opt_u = NULL;
12820 int read_flags = 0;
12824 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12833 read_flags |= BUILTIN_READ_SILENT;
12839 read_flags |= BUILTIN_READ_RAW;
12849 /* "read -s" needs to save/restore termios, can't allow ^C
12850 * to jump out of it.
12853 r = shell_builtin_read(setvar2,
12855 bltinlookup("IFS"), /* can be NULL */
12864 if ((uintptr_t)r > 1)
12865 ash_msg_and_raise_error(r);
12867 return (uintptr_t)r;
12870 static int FAST_FUNC
12871 umaskcmd(int argc UNUSED_PARAM, char **argv)
12873 static const char permuser[3] ALIGN1 = "ugo";
12874 static const char permmode[3] ALIGN1 = "rwx";
12875 static const short permmask[] ALIGN2 = {
12876 S_IRUSR, S_IWUSR, S_IXUSR,
12877 S_IRGRP, S_IWGRP, S_IXGRP,
12878 S_IROTH, S_IWOTH, S_IXOTH
12881 /* TODO: use bb_parse_mode() instead */
12886 int symbolic_mode = 0;
12888 while (nextopt("S") != '\0') {
12899 if (symbolic_mode) {
12903 for (i = 0; i < 3; i++) {
12906 *p++ = permuser[i];
12908 for (j = 0; j < 3; j++) {
12909 if ((mask & permmask[3 * i + j]) == 0) {
12910 *p++ = permmode[j];
12918 out1fmt("%.4o\n", mask);
12921 if (isdigit((unsigned char) *ap)) {
12924 if (*ap >= '8' || *ap < '0')
12925 ash_msg_and_raise_error(msg_illnum, argv[1]);
12926 mask = (mask << 3) + (*ap - '0');
12927 } while (*++ap != '\0');
12930 mask = ~mask & 0777;
12931 if (!bb_parse_mode(ap, &mask)) {
12932 ash_msg_and_raise_error("illegal mode: %s", ap);
12934 umask(~mask & 0777);
12940 static int FAST_FUNC
12941 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12943 return shell_builtin_ulimit(argv);
12946 /* ============ main() and helpers */
12949 * Called to exit the shell.
12958 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
12959 save_history(line_input_state);
12962 status = exitstatus;
12963 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12964 if (setjmp(loc.loc)) {
12965 if (exception_type == EXEXIT)
12966 /* dash bug: it just does _exit(exitstatus) here
12967 * but we have to do setjobctl(0) first!
12968 * (bug is still not fixed in dash-0.5.3 - if you run dash
12969 * under Midnight Commander, on exit from dash MC is backgrounded) */
12970 status = exitstatus;
12973 exception_handler = &loc;
12980 flush_stdout_stderr();
12990 /* from input.c: */
12991 /* we will never free this */
12992 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12995 signal(SIGCHLD, SIG_DFL);
12996 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12997 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12999 signal(SIGHUP, SIG_DFL);
13005 struct stat st1, st2;
13008 for (envp = environ; envp && *envp; envp++) {
13009 if (strchr(*envp, '=')) {
13010 setvareq(*envp, VEXPORT|VTEXTFIXED);
13014 setvar2("PPID", utoa(getppid()));
13015 #if ENABLE_ASH_BASH_COMPAT
13016 p = lookupvar("SHLVL");
13017 setvar2("SHLVL", utoa(p ? atoi(p) + 1 : 1));
13019 p = lookupvar("PWD");
13021 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13022 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13032 //usage:#define ash_trivial_usage
13033 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13034 //usage:#define ash_full_usage "\n\n"
13035 //usage: "Unix shell interpreter"
13037 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13038 //usage:# define sh_trivial_usage ash_trivial_usage
13039 //usage:# define sh_full_usage ash_full_usage
13041 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13042 //usage:# define bash_trivial_usage ash_trivial_usage
13043 //usage:# define bash_full_usage ash_full_usage
13047 * Process the shell command line arguments.
13050 procargs(char **argv)
13053 const char *xminusc;
13058 /* if (xargv[0]) - mmm, this is always true! */
13060 for (i = 0; i < NOPTS; i++)
13063 if (options(/*cmdline:*/ 1)) {
13064 /* it already printed err message */
13065 raise_exception(EXERROR);
13069 if (*xargv == NULL) {
13071 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13074 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13078 for (i = 0; i < NOPTS; i++)
13079 if (optlist[i] == 2)
13084 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13089 } else if (!sflag) {
13090 setinputfile(*xargv, 0);
13093 commandname = arg0;
13096 shellparam.p = xargv;
13097 #if ENABLE_ASH_GETOPTS
13098 shellparam.optind = 1;
13099 shellparam.optoff = -1;
13101 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13103 shellparam.nparam++;
13110 * Read /etc/profile or .profile.
13113 read_profile(const char *name)
13117 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13126 * This routine is called when an error or an interrupt occurs in an
13127 * interactive shell and control is returned to the main command loop.
13135 /* from input.c: */
13136 g_parsefile->left_in_buffer = 0;
13137 g_parsefile->left_in_line = 0; /* clear input buffer */
13139 /* from parser.c: */
13142 /* from redir.c: */
13143 clearredir(/*drop:*/ 0);
13147 static short profile_buf[16384];
13148 extern int etext();
13152 * Main routine. We initialize things, parse the arguments, execute
13153 * profiles if we're a login shell, and then call cmdloop to execute
13154 * commands. The setjmp call sets up the location to jump to when an
13155 * exception occurs. When an exception occurs the variable "state"
13156 * is used to figure out how far we had gotten.
13158 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13159 int ash_main(int argc UNUSED_PARAM, char **argv)
13161 const char *shinit;
13162 volatile smallint state;
13163 struct jmploc jmploc;
13164 struct stackmark smark;
13166 /* Initialize global data */
13170 #if ENABLE_ASH_ALIAS
13176 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13179 #if ENABLE_FEATURE_EDITING
13180 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13183 if (setjmp(jmploc.loc)) {
13189 e = exception_type;
13193 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13197 outcslow('\n', stderr);
13200 popstackmark(&smark);
13201 FORCE_INT_ON; /* enable interrupts */
13210 exception_handler = &jmploc;
13213 TRACE(("Shell args: "));
13214 trace_puts_args(argv);
13216 rootpid = getpid();
13219 setstackmark(&smark);
13222 if (argv[0] && argv[0][0] == '-')
13228 read_profile("/etc/profile");
13231 hp = lookupvar("HOME");
13233 hp = concat_path_file(hp, ".profile");
13242 getuid() == geteuid() && getgid() == getegid() &&
13246 shinit = lookupvar("ENV");
13247 if (shinit != NULL && *shinit != '\0') {
13248 read_profile(shinit);
13254 /* evalstring pushes parsefile stack.
13255 * Ensure we don't falsely claim that 0 (stdin)
13256 * is one of stacked source fds.
13257 * Testcase: ash -c 'exec 1>&0' must not complain. */
13258 // if (!sflag) g_parsefile->pf_fd = -1;
13259 // ^^ not necessary since now we special-case fd 0
13260 // in is_hidden_fd() to not be considered "hidden fd"
13261 evalstring(minusc, 0);
13264 if (sflag || minusc == NULL) {
13265 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13267 const char *hp = lookupvar("HISTFILE");
13269 hp = lookupvar("HOME");
13271 hp = concat_path_file(hp, ".ash_history");
13272 setvar2("HISTFILE", hp);
13274 hp = lookupvar("HISTFILE");
13278 line_input_state->hist_file = hp;
13279 # if ENABLE_FEATURE_SH_HISTFILESIZE
13280 hp = lookupvar("HISTFILESIZE");
13281 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13285 state4: /* XXX ??? - why isn't this before the "if" statement */
13293 extern void _mcleanup(void);
13297 TRACE(("End of main reached\n"));
13304 * Copyright (c) 1989, 1991, 1993, 1994
13305 * The Regents of the University of California. All rights reserved.
13307 * This code is derived from software contributed to Berkeley by
13308 * Kenneth Almquist.
13310 * Redistribution and use in source and binary forms, with or without
13311 * modification, are permitted provided that the following conditions
13313 * 1. Redistributions of source code must retain the above copyright
13314 * notice, this list of conditions and the following disclaimer.
13315 * 2. Redistributions in binary form must reproduce the above copyright
13316 * notice, this list of conditions and the following disclaimer in the
13317 * documentation and/or other materials provided with the distribution.
13318 * 3. Neither the name of the University nor the names of its contributors
13319 * may be used to endorse or promote products derived from this software
13320 * without specific prior written permission.
13322 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13323 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13324 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13325 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13326 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13327 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13328 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13329 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13330 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13331 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF