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 the GPL v2 or later, see the file LICENSE in this tarball.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
30 /* Tweak debug output verbosity here */
37 #define JOBS ENABLE_ASH_JOB_CONTROL
39 #include "busybox.h" /* for applet_names */
43 #include <sys/times.h>
45 #include "shell_common.h"
47 #if ENABLE_ASH_RANDOM_SUPPORT
50 # define CLEAR_RANDOM_T(rnd) ((void)0)
53 #include "NUM_APPLETS.h"
55 /* STANDALONE does not make sense, and won't compile */
56 # undef CONFIG_FEATURE_SH_STANDALONE
57 # undef ENABLE_FEATURE_SH_STANDALONE
58 # undef IF_FEATURE_SH_STANDALONE
59 # undef IF_NOT_FEATURE_SH_STANDALONE
60 # define ENABLE_FEATURE_SH_STANDALONE 0
61 # define IF_FEATURE_SH_STANDALONE(...)
62 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
66 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
70 # error "Do not even bother, ash will not run on NOMMU machine"
73 //applet:IF_ASH(APPLET(ash, _BB_DIR_BIN, _BB_SUID_DROP))
74 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, _BB_DIR_BIN, _BB_SUID_DROP, sh))
75 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, _BB_DIR_BIN, _BB_SUID_DROP, bash))
77 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
78 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
83 //config: depends on !NOMMU
85 //config: Tha 'ash' shell adds about 60k in the default configuration and is
86 //config: the most complete and most pedantically correct shell included with
87 //config: busybox. This shell is actually a derivative of the Debian 'dash'
88 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
89 //config: (written by Kenneth Almquist) from NetBSD.
91 //config:config ASH_BASH_COMPAT
92 //config: bool "bash-compatible extensions"
94 //config: depends on ASH
96 //config: Enable bash-compatible extensions.
98 //config:config ASH_JOB_CONTROL
99 //config: bool "Job control"
101 //config: depends on ASH
103 //config: Enable job control in the ash shell.
105 //config:config ASH_ALIAS
106 //config: bool "alias support"
108 //config: depends on ASH
110 //config: Enable alias support in the ash shell.
112 //config:config ASH_GETOPTS
113 //config: bool "Builtin getopt to parse positional parameters"
115 //config: depends on ASH
117 //config: Enable getopts builtin in the ash shell.
119 //config:config ASH_BUILTIN_ECHO
120 //config: bool "Builtin version of 'echo'"
122 //config: depends on ASH
124 //config: Enable support for echo, builtin to ash.
126 //config:config ASH_BUILTIN_PRINTF
127 //config: bool "Builtin version of 'printf'"
129 //config: depends on ASH
131 //config: Enable support for printf, builtin to ash.
133 //config:config ASH_BUILTIN_TEST
134 //config: bool "Builtin version of 'test'"
136 //config: depends on ASH
138 //config: Enable support for test, builtin to ash.
140 //config:config ASH_CMDCMD
141 //config: bool "'command' command to override shell builtins"
143 //config: depends on ASH
145 //config: Enable support for the ash 'command' builtin, which allows
146 //config: you to run the specified command with the specified arguments,
147 //config: even when there is an ash builtin command with the same name.
149 //config:config ASH_MAIL
150 //config: bool "Check for new mail on interactive shells"
152 //config: depends on ASH
154 //config: Enable "check for new mail" in the ash shell.
156 //config:config ASH_OPTIMIZE_FOR_SIZE
157 //config: bool "Optimize for size instead of speed"
159 //config: depends on ASH
161 //config: Compile ash for reduced size at the price of speed.
163 //config:config ASH_RANDOM_SUPPORT
164 //config: bool "Pseudorandom generator and $RANDOM variable"
166 //config: depends on ASH
168 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
169 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
170 //config: You can reset the generator by using a specified start value.
171 //config: After "unset RANDOM" the generator will switch off and this
172 //config: variable will no longer have special treatment.
174 //config:config ASH_EXPAND_PRMT
175 //config: bool "Expand prompt string"
177 //config: depends on ASH
179 //config: "PS#" may contain volatile content, such as backquote commands.
180 //config: This option recreates the prompt string from the environment
181 //config: variable each time it is displayed.
183 //usage:#define ash_trivial_usage NOUSAGE_STR
184 //usage:#define ash_full_usage ""
185 //usage:#define sh_trivial_usage NOUSAGE_STR
186 //usage:#define sh_full_usage ""
187 //usage:#define bash_trivial_usage NOUSAGE_STR
188 //usage:#define bash_full_usage ""
191 /* ============ Hash table sizes. Configurable. */
195 #define CMDTABLESIZE 31 /* should be prime */
198 /* ============ Shell options */
200 static const char *const optletters_optnames[] = {
215 #if ENABLE_ASH_BASH_COMPAT
224 #define optletters(n) optletters_optnames[n][0]
225 #define optnames(n) (optletters_optnames[n] + 1)
227 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
230 /* ============ Misc data */
232 #define msg_illnum "Illegal number: %s"
235 * We enclose jmp_buf in a structure so that we can declare pointers to
236 * jump locations. The global variable handler contains the location to
237 * jump to when an exception occurs, and the global variable exception_type
238 * contains a code identifying the exception. To implement nested
239 * exception handlers, the user should save the value of handler on entry
240 * to an inner scope, set handler to point to a jmploc structure for the
241 * inner scope, and restore handler on exit from the scope.
247 struct globals_misc {
248 /* pid of main shell */
250 /* shell level: 0 for the main shell, 1 for its children, and so on */
252 #define rootshell (!shlvl)
253 char *minusc; /* argument to -c option */
255 char *curdir; // = nullstr; /* current working directory */
256 char *physdir; // = nullstr; /* physical working directory */
258 char *arg0; /* value of $0 */
260 struct jmploc *exception_handler;
262 volatile int suppress_int; /* counter */
263 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
264 /* last pending signal */
265 volatile /*sig_atomic_t*/ smallint pending_sig;
266 smallint exception_type; /* kind of exception (0..5) */
268 #define EXINT 0 /* SIGINT received */
269 #define EXERROR 1 /* a generic error */
270 #define EXSHELLPROC 2 /* execute a shell procedure */
271 #define EXEXEC 3 /* command execution failed */
272 #define EXEXIT 4 /* exit the shell */
273 #define EXSIG 5 /* trapped signal in wait(1) */
276 char nullstr[1]; /* zero length string */
279 #define eflag optlist[0]
280 #define fflag optlist[1]
281 #define Iflag optlist[2]
282 #define iflag optlist[3]
283 #define mflag optlist[4]
284 #define nflag optlist[5]
285 #define sflag optlist[6]
286 #define xflag optlist[7]
287 #define vflag optlist[8]
288 #define Cflag optlist[9]
289 #define aflag optlist[10]
290 #define bflag optlist[11]
291 #define uflag optlist[12]
292 #define viflag optlist[13]
293 #if ENABLE_ASH_BASH_COMPAT
294 # define pipefail optlist[14]
299 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
300 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
303 /* trap handler commands */
305 * Sigmode records the current value of the signal handlers for the various
306 * modes. A value of zero means that the current handler is not known.
307 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
309 char sigmode[NSIG - 1];
310 #define S_DFL 1 /* default signal handling (SIG_DFL) */
311 #define S_CATCH 2 /* signal is caught */
312 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
313 #define S_HARD_IGN 4 /* signal is ignored permenantly */
315 /* indicates specified signal received */
316 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
317 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
319 char **trap_ptr; /* used only by "trap hack" */
321 /* Rarely referenced stuff */
322 #if ENABLE_ASH_RANDOM_SUPPORT
325 pid_t backgndpid; /* pid of last background process */
326 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
328 extern struct globals_misc *const ash_ptr_to_globals_misc;
329 #define G_misc (*ash_ptr_to_globals_misc)
330 #define rootpid (G_misc.rootpid )
331 #define shlvl (G_misc.shlvl )
332 #define minusc (G_misc.minusc )
333 #define curdir (G_misc.curdir )
334 #define physdir (G_misc.physdir )
335 #define arg0 (G_misc.arg0 )
336 #define exception_handler (G_misc.exception_handler)
337 #define exception_type (G_misc.exception_type )
338 #define suppress_int (G_misc.suppress_int )
339 #define pending_int (G_misc.pending_int )
340 #define pending_sig (G_misc.pending_sig )
341 #define isloginsh (G_misc.isloginsh )
342 #define nullstr (G_misc.nullstr )
343 #define optlist (G_misc.optlist )
344 #define sigmode (G_misc.sigmode )
345 #define gotsig (G_misc.gotsig )
346 #define may_have_traps (G_misc.may_have_traps )
347 #define trap (G_misc.trap )
348 #define trap_ptr (G_misc.trap_ptr )
349 #define random_gen (G_misc.random_gen )
350 #define backgndpid (G_misc.backgndpid )
351 #define job_warning (G_misc.job_warning)
352 #define INIT_G_misc() do { \
353 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
361 /* ============ DEBUG */
363 static void trace_printf(const char *fmt, ...);
364 static void trace_vprintf(const char *fmt, va_list va);
365 # define TRACE(param) trace_printf param
366 # define TRACEV(param) trace_vprintf param
367 # define close(fd) do { \
369 if (close(dfd) < 0) \
370 bb_error_msg("bug on %d: closing %d(0x%x)", \
371 __LINE__, dfd, dfd); \
374 # define TRACE(param)
375 # define TRACEV(param)
379 /* ============ Utility functions */
380 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
382 static int isdigit_str9(const char *str)
384 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
385 while (--maxlen && isdigit(*str))
387 return (*str == '\0');
390 static const char *var_end(const char *var)
399 /* ============ Interrupts / exceptions */
401 * These macros allow the user to suspend the handling of interrupt signals
402 * over a period of time. This is similar to SIGHOLD or to sigblock, but
403 * much more efficient and portable. (But hacking the kernel is so much
404 * more fun than worrying about efficiency and portability. :-))
406 #define INT_OFF do { \
412 * Called to raise an exception. Since C doesn't include exceptions, we
413 * just do a longjmp to the exception handler. The type of exception is
414 * stored in the global variable "exception_type".
416 static void raise_exception(int) NORETURN;
418 raise_exception(int e)
421 if (exception_handler == NULL)
426 longjmp(exception_handler->loc, 1);
429 #define raise_exception(e) do { \
430 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
431 raise_exception(e); \
436 * Called from trap.c when a SIGINT is received. (If the user specifies
437 * that SIGINT is to be trapped or ignored using the trap builtin, then
438 * this routine is not called.) Suppressint is nonzero when interrupts
439 * are held using the INT_OFF macro. (The test for iflag is just
440 * defensive programming.)
442 static void raise_interrupt(void) NORETURN;
444 raise_interrupt(void)
449 /* Signal is not automatically unmasked after it is raised,
450 * do it ourself - unmask all signals */
451 sigprocmask_allsigs(SIG_UNBLOCK);
452 /* pending_sig = 0; - now done in signal_handler() */
455 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
456 if (!(rootshell && iflag)) {
457 /* Kill ourself with SIGINT */
458 signal(SIGINT, SIG_DFL);
463 raise_exception(ex_type);
467 #define raise_interrupt() do { \
468 TRACE(("raising interrupt on line %d\n", __LINE__)); \
473 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
477 if (--suppress_int == 0 && pending_int) {
481 #define INT_ON int_on()
482 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
490 #define FORCE_INT_ON force_int_on()
492 #define SAVE_INT(v) ((v) = suppress_int)
494 #define RESTORE_INT(v) do { \
496 suppress_int = (v); \
497 if (suppress_int == 0 && pending_int) \
502 /* ============ Stdout/stderr output */
505 outstr(const char *p, FILE *file)
513 flush_stdout_stderr(void)
521 outcslow(int c, FILE *dest)
529 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
531 out1fmt(const char *fmt, ...)
538 r = vprintf(fmt, ap);
544 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
546 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
553 ret = vsnprintf(outbuf, length, fmt, ap);
560 out1str(const char *p)
566 out2str(const char *p)
569 flush_stdout_stderr();
573 /* ============ Parser structures */
575 /* control characters in argument strings */
576 #define CTL_FIRST CTLESC
577 #define CTLESC ((unsigned char)'\201') /* escape next character */
578 #define CTLVAR ((unsigned char)'\202') /* variable defn */
579 #define CTLENDVAR ((unsigned char)'\203')
580 #define CTLBACKQ ((unsigned char)'\204')
581 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
582 /* CTLBACKQ | CTLQUOTE == '\205' */
583 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
584 #define CTLENDARI ((unsigned char)'\207')
585 #define CTLQUOTEMARK ((unsigned char)'\210')
586 #define CTL_LAST CTLQUOTEMARK
588 /* variable substitution byte (follows CTLVAR) */
589 #define VSTYPE 0x0f /* type of variable substitution */
590 #define VSNUL 0x10 /* colon--treat the empty string as unset */
591 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
593 /* values of VSTYPE field */
594 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
595 #define VSMINUS 0x2 /* ${var-text} */
596 #define VSPLUS 0x3 /* ${var+text} */
597 #define VSQUESTION 0x4 /* ${var?message} */
598 #define VSASSIGN 0x5 /* ${var=text} */
599 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
600 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
601 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
602 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
603 #define VSLENGTH 0xa /* ${#var} */
604 #if ENABLE_ASH_BASH_COMPAT
605 #define VSSUBSTR 0xc /* ${var:position:length} */
606 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
607 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
610 static const char dolatstr[] ALIGN1 = {
611 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
631 #if ENABLE_ASH_BASH_COMPAT
648 smallint type; /* Nxxxx */
651 union node *redirect;
656 smallint pipe_backgnd;
657 struct nodelist *cmdlist;
663 union node *redirect;
676 union node *elsepart;
703 struct nodelist *backquote;
706 /* nfile and ndup layout must match!
707 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
708 * that it is actually NTO2 (>&file), and change its type.
725 char *_unused_expfname;
744 struct nredir nredir;
745 struct nbinary nbinary;
749 struct nclist nclist;
758 * NODE_EOF is returned by parsecmd when it encounters an end of file.
759 * It must be distinct from NULL.
761 #define NODE_EOF ((union node *) -1L)
764 struct nodelist *next;
777 freefunc(struct funcnode *f)
779 if (f && --f->count < 0)
784 /* ============ Debugging output */
788 static FILE *tracefile;
791 trace_printf(const char *fmt, ...)
798 fprintf(tracefile, "%u ", (int) time(NULL));
800 fprintf(tracefile, "[%u] ", (int) getpid());
802 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
804 vfprintf(tracefile, fmt, va);
809 trace_vprintf(const char *fmt, va_list va)
814 fprintf(tracefile, "%u ", (int) time(NULL));
816 fprintf(tracefile, "[%u] ", (int) getpid());
818 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
819 vfprintf(tracefile, fmt, va);
823 trace_puts(const char *s)
831 trace_puts_quoted(char *s)
838 putc('"', tracefile);
839 for (p = s; *p; p++) {
840 switch ((unsigned char)*p) {
841 case '\n': c = 'n'; goto backslash;
842 case '\t': c = 't'; goto backslash;
843 case '\r': c = 'r'; goto backslash;
844 case '\"': c = '\"'; goto backslash;
845 case '\\': c = '\\'; goto backslash;
846 case CTLESC: c = 'e'; goto backslash;
847 case CTLVAR: c = 'v'; goto backslash;
848 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
849 case CTLBACKQ: c = 'q'; goto backslash;
850 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
852 putc('\\', tracefile);
856 if (*p >= ' ' && *p <= '~')
859 putc('\\', tracefile);
860 putc((*p >> 6) & 03, tracefile);
861 putc((*p >> 3) & 07, tracefile);
862 putc(*p & 07, tracefile);
867 putc('"', tracefile);
871 trace_puts_args(char **ap)
878 trace_puts_quoted(*ap);
880 putc('\n', tracefile);
883 putc(' ', tracefile);
898 /* leave open because libedit might be using it */
901 strcpy(s, "./trace");
903 if (!freopen(s, "a", tracefile)) {
904 fprintf(stderr, "Can't re-open %s\n", s);
909 tracefile = fopen(s, "a");
910 if (tracefile == NULL) {
911 fprintf(stderr, "Can't open %s\n", s);
917 flags = fcntl(fileno(tracefile), F_GETFL);
919 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
921 setlinebuf(tracefile);
922 fputs("\nTracing started.\n", tracefile);
926 indent(int amount, char *pfx, FILE *fp)
930 for (i = 0; i < amount; i++) {
931 if (pfx && i == amount - 1)
937 /* little circular references here... */
938 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
941 sharg(union node *arg, FILE *fp)
944 struct nodelist *bqlist;
945 unsigned char subtype;
947 if (arg->type != NARG) {
948 out1fmt("<node type %d>\n", arg->type);
951 bqlist = arg->narg.backquote;
952 for (p = arg->narg.text; *p; p++) {
953 switch ((unsigned char)*p) {
961 if (subtype == VSLENGTH)
970 switch (subtype & VSTYPE) {
1003 out1fmt("<subtype %d>", subtype);
1010 case CTLBACKQ|CTLQUOTE:
1013 shtree(bqlist->n, -1, NULL, fp);
1024 shcmd(union node *cmd, FILE *fp)
1032 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1038 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1042 switch (np->nfile.type) {
1043 case NTO: s = ">>"+1; dftfd = 1; break;
1044 case NCLOBBER: s = ">|"; dftfd = 1; break;
1045 case NAPPEND: s = ">>"; dftfd = 1; break;
1046 #if ENABLE_ASH_BASH_COMPAT
1049 case NTOFD: s = ">&"; dftfd = 1; break;
1050 case NFROM: s = "<"; break;
1051 case NFROMFD: s = "<&"; break;
1052 case NFROMTO: s = "<>"; break;
1053 default: s = "*error*"; break;
1055 if (np->nfile.fd != dftfd)
1056 fprintf(fp, "%d", np->nfile.fd);
1058 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1059 fprintf(fp, "%d", np->ndup.dupfd);
1061 sharg(np->nfile.fname, fp);
1068 shtree(union node *n, int ind, char *pfx, FILE *fp)
1070 struct nodelist *lp;
1076 indent(ind, pfx, fp);
1078 if (n == NODE_EOF) {
1093 shtree(n->nbinary.ch1, ind, NULL, fp);
1096 shtree(n->nbinary.ch2, ind, NULL, fp);
1104 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1105 shtree(lp->n, 0, NULL, fp);
1109 if (n->npipe.pipe_backgnd)
1115 fprintf(fp, "<node type %d>", n->type);
1123 showtree(union node *n)
1125 trace_puts("showtree called\n");
1126 shtree(n, 1, NULL, stderr);
1132 /* ============ Parser data */
1135 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1138 struct strlist *next;
1145 struct strpush *prev; /* preceding string on stack */
1147 int prev_left_in_line;
1148 #if ENABLE_ASH_ALIAS
1149 struct alias *ap; /* if push was associated with an alias */
1151 char *string; /* remember the string since it may change */
1155 struct parsefile *prev; /* preceding file on stack */
1156 int linno; /* current line */
1157 int pf_fd; /* file descriptor (or -1 if string) */
1158 int left_in_line; /* number of chars left in this line */
1159 int left_in_buffer; /* number of chars left in this buffer past the line */
1160 char *next_to_pgetc; /* next char in buffer */
1161 char *buf; /* input buffer */
1162 struct strpush *strpush; /* for pushing strings at this level */
1163 struct strpush basestrpush; /* so pushing one is fast */
1166 static struct parsefile basepf; /* top level input file */
1167 static struct parsefile *g_parsefile = &basepf; /* current input file */
1168 static int startlinno; /* line # where last token started */
1169 static char *commandname; /* currently executing command */
1170 static struct strlist *cmdenviron; /* environment for builtin command */
1171 static uint8_t exitstatus; /* exit status of last command */
1174 /* ============ Message printing */
1177 ash_vmsg(const char *msg, va_list ap)
1179 fprintf(stderr, "%s: ", arg0);
1181 if (strcmp(arg0, commandname))
1182 fprintf(stderr, "%s: ", commandname);
1183 if (!iflag || g_parsefile->pf_fd > 0)
1184 fprintf(stderr, "line %d: ", startlinno);
1186 vfprintf(stderr, msg, ap);
1187 outcslow('\n', stderr);
1191 * Exverror is called to raise the error exception. If the second argument
1192 * is not NULL then error prints an error message using printf style
1193 * formatting. It then raises the error exception.
1195 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1197 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1201 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1203 TRACE(("\") pid=%d\n", getpid()));
1205 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1210 flush_stdout_stderr();
1211 raise_exception(cond);
1215 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1217 ash_msg_and_raise_error(const char *msg, ...)
1222 ash_vmsg_and_raise(EXERROR, msg, ap);
1227 static void raise_error_syntax(const char *) NORETURN;
1229 raise_error_syntax(const char *msg)
1231 ash_msg_and_raise_error("syntax error: %s", msg);
1235 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1237 ash_msg_and_raise(int cond, const char *msg, ...)
1242 ash_vmsg_and_raise(cond, msg, ap);
1248 * error/warning routines for external builtins
1251 ash_msg(const char *fmt, ...)
1261 * Return a string describing an error. The returned string may be a
1262 * pointer to a static buffer that will be overwritten on the next call.
1263 * Action describes the operation that got the error.
1266 errmsg(int e, const char *em)
1268 if (e == ENOENT || e == ENOTDIR) {
1275 /* ============ Memory allocation */
1278 /* I consider these wrappers nearly useless:
1279 * ok, they return you to nearest exception handler, but
1280 * how much memory do you leak in the process, making
1281 * memory starvation worse?
1284 ckrealloc(void * p, size_t nbytes)
1286 p = realloc(p, nbytes);
1288 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1293 ckmalloc(size_t nbytes)
1295 return ckrealloc(NULL, nbytes);
1299 ckzalloc(size_t nbytes)
1301 return memset(ckmalloc(nbytes), 0, nbytes);
1305 ckstrdup(const char *s)
1307 char *p = strdup(s);
1309 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1313 /* Using bbox equivalents. They exit if out of memory */
1314 # define ckrealloc xrealloc
1315 # define ckmalloc xmalloc
1316 # define ckzalloc xzalloc
1317 # define ckstrdup xstrdup
1321 * It appears that grabstackstr() will barf with such alignments
1322 * because stalloc() will return a string allocated in a new stackblock.
1324 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1326 /* Most machines require the value returned from malloc to be aligned
1327 * in some way. The following macro will get this right
1328 * on many machines. */
1329 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1330 /* Minimum size of a block */
1331 MINSIZE = SHELL_ALIGN(504),
1334 struct stack_block {
1335 struct stack_block *prev;
1336 char space[MINSIZE];
1340 struct stack_block *stackp;
1343 struct stackmark *marknext;
1347 struct globals_memstack {
1348 struct stack_block *g_stackp; // = &stackbase;
1349 struct stackmark *markp;
1350 char *g_stacknxt; // = stackbase.space;
1351 char *sstrend; // = stackbase.space + MINSIZE;
1352 size_t g_stacknleft; // = MINSIZE;
1353 int herefd; // = -1;
1354 struct stack_block stackbase;
1356 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1357 #define G_memstack (*ash_ptr_to_globals_memstack)
1358 #define g_stackp (G_memstack.g_stackp )
1359 #define markp (G_memstack.markp )
1360 #define g_stacknxt (G_memstack.g_stacknxt )
1361 #define sstrend (G_memstack.sstrend )
1362 #define g_stacknleft (G_memstack.g_stacknleft)
1363 #define herefd (G_memstack.herefd )
1364 #define stackbase (G_memstack.stackbase )
1365 #define INIT_G_memstack() do { \
1366 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1368 g_stackp = &stackbase; \
1369 g_stacknxt = stackbase.space; \
1370 g_stacknleft = MINSIZE; \
1371 sstrend = stackbase.space + MINSIZE; \
1376 #define stackblock() ((void *)g_stacknxt)
1377 #define stackblocksize() g_stacknleft
1380 * Parse trees for commands are allocated in lifo order, so we use a stack
1381 * to make this more efficient, and also to avoid all sorts of exception
1382 * handling code to handle interrupts in the middle of a parse.
1384 * The size 504 was chosen because the Ultrix malloc handles that size
1388 stalloc(size_t nbytes)
1393 aligned = SHELL_ALIGN(nbytes);
1394 if (aligned > g_stacknleft) {
1397 struct stack_block *sp;
1399 blocksize = aligned;
1400 if (blocksize < MINSIZE)
1401 blocksize = MINSIZE;
1402 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1403 if (len < blocksize)
1404 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1407 sp->prev = g_stackp;
1408 g_stacknxt = sp->space;
1409 g_stacknleft = blocksize;
1410 sstrend = g_stacknxt + blocksize;
1415 g_stacknxt += aligned;
1416 g_stacknleft -= aligned;
1421 stzalloc(size_t nbytes)
1423 return memset(stalloc(nbytes), 0, nbytes);
1430 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1431 write(STDERR_FILENO, "stunalloc\n", 10);
1435 g_stacknleft += g_stacknxt - (char *)p;
1440 * Like strdup but works with the ash stack.
1443 ststrdup(const char *p)
1445 size_t len = strlen(p) + 1;
1446 return memcpy(stalloc(len), p, len);
1450 setstackmark(struct stackmark *mark)
1452 mark->stackp = g_stackp;
1453 mark->stacknxt = g_stacknxt;
1454 mark->stacknleft = g_stacknleft;
1455 mark->marknext = markp;
1460 popstackmark(struct stackmark *mark)
1462 struct stack_block *sp;
1468 markp = mark->marknext;
1469 while (g_stackp != mark->stackp) {
1471 g_stackp = sp->prev;
1474 g_stacknxt = mark->stacknxt;
1475 g_stacknleft = mark->stacknleft;
1476 sstrend = mark->stacknxt + mark->stacknleft;
1481 * When the parser reads in a string, it wants to stick the string on the
1482 * stack and only adjust the stack pointer when it knows how big the
1483 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1484 * of space on top of the stack and stackblocklen returns the length of
1485 * this block. Growstackblock will grow this space by at least one byte,
1486 * possibly moving it (like realloc). Grabstackblock actually allocates the
1487 * part of the block that has been used.
1490 growstackblock(void)
1494 newlen = g_stacknleft * 2;
1495 if (newlen < g_stacknleft)
1496 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1500 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1501 struct stack_block *oldstackp;
1502 struct stackmark *xmark;
1503 struct stack_block *sp;
1504 struct stack_block *prevstackp;
1508 oldstackp = g_stackp;
1510 prevstackp = sp->prev;
1511 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1512 sp = ckrealloc(sp, grosslen);
1513 sp->prev = prevstackp;
1515 g_stacknxt = sp->space;
1516 g_stacknleft = newlen;
1517 sstrend = sp->space + newlen;
1520 * Stack marks pointing to the start of the old block
1521 * must be relocated to point to the new block
1524 while (xmark != NULL && xmark->stackp == oldstackp) {
1525 xmark->stackp = g_stackp;
1526 xmark->stacknxt = g_stacknxt;
1527 xmark->stacknleft = g_stacknleft;
1528 xmark = xmark->marknext;
1532 char *oldspace = g_stacknxt;
1533 size_t oldlen = g_stacknleft;
1534 char *p = stalloc(newlen);
1536 /* free the space we just allocated */
1537 g_stacknxt = memcpy(p, oldspace, oldlen);
1538 g_stacknleft += newlen;
1543 grabstackblock(size_t len)
1545 len = SHELL_ALIGN(len);
1547 g_stacknleft -= len;
1551 * The following routines are somewhat easier to use than the above.
1552 * The user declares a variable of type STACKSTR, which may be declared
1553 * to be a register. The macro STARTSTACKSTR initializes things. Then
1554 * the user uses the macro STPUTC to add characters to the string. In
1555 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1556 * grown as necessary. When the user is done, she can just leave the
1557 * string there and refer to it using stackblock(). Or she can allocate
1558 * the space for it using grabstackstr(). If it is necessary to allow
1559 * someone else to use the stack temporarily and then continue to grow
1560 * the string, the user should use grabstack to allocate the space, and
1561 * then call ungrabstr(p) to return to the previous mode of operation.
1563 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1564 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1565 * is space for at least one character.
1570 size_t len = stackblocksize();
1571 if (herefd >= 0 && len >= 1024) {
1572 full_write(herefd, stackblock(), len);
1573 return stackblock();
1576 return (char *)stackblock() + len;
1580 * Called from CHECKSTRSPACE.
1583 makestrspace(size_t newlen, char *p)
1585 size_t len = p - g_stacknxt;
1586 size_t size = stackblocksize();
1591 size = stackblocksize();
1593 if (nleft >= newlen)
1597 return (char *)stackblock() + len;
1601 stack_nputstr(const char *s, size_t n, char *p)
1603 p = makestrspace(n, p);
1604 p = (char *)memcpy(p, s, n) + n;
1609 stack_putstr(const char *s, char *p)
1611 return stack_nputstr(s, strlen(s), p);
1615 _STPUTC(int c, char *p)
1623 #define STARTSTACKSTR(p) ((p) = stackblock())
1624 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1625 #define CHECKSTRSPACE(n, p) do { \
1628 size_t m = sstrend - q; \
1630 (p) = makestrspace(l, q); \
1632 #define USTPUTC(c, p) (*(p)++ = (c))
1633 #define STACKSTRNUL(p) do { \
1634 if ((p) == sstrend) \
1635 (p) = growstackstr(); \
1638 #define STUNPUTC(p) (--(p))
1639 #define STTOPC(p) ((p)[-1])
1640 #define STADJUST(amount, p) ((p) += (amount))
1642 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1643 #define ungrabstackstr(s, p) stunalloc(s)
1644 #define stackstrend() ((void *)sstrend)
1647 /* ============ String helpers */
1650 * prefix -- see if pfx is a prefix of string.
1653 prefix(const char *string, const char *pfx)
1656 if (*pfx++ != *string++)
1659 return (char *) string;
1663 * Check for a valid number. This should be elsewhere.
1666 is_number(const char *p)
1671 } while (*++p != '\0');
1676 * Convert a string of digits to an integer, printing an error message on
1680 number(const char *s)
1683 ash_msg_and_raise_error(msg_illnum, s);
1688 * Produce a possibly single quoted string suitable as input to the shell.
1689 * The return string is allocated on the stack.
1692 single_quote(const char *s)
1702 len = strchrnul(s, '\'') - s;
1704 q = p = makestrspace(len + 3, p);
1707 q = (char *)memcpy(q, s, len) + len;
1716 do len++; while (*++s == '\'');
1718 q = p = makestrspace(len + 3, p);
1721 q = (char *)memcpy(q, s - len, len) + len;
1729 return stackblock();
1733 /* ============ nextopt */
1735 static char **argptr; /* argument list for builtin commands */
1736 static char *optionarg; /* set by nextopt (like getopt) */
1737 static char *optptr; /* used by nextopt */
1740 * XXX - should get rid of. Have all builtins use getopt(3).
1741 * The library getopt must have the BSD extension static variable
1742 * "optreset", otherwise it can't be used within the shell safely.
1744 * Standard option processing (a la getopt) for builtin routines.
1745 * The only argument that is passed to nextopt is the option string;
1746 * the other arguments are unnecessary. It returns the character,
1747 * or '\0' on end of input.
1750 nextopt(const char *optstring)
1757 if (p == NULL || *p == '\0') {
1758 /* We ate entire "-param", take next one */
1764 if (*++p == '\0') /* just "-" ? */
1767 if (LONE_DASH(p)) /* "--" ? */
1769 /* p => next "-param" */
1771 /* p => some option char in the middle of a "-param" */
1773 for (q = optstring; *q != c;) {
1775 ash_msg_and_raise_error("illegal option -%c", c);
1783 ash_msg_and_raise_error("no arg for -%c option", c);
1793 /* ============ Shell variables */
1796 * The parsefile structure pointed to by the global variable parsefile
1797 * contains information about the current file being read.
1800 int nparam; /* # of positional parameters (without $0) */
1801 #if ENABLE_ASH_GETOPTS
1802 int optind; /* next parameter to be processed by getopts */
1803 int optoff; /* used by getopts */
1805 unsigned char malloced; /* if parameter list dynamically allocated */
1806 char **p; /* parameter list */
1810 * Free the list of positional parameters.
1813 freeparam(volatile struct shparam *param)
1815 if (param->malloced) {
1817 ap = ap1 = param->p;
1824 #if ENABLE_ASH_GETOPTS
1825 static void FAST_FUNC getoptsreset(const char *value);
1829 struct var *next; /* next entry in hash list */
1830 int flags; /* flags are defined above */
1831 const char *var_text; /* name=value */
1832 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1833 /* the variable gets set/unset */
1837 struct localvar *next; /* next local variable in list */
1838 struct var *vp; /* the variable that was made local */
1839 int flags; /* saved flags */
1840 const char *text; /* saved text */
1844 #define VEXPORT 0x01 /* variable is exported */
1845 #define VREADONLY 0x02 /* variable cannot be modified */
1846 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1847 #define VTEXTFIXED 0x08 /* text is statically allocated */
1848 #define VSTACK 0x10 /* text is allocated on the stack */
1849 #define VUNSET 0x20 /* the variable is not set */
1850 #define VNOFUNC 0x40 /* don't call the callback function */
1851 #define VNOSET 0x80 /* do not set variable - just readonly test */
1852 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1853 #if ENABLE_ASH_RANDOM_SUPPORT
1854 # define VDYNAMIC 0x200 /* dynamic variable */
1860 /* Need to be before varinit_data[] */
1861 #if ENABLE_LOCALE_SUPPORT
1862 static void FAST_FUNC
1863 change_lc_all(const char *value)
1865 if (value && *value != '\0')
1866 setlocale(LC_ALL, value);
1868 static void FAST_FUNC
1869 change_lc_ctype(const char *value)
1871 if (value && *value != '\0')
1872 setlocale(LC_CTYPE, value);
1876 static void chkmail(void);
1877 static void changemail(const char *) FAST_FUNC;
1879 static void changepath(const char *) FAST_FUNC;
1880 #if ENABLE_ASH_RANDOM_SUPPORT
1881 static void change_random(const char *) FAST_FUNC;
1884 static const struct {
1886 const char *var_text;
1887 void (*var_func)(const char *) FAST_FUNC;
1888 } varinit_data[] = {
1889 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1891 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1892 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1894 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1895 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1896 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1897 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1898 #if ENABLE_ASH_GETOPTS
1899 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1901 #if ENABLE_ASH_RANDOM_SUPPORT
1902 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1904 #if ENABLE_LOCALE_SUPPORT
1905 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1906 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1908 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1909 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1915 struct globals_var {
1916 struct shparam shellparam; /* $@ current positional parameters */
1917 struct redirtab *redirlist;
1919 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1920 struct var *vartab[VTABSIZE];
1921 struct var varinit[ARRAY_SIZE(varinit_data)];
1923 extern struct globals_var *const ash_ptr_to_globals_var;
1924 #define G_var (*ash_ptr_to_globals_var)
1925 #define shellparam (G_var.shellparam )
1926 //#define redirlist (G_var.redirlist )
1927 #define g_nullredirs (G_var.g_nullredirs )
1928 #define preverrout_fd (G_var.preverrout_fd)
1929 #define vartab (G_var.vartab )
1930 #define varinit (G_var.varinit )
1931 #define INIT_G_var() do { \
1933 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1935 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1936 varinit[i].flags = varinit_data[i].flags; \
1937 varinit[i].var_text = varinit_data[i].var_text; \
1938 varinit[i].var_func = varinit_data[i].var_func; \
1942 #define vifs varinit[0]
1944 # define vmail (&vifs)[1]
1945 # define vmpath (&vmail)[1]
1946 # define vpath (&vmpath)[1]
1948 # define vpath (&vifs)[1]
1950 #define vps1 (&vpath)[1]
1951 #define vps2 (&vps1)[1]
1952 #define vps4 (&vps2)[1]
1953 #if ENABLE_ASH_GETOPTS
1954 # define voptind (&vps4)[1]
1955 # if ENABLE_ASH_RANDOM_SUPPORT
1956 # define vrandom (&voptind)[1]
1959 # if ENABLE_ASH_RANDOM_SUPPORT
1960 # define vrandom (&vps4)[1]
1965 * The following macros access the values of the above variables.
1966 * They have to skip over the name. They return the null string
1967 * for unset variables.
1969 #define ifsval() (vifs.var_text + 4)
1970 #define ifsset() ((vifs.flags & VUNSET) == 0)
1972 # define mailval() (vmail.var_text + 5)
1973 # define mpathval() (vmpath.var_text + 9)
1974 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1976 #define pathval() (vpath.var_text + 5)
1977 #define ps1val() (vps1.var_text + 4)
1978 #define ps2val() (vps2.var_text + 4)
1979 #define ps4val() (vps4.var_text + 4)
1980 #if ENABLE_ASH_GETOPTS
1981 # define optindval() (voptind.var_text + 7)
1985 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1986 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1988 #if ENABLE_ASH_GETOPTS
1989 static void FAST_FUNC
1990 getoptsreset(const char *value)
1992 shellparam.optind = number(value);
1993 shellparam.optoff = -1;
1998 * Return of a legal variable name (a letter or underscore followed by zero or
1999 * more letters, underscores, and digits).
2001 static char* FAST_FUNC
2002 endofname(const char *name)
2010 if (!is_in_name(*p))
2017 * Compares two strings up to the first = or '\0'. The first
2018 * string must be terminated by '='; the second may be terminated by
2019 * either '=' or '\0'.
2022 varcmp(const char *p, const char *q)
2026 while ((c = *p) == (d = *q)) {
2041 * Find the appropriate entry in the hash table from the name.
2043 static struct var **
2044 hashvar(const char *p)
2048 hashval = ((unsigned char) *p) << 4;
2049 while (*p && *p != '=')
2050 hashval += (unsigned char) *p++;
2051 return &vartab[hashval % VTABSIZE];
2055 vpcmp(const void *a, const void *b)
2057 return varcmp(*(const char **)a, *(const char **)b);
2061 * This routine initializes the builtin variables.
2071 * PS1 depends on uid
2073 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2074 vps1.var_text = "PS1=\\w \\$ ";
2077 vps1.var_text = "PS1=# ";
2080 end = vp + ARRAY_SIZE(varinit);
2082 vpp = hashvar(vp->var_text);
2085 } while (++vp < end);
2088 static struct var **
2089 findvar(struct var **vpp, const char *name)
2091 for (; *vpp; vpp = &(*vpp)->next) {
2092 if (varcmp((*vpp)->var_text, name) == 0) {
2100 * Find the value of a variable. Returns NULL if not set.
2102 static const char* FAST_FUNC
2103 lookupvar(const char *name)
2107 v = *findvar(hashvar(name), name);
2109 #if ENABLE_ASH_RANDOM_SUPPORT
2111 * Dynamic variables are implemented roughly the same way they are
2112 * in bash. Namely, they're "special" so long as they aren't unset.
2113 * As soon as they're unset, they're no longer dynamic, and dynamic
2114 * lookup will no longer happen at that point. -- PFM.
2116 if (v->flags & VDYNAMIC)
2119 if (!(v->flags & VUNSET))
2120 return var_end(v->var_text);
2126 * Search the environment of a builtin command.
2129 bltinlookup(const char *name)
2133 for (sp = cmdenviron; sp; sp = sp->next) {
2134 if (varcmp(sp->text, name) == 0)
2135 return var_end(sp->text);
2137 return lookupvar(name);
2141 * Same as setvar except that the variable and value are passed in
2142 * the first argument as name=value. Since the first argument will
2143 * be actually stored in the table, it should not be a string that
2145 * Called with interrupts off.
2148 setvareq(char *s, int flags)
2150 struct var *vp, **vpp;
2153 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2154 vp = *findvar(vpp, s);
2156 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2159 if (flags & VNOSAVE)
2162 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2168 if (vp->var_func && !(flags & VNOFUNC))
2169 vp->var_func(var_end(s));
2171 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2172 free((char*)vp->var_text);
2174 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2176 /* variable s is not found */
2179 vp = ckzalloc(sizeof(*vp));
2181 /*vp->func = NULL; - ckzalloc did it */
2184 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2191 * Set the value of a variable. The flags argument is ored with the
2192 * flags of the variable. If val is NULL, the variable is unset.
2195 setvar(const char *name, const char *val, int flags)
2202 q = endofname(name);
2203 p = strchrnul(q, '=');
2205 if (!namelen || p != q)
2206 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2211 vallen = strlen(val);
2214 nameeq = ckmalloc(namelen + vallen + 2);
2215 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2218 p = (char *)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(int whichprompt)
2435 #if ENABLE_ASH_EXPAND_PRMT
2436 struct stackmark smark;
2441 switch (whichprompt) {
2451 #if ENABLE_ASH_EXPAND_PRMT
2452 setstackmark(&smark);
2453 stalloc(stackblocksize());
2455 putprompt(expandstr(prompt));
2456 #if ENABLE_ASH_EXPAND_PRMT
2457 popstackmark(&smark);
2462 /* ============ The cd and pwd commands */
2464 #define CD_PHYSICAL 1
2474 while ((i = nextopt("LP")) != '\0') {
2476 flags ^= CD_PHYSICAL;
2485 * Update curdir (the name of the current directory) in response to a
2489 updatepwd(const char *dir)
2496 cdcomppath = ststrdup(dir);
2499 if (curdir == nullstr)
2501 new = stack_putstr(curdir, new);
2503 new = makestrspace(strlen(dir) + 2, new);
2504 lim = (char *)stackblock() + 1;
2508 if (new > lim && *lim == '/')
2513 if (dir[1] == '/' && dir[2] != '/') {
2519 p = strtok(cdcomppath, "/");
2523 if (p[1] == '.' && p[2] == '\0') {
2535 new = stack_putstr(p, new);
2543 return stackblock();
2547 * Find out what the current directory is. If we already know the current
2548 * directory, this routine returns immediately.
2553 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2554 return dir ? dir : nullstr;
2558 setpwd(const char *val, int setold)
2562 oldcur = dir = curdir;
2565 setvar("OLDPWD", oldcur, VEXPORT);
2568 if (physdir != nullstr) {
2569 if (physdir != oldcur)
2573 if (oldcur == val || !val) {
2579 dir = ckstrdup(val);
2580 if (oldcur != dir && oldcur != nullstr) {
2585 setvar("PWD", dir, VEXPORT);
2588 static void hashcd(void);
2591 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2592 * know that the current directory has changed.
2595 docd(const char *dest, int flags)
2597 const char *dir = NULL;
2600 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2603 if (!(flags & CD_PHYSICAL)) {
2604 dir = updatepwd(dest);
2618 static int FAST_FUNC
2619 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2631 dest = bltinlookup("HOME");
2632 else if (LONE_DASH(dest)) {
2633 dest = bltinlookup("OLDPWD");
2655 path = bltinlookup("CDPATH");
2664 p = path_advance(&path, dest);
2665 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2669 if (!docd(p, flags))
2674 ash_msg_and_raise_error("can't cd to %s", dest);
2677 if (flags & CD_PRINT)
2678 out1fmt("%s\n", curdir);
2682 static int FAST_FUNC
2683 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2686 const char *dir = curdir;
2690 if (physdir == nullstr)
2694 out1fmt("%s\n", dir);
2699 /* ============ ... */
2702 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2704 /* Syntax classes */
2705 #define CWORD 0 /* character is nothing special */
2706 #define CNL 1 /* newline character */
2707 #define CBACK 2 /* a backslash character */
2708 #define CSQUOTE 3 /* single quote */
2709 #define CDQUOTE 4 /* double quote */
2710 #define CENDQUOTE 5 /* a terminating quote */
2711 #define CBQUOTE 6 /* backwards single quote */
2712 #define CVAR 7 /* a dollar sign */
2713 #define CENDVAR 8 /* a '}' character */
2714 #define CLP 9 /* a left paren in arithmetic */
2715 #define CRP 10 /* a right paren in arithmetic */
2716 #define CENDFILE 11 /* end of file */
2717 #define CCTL 12 /* like CWORD, except it must be escaped */
2718 #define CSPCL 13 /* these terminate a word */
2719 #define CIGN 14 /* character should be ignored */
2722 #if ENABLE_ASH_ALIAS
2726 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2728 #if ENABLE_SH_MATH_SUPPORT
2729 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2731 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2733 static const uint16_t S_I_T[] = {
2734 #if ENABLE_ASH_ALIAS
2735 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2737 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2738 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2739 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2740 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2741 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2742 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2743 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2744 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2745 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2746 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2747 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2748 #if !USE_SIT_FUNCTION
2749 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2750 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2751 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2755 /* Constants below must match table above */
2757 #if ENABLE_ASH_ALIAS
2758 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2760 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2761 CNL_CNL_CNL_CNL , /* 2 */
2762 CWORD_CCTL_CCTL_CWORD , /* 3 */
2763 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2764 CVAR_CVAR_CWORD_CVAR , /* 5 */
2765 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2766 CSPCL_CWORD_CWORD_CLP , /* 7 */
2767 CSPCL_CWORD_CWORD_CRP , /* 8 */
2768 CBACK_CBACK_CCTL_CBACK , /* 9 */
2769 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2770 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2771 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2772 CWORD_CWORD_CWORD_CWORD , /* 13 */
2773 CCTL_CCTL_CCTL_CCTL , /* 14 */
2776 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2777 * caller must ensure proper cast on it if c is *char_ptr!
2779 /* Values for syntax param */
2780 #define BASESYNTAX 0 /* not in quotes */
2781 #define DQSYNTAX 1 /* in double quotes */
2782 #define SQSYNTAX 2 /* in single quotes */
2783 #define ARISYNTAX 3 /* in arithmetic */
2784 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2786 #if USE_SIT_FUNCTION
2789 SIT(int c, int syntax)
2791 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2792 # if ENABLE_ASH_ALIAS
2793 static const uint8_t syntax_index_table[] ALIGN1 = {
2794 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2795 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2796 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2800 static const uint8_t syntax_index_table[] ALIGN1 = {
2801 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2802 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2803 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2812 # if ENABLE_ASH_ALIAS
2818 /* Cast is purely for paranoia here,
2819 * just in case someone passed signed char to us */
2820 if ((unsigned char)c >= CTL_FIRST
2821 && (unsigned char)c <= CTL_LAST
2825 s = strchrnul(spec_symbls, c);
2828 indx = syntax_index_table[s - spec_symbls];
2830 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2833 #else /* !USE_SIT_FUNCTION */
2835 static const uint8_t syntax_index_table[] = {
2836 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2837 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2847 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2848 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2870 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2871 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2872 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2873 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2874 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2875 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2876 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2877 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2878 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2879 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2880 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2881 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2882 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2883 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2884 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2885 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2886 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2887 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2888 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2889 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2890 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2891 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2896 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2897 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2898 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2899 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2900 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2901 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2904 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2905 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2929 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2930 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2931 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2934 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2962 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2963 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2964 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2965 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2967 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2968 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2969 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2970 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2971 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2972 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2973 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2974 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3093 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3094 # if ENABLE_ASH_ALIAS
3095 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3099 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3101 #endif /* !USE_SIT_FUNCTION */
3104 /* ============ Alias handling */
3106 #if ENABLE_ASH_ALIAS
3108 #define ALIASINUSE 1
3119 static struct alias **atab; // [ATABSIZE];
3120 #define INIT_G_alias() do { \
3121 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3125 static struct alias **
3126 __lookupalias(const char *name) {
3127 unsigned int hashval;
3134 ch = (unsigned char)*p;
3138 ch = (unsigned char)*++p;
3140 app = &atab[hashval % ATABSIZE];
3142 for (; *app; app = &(*app)->next) {
3143 if (strcmp(name, (*app)->name) == 0) {
3151 static struct alias *
3152 lookupalias(const char *name, int check)
3154 struct alias *ap = *__lookupalias(name);
3156 if (check && ap && (ap->flag & ALIASINUSE))
3161 static struct alias *
3162 freealias(struct alias *ap)
3166 if (ap->flag & ALIASINUSE) {
3167 ap->flag |= ALIASDEAD;
3179 setalias(const char *name, const char *val)
3181 struct alias *ap, **app;
3183 app = __lookupalias(name);
3187 if (!(ap->flag & ALIASINUSE)) {
3190 ap->val = ckstrdup(val);
3191 ap->flag &= ~ALIASDEAD;
3194 ap = ckzalloc(sizeof(struct alias));
3195 ap->name = ckstrdup(name);
3196 ap->val = ckstrdup(val);
3197 /*ap->flag = 0; - ckzalloc did it */
3198 /*ap->next = NULL;*/
3205 unalias(const char *name)
3209 app = __lookupalias(name);
3213 *app = freealias(*app);
3224 struct alias *ap, **app;
3228 for (i = 0; i < ATABSIZE; i++) {
3230 for (ap = *app; ap; ap = *app) {
3231 *app = freealias(*app);
3241 printalias(const struct alias *ap)
3243 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3247 * TODO - sort output
3249 static int FAST_FUNC
3250 aliascmd(int argc UNUSED_PARAM, char **argv)
3259 for (i = 0; i < ATABSIZE; i++) {
3260 for (ap = atab[i]; ap; ap = ap->next) {
3266 while ((n = *++argv) != NULL) {
3267 v = strchr(n+1, '=');
3268 if (v == NULL) { /* n+1: funny ksh stuff */
3269 ap = *__lookupalias(n);
3271 fprintf(stderr, "%s: %s not found\n", "alias", n);
3284 static int FAST_FUNC
3285 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3289 while ((i = nextopt("a")) != '\0') {
3295 for (i = 0; *argptr; argptr++) {
3296 if (unalias(*argptr)) {
3297 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3305 #endif /* ASH_ALIAS */
3308 /* ============ jobs.c */
3310 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3313 #define FORK_NOJOB 2
3315 /* mode flags for showjob(s) */
3316 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3317 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3318 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3321 * A job structure contains information about a job. A job is either a
3322 * single process or a set of processes contained in a pipeline. In the
3323 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3327 pid_t ps_pid; /* process id */
3328 int ps_status; /* last process status from wait() */
3329 char *ps_cmd; /* text of command being run */
3333 struct procstat ps0; /* status of process */
3334 struct procstat *ps; /* status or processes when more than one */
3336 int stopstatus; /* status of a stopped job */
3339 nprocs: 16, /* number of processes */
3341 #define JOBRUNNING 0 /* at least one proc running */
3342 #define JOBSTOPPED 1 /* all procs are stopped */
3343 #define JOBDONE 2 /* all procs are completed */
3345 sigint: 1, /* job was killed by SIGINT */
3346 jobctl: 1, /* job running under job control */
3348 waited: 1, /* true if this entry has been waited for */
3349 used: 1, /* true if this entry is in used */
3350 changed: 1; /* true if status has changed */
3351 struct job *prev_job; /* previous job */
3354 static struct job *makejob(/*union node *,*/ int);
3355 static int forkshell(struct job *, union node *, int);
3356 static int waitforjob(struct job *);
3359 enum { doing_jobctl = 0 };
3360 #define setjobctl(on) do {} while (0)
3362 static smallint doing_jobctl; //references:8
3363 static void setjobctl(int);
3370 ignoresig(int signo)
3372 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3373 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3374 /* No, need to do it */
3375 signal(signo, SIG_IGN);
3377 sigmode[signo - 1] = S_HARD_IGN;
3381 * Only one usage site - in setsignal()
3384 signal_handler(int signo)
3386 gotsig[signo - 1] = 1;
3388 if (signo == SIGINT && !trap[SIGINT]) {
3389 if (!suppress_int) {
3391 raise_interrupt(); /* does not return */
3395 pending_sig = signo;
3400 * Set the signal handler for the specified signal. The routine figures
3401 * out what it should be set to.
3404 setsignal(int signo)
3407 char cur_act, new_act;
3408 struct sigaction act;
3412 if (t != NULL) { /* trap for this sig is set */
3414 if (t[0] == '\0') /* trap is "": ignore this sig */
3418 if (rootshell && new_act == S_DFL) {
3421 if (iflag || minusc || sflag == 0)
3430 * "In all cases, bash ignores SIGQUIT. Non-builtin
3431 * commands run by bash have signal handlers
3432 * set to the values inherited by the shell
3433 * from its parent". */
3449 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3450 //whereas we have to restore it to what shell got on entry
3451 //from the parent. See comment above
3453 t = &sigmode[signo - 1];
3456 /* current setting is not yet known */
3457 if (sigaction(signo, NULL, &act)) {
3458 /* pretend it worked; maybe we should give a warning,
3459 * but other shells don't. We don't alter sigmode,
3460 * so we retry every time.
3461 * btw, in Linux it never fails. --vda */
3464 if (act.sa_handler == SIG_IGN) {
3465 cur_act = S_HARD_IGN;
3467 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3469 cur_act = S_IGN; /* don't hard ignore these */
3473 if (cur_act == S_HARD_IGN || cur_act == new_act)
3476 act.sa_handler = SIG_DFL;
3479 act.sa_handler = signal_handler;
3480 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3481 sigfillset(&act.sa_mask); /* ditto */
3484 act.sa_handler = SIG_IGN;
3487 sigaction_set(signo, &act);
3492 /* mode flags for set_curjob */
3493 #define CUR_DELETE 2
3494 #define CUR_RUNNING 1
3495 #define CUR_STOPPED 0
3497 /* mode flags for dowait */
3498 #define DOWAIT_NONBLOCK WNOHANG
3499 #define DOWAIT_BLOCK 0
3502 /* pgrp of shell on invocation */
3503 static int initialpgrp; //references:2
3504 static int ttyfd = -1; //5
3507 static struct job *jobtab; //5
3509 static unsigned njobs; //4
3511 static struct job *curjob; //lots
3512 /* number of presumed living untracked jobs */
3513 static int jobless; //4
3516 set_curjob(struct job *jp, unsigned mode)
3519 struct job **jpp, **curp;
3521 /* first remove from list */
3522 jpp = curp = &curjob;
3527 jpp = &jp1->prev_job;
3529 *jpp = jp1->prev_job;
3531 /* Then re-insert in correct position */
3539 /* job being deleted */
3542 /* newly created job or backgrounded job,
3543 put after all stopped jobs. */
3547 if (!jp1 || jp1->state != JOBSTOPPED)
3550 jpp = &jp1->prev_job;
3556 /* newly stopped job - becomes curjob */
3557 jp->prev_job = *jpp;
3565 jobno(const struct job *jp)
3567 return jp - jobtab + 1;
3572 * Convert a job name to a job structure.
3575 #define getjob(name, getctl) getjob(name)
3578 getjob(const char *name, int getctl)
3582 const char *err_msg = "%s: no such job";
3586 char *(*match)(const char *, const char *);
3601 if (c == '+' || c == '%') {
3603 err_msg = "No current job";
3609 err_msg = "No previous job";
3620 jp = jobtab + num - 1;
3635 if (match(jp->ps[0].ps_cmd, p)) {
3639 err_msg = "%s: ambiguous";
3649 err_msg = "job %s not created under job control";
3650 if (getctl && jp->jobctl == 0)
3655 ash_msg_and_raise_error(err_msg, name);
3659 * Mark a job structure as unused.
3662 freejob(struct job *jp)
3664 struct procstat *ps;
3668 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3669 if (ps->ps_cmd != nullstr)
3672 if (jp->ps != &jp->ps0)
3675 set_curjob(jp, CUR_DELETE);
3681 xtcsetpgrp(int fd, pid_t pgrp)
3683 if (tcsetpgrp(fd, pgrp))
3684 ash_msg_and_raise_error("can't set tty process group (%m)");
3688 * Turn job control on and off.
3690 * Note: This code assumes that the third arg to ioctl is a character
3691 * pointer, which is true on Berkeley systems but not System V. Since
3692 * System V doesn't have job control yet, this isn't a problem now.
3694 * Called with interrupts off.
3702 if (on == doing_jobctl || rootshell == 0)
3706 ofd = fd = open(_PATH_TTY, O_RDWR);
3708 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3709 * That sometimes helps to acquire controlling tty.
3710 * Obviously, a workaround for bugs when someone
3711 * failed to provide a controlling tty to bash! :) */
3717 fd = fcntl(fd, F_DUPFD, 10);
3722 /* fd is a tty at this point */
3723 close_on_exec_on(fd);
3724 do { /* while we are in the background */
3725 pgrp = tcgetpgrp(fd);
3728 ash_msg("can't access tty; job control turned off");
3732 if (pgrp == getpgrp())
3743 xtcsetpgrp(fd, pgrp);
3745 /* turning job control off */
3748 /* was xtcsetpgrp, but this can make exiting ash
3749 * loop forever if pty is already deleted */
3750 tcsetpgrp(fd, pgrp);
3764 static int FAST_FUNC
3765 killcmd(int argc, char **argv)
3768 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3770 if (argv[i][0] == '%') {
3771 struct job *jp = getjob(argv[i], 0);
3772 unsigned pid = jp->ps[0].ps_pid;
3773 /* Enough space for ' -NNN<nul>' */
3774 argv[i] = alloca(sizeof(int)*3 + 3);
3775 /* kill_main has matching code to expect
3776 * leading space. Needed to not confuse
3777 * negative pids with "kill -SIGNAL_NO" syntax */
3778 sprintf(argv[i], " -%u", pid);
3780 } while (argv[++i]);
3782 return kill_main(argc, argv);
3786 showpipe(struct job *jp /*, FILE *out*/)
3788 struct procstat *ps;
3789 struct procstat *psend;
3791 psend = jp->ps + jp->nprocs;
3792 for (ps = jp->ps + 1; ps < psend; ps++)
3793 printf(" | %s", ps->ps_cmd);
3794 outcslow('\n', stdout);
3795 flush_stdout_stderr();
3800 restartjob(struct job *jp, int mode)
3802 struct procstat *ps;
3808 if (jp->state == JOBDONE)
3810 jp->state = JOBRUNNING;
3811 pgid = jp->ps[0].ps_pid;
3812 if (mode == FORK_FG)
3813 xtcsetpgrp(ttyfd, pgid);
3814 killpg(pgid, SIGCONT);
3818 if (WIFSTOPPED(ps->ps_status)) {
3824 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3829 static int FAST_FUNC
3830 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3836 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3840 jp = getjob(*argv, 1);
3841 if (mode == FORK_BG) {
3842 set_curjob(jp, CUR_RUNNING);
3843 printf("[%d] ", jobno(jp));
3845 out1str(jp->ps[0].ps_cmd);
3846 showpipe(jp /*, stdout*/);
3847 retval = restartjob(jp, mode);
3848 } while (*argv && *++argv);
3854 sprint_status(char *s, int status, int sigonly)
3860 if (!WIFEXITED(status)) {
3862 if (WIFSTOPPED(status))
3863 st = WSTOPSIG(status);
3866 st = WTERMSIG(status);
3868 if (st == SIGINT || st == SIGPIPE)
3871 if (WIFSTOPPED(status))
3876 col = fmtstr(s, 32, strsignal(st));
3877 if (WCOREDUMP(status)) {
3878 col += fmtstr(s + col, 16, " (core dumped)");
3880 } else if (!sigonly) {
3881 st = WEXITSTATUS(status);
3883 col = fmtstr(s, 16, "Done(%d)", st);
3885 col = fmtstr(s, 16, "Done");
3892 dowait(int wait_flags, struct job *job)
3897 struct job *thisjob;
3900 TRACE(("dowait(0x%x) called\n", wait_flags));
3902 /* Do a wait system call. If job control is compiled in, we accept
3903 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3904 * NB: _not_ safe_waitpid, we need to detect EINTR */
3906 wait_flags |= WUNTRACED;
3907 pid = waitpid(-1, &status, wait_flags);
3908 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3909 pid, status, errno, strerror(errno)));
3915 for (jp = curjob; jp; jp = jp->prev_job) {
3916 struct procstat *ps;
3917 struct procstat *psend;
3918 if (jp->state == JOBDONE)
3922 psend = ps + jp->nprocs;
3924 if (ps->ps_pid == pid) {
3925 TRACE(("Job %d: changing status of proc %d "
3926 "from 0x%x to 0x%x\n",
3927 jobno(jp), pid, ps->ps_status, status));
3928 ps->ps_status = status;
3931 if (ps->ps_status == -1)
3934 if (state == JOBRUNNING)
3936 if (WIFSTOPPED(ps->ps_status)) {
3937 jp->stopstatus = ps->ps_status;
3941 } while (++ps < psend);
3946 if (!WIFSTOPPED(status))
3952 if (state != JOBRUNNING) {
3953 thisjob->changed = 1;
3955 if (thisjob->state != state) {
3956 TRACE(("Job %d: changing state from %d to %d\n",
3957 jobno(thisjob), thisjob->state, state));
3958 thisjob->state = state;
3960 if (state == JOBSTOPPED) {
3961 set_curjob(thisjob, CUR_STOPPED);
3970 if (thisjob && thisjob == job) {
3974 len = sprint_status(s, status, 1);
3985 blocking_wait_with_raise_on_sig(void)
3987 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
3988 if (pid <= 0 && pending_sig)
3989 raise_exception(EXSIG);
3995 showjob(FILE *out, struct job *jp, int mode)
3997 struct procstat *ps;
3998 struct procstat *psend;
4005 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4006 /* just output process (group) id of pipeline */
4007 fprintf(out, "%d\n", ps->ps_pid);
4011 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4016 else if (curjob && jp == curjob->prev_job)
4019 if (mode & SHOW_PIDS)
4020 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4022 psend = ps + jp->nprocs;
4024 if (jp->state == JOBRUNNING) {
4025 strcpy(s + col, "Running");
4026 col += sizeof("Running") - 1;
4028 int status = psend[-1].ps_status;
4029 if (jp->state == JOBSTOPPED)
4030 status = jp->stopstatus;
4031 col += sprint_status(s + col, status, 0);
4033 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4035 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4036 * or prints several "PID | <cmdN>" lines,
4037 * depending on SHOW_PIDS bit.
4038 * We do not print status of individual processes
4039 * between PID and <cmdN>. bash does it, but not very well:
4040 * first line shows overall job status, not process status,
4041 * making it impossible to know 1st process status.
4045 /* for each process */
4048 if (mode & SHOW_PIDS)
4049 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4051 fprintf(out, "%s%*c%s%s",
4053 33 - col >= 0 ? 33 - col : 0, ' ',
4054 ps == jp->ps ? "" : "| ",
4057 } while (++ps != psend);
4058 outcslow('\n', out);
4062 if (jp->state == JOBDONE) {
4063 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4069 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4070 * statuses have changed since the last call to showjobs.
4073 showjobs(FILE *out, int mode)
4077 TRACE(("showjobs(0x%x) called\n", mode));
4079 /* Handle all finished jobs */
4080 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4083 for (jp = curjob; jp; jp = jp->prev_job) {
4084 if (!(mode & SHOW_CHANGED) || jp->changed) {
4085 showjob(out, jp, mode);
4090 static int FAST_FUNC
4091 jobscmd(int argc UNUSED_PARAM, char **argv)
4096 while ((m = nextopt("lp")) != '\0') {
4100 mode |= SHOW_ONLY_PGID;
4106 showjob(stdout, getjob(*argv, 0), mode);
4109 showjobs(stdout, mode);
4116 /* Called only on finished or stopped jobs (no members are running) */
4118 getstatus(struct job *job)
4122 struct procstat *ps;
4124 /* Fetch last member's status */
4125 ps = job->ps + job->nprocs - 1;
4126 status = ps->ps_status;
4128 /* "set -o pipefail" mode: use last _nonzero_ status */
4129 while (status == 0 && --ps >= job->ps)
4130 status = ps->ps_status;
4133 retval = WEXITSTATUS(status);
4134 if (!WIFEXITED(status)) {
4136 retval = WSTOPSIG(status);
4137 if (!WIFSTOPPED(status))
4140 /* XXX: limits number of signals */
4141 retval = WTERMSIG(status);
4143 if (retval == SIGINT)
4149 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4150 jobno(job), job->nprocs, status, retval));
4154 static int FAST_FUNC
4155 waitcmd(int argc UNUSED_PARAM, char **argv)
4162 raise_exception(EXSIG);
4169 /* wait for all jobs */
4173 if (!jp) /* no running procs */
4175 if (jp->state == JOBRUNNING)
4180 blocking_wait_with_raise_on_sig();
4182 * "When bash is waiting for an asynchronous command via
4183 * the wait builtin, the reception of a signal for which a trap
4184 * has been set will cause the wait builtin to return immediately
4185 * with an exit status greater than 128, immediately after which
4186 * the trap is executed."
4188 * blocking_wait_with_raise_on_sig raises signal handlers
4189 * if it gets no pid (pid < 0). However,
4190 * if child sends us a signal *and immediately exits*,
4191 * blocking_wait_with_raise_on_sig gets pid > 0
4192 * and does not handle pending_sig. Check this case: */
4194 raise_exception(EXSIG);
4200 if (**argv != '%') {
4201 pid_t pid = number(*argv);
4206 if (job->ps[job->nprocs - 1].ps_pid == pid)
4208 job = job->prev_job;
4211 job = getjob(*argv, 0);
4212 /* loop until process terminated or stopped */
4213 while (job->state == JOBRUNNING)
4214 blocking_wait_with_raise_on_sig();
4216 retval = getstatus(job);
4229 struct job *jp, *jq;
4231 len = njobs * sizeof(*jp);
4233 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4235 offset = (char *)jp - (char *)jq;
4237 /* Relocate pointers */
4240 jq = (struct job *)((char *)jq + l);
4244 #define joff(p) ((struct job *)((char *)(p) + l))
4245 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4246 if (joff(jp)->ps == &jq->ps0)
4247 jmove(joff(jp)->ps);
4248 if (joff(jp)->prev_job)
4249 jmove(joff(jp)->prev_job);
4259 jp = (struct job *)((char *)jp + len);
4263 } while (--jq >= jp);
4268 * Return a new job structure.
4269 * Called with interrupts off.
4272 makejob(/*union node *node,*/ int nprocs)
4277 for (i = njobs, jp = jobtab; ; jp++) {
4284 if (jp->state != JOBDONE || !jp->waited)
4293 memset(jp, 0, sizeof(*jp));
4295 /* jp->jobctl is a bitfield.
4296 * "jp->jobctl |= jobctl" likely to give awful code */
4300 jp->prev_job = curjob;
4305 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4307 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4314 * Return a string identifying a command (to be printed by the
4317 static char *cmdnextc;
4320 cmdputs(const char *s)
4322 static const char vstype[VSTYPE + 1][3] = {
4323 "", "}", "-", "+", "?", "=",
4324 "%", "%%", "#", "##"
4325 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4328 const char *p, *str;
4332 unsigned char subtype = 0;
4336 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4338 while ((c = *p++) != '\0') {
4346 if ((subtype & VSTYPE) == VSLENGTH)
4350 if (!(subtype & VSQUOTE) == !(quoted & 1))
4356 str = "\"}" + !(quoted & 1);
4363 case CTLBACKQ+CTLQUOTE:
4366 #if ENABLE_SH_MATH_SUPPORT
4381 if ((subtype & VSTYPE) != VSNORMAL)
4383 str = vstype[subtype & VSTYPE];
4384 if (subtype & VSNUL)
4393 /* These can only happen inside quotes */
4406 while ((c = *str++) != '\0') {
4409 } /* while *p++ not NUL */
4412 USTPUTC('"', nextc);
4418 /* cmdtxt() and cmdlist() call each other */
4419 static void cmdtxt(union node *n);
4422 cmdlist(union node *np, int sep)
4424 for (; np; np = np->narg.next) {
4428 if (sep && np->narg.next)
4434 cmdtxt(union node *n)
4437 struct nodelist *lp;
4448 lp = n->npipe.cmdlist;
4466 cmdtxt(n->nbinary.ch1);
4482 cmdtxt(n->nif.test);
4484 if (n->nif.elsepart) {
4485 cmdtxt(n->nif.ifpart);
4487 n = n->nif.elsepart;
4505 cmdtxt(n->nbinary.ch1);
4515 cmdputs(n->nfor.var);
4517 cmdlist(n->nfor.args, 1);
4522 cmdputs(n->narg.text);
4526 cmdlist(n->ncmd.args, 1);
4527 cmdlist(n->ncmd.redirect, 0);
4540 cmdputs(n->ncase.expr->narg.text);
4542 for (np = n->ncase.cases; np; np = np->nclist.next) {
4543 cmdtxt(np->nclist.pattern);
4545 cmdtxt(np->nclist.body);
4559 #if ENABLE_ASH_BASH_COMPAT
4574 cmdputs(utoa(n->nfile.fd));
4576 if (n->type == NTOFD || n->type == NFROMFD) {
4577 cmdputs(utoa(n->ndup.dupfd));
4586 commandtext(union node *n)
4590 STARTSTACKSTR(cmdnextc);
4592 name = stackblock();
4593 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4594 name, cmdnextc, cmdnextc));
4595 return ckstrdup(name);
4600 * Fork off a subshell. If we are doing job control, give the subshell its
4601 * own process group. Jp is a job structure that the job is to be added to.
4602 * N is the command that will be evaluated by the child. Both jp and n may
4603 * be NULL. The mode parameter can be one of the following:
4604 * FORK_FG - Fork off a foreground process.
4605 * FORK_BG - Fork off a background process.
4606 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4607 * process group even if job control is on.
4609 * When job control is turned off, background processes have their standard
4610 * input redirected to /dev/null (except for the second and later processes
4613 * Called with interrupts off.
4616 * Clear traps on a fork.
4623 for (tp = trap; tp < &trap[NSIG]; tp++) {
4624 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4626 if (trap_ptr == trap)
4628 /* else: it "belongs" to trap_ptr vector, don't free */
4630 if ((tp - trap) != 0)
4631 setsignal(tp - trap);
4637 /* Lives far away from here, needed for forkchild */
4638 static void closescript(void);
4640 /* Called after fork(), in child */
4641 static NOINLINE void
4642 forkchild(struct job *jp, union node *n, int mode)
4646 TRACE(("Child shell %d\n", getpid()));
4650 /* man bash: "Non-builtin commands run by bash have signal handlers
4651 * set to the values inherited by the shell from its parent".
4652 * Do we do it correctly? */
4656 if (mode == FORK_NOJOB /* is it `xxx` ? */
4657 && n && n->type == NCMD /* is it single cmd? */
4658 /* && n->ncmd.args->type == NARG - always true? */
4659 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4660 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4661 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4663 TRACE(("Trap hack\n"));
4664 /* Awful hack for `trap` or $(trap).
4666 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4667 * contains an example where "trap" is executed in a subshell:
4669 * save_traps=$(trap)
4671 * eval "$save_traps"
4673 * Standard does not say that "trap" in subshell shall print
4674 * parent shell's traps. It only says that its output
4675 * must have suitable form, but then, in the above example
4676 * (which is not supposed to be normative), it implies that.
4678 * bash (and probably other shell) does implement it
4679 * (traps are reset to defaults, but "trap" still shows them),
4680 * but as a result, "trap" logic is hopelessly messed up:
4683 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4684 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4685 * # true | trap <--- trap is in subshell - no output (ditto)
4686 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4687 * trap -- 'echo Ho' SIGWINCH
4688 * # echo `(trap)` <--- in subshell in subshell - output
4689 * trap -- 'echo Ho' SIGWINCH
4690 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4691 * trap -- 'echo Ho' SIGWINCH
4693 * The rules when to forget and when to not forget traps
4694 * get really complex and nonsensical.
4696 * Our solution: ONLY bare $(trap) or `trap` is special.
4698 /* Save trap handler strings for trap builtin to print */
4699 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4700 /* Fall through into clearing traps */
4704 /* do job control only in root shell */
4706 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4709 if (jp->nprocs == 0)
4712 pgrp = jp->ps[0].ps_pid;
4713 /* this can fail because we are doing it in the parent also */
4715 if (mode == FORK_FG)
4716 xtcsetpgrp(ttyfd, pgrp);
4721 if (mode == FORK_BG) {
4722 /* man bash: "When job control is not in effect,
4723 * asynchronous commands ignore SIGINT and SIGQUIT" */
4726 if (jp->nprocs == 0) {
4728 if (open(bb_dev_null, O_RDONLY) != 0)
4729 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4733 if (iflag) { /* why if iflag only? */
4738 * "In all cases, bash ignores SIGQUIT. Non-builtin
4739 * commands run by bash have signal handlers
4740 * set to the values inherited by the shell
4742 * Take care of the second rule: */
4746 if (n && n->type == NCMD
4747 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4749 TRACE(("Job hack\n"));
4750 /* "jobs": we do not want to clear job list for it,
4751 * instead we remove only _its_ own_ job from job list.
4752 * This makes "jobs .... | cat" more useful.
4758 for (jp = curjob; jp; jp = jp->prev_job)
4763 /* Called after fork(), in parent */
4765 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4768 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4770 TRACE(("In parent shell: child = %d\n", pid));
4772 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4778 if (mode != FORK_NOJOB && jp->jobctl) {
4781 if (jp->nprocs == 0)
4784 pgrp = jp->ps[0].ps_pid;
4785 /* This can fail because we are doing it in the child also */
4789 if (mode == FORK_BG) {
4790 backgndpid = pid; /* set $! */
4791 set_curjob(jp, CUR_RUNNING);
4794 struct procstat *ps = &jp->ps[jp->nprocs++];
4797 ps->ps_cmd = nullstr;
4799 if (doing_jobctl && n)
4800 ps->ps_cmd = commandtext(n);
4806 forkshell(struct job *jp, union node *n, int mode)
4810 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4813 TRACE(("Fork failed, errno=%d", errno));
4816 ash_msg_and_raise_error("can't fork");
4819 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4820 forkchild(jp, n, mode);
4822 forkparent(jp, n, mode, pid);
4828 * Wait for job to finish.
4830 * Under job control we have the problem that while a child process
4831 * is running interrupts generated by the user are sent to the child
4832 * but not to the shell. This means that an infinite loop started by
4833 * an interactive user may be hard to kill. With job control turned off,
4834 * an interactive user may place an interactive program inside a loop.
4835 * If the interactive program catches interrupts, the user doesn't want
4836 * these interrupts to also abort the loop. The approach we take here
4837 * is to have the shell ignore interrupt signals while waiting for a
4838 * foreground process to terminate, and then send itself an interrupt
4839 * signal if the child process was terminated by an interrupt signal.
4840 * Unfortunately, some programs want to do a bit of cleanup and then
4841 * exit on interrupt; unless these processes terminate themselves by
4842 * sending a signal to themselves (instead of calling exit) they will
4843 * confuse this approach.
4845 * Called with interrupts off.
4848 waitforjob(struct job *jp)
4852 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4855 while (jp->state == JOBRUNNING) {
4856 /* In non-interactive shells, we _can_ get
4857 * a keyboard signal here and be EINTRed,
4858 * but we just loop back, waiting for command to complete.
4861 * "If bash is waiting for a command to complete and receives
4862 * a signal for which a trap has been set, the trap
4863 * will not be executed until the command completes."
4865 * Reality is that even if trap is not set, bash
4866 * will not act on the signal until command completes.
4867 * Try this. sleep5intoff.c:
4868 * #include <signal.h>
4869 * #include <unistd.h>
4872 * sigemptyset(&set);
4873 * sigaddset(&set, SIGINT);
4874 * sigaddset(&set, SIGQUIT);
4875 * sigprocmask(SIG_BLOCK, &set, NULL);
4879 * $ bash -c './sleep5intoff; echo hi'
4880 * ^C^C^C^C <--- pressing ^C once a second
4882 * $ bash -c './sleep5intoff; echo hi'
4883 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4886 dowait(DOWAIT_BLOCK, jp);
4893 xtcsetpgrp(ttyfd, rootpid);
4895 * This is truly gross.
4896 * If we're doing job control, then we did a TIOCSPGRP which
4897 * caused us (the shell) to no longer be in the controlling
4898 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4899 * intuit from the subprocess exit status whether a SIGINT
4900 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4902 if (jp->sigint) /* TODO: do the same with all signals */
4903 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4905 if (jp->state == JOBDONE)
4912 * return 1 if there are stopped jobs, otherwise 0
4924 if (jp && jp->state == JOBSTOPPED) {
4925 out2str("You have stopped jobs.\n");
4934 /* ============ redir.c
4936 * Code for dealing with input/output redirection.
4939 #define EMPTY -2 /* marks an unused slot in redirtab */
4940 #define CLOSED -3 /* marks a slot of previously-closed fd */
4943 * Open a file in noclobber mode.
4944 * The code was copied from bash.
4947 noclobberopen(const char *fname)
4950 struct stat finfo, finfo2;
4953 * If the file exists and is a regular file, return an error
4956 r = stat(fname, &finfo);
4957 if (r == 0 && S_ISREG(finfo.st_mode)) {
4963 * If the file was not present (r != 0), make sure we open it
4964 * exclusively so that if it is created before we open it, our open
4965 * will fail. Make sure that we do not truncate an existing file.
4966 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4967 * file was not a regular file, we leave O_EXCL off.
4970 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4971 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4973 /* If the open failed, return the file descriptor right away. */
4978 * OK, the open succeeded, but the file may have been changed from a
4979 * non-regular file to a regular file between the stat and the open.
4980 * We are assuming that the O_EXCL open handles the case where FILENAME
4981 * did not exist and is symlinked to an existing file between the stat
4986 * If we can open it and fstat the file descriptor, and neither check
4987 * revealed that it was a regular file, and the file has not been
4988 * replaced, return the file descriptor.
4990 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4991 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4994 /* The file has been replaced. badness. */
5001 * Handle here documents. Normally we fork off a process to write the
5002 * data to a pipe. If the document is short, we can stuff the data in
5003 * the pipe without forking.
5005 /* openhere needs this forward reference */
5006 static void expandhere(union node *arg, int fd);
5008 openhere(union node *redir)
5014 ash_msg_and_raise_error("pipe call failed");
5015 if (redir->type == NHERE) {
5016 len = strlen(redir->nhere.doc->narg.text);
5017 if (len <= PIPE_BUF) {
5018 full_write(pip[1], redir->nhere.doc->narg.text, len);
5022 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5025 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5026 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5027 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5028 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5029 signal(SIGPIPE, SIG_DFL);
5030 if (redir->type == NHERE)
5031 full_write(pip[1], redir->nhere.doc->narg.text, len);
5033 expandhere(redir->nhere.doc, pip[1]);
5034 _exit(EXIT_SUCCESS);
5042 openredirect(union node *redir)
5047 switch (redir->nfile.type) {
5049 fname = redir->nfile.expfname;
5050 f = open(fname, O_RDONLY);
5055 fname = redir->nfile.expfname;
5056 f = open(fname, O_RDWR|O_CREAT, 0666);
5061 #if ENABLE_ASH_BASH_COMPAT
5064 /* Take care of noclobber mode. */
5066 fname = redir->nfile.expfname;
5067 f = noclobberopen(fname);
5074 fname = redir->nfile.expfname;
5075 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5080 fname = redir->nfile.expfname;
5081 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5089 /* Fall through to eliminate warning. */
5090 /* Our single caller does this itself */
5097 f = openhere(redir);
5103 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5105 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5109 * Copy a file descriptor to be >= to. Returns -1
5110 * if the source file descriptor is closed, EMPTY if there are no unused
5111 * file descriptors left.
5113 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5114 * old code was doing close(to) prior to copyfd() to achieve the same */
5116 COPYFD_EXACT = (int)~(INT_MAX),
5117 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5120 copyfd(int from, int to)
5124 if (to & COPYFD_EXACT) {
5125 to &= ~COPYFD_EXACT;
5127 newfd = dup2(from, to);
5129 newfd = fcntl(from, F_DUPFD, to);
5132 if (errno == EMFILE)
5134 /* Happens when source fd is not open: try "echo >&99" */
5135 ash_msg_and_raise_error("%d: %m", from);
5140 /* Struct def and variable are moved down to the first usage site */
5145 struct redirtab *next;
5148 struct two_fd_t two_fd[];
5150 #define redirlist (G_var.redirlist)
5152 static int need_to_remember(struct redirtab *rp, int fd)
5156 if (!rp) /* remembering was not requested */
5159 for (i = 0; i < rp->pair_count; i++) {
5160 if (rp->two_fd[i].orig == fd) {
5161 /* already remembered */
5168 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5169 static int is_hidden_fd(struct redirtab *rp, int fd)
5172 struct parsefile *pf;
5176 /* Check open scripts' fds */
5179 /* We skip pf_fd == 0 case because of the following case:
5180 * $ ash # running ash interactively
5182 * and in script.sh: "exec 9>&0".
5183 * Even though top-level pf_fd _is_ 0,
5184 * it's still ok to use it: "read" builtin uses it,
5185 * why should we cripple "exec" builtin?
5187 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5195 /* Check saved fds of redirects */
5196 fd |= COPYFD_RESTORE;
5197 for (i = 0; i < rp->pair_count; i++) {
5198 if (rp->two_fd[i].copy == fd) {
5206 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5207 * old file descriptors are stashed away so that the redirection can be
5208 * undone by calling popredir.
5210 /* flags passed to redirect */
5211 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5212 #define REDIR_SAVEFD2 03 /* set preverrout */
5214 redirect(union node *redir, int flags)
5216 struct redirtab *sv;
5221 int copied_fd2 = -1;
5231 if (flags & REDIR_PUSH) {
5232 union node *tmp = redir;
5235 #if ENABLE_ASH_BASH_COMPAT
5236 if (tmp->nfile.type == NTO2)
5239 tmp = tmp->nfile.next;
5241 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5242 sv->next = redirlist;
5243 sv->pair_count = sv_pos;
5245 sv->nullredirs = g_nullredirs - 1;
5247 while (sv_pos > 0) {
5249 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5255 fd = redir->nfile.fd;
5256 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5257 right_fd = redir->ndup.dupfd;
5258 //bb_error_msg("doing %d > %d", fd, right_fd);
5259 /* redirect from/to same file descriptor? */
5262 /* "echo >&10" and 10 is a fd opened to a sh script? */
5263 if (is_hidden_fd(sv, right_fd)) {
5264 errno = EBADF; /* as if it is closed */
5265 ash_msg_and_raise_error("%d: %m", right_fd);
5269 newfd = openredirect(redir); /* always >= 0 */
5271 /* Descriptor wasn't open before redirect.
5272 * Mark it for close in the future */
5273 if (need_to_remember(sv, fd)) {
5274 goto remember_to_close;
5279 #if ENABLE_ASH_BASH_COMPAT
5282 if (need_to_remember(sv, fd)) {
5283 /* Copy old descriptor */
5284 /* Careful to not accidentally "save"
5285 * to the same fd as right side fd in N>&M */
5286 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5287 i = fcntl(fd, F_DUPFD, minfd);
5288 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5289 * are closed in popredir() in the child, preventing them from leaking
5290 * into child. (popredir() also cleans up the mess in case of failures)
5295 /* Strange error (e.g. "too many files" EMFILE?) */
5299 ash_msg_and_raise_error("%d: %m", fd);
5302 /* EBADF: it is not open - good, remember to close it */
5305 } else { /* fd is open, save its copy */
5306 /* "exec fd>&-" should not close fds
5307 * which point to script file(s).
5308 * Force them to be restored afterwards */
5309 if (is_hidden_fd(sv, fd))
5310 i |= COPYFD_RESTORE;
5314 sv->two_fd[sv_pos].orig = fd;
5315 sv->two_fd[sv_pos].copy = i;
5319 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5320 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5321 /* Don't want to trigger debugging */
5325 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5327 } else if (fd != newfd) { /* move newfd to fd */
5328 copyfd(newfd, fd | COPYFD_EXACT);
5329 #if ENABLE_ASH_BASH_COMPAT
5330 if (!(redir->nfile.type == NTO2 && fd == 2))
5334 #if ENABLE_ASH_BASH_COMPAT
5335 if (redir->nfile.type == NTO2 && fd == 1) {
5336 /* We already redirected it to fd 1, now copy it to 2 */
5342 } while ((redir = redir->nfile.next) != NULL);
5345 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5346 preverrout_fd = copied_fd2;
5350 * Undo the effects of the last redirection.
5353 popredir(int drop, int restore)
5355 struct redirtab *rp;
5358 if (--g_nullredirs >= 0)
5362 for (i = 0; i < rp->pair_count; i++) {
5363 int fd = rp->two_fd[i].orig;
5364 int copy = rp->two_fd[i].copy;
5365 if (copy == CLOSED) {
5370 if (copy != EMPTY) {
5371 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5372 copy &= ~COPYFD_RESTORE;
5374 copyfd(copy, fd | COPYFD_EXACT);
5376 close(copy & ~COPYFD_RESTORE);
5379 redirlist = rp->next;
5380 g_nullredirs = rp->nullredirs;
5386 * Undo all redirections. Called on error or interrupt.
5390 * Discard all saved file descriptors.
5393 clearredir(int drop)
5399 popredir(drop, /*restore:*/ 0);
5404 redirectsafe(union node *redir, int flags)
5407 volatile int saveint;
5408 struct jmploc *volatile savehandler = exception_handler;
5409 struct jmploc jmploc;
5412 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5413 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5415 exception_handler = &jmploc;
5416 redirect(redir, flags);
5418 exception_handler = savehandler;
5419 if (err && exception_type != EXERROR)
5420 longjmp(exception_handler->loc, 1);
5421 RESTORE_INT(saveint);
5426 /* ============ Routines to expand arguments to commands
5428 * We have to deal with backquotes, shell variables, and file metacharacters.
5431 #if ENABLE_SH_MATH_SUPPORT
5433 ash_arith(const char *s)
5435 arith_eval_hooks_t math_hooks;
5439 math_hooks.lookupvar = lookupvar;
5440 math_hooks.setvar = setvar2;
5441 math_hooks.endofname = endofname;
5444 result = arith(s, &errcode, &math_hooks);
5447 ash_msg_and_raise_error("exponent less than 0");
5449 ash_msg_and_raise_error("divide by zero");
5451 ash_msg_and_raise_error("expression recursion loop detected");
5452 raise_error_syntax(s);
5463 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5464 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5465 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5466 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5467 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5468 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5469 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5470 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5471 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5475 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5476 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5477 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5478 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5479 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5482 * Structure specifying which parts of the string should be searched
5483 * for IFS characters.
5486 struct ifsregion *next; /* next region in list */
5487 int begoff; /* offset of start of region */
5488 int endoff; /* offset of end of region */
5489 int nulonly; /* search for nul bytes only */
5493 struct strlist *list;
5494 struct strlist **lastp;
5497 /* output of current string */
5498 static char *expdest;
5499 /* list of back quote expressions */
5500 static struct nodelist *argbackq;
5501 /* first struct in list of ifs regions */
5502 static struct ifsregion ifsfirst;
5503 /* last struct in list */
5504 static struct ifsregion *ifslastp;
5505 /* holds expanded arg list */
5506 static struct arglist exparg;
5516 expdest = makestrspace(32, expdest);
5517 len = fmtstr(expdest, 32, arith_t_fmt, num);
5518 STADJUST(len, expdest);
5523 esclen(const char *start, const char *p)
5527 while (p > start && (unsigned char)*--p == CTLESC) {
5534 * Remove any CTLESC characters from a string.
5537 rmescapes(char *str, int flag)
5539 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5543 unsigned protect_against_glob;
5546 p = strpbrk(str, qchars);
5552 if (flag & RMESCAPE_ALLOC) {
5553 size_t len = p - str;
5554 size_t fulllen = len + strlen(p) + 1;
5556 if (flag & RMESCAPE_GROW) {
5557 int strloc = str - (char *)stackblock();
5558 r = makestrspace(fulllen, expdest);
5559 /* p and str may be invalidated by makestrspace */
5560 str = (char *)stackblock() + strloc;
5562 } else if (flag & RMESCAPE_HEAP) {
5563 r = ckmalloc(fulllen);
5565 r = stalloc(fulllen);
5569 q = (char *)memcpy(q, str, len) + len;
5573 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5574 globbing = flag & RMESCAPE_GLOB;
5575 protect_against_glob = globbing;
5577 if ((unsigned char)*p == CTLQUOTEMARK) {
5578 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5579 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5580 // Note: both inquotes and protect_against_glob only affect whether
5581 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5582 inquotes = ~inquotes;
5584 protect_against_glob = globbing;
5588 /* naked back slash */
5589 protect_against_glob = 0;
5592 if ((unsigned char)*p == CTLESC) {
5594 if (protect_against_glob && inquotes && *p != '/') {
5598 protect_against_glob = globbing;
5603 if (flag & RMESCAPE_GROW) {
5605 STADJUST(q - r + 1, expdest);
5609 #define pmatch(a, b) !fnmatch((a), (b), 0)
5612 * Prepare a pattern for a expmeta (internal glob(3)) call.
5614 * Returns an stalloced string.
5617 preglob(const char *pattern, int quoted, int flag)
5619 flag |= RMESCAPE_GLOB;
5621 flag |= RMESCAPE_QUOTED;
5623 return rmescapes((char *)pattern, flag);
5627 * Put a string on the stack.
5630 memtodest(const char *p, size_t len, int syntax, int quotes)
5634 q = makestrspace(quotes ? len * 2 : len, q);
5637 unsigned char c = *p++;
5641 int n = SIT(c, syntax);
5642 if (n == CCTL || n == CBACK)
5652 strtodest(const char *p, int syntax, int quotes)
5654 memtodest(p, strlen(p), syntax, quotes);
5658 * Record the fact that we have to scan this region of the
5659 * string for IFS characters.
5662 recordregion(int start, int end, int nulonly)
5664 struct ifsregion *ifsp;
5666 if (ifslastp == NULL) {
5670 ifsp = ckzalloc(sizeof(*ifsp));
5671 /*ifsp->next = NULL; - ckzalloc did it */
5672 ifslastp->next = ifsp;
5676 ifslastp->begoff = start;
5677 ifslastp->endoff = end;
5678 ifslastp->nulonly = nulonly;
5682 removerecordregions(int endoff)
5684 if (ifslastp == NULL)
5687 if (ifsfirst.endoff > endoff) {
5688 while (ifsfirst.next != NULL) {
5689 struct ifsregion *ifsp;
5691 ifsp = ifsfirst.next->next;
5692 free(ifsfirst.next);
5693 ifsfirst.next = ifsp;
5696 if (ifsfirst.begoff > endoff)
5699 ifslastp = &ifsfirst;
5700 ifsfirst.endoff = endoff;
5705 ifslastp = &ifsfirst;
5706 while (ifslastp->next && ifslastp->next->begoff < endoff)
5707 ifslastp=ifslastp->next;
5708 while (ifslastp->next != NULL) {
5709 struct ifsregion *ifsp;
5711 ifsp = ifslastp->next->next;
5712 free(ifslastp->next);
5713 ifslastp->next = ifsp;
5716 if (ifslastp->endoff > endoff)
5717 ifslastp->endoff = endoff;
5721 exptilde(char *startp, char *p, int flags)
5727 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5732 while ((c = *++p) != '\0') {
5739 if (flags & EXP_VARTILDE)
5749 if (*name == '\0') {
5750 home = lookupvar("HOME");
5752 pw = getpwnam(name);
5757 if (!home || !*home)
5760 startloc = expdest - (char *)stackblock();
5761 strtodest(home, SQSYNTAX, quotes);
5762 recordregion(startloc, expdest - (char *)stackblock(), 0);
5770 * Execute a command inside back quotes. If it's a builtin command, we
5771 * want to save its output in a block obtained from malloc. Otherwise
5772 * we fork off a subprocess and get the output of the command via a pipe.
5773 * Should be called with interrupts off.
5775 struct backcmd { /* result of evalbackcmd */
5776 int fd; /* file descriptor to read from */
5777 int nleft; /* number of chars in buffer */
5778 char *buf; /* buffer */
5779 struct job *jp; /* job structure for command */
5782 /* These forward decls are needed to use "eval" code for backticks handling: */
5783 static uint8_t back_exitstatus; /* exit status of backquoted command */
5784 #define EV_EXIT 01 /* exit after evaluating tree */
5785 static void evaltree(union node *, int);
5787 static void FAST_FUNC
5788 evalbackcmd(union node *n, struct backcmd *result)
5799 saveherefd = herefd;
5807 ash_msg_and_raise_error("pipe call failed");
5808 jp = makejob(/*n,*/ 1);
5809 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5814 copyfd(pip[1], 1 | COPYFD_EXACT);
5818 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5822 result->fd = pip[0];
5825 herefd = saveherefd;
5827 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5828 result->fd, result->buf, result->nleft, result->jp));
5832 * Expand stuff in backwards quotes.
5835 expbackq(union node *cmd, int quoted, int quotes)
5843 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5844 struct stackmark smark;
5847 setstackmark(&smark);
5849 startloc = dest - (char *)stackblock();
5851 evalbackcmd(cmd, &in);
5852 popstackmark(&smark);
5859 memtodest(p, i, syntax, quotes);
5863 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5864 TRACE(("expbackq: read returns %d\n", i));
5873 back_exitstatus = waitforjob(in.jp);
5877 /* Eat all trailing newlines */
5879 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5884 recordregion(startloc, dest - (char *)stackblock(), 0);
5885 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5886 (dest - (char *)stackblock()) - startloc,
5887 (dest - (char *)stackblock()) - startloc,
5888 stackblock() + startloc));
5891 #if ENABLE_SH_MATH_SUPPORT
5893 * Expand arithmetic expression. Backup to start of expression,
5894 * evaluate, place result in (backed up) result, adjust string position.
5907 * This routine is slightly over-complicated for
5908 * efficiency. Next we scan backwards looking for the
5909 * start of arithmetic.
5911 start = stackblock();
5918 while ((unsigned char)*p != CTLARI) {
5922 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5927 esc = esclen(start, p);
5937 removerecordregions(begoff);
5944 rmescapes(p + 2, 0);
5946 len = cvtnum(ash_arith(p + 2));
5949 recordregion(begoff, begoff + len, 0);
5953 /* argstr needs it */
5954 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5957 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5958 * characters to allow for further processing. Otherwise treat
5959 * $@ like $* since no splitting will be performed.
5961 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5962 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5963 * for correct expansion of "B=$A" word.
5966 argstr(char *p, int flags, struct strlist *var_str_list)
5968 static const char spclchars[] ALIGN1 = {
5976 CTLBACKQ | CTLQUOTE,
5977 #if ENABLE_SH_MATH_SUPPORT
5982 const char *reject = spclchars;
5983 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5984 int breakall = flags & EXP_WORD;
5989 if (!(flags & EXP_VARTILDE)) {
5991 } else if (flags & EXP_VARTILDE2) {
5996 if (flags & EXP_TILDE) {
5999 flags &= ~EXP_TILDE;
6002 if (*q == CTLESC && (flags & EXP_QWORD))
6005 p = exptilde(p, q, flags);
6008 startloc = expdest - (char *)stackblock();
6012 length += strcspn(p + length, reject);
6016 #if ENABLE_SH_MATH_SUPPORT
6020 /* c == '=' || c == ':' || c == CTLENDARI */
6026 expdest = stack_nputstr(p, length, expdest);
6027 newloc = expdest - (char *)stackblock();
6028 if (breakall && !inquotes && newloc > startloc) {
6029 recordregion(startloc, newloc, 0);
6040 if (flags & EXP_VARTILDE2) {
6044 flags |= EXP_VARTILDE2;
6049 * sort of a hack - expand tildes in variable
6050 * assignments (after the first '=' and after ':'s).
6059 case CTLENDVAR: /* ??? */
6062 /* "$@" syntax adherence hack */
6064 && memcmp(p, dolatstr, 4) == 0
6065 && ( p[4] == CTLQUOTEMARK
6066 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
6069 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
6072 inquotes = !inquotes;
6085 p = evalvar(p, flags, var_str_list);
6089 case CTLBACKQ|CTLQUOTE:
6090 expbackq(argbackq->n, c, quotes);
6091 argbackq = argbackq->next;
6093 #if ENABLE_SH_MATH_SUPPORT
6106 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
6109 // This commented out code was added by James Simmons <jsimmons@infradead.org>
6110 // as part of a larger change when he added support for ${var/a/b}.
6111 // However, it broke # and % operators:
6115 //echo ${var#ab} abcdcd abcdcd
6116 //echo ${var##ab} abcdcd abcdcd
6117 //echo ${var#a*b} abcdcd ababcdcd (!)
6118 //echo ${var##a*b} cdcd cdcd
6119 //echo ${var#?} babcdcd ababcdcd (!)
6120 //echo ${var##?} babcdcd babcdcd
6121 //echo ${var#*} ababcdcd babcdcd (!)
6123 //echo ${var%cd} ababcd ababcd
6124 //echo ${var%%cd} ababcd abab (!)
6125 //echo ${var%c*d} ababcd ababcd
6126 //echo ${var%%c*d} abab ababcdcd (!)
6127 //echo ${var%?} ababcdc ababcdc
6128 //echo ${var%%?} ababcdc ababcdcd (!)
6129 //echo ${var%*} ababcdcd ababcdcd
6132 // Commenting it back out helped. Remove it completely if it really
6135 char *loc, *loc2; //, *full;
6141 int match; // = strlen(str);
6142 const char *s = loc2;
6149 match = pmatch(str, s); // this line was deleted
6151 // // chop off end if its '*'
6152 // full = strrchr(str, '*');
6153 // if (full && full != str)
6156 // // If str starts with '*' replace with s.
6157 // if ((*str == '*') && strlen(s) >= match) {
6158 // full = xstrdup(s);
6159 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6161 // full = xstrndup(str, match);
6162 // match = strncmp(s, full, strlen(full));
6166 if (match) // if (!match)
6168 if (quotes && (unsigned char)*loc == CTLESC)
6177 scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
6179 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6180 int try2optimize = match_at_start;
6186 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6187 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6188 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6190 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6191 * and on each iteration they go back two/one char until they reach the beginning.
6192 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6194 /* TODO: document in what other circumstances we are called. */
6196 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6199 const char *s = loc2;
6200 if (match_at_start) {
6204 match = pmatch(pattern, s);
6205 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6209 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6211 /* Maybe we can optimize this:
6212 * if pattern ends with unescaped *, we can avoid checking
6213 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6214 * it wont match truncated "raw_value_of_" strings too.
6216 unsigned plen = strlen(pattern);
6217 /* Does it end with "*"? */
6218 if (plen != 0 && pattern[--plen] == '*') {
6219 /* "xxxx*" is not escaped */
6220 /* "xxx\*" is escaped */
6221 /* "xx\\*" is not escaped */
6222 /* "x\\\*" is escaped */
6224 while (plen != 0 && pattern[--plen] == '\\')
6227 break; /* ends with unescaped "*" */
6235 esc = esclen(startp, loc);
6246 static void varunset(const char *, const char *, const char *, int) NORETURN;
6248 varunset(const char *end, const char *var, const char *umsg, int varflags)
6254 msg = "parameter not set";
6256 if ((unsigned char)*end == CTLENDVAR) {
6257 if (varflags & VSNUL)
6263 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6266 #if ENABLE_ASH_BASH_COMPAT
6268 parse_sub_pattern(char *arg, int inquotes)
6270 char *idx, *repl = NULL;
6279 /* Only the first '/' seen is our separator */
6286 if (!inquotes && c == '\\' && arg[1] == '\\')
6287 arg++; /* skip both \\, not just first one */
6294 #endif /* ENABLE_ASH_BASH_COMPAT */
6297 subevalvar(char *p, char *str, int strloc, int subtype,
6298 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6300 struct nodelist *saveargbackq = argbackq;
6303 char *rmesc, *rmescend;
6304 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
6305 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6306 int saveherefd = herefd;
6307 int amount, workloc, resetloc;
6309 char *(*scan)(char*, char*, char*, char*, int, int);
6312 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6314 STPUTC('\0', expdest);
6315 herefd = saveherefd;
6316 argbackq = saveargbackq;
6317 startp = (char *)stackblock() + startloc;
6321 setvar(str, startp, 0);
6322 amount = startp - expdest;
6323 STADJUST(amount, expdest);
6326 #if ENABLE_ASH_BASH_COMPAT
6328 loc = str = stackblock() + strloc;
6329 /* Read POS in ${var:POS:LEN} */
6330 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6331 len = str - startp - 1;
6333 /* *loc != '\0', guaranteed by parser */
6337 /* Adjust the length by the number of escapes */
6338 for (ptr = startp; ptr < (str - 1); ptr++) {
6339 if ((unsigned char)*ptr == CTLESC) {
6347 if (*loc++ == ':') {
6351 /* Skip POS in ${var:POS:LEN} */
6353 while (*loc && *loc != ':') {
6355 * bash complains on: var=qwe; echo ${var:1a:123}
6357 ash_msg_and_raise_error(msg_illnum, str);
6361 if (*loc++ == ':') {
6365 if (pos >= orig_len) {
6369 if (len > (orig_len - pos))
6370 len = orig_len - pos;
6372 for (str = startp; pos; str++, pos--) {
6373 if (quotes && (unsigned char)*str == CTLESC)
6376 for (loc = startp; len; len--) {
6377 if (quotes && (unsigned char)*str == CTLESC)
6382 amount = loc - expdest;
6383 STADJUST(amount, expdest);
6388 varunset(p, str, startp, varflags);
6391 resetloc = expdest - (char *)stackblock();
6393 /* We'll comeback here if we grow the stack while handling
6394 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6395 * stack will need rebasing, and we'll need to remove our work
6398 IF_ASH_BASH_COMPAT(restart:)
6400 amount = expdest - ((char *)stackblock() + resetloc);
6401 STADJUST(-amount, expdest);
6402 startp = (char *)stackblock() + startloc;
6405 rmescend = (char *)stackblock() + strloc;
6407 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6408 if (rmesc != startp) {
6410 startp = (char *)stackblock() + startloc;
6414 str = (char *)stackblock() + strloc;
6415 preglob(str, varflags & VSQUOTE, 0);
6416 workloc = expdest - (char *)stackblock();
6418 #if ENABLE_ASH_BASH_COMPAT
6419 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6423 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6428 /* If there's no pattern to match, return the expansion unmolested */
6437 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6439 /* No match, advance */
6440 char *restart_detect = stackblock();
6442 STPUTC(*idx, expdest);
6443 if (quotes && (unsigned char)*idx == CTLESC) {
6446 STPUTC(*idx, expdest);
6448 if (stackblock() != restart_detect)
6453 /* continue; - prone to quadratic behavior, smarter code: */
6456 if (str[0] == '*') {
6457 /* Pattern is "*foo". If "*foo" does not match "long_string",
6458 * it would never match "ong_string" etc, no point in trying.
6465 if (subtype == VSREPLACEALL) {
6467 if (quotes && (unsigned char)*idx == CTLESC)
6476 for (loc = (char*)repl; *loc; loc++) {
6477 char *restart_detect = stackblock();
6478 if (quotes && *loc == '\\') {
6479 STPUTC(CTLESC, expdest);
6482 STPUTC(*loc, expdest);
6483 if (stackblock() != restart_detect)
6488 if (subtype == VSREPLACE) {
6490 char *restart_detect = stackblock();
6491 if (quotes && *idx == '\\') {
6492 STPUTC(CTLESC, expdest);
6495 STPUTC(*idx, expdest);
6496 if (stackblock() != restart_detect)
6505 /* We've put the replaced text into a buffer at workloc, now
6506 * move it to the right place and adjust the stack.
6508 STPUTC('\0', expdest);
6509 startp = (char *)stackblock() + startloc;
6510 memmove(startp, (char *)stackblock() + workloc, len + 1);
6511 amount = expdest - (startp + len);
6512 STADJUST(-amount, expdest);
6515 #endif /* ENABLE_ASH_BASH_COMPAT */
6517 subtype -= VSTRIMRIGHT;
6519 if (subtype < 0 || subtype > 7)
6522 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6523 zero = subtype >> 1;
6524 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6525 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6527 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6530 memmove(startp, loc, str - loc);
6531 loc = startp + (str - loc) - 1;
6534 amount = loc - expdest;
6535 STADJUST(amount, expdest);
6541 * Add the value of a specialized variable to the stack string.
6542 * name parameter (examples):
6543 * ash -c 'echo $1' name:'1='
6544 * ash -c 'echo $qwe' name:'qwe='
6545 * ash -c 'echo $$' name:'$='
6546 * ash -c 'echo ${$}' name:'$='
6547 * ash -c 'echo ${$##q}' name:'$=q'
6548 * ash -c 'echo ${#$}' name:'$='
6549 * note: examples with bad shell syntax:
6550 * ash -c 'echo ${#$1}' name:'$=1'
6551 * ash -c 'echo ${#1#}' name:'1=#'
6553 static NOINLINE ssize_t
6554 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6561 int subtype = varflags & VSTYPE;
6562 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6563 int quoted = varflags & VSQUOTE;
6564 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6574 num = shellparam.nparam;
6582 goto check_1char_name;
6584 expdest = makestrspace(NOPTS, expdest);
6585 for (i = NOPTS - 1; i >= 0; i--) {
6587 USTPUTC(optletters(i), expdest);
6593 /* handles cases similar to ${#$1} */
6594 if (name[2] != '\0')
6595 raise_error_syntax("bad substitution");
6602 if (quoted && (flags & EXP_FULL)) {
6603 /* note: this is not meant as PEOF value */
6604 sep = 1 << CHAR_BIT;
6609 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6610 i = SIT(sep, syntax);
6611 if (quotes && (i == CCTL || i == CBACK))
6617 while ((p = *ap++) != NULL) {
6620 partlen = strlen(p);
6623 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6624 memtodest(p, partlen, syntax, quotes);
6630 if (subtype == VSPLUS || subtype == VSLENGTH) {
6636 /* note: may put NUL despite sep != 0
6637 * (see sep = 1 << CHAR_BIT above) */
6643 } /* case '@' and '*' */
6654 num = atoi(name); /* number(name) fails on ${N#str} etc */
6655 if (num < 0 || num > shellparam.nparam)
6657 p = num ? shellparam.p[num - 1] : arg0;
6660 /* NB: name has form "VAR=..." */
6662 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6663 * which should be considered before we check variables. */
6665 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6669 str = var_str_list->text;
6670 eq = strchr(str, '=');
6671 if (!eq) /* stop at first non-assignment */
6674 if (name_len == (unsigned)(eq - str)
6675 && strncmp(str, name, name_len) == 0
6678 /* goto value; - WRONG! */
6679 /* think "A=1 A=2 B=$A" */
6681 var_str_list = var_str_list->next;
6682 } while (var_str_list);
6686 p = lookupvar(name);
6692 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6693 memtodest(p, len, syntax, quotes);
6697 if (subtype == VSPLUS || subtype == VSLENGTH)
6698 STADJUST(-len, expdest);
6703 * Expand a variable, and return a pointer to the next character in the
6707 evalvar(char *p, int flags, struct strlist *var_str_list)
6718 varflags = (unsigned char) *p++;
6719 subtype = varflags & VSTYPE;
6720 quoted = varflags & VSQUOTE;
6722 easy = (!quoted || (*var == '@' && shellparam.nparam));
6723 startloc = expdest - (char *)stackblock();
6724 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6727 varlen = varvalue(var, varflags, flags, var_str_list);
6728 if (varflags & VSNUL)
6731 if (subtype == VSPLUS) {
6732 varlen = -1 - varlen;
6736 if (subtype == VSMINUS) {
6740 p, flags | EXP_TILDE |
6741 (quoted ? EXP_QWORD : EXP_WORD),
6751 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6753 if (subevalvar(p, var, /* strloc: */ 0,
6754 subtype, startloc, varflags,
6760 * Remove any recorded regions beyond
6763 removerecordregions(startloc);
6773 if (varlen < 0 && uflag)
6774 varunset(p, var, 0, 0);
6776 if (subtype == VSLENGTH) {
6777 cvtnum(varlen > 0 ? varlen : 0);
6781 if (subtype == VSNORMAL) {
6792 case VSTRIMRIGHTMAX:
6793 #if ENABLE_ASH_BASH_COMPAT
6806 * Terminate the string and start recording the pattern
6809 STPUTC('\0', expdest);
6810 patloc = expdest - (char *)stackblock();
6811 if (NULL == subevalvar(p, /* str: */ NULL, patloc, subtype,
6813 //TODO: | EXP_REDIR too? All other such places do it too
6814 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6817 int amount = expdest - (
6818 (char *)stackblock() + patloc - 1
6820 STADJUST(-amount, expdest);
6822 /* Remove any recorded regions beyond start of variable */
6823 removerecordregions(startloc);
6825 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6829 if (subtype != VSNORMAL) { /* skip to end of alternative */
6832 unsigned char c = *p++;
6835 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6837 argbackq = argbackq->next;
6838 } else if (c == CTLVAR) {
6839 if ((*p++ & VSTYPE) != VSNORMAL)
6841 } else if (c == CTLENDVAR) {
6851 * Break the argument string into pieces based upon IFS and add the
6852 * strings to the argument list. The regions of the string to be
6853 * searched for IFS characters have been stored by recordregion.
6856 ifsbreakup(char *string, struct arglist *arglist)
6858 struct ifsregion *ifsp;
6863 const char *ifs, *realifs;
6868 if (ifslastp != NULL) {
6871 realifs = ifsset() ? ifsval() : defifs;
6874 p = string + ifsp->begoff;
6875 nulonly = ifsp->nulonly;
6876 ifs = nulonly ? nullstr : realifs;
6878 while (p < string + ifsp->endoff) {
6880 if ((unsigned char)*p == CTLESC)
6882 if (!strchr(ifs, *p)) {
6887 ifsspc = (strchr(defifs, *p) != NULL);
6888 /* Ignore IFS whitespace at start */
6889 if (q == start && ifsspc) {
6895 sp = stzalloc(sizeof(*sp));
6897 *arglist->lastp = sp;
6898 arglist->lastp = &sp->next;
6902 if (p >= string + ifsp->endoff) {
6906 if ((unsigned char)*p == CTLESC)
6908 if (strchr(ifs, *p) == NULL) {
6912 if (strchr(defifs, *p) == NULL) {
6927 } while (ifsp != NULL);
6936 sp = stzalloc(sizeof(*sp));
6938 *arglist->lastp = sp;
6939 arglist->lastp = &sp->next;
6945 struct ifsregion *p;
6950 struct ifsregion *ifsp;
6956 ifsfirst.next = NULL;
6961 * Add a file name to the list.
6964 addfname(const char *name)
6968 sp = stzalloc(sizeof(*sp));
6969 sp->text = ststrdup(name);
6971 exparg.lastp = &sp->next;
6975 * Do metacharacter (i.e. *, ?, [...]) expansion.
6978 expmeta(char *expdir, char *enddir, char *name)
6993 for (p = name; *p; p++) {
6994 if (*p == '*' || *p == '?')
6996 else if (*p == '[') {
7003 if (*q == '/' || *q == '\0')
7010 } else if (*p == '\\')
7012 else if (*p == '/') {
7019 if (metaflag == 0) { /* we've reached the end of the file name */
7020 if (enddir != expdir)
7028 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7039 } while (p < start);
7041 if (enddir == expdir) {
7043 } else if (enddir == expdir + 1 && *expdir == '/') {
7052 if (enddir != expdir)
7054 if (*endname == 0) {
7066 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7067 if (dp->d_name[0] == '.' && !matchdot)
7069 if (pmatch(start, dp->d_name)) {
7071 strcpy(enddir, dp->d_name);
7074 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7077 expmeta(expdir, p, endname);
7086 static struct strlist *
7087 msort(struct strlist *list, int len)
7089 struct strlist *p, *q = NULL;
7090 struct strlist **lpp;
7098 for (n = half; --n >= 0;) {
7102 q->next = NULL; /* terminate first half of list */
7103 q = msort(list, half); /* sort first half of list */
7104 p = msort(p, len - half); /* sort second half */
7107 #if ENABLE_LOCALE_SUPPORT
7108 if (strcoll(p->text, q->text) < 0)
7110 if (strcmp(p->text, q->text) < 0)
7134 * Sort the results of file name expansion. It calculates the number of
7135 * strings to sort and then calls msort (short for merge sort) to do the
7138 static struct strlist *
7139 expsort(struct strlist *str)
7145 for (sp = str; sp; sp = sp->next)
7147 return msort(str, len);
7151 expandmeta(struct strlist *str /*, int flag*/)
7153 static const char metachars[] ALIGN1 = {
7156 /* TODO - EXP_REDIR */
7160 struct strlist **savelastp;
7166 if (!strpbrk(str->text, metachars))
7168 savelastp = exparg.lastp;
7171 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7173 int i = strlen(str->text);
7174 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7176 expmeta(expdir, expdir, p);
7181 if (exparg.lastp == savelastp) {
7186 *exparg.lastp = str;
7187 rmescapes(str->text, 0);
7188 exparg.lastp = &str->next;
7190 *exparg.lastp = NULL;
7191 *savelastp = sp = expsort(*savelastp);
7192 while (sp->next != NULL)
7194 exparg.lastp = &sp->next;
7201 * Perform variable substitution and command substitution on an argument,
7202 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7203 * perform splitting and file name expansion. When arglist is NULL, perform
7204 * here document expansion.
7207 expandarg(union node *arg, struct arglist *arglist, int flag)
7212 argbackq = arg->narg.backquote;
7213 STARTSTACKSTR(expdest);
7214 ifsfirst.next = NULL;
7216 argstr(arg->narg.text, flag,
7217 /* var_str_list: */ arglist ? arglist->list : NULL);
7218 p = _STPUTC('\0', expdest);
7220 if (arglist == NULL) {
7221 return; /* here document expanded */
7223 p = grabstackstr(p);
7224 exparg.lastp = &exparg.list;
7228 if (flag & EXP_FULL) {
7229 ifsbreakup(p, &exparg);
7230 *exparg.lastp = NULL;
7231 exparg.lastp = &exparg.list;
7232 expandmeta(exparg.list /*, flag*/);
7234 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7236 sp = stzalloc(sizeof(*sp));
7239 exparg.lastp = &sp->next;
7243 *exparg.lastp = NULL;
7245 *arglist->lastp = exparg.list;
7246 arglist->lastp = exparg.lastp;
7251 * Expand shell variables and backquotes inside a here document.
7254 expandhere(union node *arg, int fd)
7257 expandarg(arg, (struct arglist *)NULL, 0);
7258 full_write(fd, stackblock(), expdest - (char *)stackblock());
7262 * Returns true if the pattern matches the string.
7265 patmatch(char *pattern, const char *string)
7267 return pmatch(preglob(pattern, 0, 0), string);
7271 * See if a pattern matches in a case statement.
7274 casematch(union node *pattern, char *val)
7276 struct stackmark smark;
7279 setstackmark(&smark);
7280 argbackq = pattern->narg.backquote;
7281 STARTSTACKSTR(expdest);
7283 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7284 /* var_str_list: */ NULL);
7285 STACKSTRNUL(expdest);
7286 result = patmatch(stackblock(), val);
7287 popstackmark(&smark);
7292 /* ============ find_command */
7296 int (*builtin)(int, char **) FAST_FUNC;
7297 /* unsigned flags; */
7299 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7300 /* "regular" builtins always take precedence over commands,
7301 * regardless of PATH=....%builtin... position */
7302 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7303 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7306 smallint cmdtype; /* CMDxxx */
7309 /* index >= 0 for commands without path (slashes) */
7310 /* (TODO: what exactly does the value mean? PATH position?) */
7311 /* index == -1 for commands with slashes */
7312 /* index == (-2 - applet_no) for NOFORK applets */
7313 const struct builtincmd *cmd;
7314 struct funcnode *func;
7317 /* values of cmdtype */
7318 #define CMDUNKNOWN -1 /* no entry in table for command */
7319 #define CMDNORMAL 0 /* command is an executable program */
7320 #define CMDFUNCTION 1 /* command is a shell function */
7321 #define CMDBUILTIN 2 /* command is a shell builtin */
7323 /* action to find_command() */
7324 #define DO_ERR 0x01 /* prints errors */
7325 #define DO_ABS 0x02 /* checks absolute paths */
7326 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7327 #define DO_ALTPATH 0x08 /* using alternate path */
7328 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7330 static void find_command(char *, struct cmdentry *, int, const char *);
7333 /* ============ Hashing commands */
7336 * When commands are first encountered, they are entered in a hash table.
7337 * This ensures that a full path search will not have to be done for them
7338 * on each invocation.
7340 * We should investigate converting to a linear search, even though that
7341 * would make the command name "hash" a misnomer.
7345 struct tblentry *next; /* next entry in hash chain */
7346 union param param; /* definition of builtin function */
7347 smallint cmdtype; /* CMDxxx */
7348 char rehash; /* if set, cd done since entry created */
7349 char cmdname[1]; /* name of command */
7352 static struct tblentry **cmdtable;
7353 #define INIT_G_cmdtable() do { \
7354 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7357 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7361 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7365 #if ENABLE_FEATURE_SH_STANDALONE
7366 if (applet_no >= 0) {
7367 if (APPLET_IS_NOEXEC(applet_no)) {
7371 run_applet_no_and_exit(applet_no, argv);
7373 /* re-exec ourselves with the new arguments */
7374 execve(bb_busybox_exec_path, argv, envp);
7375 /* If they called chroot or otherwise made the binary no longer
7376 * executable, fall through */
7383 execve(cmd, argv, envp);
7384 } while (errno == EINTR);
7386 execve(cmd, argv, envp);
7392 if (errno == ENOEXEC) {
7396 for (ap = argv; *ap; ap++)
7398 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7400 ap[0] = cmd = (char *)DEFAULT_SHELL;
7403 while ((*ap++ = *argv++) != NULL)
7412 * Exec a program. Never returns. If you change this routine, you may
7413 * have to change the find_command routine as well.
7415 static void shellexec(char **, const char *, int) NORETURN;
7417 shellexec(char **argv, const char *path, int idx)
7423 #if ENABLE_FEATURE_SH_STANDALONE
7427 clearredir(/*drop:*/ 1);
7428 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7429 if (strchr(argv[0], '/') != NULL
7430 #if ENABLE_FEATURE_SH_STANDALONE
7431 || (applet_no = find_applet_by_name(argv[0])) >= 0
7434 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7438 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7439 if (--idx < 0 && pathopt == NULL) {
7440 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7441 if (errno != ENOENT && errno != ENOTDIR)
7448 /* Map to POSIX errors */
7460 exitstatus = exerrno;
7461 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7462 argv[0], e, suppress_int));
7463 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7468 printentry(struct tblentry *cmdp)
7474 idx = cmdp->param.index;
7477 name = path_advance(&path, cmdp->cmdname);
7479 } while (--idx >= 0);
7480 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7484 * Clear out command entries. The argument specifies the first entry in
7485 * PATH which has changed.
7488 clearcmdentry(int firstchange)
7490 struct tblentry **tblp;
7491 struct tblentry **pp;
7492 struct tblentry *cmdp;
7495 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7497 while ((cmdp = *pp) != NULL) {
7498 if ((cmdp->cmdtype == CMDNORMAL &&
7499 cmdp->param.index >= firstchange)
7500 || (cmdp->cmdtype == CMDBUILTIN &&
7501 builtinloc >= firstchange)
7514 * Locate a command in the command hash table. If "add" is nonzero,
7515 * add the command to the table if it is not already present. The
7516 * variable "lastcmdentry" is set to point to the address of the link
7517 * pointing to the entry, so that delete_cmd_entry can delete the
7520 * Interrupts must be off if called with add != 0.
7522 static struct tblentry **lastcmdentry;
7524 static struct tblentry *
7525 cmdlookup(const char *name, int add)
7527 unsigned int hashval;
7529 struct tblentry *cmdp;
7530 struct tblentry **pp;
7533 hashval = (unsigned char)*p << 4;
7535 hashval += (unsigned char)*p++;
7537 pp = &cmdtable[hashval % CMDTABLESIZE];
7538 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7539 if (strcmp(cmdp->cmdname, name) == 0)
7543 if (add && cmdp == NULL) {
7544 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7546 /* + 1 - already done because
7547 * tblentry::cmdname is char[1] */);
7548 /*cmdp->next = NULL; - ckzalloc did it */
7549 cmdp->cmdtype = CMDUNKNOWN;
7550 strcpy(cmdp->cmdname, name);
7557 * Delete the command entry returned on the last lookup.
7560 delete_cmd_entry(void)
7562 struct tblentry *cmdp;
7565 cmdp = *lastcmdentry;
7566 *lastcmdentry = cmdp->next;
7567 if (cmdp->cmdtype == CMDFUNCTION)
7568 freefunc(cmdp->param.func);
7574 * Add a new command entry, replacing any existing command entry for
7575 * the same name - except special builtins.
7578 addcmdentry(char *name, struct cmdentry *entry)
7580 struct tblentry *cmdp;
7582 cmdp = cmdlookup(name, 1);
7583 if (cmdp->cmdtype == CMDFUNCTION) {
7584 freefunc(cmdp->param.func);
7586 cmdp->cmdtype = entry->cmdtype;
7587 cmdp->param = entry->u;
7591 static int FAST_FUNC
7592 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7594 struct tblentry **pp;
7595 struct tblentry *cmdp;
7597 struct cmdentry entry;
7600 if (nextopt("r") != '\0') {
7605 if (*argptr == NULL) {
7606 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7607 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7608 if (cmdp->cmdtype == CMDNORMAL)
7616 while ((name = *argptr) != NULL) {
7617 cmdp = cmdlookup(name, 0);
7619 && (cmdp->cmdtype == CMDNORMAL
7620 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7624 find_command(name, &entry, DO_ERR, pathval());
7625 if (entry.cmdtype == CMDUNKNOWN)
7633 * Called when a cd is done. Marks all commands so the next time they
7634 * are executed they will be rehashed.
7639 struct tblentry **pp;
7640 struct tblentry *cmdp;
7642 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7643 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7644 if (cmdp->cmdtype == CMDNORMAL
7645 || (cmdp->cmdtype == CMDBUILTIN
7646 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7656 * Fix command hash table when PATH changed.
7657 * Called before PATH is changed. The argument is the new value of PATH;
7658 * pathval() still returns the old value at this point.
7659 * Called with interrupts off.
7661 static void FAST_FUNC
7662 changepath(const char *new)
7670 firstchange = 9999; /* assume no change */
7676 if ((*old == '\0' && *new == ':')
7677 || (*old == ':' && *new == '\0')
7681 old = new; /* ignore subsequent differences */
7685 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7692 if (builtinloc < 0 && idx_bltin >= 0)
7693 builtinloc = idx_bltin; /* zap builtins */
7694 if (builtinloc >= 0 && idx_bltin < 0)
7696 clearcmdentry(firstchange);
7697 builtinloc = idx_bltin;
7712 #define TENDBQUOTE 12
7729 typedef smallint token_id_t;
7731 /* first char is indicating which tokens mark the end of a list */
7732 static const char *const tokname_array[] = {
7746 #define KWDOFFSET 13
7747 /* the following are keywords */
7766 /* Wrapper around strcmp for qsort/bsearch/... */
7768 pstrcmp(const void *a, const void *b)
7770 return strcmp((char*) a, (*(char**) b) + 1);
7773 static const char *const *
7774 findkwd(const char *s)
7776 return bsearch(s, tokname_array + KWDOFFSET,
7777 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7778 sizeof(tokname_array[0]), pstrcmp);
7782 * Locate and print what a word is...
7785 describe_command(char *command, int describe_command_verbose)
7787 struct cmdentry entry;
7788 struct tblentry *cmdp;
7789 #if ENABLE_ASH_ALIAS
7790 const struct alias *ap;
7792 const char *path = pathval();
7794 if (describe_command_verbose) {
7798 /* First look at the keywords */
7799 if (findkwd(command)) {
7800 out1str(describe_command_verbose ? " is a shell keyword" : command);
7804 #if ENABLE_ASH_ALIAS
7805 /* Then look at the aliases */
7806 ap = lookupalias(command, 0);
7808 if (!describe_command_verbose) {
7813 out1fmt(" is an alias for %s", ap->val);
7817 /* Then check if it is a tracked alias */
7818 cmdp = cmdlookup(command, 0);
7820 entry.cmdtype = cmdp->cmdtype;
7821 entry.u = cmdp->param;
7823 /* Finally use brute force */
7824 find_command(command, &entry, DO_ABS, path);
7827 switch (entry.cmdtype) {
7829 int j = entry.u.index;
7835 p = path_advance(&path, command);
7839 if (describe_command_verbose) {
7841 (cmdp ? " a tracked alias for" : nullstr), p
7850 if (describe_command_verbose) {
7851 out1str(" is a shell function");
7858 if (describe_command_verbose) {
7859 out1fmt(" is a %sshell builtin",
7860 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7861 "special " : nullstr
7869 if (describe_command_verbose) {
7870 out1str(": not found\n");
7879 static int FAST_FUNC
7880 typecmd(int argc UNUSED_PARAM, char **argv)
7886 /* type -p ... ? (we don't bother checking for 'p') */
7887 if (argv[1] && argv[1][0] == '-') {
7892 err |= describe_command(argv[i++], verbose);
7897 #if ENABLE_ASH_CMDCMD
7898 static int FAST_FUNC
7899 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7907 while ((c = nextopt("pvV")) != '\0')
7909 verify |= VERIFY_VERBOSE;
7911 verify |= VERIFY_BRIEF;
7916 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7917 if (verify && (*argptr != NULL)) {
7918 return describe_command(*argptr, verify - VERIFY_BRIEF);
7926 /* ============ eval.c */
7928 static int funcblocksize; /* size of structures in function */
7929 static int funcstringsize; /* size of strings in node */
7930 static void *funcblock; /* block to allocate function from */
7931 static char *funcstring; /* block to allocate strings from */
7933 /* flags in argument to evaltree */
7934 #define EV_EXIT 01 /* exit after evaluating tree */
7935 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7936 #define EV_BACKCMD 04 /* command executing within back quotes */
7938 static const uint8_t nodesize[N_NUMBER] = {
7939 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7940 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7941 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7942 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7943 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7944 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7945 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7946 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7947 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7948 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7949 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7950 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7951 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7952 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7953 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7954 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7955 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7956 #if ENABLE_ASH_BASH_COMPAT
7957 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7959 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7960 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7961 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7962 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7963 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7964 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7965 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7966 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7967 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7970 static void calcsize(union node *n);
7973 sizenodelist(struct nodelist *lp)
7976 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7983 calcsize(union node *n)
7987 funcblocksize += nodesize[n->type];
7990 calcsize(n->ncmd.redirect);
7991 calcsize(n->ncmd.args);
7992 calcsize(n->ncmd.assign);
7995 sizenodelist(n->npipe.cmdlist);
8000 calcsize(n->nredir.redirect);
8001 calcsize(n->nredir.n);
8008 calcsize(n->nbinary.ch2);
8009 calcsize(n->nbinary.ch1);
8012 calcsize(n->nif.elsepart);
8013 calcsize(n->nif.ifpart);
8014 calcsize(n->nif.test);
8017 funcstringsize += strlen(n->nfor.var) + 1;
8018 calcsize(n->nfor.body);
8019 calcsize(n->nfor.args);
8022 calcsize(n->ncase.cases);
8023 calcsize(n->ncase.expr);
8026 calcsize(n->nclist.body);
8027 calcsize(n->nclist.pattern);
8028 calcsize(n->nclist.next);
8032 sizenodelist(n->narg.backquote);
8033 funcstringsize += strlen(n->narg.text) + 1;
8034 calcsize(n->narg.next);
8037 #if ENABLE_ASH_BASH_COMPAT
8044 calcsize(n->nfile.fname);
8045 calcsize(n->nfile.next);
8049 calcsize(n->ndup.vname);
8050 calcsize(n->ndup.next);
8054 calcsize(n->nhere.doc);
8055 calcsize(n->nhere.next);
8058 calcsize(n->nnot.com);
8064 nodeckstrdup(char *s)
8066 char *rtn = funcstring;
8068 strcpy(funcstring, s);
8069 funcstring += strlen(s) + 1;
8073 static union node *copynode(union node *);
8075 static struct nodelist *
8076 copynodelist(struct nodelist *lp)
8078 struct nodelist *start;
8079 struct nodelist **lpp;
8084 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8085 (*lpp)->n = copynode(lp->n);
8087 lpp = &(*lpp)->next;
8094 copynode(union node *n)
8101 funcblock = (char *) funcblock + nodesize[n->type];
8105 new->ncmd.redirect = copynode(n->ncmd.redirect);
8106 new->ncmd.args = copynode(n->ncmd.args);
8107 new->ncmd.assign = copynode(n->ncmd.assign);
8110 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8111 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8116 new->nredir.redirect = copynode(n->nredir.redirect);
8117 new->nredir.n = copynode(n->nredir.n);
8124 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8125 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8128 new->nif.elsepart = copynode(n->nif.elsepart);
8129 new->nif.ifpart = copynode(n->nif.ifpart);
8130 new->nif.test = copynode(n->nif.test);
8133 new->nfor.var = nodeckstrdup(n->nfor.var);
8134 new->nfor.body = copynode(n->nfor.body);
8135 new->nfor.args = copynode(n->nfor.args);
8138 new->ncase.cases = copynode(n->ncase.cases);
8139 new->ncase.expr = copynode(n->ncase.expr);
8142 new->nclist.body = copynode(n->nclist.body);
8143 new->nclist.pattern = copynode(n->nclist.pattern);
8144 new->nclist.next = copynode(n->nclist.next);
8148 new->narg.backquote = copynodelist(n->narg.backquote);
8149 new->narg.text = nodeckstrdup(n->narg.text);
8150 new->narg.next = copynode(n->narg.next);
8153 #if ENABLE_ASH_BASH_COMPAT
8160 new->nfile.fname = copynode(n->nfile.fname);
8161 new->nfile.fd = n->nfile.fd;
8162 new->nfile.next = copynode(n->nfile.next);
8166 new->ndup.vname = copynode(n->ndup.vname);
8167 new->ndup.dupfd = n->ndup.dupfd;
8168 new->ndup.fd = n->ndup.fd;
8169 new->ndup.next = copynode(n->ndup.next);
8173 new->nhere.doc = copynode(n->nhere.doc);
8174 new->nhere.fd = n->nhere.fd;
8175 new->nhere.next = copynode(n->nhere.next);
8178 new->nnot.com = copynode(n->nnot.com);
8181 new->type = n->type;
8186 * Make a copy of a parse tree.
8188 static struct funcnode *
8189 copyfunc(union node *n)
8194 funcblocksize = offsetof(struct funcnode, n);
8197 blocksize = funcblocksize;
8198 f = ckmalloc(blocksize + funcstringsize);
8199 funcblock = (char *) f + offsetof(struct funcnode, n);
8200 funcstring = (char *) f + blocksize;
8207 * Define a shell function.
8210 defun(char *name, union node *func)
8212 struct cmdentry entry;
8215 entry.cmdtype = CMDFUNCTION;
8216 entry.u.func = copyfunc(func);
8217 addcmdentry(name, &entry);
8221 /* Reasons for skipping commands (see comment on breakcmd routine) */
8222 #define SKIPBREAK (1 << 0)
8223 #define SKIPCONT (1 << 1)
8224 #define SKIPFUNC (1 << 2)
8225 #define SKIPFILE (1 << 3)
8226 #define SKIPEVAL (1 << 4)
8227 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8228 static int skipcount; /* number of levels to skip */
8229 static int funcnest; /* depth of function calls */
8230 static int loopnest; /* current loop nesting level */
8232 /* Forward decl way out to parsing code - dotrap needs it */
8233 static int evalstring(char *s, int mask);
8235 /* Called to execute a trap.
8236 * Single callsite - at the end of evaltree().
8237 * If we return non-zero, exaltree raises EXEXIT exception.
8239 * Perhaps we should avoid entering new trap handlers
8240 * while we are executing a trap handler. [is it a TODO?]
8249 savestatus = exitstatus;
8253 TRACE(("dotrap entered\n"));
8254 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8261 /* non-trapped SIGINT is handled separately by raise_interrupt,
8262 * don't upset it by resetting gotsig[SIGINT-1] */
8263 if (sig == SIGINT && !t)
8266 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8270 want_exexit = evalstring(t, SKIPEVAL);
8271 exitstatus = savestatus;
8273 TRACE(("dotrap returns %d\n", want_exexit));
8278 TRACE(("dotrap returns 0\n"));
8282 /* forward declarations - evaluation is fairly recursive business... */
8283 static void evalloop(union node *, int);
8284 static void evalfor(union node *, int);
8285 static void evalcase(union node *, int);
8286 static void evalsubshell(union node *, int);
8287 static void expredir(union node *);
8288 static void evalpipe(union node *, int);
8289 static void evalcommand(union node *, int);
8290 static int evalbltin(const struct builtincmd *, int, char **);
8291 static void prehash(union node *);
8294 * Evaluate a parse tree. The value is left in the global variable
8298 evaltree(union node *n, int flags)
8300 struct jmploc *volatile savehandler = exception_handler;
8301 struct jmploc jmploc;
8303 void (*evalfn)(union node *, int);
8307 SAVE_INT(int_level);
8310 TRACE(("evaltree(NULL) called\n"));
8313 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8315 exception_handler = &jmploc;
8317 int err = setjmp(jmploc.loc);
8319 /* if it was a signal, check for trap handlers */
8320 if (exception_type == EXSIG) {
8321 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8322 exception_type, err));
8325 /* continue on the way out */
8326 TRACE(("exception %d in evaltree, propagating err=%d\n",
8327 exception_type, err));
8328 exception_handler = savehandler;
8329 longjmp(exception_handler->loc, err);
8336 out1fmt("Node type = %d\n", n->type);
8341 evaltree(n->nnot.com, EV_TESTED);
8342 status = !exitstatus;
8345 expredir(n->nredir.redirect);
8346 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8348 evaltree(n->nredir.n, flags & EV_TESTED);
8349 status = exitstatus;
8351 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8354 evalfn = evalcommand;
8356 if (eflag && !(flags & EV_TESTED))
8368 evalfn = evalsubshell;
8381 #error NAND + 1 != NOR
8383 #if NOR + 1 != NSEMI
8384 #error NOR + 1 != NSEMI
8386 unsigned is_or = n->type - NAND;
8389 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8391 if (!exitstatus == is_or)
8404 evaltree(n->nif.test, EV_TESTED);
8407 if (exitstatus == 0) {
8411 if (n->nif.elsepart) {
8412 n = n->nif.elsepart;
8417 defun(n->narg.text, n->narg.next);
8421 exitstatus = status;
8426 exception_handler = savehandler;
8428 if (checkexit & exitstatus)
8429 evalskip |= SKIPEVAL;
8430 else if (pending_sig && dotrap())
8433 if (flags & EV_EXIT) {
8435 raise_exception(EXEXIT);
8438 RESTORE_INT(int_level);
8439 TRACE(("leaving evaltree (no interrupts)\n"));
8442 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8445 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8448 evalloop(union node *n, int flags)
8458 evaltree(n->nbinary.ch1, EV_TESTED);
8461 if (evalskip == SKIPCONT && --skipcount <= 0) {
8465 if (evalskip == SKIPBREAK && --skipcount <= 0)
8470 if (n->type != NWHILE)
8474 evaltree(n->nbinary.ch2, flags);
8475 status = exitstatus;
8480 exitstatus = status;
8484 evalfor(union node *n, int flags)
8486 struct arglist arglist;
8489 struct stackmark smark;
8491 setstackmark(&smark);
8492 arglist.list = NULL;
8493 arglist.lastp = &arglist.list;
8494 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8495 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8500 *arglist.lastp = NULL;
8505 for (sp = arglist.list; sp; sp = sp->next) {
8506 setvar(n->nfor.var, sp->text, 0);
8507 evaltree(n->nfor.body, flags);
8509 if (evalskip == SKIPCONT && --skipcount <= 0) {
8513 if (evalskip == SKIPBREAK && --skipcount <= 0)
8520 popstackmark(&smark);
8524 evalcase(union node *n, int flags)
8528 struct arglist arglist;
8529 struct stackmark smark;
8531 setstackmark(&smark);
8532 arglist.list = NULL;
8533 arglist.lastp = &arglist.list;
8534 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8536 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8537 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8538 if (casematch(patp, arglist.list->text)) {
8539 if (evalskip == 0) {
8540 evaltree(cp->nclist.body, flags);
8547 popstackmark(&smark);
8551 * Kick off a subshell to evaluate a tree.
8554 evalsubshell(union node *n, int flags)
8557 int backgnd = (n->type == NBACKGND);
8560 expredir(n->nredir.redirect);
8561 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8564 jp = makejob(/*n,*/ 1);
8565 if (forkshell(jp, n, backgnd) == 0) {
8570 flags &= ~EV_TESTED;
8572 redirect(n->nredir.redirect, 0);
8573 evaltreenr(n->nredir.n, flags);
8578 status = waitforjob(jp);
8579 exitstatus = status;
8584 * Compute the names of the files in a redirection list.
8586 static void fixredir(union node *, const char *, int);
8588 expredir(union node *n)
8592 for (redir = n; redir; redir = redir->nfile.next) {
8596 fn.lastp = &fn.list;
8597 switch (redir->type) {
8601 #if ENABLE_ASH_BASH_COMPAT
8606 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8607 #if ENABLE_ASH_BASH_COMPAT
8610 redir->nfile.expfname = fn.list->text;
8613 case NTOFD: /* >& */
8614 if (redir->ndup.vname) {
8615 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8616 if (fn.list == NULL)
8617 ash_msg_and_raise_error("redir error");
8618 #if ENABLE_ASH_BASH_COMPAT
8619 //FIXME: we used expandarg with different args!
8620 if (!isdigit_str9(fn.list->text)) {
8621 /* >&file, not >&fd */
8622 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8623 ash_msg_and_raise_error("redir error");
8625 goto store_expfname;
8628 fixredir(redir, fn.list->text, 1);
8636 * Evaluate a pipeline. All the processes in the pipeline are children
8637 * of the process creating the pipeline. (This differs from some versions
8638 * of the shell, which make the last process in a pipeline the parent
8642 evalpipe(union node *n, int flags)
8645 struct nodelist *lp;
8650 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8652 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8656 jp = makejob(/*n,*/ pipelen);
8658 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8662 if (pipe(pip) < 0) {
8664 ash_msg_and_raise_error("pipe call failed");
8667 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8680 evaltreenr(lp->n, flags);
8686 /* Don't want to trigger debugging */
8690 if (n->npipe.pipe_backgnd == 0) {
8691 exitstatus = waitforjob(jp);
8692 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8698 * Controls whether the shell is interactive or not.
8701 setinteractive(int on)
8703 static smallint is_interactive;
8705 if (++on == is_interactive)
8707 is_interactive = on;
8711 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8712 if (is_interactive > 1) {
8713 /* Looks like they want an interactive shell */
8714 static smallint did_banner;
8717 /* note: ash and hush share this string */
8718 out1fmt("\n\n%s %s\n"
8719 "Enter 'help' for a list of built-in commands."
8722 "built-in shell (ash)"
8736 setinteractive(iflag);
8738 #if ENABLE_FEATURE_EDITING_VI
8740 line_input_state->flags |= VI_MODE;
8742 line_input_state->flags &= ~VI_MODE;
8744 viflag = 0; /* forcibly keep the option off */
8748 static struct localvar *localvars;
8751 * Called after a function returns.
8752 * Interrupts must be off.
8757 struct localvar *lvp;
8760 while ((lvp = localvars) != NULL) {
8761 localvars = lvp->next;
8763 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8764 if (vp == NULL) { /* $- saved */
8765 memcpy(optlist, lvp->text, sizeof(optlist));
8766 free((char*)lvp->text);
8768 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8769 unsetvar(vp->var_text);
8772 vp->var_func(var_end(lvp->text));
8773 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8774 free((char*)vp->var_text);
8775 vp->flags = lvp->flags;
8776 vp->var_text = lvp->text;
8783 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8785 volatile struct shparam saveparam;
8786 struct localvar *volatile savelocalvars;
8787 struct jmploc *volatile savehandler;
8788 struct jmploc jmploc;
8791 saveparam = shellparam;
8792 savelocalvars = localvars;
8793 e = setjmp(jmploc.loc);
8798 savehandler = exception_handler;
8799 exception_handler = &jmploc;
8801 shellparam.malloced = 0;
8805 shellparam.nparam = argc - 1;
8806 shellparam.p = argv + 1;
8807 #if ENABLE_ASH_GETOPTS
8808 shellparam.optind = 1;
8809 shellparam.optoff = -1;
8811 evaltree(&func->n, flags & EV_TESTED);
8817 localvars = savelocalvars;
8818 freeparam(&shellparam);
8819 shellparam = saveparam;
8820 exception_handler = savehandler;
8822 evalskip &= ~SKIPFUNC;
8826 #if ENABLE_ASH_CMDCMD
8828 parse_command_args(char **argv, const char **path)
8841 if (c == '-' && !*cp) {
8848 *path = bb_default_path;
8851 /* run 'typecmd' for other options */
8862 * Make a variable a local variable. When a variable is made local, it's
8863 * value and flags are saved in a localvar structure. The saved values
8864 * will be restored when the shell function returns. We handle the name
8865 * "-" as a special case.
8870 struct localvar *lvp;
8875 lvp = ckzalloc(sizeof(struct localvar));
8876 if (LONE_DASH(name)) {
8878 p = ckmalloc(sizeof(optlist));
8879 lvp->text = memcpy(p, optlist, sizeof(optlist));
8884 vpp = hashvar(name);
8885 vp = *findvar(vpp, name);
8886 eq = strchr(name, '=');
8889 setvareq(name, VSTRFIXED);
8891 setvar(name, NULL, VSTRFIXED);
8892 vp = *vpp; /* the new variable */
8893 lvp->flags = VUNSET;
8895 lvp->text = vp->var_text;
8896 lvp->flags = vp->flags;
8897 vp->flags |= VSTRFIXED|VTEXTFIXED;
8903 lvp->next = localvars;
8909 * The "local" command.
8911 static int FAST_FUNC
8912 localcmd(int argc UNUSED_PARAM, char **argv)
8917 while ((name = *argv++) != NULL) {
8923 static int FAST_FUNC
8924 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8929 static int FAST_FUNC
8930 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8935 static int FAST_FUNC
8936 execcmd(int argc UNUSED_PARAM, char **argv)
8939 iflag = 0; /* exit on error */
8942 shellexec(argv + 1, pathval(), 0);
8948 * The return command.
8950 static int FAST_FUNC
8951 returncmd(int argc UNUSED_PARAM, char **argv)
8954 * If called outside a function, do what ksh does;
8955 * skip the rest of the file.
8957 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8958 return argv[1] ? number(argv[1]) : exitstatus;
8961 /* Forward declarations for builtintab[] */
8962 static int breakcmd(int, char **) FAST_FUNC;
8963 static int dotcmd(int, char **) FAST_FUNC;
8964 static int evalcmd(int, char **) FAST_FUNC;
8965 static int exitcmd(int, char **) FAST_FUNC;
8966 static int exportcmd(int, char **) FAST_FUNC;
8967 #if ENABLE_ASH_GETOPTS
8968 static int getoptscmd(int, char **) FAST_FUNC;
8970 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8971 static int helpcmd(int, char **) FAST_FUNC;
8973 #if ENABLE_SH_MATH_SUPPORT
8974 static int letcmd(int, char **) FAST_FUNC;
8976 static int readcmd(int, char **) FAST_FUNC;
8977 static int setcmd(int, char **) FAST_FUNC;
8978 static int shiftcmd(int, char **) FAST_FUNC;
8979 static int timescmd(int, char **) FAST_FUNC;
8980 static int trapcmd(int, char **) FAST_FUNC;
8981 static int umaskcmd(int, char **) FAST_FUNC;
8982 static int unsetcmd(int, char **) FAST_FUNC;
8983 static int ulimitcmd(int, char **) FAST_FUNC;
8985 #define BUILTIN_NOSPEC "0"
8986 #define BUILTIN_SPECIAL "1"
8987 #define BUILTIN_REGULAR "2"
8988 #define BUILTIN_SPEC_REG "3"
8989 #define BUILTIN_ASSIGN "4"
8990 #define BUILTIN_SPEC_ASSG "5"
8991 #define BUILTIN_REG_ASSG "6"
8992 #define BUILTIN_SPEC_REG_ASSG "7"
8994 /* Stubs for calling non-FAST_FUNC's */
8995 #if ENABLE_ASH_BUILTIN_ECHO
8996 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8998 #if ENABLE_ASH_BUILTIN_PRINTF
8999 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9001 #if ENABLE_ASH_BUILTIN_TEST
9002 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9005 /* Keep these in proper order since it is searched via bsearch() */
9006 static const struct builtincmd builtintab[] = {
9007 { BUILTIN_SPEC_REG "." , dotcmd },
9008 { BUILTIN_SPEC_REG ":" , truecmd },
9009 #if ENABLE_ASH_BUILTIN_TEST
9010 { BUILTIN_REGULAR "[" , testcmd },
9011 #if ENABLE_ASH_BASH_COMPAT
9012 { BUILTIN_REGULAR "[[" , testcmd },
9015 #if ENABLE_ASH_ALIAS
9016 { BUILTIN_REG_ASSG "alias" , aliascmd },
9019 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9021 { BUILTIN_SPEC_REG "break" , breakcmd },
9022 { BUILTIN_REGULAR "cd" , cdcmd },
9023 { BUILTIN_NOSPEC "chdir" , cdcmd },
9024 #if ENABLE_ASH_CMDCMD
9025 { BUILTIN_REGULAR "command" , commandcmd },
9027 { BUILTIN_SPEC_REG "continue", breakcmd },
9028 #if ENABLE_ASH_BUILTIN_ECHO
9029 { BUILTIN_REGULAR "echo" , echocmd },
9031 { BUILTIN_SPEC_REG "eval" , evalcmd },
9032 { BUILTIN_SPEC_REG "exec" , execcmd },
9033 { BUILTIN_SPEC_REG "exit" , exitcmd },
9034 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9035 { BUILTIN_REGULAR "false" , falsecmd },
9037 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9039 #if ENABLE_ASH_GETOPTS
9040 { BUILTIN_REGULAR "getopts" , getoptscmd },
9042 { BUILTIN_NOSPEC "hash" , hashcmd },
9043 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9044 { BUILTIN_NOSPEC "help" , helpcmd },
9047 { BUILTIN_REGULAR "jobs" , jobscmd },
9048 { BUILTIN_REGULAR "kill" , killcmd },
9050 #if ENABLE_SH_MATH_SUPPORT
9051 { BUILTIN_NOSPEC "let" , letcmd },
9053 { BUILTIN_ASSIGN "local" , localcmd },
9054 #if ENABLE_ASH_BUILTIN_PRINTF
9055 { BUILTIN_REGULAR "printf" , printfcmd },
9057 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9058 { BUILTIN_REGULAR "read" , readcmd },
9059 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9060 { BUILTIN_SPEC_REG "return" , returncmd },
9061 { BUILTIN_SPEC_REG "set" , setcmd },
9062 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9063 #if ENABLE_ASH_BASH_COMPAT
9064 { BUILTIN_SPEC_REG "source" , dotcmd },
9066 #if ENABLE_ASH_BUILTIN_TEST
9067 { BUILTIN_REGULAR "test" , testcmd },
9069 { BUILTIN_SPEC_REG "times" , timescmd },
9070 { BUILTIN_SPEC_REG "trap" , trapcmd },
9071 { BUILTIN_REGULAR "true" , truecmd },
9072 { BUILTIN_NOSPEC "type" , typecmd },
9073 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9074 { BUILTIN_REGULAR "umask" , umaskcmd },
9075 #if ENABLE_ASH_ALIAS
9076 { BUILTIN_REGULAR "unalias" , unaliascmd },
9078 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9079 { BUILTIN_REGULAR "wait" , waitcmd },
9082 /* Should match the above table! */
9083 #define COMMANDCMD (builtintab + \
9085 1 * ENABLE_ASH_BUILTIN_TEST + \
9086 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9087 1 * ENABLE_ASH_ALIAS + \
9088 1 * ENABLE_ASH_JOB_CONTROL + \
9090 #define EXECCMD (builtintab + \
9092 1 * ENABLE_ASH_BUILTIN_TEST + \
9093 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9094 1 * ENABLE_ASH_ALIAS + \
9095 1 * ENABLE_ASH_JOB_CONTROL + \
9097 1 * ENABLE_ASH_CMDCMD + \
9099 ENABLE_ASH_BUILTIN_ECHO + \
9103 * Search the table of builtin commands.
9105 static struct builtincmd *
9106 find_builtin(const char *name)
9108 struct builtincmd *bp;
9111 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9118 * Execute a simple command.
9121 isassignment(const char *p)
9123 const char *q = endofname(p);
9128 static int FAST_FUNC
9129 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9131 /* Preserve exitstatus of a previous possible redirection
9132 * as POSIX mandates */
9133 return back_exitstatus;
9136 evalcommand(union node *cmd, int flags)
9138 static const struct builtincmd null_bltin = {
9139 "\0\0", bltincmd /* why three NULs? */
9141 struct stackmark smark;
9143 struct arglist arglist;
9144 struct arglist varlist;
9147 const struct strlist *sp;
9148 struct cmdentry cmdentry;
9155 struct builtincmd *bcmd;
9156 smallint cmd_is_exec;
9157 smallint pseudovarflag = 0;
9159 /* First expand the arguments. */
9160 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9161 setstackmark(&smark);
9162 back_exitstatus = 0;
9164 cmdentry.cmdtype = CMDBUILTIN;
9165 cmdentry.u.cmd = &null_bltin;
9166 varlist.lastp = &varlist.list;
9167 *varlist.lastp = NULL;
9168 arglist.lastp = &arglist.list;
9169 *arglist.lastp = NULL;
9172 if (cmd->ncmd.args) {
9173 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9174 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9177 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9178 struct strlist **spp;
9180 spp = arglist.lastp;
9181 if (pseudovarflag && isassignment(argp->narg.text))
9182 expandarg(argp, &arglist, EXP_VARTILDE);
9184 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9186 for (sp = *spp; sp; sp = sp->next)
9190 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9191 for (sp = arglist.list; sp; sp = sp->next) {
9192 TRACE(("evalcommand arg: %s\n", sp->text));
9193 *nargv++ = sp->text;
9198 if (iflag && funcnest == 0 && argc > 0)
9199 lastarg = nargv[-1];
9202 expredir(cmd->ncmd.redirect);
9203 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9205 path = vpath.var_text;
9206 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9207 struct strlist **spp;
9210 spp = varlist.lastp;
9211 expandarg(argp, &varlist, EXP_VARTILDE);
9214 * Modify the command lookup path, if a PATH= assignment
9218 if (varcmp(p, path) == 0)
9222 /* Print the command if xflag is set. */
9225 const char *p = " %s" + 1;
9227 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9229 for (n = 0; n < 2; n++) {
9231 fdprintf(preverrout_fd, p, sp->text);
9237 safe_write(preverrout_fd, "\n", 1);
9243 /* Now locate the command. */
9245 const char *oldpath;
9246 int cmd_flag = DO_ERR;
9251 find_command(argv[0], &cmdentry, cmd_flag, path);
9252 if (cmdentry.cmdtype == CMDUNKNOWN) {
9253 flush_stdout_stderr();
9258 /* implement bltin and command here */
9259 if (cmdentry.cmdtype != CMDBUILTIN)
9262 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9263 if (cmdentry.u.cmd == EXECCMD)
9265 #if ENABLE_ASH_CMDCMD
9266 if (cmdentry.u.cmd == COMMANDCMD) {
9268 nargv = parse_command_args(argv, &path);
9271 argc -= nargv - argv;
9273 cmd_flag |= DO_NOFUNC;
9281 /* We have a redirection error. */
9283 raise_exception(EXERROR);
9285 exitstatus = status;
9289 /* Execute the command. */
9290 switch (cmdentry.cmdtype) {
9293 #if ENABLE_FEATURE_SH_NOFORK
9294 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9295 * around run_nofork_applet() call.
9296 * (2) Should this check also be done in forkshell()?
9297 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9299 /* find_command() encodes applet_no as (-2 - applet_no) */
9300 int applet_no = (- cmdentry.u.index - 2);
9301 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9302 listsetvar(varlist.list, VEXPORT|VSTACK);
9303 /* run <applet>_main() */
9304 exitstatus = run_nofork_applet(applet_no, argv);
9308 /* Can we avoid forking off? For example, very last command
9309 * in a script or a subshell does not need forking,
9310 * we can just exec it.
9312 if (!(flags & EV_EXIT) || may_have_traps) {
9313 /* No, forking off a child is necessary */
9315 jp = makejob(/*cmd,*/ 1);
9316 if (forkshell(jp, cmd, FORK_FG) != 0) {
9318 exitstatus = waitforjob(jp);
9320 TRACE(("forked child exited with %d\n", exitstatus));
9325 /* fall through to exec'ing external program */
9327 listsetvar(varlist.list, VEXPORT|VSTACK);
9328 shellexec(argv, path, cmdentry.u.index);
9332 cmdenviron = varlist.list;
9334 struct strlist *list = cmdenviron;
9336 if (spclbltin > 0 || argc == 0) {
9338 if (cmd_is_exec && argc > 1)
9341 listsetvar(list, i);
9343 /* Tight loop with builtins only:
9344 * "while kill -0 $child; do true; done"
9345 * will never exit even if $child died, unless we do this
9346 * to reap the zombie and make kill detect that it's gone: */
9347 dowait(DOWAIT_NONBLOCK, NULL);
9349 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9351 int i = exception_type;
9356 exit_status = 128 + SIGINT;
9358 exit_status = 128 + pending_sig;
9359 exitstatus = exit_status;
9360 if (i == EXINT || spclbltin > 0) {
9362 longjmp(exception_handler->loc, 1);
9369 listsetvar(varlist.list, 0);
9370 /* See above for the rationale */
9371 dowait(DOWAIT_NONBLOCK, NULL);
9372 if (evalfun(cmdentry.u.func, argc, argv, flags))
9379 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9381 /* dsl: I think this is intended to be used to support
9382 * '_' in 'vi' command mode during line editing...
9383 * However I implemented that within libedit itself.
9385 setvar("_", lastarg, 0);
9387 popstackmark(&smark);
9391 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9393 char *volatile savecmdname;
9394 struct jmploc *volatile savehandler;
9395 struct jmploc jmploc;
9398 savecmdname = commandname;
9399 i = setjmp(jmploc.loc);
9402 savehandler = exception_handler;
9403 exception_handler = &jmploc;
9404 commandname = argv[0];
9406 optptr = NULL; /* initialize nextopt */
9407 exitstatus = (*cmd->builtin)(argc, argv);
9408 flush_stdout_stderr();
9410 exitstatus |= ferror(stdout);
9412 commandname = savecmdname;
9413 exception_handler = savehandler;
9419 goodname(const char *p)
9421 return !*endofname(p);
9426 * Search for a command. This is called before we fork so that the
9427 * location of the command will be available in the parent as well as
9428 * the child. The check for "goodname" is an overly conservative
9429 * check that the name will not be subject to expansion.
9432 prehash(union node *n)
9434 struct cmdentry entry;
9436 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9437 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9441 /* ============ Builtin commands
9443 * Builtin commands whose functions are closely tied to evaluation
9444 * are implemented here.
9448 * Handle break and continue commands. Break, continue, and return are
9449 * all handled by setting the evalskip flag. The evaluation routines
9450 * above all check this flag, and if it is set they start skipping
9451 * commands rather than executing them. The variable skipcount is
9452 * the number of loops to break/continue, or the number of function
9453 * levels to return. (The latter is always 1.) It should probably
9454 * be an error to break out of more loops than exist, but it isn't
9455 * in the standard shell so we don't make it one here.
9457 static int FAST_FUNC
9458 breakcmd(int argc UNUSED_PARAM, char **argv)
9460 int n = argv[1] ? number(argv[1]) : 1;
9463 ash_msg_and_raise_error(msg_illnum, argv[1]);
9467 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9474 /* ============ input.c
9476 * This implements the input routines used by the parser.
9480 INPUT_PUSH_FILE = 1,
9481 INPUT_NOFILE_OK = 2,
9484 static smallint checkkwd;
9485 /* values of checkkwd variable */
9486 #define CHKALIAS 0x1
9491 * Push a string back onto the input at this current parsefile level.
9492 * We handle aliases this way.
9494 #if !ENABLE_ASH_ALIAS
9495 #define pushstring(s, ap) pushstring(s)
9498 pushstring(char *s, struct alias *ap)
9505 if (g_parsefile->strpush) {
9506 sp = ckzalloc(sizeof(*sp));
9507 sp->prev = g_parsefile->strpush;
9509 sp = &(g_parsefile->basestrpush);
9511 g_parsefile->strpush = sp;
9512 sp->prev_string = g_parsefile->next_to_pgetc;
9513 sp->prev_left_in_line = g_parsefile->left_in_line;
9514 #if ENABLE_ASH_ALIAS
9517 ap->flag |= ALIASINUSE;
9521 g_parsefile->next_to_pgetc = s;
9522 g_parsefile->left_in_line = len;
9529 struct strpush *sp = g_parsefile->strpush;
9532 #if ENABLE_ASH_ALIAS
9534 if (g_parsefile->next_to_pgetc[-1] == ' '
9535 || g_parsefile->next_to_pgetc[-1] == '\t'
9537 checkkwd |= CHKALIAS;
9539 if (sp->string != sp->ap->val) {
9542 sp->ap->flag &= ~ALIASINUSE;
9543 if (sp->ap->flag & ALIASDEAD) {
9544 unalias(sp->ap->name);
9548 g_parsefile->next_to_pgetc = sp->prev_string;
9549 g_parsefile->left_in_line = sp->prev_left_in_line;
9550 g_parsefile->strpush = sp->prev;
9551 if (sp != &(g_parsefile->basestrpush))
9556 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9557 //it peeks whether it is &>, and then pushes back both chars.
9558 //This function needs to save last *next_to_pgetc to buf[0]
9559 //to make two pungetc() reliable. Currently,
9560 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9565 char *buf = g_parsefile->buf;
9567 g_parsefile->next_to_pgetc = buf;
9568 #if ENABLE_FEATURE_EDITING
9570 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9571 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9573 #if ENABLE_FEATURE_TAB_COMPLETION
9574 line_input_state->path_lookup = pathval();
9576 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9578 /* Ctrl+C pressed */
9587 if (nr < 0 && errno == 0) {
9588 /* Ctrl+D pressed */
9593 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9597 /* nonblock_safe_read() handles this problem */
9599 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9600 int flags = fcntl(0, F_GETFL);
9601 if (flags >= 0 && (flags & O_NONBLOCK)) {
9602 flags &= ~O_NONBLOCK;
9603 if (fcntl(0, F_SETFL, flags) >= 0) {
9604 out2str("sh: turning off NDELAY mode\n");
9615 * Refill the input buffer and return the next input character:
9617 * 1) If a string was pushed back on the input, pop it;
9618 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9619 * or we are reading from a string so we can't refill the buffer,
9621 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9622 * 4) Process input up to the next newline, deleting nul characters.
9624 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9625 #define pgetc_debug(...) ((void)0)
9632 while (g_parsefile->strpush) {
9633 #if ENABLE_ASH_ALIAS
9634 if (g_parsefile->left_in_line == -1
9635 && g_parsefile->strpush->ap
9636 && g_parsefile->next_to_pgetc[-1] != ' '
9637 && g_parsefile->next_to_pgetc[-1] != '\t'
9639 pgetc_debug("preadbuffer PEOA");
9644 /* try "pgetc" now: */
9645 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9646 g_parsefile->left_in_line,
9647 g_parsefile->next_to_pgetc,
9648 g_parsefile->next_to_pgetc);
9649 if (--g_parsefile->left_in_line >= 0)
9650 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9652 /* on both branches above g_parsefile->left_in_line < 0.
9653 * "pgetc" needs refilling.
9656 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9657 * pungetc() may increment it a few times.
9658 * Assuming it won't increment it to less than -90.
9660 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9661 pgetc_debug("preadbuffer PEOF1");
9662 /* even in failure keep left_in_line and next_to_pgetc
9663 * in lock step, for correct multi-layer pungetc.
9664 * left_in_line was decremented before preadbuffer(),
9665 * must inc next_to_pgetc: */
9666 g_parsefile->next_to_pgetc++;
9670 more = g_parsefile->left_in_buffer;
9672 flush_stdout_stderr();
9676 /* don't try reading again */
9677 g_parsefile->left_in_line = -99;
9678 pgetc_debug("preadbuffer PEOF2");
9679 g_parsefile->next_to_pgetc++;
9684 /* Find out where's the end of line.
9685 * Set g_parsefile->left_in_line
9686 * and g_parsefile->left_in_buffer acordingly.
9687 * NUL chars are deleted.
9689 q = g_parsefile->next_to_pgetc;
9697 memmove(q, q + 1, more);
9701 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9707 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9708 if (g_parsefile->left_in_line < 0)
9713 g_parsefile->left_in_buffer = more;
9718 out2str(g_parsefile->next_to_pgetc);
9722 pgetc_debug("preadbuffer at %d:%p'%s'",
9723 g_parsefile->left_in_line,
9724 g_parsefile->next_to_pgetc,
9725 g_parsefile->next_to_pgetc);
9726 return (unsigned char)*g_parsefile->next_to_pgetc++;
9729 #define pgetc_as_macro() \
9730 (--g_parsefile->left_in_line >= 0 \
9731 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9738 pgetc_debug("pgetc_fast at %d:%p'%s'",
9739 g_parsefile->left_in_line,
9740 g_parsefile->next_to_pgetc,
9741 g_parsefile->next_to_pgetc);
9742 return pgetc_as_macro();
9745 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9746 # define pgetc_fast() pgetc()
9748 # define pgetc_fast() pgetc_as_macro()
9751 #if ENABLE_ASH_ALIAS
9753 pgetc_without_PEOA(void)
9757 pgetc_debug("pgetc_fast at %d:%p'%s'",
9758 g_parsefile->left_in_line,
9759 g_parsefile->next_to_pgetc,
9760 g_parsefile->next_to_pgetc);
9762 } while (c == PEOA);
9766 # define pgetc_without_PEOA() pgetc()
9770 * Read a line from the script.
9773 pfgets(char *line, int len)
9779 while (--nleft > 0) {
9780 c = pgetc_without_PEOA();
9795 * Undo the last call to pgetc. Only one character may be pushed back.
9796 * PEOF may be pushed back.
9801 g_parsefile->left_in_line++;
9802 g_parsefile->next_to_pgetc--;
9803 pgetc_debug("pushed back to %d:%p'%s'",
9804 g_parsefile->left_in_line,
9805 g_parsefile->next_to_pgetc,
9806 g_parsefile->next_to_pgetc);
9810 * To handle the "." command, a stack of input files is used. Pushfile
9811 * adds a new entry to the stack and popfile restores the previous level.
9816 struct parsefile *pf;
9818 pf = ckzalloc(sizeof(*pf));
9819 pf->prev = g_parsefile;
9821 /*pf->strpush = NULL; - ckzalloc did it */
9822 /*pf->basestrpush.prev = NULL;*/
9829 struct parsefile *pf = g_parsefile;
9837 g_parsefile = pf->prev;
9843 * Return to top level.
9848 while (g_parsefile != &basepf)
9853 * Close the file(s) that the shell is reading commands from. Called
9854 * after a fork is done.
9860 if (g_parsefile->pf_fd > 0) {
9861 close(g_parsefile->pf_fd);
9862 g_parsefile->pf_fd = 0;
9867 * Like setinputfile, but takes an open file descriptor. Call this with
9871 setinputfd(int fd, int push)
9873 close_on_exec_on(fd);
9876 g_parsefile->buf = NULL;
9878 g_parsefile->pf_fd = fd;
9879 if (g_parsefile->buf == NULL)
9880 g_parsefile->buf = ckmalloc(IBUFSIZ);
9881 g_parsefile->left_in_buffer = 0;
9882 g_parsefile->left_in_line = 0;
9883 g_parsefile->linno = 1;
9887 * Set the input to take input from a file. If push is set, push the
9888 * old input onto the stack first.
9891 setinputfile(const char *fname, int flags)
9897 fd = open(fname, O_RDONLY);
9899 if (flags & INPUT_NOFILE_OK)
9901 ash_msg_and_raise_error("can't open '%s'", fname);
9904 fd2 = copyfd(fd, 10);
9907 ash_msg_and_raise_error("out of file descriptors");
9910 setinputfd(fd, flags & INPUT_PUSH_FILE);
9917 * Like setinputfile, but takes input from a string.
9920 setinputstring(char *string)
9924 g_parsefile->next_to_pgetc = string;
9925 g_parsefile->left_in_line = strlen(string);
9926 g_parsefile->buf = NULL;
9927 g_parsefile->linno = 1;
9932 /* ============ mail.c
9934 * Routines to check for mail.
9939 #define MAXMBOXES 10
9941 /* times of mailboxes */
9942 static time_t mailtime[MAXMBOXES];
9943 /* Set if MAIL or MAILPATH is changed. */
9944 static smallint mail_var_path_changed;
9947 * Print appropriate message(s) if mail has arrived.
9948 * If mail_var_path_changed is set,
9949 * then the value of MAIL has mail_var_path_changed,
9950 * so we just update the values.
9959 struct stackmark smark;
9962 setstackmark(&smark);
9963 mpath = mpathset() ? mpathval() : mailval();
9964 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9965 p = path_advance(&mpath, nullstr);
9970 for (q = p; *q; q++)
9976 q[-1] = '\0'; /* delete trailing '/' */
9977 if (stat(p, &statb) < 0) {
9981 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9984 pathopt ? pathopt : "you have mail"
9987 *mtp = statb.st_mtime;
9989 mail_var_path_changed = 0;
9990 popstackmark(&smark);
9993 static void FAST_FUNC
9994 changemail(const char *val UNUSED_PARAM)
9996 mail_var_path_changed = 1;
9999 #endif /* ASH_MAIL */
10002 /* ============ ??? */
10005 * Set the shell parameters.
10008 setparam(char **argv)
10014 for (nparam = 0; argv[nparam]; nparam++)
10016 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10018 *ap++ = ckstrdup(*argv++);
10021 freeparam(&shellparam);
10022 shellparam.malloced = 1;
10023 shellparam.nparam = nparam;
10024 shellparam.p = newparam;
10025 #if ENABLE_ASH_GETOPTS
10026 shellparam.optind = 1;
10027 shellparam.optoff = -1;
10032 * Process shell options. The global variable argptr contains a pointer
10033 * to the argument list; we advance it past the options.
10035 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10036 * For a non-interactive shell, an error condition encountered
10037 * by a special built-in ... shall cause the shell to write a diagnostic message
10038 * to standard error and exit as shown in the following table:
10039 * Error Special Built-In
10041 * Utility syntax error (option or operand error) Shall exit
10043 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10044 * we see that bash does not do that (set "finishes" with error code 1 instead,
10045 * and shell continues), and people rely on this behavior!
10047 * set -o barfoo 2>/dev/null
10050 * Oh well. Let's mimic that.
10053 plus_minus_o(char *name, int val)
10058 for (i = 0; i < NOPTS; i++) {
10059 if (strcmp(name, optnames(i)) == 0) {
10064 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10067 for (i = 0; i < NOPTS; i++) {
10069 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10071 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10077 setoption(int flag, int val)
10081 for (i = 0; i < NOPTS; i++) {
10082 if (optletters(i) == flag) {
10087 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10091 options(int cmdline)
10099 while ((p = *argptr) != NULL) {
10101 if (c != '-' && c != '+')
10104 val = 0; /* val = 0 if c == '+' */
10107 if (p[0] == '\0' || LONE_DASH(p)) {
10109 /* "-" means turn off -x and -v */
10112 /* "--" means reset params */
10113 else if (*argptr == NULL)
10116 break; /* "-" or "--" terminates options */
10119 /* first char was + or - */
10120 while ((c = *p++) != '\0') {
10121 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10122 if (c == 'c' && cmdline) {
10123 minusc = p; /* command is after shell args */
10124 } else if (c == 'o') {
10125 if (plus_minus_o(*argptr, val)) {
10126 /* it already printed err message */
10127 return 1; /* error */
10131 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10133 /* bash does not accept +-login, we also won't */
10134 } else if (cmdline && val && (c == '-')) { /* long options */
10135 if (strcmp(p, "login") == 0)
10147 * The shift builtin command.
10149 static int FAST_FUNC
10150 shiftcmd(int argc UNUSED_PARAM, char **argv)
10157 n = number(argv[1]);
10158 if (n > shellparam.nparam)
10159 n = 0; /* bash compat, was = shellparam.nparam; */
10161 shellparam.nparam -= n;
10162 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10163 if (shellparam.malloced)
10166 ap2 = shellparam.p;
10167 while ((*ap2++ = *ap1++) != NULL)
10169 #if ENABLE_ASH_GETOPTS
10170 shellparam.optind = 1;
10171 shellparam.optoff = -1;
10178 * POSIX requires that 'set' (but not export or readonly) output the
10179 * variables in lexicographic order - by the locale's collating order (sigh).
10180 * Maybe we could keep them in an ordered balanced binary tree
10181 * instead of hashed lists.
10182 * For now just roll 'em through qsort for printing...
10185 showvars(const char *sep_prefix, int on, int off)
10188 char **ep, **epend;
10190 ep = listvars(on, off, &epend);
10191 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10193 sep = *sep_prefix ? " " : sep_prefix;
10195 for (; ep < epend; ep++) {
10199 p = strchrnul(*ep, '=');
10202 q = single_quote(++p);
10203 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10209 * The set command builtin.
10211 static int FAST_FUNC
10212 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10217 return showvars(nullstr, 0, VUNSET);
10220 if (!options(0)) { /* if no parse error... */
10223 if (*argptr != NULL) {
10231 #if ENABLE_ASH_RANDOM_SUPPORT
10232 static void FAST_FUNC
10233 change_random(const char *value)
10237 if (value == NULL) {
10238 /* "get", generate */
10239 t = next_random(&random_gen);
10240 /* set without recursion */
10241 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10242 vrandom.flags &= ~VNOFUNC;
10245 t = strtoul(value, NULL, 10);
10246 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10251 #if ENABLE_ASH_GETOPTS
10253 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10262 if (*param_optind < 1)
10264 optnext = optfirst + *param_optind - 1;
10266 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10269 p = optnext[-1] + *optoff;
10270 if (p == NULL || *p == '\0') {
10271 /* Current word is done, advance */
10273 if (p == NULL || *p != '-' || *++p == '\0') {
10280 if (LONE_DASH(p)) /* check for "--" */
10285 for (q = optstr; *q != c;) {
10287 if (optstr[0] == ':') {
10290 err |= setvarsafe("OPTARG", s, 0);
10292 fprintf(stderr, "Illegal option -%c\n", c);
10293 unsetvar("OPTARG");
10303 if (*p == '\0' && (p = *optnext) == NULL) {
10304 if (optstr[0] == ':') {
10307 err |= setvarsafe("OPTARG", s, 0);
10310 fprintf(stderr, "No arg for -%c option\n", c);
10311 unsetvar("OPTARG");
10319 err |= setvarsafe("OPTARG", p, 0);
10322 err |= setvarsafe("OPTARG", nullstr, 0);
10324 *optoff = p ? p - *(optnext - 1) : -1;
10325 *param_optind = optnext - optfirst + 1;
10326 fmtstr(s, sizeof(s), "%d", *param_optind);
10327 err |= setvarsafe("OPTIND", s, VNOFUNC);
10330 err |= setvarsafe(optvar, s, 0);
10334 flush_stdout_stderr();
10335 raise_exception(EXERROR);
10341 * The getopts builtin. Shellparam.optnext points to the next argument
10342 * to be processed. Shellparam.optptr points to the next character to
10343 * be processed in the current argument. If shellparam.optnext is NULL,
10344 * then it's the first time getopts has been called.
10346 static int FAST_FUNC
10347 getoptscmd(int argc, char **argv)
10352 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10354 optbase = shellparam.p;
10355 if (shellparam.optind > shellparam.nparam + 1) {
10356 shellparam.optind = 1;
10357 shellparam.optoff = -1;
10360 optbase = &argv[3];
10361 if (shellparam.optind > argc - 2) {
10362 shellparam.optind = 1;
10363 shellparam.optoff = -1;
10367 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10368 &shellparam.optoff);
10370 #endif /* ASH_GETOPTS */
10373 /* ============ Shell parser */
10376 struct heredoc *next; /* next here document in list */
10377 union node *here; /* redirection node */
10378 char *eofmark; /* string indicating end of input */
10379 smallint striptabs; /* if set, strip leading tabs */
10382 static smallint tokpushback; /* last token pushed back */
10383 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10384 static smallint quoteflag; /* set if (part of) last token was quoted */
10385 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10386 static struct heredoc *heredoclist; /* list of here documents to read */
10387 static char *wordtext; /* text of last word returned by readtoken */
10388 static struct nodelist *backquotelist;
10389 static union node *redirnode;
10390 static struct heredoc *heredoc;
10392 static const char *
10393 tokname(char *buf, int tok)
10396 return tokname_array[tok] + 1;
10397 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10401 /* raise_error_unexpected_syntax:
10402 * Called when an unexpected token is read during the parse. The argument
10403 * is the token that is expected, or -1 if more than one type of token can
10404 * occur at this point.
10406 static void raise_error_unexpected_syntax(int) NORETURN;
10408 raise_error_unexpected_syntax(int token)
10414 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10416 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10417 raise_error_syntax(msg);
10421 #define EOFMARKLEN 79
10423 /* parsing is heavily cross-recursive, need these forward decls */
10424 static union node *andor(void);
10425 static union node *pipeline(void);
10426 static union node *parse_command(void);
10427 static void parseheredoc(void);
10428 static char peektoken(void);
10429 static int readtoken(void);
10431 static union node *
10434 union node *n1, *n2, *n3;
10437 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10438 if (nlflag == 2 && peektoken())
10444 if (tok == TBACKGND) {
10445 if (n2->type == NPIPE) {
10446 n2->npipe.pipe_backgnd = 1;
10448 if (n2->type != NREDIR) {
10449 n3 = stzalloc(sizeof(struct nredir));
10451 /*n3->nredir.redirect = NULL; - stzalloc did it */
10454 n2->type = NBACKGND;
10460 n3 = stzalloc(sizeof(struct nbinary));
10462 n3->nbinary.ch1 = n1;
10463 n3->nbinary.ch2 = n2;
10479 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10487 pungetc(); /* push back EOF on input */
10491 raise_error_unexpected_syntax(-1);
10498 static union node *
10501 union node *n1, *n2, *n3;
10509 } else if (t == TOR) {
10515 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10517 n3 = stzalloc(sizeof(struct nbinary));
10519 n3->nbinary.ch1 = n1;
10520 n3->nbinary.ch2 = n2;
10525 static union node *
10528 union node *n1, *n2, *pipenode;
10529 struct nodelist *lp, *prev;
10533 TRACE(("pipeline: entered\n"));
10534 if (readtoken() == TNOT) {
10536 checkkwd = CHKKWD | CHKALIAS;
10539 n1 = parse_command();
10540 if (readtoken() == TPIPE) {
10541 pipenode = stzalloc(sizeof(struct npipe));
10542 pipenode->type = NPIPE;
10543 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10544 lp = stzalloc(sizeof(struct nodelist));
10545 pipenode->npipe.cmdlist = lp;
10549 lp = stzalloc(sizeof(struct nodelist));
10550 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10551 lp->n = parse_command();
10553 } while (readtoken() == TPIPE);
10559 n2 = stzalloc(sizeof(struct nnot));
10567 static union node *
10572 n = stzalloc(sizeof(struct narg));
10574 /*n->narg.next = NULL; - stzalloc did it */
10575 n->narg.text = wordtext;
10576 n->narg.backquote = backquotelist;
10581 fixredir(union node *n, const char *text, int err)
10585 TRACE(("Fix redir %s %d\n", text, err));
10587 n->ndup.vname = NULL;
10589 fd = bb_strtou(text, NULL, 10);
10590 if (!errno && fd >= 0)
10591 n->ndup.dupfd = fd;
10592 else if (LONE_DASH(text))
10593 n->ndup.dupfd = -1;
10596 raise_error_syntax("bad fd number");
10597 n->ndup.vname = makename();
10602 * Returns true if the text contains nothing to expand (no dollar signs
10606 noexpand(const char *text)
10610 while ((c = *text++) != '\0') {
10611 if (c == CTLQUOTEMARK)
10615 else if (SIT(c, BASESYNTAX) == CCTL)
10624 union node *n = redirnode;
10626 if (readtoken() != TWORD)
10627 raise_error_unexpected_syntax(-1);
10628 if (n->type == NHERE) {
10629 struct heredoc *here = heredoc;
10633 if (quoteflag == 0)
10635 TRACE(("Here document %d\n", n->type));
10636 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10637 raise_error_syntax("illegal eof marker for << redirection");
10638 rmescapes(wordtext, 0);
10639 here->eofmark = wordtext;
10641 if (heredoclist == NULL)
10642 heredoclist = here;
10644 for (p = heredoclist; p->next; p = p->next)
10648 } else if (n->type == NTOFD || n->type == NFROMFD) {
10649 fixredir(n, wordtext, 0);
10651 n->nfile.fname = makename();
10655 static union node *
10658 union node *args, **app;
10659 union node *n = NULL;
10660 union node *vars, **vpp;
10661 union node **rpp, *redir;
10663 #if ENABLE_ASH_BASH_COMPAT
10664 smallint double_brackets_flag = 0;
10674 savecheckkwd = CHKALIAS;
10677 checkkwd = savecheckkwd;
10680 #if ENABLE_ASH_BASH_COMPAT
10681 case TAND: /* "&&" */
10682 case TOR: /* "||" */
10683 if (!double_brackets_flag) {
10687 wordtext = (char *) (t == TAND ? "-a" : "-o");
10690 n = stzalloc(sizeof(struct narg));
10692 /*n->narg.next = NULL; - stzalloc did it */
10693 n->narg.text = wordtext;
10694 #if ENABLE_ASH_BASH_COMPAT
10695 if (strcmp("[[", wordtext) == 0)
10696 double_brackets_flag = 1;
10697 else if (strcmp("]]", wordtext) == 0)
10698 double_brackets_flag = 0;
10700 n->narg.backquote = backquotelist;
10701 if (savecheckkwd && isassignment(wordtext)) {
10703 vpp = &n->narg.next;
10706 app = &n->narg.next;
10711 *rpp = n = redirnode;
10712 rpp = &n->nfile.next;
10713 parsefname(); /* read name of redirection file */
10716 if (args && app == &args->narg.next
10719 struct builtincmd *bcmd;
10722 /* We have a function */
10723 if (readtoken() != TRP)
10724 raise_error_unexpected_syntax(TRP);
10725 name = n->narg.text;
10726 if (!goodname(name)
10727 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10729 raise_error_syntax("bad function name");
10732 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10733 n->narg.next = parse_command();
10746 n = stzalloc(sizeof(struct ncmd));
10748 n->ncmd.args = args;
10749 n->ncmd.assign = vars;
10750 n->ncmd.redirect = redir;
10754 static union node *
10755 parse_command(void)
10757 union node *n1, *n2;
10758 union node *ap, **app;
10759 union node *cp, **cpp;
10760 union node *redir, **rpp;
10767 switch (readtoken()) {
10769 raise_error_unexpected_syntax(-1);
10772 n1 = stzalloc(sizeof(struct nif));
10774 n1->nif.test = list(0);
10775 if (readtoken() != TTHEN)
10776 raise_error_unexpected_syntax(TTHEN);
10777 n1->nif.ifpart = list(0);
10779 while (readtoken() == TELIF) {
10780 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10781 n2 = n2->nif.elsepart;
10783 n2->nif.test = list(0);
10784 if (readtoken() != TTHEN)
10785 raise_error_unexpected_syntax(TTHEN);
10786 n2->nif.ifpart = list(0);
10788 if (lasttoken == TELSE)
10789 n2->nif.elsepart = list(0);
10791 n2->nif.elsepart = NULL;
10799 n1 = stzalloc(sizeof(struct nbinary));
10800 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10801 n1->nbinary.ch1 = list(0);
10804 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10805 got == TWORD ? wordtext : ""));
10806 raise_error_unexpected_syntax(TDO);
10808 n1->nbinary.ch2 = list(0);
10813 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10814 raise_error_syntax("bad for loop variable");
10815 n1 = stzalloc(sizeof(struct nfor));
10817 n1->nfor.var = wordtext;
10818 checkkwd = CHKKWD | CHKALIAS;
10819 if (readtoken() == TIN) {
10821 while (readtoken() == TWORD) {
10822 n2 = stzalloc(sizeof(struct narg));
10824 /*n2->narg.next = NULL; - stzalloc did it */
10825 n2->narg.text = wordtext;
10826 n2->narg.backquote = backquotelist;
10828 app = &n2->narg.next;
10831 n1->nfor.args = ap;
10832 if (lasttoken != TNL && lasttoken != TSEMI)
10833 raise_error_unexpected_syntax(-1);
10835 n2 = stzalloc(sizeof(struct narg));
10837 /*n2->narg.next = NULL; - stzalloc did it */
10838 n2->narg.text = (char *)dolatstr;
10839 /*n2->narg.backquote = NULL;*/
10840 n1->nfor.args = n2;
10842 * Newline or semicolon here is optional (but note
10843 * that the original Bourne shell only allowed NL).
10845 if (lasttoken != TNL && lasttoken != TSEMI)
10848 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10849 if (readtoken() != TDO)
10850 raise_error_unexpected_syntax(TDO);
10851 n1->nfor.body = list(0);
10855 n1 = stzalloc(sizeof(struct ncase));
10857 if (readtoken() != TWORD)
10858 raise_error_unexpected_syntax(TWORD);
10859 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10861 /*n2->narg.next = NULL; - stzalloc did it */
10862 n2->narg.text = wordtext;
10863 n2->narg.backquote = backquotelist;
10865 checkkwd = CHKKWD | CHKALIAS;
10866 } while (readtoken() == TNL);
10867 if (lasttoken != TIN)
10868 raise_error_unexpected_syntax(TIN);
10869 cpp = &n1->ncase.cases;
10871 checkkwd = CHKNL | CHKKWD;
10873 while (t != TESAC) {
10874 if (lasttoken == TLP)
10876 *cpp = cp = stzalloc(sizeof(struct nclist));
10878 app = &cp->nclist.pattern;
10880 *app = ap = stzalloc(sizeof(struct narg));
10882 /*ap->narg.next = NULL; - stzalloc did it */
10883 ap->narg.text = wordtext;
10884 ap->narg.backquote = backquotelist;
10885 if (readtoken() != TPIPE)
10887 app = &ap->narg.next;
10890 //ap->narg.next = NULL;
10891 if (lasttoken != TRP)
10892 raise_error_unexpected_syntax(TRP);
10893 cp->nclist.body = list(2);
10895 cpp = &cp->nclist.next;
10897 checkkwd = CHKNL | CHKKWD;
10901 raise_error_unexpected_syntax(TENDCASE);
10908 n1 = stzalloc(sizeof(struct nredir));
10909 n1->type = NSUBSHELL;
10910 n1->nredir.n = list(0);
10911 /*n1->nredir.redirect = NULL; - stzalloc did it */
10921 return simplecmd();
10924 if (readtoken() != t)
10925 raise_error_unexpected_syntax(t);
10928 /* Now check for redirection which may follow command */
10929 checkkwd = CHKKWD | CHKALIAS;
10931 while (readtoken() == TREDIR) {
10932 *rpp = n2 = redirnode;
10933 rpp = &n2->nfile.next;
10939 if (n1->type != NSUBSHELL) {
10940 n2 = stzalloc(sizeof(struct nredir));
10945 n1->nredir.redirect = redir;
10950 #if ENABLE_ASH_BASH_COMPAT
10951 static int decode_dollar_squote(void)
10953 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10959 p = strchr(C_escapes, c);
10964 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10968 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10970 } else if (c == 'x') { /* \xHH */
10974 } while (isxdigit(c) && --cnt);
10976 if (cnt == 3) { /* \x but next char is "bad" */
10980 } else { /* simple seq like \\ or \t */
10985 c = bb_process_escape_sequence((void*)&p);
10986 } else { /* unrecognized "\z": print both chars unless ' or " */
10987 if (c != '\'' && c != '"') {
10989 c |= 0x100; /* "please encode \, then me" */
10997 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10998 * is not NULL, read a here document. In the latter case, eofmark is the
10999 * word which marks the end of the document and striptabs is true if
11000 * leading tabs should be stripped from the document. The argument c
11001 * is the first character of the input token or document.
11003 * Because C does not have internal subroutines, I have simulated them
11004 * using goto's to implement the subroutine linkage. The following macros
11005 * will run code that appears at the end of readtoken1.
11007 #define CHECKEND() {goto checkend; checkend_return:;}
11008 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11009 #define PARSESUB() {goto parsesub; parsesub_return:;}
11010 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11011 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11012 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11014 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11016 /* NB: syntax parameter fits into smallint */
11017 /* c parameter is an unsigned char or PEOF or PEOA */
11020 char line[EOFMARKLEN + 1];
11021 struct nodelist *bqlist;
11025 smallint prevsyntax; /* syntax before arithmetic */
11026 #if ENABLE_ASH_EXPAND_PRMT
11027 smallint pssyntax; /* we are expanding a prompt string */
11029 int varnest; /* levels of variables expansion */
11030 int arinest; /* levels of arithmetic expansion */
11031 int parenlevel; /* levels of parens in arithmetic */
11032 int dqvarnest; /* levels of variables expansion within double quotes */
11034 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11037 /* Avoid longjmp clobbering */
11043 (void) &parenlevel;
11046 (void) &prevsyntax;
11049 startlinno = g_parsefile->linno;
11054 #if ENABLE_ASH_EXPAND_PRMT
11055 pssyntax = (syntax == PSSYNTAX);
11059 dblquote = (syntax == DQSYNTAX);
11065 STARTSTACKSTR(out);
11067 /* For each line, until end of word */
11069 CHECKEND(); /* set c to PEOF if at end of here document */
11070 for (;;) { /* until end of line or end of word */
11071 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11072 switch (SIT(c, syntax)) {
11073 case CNL: /* '\n' */
11074 if (syntax == BASESYNTAX)
11075 goto endword; /* exit outer loop */
11077 g_parsefile->linno++;
11081 goto loop; /* continue outer loop */
11086 if (eofmark == NULL || dblquote)
11087 USTPUTC(CTLESC, out);
11088 #if ENABLE_ASH_BASH_COMPAT
11089 if (c == '\\' && bash_dollar_squote) {
11090 c = decode_dollar_squote();
11092 USTPUTC('\\', out);
11093 c = (unsigned char)c;
11099 case CBACK: /* backslash */
11100 c = pgetc_without_PEOA();
11102 USTPUTC(CTLESC, out);
11103 USTPUTC('\\', out);
11105 } else if (c == '\n') {
11109 #if ENABLE_ASH_EXPAND_PRMT
11110 if (c == '$' && pssyntax) {
11111 USTPUTC(CTLESC, out);
11112 USTPUTC('\\', out);
11115 if (dblquote && c != '\\'
11116 && c != '`' && c != '$'
11117 && (c != '"' || eofmark != NULL)
11119 USTPUTC(CTLESC, out);
11120 USTPUTC('\\', out);
11122 if (SIT(c, SQSYNTAX) == CCTL)
11123 USTPUTC(CTLESC, out);
11131 if (eofmark == NULL) {
11132 USTPUTC(CTLQUOTEMARK, out);
11140 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11141 if (eofmark != NULL && arinest == 0
11146 if (dqvarnest == 0) {
11147 syntax = BASESYNTAX;
11154 case CVAR: /* '$' */
11155 PARSESUB(); /* parse substitution */
11157 case CENDVAR: /* '}' */
11160 if (dqvarnest > 0) {
11163 USTPUTC(CTLENDVAR, out);
11168 #if ENABLE_SH_MATH_SUPPORT
11169 case CLP: /* '(' in arithmetic */
11173 case CRP: /* ')' in arithmetic */
11174 if (parenlevel > 0) {
11178 if (pgetc() == ')') {
11179 if (--arinest == 0) {
11180 USTPUTC(CTLENDARI, out);
11181 syntax = prevsyntax;
11182 dblquote = (syntax == DQSYNTAX);
11187 * unbalanced parens
11188 * (don't 2nd guess - no error)
11196 case CBQUOTE: /* '`' */
11200 goto endword; /* exit outer loop */
11204 if (varnest == 0) {
11205 #if ENABLE_ASH_BASH_COMPAT
11207 if (pgetc() == '>')
11208 c = 0x100 + '>'; /* flag &> */
11212 goto endword; /* exit outer loop */
11214 IF_ASH_ALIAS(if (c != PEOA))
11222 #if ENABLE_SH_MATH_SUPPORT
11223 if (syntax == ARISYNTAX)
11224 raise_error_syntax("missing '))'");
11226 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11227 raise_error_syntax("unterminated quoted string");
11228 if (varnest != 0) {
11229 startlinno = g_parsefile->linno;
11231 raise_error_syntax("missing '}'");
11233 USTPUTC('\0', out);
11234 len = out - (char *)stackblock();
11235 out = stackblock();
11236 if (eofmark == NULL) {
11237 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11240 if (isdigit_str9(out)) {
11241 PARSEREDIR(); /* passed as params: out, c */
11242 lasttoken = TREDIR;
11245 /* else: non-number X seen, interpret it
11246 * as "NNNX>file" = "NNNX >file" */
11250 quoteflag = quotef;
11251 backquotelist = bqlist;
11252 grabstackblock(len);
11256 /* end of readtoken routine */
11259 * Check to see whether we are at the end of the here document. When this
11260 * is called, c is set to the first character of the next input line. If
11261 * we are at the end of the here document, this routine sets the c to PEOF.
11265 #if ENABLE_ASH_ALIAS
11267 c = pgetc_without_PEOA();
11270 while (c == '\t') {
11271 c = pgetc_without_PEOA();
11274 if (c == *eofmark) {
11275 if (pfgets(line, sizeof(line)) != NULL) {
11279 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11281 if (*p == '\n' && *q == '\0') {
11283 g_parsefile->linno++;
11284 needprompt = doprompt;
11286 pushstring(line, NULL);
11291 goto checkend_return;
11295 * Parse a redirection operator. The variable "out" points to a string
11296 * specifying the fd to be redirected. The variable "c" contains the
11297 * first character of the redirection operator.
11300 /* out is already checked to be a valid number or "" */
11301 int fd = (*out == '\0' ? -1 : atoi(out));
11304 np = stzalloc(sizeof(struct nfile));
11309 np->type = NAPPEND;
11311 np->type = NCLOBBER;
11314 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11320 #if ENABLE_ASH_BASH_COMPAT
11321 else if (c == 0x100 + '>') { /* this flags &> redirection */
11323 pgetc(); /* this is '>', no need to check */
11327 else { /* c == '<' */
11328 /*np->nfile.fd = 0; - stzalloc did it */
11332 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11333 np = stzalloc(sizeof(struct nhere));
11334 /*np->nfile.fd = 0; - stzalloc did it */
11337 heredoc = stzalloc(sizeof(struct heredoc));
11338 heredoc->here = np;
11341 heredoc->striptabs = 1;
11343 /*heredoc->striptabs = 0; - stzalloc did it */
11349 np->type = NFROMFD;
11353 np->type = NFROMTO;
11365 goto parseredir_return;
11369 * Parse a substitution. At this point, we have read the dollar sign
11370 * and nothing else.
11373 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11374 * (assuming ascii char codes, as the original implementation did) */
11375 #define is_special(c) \
11376 (((unsigned)(c) - 33 < 32) \
11377 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11379 unsigned char subtype;
11383 static const char types[] ALIGN1 = "}-+?=";
11386 if (c > 255 /* PEOA or PEOF */
11387 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11389 #if ENABLE_ASH_BASH_COMPAT
11391 bash_dollar_squote = 1;
11396 } else if (c == '(') { /* $(command) or $((arith)) */
11397 if (pgetc() == '(') {
11398 #if ENABLE_SH_MATH_SUPPORT
11401 raise_error_syntax("you disabled math support for $((arith)) syntax");
11408 USTPUTC(CTLVAR, out);
11409 typeloc = out - (char *)stackblock();
11410 USTPUTC(VSNORMAL, out);
11411 subtype = VSNORMAL;
11419 subtype = VSLENGTH;
11423 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11427 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11428 } else if (isdigit(c)) {
11432 } while (isdigit(c));
11433 } else if (is_special(c)) {
11438 raise_error_syntax("bad substitution");
11440 if (c != '}' && subtype == VSLENGTH)
11445 if (subtype == 0) {
11449 #if ENABLE_ASH_BASH_COMPAT
11450 if (c == ':' || c == '$' || isdigit(c)) {
11452 subtype = VSSUBSTR;
11459 p = strchr(types, c);
11462 subtype = p - types + VSNORMAL;
11467 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11475 #if ENABLE_ASH_BASH_COMPAT
11477 subtype = VSREPLACE;
11480 subtype++; /* VSREPLACEALL */
11489 if (dblquote || arinest)
11491 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11492 if (subtype != VSNORMAL) {
11494 if (dblquote || arinest) {
11499 goto parsesub_return;
11503 * Called to parse command substitutions. Newstyle is set if the command
11504 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11505 * list of commands (passed by reference), and savelen is the number of
11506 * characters on the top of the stack which must be preserved.
11509 struct nodelist **nlpp;
11512 char *volatile str;
11513 struct jmploc jmploc;
11514 struct jmploc *volatile savehandler;
11516 smallint saveprompt = 0;
11519 (void) &saveprompt;
11521 savepbq = parsebackquote;
11522 if (setjmp(jmploc.loc)) {
11524 parsebackquote = 0;
11525 exception_handler = savehandler;
11526 longjmp(exception_handler->loc, 1);
11530 savelen = out - (char *)stackblock();
11532 str = ckmalloc(savelen);
11533 memcpy(str, stackblock(), savelen);
11535 savehandler = exception_handler;
11536 exception_handler = &jmploc;
11539 /* We must read until the closing backquote, giving special
11540 treatment to some slashes, and then push the string and
11541 reread it as input, interpreting it normally. */
11548 STARTSTACKSTR(pout);
11561 g_parsefile->linno++;
11565 * If eating a newline, avoid putting
11566 * the newline into the new character
11567 * stream (via the STPUTC after the
11572 if (pc != '\\' && pc != '`' && pc != '$'
11573 && (!dblquote || pc != '"')
11575 STPUTC('\\', pout);
11577 if (pc <= 255 /* not PEOA or PEOF */) {
11583 IF_ASH_ALIAS(case PEOA:)
11584 startlinno = g_parsefile->linno;
11585 raise_error_syntax("EOF in backquote substitution");
11588 g_parsefile->linno++;
11589 needprompt = doprompt;
11598 STPUTC('\0', pout);
11599 psavelen = pout - (char *)stackblock();
11600 if (psavelen > 0) {
11601 pstr = grabstackstr(pout);
11602 setinputstring(pstr);
11607 nlpp = &(*nlpp)->next;
11608 *nlpp = stzalloc(sizeof(**nlpp));
11609 /* (*nlpp)->next = NULL; - stzalloc did it */
11610 parsebackquote = oldstyle;
11613 saveprompt = doprompt;
11620 doprompt = saveprompt;
11621 else if (readtoken() != TRP)
11622 raise_error_unexpected_syntax(TRP);
11627 * Start reading from old file again, ignoring any pushed back
11628 * tokens left from the backquote parsing
11633 while (stackblocksize() <= savelen)
11635 STARTSTACKSTR(out);
11637 memcpy(out, str, savelen);
11638 STADJUST(savelen, out);
11644 parsebackquote = savepbq;
11645 exception_handler = savehandler;
11646 if (arinest || dblquote)
11647 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11649 USTPUTC(CTLBACKQ, out);
11651 goto parsebackq_oldreturn;
11652 goto parsebackq_newreturn;
11655 #if ENABLE_SH_MATH_SUPPORT
11657 * Parse an arithmetic expansion (indicate start of one and set state)
11660 if (++arinest == 1) {
11661 prevsyntax = syntax;
11662 syntax = ARISYNTAX;
11663 USTPUTC(CTLARI, out);
11670 * we collapse embedded arithmetic expansion to
11671 * parenthesis, which should be equivalent
11675 goto parsearith_return;
11679 } /* end of readtoken */
11682 * Read the next input token.
11683 * If the token is a word, we set backquotelist to the list of cmds in
11684 * backquotes. We set quoteflag to true if any part of the word was
11686 * If the token is TREDIR, then we set redirnode to a structure containing
11688 * In all cases, the variable startlinno is set to the number of the line
11689 * on which the token starts.
11691 * [Change comment: here documents and internal procedures]
11692 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11693 * word parsing code into a separate routine. In this case, readtoken
11694 * doesn't need to have any internal procedures, but parseword does.
11695 * We could also make parseoperator in essence the main routine, and
11696 * have parseword (readtoken1?) handle both words and redirection.]
11698 #define NEW_xxreadtoken
11699 #ifdef NEW_xxreadtoken
11700 /* singles must be first! */
11701 static const char xxreadtoken_chars[7] ALIGN1 = {
11702 '\n', '(', ')', /* singles */
11703 '&', '|', ';', /* doubles */
11707 #define xxreadtoken_singles 3
11708 #define xxreadtoken_doubles 3
11710 static const char xxreadtoken_tokens[] ALIGN1 = {
11711 TNL, TLP, TRP, /* only single occurrence allowed */
11712 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11713 TEOF, /* corresponds to trailing nul */
11714 TAND, TOR, TENDCASE /* if double occurrence */
11729 startlinno = g_parsefile->linno;
11730 for (;;) { /* until token or start of word found */
11732 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11736 while ((c = pgetc()) != '\n' && c != PEOF)
11739 } else if (c == '\\') {
11740 if (pgetc() != '\n') {
11742 break; /* return readtoken1(...) */
11744 startlinno = ++g_parsefile->linno;
11750 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11753 g_parsefile->linno++;
11754 needprompt = doprompt;
11757 p = strchr(xxreadtoken_chars, c);
11759 break; /* return readtoken1(...) */
11761 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11763 if (cc == c) { /* double occurrence? */
11764 p += xxreadtoken_doubles + 1;
11767 #if ENABLE_ASH_BASH_COMPAT
11768 if (c == '&' && cc == '>') /* &> */
11769 break; /* return readtoken1(...) */
11774 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11779 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11781 #else /* old xxreadtoken */
11782 #define RETURN(token) return lasttoken = token
11795 startlinno = g_parsefile->linno;
11796 for (;;) { /* until token or start of word found */
11799 case ' ': case '\t':
11800 IF_ASH_ALIAS(case PEOA:)
11803 while ((c = pgetc()) != '\n' && c != PEOF)
11808 if (pgetc() == '\n') {
11809 startlinno = ++g_parsefile->linno;
11817 g_parsefile->linno++;
11818 needprompt = doprompt;
11823 if (pgetc() == '&')
11828 if (pgetc() == '|')
11833 if (pgetc() == ';')
11846 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11849 #endif /* old xxreadtoken */
11856 smallint alreadyseen = tokpushback;
11859 #if ENABLE_ASH_ALIAS
11868 if (checkkwd & CHKNL) {
11875 if (t != TWORD || quoteflag) {
11880 * check for keywords
11882 if (checkkwd & CHKKWD) {
11883 const char *const *pp;
11885 pp = findkwd(wordtext);
11887 lasttoken = t = pp - tokname_array;
11888 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11893 if (checkkwd & CHKALIAS) {
11894 #if ENABLE_ASH_ALIAS
11896 ap = lookupalias(wordtext, 1);
11899 pushstring(ap->val, ap);
11909 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11911 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11923 return tokname_array[t][0];
11927 * Read and parse a command. Returns NODE_EOF on end of file.
11928 * (NULL is a valid parse tree indicating a blank line.)
11930 static union node *
11931 parsecmd(int interact)
11936 doprompt = interact;
11938 setprompt(doprompt);
11950 * Input any here documents.
11955 struct heredoc *here;
11958 here = heredoclist;
11959 heredoclist = NULL;
11965 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11966 here->eofmark, here->striptabs);
11967 n = stzalloc(sizeof(struct narg));
11968 n->narg.type = NARG;
11969 /*n->narg.next = NULL; - stzalloc did it */
11970 n->narg.text = wordtext;
11971 n->narg.backquote = backquotelist;
11972 here->here->nhere.doc = n;
11979 * called by editline -- any expansions to the prompt should be added here.
11981 #if ENABLE_ASH_EXPAND_PRMT
11982 static const char *
11983 expandstr(const char *ps)
11987 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11988 * and token processing _can_ alter it (delete NULs etc). */
11989 setinputstring((char *)ps);
11990 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11993 n.narg.type = NARG;
11994 n.narg.next = NULL;
11995 n.narg.text = wordtext;
11996 n.narg.backquote = backquotelist;
11998 expandarg(&n, NULL, 0);
11999 return stackblock();
12004 * Execute a command or commands contained in a string.
12007 evalstring(char *s, int mask)
12010 struct stackmark smark;
12014 setstackmark(&smark);
12017 while ((n = parsecmd(0)) != NODE_EOF) {
12019 popstackmark(&smark);
12032 * The eval command.
12034 static int FAST_FUNC
12035 evalcmd(int argc UNUSED_PARAM, char **argv)
12044 STARTSTACKSTR(concat);
12046 concat = stack_putstr(p, concat);
12050 STPUTC(' ', concat);
12052 STPUTC('\0', concat);
12053 p = grabstackstr(concat);
12055 evalstring(p, ~SKIPEVAL);
12062 * Read and execute commands.
12063 * "Top" is nonzero for the top level command loop;
12064 * it turns on prompting if the shell is interactive.
12070 struct stackmark smark;
12074 TRACE(("cmdloop(%d) called\n", top));
12078 setstackmark(&smark);
12081 showjobs(stderr, SHOW_CHANGED);
12084 if (iflag && top) {
12086 #if ENABLE_ASH_MAIL
12090 n = parsecmd(inter);
12092 if (DEBUG > 2 && debug && (n != NODE_EOF))
12095 if (n == NODE_EOF) {
12096 if (!top || numeof >= 50)
12098 if (!stoppedjobs()) {
12101 out2str("\nUse \"exit\" to leave shell.\n");
12104 } else if (nflag == 0) {
12105 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12110 popstackmark(&smark);
12115 return skip & SKIPEVAL;
12122 * Take commands from a file. To be compatible we should do a path
12123 * search for the file, which is necessary to find sub-commands.
12126 find_dot_file(char *name)
12129 const char *path = pathval();
12132 /* don't try this for absolute or relative paths */
12133 if (strchr(name, '/'))
12136 /* IIRC standards do not say whether . is to be searched.
12137 * And it is even smaller this way, making it unconditional for now:
12139 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12144 while ((fullname = path_advance(&path, name)) != NULL) {
12146 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12148 * Don't bother freeing here, since it will
12149 * be freed by the caller.
12153 if (fullname != name)
12154 stunalloc(fullname);
12157 /* not found in the PATH */
12158 ash_msg_and_raise_error("%s: not found", name);
12162 static int FAST_FUNC
12163 dotcmd(int argc, char **argv)
12166 struct strlist *sp;
12167 volatile struct shparam saveparam;
12169 for (sp = cmdenviron; sp; sp = sp->next)
12170 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12173 /* bash says: "bash: .: filename argument required" */
12174 return 2; /* bash compat */
12177 /* "false; . empty_file; echo $?" should print 0, not 1: */
12180 fullname = find_dot_file(argv[1]);
12184 if (argc) { /* argc > 0, argv[0] != NULL */
12185 saveparam = shellparam;
12186 shellparam.malloced = 0;
12187 shellparam.nparam = argc;
12188 shellparam.p = argv;
12191 setinputfile(fullname, INPUT_PUSH_FILE);
12192 commandname = fullname;
12197 freeparam(&shellparam);
12198 shellparam = saveparam;
12204 static int FAST_FUNC
12205 exitcmd(int argc UNUSED_PARAM, char **argv)
12210 exitstatus = number(argv[1]);
12211 raise_exception(EXEXIT);
12216 * Read a file containing shell functions.
12219 readcmdfile(char *name)
12221 setinputfile(name, INPUT_PUSH_FILE);
12227 /* ============ find_command inplementation */
12230 * Resolve a command name. If you change this routine, you may have to
12231 * change the shellexec routine as well.
12234 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12236 struct tblentry *cmdp;
12243 struct builtincmd *bcmd;
12245 /* If name contains a slash, don't use PATH or hash table */
12246 if (strchr(name, '/') != NULL) {
12247 entry->u.index = -1;
12248 if (act & DO_ABS) {
12249 while (stat(name, &statb) < 0) {
12251 if (errno == EINTR)
12254 entry->cmdtype = CMDUNKNOWN;
12258 entry->cmdtype = CMDNORMAL;
12262 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12264 updatetbl = (path == pathval());
12267 if (strstr(path, "%builtin") != NULL)
12268 act |= DO_ALTBLTIN;
12271 /* If name is in the table, check answer will be ok */
12272 cmdp = cmdlookup(name, 0);
12273 if (cmdp != NULL) {
12276 switch (cmdp->cmdtype) {
12294 } else if (cmdp->rehash == 0)
12295 /* if not invalidated by cd, we're done */
12299 /* If %builtin not in path, check for builtin next */
12300 bcmd = find_builtin(name);
12302 if (IS_BUILTIN_REGULAR(bcmd))
12303 goto builtin_success;
12304 if (act & DO_ALTPATH) {
12305 if (!(act & DO_ALTBLTIN))
12306 goto builtin_success;
12307 } else if (builtinloc <= 0) {
12308 goto builtin_success;
12312 #if ENABLE_FEATURE_SH_STANDALONE
12314 int applet_no = find_applet_by_name(name);
12315 if (applet_no >= 0) {
12316 entry->cmdtype = CMDNORMAL;
12317 entry->u.index = -2 - applet_no;
12323 /* We have to search path. */
12324 prev = -1; /* where to start */
12325 if (cmdp && cmdp->rehash) { /* doing a rehash */
12326 if (cmdp->cmdtype == CMDBUILTIN)
12329 prev = cmdp->param.index;
12335 while ((fullname = path_advance(&path, name)) != NULL) {
12336 stunalloc(fullname);
12337 /* NB: code below will still use fullname
12338 * despite it being "unallocated" */
12341 if (prefix(pathopt, "builtin")) {
12343 goto builtin_success;
12346 if ((act & DO_NOFUNC)
12347 || !prefix(pathopt, "func")
12348 ) { /* ignore unimplemented options */
12352 /* if rehash, don't redo absolute path names */
12353 if (fullname[0] == '/' && idx <= prev) {
12356 TRACE(("searchexec \"%s\": no change\n", name));
12359 while (stat(fullname, &statb) < 0) {
12361 if (errno == EINTR)
12364 if (errno != ENOENT && errno != ENOTDIR)
12368 e = EACCES; /* if we fail, this will be the error */
12369 if (!S_ISREG(statb.st_mode))
12371 if (pathopt) { /* this is a %func directory */
12372 stalloc(strlen(fullname) + 1);
12373 /* NB: stalloc will return space pointed by fullname
12374 * (because we don't have any intervening allocations
12375 * between stunalloc above and this stalloc) */
12376 readcmdfile(fullname);
12377 cmdp = cmdlookup(name, 0);
12378 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12379 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12380 stunalloc(fullname);
12383 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12385 entry->cmdtype = CMDNORMAL;
12386 entry->u.index = idx;
12390 cmdp = cmdlookup(name, 1);
12391 cmdp->cmdtype = CMDNORMAL;
12392 cmdp->param.index = idx;
12397 /* We failed. If there was an entry for this command, delete it */
12398 if (cmdp && updatetbl)
12399 delete_cmd_entry();
12401 ash_msg("%s: %s", name, errmsg(e, "not found"));
12402 entry->cmdtype = CMDUNKNOWN;
12407 entry->cmdtype = CMDBUILTIN;
12408 entry->u.cmd = bcmd;
12412 cmdp = cmdlookup(name, 1);
12413 cmdp->cmdtype = CMDBUILTIN;
12414 cmdp->param.cmd = bcmd;
12418 entry->cmdtype = cmdp->cmdtype;
12419 entry->u = cmdp->param;
12423 /* ============ trap.c */
12426 * The trap builtin.
12428 static int FAST_FUNC
12429 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12433 int signo, exitcode;
12438 for (signo = 0; signo < NSIG; signo++) {
12439 char *tr = trap_ptr[signo];
12441 /* note: bash adds "SIG", but only if invoked
12442 * as "bash". If called as "sh", or if set -o posix,
12443 * then it prints short signal names.
12444 * We are printing short names: */
12445 out1fmt("trap -- %s %s\n",
12447 get_signame(signo));
12448 /* trap_ptr != trap only if we are in special-cased `trap` code.
12449 * In this case, we will exit very soon, no need to free(). */
12450 /* if (trap_ptr != trap && tp[0]) */
12455 if (trap_ptr != trap) {
12468 signo = get_signum(*ap);
12470 /* Mimic bash message exactly */
12471 ash_msg("%s: invalid signal specification", *ap);
12477 if (LONE_DASH(action))
12480 action = ckstrdup(action);
12484 may_have_traps = 1;
12485 trap[signo] = action;
12496 /* ============ Builtins */
12498 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12500 * Lists available builtins
12502 static int FAST_FUNC
12503 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12509 "Built-in commands:\n"
12510 "------------------\n");
12511 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12512 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12513 builtintab[i].name + 1);
12519 #if ENABLE_FEATURE_SH_STANDALONE
12521 const char *a = applet_names;
12523 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12528 a += strlen(a) + 1;
12533 return EXIT_SUCCESS;
12535 #endif /* FEATURE_SH_EXTRA_QUIET */
12538 * The export and readonly commands.
12540 static int FAST_FUNC
12541 exportcmd(int argc UNUSED_PARAM, char **argv)
12547 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12549 if (nextopt("p") != 'p') {
12554 p = strchr(name, '=');
12558 vp = *findvar(hashvar(name), name);
12564 setvar(name, p, flag);
12565 } while ((name = *++aptr) != NULL);
12569 showvars(argv[0], flag, 0);
12574 * Delete a function if it exists.
12577 unsetfunc(const char *name)
12579 struct tblentry *cmdp;
12581 cmdp = cmdlookup(name, 0);
12582 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12583 delete_cmd_entry();
12587 * The unset builtin command. We unset the function before we unset the
12588 * variable to allow a function to be unset when there is a readonly variable
12589 * with the same name.
12591 static int FAST_FUNC
12592 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12599 while ((i = nextopt("vf")) != 0) {
12603 for (ap = argptr; *ap; ap++) {
12616 static const unsigned char timescmd_str[] ALIGN1 = {
12617 ' ', offsetof(struct tms, tms_utime),
12618 '\n', offsetof(struct tms, tms_stime),
12619 ' ', offsetof(struct tms, tms_cutime),
12620 '\n', offsetof(struct tms, tms_cstime),
12623 static int FAST_FUNC
12624 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12626 unsigned long clk_tck, s, t;
12627 const unsigned char *p;
12630 clk_tck = sysconf(_SC_CLK_TCK);
12635 t = *(clock_t *)(((char *) &buf) + p[1]);
12638 out1fmt("%lum%lu.%03lus%c",
12640 (t * 1000) / clk_tck,
12648 #if ENABLE_SH_MATH_SUPPORT
12650 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12651 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12653 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12655 static int FAST_FUNC
12656 letcmd(int argc UNUSED_PARAM, char **argv)
12662 ash_msg_and_raise_error("expression expected");
12664 i = ash_arith(*argv);
12672 * The read builtin. Options:
12673 * -r Do not interpret '\' specially
12674 * -s Turn off echo (tty only)
12675 * -n NCHARS Read NCHARS max
12676 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12677 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12678 * -u FD Read from given FD instead of fd 0
12679 * This uses unbuffered input, which may be avoidable in some cases.
12680 * TODO: bash also has:
12681 * -a ARRAY Read into array[0],[1],etc
12682 * -d DELIM End on DELIM char, not newline
12683 * -e Use line editing (tty only)
12685 static int FAST_FUNC
12686 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12688 char *opt_n = NULL;
12689 char *opt_p = NULL;
12690 char *opt_t = NULL;
12691 char *opt_u = NULL;
12692 int read_flags = 0;
12696 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12705 read_flags |= BUILTIN_READ_SILENT;
12711 read_flags |= BUILTIN_READ_RAW;
12721 r = shell_builtin_read(setvar2,
12723 bltinlookup("IFS"), /* can be NULL */
12731 if ((uintptr_t)r > 1)
12732 ash_msg_and_raise_error(r);
12734 return (uintptr_t)r;
12737 static int FAST_FUNC
12738 umaskcmd(int argc UNUSED_PARAM, char **argv)
12740 static const char permuser[3] ALIGN1 = "ugo";
12741 static const char permmode[3] ALIGN1 = "rwx";
12742 static const short permmask[] ALIGN2 = {
12743 S_IRUSR, S_IWUSR, S_IXUSR,
12744 S_IRGRP, S_IWGRP, S_IXGRP,
12745 S_IROTH, S_IWOTH, S_IXOTH
12748 /* TODO: use bb_parse_mode() instead */
12753 int symbolic_mode = 0;
12755 while (nextopt("S") != '\0') {
12766 if (symbolic_mode) {
12770 for (i = 0; i < 3; i++) {
12773 *p++ = permuser[i];
12775 for (j = 0; j < 3; j++) {
12776 if ((mask & permmask[3 * i + j]) == 0) {
12777 *p++ = permmode[j];
12785 out1fmt("%.4o\n", mask);
12788 if (isdigit((unsigned char) *ap)) {
12791 if (*ap >= '8' || *ap < '0')
12792 ash_msg_and_raise_error(msg_illnum, argv[1]);
12793 mask = (mask << 3) + (*ap - '0');
12794 } while (*++ap != '\0');
12797 mask = ~mask & 0777;
12798 if (!bb_parse_mode(ap, &mask)) {
12799 ash_msg_and_raise_error("illegal mode: %s", ap);
12801 umask(~mask & 0777);
12807 static int FAST_FUNC
12808 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12810 return shell_builtin_ulimit(argv);
12813 /* ============ main() and helpers */
12816 * Called to exit the shell.
12818 static void exitshell(void) NORETURN;
12826 status = exitstatus;
12827 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12828 if (setjmp(loc.loc)) {
12829 if (exception_type == EXEXIT)
12830 /* dash bug: it just does _exit(exitstatus) here
12831 * but we have to do setjobctl(0) first!
12832 * (bug is still not fixed in dash-0.5.3 - if you run dash
12833 * under Midnight Commander, on exit from dash MC is backgrounded) */
12834 status = exitstatus;
12837 exception_handler = &loc;
12844 flush_stdout_stderr();
12854 /* from input.c: */
12855 /* we will never free this */
12856 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12859 signal(SIGCHLD, SIG_DFL);
12860 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12861 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12863 signal(SIGHUP, SIG_DFL);
12869 struct stat st1, st2;
12872 for (envp = environ; envp && *envp; envp++) {
12873 if (strchr(*envp, '=')) {
12874 setvareq(*envp, VEXPORT|VTEXTFIXED);
12878 setvar("PPID", utoa(getppid()), 0);
12880 p = lookupvar("PWD");
12882 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12883 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12890 * Process the shell command line arguments.
12893 procargs(char **argv)
12896 const char *xminusc;
12901 /* if (xargv[0]) - mmm, this is always true! */
12903 for (i = 0; i < NOPTS; i++)
12907 /* it already printed err message */
12908 raise_exception(EXERROR);
12912 if (*xargv == NULL) {
12914 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12917 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12921 for (i = 0; i < NOPTS; i++)
12922 if (optlist[i] == 2)
12927 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12932 } else if (!sflag) {
12933 setinputfile(*xargv, 0);
12936 commandname = arg0;
12939 shellparam.p = xargv;
12940 #if ENABLE_ASH_GETOPTS
12941 shellparam.optind = 1;
12942 shellparam.optoff = -1;
12944 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12946 shellparam.nparam++;
12953 * Read /etc/profile or .profile.
12956 read_profile(const char *name)
12960 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12969 * This routine is called when an error or an interrupt occurs in an
12970 * interactive shell and control is returned to the main command loop.
12978 /* from input.c: */
12979 g_parsefile->left_in_buffer = 0;
12980 g_parsefile->left_in_line = 0; /* clear input buffer */
12982 /* from parser.c: */
12985 /* from redir.c: */
12986 clearredir(/*drop:*/ 0);
12990 static short profile_buf[16384];
12991 extern int etext();
12995 * Main routine. We initialize things, parse the arguments, execute
12996 * profiles if we're a login shell, and then call cmdloop to execute
12997 * commands. The setjmp call sets up the location to jump to when an
12998 * exception occurs. When an exception occurs the variable "state"
12999 * is used to figure out how far we had gotten.
13001 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13002 int ash_main(int argc UNUSED_PARAM, char **argv)
13004 const char *shinit;
13005 volatile smallint state;
13006 struct jmploc jmploc;
13007 struct stackmark smark;
13009 /* Initialize global data */
13013 #if ENABLE_ASH_ALIAS
13019 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13022 #if ENABLE_FEATURE_EDITING
13023 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13026 if (setjmp(jmploc.loc)) {
13032 e = exception_type;
13036 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13039 outcslow('\n', stderr);
13041 popstackmark(&smark);
13042 FORCE_INT_ON; /* enable interrupts */
13051 exception_handler = &jmploc;
13054 TRACE(("Shell args: "));
13055 trace_puts_args(argv);
13057 rootpid = getpid();
13060 setstackmark(&smark);
13063 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13065 const char *hp = lookupvar("HISTFILE");
13068 hp = lookupvar("HOME");
13070 char *defhp = concat_path_file(hp, ".ash_history");
13071 setvar("HISTFILE", defhp, 0);
13077 if (/* argv[0] && */ argv[0][0] == '-')
13081 read_profile("/etc/profile");
13084 read_profile(".profile");
13090 getuid() == geteuid() && getgid() == getegid() &&
13094 shinit = lookupvar("ENV");
13095 if (shinit != NULL && *shinit != '\0') {
13096 read_profile(shinit);
13102 /* evalstring pushes parsefile stack.
13103 * Ensure we don't falsely claim that 0 (stdin)
13104 * is one of stacked source fds.
13105 * Testcase: ash -c 'exec 1>&0' must not complain. */
13106 // if (!sflag) g_parsefile->pf_fd = -1;
13107 // ^^ not necessary since now we special-case fd 0
13108 // in is_hidden_fd() to not be considered "hidden fd"
13109 evalstring(minusc, 0);
13112 if (sflag || minusc == NULL) {
13113 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13115 const char *hp = lookupvar("HISTFILE");
13117 line_input_state->hist_file = hp;
13120 state4: /* XXX ??? - why isn't this before the "if" statement */
13128 extern void _mcleanup(void);
13138 * Copyright (c) 1989, 1991, 1993, 1994
13139 * The Regents of the University of California. All rights reserved.
13141 * This code is derived from software contributed to Berkeley by
13142 * Kenneth Almquist.
13144 * Redistribution and use in source and binary forms, with or without
13145 * modification, are permitted provided that the following conditions
13147 * 1. Redistributions of source code must retain the above copyright
13148 * notice, this list of conditions and the following disclaimer.
13149 * 2. Redistributions in binary form must reproduce the above copyright
13150 * notice, this list of conditions and the following disclaimer in the
13151 * documentation and/or other materials provided with the distribution.
13152 * 3. Neither the name of the University nor the names of its contributors
13153 * may be used to endorse or promote products derived from this software
13154 * without specific prior written permission.
13156 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13157 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13158 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13159 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13160 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13161 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13162 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13163 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13164 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13165 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF