1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
30 /* Tweak debug output verbosity here */
37 #define JOBS ENABLE_ASH_JOB_CONTROL
39 #include "busybox.h" /* for applet_names */
43 #include <sys/times.h>
45 #include "shell_common.h"
46 #if ENABLE_SH_MATH_SUPPORT
49 #if ENABLE_ASH_RANDOM_SUPPORT
52 # define CLEAR_RANDOM_T(rnd) ((void)0)
55 #include "NUM_APPLETS.h"
57 /* STANDALONE does not make sense, and won't compile */
58 # undef CONFIG_FEATURE_SH_STANDALONE
59 # undef ENABLE_FEATURE_SH_STANDALONE
60 # undef IF_FEATURE_SH_STANDALONE
61 # undef IF_NOT_FEATURE_SH_STANDALONE
62 # define ENABLE_FEATURE_SH_STANDALONE 0
63 # define IF_FEATURE_SH_STANDALONE(...)
64 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
68 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
72 # error "Do not even bother, ash will not run on NOMMU machine"
75 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
76 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
77 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
79 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
80 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
85 //config: depends on !NOMMU
87 //config: Tha 'ash' shell adds about 60k in the default configuration and is
88 //config: the most complete and most pedantically correct shell included with
89 //config: busybox. This shell is actually a derivative of the Debian 'dash'
90 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
91 //config: (written by Kenneth Almquist) from NetBSD.
93 //config:config ASH_BASH_COMPAT
94 //config: bool "bash-compatible extensions"
96 //config: depends on ASH
98 //config: Enable bash-compatible extensions.
100 //config:config ASH_JOB_CONTROL
101 //config: bool "Job control"
103 //config: depends on ASH
105 //config: Enable job control in the ash shell.
107 //config:config ASH_ALIAS
108 //config: bool "alias support"
110 //config: depends on ASH
112 //config: Enable alias support in the ash shell.
114 //config:config ASH_GETOPTS
115 //config: bool "Builtin getopt to parse positional parameters"
117 //config: depends on ASH
119 //config: Enable getopts builtin in the ash shell.
121 //config:config ASH_BUILTIN_ECHO
122 //config: bool "Builtin version of 'echo'"
124 //config: depends on ASH
126 //config: Enable support for echo, builtin to ash.
128 //config:config ASH_BUILTIN_PRINTF
129 //config: bool "Builtin version of 'printf'"
131 //config: depends on ASH
133 //config: Enable support for printf, builtin to ash.
135 //config:config ASH_BUILTIN_TEST
136 //config: bool "Builtin version of 'test'"
138 //config: depends on ASH
140 //config: Enable support for test, builtin to ash.
142 //config:config ASH_CMDCMD
143 //config: bool "'command' command to override shell builtins"
145 //config: depends on ASH
147 //config: Enable support for the ash 'command' builtin, which allows
148 //config: you to run the specified command with the specified arguments,
149 //config: even when there is an ash builtin command with the same name.
151 //config:config ASH_MAIL
152 //config: bool "Check for new mail on interactive shells"
154 //config: depends on ASH
156 //config: Enable "check for new mail" in the ash shell.
158 //config:config ASH_OPTIMIZE_FOR_SIZE
159 //config: bool "Optimize for size instead of speed"
161 //config: depends on ASH
163 //config: Compile ash for reduced size at the price of speed.
165 //config:config ASH_RANDOM_SUPPORT
166 //config: bool "Pseudorandom generator and $RANDOM variable"
168 //config: depends on ASH
170 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
171 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
172 //config: You can reset the generator by using a specified start value.
173 //config: After "unset RANDOM" the generator will switch off and this
174 //config: variable will no longer have special treatment.
176 //config:config ASH_EXPAND_PRMT
177 //config: bool "Expand prompt string"
179 //config: depends on ASH
181 //config: "PS#" may contain volatile content, such as backquote commands.
182 //config: This option recreates the prompt string from the environment
183 //config: variable each time it is displayed.
186 //usage:#define ash_trivial_usage NOUSAGE_STR
187 //usage:#define ash_full_usage ""
188 //usage:#define sh_trivial_usage NOUSAGE_STR
189 //usage:#define sh_full_usage ""
190 //usage:#define bash_trivial_usage NOUSAGE_STR
191 //usage:#define bash_full_usage ""
194 /* ============ Hash table sizes. Configurable. */
198 #define CMDTABLESIZE 31 /* should be prime */
201 /* ============ Shell options */
203 static const char *const optletters_optnames[] = {
218 #if ENABLE_ASH_BASH_COMPAT
227 #define optletters(n) optletters_optnames[n][0]
228 #define optnames(n) (optletters_optnames[n] + 1)
230 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
233 /* ============ Misc data */
235 #define msg_illnum "Illegal number: %s"
238 * We enclose jmp_buf in a structure so that we can declare pointers to
239 * jump locations. The global variable handler contains the location to
240 * jump to when an exception occurs, and the global variable exception_type
241 * contains a code identifying the exception. To implement nested
242 * exception handlers, the user should save the value of handler on entry
243 * to an inner scope, set handler to point to a jmploc structure for the
244 * inner scope, and restore handler on exit from the scope.
250 struct globals_misc {
251 /* pid of main shell */
253 /* shell level: 0 for the main shell, 1 for its children, and so on */
255 #define rootshell (!shlvl)
256 char *minusc; /* argument to -c option */
258 char *curdir; // = nullstr; /* current working directory */
259 char *physdir; // = nullstr; /* physical working directory */
261 char *arg0; /* value of $0 */
263 struct jmploc *exception_handler;
265 volatile int suppress_int; /* counter */
266 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
267 /* last pending signal */
268 volatile /*sig_atomic_t*/ smallint pending_sig;
269 smallint exception_type; /* kind of exception (0..5) */
271 #define EXINT 0 /* SIGINT received */
272 #define EXERROR 1 /* a generic error */
273 #define EXSHELLPROC 2 /* execute a shell procedure */
274 #define EXEXEC 3 /* command execution failed */
275 #define EXEXIT 4 /* exit the shell */
276 #define EXSIG 5 /* trapped signal in wait(1) */
279 char nullstr[1]; /* zero length string */
282 #define eflag optlist[0]
283 #define fflag optlist[1]
284 #define Iflag optlist[2]
285 #define iflag optlist[3]
286 #define mflag optlist[4]
287 #define nflag optlist[5]
288 #define sflag optlist[6]
289 #define xflag optlist[7]
290 #define vflag optlist[8]
291 #define Cflag optlist[9]
292 #define aflag optlist[10]
293 #define bflag optlist[11]
294 #define uflag optlist[12]
295 #define viflag optlist[13]
296 #if ENABLE_ASH_BASH_COMPAT
297 # define pipefail optlist[14]
302 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
303 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
306 /* trap handler commands */
308 * Sigmode records the current value of the signal handlers for the various
309 * modes. A value of zero means that the current handler is not known.
310 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
312 char sigmode[NSIG - 1];
313 #define S_DFL 1 /* default signal handling (SIG_DFL) */
314 #define S_CATCH 2 /* signal is caught */
315 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
316 #define S_HARD_IGN 4 /* signal is ignored permenantly */
318 /* indicates specified signal received */
319 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
320 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
322 char **trap_ptr; /* used only by "trap hack" */
324 /* Rarely referenced stuff */
325 #if ENABLE_ASH_RANDOM_SUPPORT
328 pid_t backgndpid; /* pid of last background process */
329 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
331 extern struct globals_misc *const ash_ptr_to_globals_misc;
332 #define G_misc (*ash_ptr_to_globals_misc)
333 #define rootpid (G_misc.rootpid )
334 #define shlvl (G_misc.shlvl )
335 #define minusc (G_misc.minusc )
336 #define curdir (G_misc.curdir )
337 #define physdir (G_misc.physdir )
338 #define arg0 (G_misc.arg0 )
339 #define exception_handler (G_misc.exception_handler)
340 #define exception_type (G_misc.exception_type )
341 #define suppress_int (G_misc.suppress_int )
342 #define pending_int (G_misc.pending_int )
343 #define pending_sig (G_misc.pending_sig )
344 #define isloginsh (G_misc.isloginsh )
345 #define nullstr (G_misc.nullstr )
346 #define optlist (G_misc.optlist )
347 #define sigmode (G_misc.sigmode )
348 #define gotsig (G_misc.gotsig )
349 #define may_have_traps (G_misc.may_have_traps )
350 #define trap (G_misc.trap )
351 #define trap_ptr (G_misc.trap_ptr )
352 #define random_gen (G_misc.random_gen )
353 #define backgndpid (G_misc.backgndpid )
354 #define job_warning (G_misc.job_warning)
355 #define INIT_G_misc() do { \
356 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
364 /* ============ DEBUG */
366 static void trace_printf(const char *fmt, ...);
367 static void trace_vprintf(const char *fmt, va_list va);
368 # define TRACE(param) trace_printf param
369 # define TRACEV(param) trace_vprintf param
370 # define close(fd) do { \
372 if (close(dfd) < 0) \
373 bb_error_msg("bug on %d: closing %d(0x%x)", \
374 __LINE__, dfd, dfd); \
377 # define TRACE(param)
378 # define TRACEV(param)
382 /* ============ Utility functions */
383 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
385 static int isdigit_str9(const char *str)
387 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
388 while (--maxlen && isdigit(*str))
390 return (*str == '\0');
393 static const char *var_end(const char *var)
402 /* ============ Interrupts / exceptions */
404 * These macros allow the user to suspend the handling of interrupt signals
405 * over a period of time. This is similar to SIGHOLD or to sigblock, but
406 * much more efficient and portable. (But hacking the kernel is so much
407 * more fun than worrying about efficiency and portability. :-))
409 #define INT_OFF do { \
415 * Called to raise an exception. Since C doesn't include exceptions, we
416 * just do a longjmp to the exception handler. The type of exception is
417 * stored in the global variable "exception_type".
419 static void raise_exception(int) NORETURN;
421 raise_exception(int e)
424 if (exception_handler == NULL)
429 longjmp(exception_handler->loc, 1);
432 #define raise_exception(e) do { \
433 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
434 raise_exception(e); \
439 * Called from trap.c when a SIGINT is received. (If the user specifies
440 * that SIGINT is to be trapped or ignored using the trap builtin, then
441 * this routine is not called.) Suppressint is nonzero when interrupts
442 * are held using the INT_OFF macro. (The test for iflag is just
443 * defensive programming.)
445 static void raise_interrupt(void) NORETURN;
447 raise_interrupt(void)
452 /* Signal is not automatically unmasked after it is raised,
453 * do it ourself - unmask all signals */
454 sigprocmask_allsigs(SIG_UNBLOCK);
455 /* pending_sig = 0; - now done in signal_handler() */
458 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
459 if (!(rootshell && iflag)) {
460 /* Kill ourself with SIGINT */
461 signal(SIGINT, SIG_DFL);
466 raise_exception(ex_type);
470 #define raise_interrupt() do { \
471 TRACE(("raising interrupt on line %d\n", __LINE__)); \
476 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
480 if (--suppress_int == 0 && pending_int) {
484 #define INT_ON int_on()
485 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
493 #define FORCE_INT_ON force_int_on()
495 #define SAVE_INT(v) ((v) = suppress_int)
497 #define RESTORE_INT(v) do { \
499 suppress_int = (v); \
500 if (suppress_int == 0 && pending_int) \
505 /* ============ Stdout/stderr output */
508 outstr(const char *p, FILE *file)
516 flush_stdout_stderr(void)
524 outcslow(int c, FILE *dest)
532 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
534 out1fmt(const char *fmt, ...)
541 r = vprintf(fmt, ap);
547 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
549 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
556 ret = vsnprintf(outbuf, length, fmt, ap);
563 out1str(const char *p)
569 out2str(const char *p)
572 flush_stdout_stderr();
576 /* ============ Parser structures */
578 /* control characters in argument strings */
579 #define CTL_FIRST CTLESC
580 #define CTLESC ((unsigned char)'\201') /* escape next character */
581 #define CTLVAR ((unsigned char)'\202') /* variable defn */
582 #define CTLENDVAR ((unsigned char)'\203')
583 #define CTLBACKQ ((unsigned char)'\204')
584 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
585 /* CTLBACKQ | CTLQUOTE == '\205' */
586 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
587 #define CTLENDARI ((unsigned char)'\207')
588 #define CTLQUOTEMARK ((unsigned char)'\210')
589 #define CTL_LAST CTLQUOTEMARK
591 /* variable substitution byte (follows CTLVAR) */
592 #define VSTYPE 0x0f /* type of variable substitution */
593 #define VSNUL 0x10 /* colon--treat the empty string as unset */
594 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
596 /* values of VSTYPE field */
597 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
598 #define VSMINUS 0x2 /* ${var-text} */
599 #define VSPLUS 0x3 /* ${var+text} */
600 #define VSQUESTION 0x4 /* ${var?message} */
601 #define VSASSIGN 0x5 /* ${var=text} */
602 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
603 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
604 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
605 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
606 #define VSLENGTH 0xa /* ${#var} */
607 #if ENABLE_ASH_BASH_COMPAT
608 #define VSSUBSTR 0xc /* ${var:position:length} */
609 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
610 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
613 static const char dolatstr[] ALIGN1 = {
614 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
634 #if ENABLE_ASH_BASH_COMPAT
651 smallint type; /* Nxxxx */
654 union node *redirect;
659 smallint pipe_backgnd;
660 struct nodelist *cmdlist;
666 union node *redirect;
679 union node *elsepart;
706 struct nodelist *backquote;
709 /* nfile and ndup layout must match!
710 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
711 * that it is actually NTO2 (>&file), and change its type.
728 char *_unused_expfname;
747 struct nredir nredir;
748 struct nbinary nbinary;
752 struct nclist nclist;
761 * NODE_EOF is returned by parsecmd when it encounters an end of file.
762 * It must be distinct from NULL.
764 #define NODE_EOF ((union node *) -1L)
767 struct nodelist *next;
780 freefunc(struct funcnode *f)
782 if (f && --f->count < 0)
787 /* ============ Debugging output */
791 static FILE *tracefile;
794 trace_printf(const char *fmt, ...)
801 fprintf(tracefile, "%u ", (int) time(NULL));
803 fprintf(tracefile, "[%u] ", (int) getpid());
805 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
807 vfprintf(tracefile, fmt, va);
812 trace_vprintf(const char *fmt, va_list va)
817 fprintf(tracefile, "%u ", (int) time(NULL));
819 fprintf(tracefile, "[%u] ", (int) getpid());
821 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
822 vfprintf(tracefile, fmt, va);
826 trace_puts(const char *s)
834 trace_puts_quoted(char *s)
841 putc('"', tracefile);
842 for (p = s; *p; p++) {
843 switch ((unsigned char)*p) {
844 case '\n': c = 'n'; goto backslash;
845 case '\t': c = 't'; goto backslash;
846 case '\r': c = 'r'; goto backslash;
847 case '\"': c = '\"'; goto backslash;
848 case '\\': c = '\\'; goto backslash;
849 case CTLESC: c = 'e'; goto backslash;
850 case CTLVAR: c = 'v'; goto backslash;
851 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
852 case CTLBACKQ: c = 'q'; goto backslash;
853 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
855 putc('\\', tracefile);
859 if (*p >= ' ' && *p <= '~')
862 putc('\\', tracefile);
863 putc((*p >> 6) & 03, tracefile);
864 putc((*p >> 3) & 07, tracefile);
865 putc(*p & 07, tracefile);
870 putc('"', tracefile);
874 trace_puts_args(char **ap)
881 trace_puts_quoted(*ap);
883 putc('\n', tracefile);
886 putc(' ', tracefile);
901 /* leave open because libedit might be using it */
904 strcpy(s, "./trace");
906 if (!freopen(s, "a", tracefile)) {
907 fprintf(stderr, "Can't re-open %s\n", s);
912 tracefile = fopen(s, "a");
913 if (tracefile == NULL) {
914 fprintf(stderr, "Can't open %s\n", s);
920 flags = fcntl(fileno(tracefile), F_GETFL);
922 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
924 setlinebuf(tracefile);
925 fputs("\nTracing started.\n", tracefile);
929 indent(int amount, char *pfx, FILE *fp)
933 for (i = 0; i < amount; i++) {
934 if (pfx && i == amount - 1)
940 /* little circular references here... */
941 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
944 sharg(union node *arg, FILE *fp)
947 struct nodelist *bqlist;
948 unsigned char subtype;
950 if (arg->type != NARG) {
951 out1fmt("<node type %d>\n", arg->type);
954 bqlist = arg->narg.backquote;
955 for (p = arg->narg.text; *p; p++) {
956 switch ((unsigned char)*p) {
965 if (subtype == VSLENGTH)
976 switch (subtype & VSTYPE) {
1002 case VSTRIMRIGHTMAX:
1009 out1fmt("<subtype %d>", subtype);
1016 case CTLBACKQ|CTLQUOTE:
1019 shtree(bqlist->n, -1, NULL, fp);
1030 shcmd(union node *cmd, FILE *fp)
1038 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1044 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1048 switch (np->nfile.type) {
1049 case NTO: s = ">>"+1; dftfd = 1; break;
1050 case NCLOBBER: s = ">|"; dftfd = 1; break;
1051 case NAPPEND: s = ">>"; dftfd = 1; break;
1052 #if ENABLE_ASH_BASH_COMPAT
1055 case NTOFD: s = ">&"; dftfd = 1; break;
1056 case NFROM: s = "<"; break;
1057 case NFROMFD: s = "<&"; break;
1058 case NFROMTO: s = "<>"; break;
1059 default: s = "*error*"; break;
1061 if (np->nfile.fd != dftfd)
1062 fprintf(fp, "%d", np->nfile.fd);
1064 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1065 fprintf(fp, "%d", np->ndup.dupfd);
1067 sharg(np->nfile.fname, fp);
1074 shtree(union node *n, int ind, char *pfx, FILE *fp)
1076 struct nodelist *lp;
1082 indent(ind, pfx, fp);
1084 if (n == NODE_EOF) {
1099 shtree(n->nbinary.ch1, ind, NULL, fp);
1102 shtree(n->nbinary.ch2, ind, NULL, fp);
1110 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1111 shtree(lp->n, 0, NULL, fp);
1115 if (n->npipe.pipe_backgnd)
1121 fprintf(fp, "<node type %d>", n->type);
1129 showtree(union node *n)
1131 trace_puts("showtree called\n");
1132 shtree(n, 1, NULL, stderr);
1138 /* ============ Parser data */
1141 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1144 struct strlist *next;
1151 struct strpush *prev; /* preceding string on stack */
1153 int prev_left_in_line;
1154 #if ENABLE_ASH_ALIAS
1155 struct alias *ap; /* if push was associated with an alias */
1157 char *string; /* remember the string since it may change */
1161 struct parsefile *prev; /* preceding file on stack */
1162 int linno; /* current line */
1163 int pf_fd; /* file descriptor (or -1 if string) */
1164 int left_in_line; /* number of chars left in this line */
1165 int left_in_buffer; /* number of chars left in this buffer past the line */
1166 char *next_to_pgetc; /* next char in buffer */
1167 char *buf; /* input buffer */
1168 struct strpush *strpush; /* for pushing strings at this level */
1169 struct strpush basestrpush; /* so pushing one is fast */
1172 static struct parsefile basepf; /* top level input file */
1173 static struct parsefile *g_parsefile = &basepf; /* current input file */
1174 static int startlinno; /* line # where last token started */
1175 static char *commandname; /* currently executing command */
1176 static struct strlist *cmdenviron; /* environment for builtin command */
1177 static uint8_t exitstatus; /* exit status of last command */
1180 /* ============ Message printing */
1183 ash_vmsg(const char *msg, va_list ap)
1185 fprintf(stderr, "%s: ", arg0);
1187 if (strcmp(arg0, commandname))
1188 fprintf(stderr, "%s: ", commandname);
1189 if (!iflag || g_parsefile->pf_fd > 0)
1190 fprintf(stderr, "line %d: ", startlinno);
1192 vfprintf(stderr, msg, ap);
1193 outcslow('\n', stderr);
1197 * Exverror is called to raise the error exception. If the second argument
1198 * is not NULL then error prints an error message using printf style
1199 * formatting. It then raises the error exception.
1201 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1203 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1207 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1209 TRACE(("\") pid=%d\n", getpid()));
1211 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1216 flush_stdout_stderr();
1217 raise_exception(cond);
1221 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1223 ash_msg_and_raise_error(const char *msg, ...)
1228 ash_vmsg_and_raise(EXERROR, msg, ap);
1233 static void raise_error_syntax(const char *) NORETURN;
1235 raise_error_syntax(const char *msg)
1237 ash_msg_and_raise_error("syntax error: %s", msg);
1241 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1243 ash_msg_and_raise(int cond, const char *msg, ...)
1248 ash_vmsg_and_raise(cond, msg, ap);
1254 * error/warning routines for external builtins
1257 ash_msg(const char *fmt, ...)
1267 * Return a string describing an error. The returned string may be a
1268 * pointer to a static buffer that will be overwritten on the next call.
1269 * Action describes the operation that got the error.
1272 errmsg(int e, const char *em)
1274 if (e == ENOENT || e == ENOTDIR) {
1281 /* ============ Memory allocation */
1284 /* I consider these wrappers nearly useless:
1285 * ok, they return you to nearest exception handler, but
1286 * how much memory do you leak in the process, making
1287 * memory starvation worse?
1290 ckrealloc(void * p, size_t nbytes)
1292 p = realloc(p, nbytes);
1294 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1299 ckmalloc(size_t nbytes)
1301 return ckrealloc(NULL, nbytes);
1305 ckzalloc(size_t nbytes)
1307 return memset(ckmalloc(nbytes), 0, nbytes);
1311 ckstrdup(const char *s)
1313 char *p = strdup(s);
1315 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1319 /* Using bbox equivalents. They exit if out of memory */
1320 # define ckrealloc xrealloc
1321 # define ckmalloc xmalloc
1322 # define ckzalloc xzalloc
1323 # define ckstrdup xstrdup
1327 * It appears that grabstackstr() will barf with such alignments
1328 * because stalloc() will return a string allocated in a new stackblock.
1330 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1332 /* Most machines require the value returned from malloc to be aligned
1333 * in some way. The following macro will get this right
1334 * on many machines. */
1335 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1336 /* Minimum size of a block */
1337 MINSIZE = SHELL_ALIGN(504),
1340 struct stack_block {
1341 struct stack_block *prev;
1342 char space[MINSIZE];
1346 struct stack_block *stackp;
1349 struct stackmark *marknext;
1353 struct globals_memstack {
1354 struct stack_block *g_stackp; // = &stackbase;
1355 struct stackmark *markp;
1356 char *g_stacknxt; // = stackbase.space;
1357 char *sstrend; // = stackbase.space + MINSIZE;
1358 size_t g_stacknleft; // = MINSIZE;
1359 int herefd; // = -1;
1360 struct stack_block stackbase;
1362 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1363 #define G_memstack (*ash_ptr_to_globals_memstack)
1364 #define g_stackp (G_memstack.g_stackp )
1365 #define markp (G_memstack.markp )
1366 #define g_stacknxt (G_memstack.g_stacknxt )
1367 #define sstrend (G_memstack.sstrend )
1368 #define g_stacknleft (G_memstack.g_stacknleft)
1369 #define herefd (G_memstack.herefd )
1370 #define stackbase (G_memstack.stackbase )
1371 #define INIT_G_memstack() do { \
1372 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1374 g_stackp = &stackbase; \
1375 g_stacknxt = stackbase.space; \
1376 g_stacknleft = MINSIZE; \
1377 sstrend = stackbase.space + MINSIZE; \
1382 #define stackblock() ((void *)g_stacknxt)
1383 #define stackblocksize() g_stacknleft
1386 * Parse trees for commands are allocated in lifo order, so we use a stack
1387 * to make this more efficient, and also to avoid all sorts of exception
1388 * handling code to handle interrupts in the middle of a parse.
1390 * The size 504 was chosen because the Ultrix malloc handles that size
1394 stalloc(size_t nbytes)
1399 aligned = SHELL_ALIGN(nbytes);
1400 if (aligned > g_stacknleft) {
1403 struct stack_block *sp;
1405 blocksize = aligned;
1406 if (blocksize < MINSIZE)
1407 blocksize = MINSIZE;
1408 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1409 if (len < blocksize)
1410 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1413 sp->prev = g_stackp;
1414 g_stacknxt = sp->space;
1415 g_stacknleft = blocksize;
1416 sstrend = g_stacknxt + blocksize;
1421 g_stacknxt += aligned;
1422 g_stacknleft -= aligned;
1427 stzalloc(size_t nbytes)
1429 return memset(stalloc(nbytes), 0, nbytes);
1436 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1437 write(STDERR_FILENO, "stunalloc\n", 10);
1441 g_stacknleft += g_stacknxt - (char *)p;
1446 * Like strdup but works with the ash stack.
1449 ststrdup(const char *p)
1451 size_t len = strlen(p) + 1;
1452 return memcpy(stalloc(len), p, len);
1456 setstackmark(struct stackmark *mark)
1458 mark->stackp = g_stackp;
1459 mark->stacknxt = g_stacknxt;
1460 mark->stacknleft = g_stacknleft;
1461 mark->marknext = markp;
1466 popstackmark(struct stackmark *mark)
1468 struct stack_block *sp;
1474 markp = mark->marknext;
1475 while (g_stackp != mark->stackp) {
1477 g_stackp = sp->prev;
1480 g_stacknxt = mark->stacknxt;
1481 g_stacknleft = mark->stacknleft;
1482 sstrend = mark->stacknxt + mark->stacknleft;
1487 * When the parser reads in a string, it wants to stick the string on the
1488 * stack and only adjust the stack pointer when it knows how big the
1489 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1490 * of space on top of the stack and stackblocklen returns the length of
1491 * this block. Growstackblock will grow this space by at least one byte,
1492 * possibly moving it (like realloc). Grabstackblock actually allocates the
1493 * part of the block that has been used.
1496 growstackblock(void)
1500 newlen = g_stacknleft * 2;
1501 if (newlen < g_stacknleft)
1502 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1506 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1507 struct stack_block *oldstackp;
1508 struct stackmark *xmark;
1509 struct stack_block *sp;
1510 struct stack_block *prevstackp;
1514 oldstackp = g_stackp;
1516 prevstackp = sp->prev;
1517 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1518 sp = ckrealloc(sp, grosslen);
1519 sp->prev = prevstackp;
1521 g_stacknxt = sp->space;
1522 g_stacknleft = newlen;
1523 sstrend = sp->space + newlen;
1526 * Stack marks pointing to the start of the old block
1527 * must be relocated to point to the new block
1530 while (xmark != NULL && xmark->stackp == oldstackp) {
1531 xmark->stackp = g_stackp;
1532 xmark->stacknxt = g_stacknxt;
1533 xmark->stacknleft = g_stacknleft;
1534 xmark = xmark->marknext;
1538 char *oldspace = g_stacknxt;
1539 size_t oldlen = g_stacknleft;
1540 char *p = stalloc(newlen);
1542 /* free the space we just allocated */
1543 g_stacknxt = memcpy(p, oldspace, oldlen);
1544 g_stacknleft += newlen;
1549 grabstackblock(size_t len)
1551 len = SHELL_ALIGN(len);
1553 g_stacknleft -= len;
1557 * The following routines are somewhat easier to use than the above.
1558 * The user declares a variable of type STACKSTR, which may be declared
1559 * to be a register. The macro STARTSTACKSTR initializes things. Then
1560 * the user uses the macro STPUTC to add characters to the string. In
1561 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1562 * grown as necessary. When the user is done, she can just leave the
1563 * string there and refer to it using stackblock(). Or she can allocate
1564 * the space for it using grabstackstr(). If it is necessary to allow
1565 * someone else to use the stack temporarily and then continue to grow
1566 * the string, the user should use grabstack to allocate the space, and
1567 * then call ungrabstr(p) to return to the previous mode of operation.
1569 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1570 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1571 * is space for at least one character.
1576 size_t len = stackblocksize();
1577 if (herefd >= 0 && len >= 1024) {
1578 full_write(herefd, stackblock(), len);
1579 return stackblock();
1582 return (char *)stackblock() + len;
1586 * Called from CHECKSTRSPACE.
1589 makestrspace(size_t newlen, char *p)
1591 size_t len = p - g_stacknxt;
1592 size_t size = stackblocksize();
1597 size = stackblocksize();
1599 if (nleft >= newlen)
1603 return (char *)stackblock() + len;
1607 stack_nputstr(const char *s, size_t n, char *p)
1609 p = makestrspace(n, p);
1610 p = (char *)memcpy(p, s, n) + n;
1615 stack_putstr(const char *s, char *p)
1617 return stack_nputstr(s, strlen(s), p);
1621 _STPUTC(int c, char *p)
1629 #define STARTSTACKSTR(p) ((p) = stackblock())
1630 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1631 #define CHECKSTRSPACE(n, p) do { \
1634 size_t m = sstrend - q; \
1636 (p) = makestrspace(l, q); \
1638 #define USTPUTC(c, p) (*(p)++ = (c))
1639 #define STACKSTRNUL(p) do { \
1640 if ((p) == sstrend) \
1641 (p) = growstackstr(); \
1644 #define STUNPUTC(p) (--(p))
1645 #define STTOPC(p) ((p)[-1])
1646 #define STADJUST(amount, p) ((p) += (amount))
1648 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1649 #define ungrabstackstr(s, p) stunalloc(s)
1650 #define stackstrend() ((void *)sstrend)
1653 /* ============ String helpers */
1656 * prefix -- see if pfx is a prefix of string.
1659 prefix(const char *string, const char *pfx)
1662 if (*pfx++ != *string++)
1665 return (char *) string;
1669 * Check for a valid number. This should be elsewhere.
1672 is_number(const char *p)
1677 } while (*++p != '\0');
1682 * Convert a string of digits to an integer, printing an error message on
1686 number(const char *s)
1689 ash_msg_and_raise_error(msg_illnum, s);
1694 * Produce a possibly single quoted string suitable as input to the shell.
1695 * The return string is allocated on the stack.
1698 single_quote(const char *s)
1708 len = strchrnul(s, '\'') - s;
1710 q = p = makestrspace(len + 3, p);
1713 q = (char *)memcpy(q, s, len) + len;
1722 do len++; while (*++s == '\'');
1724 q = p = makestrspace(len + 3, p);
1727 q = (char *)memcpy(q, s - len, len) + len;
1735 return stackblock();
1739 /* ============ nextopt */
1741 static char **argptr; /* argument list for builtin commands */
1742 static char *optionarg; /* set by nextopt (like getopt) */
1743 static char *optptr; /* used by nextopt */
1746 * XXX - should get rid of. Have all builtins use getopt(3).
1747 * The library getopt must have the BSD extension static variable
1748 * "optreset", otherwise it can't be used within the shell safely.
1750 * Standard option processing (a la getopt) for builtin routines.
1751 * The only argument that is passed to nextopt is the option string;
1752 * the other arguments are unnecessary. It returns the character,
1753 * or '\0' on end of input.
1756 nextopt(const char *optstring)
1763 if (p == NULL || *p == '\0') {
1764 /* We ate entire "-param", take next one */
1770 if (*++p == '\0') /* just "-" ? */
1773 if (LONE_DASH(p)) /* "--" ? */
1775 /* p => next "-param" */
1777 /* p => some option char in the middle of a "-param" */
1779 for (q = optstring; *q != c;) {
1781 ash_msg_and_raise_error("illegal option -%c", c);
1789 ash_msg_and_raise_error("no arg for -%c option", c);
1799 /* ============ Shell variables */
1802 * The parsefile structure pointed to by the global variable parsefile
1803 * contains information about the current file being read.
1806 int nparam; /* # of positional parameters (without $0) */
1807 #if ENABLE_ASH_GETOPTS
1808 int optind; /* next parameter to be processed by getopts */
1809 int optoff; /* used by getopts */
1811 unsigned char malloced; /* if parameter list dynamically allocated */
1812 char **p; /* parameter list */
1816 * Free the list of positional parameters.
1819 freeparam(volatile struct shparam *param)
1821 if (param->malloced) {
1823 ap = ap1 = param->p;
1830 #if ENABLE_ASH_GETOPTS
1831 static void FAST_FUNC getoptsreset(const char *value);
1835 struct var *next; /* next entry in hash list */
1836 int flags; /* flags are defined above */
1837 const char *var_text; /* name=value */
1838 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1839 /* the variable gets set/unset */
1843 struct localvar *next; /* next local variable in list */
1844 struct var *vp; /* the variable that was made local */
1845 int flags; /* saved flags */
1846 const char *text; /* saved text */
1850 #define VEXPORT 0x01 /* variable is exported */
1851 #define VREADONLY 0x02 /* variable cannot be modified */
1852 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1853 #define VTEXTFIXED 0x08 /* text is statically allocated */
1854 #define VSTACK 0x10 /* text is allocated on the stack */
1855 #define VUNSET 0x20 /* the variable is not set */
1856 #define VNOFUNC 0x40 /* don't call the callback function */
1857 #define VNOSET 0x80 /* do not set variable - just readonly test */
1858 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1859 #if ENABLE_ASH_RANDOM_SUPPORT
1860 # define VDYNAMIC 0x200 /* dynamic variable */
1866 /* Need to be before varinit_data[] */
1867 #if ENABLE_LOCALE_SUPPORT
1868 static void FAST_FUNC
1869 change_lc_all(const char *value)
1871 if (value && *value != '\0')
1872 setlocale(LC_ALL, value);
1874 static void FAST_FUNC
1875 change_lc_ctype(const char *value)
1877 if (value && *value != '\0')
1878 setlocale(LC_CTYPE, value);
1882 static void chkmail(void);
1883 static void changemail(const char *) FAST_FUNC;
1885 static void changepath(const char *) FAST_FUNC;
1886 #if ENABLE_ASH_RANDOM_SUPPORT
1887 static void change_random(const char *) FAST_FUNC;
1890 static const struct {
1892 const char *var_text;
1893 void (*var_func)(const char *) FAST_FUNC;
1894 } varinit_data[] = {
1895 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1897 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1898 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1900 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1901 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1902 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1903 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1904 #if ENABLE_ASH_GETOPTS
1905 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1907 #if ENABLE_ASH_RANDOM_SUPPORT
1908 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1910 #if ENABLE_LOCALE_SUPPORT
1911 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1912 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1914 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1915 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1921 struct globals_var {
1922 struct shparam shellparam; /* $@ current positional parameters */
1923 struct redirtab *redirlist;
1925 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1926 struct var *vartab[VTABSIZE];
1927 struct var varinit[ARRAY_SIZE(varinit_data)];
1929 extern struct globals_var *const ash_ptr_to_globals_var;
1930 #define G_var (*ash_ptr_to_globals_var)
1931 #define shellparam (G_var.shellparam )
1932 //#define redirlist (G_var.redirlist )
1933 #define g_nullredirs (G_var.g_nullredirs )
1934 #define preverrout_fd (G_var.preverrout_fd)
1935 #define vartab (G_var.vartab )
1936 #define varinit (G_var.varinit )
1937 #define INIT_G_var() do { \
1939 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1941 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1942 varinit[i].flags = varinit_data[i].flags; \
1943 varinit[i].var_text = varinit_data[i].var_text; \
1944 varinit[i].var_func = varinit_data[i].var_func; \
1948 #define vifs varinit[0]
1950 # define vmail (&vifs)[1]
1951 # define vmpath (&vmail)[1]
1952 # define vpath (&vmpath)[1]
1954 # define vpath (&vifs)[1]
1956 #define vps1 (&vpath)[1]
1957 #define vps2 (&vps1)[1]
1958 #define vps4 (&vps2)[1]
1959 #if ENABLE_ASH_GETOPTS
1960 # define voptind (&vps4)[1]
1961 # if ENABLE_ASH_RANDOM_SUPPORT
1962 # define vrandom (&voptind)[1]
1965 # if ENABLE_ASH_RANDOM_SUPPORT
1966 # define vrandom (&vps4)[1]
1971 * The following macros access the values of the above variables.
1972 * They have to skip over the name. They return the null string
1973 * for unset variables.
1975 #define ifsval() (vifs.var_text + 4)
1976 #define ifsset() ((vifs.flags & VUNSET) == 0)
1978 # define mailval() (vmail.var_text + 5)
1979 # define mpathval() (vmpath.var_text + 9)
1980 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1982 #define pathval() (vpath.var_text + 5)
1983 #define ps1val() (vps1.var_text + 4)
1984 #define ps2val() (vps2.var_text + 4)
1985 #define ps4val() (vps4.var_text + 4)
1986 #if ENABLE_ASH_GETOPTS
1987 # define optindval() (voptind.var_text + 7)
1990 #if ENABLE_ASH_GETOPTS
1991 static void FAST_FUNC
1992 getoptsreset(const char *value)
1994 shellparam.optind = number(value);
1995 shellparam.optoff = -1;
1999 /* math.h has these, otherwise define our private copies */
2000 #if !ENABLE_SH_MATH_SUPPORT
2001 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
2002 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
2004 * Return the pointer to the first char which is not part of a legal variable name
2005 * (a letter or underscore followed by letters, underscores, and digits).
2008 endofname(const char *name)
2010 if (!is_name(*name))
2013 if (!is_in_name(*name))
2021 * Compares two strings up to the first = or '\0'. The first
2022 * string must be terminated by '='; the second may be terminated by
2023 * either '=' or '\0'.
2026 varcmp(const char *p, const char *q)
2030 while ((c = *p) == (d = *q)) {
2045 * Find the appropriate entry in the hash table from the name.
2047 static struct var **
2048 hashvar(const char *p)
2052 hashval = ((unsigned char) *p) << 4;
2053 while (*p && *p != '=')
2054 hashval += (unsigned char) *p++;
2055 return &vartab[hashval % VTABSIZE];
2059 vpcmp(const void *a, const void *b)
2061 return varcmp(*(const char **)a, *(const char **)b);
2065 * This routine initializes the builtin variables.
2075 * PS1 depends on uid
2077 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2078 vps1.var_text = "PS1=\\w \\$ ";
2081 vps1.var_text = "PS1=# ";
2084 end = vp + ARRAY_SIZE(varinit);
2086 vpp = hashvar(vp->var_text);
2089 } while (++vp < end);
2092 static struct var **
2093 findvar(struct var **vpp, const char *name)
2095 for (; *vpp; vpp = &(*vpp)->next) {
2096 if (varcmp((*vpp)->var_text, name) == 0) {
2104 * Find the value of a variable. Returns NULL if not set.
2106 static const char* FAST_FUNC
2107 lookupvar(const char *name)
2111 v = *findvar(hashvar(name), name);
2113 #if ENABLE_ASH_RANDOM_SUPPORT
2115 * Dynamic variables are implemented roughly the same way they are
2116 * in bash. Namely, they're "special" so long as they aren't unset.
2117 * As soon as they're unset, they're no longer dynamic, and dynamic
2118 * lookup will no longer happen at that point. -- PFM.
2120 if (v->flags & VDYNAMIC)
2123 if (!(v->flags & VUNSET))
2124 return var_end(v->var_text);
2130 * Search the environment of a builtin command.
2133 bltinlookup(const char *name)
2137 for (sp = cmdenviron; sp; sp = sp->next) {
2138 if (varcmp(sp->text, name) == 0)
2139 return var_end(sp->text);
2141 return lookupvar(name);
2145 * Same as setvar except that the variable and value are passed in
2146 * the first argument as name=value. Since the first argument will
2147 * be actually stored in the table, it should not be a string that
2149 * Called with interrupts off.
2152 setvareq(char *s, int flags)
2154 struct var *vp, **vpp;
2157 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2158 vp = *findvar(vpp, s);
2160 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2163 if (flags & VNOSAVE)
2166 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2172 if (vp->var_func && !(flags & VNOFUNC))
2173 vp->var_func(var_end(s));
2175 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2176 free((char*)vp->var_text);
2178 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2180 /* variable s is not found */
2183 vp = ckzalloc(sizeof(*vp));
2185 /*vp->func = NULL; - ckzalloc did it */
2188 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2195 * Set the value of a variable. The flags argument is ored with the
2196 * flags of the variable. If val is NULL, the variable is unset.
2199 setvar(const char *name, const char *val, int flags)
2207 q = endofname(name);
2208 p = strchrnul(q, '=');
2210 if (!namelen || p != q)
2211 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2216 vallen = strlen(val);
2220 nameeq = ckmalloc(namelen + vallen + 2);
2221 p = memcpy(nameeq, name, namelen) + namelen;
2224 p = memcpy(p, val, vallen) + vallen;
2227 setvareq(nameeq, flags | VNOSAVE);
2231 static void FAST_FUNC
2232 setvar2(const char *name, const char *val)
2234 setvar(name, val, 0);
2237 #if ENABLE_ASH_GETOPTS
2239 * Safe version of setvar, returns 1 on success 0 on failure.
2242 setvarsafe(const char *name, const char *val, int flags)
2245 volatile int saveint;
2246 struct jmploc *volatile savehandler = exception_handler;
2247 struct jmploc jmploc;
2250 if (setjmp(jmploc.loc))
2253 exception_handler = &jmploc;
2254 setvar(name, val, flags);
2257 exception_handler = savehandler;
2258 RESTORE_INT(saveint);
2264 * Unset the specified variable.
2267 unsetvar(const char *s)
2273 vpp = findvar(hashvar(s), s);
2277 int flags = vp->flags;
2280 if (flags & VREADONLY)
2282 #if ENABLE_ASH_RANDOM_SUPPORT
2283 vp->flags &= ~VDYNAMIC;
2287 if ((flags & VSTRFIXED) == 0) {
2289 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2290 free((char*)vp->var_text);
2296 vp->flags &= ~VEXPORT;
2306 * Process a linked list of variable assignments.
2309 listsetvar(struct strlist *list_set_var, int flags)
2311 struct strlist *lp = list_set_var;
2317 setvareq(lp->text, flags);
2324 * Generate a list of variables satisfying the given conditions.
2327 listvars(int on, int off, char ***end)
2338 for (vp = *vpp; vp; vp = vp->next) {
2339 if ((vp->flags & mask) == on) {
2340 if (ep == stackstrend())
2341 ep = growstackstr();
2342 *ep++ = (char*)vp->var_text;
2345 } while (++vpp < vartab + VTABSIZE);
2346 if (ep == stackstrend())
2347 ep = growstackstr();
2351 return grabstackstr(ep);
2355 /* ============ Path search helper
2357 * The variable path (passed by reference) should be set to the start
2358 * of the path before the first call; path_advance will update
2359 * this value as it proceeds. Successive calls to path_advance will return
2360 * the possible path expansions in sequence. If an option (indicated by
2361 * a percent sign) appears in the path entry then the global variable
2362 * pathopt will be set to point to it; otherwise pathopt will be set to
2365 static const char *pathopt; /* set by path_advance */
2368 path_advance(const char **path, const char *name)
2378 for (p = start; *p && *p != ':' && *p != '%'; p++)
2380 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2381 while (stackblocksize() < len)
2385 memcpy(q, start, p - start);
2393 while (*p && *p != ':')
2400 return stalloc(len);
2404 /* ============ Prompt */
2406 static smallint doprompt; /* if set, prompt the user */
2407 static smallint needprompt; /* true if interactive and at start of line */
2409 #if ENABLE_FEATURE_EDITING
2410 static line_input_t *line_input_state;
2411 static const char *cmdedit_prompt;
2413 putprompt(const char *s)
2415 if (ENABLE_ASH_EXPAND_PRMT) {
2416 free((char*)cmdedit_prompt);
2417 cmdedit_prompt = ckstrdup(s);
2424 putprompt(const char *s)
2430 #if ENABLE_ASH_EXPAND_PRMT
2431 /* expandstr() needs parsing machinery, so it is far away ahead... */
2432 static const char *expandstr(const char *ps);
2434 #define expandstr(s) s
2438 setprompt_if(smallint do_set, int whichprompt)
2441 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2448 switch (whichprompt) {
2458 #if ENABLE_ASH_EXPAND_PRMT
2459 setstackmark(&smark);
2460 stalloc(stackblocksize());
2462 putprompt(expandstr(prompt));
2463 #if ENABLE_ASH_EXPAND_PRMT
2464 popstackmark(&smark);
2469 /* ============ The cd and pwd commands */
2471 #define CD_PHYSICAL 1
2481 while ((i = nextopt("LP")) != '\0') {
2483 flags ^= CD_PHYSICAL;
2492 * Update curdir (the name of the current directory) in response to a
2496 updatepwd(const char *dir)
2503 cdcomppath = ststrdup(dir);
2506 if (curdir == nullstr)
2508 new = stack_putstr(curdir, new);
2510 new = makestrspace(strlen(dir) + 2, new);
2511 lim = (char *)stackblock() + 1;
2515 if (new > lim && *lim == '/')
2520 if (dir[1] == '/' && dir[2] != '/') {
2526 p = strtok(cdcomppath, "/");
2530 if (p[1] == '.' && p[2] == '\0') {
2542 new = stack_putstr(p, new);
2550 return stackblock();
2554 * Find out what the current directory is. If we already know the current
2555 * directory, this routine returns immediately.
2560 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2561 return dir ? dir : nullstr;
2565 setpwd(const char *val, int setold)
2569 oldcur = dir = curdir;
2572 setvar("OLDPWD", oldcur, VEXPORT);
2575 if (physdir != nullstr) {
2576 if (physdir != oldcur)
2580 if (oldcur == val || !val) {
2586 dir = ckstrdup(val);
2587 if (oldcur != dir && oldcur != nullstr) {
2592 setvar("PWD", dir, VEXPORT);
2595 static void hashcd(void);
2598 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2599 * know that the current directory has changed.
2602 docd(const char *dest, int flags)
2604 const char *dir = NULL;
2607 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2610 if (!(flags & CD_PHYSICAL)) {
2611 dir = updatepwd(dest);
2625 static int FAST_FUNC
2626 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2638 dest = bltinlookup("HOME");
2639 else if (LONE_DASH(dest)) {
2640 dest = bltinlookup("OLDPWD");
2662 path = bltinlookup("CDPATH");
2671 p = path_advance(&path, dest);
2672 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2676 if (!docd(p, flags))
2681 ash_msg_and_raise_error("can't cd to %s", dest);
2684 if (flags & CD_PRINT)
2685 out1fmt("%s\n", curdir);
2689 static int FAST_FUNC
2690 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2693 const char *dir = curdir;
2697 if (physdir == nullstr)
2701 out1fmt("%s\n", dir);
2706 /* ============ ... */
2709 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2711 /* Syntax classes */
2712 #define CWORD 0 /* character is nothing special */
2713 #define CNL 1 /* newline character */
2714 #define CBACK 2 /* a backslash character */
2715 #define CSQUOTE 3 /* single quote */
2716 #define CDQUOTE 4 /* double quote */
2717 #define CENDQUOTE 5 /* a terminating quote */
2718 #define CBQUOTE 6 /* backwards single quote */
2719 #define CVAR 7 /* a dollar sign */
2720 #define CENDVAR 8 /* a '}' character */
2721 #define CLP 9 /* a left paren in arithmetic */
2722 #define CRP 10 /* a right paren in arithmetic */
2723 #define CENDFILE 11 /* end of file */
2724 #define CCTL 12 /* like CWORD, except it must be escaped */
2725 #define CSPCL 13 /* these terminate a word */
2726 #define CIGN 14 /* character should be ignored */
2729 #if ENABLE_ASH_ALIAS
2733 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2735 #if ENABLE_SH_MATH_SUPPORT
2736 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2738 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2740 static const uint16_t S_I_T[] = {
2741 #if ENABLE_ASH_ALIAS
2742 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2744 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2745 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2746 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2747 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2748 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2749 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2750 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2751 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2752 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2753 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2754 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2755 #if !USE_SIT_FUNCTION
2756 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2757 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2758 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2762 /* Constants below must match table above */
2764 #if ENABLE_ASH_ALIAS
2765 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2767 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2768 CNL_CNL_CNL_CNL , /* 2 */
2769 CWORD_CCTL_CCTL_CWORD , /* 3 */
2770 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2771 CVAR_CVAR_CWORD_CVAR , /* 5 */
2772 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2773 CSPCL_CWORD_CWORD_CLP , /* 7 */
2774 CSPCL_CWORD_CWORD_CRP , /* 8 */
2775 CBACK_CBACK_CCTL_CBACK , /* 9 */
2776 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2777 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2778 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2779 CWORD_CWORD_CWORD_CWORD , /* 13 */
2780 CCTL_CCTL_CCTL_CCTL , /* 14 */
2783 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2784 * caller must ensure proper cast on it if c is *char_ptr!
2786 /* Values for syntax param */
2787 #define BASESYNTAX 0 /* not in quotes */
2788 #define DQSYNTAX 1 /* in double quotes */
2789 #define SQSYNTAX 2 /* in single quotes */
2790 #define ARISYNTAX 3 /* in arithmetic */
2791 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2793 #if USE_SIT_FUNCTION
2796 SIT(int c, int syntax)
2798 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2799 # if ENABLE_ASH_ALIAS
2800 static const uint8_t syntax_index_table[] ALIGN1 = {
2801 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2802 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2803 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2807 static const uint8_t syntax_index_table[] ALIGN1 = {
2808 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2809 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2810 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2819 # if ENABLE_ASH_ALIAS
2825 /* Cast is purely for paranoia here,
2826 * just in case someone passed signed char to us */
2827 if ((unsigned char)c >= CTL_FIRST
2828 && (unsigned char)c <= CTL_LAST
2832 s = strchrnul(spec_symbls, c);
2835 indx = syntax_index_table[s - spec_symbls];
2837 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2840 #else /* !USE_SIT_FUNCTION */
2842 static const uint8_t syntax_index_table[] = {
2843 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2844 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2854 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2855 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2877 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2878 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2879 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2881 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2883 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2884 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2885 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2886 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2887 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2888 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2889 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2890 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2891 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2892 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2901 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2903 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2904 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2905 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2906 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2907 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2908 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2936 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2937 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2938 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2941 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2969 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2970 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2971 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2972 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2974 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2975 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2976 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2977 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2978 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2979 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2980 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2981 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3100 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3101 # if ENABLE_ASH_ALIAS
3102 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3106 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3108 #endif /* !USE_SIT_FUNCTION */
3111 /* ============ Alias handling */
3113 #if ENABLE_ASH_ALIAS
3115 #define ALIASINUSE 1
3126 static struct alias **atab; // [ATABSIZE];
3127 #define INIT_G_alias() do { \
3128 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3132 static struct alias **
3133 __lookupalias(const char *name) {
3134 unsigned int hashval;
3141 ch = (unsigned char)*p;
3145 ch = (unsigned char)*++p;
3147 app = &atab[hashval % ATABSIZE];
3149 for (; *app; app = &(*app)->next) {
3150 if (strcmp(name, (*app)->name) == 0) {
3158 static struct alias *
3159 lookupalias(const char *name, int check)
3161 struct alias *ap = *__lookupalias(name);
3163 if (check && ap && (ap->flag & ALIASINUSE))
3168 static struct alias *
3169 freealias(struct alias *ap)
3173 if (ap->flag & ALIASINUSE) {
3174 ap->flag |= ALIASDEAD;
3186 setalias(const char *name, const char *val)
3188 struct alias *ap, **app;
3190 app = __lookupalias(name);
3194 if (!(ap->flag & ALIASINUSE)) {
3197 ap->val = ckstrdup(val);
3198 ap->flag &= ~ALIASDEAD;
3201 ap = ckzalloc(sizeof(struct alias));
3202 ap->name = ckstrdup(name);
3203 ap->val = ckstrdup(val);
3204 /*ap->flag = 0; - ckzalloc did it */
3205 /*ap->next = NULL;*/
3212 unalias(const char *name)
3216 app = __lookupalias(name);
3220 *app = freealias(*app);
3231 struct alias *ap, **app;
3235 for (i = 0; i < ATABSIZE; i++) {
3237 for (ap = *app; ap; ap = *app) {
3238 *app = freealias(*app);
3248 printalias(const struct alias *ap)
3250 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3254 * TODO - sort output
3256 static int FAST_FUNC
3257 aliascmd(int argc UNUSED_PARAM, char **argv)
3266 for (i = 0; i < ATABSIZE; i++) {
3267 for (ap = atab[i]; ap; ap = ap->next) {
3273 while ((n = *++argv) != NULL) {
3274 v = strchr(n+1, '=');
3275 if (v == NULL) { /* n+1: funny ksh stuff */
3276 ap = *__lookupalias(n);
3278 fprintf(stderr, "%s: %s not found\n", "alias", n);
3291 static int FAST_FUNC
3292 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3296 while ((i = nextopt("a")) != '\0') {
3302 for (i = 0; *argptr; argptr++) {
3303 if (unalias(*argptr)) {
3304 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3312 #endif /* ASH_ALIAS */
3315 /* ============ jobs.c */
3317 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3320 #define FORK_NOJOB 2
3322 /* mode flags for showjob(s) */
3323 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3324 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3325 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3328 * A job structure contains information about a job. A job is either a
3329 * single process or a set of processes contained in a pipeline. In the
3330 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3334 pid_t ps_pid; /* process id */
3335 int ps_status; /* last process status from wait() */
3336 char *ps_cmd; /* text of command being run */
3340 struct procstat ps0; /* status of process */
3341 struct procstat *ps; /* status or processes when more than one */
3343 int stopstatus; /* status of a stopped job */
3346 nprocs: 16, /* number of processes */
3348 #define JOBRUNNING 0 /* at least one proc running */
3349 #define JOBSTOPPED 1 /* all procs are stopped */
3350 #define JOBDONE 2 /* all procs are completed */
3352 sigint: 1, /* job was killed by SIGINT */
3353 jobctl: 1, /* job running under job control */
3355 waited: 1, /* true if this entry has been waited for */
3356 used: 1, /* true if this entry is in used */
3357 changed: 1; /* true if status has changed */
3358 struct job *prev_job; /* previous job */
3361 static struct job *makejob(/*union node *,*/ int);
3362 static int forkshell(struct job *, union node *, int);
3363 static int waitforjob(struct job *);
3366 enum { doing_jobctl = 0 };
3367 #define setjobctl(on) do {} while (0)
3369 static smallint doing_jobctl; //references:8
3370 static void setjobctl(int);
3377 ignoresig(int signo)
3379 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3380 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3381 /* No, need to do it */
3382 signal(signo, SIG_IGN);
3384 sigmode[signo - 1] = S_HARD_IGN;
3388 * Only one usage site - in setsignal()
3391 signal_handler(int signo)
3393 gotsig[signo - 1] = 1;
3395 if (signo == SIGINT && !trap[SIGINT]) {
3396 if (!suppress_int) {
3398 raise_interrupt(); /* does not return */
3402 pending_sig = signo;
3407 * Set the signal handler for the specified signal. The routine figures
3408 * out what it should be set to.
3411 setsignal(int signo)
3414 char cur_act, new_act;
3415 struct sigaction act;
3419 if (t != NULL) { /* trap for this sig is set */
3421 if (t[0] == '\0') /* trap is "": ignore this sig */
3425 if (rootshell && new_act == S_DFL) {
3428 if (iflag || minusc || sflag == 0)
3437 * "In all cases, bash ignores SIGQUIT. Non-builtin
3438 * commands run by bash have signal handlers
3439 * set to the values inherited by the shell
3440 * from its parent". */
3456 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3457 //whereas we have to restore it to what shell got on entry
3458 //from the parent. See comment above
3460 t = &sigmode[signo - 1];
3463 /* current setting is not yet known */
3464 if (sigaction(signo, NULL, &act)) {
3465 /* pretend it worked; maybe we should give a warning,
3466 * but other shells don't. We don't alter sigmode,
3467 * so we retry every time.
3468 * btw, in Linux it never fails. --vda */
3471 if (act.sa_handler == SIG_IGN) {
3472 cur_act = S_HARD_IGN;
3474 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3476 cur_act = S_IGN; /* don't hard ignore these */
3480 if (cur_act == S_HARD_IGN || cur_act == new_act)
3483 act.sa_handler = SIG_DFL;
3486 act.sa_handler = signal_handler;
3487 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3488 sigfillset(&act.sa_mask); /* ditto */
3491 act.sa_handler = SIG_IGN;
3494 sigaction_set(signo, &act);
3499 /* mode flags for set_curjob */
3500 #define CUR_DELETE 2
3501 #define CUR_RUNNING 1
3502 #define CUR_STOPPED 0
3504 /* mode flags for dowait */
3505 #define DOWAIT_NONBLOCK WNOHANG
3506 #define DOWAIT_BLOCK 0
3509 /* pgrp of shell on invocation */
3510 static int initialpgrp; //references:2
3511 static int ttyfd = -1; //5
3514 static struct job *jobtab; //5
3516 static unsigned njobs; //4
3518 static struct job *curjob; //lots
3519 /* number of presumed living untracked jobs */
3520 static int jobless; //4
3523 set_curjob(struct job *jp, unsigned mode)
3526 struct job **jpp, **curp;
3528 /* first remove from list */
3529 jpp = curp = &curjob;
3534 jpp = &jp1->prev_job;
3536 *jpp = jp1->prev_job;
3538 /* Then re-insert in correct position */
3546 /* job being deleted */
3549 /* newly created job or backgrounded job,
3550 put after all stopped jobs. */
3554 if (!jp1 || jp1->state != JOBSTOPPED)
3557 jpp = &jp1->prev_job;
3563 /* newly stopped job - becomes curjob */
3564 jp->prev_job = *jpp;
3572 jobno(const struct job *jp)
3574 return jp - jobtab + 1;
3579 * Convert a job name to a job structure.
3582 #define getjob(name, getctl) getjob(name)
3585 getjob(const char *name, int getctl)
3589 const char *err_msg = "%s: no such job";
3593 char *(*match)(const char *, const char *);
3608 if (c == '+' || c == '%') {
3610 err_msg = "No current job";
3616 err_msg = "No previous job";
3627 jp = jobtab + num - 1;
3642 if (match(jp->ps[0].ps_cmd, p)) {
3646 err_msg = "%s: ambiguous";
3656 err_msg = "job %s not created under job control";
3657 if (getctl && jp->jobctl == 0)
3662 ash_msg_and_raise_error(err_msg, name);
3666 * Mark a job structure as unused.
3669 freejob(struct job *jp)
3671 struct procstat *ps;
3675 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3676 if (ps->ps_cmd != nullstr)
3679 if (jp->ps != &jp->ps0)
3682 set_curjob(jp, CUR_DELETE);
3688 xtcsetpgrp(int fd, pid_t pgrp)
3690 if (tcsetpgrp(fd, pgrp))
3691 ash_msg_and_raise_error("can't set tty process group (%m)");
3695 * Turn job control on and off.
3697 * Note: This code assumes that the third arg to ioctl is a character
3698 * pointer, which is true on Berkeley systems but not System V. Since
3699 * System V doesn't have job control yet, this isn't a problem now.
3701 * Called with interrupts off.
3709 if (on == doing_jobctl || rootshell == 0)
3713 ofd = fd = open(_PATH_TTY, O_RDWR);
3715 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3716 * That sometimes helps to acquire controlling tty.
3717 * Obviously, a workaround for bugs when someone
3718 * failed to provide a controlling tty to bash! :) */
3724 fd = fcntl(fd, F_DUPFD, 10);
3729 /* fd is a tty at this point */
3730 close_on_exec_on(fd);
3731 do { /* while we are in the background */
3732 pgrp = tcgetpgrp(fd);
3735 ash_msg("can't access tty; job control turned off");
3739 if (pgrp == getpgrp())
3750 xtcsetpgrp(fd, pgrp);
3752 /* turning job control off */
3755 /* was xtcsetpgrp, but this can make exiting ash
3756 * loop forever if pty is already deleted */
3757 tcsetpgrp(fd, pgrp);
3771 static int FAST_FUNC
3772 killcmd(int argc, char **argv)
3775 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3777 if (argv[i][0] == '%') {
3778 struct job *jp = getjob(argv[i], 0);
3779 unsigned pid = jp->ps[0].ps_pid;
3780 /* Enough space for ' -NNN<nul>' */
3781 argv[i] = alloca(sizeof(int)*3 + 3);
3782 /* kill_main has matching code to expect
3783 * leading space. Needed to not confuse
3784 * negative pids with "kill -SIGNAL_NO" syntax */
3785 sprintf(argv[i], " -%u", pid);
3787 } while (argv[++i]);
3789 return kill_main(argc, argv);
3793 showpipe(struct job *jp /*, FILE *out*/)
3795 struct procstat *ps;
3796 struct procstat *psend;
3798 psend = jp->ps + jp->nprocs;
3799 for (ps = jp->ps + 1; ps < psend; ps++)
3800 printf(" | %s", ps->ps_cmd);
3801 outcslow('\n', stdout);
3802 flush_stdout_stderr();
3807 restartjob(struct job *jp, int mode)
3809 struct procstat *ps;
3815 if (jp->state == JOBDONE)
3817 jp->state = JOBRUNNING;
3818 pgid = jp->ps[0].ps_pid;
3819 if (mode == FORK_FG)
3820 xtcsetpgrp(ttyfd, pgid);
3821 killpg(pgid, SIGCONT);
3825 if (WIFSTOPPED(ps->ps_status)) {
3831 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3836 static int FAST_FUNC
3837 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3843 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3847 jp = getjob(*argv, 1);
3848 if (mode == FORK_BG) {
3849 set_curjob(jp, CUR_RUNNING);
3850 printf("[%d] ", jobno(jp));
3852 out1str(jp->ps[0].ps_cmd);
3853 showpipe(jp /*, stdout*/);
3854 retval = restartjob(jp, mode);
3855 } while (*argv && *++argv);
3861 sprint_status(char *s, int status, int sigonly)
3867 if (!WIFEXITED(status)) {
3869 if (WIFSTOPPED(status))
3870 st = WSTOPSIG(status);
3873 st = WTERMSIG(status);
3875 if (st == SIGINT || st == SIGPIPE)
3878 if (WIFSTOPPED(status))
3883 col = fmtstr(s, 32, strsignal(st));
3884 if (WCOREDUMP(status)) {
3885 col += fmtstr(s + col, 16, " (core dumped)");
3887 } else if (!sigonly) {
3888 st = WEXITSTATUS(status);
3890 col = fmtstr(s, 16, "Done(%d)", st);
3892 col = fmtstr(s, 16, "Done");
3899 dowait(int wait_flags, struct job *job)
3904 struct job *thisjob;
3907 TRACE(("dowait(0x%x) called\n", wait_flags));
3909 /* Do a wait system call. If job control is compiled in, we accept
3910 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3911 * NB: _not_ safe_waitpid, we need to detect EINTR */
3913 wait_flags |= WUNTRACED;
3914 pid = waitpid(-1, &status, wait_flags);
3915 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3916 pid, status, errno, strerror(errno)));
3922 for (jp = curjob; jp; jp = jp->prev_job) {
3923 struct procstat *ps;
3924 struct procstat *psend;
3925 if (jp->state == JOBDONE)
3929 psend = ps + jp->nprocs;
3931 if (ps->ps_pid == pid) {
3932 TRACE(("Job %d: changing status of proc %d "
3933 "from 0x%x to 0x%x\n",
3934 jobno(jp), pid, ps->ps_status, status));
3935 ps->ps_status = status;
3938 if (ps->ps_status == -1)
3941 if (state == JOBRUNNING)
3943 if (WIFSTOPPED(ps->ps_status)) {
3944 jp->stopstatus = ps->ps_status;
3948 } while (++ps < psend);
3953 if (!WIFSTOPPED(status))
3959 if (state != JOBRUNNING) {
3960 thisjob->changed = 1;
3962 if (thisjob->state != state) {
3963 TRACE(("Job %d: changing state from %d to %d\n",
3964 jobno(thisjob), thisjob->state, state));
3965 thisjob->state = state;
3967 if (state == JOBSTOPPED) {
3968 set_curjob(thisjob, CUR_STOPPED);
3977 if (thisjob && thisjob == job) {
3981 len = sprint_status(s, status, 1);
3992 blocking_wait_with_raise_on_sig(void)
3994 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
3995 if (pid <= 0 && pending_sig)
3996 raise_exception(EXSIG);
4002 showjob(FILE *out, struct job *jp, int mode)
4004 struct procstat *ps;
4005 struct procstat *psend;
4012 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4013 /* just output process (group) id of pipeline */
4014 fprintf(out, "%d\n", ps->ps_pid);
4018 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4023 else if (curjob && jp == curjob->prev_job)
4026 if (mode & SHOW_PIDS)
4027 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4029 psend = ps + jp->nprocs;
4031 if (jp->state == JOBRUNNING) {
4032 strcpy(s + col, "Running");
4033 col += sizeof("Running") - 1;
4035 int status = psend[-1].ps_status;
4036 if (jp->state == JOBSTOPPED)
4037 status = jp->stopstatus;
4038 col += sprint_status(s + col, status, 0);
4040 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4042 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4043 * or prints several "PID | <cmdN>" lines,
4044 * depending on SHOW_PIDS bit.
4045 * We do not print status of individual processes
4046 * between PID and <cmdN>. bash does it, but not very well:
4047 * first line shows overall job status, not process status,
4048 * making it impossible to know 1st process status.
4052 /* for each process */
4055 if (mode & SHOW_PIDS)
4056 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4058 fprintf(out, "%s%*c%s%s",
4060 33 - col >= 0 ? 33 - col : 0, ' ',
4061 ps == jp->ps ? "" : "| ",
4064 } while (++ps != psend);
4065 outcslow('\n', out);
4069 if (jp->state == JOBDONE) {
4070 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4076 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4077 * statuses have changed since the last call to showjobs.
4080 showjobs(FILE *out, int mode)
4084 TRACE(("showjobs(0x%x) called\n", mode));
4086 /* Handle all finished jobs */
4087 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4090 for (jp = curjob; jp; jp = jp->prev_job) {
4091 if (!(mode & SHOW_CHANGED) || jp->changed) {
4092 showjob(out, jp, mode);
4097 static int FAST_FUNC
4098 jobscmd(int argc UNUSED_PARAM, char **argv)
4103 while ((m = nextopt("lp")) != '\0') {
4107 mode |= SHOW_ONLY_PGID;
4113 showjob(stdout, getjob(*argv, 0), mode);
4116 showjobs(stdout, mode);
4123 /* Called only on finished or stopped jobs (no members are running) */
4125 getstatus(struct job *job)
4129 struct procstat *ps;
4131 /* Fetch last member's status */
4132 ps = job->ps + job->nprocs - 1;
4133 status = ps->ps_status;
4135 /* "set -o pipefail" mode: use last _nonzero_ status */
4136 while (status == 0 && --ps >= job->ps)
4137 status = ps->ps_status;
4140 retval = WEXITSTATUS(status);
4141 if (!WIFEXITED(status)) {
4143 retval = WSTOPSIG(status);
4144 if (!WIFSTOPPED(status))
4147 /* XXX: limits number of signals */
4148 retval = WTERMSIG(status);
4150 if (retval == SIGINT)
4156 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4157 jobno(job), job->nprocs, status, retval));
4161 static int FAST_FUNC
4162 waitcmd(int argc UNUSED_PARAM, char **argv)
4169 raise_exception(EXSIG);
4176 /* wait for all jobs */
4180 if (!jp) /* no running procs */
4182 if (jp->state == JOBRUNNING)
4187 blocking_wait_with_raise_on_sig();
4189 * "When bash is waiting for an asynchronous command via
4190 * the wait builtin, the reception of a signal for which a trap
4191 * has been set will cause the wait builtin to return immediately
4192 * with an exit status greater than 128, immediately after which
4193 * the trap is executed."
4195 * blocking_wait_with_raise_on_sig raises signal handlers
4196 * if it gets no pid (pid < 0). However,
4197 * if child sends us a signal *and immediately exits*,
4198 * blocking_wait_with_raise_on_sig gets pid > 0
4199 * and does not handle pending_sig. Check this case: */
4201 raise_exception(EXSIG);
4207 if (**argv != '%') {
4208 pid_t pid = number(*argv);
4213 if (job->ps[job->nprocs - 1].ps_pid == pid)
4215 job = job->prev_job;
4218 job = getjob(*argv, 0);
4219 /* loop until process terminated or stopped */
4220 while (job->state == JOBRUNNING)
4221 blocking_wait_with_raise_on_sig();
4223 retval = getstatus(job);
4236 struct job *jp, *jq;
4238 len = njobs * sizeof(*jp);
4240 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4242 offset = (char *)jp - (char *)jq;
4244 /* Relocate pointers */
4247 jq = (struct job *)((char *)jq + l);
4251 #define joff(p) ((struct job *)((char *)(p) + l))
4252 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4253 if (joff(jp)->ps == &jq->ps0)
4254 jmove(joff(jp)->ps);
4255 if (joff(jp)->prev_job)
4256 jmove(joff(jp)->prev_job);
4266 jp = (struct job *)((char *)jp + len);
4270 } while (--jq >= jp);
4275 * Return a new job structure.
4276 * Called with interrupts off.
4279 makejob(/*union node *node,*/ int nprocs)
4284 for (i = njobs, jp = jobtab; ; jp++) {
4291 if (jp->state != JOBDONE || !jp->waited)
4300 memset(jp, 0, sizeof(*jp));
4302 /* jp->jobctl is a bitfield.
4303 * "jp->jobctl |= jobctl" likely to give awful code */
4307 jp->prev_job = curjob;
4312 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4314 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4321 * Return a string identifying a command (to be printed by the
4324 static char *cmdnextc;
4327 cmdputs(const char *s)
4329 static const char vstype[VSTYPE + 1][3] = {
4330 "", "}", "-", "+", "?", "=",
4331 "%", "%%", "#", "##"
4332 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4335 const char *p, *str;
4339 unsigned char subtype = 0;
4343 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4345 while ((c = *p++) != '\0') {
4353 if ((subtype & VSTYPE) == VSLENGTH)
4357 if (!(subtype & VSQUOTE) == !(quoted & 1))
4363 str = "\"}" + !(quoted & 1);
4370 case CTLBACKQ+CTLQUOTE:
4373 #if ENABLE_SH_MATH_SUPPORT
4388 if ((subtype & VSTYPE) != VSNORMAL)
4390 str = vstype[subtype & VSTYPE];
4391 if (subtype & VSNUL)
4400 /* These can only happen inside quotes */
4413 while ((c = *str++) != '\0') {
4416 } /* while *p++ not NUL */
4419 USTPUTC('"', nextc);
4425 /* cmdtxt() and cmdlist() call each other */
4426 static void cmdtxt(union node *n);
4429 cmdlist(union node *np, int sep)
4431 for (; np; np = np->narg.next) {
4435 if (sep && np->narg.next)
4441 cmdtxt(union node *n)
4444 struct nodelist *lp;
4455 lp = n->npipe.cmdlist;
4473 cmdtxt(n->nbinary.ch1);
4489 cmdtxt(n->nif.test);
4491 if (n->nif.elsepart) {
4492 cmdtxt(n->nif.ifpart);
4494 n = n->nif.elsepart;
4512 cmdtxt(n->nbinary.ch1);
4522 cmdputs(n->nfor.var);
4524 cmdlist(n->nfor.args, 1);
4529 cmdputs(n->narg.text);
4533 cmdlist(n->ncmd.args, 1);
4534 cmdlist(n->ncmd.redirect, 0);
4547 cmdputs(n->ncase.expr->narg.text);
4549 for (np = n->ncase.cases; np; np = np->nclist.next) {
4550 cmdtxt(np->nclist.pattern);
4552 cmdtxt(np->nclist.body);
4566 #if ENABLE_ASH_BASH_COMPAT
4581 cmdputs(utoa(n->nfile.fd));
4583 if (n->type == NTOFD || n->type == NFROMFD) {
4584 cmdputs(utoa(n->ndup.dupfd));
4593 commandtext(union node *n)
4597 STARTSTACKSTR(cmdnextc);
4599 name = stackblock();
4600 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4601 name, cmdnextc, cmdnextc));
4602 return ckstrdup(name);
4607 * Fork off a subshell. If we are doing job control, give the subshell its
4608 * own process group. Jp is a job structure that the job is to be added to.
4609 * N is the command that will be evaluated by the child. Both jp and n may
4610 * be NULL. The mode parameter can be one of the following:
4611 * FORK_FG - Fork off a foreground process.
4612 * FORK_BG - Fork off a background process.
4613 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4614 * process group even if job control is on.
4616 * When job control is turned off, background processes have their standard
4617 * input redirected to /dev/null (except for the second and later processes
4620 * Called with interrupts off.
4623 * Clear traps on a fork.
4630 for (tp = trap; tp < &trap[NSIG]; tp++) {
4631 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4633 if (trap_ptr == trap)
4635 /* else: it "belongs" to trap_ptr vector, don't free */
4637 if ((tp - trap) != 0)
4638 setsignal(tp - trap);
4645 /* Lives far away from here, needed for forkchild */
4646 static void closescript(void);
4648 /* Called after fork(), in child */
4649 static NOINLINE void
4650 forkchild(struct job *jp, union node *n, int mode)
4654 TRACE(("Child shell %d\n", getpid()));
4658 /* man bash: "Non-builtin commands run by bash have signal handlers
4659 * set to the values inherited by the shell from its parent".
4660 * Do we do it correctly? */
4664 if (mode == FORK_NOJOB /* is it `xxx` ? */
4665 && n && n->type == NCMD /* is it single cmd? */
4666 /* && n->ncmd.args->type == NARG - always true? */
4667 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4668 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4669 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4671 TRACE(("Trap hack\n"));
4672 /* Awful hack for `trap` or $(trap).
4674 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4675 * contains an example where "trap" is executed in a subshell:
4677 * save_traps=$(trap)
4679 * eval "$save_traps"
4681 * Standard does not say that "trap" in subshell shall print
4682 * parent shell's traps. It only says that its output
4683 * must have suitable form, but then, in the above example
4684 * (which is not supposed to be normative), it implies that.
4686 * bash (and probably other shell) does implement it
4687 * (traps are reset to defaults, but "trap" still shows them),
4688 * but as a result, "trap" logic is hopelessly messed up:
4691 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4692 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4693 * # true | trap <--- trap is in subshell - no output (ditto)
4694 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4695 * trap -- 'echo Ho' SIGWINCH
4696 * # echo `(trap)` <--- in subshell in subshell - output
4697 * trap -- 'echo Ho' SIGWINCH
4698 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4699 * trap -- 'echo Ho' SIGWINCH
4701 * The rules when to forget and when to not forget traps
4702 * get really complex and nonsensical.
4704 * Our solution: ONLY bare $(trap) or `trap` is special.
4706 /* Save trap handler strings for trap builtin to print */
4707 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4708 /* Fall through into clearing traps */
4712 /* do job control only in root shell */
4714 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4717 if (jp->nprocs == 0)
4720 pgrp = jp->ps[0].ps_pid;
4721 /* this can fail because we are doing it in the parent also */
4723 if (mode == FORK_FG)
4724 xtcsetpgrp(ttyfd, pgrp);
4729 if (mode == FORK_BG) {
4730 /* man bash: "When job control is not in effect,
4731 * asynchronous commands ignore SIGINT and SIGQUIT" */
4734 if (jp->nprocs == 0) {
4736 if (open(bb_dev_null, O_RDONLY) != 0)
4737 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4741 if (iflag) { /* why if iflag only? */
4746 * "In all cases, bash ignores SIGQUIT. Non-builtin
4747 * commands run by bash have signal handlers
4748 * set to the values inherited by the shell
4750 * Take care of the second rule: */
4754 if (n && n->type == NCMD
4755 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4757 TRACE(("Job hack\n"));
4758 /* "jobs": we do not want to clear job list for it,
4759 * instead we remove only _its_ own_ job from job list.
4760 * This makes "jobs .... | cat" more useful.
4766 for (jp = curjob; jp; jp = jp->prev_job)
4771 /* Called after fork(), in parent */
4773 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4776 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4778 TRACE(("In parent shell: child = %d\n", pid));
4780 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4786 if (mode != FORK_NOJOB && jp->jobctl) {
4789 if (jp->nprocs == 0)
4792 pgrp = jp->ps[0].ps_pid;
4793 /* This can fail because we are doing it in the child also */
4797 if (mode == FORK_BG) {
4798 backgndpid = pid; /* set $! */
4799 set_curjob(jp, CUR_RUNNING);
4802 struct procstat *ps = &jp->ps[jp->nprocs++];
4805 ps->ps_cmd = nullstr;
4807 if (doing_jobctl && n)
4808 ps->ps_cmd = commandtext(n);
4814 forkshell(struct job *jp, union node *n, int mode)
4818 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4821 TRACE(("Fork failed, errno=%d", errno));
4824 ash_msg_and_raise_error("can't fork");
4827 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4828 forkchild(jp, n, mode);
4830 forkparent(jp, n, mode, pid);
4836 * Wait for job to finish.
4838 * Under job control we have the problem that while a child process
4839 * is running interrupts generated by the user are sent to the child
4840 * but not to the shell. This means that an infinite loop started by
4841 * an interactive user may be hard to kill. With job control turned off,
4842 * an interactive user may place an interactive program inside a loop.
4843 * If the interactive program catches interrupts, the user doesn't want
4844 * these interrupts to also abort the loop. The approach we take here
4845 * is to have the shell ignore interrupt signals while waiting for a
4846 * foreground process to terminate, and then send itself an interrupt
4847 * signal if the child process was terminated by an interrupt signal.
4848 * Unfortunately, some programs want to do a bit of cleanup and then
4849 * exit on interrupt; unless these processes terminate themselves by
4850 * sending a signal to themselves (instead of calling exit) they will
4851 * confuse this approach.
4853 * Called with interrupts off.
4856 waitforjob(struct job *jp)
4860 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4863 while (jp->state == JOBRUNNING) {
4864 /* In non-interactive shells, we _can_ get
4865 * a keyboard signal here and be EINTRed,
4866 * but we just loop back, waiting for command to complete.
4869 * "If bash is waiting for a command to complete and receives
4870 * a signal for which a trap has been set, the trap
4871 * will not be executed until the command completes."
4873 * Reality is that even if trap is not set, bash
4874 * will not act on the signal until command completes.
4875 * Try this. sleep5intoff.c:
4876 * #include <signal.h>
4877 * #include <unistd.h>
4880 * sigemptyset(&set);
4881 * sigaddset(&set, SIGINT);
4882 * sigaddset(&set, SIGQUIT);
4883 * sigprocmask(SIG_BLOCK, &set, NULL);
4887 * $ bash -c './sleep5intoff; echo hi'
4888 * ^C^C^C^C <--- pressing ^C once a second
4890 * $ bash -c './sleep5intoff; echo hi'
4891 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4894 dowait(DOWAIT_BLOCK, jp);
4901 xtcsetpgrp(ttyfd, rootpid);
4903 * This is truly gross.
4904 * If we're doing job control, then we did a TIOCSPGRP which
4905 * caused us (the shell) to no longer be in the controlling
4906 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4907 * intuit from the subprocess exit status whether a SIGINT
4908 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4910 if (jp->sigint) /* TODO: do the same with all signals */
4911 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4913 if (jp->state == JOBDONE)
4920 * return 1 if there are stopped jobs, otherwise 0
4932 if (jp && jp->state == JOBSTOPPED) {
4933 out2str("You have stopped jobs.\n");
4942 /* ============ redir.c
4944 * Code for dealing with input/output redirection.
4949 #define EMPTY -2 /* marks an unused slot in redirtab */
4950 #define CLOSED -3 /* marks a slot of previously-closed fd */
4953 * Open a file in noclobber mode.
4954 * The code was copied from bash.
4957 noclobberopen(const char *fname)
4960 struct stat finfo, finfo2;
4963 * If the file exists and is a regular file, return an error
4966 r = stat(fname, &finfo);
4967 if (r == 0 && S_ISREG(finfo.st_mode)) {
4973 * If the file was not present (r != 0), make sure we open it
4974 * exclusively so that if it is created before we open it, our open
4975 * will fail. Make sure that we do not truncate an existing file.
4976 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4977 * file was not a regular file, we leave O_EXCL off.
4980 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4981 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4983 /* If the open failed, return the file descriptor right away. */
4988 * OK, the open succeeded, but the file may have been changed from a
4989 * non-regular file to a regular file between the stat and the open.
4990 * We are assuming that the O_EXCL open handles the case where FILENAME
4991 * did not exist and is symlinked to an existing file between the stat
4996 * If we can open it and fstat the file descriptor, and neither check
4997 * revealed that it was a regular file, and the file has not been
4998 * replaced, return the file descriptor.
5000 if (fstat(fd, &finfo2) == 0
5001 && !S_ISREG(finfo2.st_mode)
5002 && finfo.st_dev == finfo2.st_dev
5003 && finfo.st_ino == finfo2.st_ino
5008 /* The file has been replaced. badness. */
5015 * Handle here documents. Normally we fork off a process to write the
5016 * data to a pipe. If the document is short, we can stuff the data in
5017 * the pipe without forking.
5019 /* openhere needs this forward reference */
5020 static void expandhere(union node *arg, int fd);
5022 openhere(union node *redir)
5028 ash_msg_and_raise_error("pipe call failed");
5029 if (redir->type == NHERE) {
5030 len = strlen(redir->nhere.doc->narg.text);
5031 if (len <= PIPE_BUF) {
5032 full_write(pip[1], redir->nhere.doc->narg.text, len);
5036 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5039 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5040 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5041 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5042 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5043 signal(SIGPIPE, SIG_DFL);
5044 if (redir->type == NHERE)
5045 full_write(pip[1], redir->nhere.doc->narg.text, len);
5047 expandhere(redir->nhere.doc, pip[1]);
5048 _exit(EXIT_SUCCESS);
5056 openredirect(union node *redir)
5061 switch (redir->nfile.type) {
5063 fname = redir->nfile.expfname;
5064 f = open(fname, O_RDONLY);
5069 fname = redir->nfile.expfname;
5070 f = open(fname, O_RDWR|O_CREAT, 0666);
5075 #if ENABLE_ASH_BASH_COMPAT
5078 /* Take care of noclobber mode. */
5080 fname = redir->nfile.expfname;
5081 f = noclobberopen(fname);
5088 fname = redir->nfile.expfname;
5089 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5094 fname = redir->nfile.expfname;
5095 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5103 /* Fall through to eliminate warning. */
5104 /* Our single caller does this itself */
5111 f = openhere(redir);
5117 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5119 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5123 * Copy a file descriptor to be >= to. Returns -1
5124 * if the source file descriptor is closed, EMPTY if there are no unused
5125 * file descriptors left.
5127 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5128 * old code was doing close(to) prior to copyfd() to achieve the same */
5130 COPYFD_EXACT = (int)~(INT_MAX),
5131 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5134 copyfd(int from, int to)
5138 if (to & COPYFD_EXACT) {
5139 to &= ~COPYFD_EXACT;
5141 newfd = dup2(from, to);
5143 newfd = fcntl(from, F_DUPFD, to);
5146 if (errno == EMFILE)
5148 /* Happens when source fd is not open: try "echo >&99" */
5149 ash_msg_and_raise_error("%d: %m", from);
5154 /* Struct def and variable are moved down to the first usage site */
5159 struct redirtab *next;
5162 struct two_fd_t two_fd[];
5164 #define redirlist (G_var.redirlist)
5166 static int need_to_remember(struct redirtab *rp, int fd)
5170 if (!rp) /* remembering was not requested */
5173 for (i = 0; i < rp->pair_count; i++) {
5174 if (rp->two_fd[i].orig == fd) {
5175 /* already remembered */
5182 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5183 static int is_hidden_fd(struct redirtab *rp, int fd)
5186 struct parsefile *pf;
5190 /* Check open scripts' fds */
5193 /* We skip pf_fd == 0 case because of the following case:
5194 * $ ash # running ash interactively
5196 * and in script.sh: "exec 9>&0".
5197 * Even though top-level pf_fd _is_ 0,
5198 * it's still ok to use it: "read" builtin uses it,
5199 * why should we cripple "exec" builtin?
5201 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5209 /* Check saved fds of redirects */
5210 fd |= COPYFD_RESTORE;
5211 for (i = 0; i < rp->pair_count; i++) {
5212 if (rp->two_fd[i].copy == fd) {
5220 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5221 * old file descriptors are stashed away so that the redirection can be
5222 * undone by calling popredir.
5224 /* flags passed to redirect */
5225 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5226 #define REDIR_SAVEFD2 03 /* set preverrout */
5228 redirect(union node *redir, int flags)
5230 struct redirtab *sv;
5235 int copied_fd2 = -1;
5245 if (flags & REDIR_PUSH) {
5246 union node *tmp = redir;
5249 #if ENABLE_ASH_BASH_COMPAT
5250 if (tmp->nfile.type == NTO2)
5253 tmp = tmp->nfile.next;
5255 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5256 sv->next = redirlist;
5257 sv->pair_count = sv_pos;
5259 sv->nullredirs = g_nullredirs - 1;
5261 while (sv_pos > 0) {
5263 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5269 fd = redir->nfile.fd;
5270 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5271 right_fd = redir->ndup.dupfd;
5272 //bb_error_msg("doing %d > %d", fd, right_fd);
5273 /* redirect from/to same file descriptor? */
5276 /* "echo >&10" and 10 is a fd opened to a sh script? */
5277 if (is_hidden_fd(sv, right_fd)) {
5278 errno = EBADF; /* as if it is closed */
5279 ash_msg_and_raise_error("%d: %m", right_fd);
5283 newfd = openredirect(redir); /* always >= 0 */
5285 /* Descriptor wasn't open before redirect.
5286 * Mark it for close in the future */
5287 if (need_to_remember(sv, fd)) {
5288 goto remember_to_close;
5293 #if ENABLE_ASH_BASH_COMPAT
5296 if (need_to_remember(sv, fd)) {
5297 /* Copy old descriptor */
5298 /* Careful to not accidentally "save"
5299 * to the same fd as right side fd in N>&M */
5300 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5301 i = fcntl(fd, F_DUPFD, minfd);
5302 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5303 * are closed in popredir() in the child, preventing them from leaking
5304 * into child. (popredir() also cleans up the mess in case of failures)
5309 /* Strange error (e.g. "too many files" EMFILE?) */
5313 ash_msg_and_raise_error("%d: %m", fd);
5316 /* EBADF: it is not open - good, remember to close it */
5319 } else { /* fd is open, save its copy */
5320 /* "exec fd>&-" should not close fds
5321 * which point to script file(s).
5322 * Force them to be restored afterwards */
5323 if (is_hidden_fd(sv, fd))
5324 i |= COPYFD_RESTORE;
5328 sv->two_fd[sv_pos].orig = fd;
5329 sv->two_fd[sv_pos].copy = i;
5333 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5334 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5335 /* Don't want to trigger debugging */
5339 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5341 } else if (fd != newfd) { /* move newfd to fd */
5342 copyfd(newfd, fd | COPYFD_EXACT);
5343 #if ENABLE_ASH_BASH_COMPAT
5344 if (!(redir->nfile.type == NTO2 && fd == 2))
5348 #if ENABLE_ASH_BASH_COMPAT
5349 if (redir->nfile.type == NTO2 && fd == 1) {
5350 /* We already redirected it to fd 1, now copy it to 2 */
5356 } while ((redir = redir->nfile.next) != NULL);
5359 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5360 preverrout_fd = copied_fd2;
5364 * Undo the effects of the last redirection.
5367 popredir(int drop, int restore)
5369 struct redirtab *rp;
5372 if (--g_nullredirs >= 0)
5376 for (i = 0; i < rp->pair_count; i++) {
5377 int fd = rp->two_fd[i].orig;
5378 int copy = rp->two_fd[i].copy;
5379 if (copy == CLOSED) {
5384 if (copy != EMPTY) {
5385 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5386 copy &= ~COPYFD_RESTORE;
5388 copyfd(copy, fd | COPYFD_EXACT);
5390 close(copy & ~COPYFD_RESTORE);
5393 redirlist = rp->next;
5394 g_nullredirs = rp->nullredirs;
5400 * Undo all redirections. Called on error or interrupt.
5404 * Discard all saved file descriptors.
5407 clearredir(int drop)
5413 popredir(drop, /*restore:*/ 0);
5418 redirectsafe(union node *redir, int flags)
5421 volatile int saveint;
5422 struct jmploc *volatile savehandler = exception_handler;
5423 struct jmploc jmploc;
5426 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5427 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5429 exception_handler = &jmploc;
5430 redirect(redir, flags);
5432 exception_handler = savehandler;
5433 if (err && exception_type != EXERROR)
5434 longjmp(exception_handler->loc, 1);
5435 RESTORE_INT(saveint);
5440 /* ============ Routines to expand arguments to commands
5442 * We have to deal with backquotes, shell variables, and file metacharacters.
5445 #if ENABLE_SH_MATH_SUPPORT
5447 ash_arith(const char *s)
5449 arith_state_t math_state;
5452 math_state.lookupvar = lookupvar;
5453 math_state.setvar = setvar2;
5454 //math_state.endofname = endofname;
5457 result = arith(&math_state, s);
5458 if (math_state.errmsg)
5459 ash_msg_and_raise_error(math_state.errmsg);
5469 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5470 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5471 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5472 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5473 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5474 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5475 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5476 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5477 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5481 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5482 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5483 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5484 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5485 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5488 * Structure specifying which parts of the string should be searched
5489 * for IFS characters.
5492 struct ifsregion *next; /* next region in list */
5493 int begoff; /* offset of start of region */
5494 int endoff; /* offset of end of region */
5495 int nulonly; /* search for nul bytes only */
5499 struct strlist *list;
5500 struct strlist **lastp;
5503 /* output of current string */
5504 static char *expdest;
5505 /* list of back quote expressions */
5506 static struct nodelist *argbackq;
5507 /* first struct in list of ifs regions */
5508 static struct ifsregion ifsfirst;
5509 /* last struct in list */
5510 static struct ifsregion *ifslastp;
5511 /* holds expanded arg list */
5512 static struct arglist exparg;
5517 #if !ENABLE_SH_MATH_SUPPORT
5518 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5519 typedef long arith_t;
5520 # define ARITH_FMT "%ld"
5527 expdest = makestrspace(32, expdest);
5528 len = fmtstr(expdest, 32, ARITH_FMT, num);
5529 STADJUST(len, expdest);
5534 esclen(const char *start, const char *p)
5538 while (p > start && (unsigned char)*--p == CTLESC) {
5545 * Remove any CTLESC characters from a string.
5548 rmescapes(char *str, int flag)
5550 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5554 unsigned protect_against_glob;
5557 p = strpbrk(str, qchars);
5563 if (flag & RMESCAPE_ALLOC) {
5564 size_t len = p - str;
5565 size_t fulllen = len + strlen(p) + 1;
5567 if (flag & RMESCAPE_GROW) {
5568 int strloc = str - (char *)stackblock();
5569 r = makestrspace(fulllen, expdest);
5570 /* p and str may be invalidated by makestrspace */
5571 str = (char *)stackblock() + strloc;
5573 } else if (flag & RMESCAPE_HEAP) {
5574 r = ckmalloc(fulllen);
5576 r = stalloc(fulllen);
5580 q = (char *)memcpy(q, str, len) + len;
5584 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5585 globbing = flag & RMESCAPE_GLOB;
5586 protect_against_glob = globbing;
5588 if ((unsigned char)*p == CTLQUOTEMARK) {
5589 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5590 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5591 // Note: both inquotes and protect_against_glob only affect whether
5592 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5593 inquotes = ~inquotes;
5595 protect_against_glob = globbing;
5599 /* naked back slash */
5600 protect_against_glob = 0;
5603 if ((unsigned char)*p == CTLESC) {
5605 if (protect_against_glob && inquotes && *p != '/') {
5609 protect_against_glob = globbing;
5614 if (flag & RMESCAPE_GROW) {
5616 STADJUST(q - r + 1, expdest);
5620 #define pmatch(a, b) !fnmatch((a), (b), 0)
5623 * Prepare a pattern for a expmeta (internal glob(3)) call.
5625 * Returns an stalloced string.
5628 preglob(const char *pattern, int quoted, int flag)
5630 flag |= RMESCAPE_GLOB;
5632 flag |= RMESCAPE_QUOTED;
5634 return rmescapes((char *)pattern, flag);
5638 * Put a string on the stack.
5641 memtodest(const char *p, size_t len, int syntax, int quotes)
5645 q = makestrspace(quotes ? len * 2 : len, q);
5648 unsigned char c = *p++;
5652 int n = SIT(c, syntax);
5653 if (n == CCTL || n == CBACK)
5663 strtodest(const char *p, int syntax, int quotes)
5665 memtodest(p, strlen(p), syntax, quotes);
5669 * Record the fact that we have to scan this region of the
5670 * string for IFS characters.
5673 recordregion(int start, int end, int nulonly)
5675 struct ifsregion *ifsp;
5677 if (ifslastp == NULL) {
5681 ifsp = ckzalloc(sizeof(*ifsp));
5682 /*ifsp->next = NULL; - ckzalloc did it */
5683 ifslastp->next = ifsp;
5687 ifslastp->begoff = start;
5688 ifslastp->endoff = end;
5689 ifslastp->nulonly = nulonly;
5693 removerecordregions(int endoff)
5695 if (ifslastp == NULL)
5698 if (ifsfirst.endoff > endoff) {
5699 while (ifsfirst.next) {
5700 struct ifsregion *ifsp;
5702 ifsp = ifsfirst.next->next;
5703 free(ifsfirst.next);
5704 ifsfirst.next = ifsp;
5707 if (ifsfirst.begoff > endoff) {
5710 ifslastp = &ifsfirst;
5711 ifsfirst.endoff = endoff;
5716 ifslastp = &ifsfirst;
5717 while (ifslastp->next && ifslastp->next->begoff < endoff)
5718 ifslastp = ifslastp->next;
5719 while (ifslastp->next) {
5720 struct ifsregion *ifsp;
5722 ifsp = ifslastp->next->next;
5723 free(ifslastp->next);
5724 ifslastp->next = ifsp;
5727 if (ifslastp->endoff > endoff)
5728 ifslastp->endoff = endoff;
5732 exptilde(char *startp, char *p, int flags)
5738 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5743 while ((c = *++p) != '\0') {
5750 if (flags & EXP_VARTILDE)
5760 if (*name == '\0') {
5761 home = lookupvar("HOME");
5763 pw = getpwnam(name);
5768 if (!home || !*home)
5771 startloc = expdest - (char *)stackblock();
5772 strtodest(home, SQSYNTAX, quotes);
5773 recordregion(startloc, expdest - (char *)stackblock(), 0);
5781 * Execute a command inside back quotes. If it's a builtin command, we
5782 * want to save its output in a block obtained from malloc. Otherwise
5783 * we fork off a subprocess and get the output of the command via a pipe.
5784 * Should be called with interrupts off.
5786 struct backcmd { /* result of evalbackcmd */
5787 int fd; /* file descriptor to read from */
5788 int nleft; /* number of chars in buffer */
5789 char *buf; /* buffer */
5790 struct job *jp; /* job structure for command */
5793 /* These forward decls are needed to use "eval" code for backticks handling: */
5794 static uint8_t back_exitstatus; /* exit status of backquoted command */
5795 #define EV_EXIT 01 /* exit after evaluating tree */
5796 static void evaltree(union node *, int);
5798 static void FAST_FUNC
5799 evalbackcmd(union node *n, struct backcmd *result)
5810 saveherefd = herefd;
5818 ash_msg_and_raise_error("pipe call failed");
5819 jp = makejob(/*n,*/ 1);
5820 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5825 copyfd(pip[1], 1 | COPYFD_EXACT);
5829 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5833 result->fd = pip[0];
5836 herefd = saveherefd;
5838 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5839 result->fd, result->buf, result->nleft, result->jp));
5843 * Expand stuff in backwards quotes.
5846 expbackq(union node *cmd, int quoted, int quotes)
5854 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5855 struct stackmark smark;
5858 setstackmark(&smark);
5860 startloc = dest - (char *)stackblock();
5862 evalbackcmd(cmd, &in);
5863 popstackmark(&smark);
5870 memtodest(p, i, syntax, quotes);
5874 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5875 TRACE(("expbackq: read returns %d\n", i));
5884 back_exitstatus = waitforjob(in.jp);
5888 /* Eat all trailing newlines */
5890 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5895 recordregion(startloc, dest - (char *)stackblock(), 0);
5896 TRACE(("evalbackq: size:%d:'%.*s'\n",
5897 (int)((dest - (char *)stackblock()) - startloc),
5898 (int)((dest - (char *)stackblock()) - startloc),
5899 stackblock() + startloc));
5902 #if ENABLE_SH_MATH_SUPPORT
5904 * Expand arithmetic expression. Backup to start of expression,
5905 * evaluate, place result in (backed up) result, adjust string position.
5918 * This routine is slightly over-complicated for
5919 * efficiency. Next we scan backwards looking for the
5920 * start of arithmetic.
5922 start = stackblock();
5929 while ((unsigned char)*p != CTLARI) {
5933 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5938 esc = esclen(start, p);
5948 removerecordregions(begoff);
5955 rmescapes(p + 2, 0);
5957 len = cvtnum(ash_arith(p + 2));
5960 recordregion(begoff, begoff + len, 0);
5964 /* argstr needs it */
5965 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5968 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5969 * characters to allow for further processing. Otherwise treat
5970 * $@ like $* since no splitting will be performed.
5972 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5973 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5974 * for correct expansion of "B=$A" word.
5977 argstr(char *p, int flags, struct strlist *var_str_list)
5979 static const char spclchars[] ALIGN1 = {
5987 CTLBACKQ | CTLQUOTE,
5988 #if ENABLE_SH_MATH_SUPPORT
5993 const char *reject = spclchars;
5994 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5995 int breakall = flags & EXP_WORD;
6000 if (!(flags & EXP_VARTILDE)) {
6002 } else if (flags & EXP_VARTILDE2) {
6007 if (flags & EXP_TILDE) {
6010 flags &= ~EXP_TILDE;
6013 if ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
6016 p = exptilde(p, q, flags);
6019 startloc = expdest - (char *)stackblock();
6023 length += strcspn(p + length, reject);
6027 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6029 /* c == '=' || c == ':' || c == CTLENDARI */
6035 expdest = stack_nputstr(p, length, expdest);
6036 newloc = expdest - (char *)stackblock();
6037 if (breakall && !inquotes && newloc > startloc) {
6038 recordregion(startloc, newloc, 0);
6049 if (flags & EXP_VARTILDE2) {
6053 flags |= EXP_VARTILDE2;
6058 * sort of a hack - expand tildes in variable
6059 * assignments (after the first '=' and after ':'s).
6068 case CTLENDVAR: /* ??? */
6071 /* "$@" syntax adherence hack */
6073 && memcmp(p, dolatstr, 4) == 0
6074 && ( p[4] == (char)CTLQUOTEMARK
6075 || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
6078 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
6081 inquotes = !inquotes;
6094 p = evalvar(p, flags, var_str_list);
6098 case CTLBACKQ|CTLQUOTE:
6099 expbackq(argbackq->n, c, quotes);
6100 argbackq = argbackq->next;
6102 #if ENABLE_SH_MATH_SUPPORT
6114 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6115 char *pattern, int quotes, int zero)
6124 const char *s = loc2;
6131 match = pmatch(pattern, s);
6136 if (quotes && (unsigned char)*loc == CTLESC)
6145 scanright(char *startp, char *rmesc, char *rmescend,
6146 char *pattern, int quotes, int match_at_start)
6148 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6149 int try2optimize = match_at_start;
6155 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6156 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6157 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6159 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6160 * and on each iteration they go back two/one char until they reach the beginning.
6161 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6163 /* TODO: document in what other circumstances we are called. */
6165 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6168 const char *s = loc2;
6169 if (match_at_start) {
6173 match = pmatch(pattern, s);
6174 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6178 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6180 /* Maybe we can optimize this:
6181 * if pattern ends with unescaped *, we can avoid checking
6182 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6183 * it wont match truncated "raw_value_of_" strings too.
6185 unsigned plen = strlen(pattern);
6186 /* Does it end with "*"? */
6187 if (plen != 0 && pattern[--plen] == '*') {
6188 /* "xxxx*" is not escaped */
6189 /* "xxx\*" is escaped */
6190 /* "xx\\*" is not escaped */
6191 /* "x\\\*" is escaped */
6193 while (plen != 0 && pattern[--plen] == '\\')
6196 break; /* ends with unescaped "*" */
6204 esc = esclen(startp, loc);
6215 static void varunset(const char *, const char *, const char *, int) NORETURN;
6217 varunset(const char *end, const char *var, const char *umsg, int varflags)
6223 msg = "parameter not set";
6225 if ((unsigned char)*end == CTLENDVAR) {
6226 if (varflags & VSNUL)
6232 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6235 #if ENABLE_ASH_BASH_COMPAT
6237 parse_sub_pattern(char *arg, int varflags)
6239 char *idx, *repl = NULL;
6242 //char *org_arg = arg;
6243 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
6250 /* Only the first '/' seen is our separator */
6259 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6260 * The result is a_\_z_c (not a\_\_z_c)!
6262 * Enable debug prints in this function and you'll see:
6263 * ash: arg:'\\b/_\\_z_' varflags:d
6264 * ash: pattern:'\\b' repl:'_\_z_'
6265 * That is, \\b is interpreted as \\b, but \\_ as \_!
6266 * IOW: search pattern and replace string treat backslashes
6267 * differently! That is the reason why we check repl below:
6269 if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
6270 arg++; /* skip both '\', not just first one */
6273 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
6277 #endif /* ENABLE_ASH_BASH_COMPAT */
6280 subevalvar(char *p, char *varname, int strloc, int subtype,
6281 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6283 struct nodelist *saveargbackq = argbackq;
6286 char *rmesc, *rmescend;
6288 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
6289 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6290 int saveherefd = herefd;
6291 int amount, workloc, resetloc;
6293 char *(*scan)(char*, char*, char*, char*, int, int);
6295 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6296 // p, varname, strloc, subtype, startloc, varflags, quotes);
6299 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6301 STPUTC('\0', expdest);
6302 herefd = saveherefd;
6303 argbackq = saveargbackq;
6304 startp = (char *)stackblock() + startloc;
6308 setvar(varname, startp, 0);
6309 amount = startp - expdest;
6310 STADJUST(amount, expdest);
6314 varunset(p, varname, startp, varflags);
6317 #if ENABLE_ASH_BASH_COMPAT
6319 loc = str = stackblock() + strloc;
6320 /* Read POS in ${var:POS:LEN} */
6321 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6322 len = str - startp - 1;
6324 /* *loc != '\0', guaranteed by parser */
6328 /* Adjust the length by the number of escapes */
6329 for (ptr = startp; ptr < (str - 1); ptr++) {
6330 if ((unsigned char)*ptr == CTLESC) {
6338 if (*loc++ == ':') {
6342 /* Skip POS in ${var:POS:LEN} */
6344 while (*loc && *loc != ':') {
6346 * bash complains on: var=qwe; echo ${var:1a:123}
6348 ash_msg_and_raise_error(msg_illnum, str);
6352 if (*loc++ == ':') {
6356 if (pos >= orig_len) {
6360 if (len > (orig_len - pos))
6361 len = orig_len - pos;
6363 for (str = startp; pos; str++, pos--) {
6364 if (quotes && (unsigned char)*str == CTLESC)
6367 for (loc = startp; len; len--) {
6368 if (quotes && (unsigned char)*str == CTLESC)
6373 amount = loc - expdest;
6374 STADJUST(amount, expdest);
6379 resetloc = expdest - (char *)stackblock();
6381 /* We'll comeback here if we grow the stack while handling
6382 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6383 * stack will need rebasing, and we'll need to remove our work
6386 IF_ASH_BASH_COMPAT(restart:)
6388 amount = expdest - ((char *)stackblock() + resetloc);
6389 STADJUST(-amount, expdest);
6390 startp = (char *)stackblock() + startloc;
6393 rmescend = (char *)stackblock() + strloc;
6395 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6396 if (rmesc != startp) {
6398 startp = (char *)stackblock() + startloc;
6402 str = (char *)stackblock() + strloc;
6403 preglob(str, varflags & VSQUOTE, 0);
6404 workloc = expdest - (char *)stackblock();
6406 #if ENABLE_ASH_BASH_COMPAT
6407 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6411 repl = parse_sub_pattern(str, varflags);
6412 //bb_error_msg("repl:'%s'", repl);
6417 /* If there's no pattern to match, return the expansion unmolested */
6426 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6427 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6429 /* No match, advance */
6430 char *restart_detect = stackblock();
6432 STPUTC(*idx, expdest);
6433 if (quotes && (unsigned char)*idx == CTLESC) {
6436 STPUTC(*idx, expdest);
6438 if (stackblock() != restart_detect)
6443 /* continue; - prone to quadratic behavior, smarter code: */
6446 if (str[0] == '*') {
6447 /* Pattern is "*foo". If "*foo" does not match "long_string",
6448 * it would never match "ong_string" etc, no point in trying.
6455 if (subtype == VSREPLACEALL) {
6457 if (quotes && (unsigned char)*idx == CTLESC)
6466 //bb_error_msg("repl:'%s'", repl);
6467 for (loc = (char*)repl; *loc; loc++) {
6468 char *restart_detect = stackblock();
6469 if (quotes && *loc == '\\') {
6470 STPUTC(CTLESC, expdest);
6473 STPUTC(*loc, expdest);
6474 if (stackblock() != restart_detect)
6479 if (subtype == VSREPLACE) {
6480 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6482 char *restart_detect = stackblock();
6483 STPUTC(*idx, expdest);
6484 if (stackblock() != restart_detect)
6493 /* We've put the replaced text into a buffer at workloc, now
6494 * move it to the right place and adjust the stack.
6496 STPUTC('\0', expdest);
6497 startp = (char *)stackblock() + startloc;
6498 memmove(startp, (char *)stackblock() + workloc, len + 1);
6499 //bb_error_msg("startp:'%s'", startp);
6500 amount = expdest - (startp + len);
6501 STADJUST(-amount, expdest);
6504 #endif /* ENABLE_ASH_BASH_COMPAT */
6506 subtype -= VSTRIMRIGHT;
6508 if (subtype < 0 || subtype > 7)
6511 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6512 zero = subtype >> 1;
6513 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6514 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6516 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6519 memmove(startp, loc, str - loc);
6520 loc = startp + (str - loc) - 1;
6523 amount = loc - expdest;
6524 STADJUST(amount, expdest);
6530 * Add the value of a specialized variable to the stack string.
6531 * name parameter (examples):
6532 * ash -c 'echo $1' name:'1='
6533 * ash -c 'echo $qwe' name:'qwe='
6534 * ash -c 'echo $$' name:'$='
6535 * ash -c 'echo ${$}' name:'$='
6536 * ash -c 'echo ${$##q}' name:'$=q'
6537 * ash -c 'echo ${#$}' name:'$='
6538 * note: examples with bad shell syntax:
6539 * ash -c 'echo ${#$1}' name:'$=1'
6540 * ash -c 'echo ${#1#}' name:'1=#'
6542 static NOINLINE ssize_t
6543 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6550 int subtype = varflags & VSTYPE;
6551 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6552 int quoted = varflags & VSQUOTE;
6553 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6563 num = shellparam.nparam;
6571 goto check_1char_name;
6573 expdest = makestrspace(NOPTS, expdest);
6574 for (i = NOPTS - 1; i >= 0; i--) {
6576 USTPUTC(optletters(i), expdest);
6582 /* handles cases similar to ${#$1} */
6583 if (name[2] != '\0')
6584 raise_error_syntax("bad substitution");
6591 if (quoted && (flags & EXP_FULL)) {
6592 /* note: this is not meant as PEOF value */
6593 sep = 1 << CHAR_BIT;
6598 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6599 i = SIT(sep, syntax);
6600 if (quotes && (i == CCTL || i == CBACK))
6606 while ((p = *ap++) != NULL) {
6609 partlen = strlen(p);
6612 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6613 memtodest(p, partlen, syntax, quotes);
6619 if (subtype == VSPLUS || subtype == VSLENGTH) {
6625 /* note: may put NUL despite sep != 0
6626 * (see sep = 1 << CHAR_BIT above) */
6632 } /* case '@' and '*' */
6643 num = atoi(name); /* number(name) fails on ${N#str} etc */
6644 if (num < 0 || num > shellparam.nparam)
6646 p = num ? shellparam.p[num - 1] : arg0;
6649 /* NB: name has form "VAR=..." */
6651 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6652 * which should be considered before we check variables. */
6654 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6658 str = var_str_list->text;
6659 eq = strchr(str, '=');
6660 if (!eq) /* stop at first non-assignment */
6663 if (name_len == (unsigned)(eq - str)
6664 && strncmp(str, name, name_len) == 0
6667 /* goto value; - WRONG! */
6668 /* think "A=1 A=2 B=$A" */
6670 var_str_list = var_str_list->next;
6671 } while (var_str_list);
6675 p = lookupvar(name);
6681 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6682 memtodest(p, len, syntax, quotes);
6686 if (subtype == VSPLUS || subtype == VSLENGTH)
6687 STADJUST(-len, expdest);
6692 * Expand a variable, and return a pointer to the next character in the
6696 evalvar(char *p, int flags, struct strlist *var_str_list)
6707 varflags = (unsigned char) *p++;
6708 subtype = varflags & VSTYPE;
6709 quoted = varflags & VSQUOTE;
6711 easy = (!quoted || (*var == '@' && shellparam.nparam));
6712 startloc = expdest - (char *)stackblock();
6713 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6716 varlen = varvalue(var, varflags, flags, var_str_list);
6717 if (varflags & VSNUL)
6720 if (subtype == VSPLUS) {
6721 varlen = -1 - varlen;
6725 if (subtype == VSMINUS) {
6730 flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
6740 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6742 if (subevalvar(p, var, /* strloc: */ 0,
6743 subtype, startloc, varflags,
6749 * Remove any recorded regions beyond
6752 removerecordregions(startloc);
6762 if (varlen < 0 && uflag)
6763 varunset(p, var, 0, 0);
6765 if (subtype == VSLENGTH) {
6766 cvtnum(varlen > 0 ? varlen : 0);
6770 if (subtype == VSNORMAL) {
6781 case VSTRIMRIGHTMAX:
6782 #if ENABLE_ASH_BASH_COMPAT
6795 * Terminate the string and start recording the pattern
6798 STPUTC('\0', expdest);
6799 patloc = expdest - (char *)stackblock();
6800 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6802 //TODO: | EXP_REDIR too? All other such places do it too
6803 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6806 int amount = expdest - (
6807 (char *)stackblock() + patloc - 1
6809 STADJUST(-amount, expdest);
6811 /* Remove any recorded regions beyond start of variable */
6812 removerecordregions(startloc);
6814 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6818 if (subtype != VSNORMAL) { /* skip to end of alternative */
6821 unsigned char c = *p++;
6824 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6826 argbackq = argbackq->next;
6827 } else if (c == CTLVAR) {
6828 if ((*p++ & VSTYPE) != VSNORMAL)
6830 } else if (c == CTLENDVAR) {
6840 * Break the argument string into pieces based upon IFS and add the
6841 * strings to the argument list. The regions of the string to be
6842 * searched for IFS characters have been stored by recordregion.
6845 ifsbreakup(char *string, struct arglist *arglist)
6847 struct ifsregion *ifsp;
6852 const char *ifs, *realifs;
6857 if (ifslastp != NULL) {
6860 realifs = ifsset() ? ifsval() : defifs;
6863 p = string + ifsp->begoff;
6864 nulonly = ifsp->nulonly;
6865 ifs = nulonly ? nullstr : realifs;
6867 while (p < string + ifsp->endoff) {
6869 if ((unsigned char)*p == CTLESC)
6871 if (!strchr(ifs, *p)) {
6876 ifsspc = (strchr(defifs, *p) != NULL);
6877 /* Ignore IFS whitespace at start */
6878 if (q == start && ifsspc) {
6884 sp = stzalloc(sizeof(*sp));
6886 *arglist->lastp = sp;
6887 arglist->lastp = &sp->next;
6891 if (p >= string + ifsp->endoff) {
6895 if ((unsigned char)*p == CTLESC)
6897 if (strchr(ifs, *p) == NULL) {
6901 if (strchr(defifs, *p) == NULL) {
6916 } while (ifsp != NULL);
6925 sp = stzalloc(sizeof(*sp));
6927 *arglist->lastp = sp;
6928 arglist->lastp = &sp->next;
6934 struct ifsregion *p;
6939 struct ifsregion *ifsp;
6945 ifsfirst.next = NULL;
6950 * Add a file name to the list.
6953 addfname(const char *name)
6957 sp = stzalloc(sizeof(*sp));
6958 sp->text = ststrdup(name);
6960 exparg.lastp = &sp->next;
6964 * Do metacharacter (i.e. *, ?, [...]) expansion.
6967 expmeta(char *expdir, char *enddir, char *name)
6982 for (p = name; *p; p++) {
6983 if (*p == '*' || *p == '?')
6985 else if (*p == '[') {
6992 if (*q == '/' || *q == '\0')
6999 } else if (*p == '\\')
7001 else if (*p == '/') {
7008 if (metaflag == 0) { /* we've reached the end of the file name */
7009 if (enddir != expdir)
7017 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7028 } while (p < start);
7030 if (enddir == expdir) {
7032 } else if (enddir == expdir + 1 && *expdir == '/') {
7041 if (enddir != expdir)
7043 if (*endname == 0) {
7055 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7056 if (dp->d_name[0] == '.' && !matchdot)
7058 if (pmatch(start, dp->d_name)) {
7060 strcpy(enddir, dp->d_name);
7063 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7066 expmeta(expdir, p, endname);
7075 static struct strlist *
7076 msort(struct strlist *list, int len)
7078 struct strlist *p, *q = NULL;
7079 struct strlist **lpp;
7087 for (n = half; --n >= 0;) {
7091 q->next = NULL; /* terminate first half of list */
7092 q = msort(list, half); /* sort first half of list */
7093 p = msort(p, len - half); /* sort second half */
7096 #if ENABLE_LOCALE_SUPPORT
7097 if (strcoll(p->text, q->text) < 0)
7099 if (strcmp(p->text, q->text) < 0)
7123 * Sort the results of file name expansion. It calculates the number of
7124 * strings to sort and then calls msort (short for merge sort) to do the
7127 static struct strlist *
7128 expsort(struct strlist *str)
7134 for (sp = str; sp; sp = sp->next)
7136 return msort(str, len);
7140 expandmeta(struct strlist *str /*, int flag*/)
7142 static const char metachars[] ALIGN1 = {
7145 /* TODO - EXP_REDIR */
7149 struct strlist **savelastp;
7155 if (!strpbrk(str->text, metachars))
7157 savelastp = exparg.lastp;
7160 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7162 int i = strlen(str->text);
7163 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7165 expmeta(expdir, expdir, p);
7170 if (exparg.lastp == savelastp) {
7175 *exparg.lastp = str;
7176 rmescapes(str->text, 0);
7177 exparg.lastp = &str->next;
7179 *exparg.lastp = NULL;
7180 *savelastp = sp = expsort(*savelastp);
7181 while (sp->next != NULL)
7183 exparg.lastp = &sp->next;
7190 * Perform variable substitution and command substitution on an argument,
7191 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7192 * perform splitting and file name expansion. When arglist is NULL, perform
7193 * here document expansion.
7196 expandarg(union node *arg, struct arglist *arglist, int flag)
7201 argbackq = arg->narg.backquote;
7202 STARTSTACKSTR(expdest);
7203 ifsfirst.next = NULL;
7205 argstr(arg->narg.text, flag,
7206 /* var_str_list: */ arglist ? arglist->list : NULL);
7207 p = _STPUTC('\0', expdest);
7209 if (arglist == NULL) {
7210 return; /* here document expanded */
7212 p = grabstackstr(p);
7213 exparg.lastp = &exparg.list;
7217 if (flag & EXP_FULL) {
7218 ifsbreakup(p, &exparg);
7219 *exparg.lastp = NULL;
7220 exparg.lastp = &exparg.list;
7221 expandmeta(exparg.list /*, flag*/);
7223 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7225 sp = stzalloc(sizeof(*sp));
7228 exparg.lastp = &sp->next;
7232 *exparg.lastp = NULL;
7234 *arglist->lastp = exparg.list;
7235 arglist->lastp = exparg.lastp;
7240 * Expand shell variables and backquotes inside a here document.
7243 expandhere(union node *arg, int fd)
7246 expandarg(arg, (struct arglist *)NULL, 0);
7247 full_write(fd, stackblock(), expdest - (char *)stackblock());
7251 * Returns true if the pattern matches the string.
7254 patmatch(char *pattern, const char *string)
7256 return pmatch(preglob(pattern, 0, 0), string);
7260 * See if a pattern matches in a case statement.
7263 casematch(union node *pattern, char *val)
7265 struct stackmark smark;
7268 setstackmark(&smark);
7269 argbackq = pattern->narg.backquote;
7270 STARTSTACKSTR(expdest);
7272 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7273 /* var_str_list: */ NULL);
7274 STACKSTRNUL(expdest);
7275 result = patmatch(stackblock(), val);
7276 popstackmark(&smark);
7281 /* ============ find_command */
7285 int (*builtin)(int, char **) FAST_FUNC;
7286 /* unsigned flags; */
7288 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7289 /* "regular" builtins always take precedence over commands,
7290 * regardless of PATH=....%builtin... position */
7291 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7292 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7295 smallint cmdtype; /* CMDxxx */
7298 /* index >= 0 for commands without path (slashes) */
7299 /* (TODO: what exactly does the value mean? PATH position?) */
7300 /* index == -1 for commands with slashes */
7301 /* index == (-2 - applet_no) for NOFORK applets */
7302 const struct builtincmd *cmd;
7303 struct funcnode *func;
7306 /* values of cmdtype */
7307 #define CMDUNKNOWN -1 /* no entry in table for command */
7308 #define CMDNORMAL 0 /* command is an executable program */
7309 #define CMDFUNCTION 1 /* command is a shell function */
7310 #define CMDBUILTIN 2 /* command is a shell builtin */
7312 /* action to find_command() */
7313 #define DO_ERR 0x01 /* prints errors */
7314 #define DO_ABS 0x02 /* checks absolute paths */
7315 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7316 #define DO_ALTPATH 0x08 /* using alternate path */
7317 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7319 static void find_command(char *, struct cmdentry *, int, const char *);
7322 /* ============ Hashing commands */
7325 * When commands are first encountered, they are entered in a hash table.
7326 * This ensures that a full path search will not have to be done for them
7327 * on each invocation.
7329 * We should investigate converting to a linear search, even though that
7330 * would make the command name "hash" a misnomer.
7334 struct tblentry *next; /* next entry in hash chain */
7335 union param param; /* definition of builtin function */
7336 smallint cmdtype; /* CMDxxx */
7337 char rehash; /* if set, cd done since entry created */
7338 char cmdname[1]; /* name of command */
7341 static struct tblentry **cmdtable;
7342 #define INIT_G_cmdtable() do { \
7343 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7346 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7350 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7354 #if ENABLE_FEATURE_SH_STANDALONE
7355 if (applet_no >= 0) {
7356 if (APPLET_IS_NOEXEC(applet_no)) {
7360 run_applet_no_and_exit(applet_no, argv);
7362 /* re-exec ourselves with the new arguments */
7363 execve(bb_busybox_exec_path, argv, envp);
7364 /* If they called chroot or otherwise made the binary no longer
7365 * executable, fall through */
7372 execve(cmd, argv, envp);
7373 } while (errno == EINTR);
7375 execve(cmd, argv, envp);
7381 if (errno == ENOEXEC) {
7385 for (ap = argv; *ap; ap++)
7387 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7389 ap[0] = cmd = (char *)DEFAULT_SHELL;
7392 while ((*ap++ = *argv++) != NULL)
7401 * Exec a program. Never returns. If you change this routine, you may
7402 * have to change the find_command routine as well.
7404 static void shellexec(char **, const char *, int) NORETURN;
7406 shellexec(char **argv, const char *path, int idx)
7412 #if ENABLE_FEATURE_SH_STANDALONE
7416 clearredir(/*drop:*/ 1);
7417 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7418 if (strchr(argv[0], '/') != NULL
7419 #if ENABLE_FEATURE_SH_STANDALONE
7420 || (applet_no = find_applet_by_name(argv[0])) >= 0
7423 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7427 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7428 if (--idx < 0 && pathopt == NULL) {
7429 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7430 if (errno != ENOENT && errno != ENOTDIR)
7437 /* Map to POSIX errors */
7449 exitstatus = exerrno;
7450 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7451 argv[0], e, suppress_int));
7452 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7457 printentry(struct tblentry *cmdp)
7463 idx = cmdp->param.index;
7466 name = path_advance(&path, cmdp->cmdname);
7468 } while (--idx >= 0);
7469 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7473 * Clear out command entries. The argument specifies the first entry in
7474 * PATH which has changed.
7477 clearcmdentry(int firstchange)
7479 struct tblentry **tblp;
7480 struct tblentry **pp;
7481 struct tblentry *cmdp;
7484 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7486 while ((cmdp = *pp) != NULL) {
7487 if ((cmdp->cmdtype == CMDNORMAL &&
7488 cmdp->param.index >= firstchange)
7489 || (cmdp->cmdtype == CMDBUILTIN &&
7490 builtinloc >= firstchange)
7503 * Locate a command in the command hash table. If "add" is nonzero,
7504 * add the command to the table if it is not already present. The
7505 * variable "lastcmdentry" is set to point to the address of the link
7506 * pointing to the entry, so that delete_cmd_entry can delete the
7509 * Interrupts must be off if called with add != 0.
7511 static struct tblentry **lastcmdentry;
7513 static struct tblentry *
7514 cmdlookup(const char *name, int add)
7516 unsigned int hashval;
7518 struct tblentry *cmdp;
7519 struct tblentry **pp;
7522 hashval = (unsigned char)*p << 4;
7524 hashval += (unsigned char)*p++;
7526 pp = &cmdtable[hashval % CMDTABLESIZE];
7527 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7528 if (strcmp(cmdp->cmdname, name) == 0)
7532 if (add && cmdp == NULL) {
7533 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7535 /* + 1 - already done because
7536 * tblentry::cmdname is char[1] */);
7537 /*cmdp->next = NULL; - ckzalloc did it */
7538 cmdp->cmdtype = CMDUNKNOWN;
7539 strcpy(cmdp->cmdname, name);
7546 * Delete the command entry returned on the last lookup.
7549 delete_cmd_entry(void)
7551 struct tblentry *cmdp;
7554 cmdp = *lastcmdentry;
7555 *lastcmdentry = cmdp->next;
7556 if (cmdp->cmdtype == CMDFUNCTION)
7557 freefunc(cmdp->param.func);
7563 * Add a new command entry, replacing any existing command entry for
7564 * the same name - except special builtins.
7567 addcmdentry(char *name, struct cmdentry *entry)
7569 struct tblentry *cmdp;
7571 cmdp = cmdlookup(name, 1);
7572 if (cmdp->cmdtype == CMDFUNCTION) {
7573 freefunc(cmdp->param.func);
7575 cmdp->cmdtype = entry->cmdtype;
7576 cmdp->param = entry->u;
7580 static int FAST_FUNC
7581 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7583 struct tblentry **pp;
7584 struct tblentry *cmdp;
7586 struct cmdentry entry;
7589 if (nextopt("r") != '\0') {
7594 if (*argptr == NULL) {
7595 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7596 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7597 if (cmdp->cmdtype == CMDNORMAL)
7605 while ((name = *argptr) != NULL) {
7606 cmdp = cmdlookup(name, 0);
7608 && (cmdp->cmdtype == CMDNORMAL
7609 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7613 find_command(name, &entry, DO_ERR, pathval());
7614 if (entry.cmdtype == CMDUNKNOWN)
7622 * Called when a cd is done. Marks all commands so the next time they
7623 * are executed they will be rehashed.
7628 struct tblentry **pp;
7629 struct tblentry *cmdp;
7631 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7632 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7633 if (cmdp->cmdtype == CMDNORMAL
7634 || (cmdp->cmdtype == CMDBUILTIN
7635 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7645 * Fix command hash table when PATH changed.
7646 * Called before PATH is changed. The argument is the new value of PATH;
7647 * pathval() still returns the old value at this point.
7648 * Called with interrupts off.
7650 static void FAST_FUNC
7651 changepath(const char *new)
7659 firstchange = 9999; /* assume no change */
7665 if ((*old == '\0' && *new == ':')
7666 || (*old == ':' && *new == '\0')
7670 old = new; /* ignore subsequent differences */
7674 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7681 if (builtinloc < 0 && idx_bltin >= 0)
7682 builtinloc = idx_bltin; /* zap builtins */
7683 if (builtinloc >= 0 && idx_bltin < 0)
7685 clearcmdentry(firstchange);
7686 builtinloc = idx_bltin;
7701 #define TENDBQUOTE 12
7718 typedef smallint token_id_t;
7720 /* first char is indicating which tokens mark the end of a list */
7721 static const char *const tokname_array[] = {
7735 #define KWDOFFSET 13
7736 /* the following are keywords */
7755 /* Wrapper around strcmp for qsort/bsearch/... */
7757 pstrcmp(const void *a, const void *b)
7759 return strcmp((char*) a, (*(char**) b) + 1);
7762 static const char *const *
7763 findkwd(const char *s)
7765 return bsearch(s, tokname_array + KWDOFFSET,
7766 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7767 sizeof(tokname_array[0]), pstrcmp);
7771 * Locate and print what a word is...
7774 describe_command(char *command, int describe_command_verbose)
7776 struct cmdentry entry;
7777 struct tblentry *cmdp;
7778 #if ENABLE_ASH_ALIAS
7779 const struct alias *ap;
7781 const char *path = pathval();
7783 if (describe_command_verbose) {
7787 /* First look at the keywords */
7788 if (findkwd(command)) {
7789 out1str(describe_command_verbose ? " is a shell keyword" : command);
7793 #if ENABLE_ASH_ALIAS
7794 /* Then look at the aliases */
7795 ap = lookupalias(command, 0);
7797 if (!describe_command_verbose) {
7802 out1fmt(" is an alias for %s", ap->val);
7806 /* Then check if it is a tracked alias */
7807 cmdp = cmdlookup(command, 0);
7809 entry.cmdtype = cmdp->cmdtype;
7810 entry.u = cmdp->param;
7812 /* Finally use brute force */
7813 find_command(command, &entry, DO_ABS, path);
7816 switch (entry.cmdtype) {
7818 int j = entry.u.index;
7824 p = path_advance(&path, command);
7828 if (describe_command_verbose) {
7830 (cmdp ? " a tracked alias for" : nullstr), p
7839 if (describe_command_verbose) {
7840 out1str(" is a shell function");
7847 if (describe_command_verbose) {
7848 out1fmt(" is a %sshell builtin",
7849 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7850 "special " : nullstr
7858 if (describe_command_verbose) {
7859 out1str(": not found\n");
7868 static int FAST_FUNC
7869 typecmd(int argc UNUSED_PARAM, char **argv)
7875 /* type -p ... ? (we don't bother checking for 'p') */
7876 if (argv[1] && argv[1][0] == '-') {
7881 err |= describe_command(argv[i++], verbose);
7886 #if ENABLE_ASH_CMDCMD
7887 static int FAST_FUNC
7888 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7896 while ((c = nextopt("pvV")) != '\0')
7898 verify |= VERIFY_VERBOSE;
7900 verify |= VERIFY_BRIEF;
7905 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7906 if (verify && (*argptr != NULL)) {
7907 return describe_command(*argptr, verify - VERIFY_BRIEF);
7915 /* ============ eval.c */
7917 static int funcblocksize; /* size of structures in function */
7918 static int funcstringsize; /* size of strings in node */
7919 static void *funcblock; /* block to allocate function from */
7920 static char *funcstring; /* block to allocate strings from */
7922 /* flags in argument to evaltree */
7923 #define EV_EXIT 01 /* exit after evaluating tree */
7924 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7925 #define EV_BACKCMD 04 /* command executing within back quotes */
7927 static const uint8_t nodesize[N_NUMBER] = {
7928 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7929 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7930 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7931 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7932 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7933 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7934 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7935 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7936 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7937 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7938 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7939 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7940 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7941 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7942 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7943 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7944 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7945 #if ENABLE_ASH_BASH_COMPAT
7946 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7948 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7949 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7950 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7951 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7952 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7953 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7954 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7955 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7956 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7959 static void calcsize(union node *n);
7962 sizenodelist(struct nodelist *lp)
7965 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7972 calcsize(union node *n)
7976 funcblocksize += nodesize[n->type];
7979 calcsize(n->ncmd.redirect);
7980 calcsize(n->ncmd.args);
7981 calcsize(n->ncmd.assign);
7984 sizenodelist(n->npipe.cmdlist);
7989 calcsize(n->nredir.redirect);
7990 calcsize(n->nredir.n);
7997 calcsize(n->nbinary.ch2);
7998 calcsize(n->nbinary.ch1);
8001 calcsize(n->nif.elsepart);
8002 calcsize(n->nif.ifpart);
8003 calcsize(n->nif.test);
8006 funcstringsize += strlen(n->nfor.var) + 1;
8007 calcsize(n->nfor.body);
8008 calcsize(n->nfor.args);
8011 calcsize(n->ncase.cases);
8012 calcsize(n->ncase.expr);
8015 calcsize(n->nclist.body);
8016 calcsize(n->nclist.pattern);
8017 calcsize(n->nclist.next);
8021 sizenodelist(n->narg.backquote);
8022 funcstringsize += strlen(n->narg.text) + 1;
8023 calcsize(n->narg.next);
8026 #if ENABLE_ASH_BASH_COMPAT
8033 calcsize(n->nfile.fname);
8034 calcsize(n->nfile.next);
8038 calcsize(n->ndup.vname);
8039 calcsize(n->ndup.next);
8043 calcsize(n->nhere.doc);
8044 calcsize(n->nhere.next);
8047 calcsize(n->nnot.com);
8053 nodeckstrdup(char *s)
8055 char *rtn = funcstring;
8057 strcpy(funcstring, s);
8058 funcstring += strlen(s) + 1;
8062 static union node *copynode(union node *);
8064 static struct nodelist *
8065 copynodelist(struct nodelist *lp)
8067 struct nodelist *start;
8068 struct nodelist **lpp;
8073 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8074 (*lpp)->n = copynode(lp->n);
8076 lpp = &(*lpp)->next;
8083 copynode(union node *n)
8090 funcblock = (char *) funcblock + nodesize[n->type];
8094 new->ncmd.redirect = copynode(n->ncmd.redirect);
8095 new->ncmd.args = copynode(n->ncmd.args);
8096 new->ncmd.assign = copynode(n->ncmd.assign);
8099 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8100 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8105 new->nredir.redirect = copynode(n->nredir.redirect);
8106 new->nredir.n = copynode(n->nredir.n);
8113 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8114 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8117 new->nif.elsepart = copynode(n->nif.elsepart);
8118 new->nif.ifpart = copynode(n->nif.ifpart);
8119 new->nif.test = copynode(n->nif.test);
8122 new->nfor.var = nodeckstrdup(n->nfor.var);
8123 new->nfor.body = copynode(n->nfor.body);
8124 new->nfor.args = copynode(n->nfor.args);
8127 new->ncase.cases = copynode(n->ncase.cases);
8128 new->ncase.expr = copynode(n->ncase.expr);
8131 new->nclist.body = copynode(n->nclist.body);
8132 new->nclist.pattern = copynode(n->nclist.pattern);
8133 new->nclist.next = copynode(n->nclist.next);
8137 new->narg.backquote = copynodelist(n->narg.backquote);
8138 new->narg.text = nodeckstrdup(n->narg.text);
8139 new->narg.next = copynode(n->narg.next);
8142 #if ENABLE_ASH_BASH_COMPAT
8149 new->nfile.fname = copynode(n->nfile.fname);
8150 new->nfile.fd = n->nfile.fd;
8151 new->nfile.next = copynode(n->nfile.next);
8155 new->ndup.vname = copynode(n->ndup.vname);
8156 new->ndup.dupfd = n->ndup.dupfd;
8157 new->ndup.fd = n->ndup.fd;
8158 new->ndup.next = copynode(n->ndup.next);
8162 new->nhere.doc = copynode(n->nhere.doc);
8163 new->nhere.fd = n->nhere.fd;
8164 new->nhere.next = copynode(n->nhere.next);
8167 new->nnot.com = copynode(n->nnot.com);
8170 new->type = n->type;
8175 * Make a copy of a parse tree.
8177 static struct funcnode *
8178 copyfunc(union node *n)
8183 funcblocksize = offsetof(struct funcnode, n);
8186 blocksize = funcblocksize;
8187 f = ckmalloc(blocksize + funcstringsize);
8188 funcblock = (char *) f + offsetof(struct funcnode, n);
8189 funcstring = (char *) f + blocksize;
8196 * Define a shell function.
8199 defun(char *name, union node *func)
8201 struct cmdentry entry;
8204 entry.cmdtype = CMDFUNCTION;
8205 entry.u.func = copyfunc(func);
8206 addcmdentry(name, &entry);
8210 /* Reasons for skipping commands (see comment on breakcmd routine) */
8211 #define SKIPBREAK (1 << 0)
8212 #define SKIPCONT (1 << 1)
8213 #define SKIPFUNC (1 << 2)
8214 #define SKIPFILE (1 << 3)
8215 #define SKIPEVAL (1 << 4)
8216 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8217 static int skipcount; /* number of levels to skip */
8218 static int funcnest; /* depth of function calls */
8219 static int loopnest; /* current loop nesting level */
8221 /* Forward decl way out to parsing code - dotrap needs it */
8222 static int evalstring(char *s, int mask);
8224 /* Called to execute a trap.
8225 * Single callsite - at the end of evaltree().
8226 * If we return non-zero, evaltree raises EXEXIT exception.
8228 * Perhaps we should avoid entering new trap handlers
8229 * while we are executing a trap handler. [is it a TODO?]
8238 savestatus = exitstatus;
8242 TRACE(("dotrap entered\n"));
8243 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8250 /* non-trapped SIGINT is handled separately by raise_interrupt,
8251 * don't upset it by resetting gotsig[SIGINT-1] */
8252 if (sig == SIGINT && !t)
8255 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8259 want_exexit = evalstring(t, SKIPEVAL);
8260 exitstatus = savestatus;
8262 TRACE(("dotrap returns %d\n", want_exexit));
8267 TRACE(("dotrap returns 0\n"));
8271 /* forward declarations - evaluation is fairly recursive business... */
8272 static void evalloop(union node *, int);
8273 static void evalfor(union node *, int);
8274 static void evalcase(union node *, int);
8275 static void evalsubshell(union node *, int);
8276 static void expredir(union node *);
8277 static void evalpipe(union node *, int);
8278 static void evalcommand(union node *, int);
8279 static int evalbltin(const struct builtincmd *, int, char **);
8280 static void prehash(union node *);
8283 * Evaluate a parse tree. The value is left in the global variable
8287 evaltree(union node *n, int flags)
8289 struct jmploc *volatile savehandler = exception_handler;
8290 struct jmploc jmploc;
8292 void (*evalfn)(union node *, int);
8296 SAVE_INT(int_level);
8299 TRACE(("evaltree(NULL) called\n"));
8302 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8304 exception_handler = &jmploc;
8306 int err = setjmp(jmploc.loc);
8308 /* if it was a signal, check for trap handlers */
8309 if (exception_type == EXSIG) {
8310 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8311 exception_type, err));
8314 /* continue on the way out */
8315 TRACE(("exception %d in evaltree, propagating err=%d\n",
8316 exception_type, err));
8317 exception_handler = savehandler;
8318 longjmp(exception_handler->loc, err);
8325 out1fmt("Node type = %d\n", n->type);
8330 evaltree(n->nnot.com, EV_TESTED);
8331 status = !exitstatus;
8334 expredir(n->nredir.redirect);
8335 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8337 evaltree(n->nredir.n, flags & EV_TESTED);
8338 status = exitstatus;
8340 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8343 evalfn = evalcommand;
8345 if (eflag && !(flags & EV_TESTED))
8357 evalfn = evalsubshell;
8370 #error NAND + 1 != NOR
8372 #if NOR + 1 != NSEMI
8373 #error NOR + 1 != NSEMI
8375 unsigned is_or = n->type - NAND;
8378 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8380 if (!exitstatus == is_or)
8393 evaltree(n->nif.test, EV_TESTED);
8396 if (exitstatus == 0) {
8400 if (n->nif.elsepart) {
8401 n = n->nif.elsepart;
8406 defun(n->narg.text, n->narg.next);
8410 exitstatus = status;
8415 exception_handler = savehandler;
8418 /* Order of checks below is important:
8419 * signal handlers trigger before exit caused by "set -e".
8421 if (pending_sig && dotrap())
8423 if (checkexit & exitstatus)
8424 evalskip |= SKIPEVAL;
8426 if (flags & EV_EXIT) {
8428 raise_exception(EXEXIT);
8431 RESTORE_INT(int_level);
8432 TRACE(("leaving evaltree (no interrupts)\n"));
8435 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8438 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8441 evalloop(union node *n, int flags)
8451 evaltree(n->nbinary.ch1, EV_TESTED);
8454 if (evalskip == SKIPCONT && --skipcount <= 0) {
8458 if (evalskip == SKIPBREAK && --skipcount <= 0)
8463 if (n->type != NWHILE)
8467 evaltree(n->nbinary.ch2, flags);
8468 status = exitstatus;
8473 exitstatus = status;
8477 evalfor(union node *n, int flags)
8479 struct arglist arglist;
8482 struct stackmark smark;
8484 setstackmark(&smark);
8485 arglist.list = NULL;
8486 arglist.lastp = &arglist.list;
8487 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8488 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8493 *arglist.lastp = NULL;
8498 for (sp = arglist.list; sp; sp = sp->next) {
8499 setvar(n->nfor.var, sp->text, 0);
8500 evaltree(n->nfor.body, flags);
8502 if (evalskip == SKIPCONT && --skipcount <= 0) {
8506 if (evalskip == SKIPBREAK && --skipcount <= 0)
8513 popstackmark(&smark);
8517 evalcase(union node *n, int flags)
8521 struct arglist arglist;
8522 struct stackmark smark;
8524 setstackmark(&smark);
8525 arglist.list = NULL;
8526 arglist.lastp = &arglist.list;
8527 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8529 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8530 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8531 if (casematch(patp, arglist.list->text)) {
8532 if (evalskip == 0) {
8533 evaltree(cp->nclist.body, flags);
8540 popstackmark(&smark);
8544 * Kick off a subshell to evaluate a tree.
8547 evalsubshell(union node *n, int flags)
8550 int backgnd = (n->type == NBACKGND);
8553 expredir(n->nredir.redirect);
8554 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8557 jp = makejob(/*n,*/ 1);
8558 if (forkshell(jp, n, backgnd) == 0) {
8563 flags &= ~EV_TESTED;
8565 redirect(n->nredir.redirect, 0);
8566 evaltreenr(n->nredir.n, flags);
8571 status = waitforjob(jp);
8572 exitstatus = status;
8577 * Compute the names of the files in a redirection list.
8579 static void fixredir(union node *, const char *, int);
8581 expredir(union node *n)
8585 for (redir = n; redir; redir = redir->nfile.next) {
8589 fn.lastp = &fn.list;
8590 switch (redir->type) {
8594 #if ENABLE_ASH_BASH_COMPAT
8599 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8600 #if ENABLE_ASH_BASH_COMPAT
8603 redir->nfile.expfname = fn.list->text;
8606 case NTOFD: /* >& */
8607 if (redir->ndup.vname) {
8608 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8609 if (fn.list == NULL)
8610 ash_msg_and_raise_error("redir error");
8611 #if ENABLE_ASH_BASH_COMPAT
8612 //FIXME: we used expandarg with different args!
8613 if (!isdigit_str9(fn.list->text)) {
8614 /* >&file, not >&fd */
8615 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8616 ash_msg_and_raise_error("redir error");
8618 goto store_expfname;
8621 fixredir(redir, fn.list->text, 1);
8629 * Evaluate a pipeline. All the processes in the pipeline are children
8630 * of the process creating the pipeline. (This differs from some versions
8631 * of the shell, which make the last process in a pipeline the parent
8635 evalpipe(union node *n, int flags)
8638 struct nodelist *lp;
8643 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8645 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8649 jp = makejob(/*n,*/ pipelen);
8651 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8655 if (pipe(pip) < 0) {
8657 ash_msg_and_raise_error("pipe call failed");
8660 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8673 evaltreenr(lp->n, flags);
8679 /* Don't want to trigger debugging */
8683 if (n->npipe.pipe_backgnd == 0) {
8684 exitstatus = waitforjob(jp);
8685 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8691 * Controls whether the shell is interactive or not.
8694 setinteractive(int on)
8696 static smallint is_interactive;
8698 if (++on == is_interactive)
8700 is_interactive = on;
8704 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8705 if (is_interactive > 1) {
8706 /* Looks like they want an interactive shell */
8707 static smallint did_banner;
8710 /* note: ash and hush share this string */
8711 out1fmt("\n\n%s %s\n"
8712 "Enter 'help' for a list of built-in commands."
8715 "built-in shell (ash)"
8729 setinteractive(iflag);
8731 #if ENABLE_FEATURE_EDITING_VI
8733 line_input_state->flags |= VI_MODE;
8735 line_input_state->flags &= ~VI_MODE;
8737 viflag = 0; /* forcibly keep the option off */
8741 static struct localvar *localvars;
8744 * Called after a function returns.
8745 * Interrupts must be off.
8750 struct localvar *lvp;
8753 while ((lvp = localvars) != NULL) {
8754 localvars = lvp->next;
8756 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8757 if (vp == NULL) { /* $- saved */
8758 memcpy(optlist, lvp->text, sizeof(optlist));
8759 free((char*)lvp->text);
8761 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8762 unsetvar(vp->var_text);
8765 vp->var_func(var_end(lvp->text));
8766 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8767 free((char*)vp->var_text);
8768 vp->flags = lvp->flags;
8769 vp->var_text = lvp->text;
8776 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8778 volatile struct shparam saveparam;
8779 struct localvar *volatile savelocalvars;
8780 struct jmploc *volatile savehandler;
8781 struct jmploc jmploc;
8784 saveparam = shellparam;
8785 savelocalvars = localvars;
8786 e = setjmp(jmploc.loc);
8791 savehandler = exception_handler;
8792 exception_handler = &jmploc;
8794 shellparam.malloced = 0;
8798 shellparam.nparam = argc - 1;
8799 shellparam.p = argv + 1;
8800 #if ENABLE_ASH_GETOPTS
8801 shellparam.optind = 1;
8802 shellparam.optoff = -1;
8804 evaltree(&func->n, flags & EV_TESTED);
8810 localvars = savelocalvars;
8811 freeparam(&shellparam);
8812 shellparam = saveparam;
8813 exception_handler = savehandler;
8815 evalskip &= ~SKIPFUNC;
8819 #if ENABLE_ASH_CMDCMD
8821 parse_command_args(char **argv, const char **path)
8834 if (c == '-' && !*cp) {
8841 *path = bb_default_path;
8844 /* run 'typecmd' for other options */
8855 * Make a variable a local variable. When a variable is made local, it's
8856 * value and flags are saved in a localvar structure. The saved values
8857 * will be restored when the shell function returns. We handle the name
8858 * "-" as a special case.
8863 struct localvar *lvp;
8868 lvp = ckzalloc(sizeof(struct localvar));
8869 if (LONE_DASH(name)) {
8871 p = ckmalloc(sizeof(optlist));
8872 lvp->text = memcpy(p, optlist, sizeof(optlist));
8877 vpp = hashvar(name);
8878 vp = *findvar(vpp, name);
8879 eq = strchr(name, '=');
8882 setvareq(name, VSTRFIXED);
8884 setvar(name, NULL, VSTRFIXED);
8885 vp = *vpp; /* the new variable */
8886 lvp->flags = VUNSET;
8888 lvp->text = vp->var_text;
8889 lvp->flags = vp->flags;
8890 vp->flags |= VSTRFIXED|VTEXTFIXED;
8896 lvp->next = localvars;
8902 * The "local" command.
8904 static int FAST_FUNC
8905 localcmd(int argc UNUSED_PARAM, char **argv)
8910 while ((name = *argv++) != NULL) {
8916 static int FAST_FUNC
8917 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8922 static int FAST_FUNC
8923 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8928 static int FAST_FUNC
8929 execcmd(int argc UNUSED_PARAM, char **argv)
8932 iflag = 0; /* exit on error */
8935 shellexec(argv + 1, pathval(), 0);
8941 * The return command.
8943 static int FAST_FUNC
8944 returncmd(int argc UNUSED_PARAM, char **argv)
8947 * If called outside a function, do what ksh does;
8948 * skip the rest of the file.
8950 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8951 return argv[1] ? number(argv[1]) : exitstatus;
8954 /* Forward declarations for builtintab[] */
8955 static int breakcmd(int, char **) FAST_FUNC;
8956 static int dotcmd(int, char **) FAST_FUNC;
8957 static int evalcmd(int, char **) FAST_FUNC;
8958 static int exitcmd(int, char **) FAST_FUNC;
8959 static int exportcmd(int, char **) FAST_FUNC;
8960 #if ENABLE_ASH_GETOPTS
8961 static int getoptscmd(int, char **) FAST_FUNC;
8963 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8964 static int helpcmd(int, char **) FAST_FUNC;
8966 #if ENABLE_SH_MATH_SUPPORT
8967 static int letcmd(int, char **) FAST_FUNC;
8969 static int readcmd(int, char **) FAST_FUNC;
8970 static int setcmd(int, char **) FAST_FUNC;
8971 static int shiftcmd(int, char **) FAST_FUNC;
8972 static int timescmd(int, char **) FAST_FUNC;
8973 static int trapcmd(int, char **) FAST_FUNC;
8974 static int umaskcmd(int, char **) FAST_FUNC;
8975 static int unsetcmd(int, char **) FAST_FUNC;
8976 static int ulimitcmd(int, char **) FAST_FUNC;
8978 #define BUILTIN_NOSPEC "0"
8979 #define BUILTIN_SPECIAL "1"
8980 #define BUILTIN_REGULAR "2"
8981 #define BUILTIN_SPEC_REG "3"
8982 #define BUILTIN_ASSIGN "4"
8983 #define BUILTIN_SPEC_ASSG "5"
8984 #define BUILTIN_REG_ASSG "6"
8985 #define BUILTIN_SPEC_REG_ASSG "7"
8987 /* Stubs for calling non-FAST_FUNC's */
8988 #if ENABLE_ASH_BUILTIN_ECHO
8989 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8991 #if ENABLE_ASH_BUILTIN_PRINTF
8992 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8994 #if ENABLE_ASH_BUILTIN_TEST
8995 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8998 /* Keep these in proper order since it is searched via bsearch() */
8999 static const struct builtincmd builtintab[] = {
9000 { BUILTIN_SPEC_REG "." , dotcmd },
9001 { BUILTIN_SPEC_REG ":" , truecmd },
9002 #if ENABLE_ASH_BUILTIN_TEST
9003 { BUILTIN_REGULAR "[" , testcmd },
9004 #if ENABLE_ASH_BASH_COMPAT
9005 { BUILTIN_REGULAR "[[" , testcmd },
9008 #if ENABLE_ASH_ALIAS
9009 { BUILTIN_REG_ASSG "alias" , aliascmd },
9012 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9014 { BUILTIN_SPEC_REG "break" , breakcmd },
9015 { BUILTIN_REGULAR "cd" , cdcmd },
9016 { BUILTIN_NOSPEC "chdir" , cdcmd },
9017 #if ENABLE_ASH_CMDCMD
9018 { BUILTIN_REGULAR "command" , commandcmd },
9020 { BUILTIN_SPEC_REG "continue", breakcmd },
9021 #if ENABLE_ASH_BUILTIN_ECHO
9022 { BUILTIN_REGULAR "echo" , echocmd },
9024 { BUILTIN_SPEC_REG "eval" , evalcmd },
9025 { BUILTIN_SPEC_REG "exec" , execcmd },
9026 { BUILTIN_SPEC_REG "exit" , exitcmd },
9027 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9028 { BUILTIN_REGULAR "false" , falsecmd },
9030 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9032 #if ENABLE_ASH_GETOPTS
9033 { BUILTIN_REGULAR "getopts" , getoptscmd },
9035 { BUILTIN_NOSPEC "hash" , hashcmd },
9036 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9037 { BUILTIN_NOSPEC "help" , helpcmd },
9040 { BUILTIN_REGULAR "jobs" , jobscmd },
9041 { BUILTIN_REGULAR "kill" , killcmd },
9043 #if ENABLE_SH_MATH_SUPPORT
9044 { BUILTIN_NOSPEC "let" , letcmd },
9046 { BUILTIN_ASSIGN "local" , localcmd },
9047 #if ENABLE_ASH_BUILTIN_PRINTF
9048 { BUILTIN_REGULAR "printf" , printfcmd },
9050 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9051 { BUILTIN_REGULAR "read" , readcmd },
9052 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9053 { BUILTIN_SPEC_REG "return" , returncmd },
9054 { BUILTIN_SPEC_REG "set" , setcmd },
9055 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9056 #if ENABLE_ASH_BASH_COMPAT
9057 { BUILTIN_SPEC_REG "source" , dotcmd },
9059 #if ENABLE_ASH_BUILTIN_TEST
9060 { BUILTIN_REGULAR "test" , testcmd },
9062 { BUILTIN_SPEC_REG "times" , timescmd },
9063 { BUILTIN_SPEC_REG "trap" , trapcmd },
9064 { BUILTIN_REGULAR "true" , truecmd },
9065 { BUILTIN_NOSPEC "type" , typecmd },
9066 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9067 { BUILTIN_REGULAR "umask" , umaskcmd },
9068 #if ENABLE_ASH_ALIAS
9069 { BUILTIN_REGULAR "unalias" , unaliascmd },
9071 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9072 { BUILTIN_REGULAR "wait" , waitcmd },
9075 /* Should match the above table! */
9076 #define COMMANDCMD (builtintab + \
9078 1 * ENABLE_ASH_BUILTIN_TEST + \
9079 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9080 1 * ENABLE_ASH_ALIAS + \
9081 1 * ENABLE_ASH_JOB_CONTROL + \
9083 #define EXECCMD (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 1 * ENABLE_ASH_CMDCMD + \
9092 ENABLE_ASH_BUILTIN_ECHO + \
9096 * Search the table of builtin commands.
9098 static struct builtincmd *
9099 find_builtin(const char *name)
9101 struct builtincmd *bp;
9104 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9111 * Execute a simple command.
9114 isassignment(const char *p)
9116 const char *q = endofname(p);
9121 static int FAST_FUNC
9122 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9124 /* Preserve exitstatus of a previous possible redirection
9125 * as POSIX mandates */
9126 return back_exitstatus;
9129 evalcommand(union node *cmd, int flags)
9131 static const struct builtincmd null_bltin = {
9132 "\0\0", bltincmd /* why three NULs? */
9134 struct stackmark smark;
9136 struct arglist arglist;
9137 struct arglist varlist;
9140 const struct strlist *sp;
9141 struct cmdentry cmdentry;
9148 struct builtincmd *bcmd;
9149 smallint cmd_is_exec;
9150 smallint pseudovarflag = 0;
9152 /* First expand the arguments. */
9153 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9154 setstackmark(&smark);
9155 back_exitstatus = 0;
9157 cmdentry.cmdtype = CMDBUILTIN;
9158 cmdentry.u.cmd = &null_bltin;
9159 varlist.lastp = &varlist.list;
9160 *varlist.lastp = NULL;
9161 arglist.lastp = &arglist.list;
9162 *arglist.lastp = NULL;
9165 if (cmd->ncmd.args) {
9166 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9167 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9170 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9171 struct strlist **spp;
9173 spp = arglist.lastp;
9174 if (pseudovarflag && isassignment(argp->narg.text))
9175 expandarg(argp, &arglist, EXP_VARTILDE);
9177 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9179 for (sp = *spp; sp; sp = sp->next)
9183 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9184 for (sp = arglist.list; sp; sp = sp->next) {
9185 TRACE(("evalcommand arg: %s\n", sp->text));
9186 *nargv++ = sp->text;
9191 if (iflag && funcnest == 0 && argc > 0)
9192 lastarg = nargv[-1];
9195 expredir(cmd->ncmd.redirect);
9196 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9198 path = vpath.var_text;
9199 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9200 struct strlist **spp;
9203 spp = varlist.lastp;
9204 expandarg(argp, &varlist, EXP_VARTILDE);
9207 * Modify the command lookup path, if a PATH= assignment
9211 if (varcmp(p, path) == 0)
9215 /* Print the command if xflag is set. */
9218 const char *p = " %s" + 1;
9220 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9222 for (n = 0; n < 2; n++) {
9224 fdprintf(preverrout_fd, p, sp->text);
9230 safe_write(preverrout_fd, "\n", 1);
9236 /* Now locate the command. */
9238 const char *oldpath;
9239 int cmd_flag = DO_ERR;
9244 find_command(argv[0], &cmdentry, cmd_flag, path);
9245 if (cmdentry.cmdtype == CMDUNKNOWN) {
9246 flush_stdout_stderr();
9251 /* implement bltin and command here */
9252 if (cmdentry.cmdtype != CMDBUILTIN)
9255 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9256 if (cmdentry.u.cmd == EXECCMD)
9258 #if ENABLE_ASH_CMDCMD
9259 if (cmdentry.u.cmd == COMMANDCMD) {
9261 nargv = parse_command_args(argv, &path);
9264 argc -= nargv - argv;
9266 cmd_flag |= DO_NOFUNC;
9274 /* We have a redirection error. */
9276 raise_exception(EXERROR);
9278 exitstatus = status;
9282 /* Execute the command. */
9283 switch (cmdentry.cmdtype) {
9286 #if ENABLE_FEATURE_SH_NOFORK
9287 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9288 * around run_nofork_applet() call.
9289 * (2) Should this check also be done in forkshell()?
9290 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9292 /* find_command() encodes applet_no as (-2 - applet_no) */
9293 int applet_no = (- cmdentry.u.index - 2);
9294 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9295 listsetvar(varlist.list, VEXPORT|VSTACK);
9296 /* run <applet>_main() */
9297 exitstatus = run_nofork_applet(applet_no, argv);
9301 /* Can we avoid forking off? For example, very last command
9302 * in a script or a subshell does not need forking,
9303 * we can just exec it.
9305 if (!(flags & EV_EXIT) || may_have_traps) {
9306 /* No, forking off a child is necessary */
9308 jp = makejob(/*cmd,*/ 1);
9309 if (forkshell(jp, cmd, FORK_FG) != 0) {
9311 exitstatus = waitforjob(jp);
9313 TRACE(("forked child exited with %d\n", exitstatus));
9318 /* fall through to exec'ing external program */
9320 listsetvar(varlist.list, VEXPORT|VSTACK);
9321 shellexec(argv, path, cmdentry.u.index);
9325 cmdenviron = varlist.list;
9327 struct strlist *list = cmdenviron;
9329 if (spclbltin > 0 || argc == 0) {
9331 if (cmd_is_exec && argc > 1)
9334 listsetvar(list, i);
9336 /* Tight loop with builtins only:
9337 * "while kill -0 $child; do true; done"
9338 * will never exit even if $child died, unless we do this
9339 * to reap the zombie and make kill detect that it's gone: */
9340 dowait(DOWAIT_NONBLOCK, NULL);
9342 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9344 int i = exception_type;
9349 exit_status = 128 + SIGINT;
9351 exit_status = 128 + pending_sig;
9352 exitstatus = exit_status;
9353 if (i == EXINT || spclbltin > 0) {
9355 longjmp(exception_handler->loc, 1);
9362 listsetvar(varlist.list, 0);
9363 /* See above for the rationale */
9364 dowait(DOWAIT_NONBLOCK, NULL);
9365 if (evalfun(cmdentry.u.func, argc, argv, flags))
9372 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9374 /* dsl: I think this is intended to be used to support
9375 * '_' in 'vi' command mode during line editing...
9376 * However I implemented that within libedit itself.
9378 setvar("_", lastarg, 0);
9380 popstackmark(&smark);
9384 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9386 char *volatile savecmdname;
9387 struct jmploc *volatile savehandler;
9388 struct jmploc jmploc;
9391 savecmdname = commandname;
9392 i = setjmp(jmploc.loc);
9395 savehandler = exception_handler;
9396 exception_handler = &jmploc;
9397 commandname = argv[0];
9399 optptr = NULL; /* initialize nextopt */
9400 exitstatus = (*cmd->builtin)(argc, argv);
9401 flush_stdout_stderr();
9403 exitstatus |= ferror(stdout);
9405 commandname = savecmdname;
9406 exception_handler = savehandler;
9412 goodname(const char *p)
9414 return endofname(p)[0] == '\0';
9419 * Search for a command. This is called before we fork so that the
9420 * location of the command will be available in the parent as well as
9421 * the child. The check for "goodname" is an overly conservative
9422 * check that the name will not be subject to expansion.
9425 prehash(union node *n)
9427 struct cmdentry entry;
9429 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9430 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9434 /* ============ Builtin commands
9436 * Builtin commands whose functions are closely tied to evaluation
9437 * are implemented here.
9441 * Handle break and continue commands. Break, continue, and return are
9442 * all handled by setting the evalskip flag. The evaluation routines
9443 * above all check this flag, and if it is set they start skipping
9444 * commands rather than executing them. The variable skipcount is
9445 * the number of loops to break/continue, or the number of function
9446 * levels to return. (The latter is always 1.) It should probably
9447 * be an error to break out of more loops than exist, but it isn't
9448 * in the standard shell so we don't make it one here.
9450 static int FAST_FUNC
9451 breakcmd(int argc UNUSED_PARAM, char **argv)
9453 int n = argv[1] ? number(argv[1]) : 1;
9456 ash_msg_and_raise_error(msg_illnum, argv[1]);
9460 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9467 /* ============ input.c
9469 * This implements the input routines used by the parser.
9473 INPUT_PUSH_FILE = 1,
9474 INPUT_NOFILE_OK = 2,
9477 static smallint checkkwd;
9478 /* values of checkkwd variable */
9479 #define CHKALIAS 0x1
9484 * Push a string back onto the input at this current parsefile level.
9485 * We handle aliases this way.
9487 #if !ENABLE_ASH_ALIAS
9488 #define pushstring(s, ap) pushstring(s)
9491 pushstring(char *s, struct alias *ap)
9498 if (g_parsefile->strpush) {
9499 sp = ckzalloc(sizeof(*sp));
9500 sp->prev = g_parsefile->strpush;
9502 sp = &(g_parsefile->basestrpush);
9504 g_parsefile->strpush = sp;
9505 sp->prev_string = g_parsefile->next_to_pgetc;
9506 sp->prev_left_in_line = g_parsefile->left_in_line;
9507 #if ENABLE_ASH_ALIAS
9510 ap->flag |= ALIASINUSE;
9514 g_parsefile->next_to_pgetc = s;
9515 g_parsefile->left_in_line = len;
9522 struct strpush *sp = g_parsefile->strpush;
9525 #if ENABLE_ASH_ALIAS
9527 if (g_parsefile->next_to_pgetc[-1] == ' '
9528 || g_parsefile->next_to_pgetc[-1] == '\t'
9530 checkkwd |= CHKALIAS;
9532 if (sp->string != sp->ap->val) {
9535 sp->ap->flag &= ~ALIASINUSE;
9536 if (sp->ap->flag & ALIASDEAD) {
9537 unalias(sp->ap->name);
9541 g_parsefile->next_to_pgetc = sp->prev_string;
9542 g_parsefile->left_in_line = sp->prev_left_in_line;
9543 g_parsefile->strpush = sp->prev;
9544 if (sp != &(g_parsefile->basestrpush))
9549 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9550 //it peeks whether it is &>, and then pushes back both chars.
9551 //This function needs to save last *next_to_pgetc to buf[0]
9552 //to make two pungetc() reliable. Currently,
9553 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9558 char *buf = g_parsefile->buf;
9560 g_parsefile->next_to_pgetc = buf;
9561 #if ENABLE_FEATURE_EDITING
9563 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9564 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9566 #if ENABLE_FEATURE_TAB_COMPLETION
9567 line_input_state->path_lookup = pathval();
9569 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9571 /* Ctrl+C pressed */
9580 if (nr < 0 && errno == 0) {
9581 /* Ctrl+D pressed */
9586 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9590 /* nonblock_safe_read() handles this problem */
9592 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9593 int flags = fcntl(0, F_GETFL);
9594 if (flags >= 0 && (flags & O_NONBLOCK)) {
9595 flags &= ~O_NONBLOCK;
9596 if (fcntl(0, F_SETFL, flags) >= 0) {
9597 out2str("sh: turning off NDELAY mode\n");
9608 * Refill the input buffer and return the next input character:
9610 * 1) If a string was pushed back on the input, pop it;
9611 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9612 * or we are reading from a string so we can't refill the buffer,
9614 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9615 * 4) Process input up to the next newline, deleting nul characters.
9617 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9618 #define pgetc_debug(...) ((void)0)
9625 while (g_parsefile->strpush) {
9626 #if ENABLE_ASH_ALIAS
9627 if (g_parsefile->left_in_line == -1
9628 && g_parsefile->strpush->ap
9629 && g_parsefile->next_to_pgetc[-1] != ' '
9630 && g_parsefile->next_to_pgetc[-1] != '\t'
9632 pgetc_debug("preadbuffer PEOA");
9637 /* try "pgetc" now: */
9638 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9639 g_parsefile->left_in_line,
9640 g_parsefile->next_to_pgetc,
9641 g_parsefile->next_to_pgetc);
9642 if (--g_parsefile->left_in_line >= 0)
9643 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9645 /* on both branches above g_parsefile->left_in_line < 0.
9646 * "pgetc" needs refilling.
9649 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9650 * pungetc() may increment it a few times.
9651 * Assuming it won't increment it to less than -90.
9653 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9654 pgetc_debug("preadbuffer PEOF1");
9655 /* even in failure keep left_in_line and next_to_pgetc
9656 * in lock step, for correct multi-layer pungetc.
9657 * left_in_line was decremented before preadbuffer(),
9658 * must inc next_to_pgetc: */
9659 g_parsefile->next_to_pgetc++;
9663 more = g_parsefile->left_in_buffer;
9665 flush_stdout_stderr();
9669 /* don't try reading again */
9670 g_parsefile->left_in_line = -99;
9671 pgetc_debug("preadbuffer PEOF2");
9672 g_parsefile->next_to_pgetc++;
9677 /* Find out where's the end of line.
9678 * Set g_parsefile->left_in_line
9679 * and g_parsefile->left_in_buffer acordingly.
9680 * NUL chars are deleted.
9682 q = g_parsefile->next_to_pgetc;
9690 memmove(q, q + 1, more);
9694 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9700 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9701 if (g_parsefile->left_in_line < 0)
9706 g_parsefile->left_in_buffer = more;
9711 out2str(g_parsefile->next_to_pgetc);
9715 pgetc_debug("preadbuffer at %d:%p'%s'",
9716 g_parsefile->left_in_line,
9717 g_parsefile->next_to_pgetc,
9718 g_parsefile->next_to_pgetc);
9719 return (unsigned char)*g_parsefile->next_to_pgetc++;
9722 #define pgetc_as_macro() \
9723 (--g_parsefile->left_in_line >= 0 \
9724 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9731 pgetc_debug("pgetc_fast at %d:%p'%s'",
9732 g_parsefile->left_in_line,
9733 g_parsefile->next_to_pgetc,
9734 g_parsefile->next_to_pgetc);
9735 return pgetc_as_macro();
9738 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9739 # define pgetc_fast() pgetc()
9741 # define pgetc_fast() pgetc_as_macro()
9744 #if ENABLE_ASH_ALIAS
9746 pgetc_without_PEOA(void)
9750 pgetc_debug("pgetc_fast at %d:%p'%s'",
9751 g_parsefile->left_in_line,
9752 g_parsefile->next_to_pgetc,
9753 g_parsefile->next_to_pgetc);
9755 } while (c == PEOA);
9759 # define pgetc_without_PEOA() pgetc()
9763 * Read a line from the script.
9766 pfgets(char *line, int len)
9772 while (--nleft > 0) {
9773 c = pgetc_without_PEOA();
9788 * Undo the last call to pgetc. Only one character may be pushed back.
9789 * PEOF may be pushed back.
9794 g_parsefile->left_in_line++;
9795 g_parsefile->next_to_pgetc--;
9796 pgetc_debug("pushed back to %d:%p'%s'",
9797 g_parsefile->left_in_line,
9798 g_parsefile->next_to_pgetc,
9799 g_parsefile->next_to_pgetc);
9803 * To handle the "." command, a stack of input files is used. Pushfile
9804 * adds a new entry to the stack and popfile restores the previous level.
9809 struct parsefile *pf;
9811 pf = ckzalloc(sizeof(*pf));
9812 pf->prev = g_parsefile;
9814 /*pf->strpush = NULL; - ckzalloc did it */
9815 /*pf->basestrpush.prev = NULL;*/
9822 struct parsefile *pf = g_parsefile;
9830 g_parsefile = pf->prev;
9836 * Return to top level.
9841 while (g_parsefile != &basepf)
9846 * Close the file(s) that the shell is reading commands from. Called
9847 * after a fork is done.
9853 if (g_parsefile->pf_fd > 0) {
9854 close(g_parsefile->pf_fd);
9855 g_parsefile->pf_fd = 0;
9860 * Like setinputfile, but takes an open file descriptor. Call this with
9864 setinputfd(int fd, int push)
9866 close_on_exec_on(fd);
9869 g_parsefile->buf = NULL;
9871 g_parsefile->pf_fd = fd;
9872 if (g_parsefile->buf == NULL)
9873 g_parsefile->buf = ckmalloc(IBUFSIZ);
9874 g_parsefile->left_in_buffer = 0;
9875 g_parsefile->left_in_line = 0;
9876 g_parsefile->linno = 1;
9880 * Set the input to take input from a file. If push is set, push the
9881 * old input onto the stack first.
9884 setinputfile(const char *fname, int flags)
9890 fd = open(fname, O_RDONLY);
9892 if (flags & INPUT_NOFILE_OK)
9894 ash_msg_and_raise_error("can't open '%s'", fname);
9897 fd2 = copyfd(fd, 10);
9900 ash_msg_and_raise_error("out of file descriptors");
9903 setinputfd(fd, flags & INPUT_PUSH_FILE);
9910 * Like setinputfile, but takes input from a string.
9913 setinputstring(char *string)
9917 g_parsefile->next_to_pgetc = string;
9918 g_parsefile->left_in_line = strlen(string);
9919 g_parsefile->buf = NULL;
9920 g_parsefile->linno = 1;
9925 /* ============ mail.c
9927 * Routines to check for mail.
9932 #define MAXMBOXES 10
9934 /* times of mailboxes */
9935 static time_t mailtime[MAXMBOXES];
9936 /* Set if MAIL or MAILPATH is changed. */
9937 static smallint mail_var_path_changed;
9940 * Print appropriate message(s) if mail has arrived.
9941 * If mail_var_path_changed is set,
9942 * then the value of MAIL has mail_var_path_changed,
9943 * so we just update the values.
9952 struct stackmark smark;
9955 setstackmark(&smark);
9956 mpath = mpathset() ? mpathval() : mailval();
9957 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9958 p = path_advance(&mpath, nullstr);
9963 for (q = p; *q; q++)
9969 q[-1] = '\0'; /* delete trailing '/' */
9970 if (stat(p, &statb) < 0) {
9974 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9977 pathopt ? pathopt : "you have mail"
9980 *mtp = statb.st_mtime;
9982 mail_var_path_changed = 0;
9983 popstackmark(&smark);
9986 static void FAST_FUNC
9987 changemail(const char *val UNUSED_PARAM)
9989 mail_var_path_changed = 1;
9992 #endif /* ASH_MAIL */
9995 /* ============ ??? */
9998 * Set the shell parameters.
10001 setparam(char **argv)
10007 for (nparam = 0; argv[nparam]; nparam++)
10009 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10011 *ap++ = ckstrdup(*argv++);
10014 freeparam(&shellparam);
10015 shellparam.malloced = 1;
10016 shellparam.nparam = nparam;
10017 shellparam.p = newparam;
10018 #if ENABLE_ASH_GETOPTS
10019 shellparam.optind = 1;
10020 shellparam.optoff = -1;
10025 * Process shell options. The global variable argptr contains a pointer
10026 * to the argument list; we advance it past the options.
10028 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10029 * For a non-interactive shell, an error condition encountered
10030 * by a special built-in ... shall cause the shell to write a diagnostic message
10031 * to standard error and exit as shown in the following table:
10032 * Error Special Built-In
10034 * Utility syntax error (option or operand error) Shall exit
10036 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10037 * we see that bash does not do that (set "finishes" with error code 1 instead,
10038 * and shell continues), and people rely on this behavior!
10040 * set -o barfoo 2>/dev/null
10043 * Oh well. Let's mimic that.
10046 plus_minus_o(char *name, int val)
10051 for (i = 0; i < NOPTS; i++) {
10052 if (strcmp(name, optnames(i)) == 0) {
10057 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10060 for (i = 0; i < NOPTS; i++) {
10062 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10064 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10070 setoption(int flag, int val)
10074 for (i = 0; i < NOPTS; i++) {
10075 if (optletters(i) == flag) {
10080 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10084 options(int cmdline)
10092 while ((p = *argptr) != NULL) {
10094 if (c != '-' && c != '+')
10097 val = 0; /* val = 0 if c == '+' */
10100 if (p[0] == '\0' || LONE_DASH(p)) {
10102 /* "-" means turn off -x and -v */
10105 /* "--" means reset params */
10106 else if (*argptr == NULL)
10109 break; /* "-" or "--" terminates options */
10112 /* first char was + or - */
10113 while ((c = *p++) != '\0') {
10114 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10115 if (c == 'c' && cmdline) {
10116 minusc = p; /* command is after shell args */
10117 } else if (c == 'o') {
10118 if (plus_minus_o(*argptr, val)) {
10119 /* it already printed err message */
10120 return 1; /* error */
10124 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10126 /* bash does not accept +-login, we also won't */
10127 } else if (cmdline && val && (c == '-')) { /* long options */
10128 if (strcmp(p, "login") == 0)
10140 * The shift builtin command.
10142 static int FAST_FUNC
10143 shiftcmd(int argc UNUSED_PARAM, char **argv)
10150 n = number(argv[1]);
10151 if (n > shellparam.nparam)
10152 n = 0; /* bash compat, was = shellparam.nparam; */
10154 shellparam.nparam -= n;
10155 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10156 if (shellparam.malloced)
10159 ap2 = shellparam.p;
10160 while ((*ap2++ = *ap1++) != NULL)
10162 #if ENABLE_ASH_GETOPTS
10163 shellparam.optind = 1;
10164 shellparam.optoff = -1;
10171 * POSIX requires that 'set' (but not export or readonly) output the
10172 * variables in lexicographic order - by the locale's collating order (sigh).
10173 * Maybe we could keep them in an ordered balanced binary tree
10174 * instead of hashed lists.
10175 * For now just roll 'em through qsort for printing...
10178 showvars(const char *sep_prefix, int on, int off)
10181 char **ep, **epend;
10183 ep = listvars(on, off, &epend);
10184 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10186 sep = *sep_prefix ? " " : sep_prefix;
10188 for (; ep < epend; ep++) {
10192 p = strchrnul(*ep, '=');
10195 q = single_quote(++p);
10196 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10202 * The set command builtin.
10204 static int FAST_FUNC
10205 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10210 return showvars(nullstr, 0, VUNSET);
10213 if (!options(0)) { /* if no parse error... */
10216 if (*argptr != NULL) {
10224 #if ENABLE_ASH_RANDOM_SUPPORT
10225 static void FAST_FUNC
10226 change_random(const char *value)
10230 if (value == NULL) {
10231 /* "get", generate */
10232 t = next_random(&random_gen);
10233 /* set without recursion */
10234 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10235 vrandom.flags &= ~VNOFUNC;
10238 t = strtoul(value, NULL, 10);
10239 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10244 #if ENABLE_ASH_GETOPTS
10246 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10255 if (*param_optind < 1)
10257 optnext = optfirst + *param_optind - 1;
10259 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10262 p = optnext[-1] + *optoff;
10263 if (p == NULL || *p == '\0') {
10264 /* Current word is done, advance */
10266 if (p == NULL || *p != '-' || *++p == '\0') {
10273 if (LONE_DASH(p)) /* check for "--" */
10278 for (q = optstr; *q != c;) {
10280 if (optstr[0] == ':') {
10283 err |= setvarsafe("OPTARG", s, 0);
10285 fprintf(stderr, "Illegal option -%c\n", c);
10286 unsetvar("OPTARG");
10296 if (*p == '\0' && (p = *optnext) == NULL) {
10297 if (optstr[0] == ':') {
10300 err |= setvarsafe("OPTARG", s, 0);
10303 fprintf(stderr, "No arg for -%c option\n", c);
10304 unsetvar("OPTARG");
10312 err |= setvarsafe("OPTARG", p, 0);
10315 err |= setvarsafe("OPTARG", nullstr, 0);
10317 *optoff = p ? p - *(optnext - 1) : -1;
10318 *param_optind = optnext - optfirst + 1;
10319 fmtstr(s, sizeof(s), "%d", *param_optind);
10320 err |= setvarsafe("OPTIND", s, VNOFUNC);
10323 err |= setvarsafe(optvar, s, 0);
10327 flush_stdout_stderr();
10328 raise_exception(EXERROR);
10334 * The getopts builtin. Shellparam.optnext points to the next argument
10335 * to be processed. Shellparam.optptr points to the next character to
10336 * be processed in the current argument. If shellparam.optnext is NULL,
10337 * then it's the first time getopts has been called.
10339 static int FAST_FUNC
10340 getoptscmd(int argc, char **argv)
10345 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10347 optbase = shellparam.p;
10348 if (shellparam.optind > shellparam.nparam + 1) {
10349 shellparam.optind = 1;
10350 shellparam.optoff = -1;
10353 optbase = &argv[3];
10354 if (shellparam.optind > argc - 2) {
10355 shellparam.optind = 1;
10356 shellparam.optoff = -1;
10360 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10361 &shellparam.optoff);
10363 #endif /* ASH_GETOPTS */
10366 /* ============ Shell parser */
10369 struct heredoc *next; /* next here document in list */
10370 union node *here; /* redirection node */
10371 char *eofmark; /* string indicating end of input */
10372 smallint striptabs; /* if set, strip leading tabs */
10375 static smallint tokpushback; /* last token pushed back */
10376 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10377 static smallint quoteflag; /* set if (part of) last token was quoted */
10378 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10379 static struct heredoc *heredoclist; /* list of here documents to read */
10380 static char *wordtext; /* text of last word returned by readtoken */
10381 static struct nodelist *backquotelist;
10382 static union node *redirnode;
10383 static struct heredoc *heredoc;
10385 static const char *
10386 tokname(char *buf, int tok)
10389 return tokname_array[tok] + 1;
10390 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10394 /* raise_error_unexpected_syntax:
10395 * Called when an unexpected token is read during the parse. The argument
10396 * is the token that is expected, or -1 if more than one type of token can
10397 * occur at this point.
10399 static void raise_error_unexpected_syntax(int) NORETURN;
10401 raise_error_unexpected_syntax(int token)
10407 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10409 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10410 raise_error_syntax(msg);
10414 #define EOFMARKLEN 79
10416 /* parsing is heavily cross-recursive, need these forward decls */
10417 static union node *andor(void);
10418 static union node *pipeline(void);
10419 static union node *parse_command(void);
10420 static void parseheredoc(void);
10421 static char peektoken(void);
10422 static int readtoken(void);
10424 static union node *
10427 union node *n1, *n2, *n3;
10430 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10431 if (nlflag == 2 && peektoken())
10437 if (tok == TBACKGND) {
10438 if (n2->type == NPIPE) {
10439 n2->npipe.pipe_backgnd = 1;
10441 if (n2->type != NREDIR) {
10442 n3 = stzalloc(sizeof(struct nredir));
10444 /*n3->nredir.redirect = NULL; - stzalloc did it */
10447 n2->type = NBACKGND;
10453 n3 = stzalloc(sizeof(struct nbinary));
10455 n3->nbinary.ch1 = n1;
10456 n3->nbinary.ch2 = n2;
10472 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10480 pungetc(); /* push back EOF on input */
10484 raise_error_unexpected_syntax(-1);
10491 static union node *
10494 union node *n1, *n2, *n3;
10502 } else if (t == TOR) {
10508 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10510 n3 = stzalloc(sizeof(struct nbinary));
10512 n3->nbinary.ch1 = n1;
10513 n3->nbinary.ch2 = n2;
10518 static union node *
10521 union node *n1, *n2, *pipenode;
10522 struct nodelist *lp, *prev;
10526 TRACE(("pipeline: entered\n"));
10527 if (readtoken() == TNOT) {
10529 checkkwd = CHKKWD | CHKALIAS;
10532 n1 = parse_command();
10533 if (readtoken() == TPIPE) {
10534 pipenode = stzalloc(sizeof(struct npipe));
10535 pipenode->type = NPIPE;
10536 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10537 lp = stzalloc(sizeof(struct nodelist));
10538 pipenode->npipe.cmdlist = lp;
10542 lp = stzalloc(sizeof(struct nodelist));
10543 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10544 lp->n = parse_command();
10546 } while (readtoken() == TPIPE);
10552 n2 = stzalloc(sizeof(struct nnot));
10560 static union node *
10565 n = stzalloc(sizeof(struct narg));
10567 /*n->narg.next = NULL; - stzalloc did it */
10568 n->narg.text = wordtext;
10569 n->narg.backquote = backquotelist;
10574 fixredir(union node *n, const char *text, int err)
10578 TRACE(("Fix redir %s %d\n", text, err));
10580 n->ndup.vname = NULL;
10582 fd = bb_strtou(text, NULL, 10);
10583 if (!errno && fd >= 0)
10584 n->ndup.dupfd = fd;
10585 else if (LONE_DASH(text))
10586 n->ndup.dupfd = -1;
10589 raise_error_syntax("bad fd number");
10590 n->ndup.vname = makename();
10595 * Returns true if the text contains nothing to expand (no dollar signs
10599 noexpand(const char *text)
10603 while ((c = *text++) != '\0') {
10604 if (c == CTLQUOTEMARK)
10608 else if (SIT(c, BASESYNTAX) == CCTL)
10617 union node *n = redirnode;
10619 if (readtoken() != TWORD)
10620 raise_error_unexpected_syntax(-1);
10621 if (n->type == NHERE) {
10622 struct heredoc *here = heredoc;
10626 if (quoteflag == 0)
10628 TRACE(("Here document %d\n", n->type));
10629 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10630 raise_error_syntax("illegal eof marker for << redirection");
10631 rmescapes(wordtext, 0);
10632 here->eofmark = wordtext;
10634 if (heredoclist == NULL)
10635 heredoclist = here;
10637 for (p = heredoclist; p->next; p = p->next)
10641 } else if (n->type == NTOFD || n->type == NFROMFD) {
10642 fixredir(n, wordtext, 0);
10644 n->nfile.fname = makename();
10648 static union node *
10651 union node *args, **app;
10652 union node *n = NULL;
10653 union node *vars, **vpp;
10654 union node **rpp, *redir;
10656 #if ENABLE_ASH_BASH_COMPAT
10657 smallint double_brackets_flag = 0;
10667 savecheckkwd = CHKALIAS;
10670 checkkwd = savecheckkwd;
10673 #if ENABLE_ASH_BASH_COMPAT
10674 case TAND: /* "&&" */
10675 case TOR: /* "||" */
10676 if (!double_brackets_flag) {
10680 wordtext = (char *) (t == TAND ? "-a" : "-o");
10683 n = stzalloc(sizeof(struct narg));
10685 /*n->narg.next = NULL; - stzalloc did it */
10686 n->narg.text = wordtext;
10687 #if ENABLE_ASH_BASH_COMPAT
10688 if (strcmp("[[", wordtext) == 0)
10689 double_brackets_flag = 1;
10690 else if (strcmp("]]", wordtext) == 0)
10691 double_brackets_flag = 0;
10693 n->narg.backquote = backquotelist;
10694 if (savecheckkwd && isassignment(wordtext)) {
10696 vpp = &n->narg.next;
10699 app = &n->narg.next;
10704 *rpp = n = redirnode;
10705 rpp = &n->nfile.next;
10706 parsefname(); /* read name of redirection file */
10709 if (args && app == &args->narg.next
10712 struct builtincmd *bcmd;
10715 /* We have a function */
10716 if (readtoken() != TRP)
10717 raise_error_unexpected_syntax(TRP);
10718 name = n->narg.text;
10719 if (!goodname(name)
10720 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10722 raise_error_syntax("bad function name");
10725 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10726 n->narg.next = parse_command();
10739 n = stzalloc(sizeof(struct ncmd));
10741 n->ncmd.args = args;
10742 n->ncmd.assign = vars;
10743 n->ncmd.redirect = redir;
10747 static union node *
10748 parse_command(void)
10750 union node *n1, *n2;
10751 union node *ap, **app;
10752 union node *cp, **cpp;
10753 union node *redir, **rpp;
10760 switch (readtoken()) {
10762 raise_error_unexpected_syntax(-1);
10765 n1 = stzalloc(sizeof(struct nif));
10767 n1->nif.test = list(0);
10768 if (readtoken() != TTHEN)
10769 raise_error_unexpected_syntax(TTHEN);
10770 n1->nif.ifpart = list(0);
10772 while (readtoken() == TELIF) {
10773 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10774 n2 = n2->nif.elsepart;
10776 n2->nif.test = list(0);
10777 if (readtoken() != TTHEN)
10778 raise_error_unexpected_syntax(TTHEN);
10779 n2->nif.ifpart = list(0);
10781 if (lasttoken == TELSE)
10782 n2->nif.elsepart = list(0);
10784 n2->nif.elsepart = NULL;
10792 n1 = stzalloc(sizeof(struct nbinary));
10793 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10794 n1->nbinary.ch1 = list(0);
10797 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10798 got == TWORD ? wordtext : ""));
10799 raise_error_unexpected_syntax(TDO);
10801 n1->nbinary.ch2 = list(0);
10806 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10807 raise_error_syntax("bad for loop variable");
10808 n1 = stzalloc(sizeof(struct nfor));
10810 n1->nfor.var = wordtext;
10811 checkkwd = CHKKWD | CHKALIAS;
10812 if (readtoken() == TIN) {
10814 while (readtoken() == TWORD) {
10815 n2 = stzalloc(sizeof(struct narg));
10817 /*n2->narg.next = NULL; - stzalloc did it */
10818 n2->narg.text = wordtext;
10819 n2->narg.backquote = backquotelist;
10821 app = &n2->narg.next;
10824 n1->nfor.args = ap;
10825 if (lasttoken != TNL && lasttoken != TSEMI)
10826 raise_error_unexpected_syntax(-1);
10828 n2 = stzalloc(sizeof(struct narg));
10830 /*n2->narg.next = NULL; - stzalloc did it */
10831 n2->narg.text = (char *)dolatstr;
10832 /*n2->narg.backquote = NULL;*/
10833 n1->nfor.args = n2;
10835 * Newline or semicolon here is optional (but note
10836 * that the original Bourne shell only allowed NL).
10838 if (lasttoken != TNL && lasttoken != TSEMI)
10841 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10842 if (readtoken() != TDO)
10843 raise_error_unexpected_syntax(TDO);
10844 n1->nfor.body = list(0);
10848 n1 = stzalloc(sizeof(struct ncase));
10850 if (readtoken() != TWORD)
10851 raise_error_unexpected_syntax(TWORD);
10852 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10854 /*n2->narg.next = NULL; - stzalloc did it */
10855 n2->narg.text = wordtext;
10856 n2->narg.backquote = backquotelist;
10858 checkkwd = CHKKWD | CHKALIAS;
10859 } while (readtoken() == TNL);
10860 if (lasttoken != TIN)
10861 raise_error_unexpected_syntax(TIN);
10862 cpp = &n1->ncase.cases;
10864 checkkwd = CHKNL | CHKKWD;
10866 while (t != TESAC) {
10867 if (lasttoken == TLP)
10869 *cpp = cp = stzalloc(sizeof(struct nclist));
10871 app = &cp->nclist.pattern;
10873 *app = ap = stzalloc(sizeof(struct narg));
10875 /*ap->narg.next = NULL; - stzalloc did it */
10876 ap->narg.text = wordtext;
10877 ap->narg.backquote = backquotelist;
10878 if (readtoken() != TPIPE)
10880 app = &ap->narg.next;
10883 //ap->narg.next = NULL;
10884 if (lasttoken != TRP)
10885 raise_error_unexpected_syntax(TRP);
10886 cp->nclist.body = list(2);
10888 cpp = &cp->nclist.next;
10890 checkkwd = CHKNL | CHKKWD;
10894 raise_error_unexpected_syntax(TENDCASE);
10901 n1 = stzalloc(sizeof(struct nredir));
10902 n1->type = NSUBSHELL;
10903 n1->nredir.n = list(0);
10904 /*n1->nredir.redirect = NULL; - stzalloc did it */
10914 return simplecmd();
10917 if (readtoken() != t)
10918 raise_error_unexpected_syntax(t);
10921 /* Now check for redirection which may follow command */
10922 checkkwd = CHKKWD | CHKALIAS;
10924 while (readtoken() == TREDIR) {
10925 *rpp = n2 = redirnode;
10926 rpp = &n2->nfile.next;
10932 if (n1->type != NSUBSHELL) {
10933 n2 = stzalloc(sizeof(struct nredir));
10938 n1->nredir.redirect = redir;
10943 #if ENABLE_ASH_BASH_COMPAT
10944 static int decode_dollar_squote(void)
10946 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10952 p = strchr(C_escapes, c);
10957 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10961 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10963 } else if (c == 'x') { /* \xHH */
10967 } while (isxdigit(c) && --cnt);
10969 if (cnt == 3) { /* \x but next char is "bad" */
10973 } else { /* simple seq like \\ or \t */
10978 c = bb_process_escape_sequence((void*)&p);
10979 } else { /* unrecognized "\z": print both chars unless ' or " */
10980 if (c != '\'' && c != '"') {
10982 c |= 0x100; /* "please encode \, then me" */
10990 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10991 * is not NULL, read a here document. In the latter case, eofmark is the
10992 * word which marks the end of the document and striptabs is true if
10993 * leading tabs should be stripped from the document. The argument c
10994 * is the first character of the input token or document.
10996 * Because C does not have internal subroutines, I have simulated them
10997 * using goto's to implement the subroutine linkage. The following macros
10998 * will run code that appears at the end of readtoken1.
11000 #define CHECKEND() {goto checkend; checkend_return:;}
11001 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11002 #define PARSESUB() {goto parsesub; parsesub_return:;}
11003 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11004 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11005 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11007 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11009 /* NB: syntax parameter fits into smallint */
11010 /* c parameter is an unsigned char or PEOF or PEOA */
11013 char line[EOFMARKLEN + 1];
11014 struct nodelist *bqlist;
11018 smallint prevsyntax; /* syntax before arithmetic */
11019 #if ENABLE_ASH_EXPAND_PRMT
11020 smallint pssyntax; /* we are expanding a prompt string */
11022 int varnest; /* levels of variables expansion */
11023 int arinest; /* levels of arithmetic expansion */
11024 int parenlevel; /* levels of parens in arithmetic */
11025 int dqvarnest; /* levels of variables expansion within double quotes */
11027 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11030 /* Avoid longjmp clobbering */
11036 (void) &parenlevel;
11039 (void) &prevsyntax;
11042 startlinno = g_parsefile->linno;
11046 #if ENABLE_ASH_EXPAND_PRMT
11047 pssyntax = (syntax == PSSYNTAX);
11051 dblquote = (syntax == DQSYNTAX);
11057 STARTSTACKSTR(out);
11059 /* For each line, until end of word */
11060 CHECKEND(); /* set c to PEOF if at end of here document */
11061 for (;;) { /* until end of line or end of word */
11062 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11063 switch (SIT(c, syntax)) {
11064 case CNL: /* '\n' */
11065 if (syntax == BASESYNTAX)
11066 goto endword; /* exit outer loop */
11068 g_parsefile->linno++;
11069 setprompt_if(doprompt, 2);
11071 goto loop; /* continue outer loop */
11076 if (eofmark == NULL || dblquote)
11077 USTPUTC(CTLESC, out);
11078 #if ENABLE_ASH_BASH_COMPAT
11079 if (c == '\\' && bash_dollar_squote) {
11080 c = decode_dollar_squote();
11082 USTPUTC('\\', out);
11083 c = (unsigned char)c;
11089 case CBACK: /* backslash */
11090 c = pgetc_without_PEOA();
11092 USTPUTC(CTLESC, out);
11093 USTPUTC('\\', out);
11095 } else if (c == '\n') {
11096 setprompt_if(doprompt, 2);
11098 #if ENABLE_ASH_EXPAND_PRMT
11099 if (c == '$' && pssyntax) {
11100 USTPUTC(CTLESC, out);
11101 USTPUTC('\\', out);
11104 /* Backslash is retained if we are in "str" and next char isn't special */
11109 && (c != '"' || eofmark != NULL)
11111 USTPUTC(CTLESC, out);
11112 USTPUTC('\\', out);
11114 if (SIT(c, SQSYNTAX) == CCTL)
11115 USTPUTC(CTLESC, out);
11123 if (eofmark == NULL) {
11124 USTPUTC(CTLQUOTEMARK, out);
11132 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11133 if (eofmark != NULL && arinest == 0
11138 if (dqvarnest == 0) {
11139 syntax = BASESYNTAX;
11146 case CVAR: /* '$' */
11147 PARSESUB(); /* parse substitution */
11149 case CENDVAR: /* '}' */
11152 if (dqvarnest > 0) {
11159 #if ENABLE_SH_MATH_SUPPORT
11160 case CLP: /* '(' in arithmetic */
11164 case CRP: /* ')' in arithmetic */
11165 if (parenlevel > 0) {
11168 if (pgetc() == ')') {
11169 if (--arinest == 0) {
11170 syntax = prevsyntax;
11171 dblquote = (syntax == DQSYNTAX);
11176 * unbalanced parens
11177 * (don't 2nd guess - no error)
11185 case CBQUOTE: /* '`' */
11189 goto endword; /* exit outer loop */
11193 if (varnest == 0) {
11194 #if ENABLE_ASH_BASH_COMPAT
11196 if (pgetc() == '>')
11197 c = 0x100 + '>'; /* flag &> */
11201 goto endword; /* exit outer loop */
11203 IF_ASH_ALIAS(if (c != PEOA))
11210 #if ENABLE_SH_MATH_SUPPORT
11211 if (syntax == ARISYNTAX)
11212 raise_error_syntax("missing '))'");
11214 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11215 raise_error_syntax("unterminated quoted string");
11216 if (varnest != 0) {
11217 startlinno = g_parsefile->linno;
11219 raise_error_syntax("missing '}'");
11221 USTPUTC('\0', out);
11222 len = out - (char *)stackblock();
11223 out = stackblock();
11224 if (eofmark == NULL) {
11225 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11228 if (isdigit_str9(out)) {
11229 PARSEREDIR(); /* passed as params: out, c */
11230 lasttoken = TREDIR;
11233 /* else: non-number X seen, interpret it
11234 * as "NNNX>file" = "NNNX >file" */
11238 quoteflag = quotef;
11239 backquotelist = bqlist;
11240 grabstackblock(len);
11244 /* end of readtoken routine */
11247 * Check to see whether we are at the end of the here document. When this
11248 * is called, c is set to the first character of the next input line. If
11249 * we are at the end of the here document, this routine sets the c to PEOF.
11253 #if ENABLE_ASH_ALIAS
11255 c = pgetc_without_PEOA();
11258 while (c == '\t') {
11259 c = pgetc_without_PEOA();
11262 if (c == *eofmark) {
11263 if (pfgets(line, sizeof(line)) != NULL) {
11267 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11269 if (*p == '\n' && *q == '\0') {
11271 g_parsefile->linno++;
11272 needprompt = doprompt;
11274 pushstring(line, NULL);
11279 goto checkend_return;
11283 * Parse a redirection operator. The variable "out" points to a string
11284 * specifying the fd to be redirected. The variable "c" contains the
11285 * first character of the redirection operator.
11288 /* out is already checked to be a valid number or "" */
11289 int fd = (*out == '\0' ? -1 : atoi(out));
11292 np = stzalloc(sizeof(struct nfile));
11297 np->type = NAPPEND;
11299 np->type = NCLOBBER;
11302 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11308 #if ENABLE_ASH_BASH_COMPAT
11309 else if (c == 0x100 + '>') { /* this flags &> redirection */
11311 pgetc(); /* this is '>', no need to check */
11315 else { /* c == '<' */
11316 /*np->nfile.fd = 0; - stzalloc did it */
11320 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11321 np = stzalloc(sizeof(struct nhere));
11322 /*np->nfile.fd = 0; - stzalloc did it */
11325 heredoc = stzalloc(sizeof(struct heredoc));
11326 heredoc->here = np;
11329 heredoc->striptabs = 1;
11331 /*heredoc->striptabs = 0; - stzalloc did it */
11337 np->type = NFROMFD;
11341 np->type = NFROMTO;
11353 goto parseredir_return;
11357 * Parse a substitution. At this point, we have read the dollar sign
11358 * and nothing else.
11361 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11362 * (assuming ascii char codes, as the original implementation did) */
11363 #define is_special(c) \
11364 (((unsigned)(c) - 33 < 32) \
11365 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11367 unsigned char subtype;
11372 if (c > 255 /* PEOA or PEOF */
11373 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11375 #if ENABLE_ASH_BASH_COMPAT
11377 bash_dollar_squote = 1;
11382 } else if (c == '(') {
11383 /* $(command) or $((arith)) */
11384 if (pgetc() == '(') {
11385 #if ENABLE_SH_MATH_SUPPORT
11388 raise_error_syntax("you disabled math support for $((arith)) syntax");
11395 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11396 USTPUTC(CTLVAR, out);
11397 typeloc = out - (char *)stackblock();
11398 USTPUTC(VSNORMAL, out);
11399 subtype = VSNORMAL;
11405 c = '#'; /* ${#} - same as $# */
11407 subtype = VSLENGTH; /* ${#VAR} */
11412 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11413 /* $[{[#]]NAME[}] */
11417 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11418 } else if (isdigit(c)) {
11419 /* $[{[#]]NUM[}] */
11423 } while (isdigit(c));
11424 } else if (is_special(c)) {
11425 /* $[{[#]]<specialchar>[}] */
11430 raise_error_syntax("bad substitution");
11432 if (c != '}' && subtype == VSLENGTH) {
11433 /* ${#VAR didn't end with } */
11439 if (subtype == 0) {
11440 /* ${VAR...} but not $VAR or ${#VAR} */
11441 /* c == first char after VAR */
11445 #if ENABLE_ASH_BASH_COMPAT
11446 if (c == ':' || c == '$' || isdigit(c)) {
11447 //TODO: support more general format ${v:EXPR:EXPR},
11448 // where EXPR follows $(()) rules
11449 subtype = VSSUBSTR;
11451 break; /* "goto do_pungetc" is bigger (!) */
11457 static const char types[] ALIGN1 = "}-+?=";
11458 const char *p = strchr(types, c);
11461 subtype = p - types + VSNORMAL;
11467 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11474 #if ENABLE_ASH_BASH_COMPAT
11476 /* ${v/[/]pattern/repl} */
11477 //TODO: encode pattern and repl separately.
11478 // Currently ${v/$var_with_slash/repl} is horribly broken
11479 subtype = VSREPLACE;
11483 subtype++; /* VSREPLACEALL */
11491 if (dblquote || arinest)
11493 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11494 if (subtype != VSNORMAL) {
11496 if (dblquote || arinest) {
11501 goto parsesub_return;
11505 * Called to parse command substitutions. Newstyle is set if the command
11506 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11507 * list of commands (passed by reference), and savelen is the number of
11508 * characters on the top of the stack which must be preserved.
11511 struct nodelist **nlpp;
11514 char *volatile str;
11515 struct jmploc jmploc;
11516 struct jmploc *volatile savehandler;
11518 smallint saveprompt = 0;
11521 (void) &saveprompt;
11523 savepbq = parsebackquote;
11524 if (setjmp(jmploc.loc)) {
11526 parsebackquote = 0;
11527 exception_handler = savehandler;
11528 longjmp(exception_handler->loc, 1);
11532 savelen = out - (char *)stackblock();
11534 str = ckmalloc(savelen);
11535 memcpy(str, stackblock(), savelen);
11537 savehandler = exception_handler;
11538 exception_handler = &jmploc;
11541 /* We must read until the closing backquote, giving special
11542 treatment to some slashes, and then push the string and
11543 reread it as input, interpreting it normally. */
11548 STARTSTACKSTR(pout);
11552 setprompt_if(needprompt, 2);
11561 g_parsefile->linno++;
11562 setprompt_if(doprompt, 2);
11564 * If eating a newline, avoid putting
11565 * the newline into the new character
11566 * stream (via the STPUTC after the
11571 if (pc != '\\' && pc != '`' && pc != '$'
11572 && (!dblquote || pc != '"')
11574 STPUTC('\\', pout);
11576 if (pc <= 255 /* not PEOA or PEOF */) {
11582 IF_ASH_ALIAS(case PEOA:)
11583 startlinno = g_parsefile->linno;
11584 raise_error_syntax("EOF in backquote substitution");
11587 g_parsefile->linno++;
11588 needprompt = doprompt;
11597 STPUTC('\0', pout);
11598 psavelen = pout - (char *)stackblock();
11599 if (psavelen > 0) {
11600 pstr = grabstackstr(pout);
11601 setinputstring(pstr);
11606 nlpp = &(*nlpp)->next;
11607 *nlpp = stzalloc(sizeof(**nlpp));
11608 /* (*nlpp)->next = NULL; - stzalloc did it */
11609 parsebackquote = oldstyle;
11612 saveprompt = doprompt;
11619 doprompt = saveprompt;
11620 else if (readtoken() != TRP)
11621 raise_error_unexpected_syntax(TRP);
11626 * Start reading from old file again, ignoring any pushed back
11627 * tokens left from the backquote parsing
11632 while (stackblocksize() <= savelen)
11634 STARTSTACKSTR(out);
11636 memcpy(out, str, savelen);
11637 STADJUST(savelen, out);
11643 parsebackquote = savepbq;
11644 exception_handler = savehandler;
11645 if (arinest || dblquote)
11646 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11648 USTPUTC(CTLBACKQ, out);
11650 goto parsebackq_oldreturn;
11651 goto parsebackq_newreturn;
11654 #if ENABLE_SH_MATH_SUPPORT
11656 * Parse an arithmetic expansion (indicate start of one and set state)
11659 if (++arinest == 1) {
11660 prevsyntax = syntax;
11661 syntax = ARISYNTAX;
11662 USTPUTC(CTLARI, out);
11669 * we collapse embedded arithmetic expansion to
11670 * parenthesis, which should be equivalent
11674 goto parsearith_return;
11678 } /* end of readtoken */
11681 * Read the next input token.
11682 * If the token is a word, we set backquotelist to the list of cmds in
11683 * backquotes. We set quoteflag to true if any part of the word was
11685 * If the token is TREDIR, then we set redirnode to a structure containing
11687 * In all cases, the variable startlinno is set to the number of the line
11688 * on which the token starts.
11690 * [Change comment: here documents and internal procedures]
11691 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11692 * word parsing code into a separate routine. In this case, readtoken
11693 * doesn't need to have any internal procedures, but parseword does.
11694 * We could also make parseoperator in essence the main routine, and
11695 * have parseword (readtoken1?) handle both words and redirection.]
11697 #define NEW_xxreadtoken
11698 #ifdef NEW_xxreadtoken
11699 /* singles must be first! */
11700 static const char xxreadtoken_chars[7] ALIGN1 = {
11701 '\n', '(', ')', /* singles */
11702 '&', '|', ';', /* doubles */
11706 #define xxreadtoken_singles 3
11707 #define xxreadtoken_doubles 3
11709 static const char xxreadtoken_tokens[] ALIGN1 = {
11710 TNL, TLP, TRP, /* only single occurrence allowed */
11711 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11712 TEOF, /* corresponds to trailing nul */
11713 TAND, TOR, TENDCASE /* if double occurrence */
11725 setprompt_if(needprompt, 2);
11726 startlinno = g_parsefile->linno;
11727 for (;;) { /* until token or start of word found */
11729 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11733 while ((c = pgetc()) != '\n' && c != PEOF)
11736 } else if (c == '\\') {
11737 if (pgetc() != '\n') {
11739 break; /* return readtoken1(...) */
11741 startlinno = ++g_parsefile->linno;
11742 setprompt_if(doprompt, 2);
11746 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11749 g_parsefile->linno++;
11750 needprompt = doprompt;
11753 p = strchr(xxreadtoken_chars, c);
11755 break; /* return readtoken1(...) */
11757 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11759 if (cc == c) { /* double occurrence? */
11760 p += xxreadtoken_doubles + 1;
11763 #if ENABLE_ASH_BASH_COMPAT
11764 if (c == '&' && cc == '>') /* &> */
11765 break; /* return readtoken1(...) */
11770 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11775 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11777 #else /* old xxreadtoken */
11778 #define RETURN(token) return lasttoken = token
11788 setprompt_if(needprompt, 2);
11789 startlinno = g_parsefile->linno;
11790 for (;;) { /* until token or start of word found */
11793 case ' ': case '\t':
11794 IF_ASH_ALIAS(case PEOA:)
11797 while ((c = pgetc()) != '\n' && c != PEOF)
11802 if (pgetc() == '\n') {
11803 startlinno = ++g_parsefile->linno;
11804 setprompt_if(doprompt, 2);
11810 g_parsefile->linno++;
11811 needprompt = doprompt;
11816 if (pgetc() == '&')
11821 if (pgetc() == '|')
11826 if (pgetc() == ';')
11839 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11842 #endif /* old xxreadtoken */
11849 smallint alreadyseen = tokpushback;
11852 #if ENABLE_ASH_ALIAS
11861 if (checkkwd & CHKNL) {
11868 if (t != TWORD || quoteflag) {
11873 * check for keywords
11875 if (checkkwd & CHKKWD) {
11876 const char *const *pp;
11878 pp = findkwd(wordtext);
11880 lasttoken = t = pp - tokname_array;
11881 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11886 if (checkkwd & CHKALIAS) {
11887 #if ENABLE_ASH_ALIAS
11889 ap = lookupalias(wordtext, 1);
11892 pushstring(ap->val, ap);
11902 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11904 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11916 return tokname_array[t][0];
11920 * Read and parse a command. Returns NODE_EOF on end of file.
11921 * (NULL is a valid parse tree indicating a blank line.)
11923 static union node *
11924 parsecmd(int interact)
11929 doprompt = interact;
11930 setprompt_if(doprompt, doprompt);
11942 * Input any here documents.
11947 struct heredoc *here;
11950 here = heredoclist;
11951 heredoclist = NULL;
11954 setprompt_if(needprompt, 2);
11955 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
11956 here->eofmark, here->striptabs);
11957 n = stzalloc(sizeof(struct narg));
11958 n->narg.type = NARG;
11959 /*n->narg.next = NULL; - stzalloc did it */
11960 n->narg.text = wordtext;
11961 n->narg.backquote = backquotelist;
11962 here->here->nhere.doc = n;
11969 * called by editline -- any expansions to the prompt should be added here.
11971 #if ENABLE_ASH_EXPAND_PRMT
11972 static const char *
11973 expandstr(const char *ps)
11977 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11978 * and token processing _can_ alter it (delete NULs etc). */
11979 setinputstring((char *)ps);
11980 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11983 n.narg.type = NARG;
11984 n.narg.next = NULL;
11985 n.narg.text = wordtext;
11986 n.narg.backquote = backquotelist;
11988 expandarg(&n, NULL, 0);
11989 return stackblock();
11994 * Execute a command or commands contained in a string.
11997 evalstring(char *s, int mask)
12000 struct stackmark smark;
12004 setstackmark(&smark);
12007 while ((n = parsecmd(0)) != NODE_EOF) {
12009 popstackmark(&smark);
12022 * The eval command.
12024 static int FAST_FUNC
12025 evalcmd(int argc UNUSED_PARAM, char **argv)
12034 STARTSTACKSTR(concat);
12036 concat = stack_putstr(p, concat);
12040 STPUTC(' ', concat);
12042 STPUTC('\0', concat);
12043 p = grabstackstr(concat);
12045 evalstring(p, ~SKIPEVAL);
12051 * Read and execute commands.
12052 * "Top" is nonzero for the top level command loop;
12053 * it turns on prompting if the shell is interactive.
12059 struct stackmark smark;
12063 TRACE(("cmdloop(%d) called\n", top));
12067 setstackmark(&smark);
12070 showjobs(stderr, SHOW_CHANGED);
12073 if (iflag && top) {
12075 #if ENABLE_ASH_MAIL
12079 n = parsecmd(inter);
12081 if (DEBUG > 2 && debug && (n != NODE_EOF))
12084 if (n == NODE_EOF) {
12085 if (!top || numeof >= 50)
12087 if (!stoppedjobs()) {
12090 out2str("\nUse \"exit\" to leave shell.\n");
12093 } else if (nflag == 0) {
12094 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12099 popstackmark(&smark);
12104 return skip & SKIPEVAL;
12111 * Take commands from a file. To be compatible we should do a path
12112 * search for the file, which is necessary to find sub-commands.
12115 find_dot_file(char *name)
12118 const char *path = pathval();
12121 /* don't try this for absolute or relative paths */
12122 if (strchr(name, '/'))
12125 /* IIRC standards do not say whether . is to be searched.
12126 * And it is even smaller this way, making it unconditional for now:
12128 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12133 while ((fullname = path_advance(&path, name)) != NULL) {
12135 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12137 * Don't bother freeing here, since it will
12138 * be freed by the caller.
12142 if (fullname != name)
12143 stunalloc(fullname);
12146 /* not found in the PATH */
12147 ash_msg_and_raise_error("%s: not found", name);
12151 static int FAST_FUNC
12152 dotcmd(int argc, char **argv)
12155 struct strlist *sp;
12156 volatile struct shparam saveparam;
12158 for (sp = cmdenviron; sp; sp = sp->next)
12159 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12162 /* bash says: "bash: .: filename argument required" */
12163 return 2; /* bash compat */
12166 /* "false; . empty_file; echo $?" should print 0, not 1: */
12169 fullname = find_dot_file(argv[1]);
12173 if (argc) { /* argc > 0, argv[0] != NULL */
12174 saveparam = shellparam;
12175 shellparam.malloced = 0;
12176 shellparam.nparam = argc;
12177 shellparam.p = argv;
12180 setinputfile(fullname, INPUT_PUSH_FILE);
12181 commandname = fullname;
12186 freeparam(&shellparam);
12187 shellparam = saveparam;
12193 static int FAST_FUNC
12194 exitcmd(int argc UNUSED_PARAM, char **argv)
12199 exitstatus = number(argv[1]);
12200 raise_exception(EXEXIT);
12205 * Read a file containing shell functions.
12208 readcmdfile(char *name)
12210 setinputfile(name, INPUT_PUSH_FILE);
12216 /* ============ find_command inplementation */
12219 * Resolve a command name. If you change this routine, you may have to
12220 * change the shellexec routine as well.
12223 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12225 struct tblentry *cmdp;
12232 struct builtincmd *bcmd;
12234 /* If name contains a slash, don't use PATH or hash table */
12235 if (strchr(name, '/') != NULL) {
12236 entry->u.index = -1;
12237 if (act & DO_ABS) {
12238 while (stat(name, &statb) < 0) {
12240 if (errno == EINTR)
12243 entry->cmdtype = CMDUNKNOWN;
12247 entry->cmdtype = CMDNORMAL;
12251 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12253 updatetbl = (path == pathval());
12256 if (strstr(path, "%builtin") != NULL)
12257 act |= DO_ALTBLTIN;
12260 /* If name is in the table, check answer will be ok */
12261 cmdp = cmdlookup(name, 0);
12262 if (cmdp != NULL) {
12265 switch (cmdp->cmdtype) {
12283 } else if (cmdp->rehash == 0)
12284 /* if not invalidated by cd, we're done */
12288 /* If %builtin not in path, check for builtin next */
12289 bcmd = find_builtin(name);
12291 if (IS_BUILTIN_REGULAR(bcmd))
12292 goto builtin_success;
12293 if (act & DO_ALTPATH) {
12294 if (!(act & DO_ALTBLTIN))
12295 goto builtin_success;
12296 } else if (builtinloc <= 0) {
12297 goto builtin_success;
12301 #if ENABLE_FEATURE_SH_STANDALONE
12303 int applet_no = find_applet_by_name(name);
12304 if (applet_no >= 0) {
12305 entry->cmdtype = CMDNORMAL;
12306 entry->u.index = -2 - applet_no;
12312 /* We have to search path. */
12313 prev = -1; /* where to start */
12314 if (cmdp && cmdp->rehash) { /* doing a rehash */
12315 if (cmdp->cmdtype == CMDBUILTIN)
12318 prev = cmdp->param.index;
12324 while ((fullname = path_advance(&path, name)) != NULL) {
12325 stunalloc(fullname);
12326 /* NB: code below will still use fullname
12327 * despite it being "unallocated" */
12330 if (prefix(pathopt, "builtin")) {
12332 goto builtin_success;
12335 if ((act & DO_NOFUNC)
12336 || !prefix(pathopt, "func")
12337 ) { /* ignore unimplemented options */
12341 /* if rehash, don't redo absolute path names */
12342 if (fullname[0] == '/' && idx <= prev) {
12345 TRACE(("searchexec \"%s\": no change\n", name));
12348 while (stat(fullname, &statb) < 0) {
12350 if (errno == EINTR)
12353 if (errno != ENOENT && errno != ENOTDIR)
12357 e = EACCES; /* if we fail, this will be the error */
12358 if (!S_ISREG(statb.st_mode))
12360 if (pathopt) { /* this is a %func directory */
12361 stalloc(strlen(fullname) + 1);
12362 /* NB: stalloc will return space pointed by fullname
12363 * (because we don't have any intervening allocations
12364 * between stunalloc above and this stalloc) */
12365 readcmdfile(fullname);
12366 cmdp = cmdlookup(name, 0);
12367 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12368 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12369 stunalloc(fullname);
12372 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12374 entry->cmdtype = CMDNORMAL;
12375 entry->u.index = idx;
12379 cmdp = cmdlookup(name, 1);
12380 cmdp->cmdtype = CMDNORMAL;
12381 cmdp->param.index = idx;
12386 /* We failed. If there was an entry for this command, delete it */
12387 if (cmdp && updatetbl)
12388 delete_cmd_entry();
12390 ash_msg("%s: %s", name, errmsg(e, "not found"));
12391 entry->cmdtype = CMDUNKNOWN;
12396 entry->cmdtype = CMDBUILTIN;
12397 entry->u.cmd = bcmd;
12401 cmdp = cmdlookup(name, 1);
12402 cmdp->cmdtype = CMDBUILTIN;
12403 cmdp->param.cmd = bcmd;
12407 entry->cmdtype = cmdp->cmdtype;
12408 entry->u = cmdp->param;
12412 /* ============ trap.c */
12415 * The trap builtin.
12417 static int FAST_FUNC
12418 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12422 int signo, exitcode;
12427 for (signo = 0; signo < NSIG; signo++) {
12428 char *tr = trap_ptr[signo];
12430 /* note: bash adds "SIG", but only if invoked
12431 * as "bash". If called as "sh", or if set -o posix,
12432 * then it prints short signal names.
12433 * We are printing short names: */
12434 out1fmt("trap -- %s %s\n",
12436 get_signame(signo));
12437 /* trap_ptr != trap only if we are in special-cased `trap` code.
12438 * In this case, we will exit very soon, no need to free(). */
12439 /* if (trap_ptr != trap && tp[0]) */
12444 if (trap_ptr != trap) {
12457 signo = get_signum(*ap);
12459 /* Mimic bash message exactly */
12460 ash_msg("%s: invalid signal specification", *ap);
12466 if (LONE_DASH(action))
12469 action = ckstrdup(action);
12473 may_have_traps = 1;
12474 trap[signo] = action;
12485 /* ============ Builtins */
12487 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12489 * Lists available builtins
12491 static int FAST_FUNC
12492 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12498 "Built-in commands:\n"
12499 "------------------\n");
12500 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12501 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12502 builtintab[i].name + 1);
12508 #if ENABLE_FEATURE_SH_STANDALONE
12510 const char *a = applet_names;
12512 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12517 a += strlen(a) + 1;
12522 return EXIT_SUCCESS;
12524 #endif /* FEATURE_SH_EXTRA_QUIET */
12527 * The export and readonly commands.
12529 static int FAST_FUNC
12530 exportcmd(int argc UNUSED_PARAM, char **argv)
12536 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12538 if (nextopt("p") != 'p') {
12543 p = strchr(name, '=');
12547 vp = *findvar(hashvar(name), name);
12553 setvar(name, p, flag);
12554 } while ((name = *++aptr) != NULL);
12558 showvars(argv[0], flag, 0);
12563 * Delete a function if it exists.
12566 unsetfunc(const char *name)
12568 struct tblentry *cmdp;
12570 cmdp = cmdlookup(name, 0);
12571 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12572 delete_cmd_entry();
12576 * The unset builtin command. We unset the function before we unset the
12577 * variable to allow a function to be unset when there is a readonly variable
12578 * with the same name.
12580 static int FAST_FUNC
12581 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12588 while ((i = nextopt("vf")) != 0) {
12592 for (ap = argptr; *ap; ap++) {
12605 static const unsigned char timescmd_str[] ALIGN1 = {
12606 ' ', offsetof(struct tms, tms_utime),
12607 '\n', offsetof(struct tms, tms_stime),
12608 ' ', offsetof(struct tms, tms_cutime),
12609 '\n', offsetof(struct tms, tms_cstime),
12612 static int FAST_FUNC
12613 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12615 unsigned long clk_tck, s, t;
12616 const unsigned char *p;
12619 clk_tck = sysconf(_SC_CLK_TCK);
12624 t = *(clock_t *)(((char *) &buf) + p[1]);
12627 out1fmt("%lum%lu.%03lus%c",
12629 (t * 1000) / clk_tck,
12637 #if ENABLE_SH_MATH_SUPPORT
12639 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12640 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12642 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12644 static int FAST_FUNC
12645 letcmd(int argc UNUSED_PARAM, char **argv)
12651 ash_msg_and_raise_error("expression expected");
12653 i = ash_arith(*argv);
12661 * The read builtin. Options:
12662 * -r Do not interpret '\' specially
12663 * -s Turn off echo (tty only)
12664 * -n NCHARS Read NCHARS max
12665 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12666 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12667 * -u FD Read from given FD instead of fd 0
12668 * This uses unbuffered input, which may be avoidable in some cases.
12669 * TODO: bash also has:
12670 * -a ARRAY Read into array[0],[1],etc
12671 * -d DELIM End on DELIM char, not newline
12672 * -e Use line editing (tty only)
12674 static int FAST_FUNC
12675 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12677 char *opt_n = NULL;
12678 char *opt_p = NULL;
12679 char *opt_t = NULL;
12680 char *opt_u = NULL;
12681 int read_flags = 0;
12685 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12694 read_flags |= BUILTIN_READ_SILENT;
12700 read_flags |= BUILTIN_READ_RAW;
12710 r = shell_builtin_read(setvar2,
12712 bltinlookup("IFS"), /* can be NULL */
12720 if ((uintptr_t)r > 1)
12721 ash_msg_and_raise_error(r);
12723 return (uintptr_t)r;
12726 static int FAST_FUNC
12727 umaskcmd(int argc UNUSED_PARAM, char **argv)
12729 static const char permuser[3] ALIGN1 = "ugo";
12730 static const char permmode[3] ALIGN1 = "rwx";
12731 static const short permmask[] ALIGN2 = {
12732 S_IRUSR, S_IWUSR, S_IXUSR,
12733 S_IRGRP, S_IWGRP, S_IXGRP,
12734 S_IROTH, S_IWOTH, S_IXOTH
12737 /* TODO: use bb_parse_mode() instead */
12742 int symbolic_mode = 0;
12744 while (nextopt("S") != '\0') {
12755 if (symbolic_mode) {
12759 for (i = 0; i < 3; i++) {
12762 *p++ = permuser[i];
12764 for (j = 0; j < 3; j++) {
12765 if ((mask & permmask[3 * i + j]) == 0) {
12766 *p++ = permmode[j];
12774 out1fmt("%.4o\n", mask);
12777 if (isdigit((unsigned char) *ap)) {
12780 if (*ap >= '8' || *ap < '0')
12781 ash_msg_and_raise_error(msg_illnum, argv[1]);
12782 mask = (mask << 3) + (*ap - '0');
12783 } while (*++ap != '\0');
12786 mask = ~mask & 0777;
12787 if (!bb_parse_mode(ap, &mask)) {
12788 ash_msg_and_raise_error("illegal mode: %s", ap);
12790 umask(~mask & 0777);
12796 static int FAST_FUNC
12797 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12799 return shell_builtin_ulimit(argv);
12802 /* ============ main() and helpers */
12805 * Called to exit the shell.
12807 static void exitshell(void) NORETURN;
12815 status = exitstatus;
12816 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12817 if (setjmp(loc.loc)) {
12818 if (exception_type == EXEXIT)
12819 /* dash bug: it just does _exit(exitstatus) here
12820 * but we have to do setjobctl(0) first!
12821 * (bug is still not fixed in dash-0.5.3 - if you run dash
12822 * under Midnight Commander, on exit from dash MC is backgrounded) */
12823 status = exitstatus;
12826 exception_handler = &loc;
12833 flush_stdout_stderr();
12843 /* from input.c: */
12844 /* we will never free this */
12845 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12848 signal(SIGCHLD, SIG_DFL);
12849 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12850 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12852 signal(SIGHUP, SIG_DFL);
12858 struct stat st1, st2;
12861 for (envp = environ; envp && *envp; envp++) {
12862 if (strchr(*envp, '=')) {
12863 setvareq(*envp, VEXPORT|VTEXTFIXED);
12867 setvar("PPID", utoa(getppid()), 0);
12869 p = lookupvar("PWD");
12871 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12872 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12879 * Process the shell command line arguments.
12882 procargs(char **argv)
12885 const char *xminusc;
12890 /* if (xargv[0]) - mmm, this is always true! */
12892 for (i = 0; i < NOPTS; i++)
12896 /* it already printed err message */
12897 raise_exception(EXERROR);
12901 if (*xargv == NULL) {
12903 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12906 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12910 for (i = 0; i < NOPTS; i++)
12911 if (optlist[i] == 2)
12916 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12921 } else if (!sflag) {
12922 setinputfile(*xargv, 0);
12925 commandname = arg0;
12928 shellparam.p = xargv;
12929 #if ENABLE_ASH_GETOPTS
12930 shellparam.optind = 1;
12931 shellparam.optoff = -1;
12933 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12935 shellparam.nparam++;
12942 * Read /etc/profile or .profile.
12945 read_profile(const char *name)
12949 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12958 * This routine is called when an error or an interrupt occurs in an
12959 * interactive shell and control is returned to the main command loop.
12967 /* from input.c: */
12968 g_parsefile->left_in_buffer = 0;
12969 g_parsefile->left_in_line = 0; /* clear input buffer */
12971 /* from parser.c: */
12974 /* from redir.c: */
12975 clearredir(/*drop:*/ 0);
12979 static short profile_buf[16384];
12980 extern int etext();
12984 * Main routine. We initialize things, parse the arguments, execute
12985 * profiles if we're a login shell, and then call cmdloop to execute
12986 * commands. The setjmp call sets up the location to jump to when an
12987 * exception occurs. When an exception occurs the variable "state"
12988 * is used to figure out how far we had gotten.
12990 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12991 int ash_main(int argc UNUSED_PARAM, char **argv)
12993 const char *shinit;
12994 volatile smallint state;
12995 struct jmploc jmploc;
12996 struct stackmark smark;
12998 /* Initialize global data */
13002 #if ENABLE_ASH_ALIAS
13008 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13011 #if ENABLE_FEATURE_EDITING
13012 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13015 if (setjmp(jmploc.loc)) {
13021 e = exception_type;
13025 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13029 outcslow('\n', stderr);
13032 popstackmark(&smark);
13033 FORCE_INT_ON; /* enable interrupts */
13042 exception_handler = &jmploc;
13045 TRACE(("Shell args: "));
13046 trace_puts_args(argv);
13048 rootpid = getpid();
13051 setstackmark(&smark);
13054 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13056 const char *hp = lookupvar("HISTFILE");
13059 hp = lookupvar("HOME");
13061 char *defhp = concat_path_file(hp, ".ash_history");
13062 setvar("HISTFILE", defhp, 0);
13068 if (argv[0] && argv[0][0] == '-')
13072 read_profile("/etc/profile");
13075 read_profile(".profile");
13081 getuid() == geteuid() && getgid() == getegid() &&
13085 shinit = lookupvar("ENV");
13086 if (shinit != NULL && *shinit != '\0') {
13087 read_profile(shinit);
13093 /* evalstring pushes parsefile stack.
13094 * Ensure we don't falsely claim that 0 (stdin)
13095 * is one of stacked source fds.
13096 * Testcase: ash -c 'exec 1>&0' must not complain. */
13097 // if (!sflag) g_parsefile->pf_fd = -1;
13098 // ^^ not necessary since now we special-case fd 0
13099 // in is_hidden_fd() to not be considered "hidden fd"
13100 evalstring(minusc, 0);
13103 if (sflag || minusc == NULL) {
13104 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13106 const char *hp = lookupvar("HISTFILE");
13108 line_input_state->hist_file = hp;
13111 state4: /* XXX ??? - why isn't this before the "if" statement */
13119 extern void _mcleanup(void);
13123 TRACE(("End of main reached\n"));
13130 * Copyright (c) 1989, 1991, 1993, 1994
13131 * The Regents of the University of California. All rights reserved.
13133 * This code is derived from software contributed to Berkeley by
13134 * Kenneth Almquist.
13136 * Redistribution and use in source and binary forms, with or without
13137 * modification, are permitted provided that the following conditions
13139 * 1. Redistributions of source code must retain the above copyright
13140 * notice, this list of conditions and the following disclaimer.
13141 * 2. Redistributions in binary form must reproduce the above copyright
13142 * notice, this list of conditions and the following disclaimer in the
13143 * documentation and/or other materials provided with the distribution.
13144 * 3. Neither the name of the University nor the names of its contributors
13145 * may be used to endorse or promote products derived from this software
13146 * without specific prior written permission.
13148 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13149 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13150 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13151 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13152 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13153 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13154 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13155 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13156 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13157 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF