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.
4947 #define EMPTY -2 /* marks an unused slot in redirtab */
4948 #define CLOSED -3 /* marks a slot of previously-closed fd */
4951 * Open a file in noclobber mode.
4952 * The code was copied from bash.
4955 noclobberopen(const char *fname)
4958 struct stat finfo, finfo2;
4961 * If the file exists and is a regular file, return an error
4964 r = stat(fname, &finfo);
4965 if (r == 0 && S_ISREG(finfo.st_mode)) {
4971 * If the file was not present (r != 0), make sure we open it
4972 * exclusively so that if it is created before we open it, our open
4973 * will fail. Make sure that we do not truncate an existing file.
4974 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4975 * file was not a regular file, we leave O_EXCL off.
4978 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4979 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4981 /* If the open failed, return the file descriptor right away. */
4986 * OK, the open succeeded, but the file may have been changed from a
4987 * non-regular file to a regular file between the stat and the open.
4988 * We are assuming that the O_EXCL open handles the case where FILENAME
4989 * did not exist and is symlinked to an existing file between the stat
4994 * If we can open it and fstat the file descriptor, and neither check
4995 * revealed that it was a regular file, and the file has not been
4996 * replaced, return the file descriptor.
4998 if (fstat(fd, &finfo2) == 0
4999 && !S_ISREG(finfo2.st_mode)
5000 && finfo.st_dev == finfo2.st_dev
5001 && finfo.st_ino == finfo2.st_ino
5006 /* The file has been replaced. badness. */
5013 * Handle here documents. Normally we fork off a process to write the
5014 * data to a pipe. If the document is short, we can stuff the data in
5015 * the pipe without forking.
5017 /* openhere needs this forward reference */
5018 static void expandhere(union node *arg, int fd);
5020 openhere(union node *redir)
5026 ash_msg_and_raise_error("pipe call failed");
5027 if (redir->type == NHERE) {
5028 len = strlen(redir->nhere.doc->narg.text);
5029 if (len <= PIPE_BUF) {
5030 full_write(pip[1], redir->nhere.doc->narg.text, len);
5034 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5037 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5038 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5039 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5040 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5041 signal(SIGPIPE, SIG_DFL);
5042 if (redir->type == NHERE)
5043 full_write(pip[1], redir->nhere.doc->narg.text, len);
5045 expandhere(redir->nhere.doc, pip[1]);
5046 _exit(EXIT_SUCCESS);
5054 openredirect(union node *redir)
5059 switch (redir->nfile.type) {
5061 fname = redir->nfile.expfname;
5062 f = open(fname, O_RDONLY);
5067 fname = redir->nfile.expfname;
5068 f = open(fname, O_RDWR|O_CREAT, 0666);
5073 #if ENABLE_ASH_BASH_COMPAT
5076 /* Take care of noclobber mode. */
5078 fname = redir->nfile.expfname;
5079 f = noclobberopen(fname);
5086 fname = redir->nfile.expfname;
5087 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5092 fname = redir->nfile.expfname;
5093 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5101 /* Fall through to eliminate warning. */
5102 /* Our single caller does this itself */
5109 f = openhere(redir);
5115 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5117 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5121 * Copy a file descriptor to be >= to. Returns -1
5122 * if the source file descriptor is closed, EMPTY if there are no unused
5123 * file descriptors left.
5125 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5126 * old code was doing close(to) prior to copyfd() to achieve the same */
5128 COPYFD_EXACT = (int)~(INT_MAX),
5129 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5132 copyfd(int from, int to)
5136 if (to & COPYFD_EXACT) {
5137 to &= ~COPYFD_EXACT;
5139 newfd = dup2(from, to);
5141 newfd = fcntl(from, F_DUPFD, to);
5144 if (errno == EMFILE)
5146 /* Happens when source fd is not open: try "echo >&99" */
5147 ash_msg_and_raise_error("%d: %m", from);
5152 /* Struct def and variable are moved down to the first usage site */
5157 struct redirtab *next;
5160 struct two_fd_t two_fd[];
5162 #define redirlist (G_var.redirlist)
5164 static int need_to_remember(struct redirtab *rp, int fd)
5168 if (!rp) /* remembering was not requested */
5171 for (i = 0; i < rp->pair_count; i++) {
5172 if (rp->two_fd[i].orig == fd) {
5173 /* already remembered */
5180 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5181 static int is_hidden_fd(struct redirtab *rp, int fd)
5184 struct parsefile *pf;
5188 /* Check open scripts' fds */
5191 /* We skip pf_fd == 0 case because of the following case:
5192 * $ ash # running ash interactively
5194 * and in script.sh: "exec 9>&0".
5195 * Even though top-level pf_fd _is_ 0,
5196 * it's still ok to use it: "read" builtin uses it,
5197 * why should we cripple "exec" builtin?
5199 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5207 /* Check saved fds of redirects */
5208 fd |= COPYFD_RESTORE;
5209 for (i = 0; i < rp->pair_count; i++) {
5210 if (rp->two_fd[i].copy == fd) {
5218 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5219 * old file descriptors are stashed away so that the redirection can be
5220 * undone by calling popredir.
5222 /* flags passed to redirect */
5223 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5224 #define REDIR_SAVEFD2 03 /* set preverrout */
5226 redirect(union node *redir, int flags)
5228 struct redirtab *sv;
5233 int copied_fd2 = -1;
5243 if (flags & REDIR_PUSH) {
5244 union node *tmp = redir;
5247 #if ENABLE_ASH_BASH_COMPAT
5248 if (tmp->nfile.type == NTO2)
5251 tmp = tmp->nfile.next;
5253 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5254 sv->next = redirlist;
5255 sv->pair_count = sv_pos;
5257 sv->nullredirs = g_nullredirs - 1;
5259 while (sv_pos > 0) {
5261 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5267 fd = redir->nfile.fd;
5268 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5269 right_fd = redir->ndup.dupfd;
5270 //bb_error_msg("doing %d > %d", fd, right_fd);
5271 /* redirect from/to same file descriptor? */
5274 /* "echo >&10" and 10 is a fd opened to a sh script? */
5275 if (is_hidden_fd(sv, right_fd)) {
5276 errno = EBADF; /* as if it is closed */
5277 ash_msg_and_raise_error("%d: %m", right_fd);
5281 newfd = openredirect(redir); /* always >= 0 */
5283 /* Descriptor wasn't open before redirect.
5284 * Mark it for close in the future */
5285 if (need_to_remember(sv, fd)) {
5286 goto remember_to_close;
5291 #if ENABLE_ASH_BASH_COMPAT
5294 if (need_to_remember(sv, fd)) {
5295 /* Copy old descriptor */
5296 /* Careful to not accidentally "save"
5297 * to the same fd as right side fd in N>&M */
5298 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5299 i = fcntl(fd, F_DUPFD, minfd);
5300 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5301 * are closed in popredir() in the child, preventing them from leaking
5302 * into child. (popredir() also cleans up the mess in case of failures)
5307 /* Strange error (e.g. "too many files" EMFILE?) */
5311 ash_msg_and_raise_error("%d: %m", fd);
5314 /* EBADF: it is not open - good, remember to close it */
5317 } else { /* fd is open, save its copy */
5318 /* "exec fd>&-" should not close fds
5319 * which point to script file(s).
5320 * Force them to be restored afterwards */
5321 if (is_hidden_fd(sv, fd))
5322 i |= COPYFD_RESTORE;
5326 sv->two_fd[sv_pos].orig = fd;
5327 sv->two_fd[sv_pos].copy = i;
5331 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5332 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5333 /* Don't want to trigger debugging */
5337 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5339 } else if (fd != newfd) { /* move newfd to fd */
5340 copyfd(newfd, fd | COPYFD_EXACT);
5341 #if ENABLE_ASH_BASH_COMPAT
5342 if (!(redir->nfile.type == NTO2 && fd == 2))
5346 #if ENABLE_ASH_BASH_COMPAT
5347 if (redir->nfile.type == NTO2 && fd == 1) {
5348 /* We already redirected it to fd 1, now copy it to 2 */
5354 } while ((redir = redir->nfile.next) != NULL);
5357 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5358 preverrout_fd = copied_fd2;
5362 * Undo the effects of the last redirection.
5365 popredir(int drop, int restore)
5367 struct redirtab *rp;
5370 if (--g_nullredirs >= 0)
5374 for (i = 0; i < rp->pair_count; i++) {
5375 int fd = rp->two_fd[i].orig;
5376 int copy = rp->two_fd[i].copy;
5377 if (copy == CLOSED) {
5382 if (copy != EMPTY) {
5383 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5384 copy &= ~COPYFD_RESTORE;
5386 copyfd(copy, fd | COPYFD_EXACT);
5388 close(copy & ~COPYFD_RESTORE);
5391 redirlist = rp->next;
5392 g_nullredirs = rp->nullredirs;
5398 * Undo all redirections. Called on error or interrupt.
5402 * Discard all saved file descriptors.
5405 clearredir(int drop)
5411 popredir(drop, /*restore:*/ 0);
5416 redirectsafe(union node *redir, int flags)
5419 volatile int saveint;
5420 struct jmploc *volatile savehandler = exception_handler;
5421 struct jmploc jmploc;
5424 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5425 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5427 exception_handler = &jmploc;
5428 redirect(redir, flags);
5430 exception_handler = savehandler;
5431 if (err && exception_type != EXERROR)
5432 longjmp(exception_handler->loc, 1);
5433 RESTORE_INT(saveint);
5438 /* ============ Routines to expand arguments to commands
5440 * We have to deal with backquotes, shell variables, and file metacharacters.
5443 #if ENABLE_SH_MATH_SUPPORT
5445 ash_arith(const char *s)
5447 arith_state_t math_state;
5450 math_state.lookupvar = lookupvar;
5451 math_state.setvar = setvar2;
5452 //math_state.endofname = endofname;
5455 result = arith(&math_state, s);
5456 if (math_state.errmsg)
5457 ash_msg_and_raise_error(math_state.errmsg);
5467 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5468 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5469 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5470 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5471 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5472 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5473 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5474 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5475 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5479 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5480 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5481 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5482 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5483 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5486 * Structure specifying which parts of the string should be searched
5487 * for IFS characters.
5490 struct ifsregion *next; /* next region in list */
5491 int begoff; /* offset of start of region */
5492 int endoff; /* offset of end of region */
5493 int nulonly; /* search for nul bytes only */
5497 struct strlist *list;
5498 struct strlist **lastp;
5501 /* output of current string */
5502 static char *expdest;
5503 /* list of back quote expressions */
5504 static struct nodelist *argbackq;
5505 /* first struct in list of ifs regions */
5506 static struct ifsregion ifsfirst;
5507 /* last struct in list */
5508 static struct ifsregion *ifslastp;
5509 /* holds expanded arg list */
5510 static struct arglist exparg;
5515 #if !ENABLE_SH_MATH_SUPPORT
5516 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5517 typedef long arith_t;
5518 # define ARITH_FMT "%ld"
5525 expdest = makestrspace(32, expdest);
5526 len = fmtstr(expdest, 32, ARITH_FMT, num);
5527 STADJUST(len, expdest);
5532 esclen(const char *start, const char *p)
5536 while (p > start && (unsigned char)*--p == CTLESC) {
5543 * Remove any CTLESC characters from a string.
5546 rmescapes(char *str, int flag)
5548 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5552 unsigned protect_against_glob;
5555 p = strpbrk(str, qchars);
5561 if (flag & RMESCAPE_ALLOC) {
5562 size_t len = p - str;
5563 size_t fulllen = len + strlen(p) + 1;
5565 if (flag & RMESCAPE_GROW) {
5566 int strloc = str - (char *)stackblock();
5567 r = makestrspace(fulllen, expdest);
5568 /* p and str may be invalidated by makestrspace */
5569 str = (char *)stackblock() + strloc;
5571 } else if (flag & RMESCAPE_HEAP) {
5572 r = ckmalloc(fulllen);
5574 r = stalloc(fulllen);
5578 q = (char *)memcpy(q, str, len) + len;
5582 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5583 globbing = flag & RMESCAPE_GLOB;
5584 protect_against_glob = globbing;
5586 if ((unsigned char)*p == CTLQUOTEMARK) {
5587 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5588 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5589 // Note: both inquotes and protect_against_glob only affect whether
5590 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5591 inquotes = ~inquotes;
5593 protect_against_glob = globbing;
5597 /* naked back slash */
5598 protect_against_glob = 0;
5601 if ((unsigned char)*p == CTLESC) {
5603 if (protect_against_glob && inquotes && *p != '/') {
5607 protect_against_glob = globbing;
5612 if (flag & RMESCAPE_GROW) {
5614 STADJUST(q - r + 1, expdest);
5618 #define pmatch(a, b) !fnmatch((a), (b), 0)
5621 * Prepare a pattern for a expmeta (internal glob(3)) call.
5623 * Returns an stalloced string.
5626 preglob(const char *pattern, int quoted, int flag)
5628 flag |= RMESCAPE_GLOB;
5630 flag |= RMESCAPE_QUOTED;
5632 return rmescapes((char *)pattern, flag);
5636 * Put a string on the stack.
5639 memtodest(const char *p, size_t len, int syntax, int quotes)
5643 q = makestrspace(quotes ? len * 2 : len, q);
5646 unsigned char c = *p++;
5650 int n = SIT(c, syntax);
5651 if (n == CCTL || n == CBACK)
5661 strtodest(const char *p, int syntax, int quotes)
5663 memtodest(p, strlen(p), syntax, quotes);
5667 * Record the fact that we have to scan this region of the
5668 * string for IFS characters.
5671 recordregion(int start, int end, int nulonly)
5673 struct ifsregion *ifsp;
5675 if (ifslastp == NULL) {
5679 ifsp = ckzalloc(sizeof(*ifsp));
5680 /*ifsp->next = NULL; - ckzalloc did it */
5681 ifslastp->next = ifsp;
5685 ifslastp->begoff = start;
5686 ifslastp->endoff = end;
5687 ifslastp->nulonly = nulonly;
5691 removerecordregions(int endoff)
5693 if (ifslastp == NULL)
5696 if (ifsfirst.endoff > endoff) {
5697 while (ifsfirst.next) {
5698 struct ifsregion *ifsp;
5700 ifsp = ifsfirst.next->next;
5701 free(ifsfirst.next);
5702 ifsfirst.next = ifsp;
5705 if (ifsfirst.begoff > endoff) {
5708 ifslastp = &ifsfirst;
5709 ifsfirst.endoff = endoff;
5714 ifslastp = &ifsfirst;
5715 while (ifslastp->next && ifslastp->next->begoff < endoff)
5716 ifslastp = ifslastp->next;
5717 while (ifslastp->next) {
5718 struct ifsregion *ifsp;
5720 ifsp = ifslastp->next->next;
5721 free(ifslastp->next);
5722 ifslastp->next = ifsp;
5725 if (ifslastp->endoff > endoff)
5726 ifslastp->endoff = endoff;
5730 exptilde(char *startp, char *p, int flags)
5736 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5741 while ((c = *++p) != '\0') {
5748 if (flags & EXP_VARTILDE)
5758 if (*name == '\0') {
5759 home = lookupvar("HOME");
5761 pw = getpwnam(name);
5766 if (!home || !*home)
5769 startloc = expdest - (char *)stackblock();
5770 strtodest(home, SQSYNTAX, quotes);
5771 recordregion(startloc, expdest - (char *)stackblock(), 0);
5779 * Execute a command inside back quotes. If it's a builtin command, we
5780 * want to save its output in a block obtained from malloc. Otherwise
5781 * we fork off a subprocess and get the output of the command via a pipe.
5782 * Should be called with interrupts off.
5784 struct backcmd { /* result of evalbackcmd */
5785 int fd; /* file descriptor to read from */
5786 int nleft; /* number of chars in buffer */
5787 char *buf; /* buffer */
5788 struct job *jp; /* job structure for command */
5791 /* These forward decls are needed to use "eval" code for backticks handling: */
5792 static uint8_t back_exitstatus; /* exit status of backquoted command */
5793 #define EV_EXIT 01 /* exit after evaluating tree */
5794 static void evaltree(union node *, int);
5796 static void FAST_FUNC
5797 evalbackcmd(union node *n, struct backcmd *result)
5808 saveherefd = herefd;
5816 ash_msg_and_raise_error("pipe call failed");
5817 jp = makejob(/*n,*/ 1);
5818 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5823 copyfd(pip[1], 1 | COPYFD_EXACT);
5827 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5831 result->fd = pip[0];
5834 herefd = saveherefd;
5836 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5837 result->fd, result->buf, result->nleft, result->jp));
5841 * Expand stuff in backwards quotes.
5844 expbackq(union node *cmd, int quoted, int quotes)
5852 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5853 struct stackmark smark;
5856 setstackmark(&smark);
5858 startloc = dest - (char *)stackblock();
5860 evalbackcmd(cmd, &in);
5861 popstackmark(&smark);
5868 memtodest(p, i, syntax, quotes);
5872 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5873 TRACE(("expbackq: read returns %d\n", i));
5882 back_exitstatus = waitforjob(in.jp);
5886 /* Eat all trailing newlines */
5888 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5893 recordregion(startloc, dest - (char *)stackblock(), 0);
5894 TRACE(("evalbackq: size:%d:'%.*s'\n",
5895 (int)((dest - (char *)stackblock()) - startloc),
5896 (int)((dest - (char *)stackblock()) - startloc),
5897 stackblock() + startloc));
5900 #if ENABLE_SH_MATH_SUPPORT
5902 * Expand arithmetic expression. Backup to start of expression,
5903 * evaluate, place result in (backed up) result, adjust string position.
5916 * This routine is slightly over-complicated for
5917 * efficiency. Next we scan backwards looking for the
5918 * start of arithmetic.
5920 start = stackblock();
5927 while ((unsigned char)*p != CTLARI) {
5931 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5936 esc = esclen(start, p);
5946 removerecordregions(begoff);
5953 rmescapes(p + 2, 0);
5955 len = cvtnum(ash_arith(p + 2));
5958 recordregion(begoff, begoff + len, 0);
5962 /* argstr needs it */
5963 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5966 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5967 * characters to allow for further processing. Otherwise treat
5968 * $@ like $* since no splitting will be performed.
5970 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5971 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5972 * for correct expansion of "B=$A" word.
5975 argstr(char *p, int flags, struct strlist *var_str_list)
5977 static const char spclchars[] ALIGN1 = {
5985 CTLBACKQ | CTLQUOTE,
5986 #if ENABLE_SH_MATH_SUPPORT
5991 const char *reject = spclchars;
5992 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5993 int breakall = flags & EXP_WORD;
5998 if (!(flags & EXP_VARTILDE)) {
6000 } else if (flags & EXP_VARTILDE2) {
6005 if (flags & EXP_TILDE) {
6008 flags &= ~EXP_TILDE;
6011 if ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
6014 p = exptilde(p, q, flags);
6017 startloc = expdest - (char *)stackblock();
6021 length += strcspn(p + length, reject);
6025 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6027 /* c == '=' || c == ':' || c == CTLENDARI */
6033 expdest = stack_nputstr(p, length, expdest);
6034 newloc = expdest - (char *)stackblock();
6035 if (breakall && !inquotes && newloc > startloc) {
6036 recordregion(startloc, newloc, 0);
6047 if (flags & EXP_VARTILDE2) {
6051 flags |= EXP_VARTILDE2;
6056 * sort of a hack - expand tildes in variable
6057 * assignments (after the first '=' and after ':'s).
6066 case CTLENDVAR: /* ??? */
6069 /* "$@" syntax adherence hack */
6071 && memcmp(p, dolatstr, 4) == 0
6072 && ( p[4] == (char)CTLQUOTEMARK
6073 || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
6076 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
6079 inquotes = !inquotes;
6092 p = evalvar(p, flags, var_str_list);
6096 case CTLBACKQ|CTLQUOTE:
6097 expbackq(argbackq->n, c, quotes);
6098 argbackq = argbackq->next;
6100 #if ENABLE_SH_MATH_SUPPORT
6112 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6113 char *pattern, int quotes, int zero)
6122 const char *s = loc2;
6129 match = pmatch(pattern, s);
6134 if (quotes && (unsigned char)*loc == CTLESC)
6143 scanright(char *startp, char *rmesc, char *rmescend,
6144 char *pattern, int quotes, int match_at_start)
6146 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6147 int try2optimize = match_at_start;
6153 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6154 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6155 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6157 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6158 * and on each iteration they go back two/one char until they reach the beginning.
6159 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6161 /* TODO: document in what other circumstances we are called. */
6163 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6166 const char *s = loc2;
6167 if (match_at_start) {
6171 match = pmatch(pattern, s);
6172 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6176 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6178 /* Maybe we can optimize this:
6179 * if pattern ends with unescaped *, we can avoid checking
6180 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6181 * it wont match truncated "raw_value_of_" strings too.
6183 unsigned plen = strlen(pattern);
6184 /* Does it end with "*"? */
6185 if (plen != 0 && pattern[--plen] == '*') {
6186 /* "xxxx*" is not escaped */
6187 /* "xxx\*" is escaped */
6188 /* "xx\\*" is not escaped */
6189 /* "x\\\*" is escaped */
6191 while (plen != 0 && pattern[--plen] == '\\')
6194 break; /* ends with unescaped "*" */
6202 esc = esclen(startp, loc);
6213 static void varunset(const char *, const char *, const char *, int) NORETURN;
6215 varunset(const char *end, const char *var, const char *umsg, int varflags)
6221 msg = "parameter not set";
6223 if ((unsigned char)*end == CTLENDVAR) {
6224 if (varflags & VSNUL)
6230 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6233 #if ENABLE_ASH_BASH_COMPAT
6235 parse_sub_pattern(char *arg, int varflags)
6237 char *idx, *repl = NULL;
6240 //char *org_arg = arg;
6241 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
6248 /* Only the first '/' seen is our separator */
6257 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6258 * The result is a_\_z_c (not a\_\_z_c)!
6260 * Enable debug prints in this function and you'll see:
6261 * ash: arg:'\\b/_\\_z_' varflags:d
6262 * ash: pattern:'\\b' repl:'_\_z_'
6263 * That is, \\b is interpreted as \\b, but \\_ as \_!
6264 * IOW: search pattern and replace string treat backslashes
6265 * differently! That is the reason why we check repl below:
6267 if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
6268 arg++; /* skip both '\', not just first one */
6271 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
6275 #endif /* ENABLE_ASH_BASH_COMPAT */
6278 subevalvar(char *p, char *varname, int strloc, int subtype,
6279 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6281 struct nodelist *saveargbackq = argbackq;
6284 char *rmesc, *rmescend;
6286 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
6287 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6288 int saveherefd = herefd;
6289 int amount, workloc, resetloc;
6291 char *(*scan)(char*, char*, char*, char*, int, int);
6293 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6294 // p, varname, strloc, subtype, startloc, varflags, quotes);
6297 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6299 STPUTC('\0', expdest);
6300 herefd = saveherefd;
6301 argbackq = saveargbackq;
6302 startp = (char *)stackblock() + startloc;
6306 setvar(varname, startp, 0);
6307 amount = startp - expdest;
6308 STADJUST(amount, expdest);
6312 varunset(p, varname, startp, varflags);
6315 #if ENABLE_ASH_BASH_COMPAT
6317 loc = str = stackblock() + strloc;
6318 /* Read POS in ${var:POS:LEN} */
6319 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6320 len = str - startp - 1;
6322 /* *loc != '\0', guaranteed by parser */
6326 /* Adjust the length by the number of escapes */
6327 for (ptr = startp; ptr < (str - 1); ptr++) {
6328 if ((unsigned char)*ptr == CTLESC) {
6336 if (*loc++ == ':') {
6340 /* Skip POS in ${var:POS:LEN} */
6342 while (*loc && *loc != ':') {
6344 * bash complains on: var=qwe; echo ${var:1a:123}
6346 ash_msg_and_raise_error(msg_illnum, str);
6350 if (*loc++ == ':') {
6354 if (pos >= orig_len) {
6358 if (len > (orig_len - pos))
6359 len = orig_len - pos;
6361 for (str = startp; pos; str++, pos--) {
6362 if (quotes && (unsigned char)*str == CTLESC)
6365 for (loc = startp; len; len--) {
6366 if (quotes && (unsigned char)*str == CTLESC)
6371 amount = loc - expdest;
6372 STADJUST(amount, expdest);
6377 resetloc = expdest - (char *)stackblock();
6379 /* We'll comeback here if we grow the stack while handling
6380 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6381 * stack will need rebasing, and we'll need to remove our work
6384 IF_ASH_BASH_COMPAT(restart:)
6386 amount = expdest - ((char *)stackblock() + resetloc);
6387 STADJUST(-amount, expdest);
6388 startp = (char *)stackblock() + startloc;
6391 rmescend = (char *)stackblock() + strloc;
6393 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6394 if (rmesc != startp) {
6396 startp = (char *)stackblock() + startloc;
6400 str = (char *)stackblock() + strloc;
6401 preglob(str, varflags & VSQUOTE, 0);
6402 workloc = expdest - (char *)stackblock();
6404 #if ENABLE_ASH_BASH_COMPAT
6405 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6409 repl = parse_sub_pattern(str, varflags);
6410 //bb_error_msg("repl:'%s'", repl);
6415 /* If there's no pattern to match, return the expansion unmolested */
6424 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6425 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6427 /* No match, advance */
6428 char *restart_detect = stackblock();
6430 STPUTC(*idx, expdest);
6431 if (quotes && (unsigned char)*idx == CTLESC) {
6434 STPUTC(*idx, expdest);
6436 if (stackblock() != restart_detect)
6441 /* continue; - prone to quadratic behavior, smarter code: */
6444 if (str[0] == '*') {
6445 /* Pattern is "*foo". If "*foo" does not match "long_string",
6446 * it would never match "ong_string" etc, no point in trying.
6453 if (subtype == VSREPLACEALL) {
6455 if (quotes && (unsigned char)*idx == CTLESC)
6464 //bb_error_msg("repl:'%s'", repl);
6465 for (loc = (char*)repl; *loc; loc++) {
6466 char *restart_detect = stackblock();
6467 if (quotes && *loc == '\\') {
6468 STPUTC(CTLESC, expdest);
6471 STPUTC(*loc, expdest);
6472 if (stackblock() != restart_detect)
6477 if (subtype == VSREPLACE) {
6478 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6480 char *restart_detect = stackblock();
6481 STPUTC(*idx, expdest);
6482 if (stackblock() != restart_detect)
6491 /* We've put the replaced text into a buffer at workloc, now
6492 * move it to the right place and adjust the stack.
6494 STPUTC('\0', expdest);
6495 startp = (char *)stackblock() + startloc;
6496 memmove(startp, (char *)stackblock() + workloc, len + 1);
6497 //bb_error_msg("startp:'%s'", startp);
6498 amount = expdest - (startp + len);
6499 STADJUST(-amount, expdest);
6502 #endif /* ENABLE_ASH_BASH_COMPAT */
6504 subtype -= VSTRIMRIGHT;
6506 if (subtype < 0 || subtype > 7)
6509 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6510 zero = subtype >> 1;
6511 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6512 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6514 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6517 memmove(startp, loc, str - loc);
6518 loc = startp + (str - loc) - 1;
6521 amount = loc - expdest;
6522 STADJUST(amount, expdest);
6528 * Add the value of a specialized variable to the stack string.
6529 * name parameter (examples):
6530 * ash -c 'echo $1' name:'1='
6531 * ash -c 'echo $qwe' name:'qwe='
6532 * ash -c 'echo $$' name:'$='
6533 * ash -c 'echo ${$}' name:'$='
6534 * ash -c 'echo ${$##q}' name:'$=q'
6535 * ash -c 'echo ${#$}' name:'$='
6536 * note: examples with bad shell syntax:
6537 * ash -c 'echo ${#$1}' name:'$=1'
6538 * ash -c 'echo ${#1#}' name:'1=#'
6540 static NOINLINE ssize_t
6541 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6548 int subtype = varflags & VSTYPE;
6549 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6550 int quoted = varflags & VSQUOTE;
6551 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6561 num = shellparam.nparam;
6569 goto check_1char_name;
6571 expdest = makestrspace(NOPTS, expdest);
6572 for (i = NOPTS - 1; i >= 0; i--) {
6574 USTPUTC(optletters(i), expdest);
6580 /* handles cases similar to ${#$1} */
6581 if (name[2] != '\0')
6582 raise_error_syntax("bad substitution");
6589 if (quoted && (flags & EXP_FULL)) {
6590 /* note: this is not meant as PEOF value */
6591 sep = 1 << CHAR_BIT;
6596 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6597 i = SIT(sep, syntax);
6598 if (quotes && (i == CCTL || i == CBACK))
6604 while ((p = *ap++) != NULL) {
6607 partlen = strlen(p);
6610 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6611 memtodest(p, partlen, syntax, quotes);
6617 if (subtype == VSPLUS || subtype == VSLENGTH) {
6623 /* note: may put NUL despite sep != 0
6624 * (see sep = 1 << CHAR_BIT above) */
6630 } /* case '@' and '*' */
6641 num = atoi(name); /* number(name) fails on ${N#str} etc */
6642 if (num < 0 || num > shellparam.nparam)
6644 p = num ? shellparam.p[num - 1] : arg0;
6647 /* NB: name has form "VAR=..." */
6649 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6650 * which should be considered before we check variables. */
6652 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6656 str = var_str_list->text;
6657 eq = strchr(str, '=');
6658 if (!eq) /* stop at first non-assignment */
6661 if (name_len == (unsigned)(eq - str)
6662 && strncmp(str, name, name_len) == 0
6665 /* goto value; - WRONG! */
6666 /* think "A=1 A=2 B=$A" */
6668 var_str_list = var_str_list->next;
6669 } while (var_str_list);
6673 p = lookupvar(name);
6679 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6680 memtodest(p, len, syntax, quotes);
6684 if (subtype == VSPLUS || subtype == VSLENGTH)
6685 STADJUST(-len, expdest);
6690 * Expand a variable, and return a pointer to the next character in the
6694 evalvar(char *p, int flags, struct strlist *var_str_list)
6705 varflags = (unsigned char) *p++;
6706 subtype = varflags & VSTYPE;
6707 quoted = varflags & VSQUOTE;
6709 easy = (!quoted || (*var == '@' && shellparam.nparam));
6710 startloc = expdest - (char *)stackblock();
6711 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6714 varlen = varvalue(var, varflags, flags, var_str_list);
6715 if (varflags & VSNUL)
6718 if (subtype == VSPLUS) {
6719 varlen = -1 - varlen;
6723 if (subtype == VSMINUS) {
6728 flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
6738 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6740 if (subevalvar(p, var, /* strloc: */ 0,
6741 subtype, startloc, varflags,
6747 * Remove any recorded regions beyond
6750 removerecordregions(startloc);
6760 if (varlen < 0 && uflag)
6761 varunset(p, var, 0, 0);
6763 if (subtype == VSLENGTH) {
6764 cvtnum(varlen > 0 ? varlen : 0);
6768 if (subtype == VSNORMAL) {
6779 case VSTRIMRIGHTMAX:
6780 #if ENABLE_ASH_BASH_COMPAT
6793 * Terminate the string and start recording the pattern
6796 STPUTC('\0', expdest);
6797 patloc = expdest - (char *)stackblock();
6798 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6800 //TODO: | EXP_REDIR too? All other such places do it too
6801 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6804 int amount = expdest - (
6805 (char *)stackblock() + patloc - 1
6807 STADJUST(-amount, expdest);
6809 /* Remove any recorded regions beyond start of variable */
6810 removerecordregions(startloc);
6812 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6816 if (subtype != VSNORMAL) { /* skip to end of alternative */
6819 unsigned char c = *p++;
6822 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6824 argbackq = argbackq->next;
6825 } else if (c == CTLVAR) {
6826 if ((*p++ & VSTYPE) != VSNORMAL)
6828 } else if (c == CTLENDVAR) {
6838 * Break the argument string into pieces based upon IFS and add the
6839 * strings to the argument list. The regions of the string to be
6840 * searched for IFS characters have been stored by recordregion.
6843 ifsbreakup(char *string, struct arglist *arglist)
6845 struct ifsregion *ifsp;
6850 const char *ifs, *realifs;
6855 if (ifslastp != NULL) {
6858 realifs = ifsset() ? ifsval() : defifs;
6861 p = string + ifsp->begoff;
6862 nulonly = ifsp->nulonly;
6863 ifs = nulonly ? nullstr : realifs;
6865 while (p < string + ifsp->endoff) {
6867 if ((unsigned char)*p == CTLESC)
6869 if (!strchr(ifs, *p)) {
6874 ifsspc = (strchr(defifs, *p) != NULL);
6875 /* Ignore IFS whitespace at start */
6876 if (q == start && ifsspc) {
6882 sp = stzalloc(sizeof(*sp));
6884 *arglist->lastp = sp;
6885 arglist->lastp = &sp->next;
6889 if (p >= string + ifsp->endoff) {
6893 if ((unsigned char)*p == CTLESC)
6895 if (strchr(ifs, *p) == NULL) {
6899 if (strchr(defifs, *p) == NULL) {
6914 } while (ifsp != NULL);
6923 sp = stzalloc(sizeof(*sp));
6925 *arglist->lastp = sp;
6926 arglist->lastp = &sp->next;
6932 struct ifsregion *p;
6937 struct ifsregion *ifsp;
6943 ifsfirst.next = NULL;
6948 * Add a file name to the list.
6951 addfname(const char *name)
6955 sp = stzalloc(sizeof(*sp));
6956 sp->text = ststrdup(name);
6958 exparg.lastp = &sp->next;
6962 * Do metacharacter (i.e. *, ?, [...]) expansion.
6965 expmeta(char *expdir, char *enddir, char *name)
6980 for (p = name; *p; p++) {
6981 if (*p == '*' || *p == '?')
6983 else if (*p == '[') {
6990 if (*q == '/' || *q == '\0')
6997 } else if (*p == '\\')
6999 else if (*p == '/') {
7006 if (metaflag == 0) { /* we've reached the end of the file name */
7007 if (enddir != expdir)
7015 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7026 } while (p < start);
7028 if (enddir == expdir) {
7030 } else if (enddir == expdir + 1 && *expdir == '/') {
7039 if (enddir != expdir)
7041 if (*endname == 0) {
7053 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7054 if (dp->d_name[0] == '.' && !matchdot)
7056 if (pmatch(start, dp->d_name)) {
7058 strcpy(enddir, dp->d_name);
7061 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7064 expmeta(expdir, p, endname);
7073 static struct strlist *
7074 msort(struct strlist *list, int len)
7076 struct strlist *p, *q = NULL;
7077 struct strlist **lpp;
7085 for (n = half; --n >= 0;) {
7089 q->next = NULL; /* terminate first half of list */
7090 q = msort(list, half); /* sort first half of list */
7091 p = msort(p, len - half); /* sort second half */
7094 #if ENABLE_LOCALE_SUPPORT
7095 if (strcoll(p->text, q->text) < 0)
7097 if (strcmp(p->text, q->text) < 0)
7121 * Sort the results of file name expansion. It calculates the number of
7122 * strings to sort and then calls msort (short for merge sort) to do the
7125 static struct strlist *
7126 expsort(struct strlist *str)
7132 for (sp = str; sp; sp = sp->next)
7134 return msort(str, len);
7138 expandmeta(struct strlist *str /*, int flag*/)
7140 static const char metachars[] ALIGN1 = {
7143 /* TODO - EXP_REDIR */
7147 struct strlist **savelastp;
7153 if (!strpbrk(str->text, metachars))
7155 savelastp = exparg.lastp;
7158 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7160 int i = strlen(str->text);
7161 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7163 expmeta(expdir, expdir, p);
7168 if (exparg.lastp == savelastp) {
7173 *exparg.lastp = str;
7174 rmescapes(str->text, 0);
7175 exparg.lastp = &str->next;
7177 *exparg.lastp = NULL;
7178 *savelastp = sp = expsort(*savelastp);
7179 while (sp->next != NULL)
7181 exparg.lastp = &sp->next;
7188 * Perform variable substitution and command substitution on an argument,
7189 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7190 * perform splitting and file name expansion. When arglist is NULL, perform
7191 * here document expansion.
7194 expandarg(union node *arg, struct arglist *arglist, int flag)
7199 argbackq = arg->narg.backquote;
7200 STARTSTACKSTR(expdest);
7201 ifsfirst.next = NULL;
7203 argstr(arg->narg.text, flag,
7204 /* var_str_list: */ arglist ? arglist->list : NULL);
7205 p = _STPUTC('\0', expdest);
7207 if (arglist == NULL) {
7208 return; /* here document expanded */
7210 p = grabstackstr(p);
7211 exparg.lastp = &exparg.list;
7215 if (flag & EXP_FULL) {
7216 ifsbreakup(p, &exparg);
7217 *exparg.lastp = NULL;
7218 exparg.lastp = &exparg.list;
7219 expandmeta(exparg.list /*, flag*/);
7221 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7223 sp = stzalloc(sizeof(*sp));
7226 exparg.lastp = &sp->next;
7230 *exparg.lastp = NULL;
7232 *arglist->lastp = exparg.list;
7233 arglist->lastp = exparg.lastp;
7238 * Expand shell variables and backquotes inside a here document.
7241 expandhere(union node *arg, int fd)
7244 expandarg(arg, (struct arglist *)NULL, 0);
7245 full_write(fd, stackblock(), expdest - (char *)stackblock());
7249 * Returns true if the pattern matches the string.
7252 patmatch(char *pattern, const char *string)
7254 return pmatch(preglob(pattern, 0, 0), string);
7258 * See if a pattern matches in a case statement.
7261 casematch(union node *pattern, char *val)
7263 struct stackmark smark;
7266 setstackmark(&smark);
7267 argbackq = pattern->narg.backquote;
7268 STARTSTACKSTR(expdest);
7270 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7271 /* var_str_list: */ NULL);
7272 STACKSTRNUL(expdest);
7273 result = patmatch(stackblock(), val);
7274 popstackmark(&smark);
7279 /* ============ find_command */
7283 int (*builtin)(int, char **) FAST_FUNC;
7284 /* unsigned flags; */
7286 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7287 /* "regular" builtins always take precedence over commands,
7288 * regardless of PATH=....%builtin... position */
7289 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7290 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7293 smallint cmdtype; /* CMDxxx */
7296 /* index >= 0 for commands without path (slashes) */
7297 /* (TODO: what exactly does the value mean? PATH position?) */
7298 /* index == -1 for commands with slashes */
7299 /* index == (-2 - applet_no) for NOFORK applets */
7300 const struct builtincmd *cmd;
7301 struct funcnode *func;
7304 /* values of cmdtype */
7305 #define CMDUNKNOWN -1 /* no entry in table for command */
7306 #define CMDNORMAL 0 /* command is an executable program */
7307 #define CMDFUNCTION 1 /* command is a shell function */
7308 #define CMDBUILTIN 2 /* command is a shell builtin */
7310 /* action to find_command() */
7311 #define DO_ERR 0x01 /* prints errors */
7312 #define DO_ABS 0x02 /* checks absolute paths */
7313 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7314 #define DO_ALTPATH 0x08 /* using alternate path */
7315 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7317 static void find_command(char *, struct cmdentry *, int, const char *);
7320 /* ============ Hashing commands */
7323 * When commands are first encountered, they are entered in a hash table.
7324 * This ensures that a full path search will not have to be done for them
7325 * on each invocation.
7327 * We should investigate converting to a linear search, even though that
7328 * would make the command name "hash" a misnomer.
7332 struct tblentry *next; /* next entry in hash chain */
7333 union param param; /* definition of builtin function */
7334 smallint cmdtype; /* CMDxxx */
7335 char rehash; /* if set, cd done since entry created */
7336 char cmdname[1]; /* name of command */
7339 static struct tblentry **cmdtable;
7340 #define INIT_G_cmdtable() do { \
7341 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7344 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7348 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7352 #if ENABLE_FEATURE_SH_STANDALONE
7353 if (applet_no >= 0) {
7354 if (APPLET_IS_NOEXEC(applet_no)) {
7358 run_applet_no_and_exit(applet_no, argv);
7360 /* re-exec ourselves with the new arguments */
7361 execve(bb_busybox_exec_path, argv, envp);
7362 /* If they called chroot or otherwise made the binary no longer
7363 * executable, fall through */
7370 execve(cmd, argv, envp);
7371 } while (errno == EINTR);
7373 execve(cmd, argv, envp);
7379 if (errno == ENOEXEC) {
7383 for (ap = argv; *ap; ap++)
7385 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7387 ap[0] = cmd = (char *)DEFAULT_SHELL;
7390 while ((*ap++ = *argv++) != NULL)
7399 * Exec a program. Never returns. If you change this routine, you may
7400 * have to change the find_command routine as well.
7402 static void shellexec(char **, const char *, int) NORETURN;
7404 shellexec(char **argv, const char *path, int idx)
7410 #if ENABLE_FEATURE_SH_STANDALONE
7414 clearredir(/*drop:*/ 1);
7415 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7416 if (strchr(argv[0], '/') != NULL
7417 #if ENABLE_FEATURE_SH_STANDALONE
7418 || (applet_no = find_applet_by_name(argv[0])) >= 0
7421 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7425 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7426 if (--idx < 0 && pathopt == NULL) {
7427 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7428 if (errno != ENOENT && errno != ENOTDIR)
7435 /* Map to POSIX errors */
7447 exitstatus = exerrno;
7448 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7449 argv[0], e, suppress_int));
7450 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7455 printentry(struct tblentry *cmdp)
7461 idx = cmdp->param.index;
7464 name = path_advance(&path, cmdp->cmdname);
7466 } while (--idx >= 0);
7467 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7471 * Clear out command entries. The argument specifies the first entry in
7472 * PATH which has changed.
7475 clearcmdentry(int firstchange)
7477 struct tblentry **tblp;
7478 struct tblentry **pp;
7479 struct tblentry *cmdp;
7482 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7484 while ((cmdp = *pp) != NULL) {
7485 if ((cmdp->cmdtype == CMDNORMAL &&
7486 cmdp->param.index >= firstchange)
7487 || (cmdp->cmdtype == CMDBUILTIN &&
7488 builtinloc >= firstchange)
7501 * Locate a command in the command hash table. If "add" is nonzero,
7502 * add the command to the table if it is not already present. The
7503 * variable "lastcmdentry" is set to point to the address of the link
7504 * pointing to the entry, so that delete_cmd_entry can delete the
7507 * Interrupts must be off if called with add != 0.
7509 static struct tblentry **lastcmdentry;
7511 static struct tblentry *
7512 cmdlookup(const char *name, int add)
7514 unsigned int hashval;
7516 struct tblentry *cmdp;
7517 struct tblentry **pp;
7520 hashval = (unsigned char)*p << 4;
7522 hashval += (unsigned char)*p++;
7524 pp = &cmdtable[hashval % CMDTABLESIZE];
7525 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7526 if (strcmp(cmdp->cmdname, name) == 0)
7530 if (add && cmdp == NULL) {
7531 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7533 /* + 1 - already done because
7534 * tblentry::cmdname is char[1] */);
7535 /*cmdp->next = NULL; - ckzalloc did it */
7536 cmdp->cmdtype = CMDUNKNOWN;
7537 strcpy(cmdp->cmdname, name);
7544 * Delete the command entry returned on the last lookup.
7547 delete_cmd_entry(void)
7549 struct tblentry *cmdp;
7552 cmdp = *lastcmdentry;
7553 *lastcmdentry = cmdp->next;
7554 if (cmdp->cmdtype == CMDFUNCTION)
7555 freefunc(cmdp->param.func);
7561 * Add a new command entry, replacing any existing command entry for
7562 * the same name - except special builtins.
7565 addcmdentry(char *name, struct cmdentry *entry)
7567 struct tblentry *cmdp;
7569 cmdp = cmdlookup(name, 1);
7570 if (cmdp->cmdtype == CMDFUNCTION) {
7571 freefunc(cmdp->param.func);
7573 cmdp->cmdtype = entry->cmdtype;
7574 cmdp->param = entry->u;
7578 static int FAST_FUNC
7579 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7581 struct tblentry **pp;
7582 struct tblentry *cmdp;
7584 struct cmdentry entry;
7587 if (nextopt("r") != '\0') {
7592 if (*argptr == NULL) {
7593 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7594 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7595 if (cmdp->cmdtype == CMDNORMAL)
7603 while ((name = *argptr) != NULL) {
7604 cmdp = cmdlookup(name, 0);
7606 && (cmdp->cmdtype == CMDNORMAL
7607 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7611 find_command(name, &entry, DO_ERR, pathval());
7612 if (entry.cmdtype == CMDUNKNOWN)
7620 * Called when a cd is done. Marks all commands so the next time they
7621 * are executed they will be rehashed.
7626 struct tblentry **pp;
7627 struct tblentry *cmdp;
7629 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7630 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7631 if (cmdp->cmdtype == CMDNORMAL
7632 || (cmdp->cmdtype == CMDBUILTIN
7633 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7643 * Fix command hash table when PATH changed.
7644 * Called before PATH is changed. The argument is the new value of PATH;
7645 * pathval() still returns the old value at this point.
7646 * Called with interrupts off.
7648 static void FAST_FUNC
7649 changepath(const char *new)
7657 firstchange = 9999; /* assume no change */
7663 if ((*old == '\0' && *new == ':')
7664 || (*old == ':' && *new == '\0')
7668 old = new; /* ignore subsequent differences */
7672 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7679 if (builtinloc < 0 && idx_bltin >= 0)
7680 builtinloc = idx_bltin; /* zap builtins */
7681 if (builtinloc >= 0 && idx_bltin < 0)
7683 clearcmdentry(firstchange);
7684 builtinloc = idx_bltin;
7699 #define TENDBQUOTE 12
7716 typedef smallint token_id_t;
7718 /* first char is indicating which tokens mark the end of a list */
7719 static const char *const tokname_array[] = {
7733 #define KWDOFFSET 13
7734 /* the following are keywords */
7753 /* Wrapper around strcmp for qsort/bsearch/... */
7755 pstrcmp(const void *a, const void *b)
7757 return strcmp((char*) a, (*(char**) b) + 1);
7760 static const char *const *
7761 findkwd(const char *s)
7763 return bsearch(s, tokname_array + KWDOFFSET,
7764 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7765 sizeof(tokname_array[0]), pstrcmp);
7769 * Locate and print what a word is...
7772 describe_command(char *command, int describe_command_verbose)
7774 struct cmdentry entry;
7775 struct tblentry *cmdp;
7776 #if ENABLE_ASH_ALIAS
7777 const struct alias *ap;
7779 const char *path = pathval();
7781 if (describe_command_verbose) {
7785 /* First look at the keywords */
7786 if (findkwd(command)) {
7787 out1str(describe_command_verbose ? " is a shell keyword" : command);
7791 #if ENABLE_ASH_ALIAS
7792 /* Then look at the aliases */
7793 ap = lookupalias(command, 0);
7795 if (!describe_command_verbose) {
7800 out1fmt(" is an alias for %s", ap->val);
7804 /* Then check if it is a tracked alias */
7805 cmdp = cmdlookup(command, 0);
7807 entry.cmdtype = cmdp->cmdtype;
7808 entry.u = cmdp->param;
7810 /* Finally use brute force */
7811 find_command(command, &entry, DO_ABS, path);
7814 switch (entry.cmdtype) {
7816 int j = entry.u.index;
7822 p = path_advance(&path, command);
7826 if (describe_command_verbose) {
7828 (cmdp ? " a tracked alias for" : nullstr), p
7837 if (describe_command_verbose) {
7838 out1str(" is a shell function");
7845 if (describe_command_verbose) {
7846 out1fmt(" is a %sshell builtin",
7847 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7848 "special " : nullstr
7856 if (describe_command_verbose) {
7857 out1str(": not found\n");
7866 static int FAST_FUNC
7867 typecmd(int argc UNUSED_PARAM, char **argv)
7873 /* type -p ... ? (we don't bother checking for 'p') */
7874 if (argv[1] && argv[1][0] == '-') {
7879 err |= describe_command(argv[i++], verbose);
7884 #if ENABLE_ASH_CMDCMD
7885 static int FAST_FUNC
7886 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7894 while ((c = nextopt("pvV")) != '\0')
7896 verify |= VERIFY_VERBOSE;
7898 verify |= VERIFY_BRIEF;
7903 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7904 if (verify && (*argptr != NULL)) {
7905 return describe_command(*argptr, verify - VERIFY_BRIEF);
7913 /* ============ eval.c */
7915 static int funcblocksize; /* size of structures in function */
7916 static int funcstringsize; /* size of strings in node */
7917 static void *funcblock; /* block to allocate function from */
7918 static char *funcstring; /* block to allocate strings from */
7920 /* flags in argument to evaltree */
7921 #define EV_EXIT 01 /* exit after evaluating tree */
7922 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7923 #define EV_BACKCMD 04 /* command executing within back quotes */
7925 static const uint8_t nodesize[N_NUMBER] = {
7926 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7927 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7928 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7929 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7930 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7931 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7932 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7933 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7934 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7935 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7936 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7937 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7938 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7939 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7940 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7941 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7942 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7943 #if ENABLE_ASH_BASH_COMPAT
7944 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7946 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7947 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7948 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7949 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7950 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7951 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7952 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7953 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7954 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7957 static void calcsize(union node *n);
7960 sizenodelist(struct nodelist *lp)
7963 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7970 calcsize(union node *n)
7974 funcblocksize += nodesize[n->type];
7977 calcsize(n->ncmd.redirect);
7978 calcsize(n->ncmd.args);
7979 calcsize(n->ncmd.assign);
7982 sizenodelist(n->npipe.cmdlist);
7987 calcsize(n->nredir.redirect);
7988 calcsize(n->nredir.n);
7995 calcsize(n->nbinary.ch2);
7996 calcsize(n->nbinary.ch1);
7999 calcsize(n->nif.elsepart);
8000 calcsize(n->nif.ifpart);
8001 calcsize(n->nif.test);
8004 funcstringsize += strlen(n->nfor.var) + 1;
8005 calcsize(n->nfor.body);
8006 calcsize(n->nfor.args);
8009 calcsize(n->ncase.cases);
8010 calcsize(n->ncase.expr);
8013 calcsize(n->nclist.body);
8014 calcsize(n->nclist.pattern);
8015 calcsize(n->nclist.next);
8019 sizenodelist(n->narg.backquote);
8020 funcstringsize += strlen(n->narg.text) + 1;
8021 calcsize(n->narg.next);
8024 #if ENABLE_ASH_BASH_COMPAT
8031 calcsize(n->nfile.fname);
8032 calcsize(n->nfile.next);
8036 calcsize(n->ndup.vname);
8037 calcsize(n->ndup.next);
8041 calcsize(n->nhere.doc);
8042 calcsize(n->nhere.next);
8045 calcsize(n->nnot.com);
8051 nodeckstrdup(char *s)
8053 char *rtn = funcstring;
8055 strcpy(funcstring, s);
8056 funcstring += strlen(s) + 1;
8060 static union node *copynode(union node *);
8062 static struct nodelist *
8063 copynodelist(struct nodelist *lp)
8065 struct nodelist *start;
8066 struct nodelist **lpp;
8071 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8072 (*lpp)->n = copynode(lp->n);
8074 lpp = &(*lpp)->next;
8081 copynode(union node *n)
8088 funcblock = (char *) funcblock + nodesize[n->type];
8092 new->ncmd.redirect = copynode(n->ncmd.redirect);
8093 new->ncmd.args = copynode(n->ncmd.args);
8094 new->ncmd.assign = copynode(n->ncmd.assign);
8097 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8098 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8103 new->nredir.redirect = copynode(n->nredir.redirect);
8104 new->nredir.n = copynode(n->nredir.n);
8111 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8112 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8115 new->nif.elsepart = copynode(n->nif.elsepart);
8116 new->nif.ifpart = copynode(n->nif.ifpart);
8117 new->nif.test = copynode(n->nif.test);
8120 new->nfor.var = nodeckstrdup(n->nfor.var);
8121 new->nfor.body = copynode(n->nfor.body);
8122 new->nfor.args = copynode(n->nfor.args);
8125 new->ncase.cases = copynode(n->ncase.cases);
8126 new->ncase.expr = copynode(n->ncase.expr);
8129 new->nclist.body = copynode(n->nclist.body);
8130 new->nclist.pattern = copynode(n->nclist.pattern);
8131 new->nclist.next = copynode(n->nclist.next);
8135 new->narg.backquote = copynodelist(n->narg.backquote);
8136 new->narg.text = nodeckstrdup(n->narg.text);
8137 new->narg.next = copynode(n->narg.next);
8140 #if ENABLE_ASH_BASH_COMPAT
8147 new->nfile.fname = copynode(n->nfile.fname);
8148 new->nfile.fd = n->nfile.fd;
8149 new->nfile.next = copynode(n->nfile.next);
8153 new->ndup.vname = copynode(n->ndup.vname);
8154 new->ndup.dupfd = n->ndup.dupfd;
8155 new->ndup.fd = n->ndup.fd;
8156 new->ndup.next = copynode(n->ndup.next);
8160 new->nhere.doc = copynode(n->nhere.doc);
8161 new->nhere.fd = n->nhere.fd;
8162 new->nhere.next = copynode(n->nhere.next);
8165 new->nnot.com = copynode(n->nnot.com);
8168 new->type = n->type;
8173 * Make a copy of a parse tree.
8175 static struct funcnode *
8176 copyfunc(union node *n)
8181 funcblocksize = offsetof(struct funcnode, n);
8184 blocksize = funcblocksize;
8185 f = ckmalloc(blocksize + funcstringsize);
8186 funcblock = (char *) f + offsetof(struct funcnode, n);
8187 funcstring = (char *) f + blocksize;
8194 * Define a shell function.
8197 defun(char *name, union node *func)
8199 struct cmdentry entry;
8202 entry.cmdtype = CMDFUNCTION;
8203 entry.u.func = copyfunc(func);
8204 addcmdentry(name, &entry);
8208 /* Reasons for skipping commands (see comment on breakcmd routine) */
8209 #define SKIPBREAK (1 << 0)
8210 #define SKIPCONT (1 << 1)
8211 #define SKIPFUNC (1 << 2)
8212 #define SKIPFILE (1 << 3)
8213 #define SKIPEVAL (1 << 4)
8214 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8215 static int skipcount; /* number of levels to skip */
8216 static int funcnest; /* depth of function calls */
8217 static int loopnest; /* current loop nesting level */
8219 /* Forward decl way out to parsing code - dotrap needs it */
8220 static int evalstring(char *s, int mask);
8222 /* Called to execute a trap.
8223 * Single callsite - at the end of evaltree().
8224 * If we return non-zero, evaltree raises EXEXIT exception.
8226 * Perhaps we should avoid entering new trap handlers
8227 * while we are executing a trap handler. [is it a TODO?]
8236 savestatus = exitstatus;
8240 TRACE(("dotrap entered\n"));
8241 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8248 /* non-trapped SIGINT is handled separately by raise_interrupt,
8249 * don't upset it by resetting gotsig[SIGINT-1] */
8250 if (sig == SIGINT && !t)
8253 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8257 want_exexit = evalstring(t, SKIPEVAL);
8258 exitstatus = savestatus;
8260 TRACE(("dotrap returns %d\n", want_exexit));
8265 TRACE(("dotrap returns 0\n"));
8269 /* forward declarations - evaluation is fairly recursive business... */
8270 static void evalloop(union node *, int);
8271 static void evalfor(union node *, int);
8272 static void evalcase(union node *, int);
8273 static void evalsubshell(union node *, int);
8274 static void expredir(union node *);
8275 static void evalpipe(union node *, int);
8276 static void evalcommand(union node *, int);
8277 static int evalbltin(const struct builtincmd *, int, char **);
8278 static void prehash(union node *);
8281 * Evaluate a parse tree. The value is left in the global variable
8285 evaltree(union node *n, int flags)
8287 struct jmploc *volatile savehandler = exception_handler;
8288 struct jmploc jmploc;
8290 void (*evalfn)(union node *, int);
8294 SAVE_INT(int_level);
8297 TRACE(("evaltree(NULL) called\n"));
8300 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8302 exception_handler = &jmploc;
8304 int err = setjmp(jmploc.loc);
8306 /* if it was a signal, check for trap handlers */
8307 if (exception_type == EXSIG) {
8308 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8309 exception_type, err));
8312 /* continue on the way out */
8313 TRACE(("exception %d in evaltree, propagating err=%d\n",
8314 exception_type, err));
8315 exception_handler = savehandler;
8316 longjmp(exception_handler->loc, err);
8323 out1fmt("Node type = %d\n", n->type);
8328 evaltree(n->nnot.com, EV_TESTED);
8329 status = !exitstatus;
8332 expredir(n->nredir.redirect);
8333 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8335 evaltree(n->nredir.n, flags & EV_TESTED);
8336 status = exitstatus;
8338 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8341 evalfn = evalcommand;
8343 if (eflag && !(flags & EV_TESTED))
8355 evalfn = evalsubshell;
8368 #error NAND + 1 != NOR
8370 #if NOR + 1 != NSEMI
8371 #error NOR + 1 != NSEMI
8373 unsigned is_or = n->type - NAND;
8376 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8378 if (!exitstatus == is_or)
8391 evaltree(n->nif.test, EV_TESTED);
8394 if (exitstatus == 0) {
8398 if (n->nif.elsepart) {
8399 n = n->nif.elsepart;
8404 defun(n->narg.text, n->narg.next);
8408 exitstatus = status;
8413 exception_handler = savehandler;
8416 /* Order of checks below is important:
8417 * signal handlers trigger before exit caused by "set -e".
8419 if (pending_sig && dotrap())
8421 if (checkexit & exitstatus)
8422 evalskip |= SKIPEVAL;
8424 if (flags & EV_EXIT) {
8426 raise_exception(EXEXIT);
8429 RESTORE_INT(int_level);
8430 TRACE(("leaving evaltree (no interrupts)\n"));
8433 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8436 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8439 evalloop(union node *n, int flags)
8449 evaltree(n->nbinary.ch1, EV_TESTED);
8452 if (evalskip == SKIPCONT && --skipcount <= 0) {
8456 if (evalskip == SKIPBREAK && --skipcount <= 0)
8461 if (n->type != NWHILE)
8465 evaltree(n->nbinary.ch2, flags);
8466 status = exitstatus;
8471 exitstatus = status;
8475 evalfor(union node *n, int flags)
8477 struct arglist arglist;
8480 struct stackmark smark;
8482 setstackmark(&smark);
8483 arglist.list = NULL;
8484 arglist.lastp = &arglist.list;
8485 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8486 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8491 *arglist.lastp = NULL;
8496 for (sp = arglist.list; sp; sp = sp->next) {
8497 setvar(n->nfor.var, sp->text, 0);
8498 evaltree(n->nfor.body, flags);
8500 if (evalskip == SKIPCONT && --skipcount <= 0) {
8504 if (evalskip == SKIPBREAK && --skipcount <= 0)
8511 popstackmark(&smark);
8515 evalcase(union node *n, int flags)
8519 struct arglist arglist;
8520 struct stackmark smark;
8522 setstackmark(&smark);
8523 arglist.list = NULL;
8524 arglist.lastp = &arglist.list;
8525 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8527 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8528 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8529 if (casematch(patp, arglist.list->text)) {
8530 if (evalskip == 0) {
8531 evaltree(cp->nclist.body, flags);
8538 popstackmark(&smark);
8542 * Kick off a subshell to evaluate a tree.
8545 evalsubshell(union node *n, int flags)
8548 int backgnd = (n->type == NBACKGND);
8551 expredir(n->nredir.redirect);
8552 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8555 jp = makejob(/*n,*/ 1);
8556 if (forkshell(jp, n, backgnd) == 0) {
8561 flags &= ~EV_TESTED;
8563 redirect(n->nredir.redirect, 0);
8564 evaltreenr(n->nredir.n, flags);
8569 status = waitforjob(jp);
8570 exitstatus = status;
8575 * Compute the names of the files in a redirection list.
8577 static void fixredir(union node *, const char *, int);
8579 expredir(union node *n)
8583 for (redir = n; redir; redir = redir->nfile.next) {
8587 fn.lastp = &fn.list;
8588 switch (redir->type) {
8592 #if ENABLE_ASH_BASH_COMPAT
8597 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8598 #if ENABLE_ASH_BASH_COMPAT
8601 redir->nfile.expfname = fn.list->text;
8604 case NTOFD: /* >& */
8605 if (redir->ndup.vname) {
8606 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8607 if (fn.list == NULL)
8608 ash_msg_and_raise_error("redir error");
8609 #if ENABLE_ASH_BASH_COMPAT
8610 //FIXME: we used expandarg with different args!
8611 if (!isdigit_str9(fn.list->text)) {
8612 /* >&file, not >&fd */
8613 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8614 ash_msg_and_raise_error("redir error");
8616 goto store_expfname;
8619 fixredir(redir, fn.list->text, 1);
8627 * Evaluate a pipeline. All the processes in the pipeline are children
8628 * of the process creating the pipeline. (This differs from some versions
8629 * of the shell, which make the last process in a pipeline the parent
8633 evalpipe(union node *n, int flags)
8636 struct nodelist *lp;
8641 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8643 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8647 jp = makejob(/*n,*/ pipelen);
8649 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8653 if (pipe(pip) < 0) {
8655 ash_msg_and_raise_error("pipe call failed");
8658 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8671 evaltreenr(lp->n, flags);
8677 /* Don't want to trigger debugging */
8681 if (n->npipe.pipe_backgnd == 0) {
8682 exitstatus = waitforjob(jp);
8683 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8689 * Controls whether the shell is interactive or not.
8692 setinteractive(int on)
8694 static smallint is_interactive;
8696 if (++on == is_interactive)
8698 is_interactive = on;
8702 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8703 if (is_interactive > 1) {
8704 /* Looks like they want an interactive shell */
8705 static smallint did_banner;
8708 /* note: ash and hush share this string */
8709 out1fmt("\n\n%s %s\n"
8710 "Enter 'help' for a list of built-in commands."
8713 "built-in shell (ash)"
8727 setinteractive(iflag);
8729 #if ENABLE_FEATURE_EDITING_VI
8731 line_input_state->flags |= VI_MODE;
8733 line_input_state->flags &= ~VI_MODE;
8735 viflag = 0; /* forcibly keep the option off */
8739 static struct localvar *localvars;
8742 * Called after a function returns.
8743 * Interrupts must be off.
8748 struct localvar *lvp;
8751 while ((lvp = localvars) != NULL) {
8752 localvars = lvp->next;
8754 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8755 if (vp == NULL) { /* $- saved */
8756 memcpy(optlist, lvp->text, sizeof(optlist));
8757 free((char*)lvp->text);
8759 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8760 unsetvar(vp->var_text);
8763 vp->var_func(var_end(lvp->text));
8764 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8765 free((char*)vp->var_text);
8766 vp->flags = lvp->flags;
8767 vp->var_text = lvp->text;
8774 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8776 volatile struct shparam saveparam;
8777 struct localvar *volatile savelocalvars;
8778 struct jmploc *volatile savehandler;
8779 struct jmploc jmploc;
8782 saveparam = shellparam;
8783 savelocalvars = localvars;
8784 e = setjmp(jmploc.loc);
8789 savehandler = exception_handler;
8790 exception_handler = &jmploc;
8792 shellparam.malloced = 0;
8796 shellparam.nparam = argc - 1;
8797 shellparam.p = argv + 1;
8798 #if ENABLE_ASH_GETOPTS
8799 shellparam.optind = 1;
8800 shellparam.optoff = -1;
8802 evaltree(&func->n, flags & EV_TESTED);
8808 localvars = savelocalvars;
8809 freeparam(&shellparam);
8810 shellparam = saveparam;
8811 exception_handler = savehandler;
8813 evalskip &= ~SKIPFUNC;
8817 #if ENABLE_ASH_CMDCMD
8819 parse_command_args(char **argv, const char **path)
8832 if (c == '-' && !*cp) {
8839 *path = bb_default_path;
8842 /* run 'typecmd' for other options */
8853 * Make a variable a local variable. When a variable is made local, it's
8854 * value and flags are saved in a localvar structure. The saved values
8855 * will be restored when the shell function returns. We handle the name
8856 * "-" as a special case.
8861 struct localvar *lvp;
8866 lvp = ckzalloc(sizeof(struct localvar));
8867 if (LONE_DASH(name)) {
8869 p = ckmalloc(sizeof(optlist));
8870 lvp->text = memcpy(p, optlist, sizeof(optlist));
8875 vpp = hashvar(name);
8876 vp = *findvar(vpp, name);
8877 eq = strchr(name, '=');
8880 setvareq(name, VSTRFIXED);
8882 setvar(name, NULL, VSTRFIXED);
8883 vp = *vpp; /* the new variable */
8884 lvp->flags = VUNSET;
8886 lvp->text = vp->var_text;
8887 lvp->flags = vp->flags;
8888 vp->flags |= VSTRFIXED|VTEXTFIXED;
8894 lvp->next = localvars;
8900 * The "local" command.
8902 static int FAST_FUNC
8903 localcmd(int argc UNUSED_PARAM, char **argv)
8908 while ((name = *argv++) != NULL) {
8914 static int FAST_FUNC
8915 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8920 static int FAST_FUNC
8921 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8926 static int FAST_FUNC
8927 execcmd(int argc UNUSED_PARAM, char **argv)
8930 iflag = 0; /* exit on error */
8933 shellexec(argv + 1, pathval(), 0);
8939 * The return command.
8941 static int FAST_FUNC
8942 returncmd(int argc UNUSED_PARAM, char **argv)
8945 * If called outside a function, do what ksh does;
8946 * skip the rest of the file.
8948 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8949 return argv[1] ? number(argv[1]) : exitstatus;
8952 /* Forward declarations for builtintab[] */
8953 static int breakcmd(int, char **) FAST_FUNC;
8954 static int dotcmd(int, char **) FAST_FUNC;
8955 static int evalcmd(int, char **) FAST_FUNC;
8956 static int exitcmd(int, char **) FAST_FUNC;
8957 static int exportcmd(int, char **) FAST_FUNC;
8958 #if ENABLE_ASH_GETOPTS
8959 static int getoptscmd(int, char **) FAST_FUNC;
8961 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8962 static int helpcmd(int, char **) FAST_FUNC;
8964 #if ENABLE_SH_MATH_SUPPORT
8965 static int letcmd(int, char **) FAST_FUNC;
8967 static int readcmd(int, char **) FAST_FUNC;
8968 static int setcmd(int, char **) FAST_FUNC;
8969 static int shiftcmd(int, char **) FAST_FUNC;
8970 static int timescmd(int, char **) FAST_FUNC;
8971 static int trapcmd(int, char **) FAST_FUNC;
8972 static int umaskcmd(int, char **) FAST_FUNC;
8973 static int unsetcmd(int, char **) FAST_FUNC;
8974 static int ulimitcmd(int, char **) FAST_FUNC;
8976 #define BUILTIN_NOSPEC "0"
8977 #define BUILTIN_SPECIAL "1"
8978 #define BUILTIN_REGULAR "2"
8979 #define BUILTIN_SPEC_REG "3"
8980 #define BUILTIN_ASSIGN "4"
8981 #define BUILTIN_SPEC_ASSG "5"
8982 #define BUILTIN_REG_ASSG "6"
8983 #define BUILTIN_SPEC_REG_ASSG "7"
8985 /* Stubs for calling non-FAST_FUNC's */
8986 #if ENABLE_ASH_BUILTIN_ECHO
8987 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8989 #if ENABLE_ASH_BUILTIN_PRINTF
8990 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8992 #if ENABLE_ASH_BUILTIN_TEST
8993 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8996 /* Keep these in proper order since it is searched via bsearch() */
8997 static const struct builtincmd builtintab[] = {
8998 { BUILTIN_SPEC_REG "." , dotcmd },
8999 { BUILTIN_SPEC_REG ":" , truecmd },
9000 #if ENABLE_ASH_BUILTIN_TEST
9001 { BUILTIN_REGULAR "[" , testcmd },
9002 #if ENABLE_ASH_BASH_COMPAT
9003 { BUILTIN_REGULAR "[[" , testcmd },
9006 #if ENABLE_ASH_ALIAS
9007 { BUILTIN_REG_ASSG "alias" , aliascmd },
9010 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9012 { BUILTIN_SPEC_REG "break" , breakcmd },
9013 { BUILTIN_REGULAR "cd" , cdcmd },
9014 { BUILTIN_NOSPEC "chdir" , cdcmd },
9015 #if ENABLE_ASH_CMDCMD
9016 { BUILTIN_REGULAR "command" , commandcmd },
9018 { BUILTIN_SPEC_REG "continue", breakcmd },
9019 #if ENABLE_ASH_BUILTIN_ECHO
9020 { BUILTIN_REGULAR "echo" , echocmd },
9022 { BUILTIN_SPEC_REG "eval" , evalcmd },
9023 { BUILTIN_SPEC_REG "exec" , execcmd },
9024 { BUILTIN_SPEC_REG "exit" , exitcmd },
9025 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9026 { BUILTIN_REGULAR "false" , falsecmd },
9028 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9030 #if ENABLE_ASH_GETOPTS
9031 { BUILTIN_REGULAR "getopts" , getoptscmd },
9033 { BUILTIN_NOSPEC "hash" , hashcmd },
9034 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9035 { BUILTIN_NOSPEC "help" , helpcmd },
9038 { BUILTIN_REGULAR "jobs" , jobscmd },
9039 { BUILTIN_REGULAR "kill" , killcmd },
9041 #if ENABLE_SH_MATH_SUPPORT
9042 { BUILTIN_NOSPEC "let" , letcmd },
9044 { BUILTIN_ASSIGN "local" , localcmd },
9045 #if ENABLE_ASH_BUILTIN_PRINTF
9046 { BUILTIN_REGULAR "printf" , printfcmd },
9048 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9049 { BUILTIN_REGULAR "read" , readcmd },
9050 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9051 { BUILTIN_SPEC_REG "return" , returncmd },
9052 { BUILTIN_SPEC_REG "set" , setcmd },
9053 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9054 #if ENABLE_ASH_BASH_COMPAT
9055 { BUILTIN_SPEC_REG "source" , dotcmd },
9057 #if ENABLE_ASH_BUILTIN_TEST
9058 { BUILTIN_REGULAR "test" , testcmd },
9060 { BUILTIN_SPEC_REG "times" , timescmd },
9061 { BUILTIN_SPEC_REG "trap" , trapcmd },
9062 { BUILTIN_REGULAR "true" , truecmd },
9063 { BUILTIN_NOSPEC "type" , typecmd },
9064 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9065 { BUILTIN_REGULAR "umask" , umaskcmd },
9066 #if ENABLE_ASH_ALIAS
9067 { BUILTIN_REGULAR "unalias" , unaliascmd },
9069 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9070 { BUILTIN_REGULAR "wait" , waitcmd },
9073 /* Should match the above table! */
9074 #define COMMANDCMD (builtintab + \
9076 1 * ENABLE_ASH_BUILTIN_TEST + \
9077 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9078 1 * ENABLE_ASH_ALIAS + \
9079 1 * ENABLE_ASH_JOB_CONTROL + \
9081 #define EXECCMD (builtintab + \
9083 1 * ENABLE_ASH_BUILTIN_TEST + \
9084 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9085 1 * ENABLE_ASH_ALIAS + \
9086 1 * ENABLE_ASH_JOB_CONTROL + \
9088 1 * ENABLE_ASH_CMDCMD + \
9090 ENABLE_ASH_BUILTIN_ECHO + \
9094 * Search the table of builtin commands.
9096 static struct builtincmd *
9097 find_builtin(const char *name)
9099 struct builtincmd *bp;
9102 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9109 * Execute a simple command.
9112 isassignment(const char *p)
9114 const char *q = endofname(p);
9119 static int FAST_FUNC
9120 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9122 /* Preserve exitstatus of a previous possible redirection
9123 * as POSIX mandates */
9124 return back_exitstatus;
9127 evalcommand(union node *cmd, int flags)
9129 static const struct builtincmd null_bltin = {
9130 "\0\0", bltincmd /* why three NULs? */
9132 struct stackmark smark;
9134 struct arglist arglist;
9135 struct arglist varlist;
9138 const struct strlist *sp;
9139 struct cmdentry cmdentry;
9146 struct builtincmd *bcmd;
9147 smallint cmd_is_exec;
9148 smallint pseudovarflag = 0;
9150 /* First expand the arguments. */
9151 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9152 setstackmark(&smark);
9153 back_exitstatus = 0;
9155 cmdentry.cmdtype = CMDBUILTIN;
9156 cmdentry.u.cmd = &null_bltin;
9157 varlist.lastp = &varlist.list;
9158 *varlist.lastp = NULL;
9159 arglist.lastp = &arglist.list;
9160 *arglist.lastp = NULL;
9163 if (cmd->ncmd.args) {
9164 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9165 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9168 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9169 struct strlist **spp;
9171 spp = arglist.lastp;
9172 if (pseudovarflag && isassignment(argp->narg.text))
9173 expandarg(argp, &arglist, EXP_VARTILDE);
9175 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9177 for (sp = *spp; sp; sp = sp->next)
9181 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9182 for (sp = arglist.list; sp; sp = sp->next) {
9183 TRACE(("evalcommand arg: %s\n", sp->text));
9184 *nargv++ = sp->text;
9189 if (iflag && funcnest == 0 && argc > 0)
9190 lastarg = nargv[-1];
9193 expredir(cmd->ncmd.redirect);
9194 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9196 path = vpath.var_text;
9197 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9198 struct strlist **spp;
9201 spp = varlist.lastp;
9202 expandarg(argp, &varlist, EXP_VARTILDE);
9205 * Modify the command lookup path, if a PATH= assignment
9209 if (varcmp(p, path) == 0)
9213 /* Print the command if xflag is set. */
9216 const char *p = " %s" + 1;
9218 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9220 for (n = 0; n < 2; n++) {
9222 fdprintf(preverrout_fd, p, sp->text);
9228 safe_write(preverrout_fd, "\n", 1);
9234 /* Now locate the command. */
9236 const char *oldpath;
9237 int cmd_flag = DO_ERR;
9242 find_command(argv[0], &cmdentry, cmd_flag, path);
9243 if (cmdentry.cmdtype == CMDUNKNOWN) {
9244 flush_stdout_stderr();
9249 /* implement bltin and command here */
9250 if (cmdentry.cmdtype != CMDBUILTIN)
9253 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9254 if (cmdentry.u.cmd == EXECCMD)
9256 #if ENABLE_ASH_CMDCMD
9257 if (cmdentry.u.cmd == COMMANDCMD) {
9259 nargv = parse_command_args(argv, &path);
9262 argc -= nargv - argv;
9264 cmd_flag |= DO_NOFUNC;
9272 /* We have a redirection error. */
9274 raise_exception(EXERROR);
9276 exitstatus = status;
9280 /* Execute the command. */
9281 switch (cmdentry.cmdtype) {
9284 #if ENABLE_FEATURE_SH_NOFORK
9285 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9286 * around run_nofork_applet() call.
9287 * (2) Should this check also be done in forkshell()?
9288 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9290 /* find_command() encodes applet_no as (-2 - applet_no) */
9291 int applet_no = (- cmdentry.u.index - 2);
9292 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9293 listsetvar(varlist.list, VEXPORT|VSTACK);
9294 /* run <applet>_main() */
9295 exitstatus = run_nofork_applet(applet_no, argv);
9299 /* Can we avoid forking off? For example, very last command
9300 * in a script or a subshell does not need forking,
9301 * we can just exec it.
9303 if (!(flags & EV_EXIT) || may_have_traps) {
9304 /* No, forking off a child is necessary */
9306 jp = makejob(/*cmd,*/ 1);
9307 if (forkshell(jp, cmd, FORK_FG) != 0) {
9309 exitstatus = waitforjob(jp);
9311 TRACE(("forked child exited with %d\n", exitstatus));
9316 /* fall through to exec'ing external program */
9318 listsetvar(varlist.list, VEXPORT|VSTACK);
9319 shellexec(argv, path, cmdentry.u.index);
9323 cmdenviron = varlist.list;
9325 struct strlist *list = cmdenviron;
9327 if (spclbltin > 0 || argc == 0) {
9329 if (cmd_is_exec && argc > 1)
9332 listsetvar(list, i);
9334 /* Tight loop with builtins only:
9335 * "while kill -0 $child; do true; done"
9336 * will never exit even if $child died, unless we do this
9337 * to reap the zombie and make kill detect that it's gone: */
9338 dowait(DOWAIT_NONBLOCK, NULL);
9340 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9342 int i = exception_type;
9347 exit_status = 128 + SIGINT;
9349 exit_status = 128 + pending_sig;
9350 exitstatus = exit_status;
9351 if (i == EXINT || spclbltin > 0) {
9353 longjmp(exception_handler->loc, 1);
9360 listsetvar(varlist.list, 0);
9361 /* See above for the rationale */
9362 dowait(DOWAIT_NONBLOCK, NULL);
9363 if (evalfun(cmdentry.u.func, argc, argv, flags))
9370 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9372 /* dsl: I think this is intended to be used to support
9373 * '_' in 'vi' command mode during line editing...
9374 * However I implemented that within libedit itself.
9376 setvar("_", lastarg, 0);
9378 popstackmark(&smark);
9382 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9384 char *volatile savecmdname;
9385 struct jmploc *volatile savehandler;
9386 struct jmploc jmploc;
9389 savecmdname = commandname;
9390 i = setjmp(jmploc.loc);
9393 savehandler = exception_handler;
9394 exception_handler = &jmploc;
9395 commandname = argv[0];
9397 optptr = NULL; /* initialize nextopt */
9398 exitstatus = (*cmd->builtin)(argc, argv);
9399 flush_stdout_stderr();
9401 exitstatus |= ferror(stdout);
9403 commandname = savecmdname;
9404 exception_handler = savehandler;
9410 goodname(const char *p)
9412 return endofname(p)[0] == '\0';
9417 * Search for a command. This is called before we fork so that the
9418 * location of the command will be available in the parent as well as
9419 * the child. The check for "goodname" is an overly conservative
9420 * check that the name will not be subject to expansion.
9423 prehash(union node *n)
9425 struct cmdentry entry;
9427 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9428 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9432 /* ============ Builtin commands
9434 * Builtin commands whose functions are closely tied to evaluation
9435 * are implemented here.
9439 * Handle break and continue commands. Break, continue, and return are
9440 * all handled by setting the evalskip flag. The evaluation routines
9441 * above all check this flag, and if it is set they start skipping
9442 * commands rather than executing them. The variable skipcount is
9443 * the number of loops to break/continue, or the number of function
9444 * levels to return. (The latter is always 1.) It should probably
9445 * be an error to break out of more loops than exist, but it isn't
9446 * in the standard shell so we don't make it one here.
9448 static int FAST_FUNC
9449 breakcmd(int argc UNUSED_PARAM, char **argv)
9451 int n = argv[1] ? number(argv[1]) : 1;
9454 ash_msg_and_raise_error(msg_illnum, argv[1]);
9458 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9465 /* ============ input.c
9467 * This implements the input routines used by the parser.
9471 INPUT_PUSH_FILE = 1,
9472 INPUT_NOFILE_OK = 2,
9475 static smallint checkkwd;
9476 /* values of checkkwd variable */
9477 #define CHKALIAS 0x1
9482 * Push a string back onto the input at this current parsefile level.
9483 * We handle aliases this way.
9485 #if !ENABLE_ASH_ALIAS
9486 #define pushstring(s, ap) pushstring(s)
9489 pushstring(char *s, struct alias *ap)
9496 if (g_parsefile->strpush) {
9497 sp = ckzalloc(sizeof(*sp));
9498 sp->prev = g_parsefile->strpush;
9500 sp = &(g_parsefile->basestrpush);
9502 g_parsefile->strpush = sp;
9503 sp->prev_string = g_parsefile->next_to_pgetc;
9504 sp->prev_left_in_line = g_parsefile->left_in_line;
9505 #if ENABLE_ASH_ALIAS
9508 ap->flag |= ALIASINUSE;
9512 g_parsefile->next_to_pgetc = s;
9513 g_parsefile->left_in_line = len;
9520 struct strpush *sp = g_parsefile->strpush;
9523 #if ENABLE_ASH_ALIAS
9525 if (g_parsefile->next_to_pgetc[-1] == ' '
9526 || g_parsefile->next_to_pgetc[-1] == '\t'
9528 checkkwd |= CHKALIAS;
9530 if (sp->string != sp->ap->val) {
9533 sp->ap->flag &= ~ALIASINUSE;
9534 if (sp->ap->flag & ALIASDEAD) {
9535 unalias(sp->ap->name);
9539 g_parsefile->next_to_pgetc = sp->prev_string;
9540 g_parsefile->left_in_line = sp->prev_left_in_line;
9541 g_parsefile->strpush = sp->prev;
9542 if (sp != &(g_parsefile->basestrpush))
9547 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9548 //it peeks whether it is &>, and then pushes back both chars.
9549 //This function needs to save last *next_to_pgetc to buf[0]
9550 //to make two pungetc() reliable. Currently,
9551 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9556 char *buf = g_parsefile->buf;
9558 g_parsefile->next_to_pgetc = buf;
9559 #if ENABLE_FEATURE_EDITING
9561 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9562 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9564 #if ENABLE_FEATURE_TAB_COMPLETION
9565 line_input_state->path_lookup = pathval();
9567 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9569 /* Ctrl+C pressed */
9578 if (nr < 0 && errno == 0) {
9579 /* Ctrl+D pressed */
9584 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9588 /* nonblock_safe_read() handles this problem */
9590 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9591 int flags = fcntl(0, F_GETFL);
9592 if (flags >= 0 && (flags & O_NONBLOCK)) {
9593 flags &= ~O_NONBLOCK;
9594 if (fcntl(0, F_SETFL, flags) >= 0) {
9595 out2str("sh: turning off NDELAY mode\n");
9606 * Refill the input buffer and return the next input character:
9608 * 1) If a string was pushed back on the input, pop it;
9609 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9610 * or we are reading from a string so we can't refill the buffer,
9612 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9613 * 4) Process input up to the next newline, deleting nul characters.
9615 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9616 #define pgetc_debug(...) ((void)0)
9623 while (g_parsefile->strpush) {
9624 #if ENABLE_ASH_ALIAS
9625 if (g_parsefile->left_in_line == -1
9626 && g_parsefile->strpush->ap
9627 && g_parsefile->next_to_pgetc[-1] != ' '
9628 && g_parsefile->next_to_pgetc[-1] != '\t'
9630 pgetc_debug("preadbuffer PEOA");
9635 /* try "pgetc" now: */
9636 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9637 g_parsefile->left_in_line,
9638 g_parsefile->next_to_pgetc,
9639 g_parsefile->next_to_pgetc);
9640 if (--g_parsefile->left_in_line >= 0)
9641 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9643 /* on both branches above g_parsefile->left_in_line < 0.
9644 * "pgetc" needs refilling.
9647 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9648 * pungetc() may increment it a few times.
9649 * Assuming it won't increment it to less than -90.
9651 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9652 pgetc_debug("preadbuffer PEOF1");
9653 /* even in failure keep left_in_line and next_to_pgetc
9654 * in lock step, for correct multi-layer pungetc.
9655 * left_in_line was decremented before preadbuffer(),
9656 * must inc next_to_pgetc: */
9657 g_parsefile->next_to_pgetc++;
9661 more = g_parsefile->left_in_buffer;
9663 flush_stdout_stderr();
9667 /* don't try reading again */
9668 g_parsefile->left_in_line = -99;
9669 pgetc_debug("preadbuffer PEOF2");
9670 g_parsefile->next_to_pgetc++;
9675 /* Find out where's the end of line.
9676 * Set g_parsefile->left_in_line
9677 * and g_parsefile->left_in_buffer acordingly.
9678 * NUL chars are deleted.
9680 q = g_parsefile->next_to_pgetc;
9688 memmove(q, q + 1, more);
9692 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9698 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9699 if (g_parsefile->left_in_line < 0)
9704 g_parsefile->left_in_buffer = more;
9709 out2str(g_parsefile->next_to_pgetc);
9713 pgetc_debug("preadbuffer at %d:%p'%s'",
9714 g_parsefile->left_in_line,
9715 g_parsefile->next_to_pgetc,
9716 g_parsefile->next_to_pgetc);
9717 return (unsigned char)*g_parsefile->next_to_pgetc++;
9720 #define pgetc_as_macro() \
9721 (--g_parsefile->left_in_line >= 0 \
9722 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9729 pgetc_debug("pgetc_fast at %d:%p'%s'",
9730 g_parsefile->left_in_line,
9731 g_parsefile->next_to_pgetc,
9732 g_parsefile->next_to_pgetc);
9733 return pgetc_as_macro();
9736 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9737 # define pgetc_fast() pgetc()
9739 # define pgetc_fast() pgetc_as_macro()
9742 #if ENABLE_ASH_ALIAS
9744 pgetc_without_PEOA(void)
9748 pgetc_debug("pgetc_fast at %d:%p'%s'",
9749 g_parsefile->left_in_line,
9750 g_parsefile->next_to_pgetc,
9751 g_parsefile->next_to_pgetc);
9753 } while (c == PEOA);
9757 # define pgetc_without_PEOA() pgetc()
9761 * Read a line from the script.
9764 pfgets(char *line, int len)
9770 while (--nleft > 0) {
9771 c = pgetc_without_PEOA();
9786 * Undo the last call to pgetc. Only one character may be pushed back.
9787 * PEOF may be pushed back.
9792 g_parsefile->left_in_line++;
9793 g_parsefile->next_to_pgetc--;
9794 pgetc_debug("pushed back to %d:%p'%s'",
9795 g_parsefile->left_in_line,
9796 g_parsefile->next_to_pgetc,
9797 g_parsefile->next_to_pgetc);
9801 * To handle the "." command, a stack of input files is used. Pushfile
9802 * adds a new entry to the stack and popfile restores the previous level.
9807 struct parsefile *pf;
9809 pf = ckzalloc(sizeof(*pf));
9810 pf->prev = g_parsefile;
9812 /*pf->strpush = NULL; - ckzalloc did it */
9813 /*pf->basestrpush.prev = NULL;*/
9820 struct parsefile *pf = g_parsefile;
9828 g_parsefile = pf->prev;
9834 * Return to top level.
9839 while (g_parsefile != &basepf)
9844 * Close the file(s) that the shell is reading commands from. Called
9845 * after a fork is done.
9851 if (g_parsefile->pf_fd > 0) {
9852 close(g_parsefile->pf_fd);
9853 g_parsefile->pf_fd = 0;
9858 * Like setinputfile, but takes an open file descriptor. Call this with
9862 setinputfd(int fd, int push)
9864 close_on_exec_on(fd);
9867 g_parsefile->buf = NULL;
9869 g_parsefile->pf_fd = fd;
9870 if (g_parsefile->buf == NULL)
9871 g_parsefile->buf = ckmalloc(IBUFSIZ);
9872 g_parsefile->left_in_buffer = 0;
9873 g_parsefile->left_in_line = 0;
9874 g_parsefile->linno = 1;
9878 * Set the input to take input from a file. If push is set, push the
9879 * old input onto the stack first.
9882 setinputfile(const char *fname, int flags)
9888 fd = open(fname, O_RDONLY);
9890 if (flags & INPUT_NOFILE_OK)
9892 ash_msg_and_raise_error("can't open '%s'", fname);
9895 fd2 = copyfd(fd, 10);
9898 ash_msg_and_raise_error("out of file descriptors");
9901 setinputfd(fd, flags & INPUT_PUSH_FILE);
9908 * Like setinputfile, but takes input from a string.
9911 setinputstring(char *string)
9915 g_parsefile->next_to_pgetc = string;
9916 g_parsefile->left_in_line = strlen(string);
9917 g_parsefile->buf = NULL;
9918 g_parsefile->linno = 1;
9923 /* ============ mail.c
9925 * Routines to check for mail.
9930 #define MAXMBOXES 10
9932 /* times of mailboxes */
9933 static time_t mailtime[MAXMBOXES];
9934 /* Set if MAIL or MAILPATH is changed. */
9935 static smallint mail_var_path_changed;
9938 * Print appropriate message(s) if mail has arrived.
9939 * If mail_var_path_changed is set,
9940 * then the value of MAIL has mail_var_path_changed,
9941 * so we just update the values.
9950 struct stackmark smark;
9953 setstackmark(&smark);
9954 mpath = mpathset() ? mpathval() : mailval();
9955 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9956 p = path_advance(&mpath, nullstr);
9961 for (q = p; *q; q++)
9967 q[-1] = '\0'; /* delete trailing '/' */
9968 if (stat(p, &statb) < 0) {
9972 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9975 pathopt ? pathopt : "you have mail"
9978 *mtp = statb.st_mtime;
9980 mail_var_path_changed = 0;
9981 popstackmark(&smark);
9984 static void FAST_FUNC
9985 changemail(const char *val UNUSED_PARAM)
9987 mail_var_path_changed = 1;
9990 #endif /* ASH_MAIL */
9993 /* ============ ??? */
9996 * Set the shell parameters.
9999 setparam(char **argv)
10005 for (nparam = 0; argv[nparam]; nparam++)
10007 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10009 *ap++ = ckstrdup(*argv++);
10012 freeparam(&shellparam);
10013 shellparam.malloced = 1;
10014 shellparam.nparam = nparam;
10015 shellparam.p = newparam;
10016 #if ENABLE_ASH_GETOPTS
10017 shellparam.optind = 1;
10018 shellparam.optoff = -1;
10023 * Process shell options. The global variable argptr contains a pointer
10024 * to the argument list; we advance it past the options.
10026 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10027 * For a non-interactive shell, an error condition encountered
10028 * by a special built-in ... shall cause the shell to write a diagnostic message
10029 * to standard error and exit as shown in the following table:
10030 * Error Special Built-In
10032 * Utility syntax error (option or operand error) Shall exit
10034 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10035 * we see that bash does not do that (set "finishes" with error code 1 instead,
10036 * and shell continues), and people rely on this behavior!
10038 * set -o barfoo 2>/dev/null
10041 * Oh well. Let's mimic that.
10044 plus_minus_o(char *name, int val)
10049 for (i = 0; i < NOPTS; i++) {
10050 if (strcmp(name, optnames(i)) == 0) {
10055 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10058 for (i = 0; i < NOPTS; i++) {
10060 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10062 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10068 setoption(int flag, int val)
10072 for (i = 0; i < NOPTS; i++) {
10073 if (optletters(i) == flag) {
10078 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10082 options(int cmdline)
10090 while ((p = *argptr) != NULL) {
10092 if (c != '-' && c != '+')
10095 val = 0; /* val = 0 if c == '+' */
10098 if (p[0] == '\0' || LONE_DASH(p)) {
10100 /* "-" means turn off -x and -v */
10103 /* "--" means reset params */
10104 else if (*argptr == NULL)
10107 break; /* "-" or "--" terminates options */
10110 /* first char was + or - */
10111 while ((c = *p++) != '\0') {
10112 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10113 if (c == 'c' && cmdline) {
10114 minusc = p; /* command is after shell args */
10115 } else if (c == 'o') {
10116 if (plus_minus_o(*argptr, val)) {
10117 /* it already printed err message */
10118 return 1; /* error */
10122 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10124 /* bash does not accept +-login, we also won't */
10125 } else if (cmdline && val && (c == '-')) { /* long options */
10126 if (strcmp(p, "login") == 0)
10138 * The shift builtin command.
10140 static int FAST_FUNC
10141 shiftcmd(int argc UNUSED_PARAM, char **argv)
10148 n = number(argv[1]);
10149 if (n > shellparam.nparam)
10150 n = 0; /* bash compat, was = shellparam.nparam; */
10152 shellparam.nparam -= n;
10153 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10154 if (shellparam.malloced)
10157 ap2 = shellparam.p;
10158 while ((*ap2++ = *ap1++) != NULL)
10160 #if ENABLE_ASH_GETOPTS
10161 shellparam.optind = 1;
10162 shellparam.optoff = -1;
10169 * POSIX requires that 'set' (but not export or readonly) output the
10170 * variables in lexicographic order - by the locale's collating order (sigh).
10171 * Maybe we could keep them in an ordered balanced binary tree
10172 * instead of hashed lists.
10173 * For now just roll 'em through qsort for printing...
10176 showvars(const char *sep_prefix, int on, int off)
10179 char **ep, **epend;
10181 ep = listvars(on, off, &epend);
10182 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10184 sep = *sep_prefix ? " " : sep_prefix;
10186 for (; ep < epend; ep++) {
10190 p = strchrnul(*ep, '=');
10193 q = single_quote(++p);
10194 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10200 * The set command builtin.
10202 static int FAST_FUNC
10203 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10208 return showvars(nullstr, 0, VUNSET);
10211 if (!options(0)) { /* if no parse error... */
10214 if (*argptr != NULL) {
10222 #if ENABLE_ASH_RANDOM_SUPPORT
10223 static void FAST_FUNC
10224 change_random(const char *value)
10228 if (value == NULL) {
10229 /* "get", generate */
10230 t = next_random(&random_gen);
10231 /* set without recursion */
10232 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10233 vrandom.flags &= ~VNOFUNC;
10236 t = strtoul(value, NULL, 10);
10237 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10242 #if ENABLE_ASH_GETOPTS
10244 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10253 if (*param_optind < 1)
10255 optnext = optfirst + *param_optind - 1;
10257 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10260 p = optnext[-1] + *optoff;
10261 if (p == NULL || *p == '\0') {
10262 /* Current word is done, advance */
10264 if (p == NULL || *p != '-' || *++p == '\0') {
10271 if (LONE_DASH(p)) /* check for "--" */
10276 for (q = optstr; *q != c;) {
10278 if (optstr[0] == ':') {
10281 err |= setvarsafe("OPTARG", s, 0);
10283 fprintf(stderr, "Illegal option -%c\n", c);
10284 unsetvar("OPTARG");
10294 if (*p == '\0' && (p = *optnext) == NULL) {
10295 if (optstr[0] == ':') {
10298 err |= setvarsafe("OPTARG", s, 0);
10301 fprintf(stderr, "No arg for -%c option\n", c);
10302 unsetvar("OPTARG");
10310 err |= setvarsafe("OPTARG", p, 0);
10313 err |= setvarsafe("OPTARG", nullstr, 0);
10315 *optoff = p ? p - *(optnext - 1) : -1;
10316 *param_optind = optnext - optfirst + 1;
10317 fmtstr(s, sizeof(s), "%d", *param_optind);
10318 err |= setvarsafe("OPTIND", s, VNOFUNC);
10321 err |= setvarsafe(optvar, s, 0);
10325 flush_stdout_stderr();
10326 raise_exception(EXERROR);
10332 * The getopts builtin. Shellparam.optnext points to the next argument
10333 * to be processed. Shellparam.optptr points to the next character to
10334 * be processed in the current argument. If shellparam.optnext is NULL,
10335 * then it's the first time getopts has been called.
10337 static int FAST_FUNC
10338 getoptscmd(int argc, char **argv)
10343 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10345 optbase = shellparam.p;
10346 if (shellparam.optind > shellparam.nparam + 1) {
10347 shellparam.optind = 1;
10348 shellparam.optoff = -1;
10351 optbase = &argv[3];
10352 if (shellparam.optind > argc - 2) {
10353 shellparam.optind = 1;
10354 shellparam.optoff = -1;
10358 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10359 &shellparam.optoff);
10361 #endif /* ASH_GETOPTS */
10364 /* ============ Shell parser */
10367 struct heredoc *next; /* next here document in list */
10368 union node *here; /* redirection node */
10369 char *eofmark; /* string indicating end of input */
10370 smallint striptabs; /* if set, strip leading tabs */
10373 static smallint tokpushback; /* last token pushed back */
10374 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10375 static smallint quoteflag; /* set if (part of) last token was quoted */
10376 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10377 static struct heredoc *heredoclist; /* list of here documents to read */
10378 static char *wordtext; /* text of last word returned by readtoken */
10379 static struct nodelist *backquotelist;
10380 static union node *redirnode;
10381 static struct heredoc *heredoc;
10383 static const char *
10384 tokname(char *buf, int tok)
10387 return tokname_array[tok] + 1;
10388 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10392 /* raise_error_unexpected_syntax:
10393 * Called when an unexpected token is read during the parse. The argument
10394 * is the token that is expected, or -1 if more than one type of token can
10395 * occur at this point.
10397 static void raise_error_unexpected_syntax(int) NORETURN;
10399 raise_error_unexpected_syntax(int token)
10405 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10407 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10408 raise_error_syntax(msg);
10412 #define EOFMARKLEN 79
10414 /* parsing is heavily cross-recursive, need these forward decls */
10415 static union node *andor(void);
10416 static union node *pipeline(void);
10417 static union node *parse_command(void);
10418 static void parseheredoc(void);
10419 static char peektoken(void);
10420 static int readtoken(void);
10422 static union node *
10425 union node *n1, *n2, *n3;
10428 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10429 if (nlflag == 2 && peektoken())
10435 if (tok == TBACKGND) {
10436 if (n2->type == NPIPE) {
10437 n2->npipe.pipe_backgnd = 1;
10439 if (n2->type != NREDIR) {
10440 n3 = stzalloc(sizeof(struct nredir));
10442 /*n3->nredir.redirect = NULL; - stzalloc did it */
10445 n2->type = NBACKGND;
10451 n3 = stzalloc(sizeof(struct nbinary));
10453 n3->nbinary.ch1 = n1;
10454 n3->nbinary.ch2 = n2;
10470 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10478 pungetc(); /* push back EOF on input */
10482 raise_error_unexpected_syntax(-1);
10489 static union node *
10492 union node *n1, *n2, *n3;
10500 } else if (t == TOR) {
10506 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10508 n3 = stzalloc(sizeof(struct nbinary));
10510 n3->nbinary.ch1 = n1;
10511 n3->nbinary.ch2 = n2;
10516 static union node *
10519 union node *n1, *n2, *pipenode;
10520 struct nodelist *lp, *prev;
10524 TRACE(("pipeline: entered\n"));
10525 if (readtoken() == TNOT) {
10527 checkkwd = CHKKWD | CHKALIAS;
10530 n1 = parse_command();
10531 if (readtoken() == TPIPE) {
10532 pipenode = stzalloc(sizeof(struct npipe));
10533 pipenode->type = NPIPE;
10534 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10535 lp = stzalloc(sizeof(struct nodelist));
10536 pipenode->npipe.cmdlist = lp;
10540 lp = stzalloc(sizeof(struct nodelist));
10541 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10542 lp->n = parse_command();
10544 } while (readtoken() == TPIPE);
10550 n2 = stzalloc(sizeof(struct nnot));
10558 static union node *
10563 n = stzalloc(sizeof(struct narg));
10565 /*n->narg.next = NULL; - stzalloc did it */
10566 n->narg.text = wordtext;
10567 n->narg.backquote = backquotelist;
10572 fixredir(union node *n, const char *text, int err)
10576 TRACE(("Fix redir %s %d\n", text, err));
10578 n->ndup.vname = NULL;
10580 fd = bb_strtou(text, NULL, 10);
10581 if (!errno && fd >= 0)
10582 n->ndup.dupfd = fd;
10583 else if (LONE_DASH(text))
10584 n->ndup.dupfd = -1;
10587 raise_error_syntax("bad fd number");
10588 n->ndup.vname = makename();
10593 * Returns true if the text contains nothing to expand (no dollar signs
10597 noexpand(const char *text)
10601 while ((c = *text++) != '\0') {
10602 if (c == CTLQUOTEMARK)
10606 else if (SIT(c, BASESYNTAX) == CCTL)
10615 union node *n = redirnode;
10617 if (readtoken() != TWORD)
10618 raise_error_unexpected_syntax(-1);
10619 if (n->type == NHERE) {
10620 struct heredoc *here = heredoc;
10624 if (quoteflag == 0)
10626 TRACE(("Here document %d\n", n->type));
10627 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10628 raise_error_syntax("illegal eof marker for << redirection");
10629 rmescapes(wordtext, 0);
10630 here->eofmark = wordtext;
10632 if (heredoclist == NULL)
10633 heredoclist = here;
10635 for (p = heredoclist; p->next; p = p->next)
10639 } else if (n->type == NTOFD || n->type == NFROMFD) {
10640 fixredir(n, wordtext, 0);
10642 n->nfile.fname = makename();
10646 static union node *
10649 union node *args, **app;
10650 union node *n = NULL;
10651 union node *vars, **vpp;
10652 union node **rpp, *redir;
10654 #if ENABLE_ASH_BASH_COMPAT
10655 smallint double_brackets_flag = 0;
10665 savecheckkwd = CHKALIAS;
10668 checkkwd = savecheckkwd;
10671 #if ENABLE_ASH_BASH_COMPAT
10672 case TAND: /* "&&" */
10673 case TOR: /* "||" */
10674 if (!double_brackets_flag) {
10678 wordtext = (char *) (t == TAND ? "-a" : "-o");
10681 n = stzalloc(sizeof(struct narg));
10683 /*n->narg.next = NULL; - stzalloc did it */
10684 n->narg.text = wordtext;
10685 #if ENABLE_ASH_BASH_COMPAT
10686 if (strcmp("[[", wordtext) == 0)
10687 double_brackets_flag = 1;
10688 else if (strcmp("]]", wordtext) == 0)
10689 double_brackets_flag = 0;
10691 n->narg.backquote = backquotelist;
10692 if (savecheckkwd && isassignment(wordtext)) {
10694 vpp = &n->narg.next;
10697 app = &n->narg.next;
10702 *rpp = n = redirnode;
10703 rpp = &n->nfile.next;
10704 parsefname(); /* read name of redirection file */
10707 if (args && app == &args->narg.next
10710 struct builtincmd *bcmd;
10713 /* We have a function */
10714 if (readtoken() != TRP)
10715 raise_error_unexpected_syntax(TRP);
10716 name = n->narg.text;
10717 if (!goodname(name)
10718 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10720 raise_error_syntax("bad function name");
10723 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10724 n->narg.next = parse_command();
10737 n = stzalloc(sizeof(struct ncmd));
10739 n->ncmd.args = args;
10740 n->ncmd.assign = vars;
10741 n->ncmd.redirect = redir;
10745 static union node *
10746 parse_command(void)
10748 union node *n1, *n2;
10749 union node *ap, **app;
10750 union node *cp, **cpp;
10751 union node *redir, **rpp;
10758 switch (readtoken()) {
10760 raise_error_unexpected_syntax(-1);
10763 n1 = stzalloc(sizeof(struct nif));
10765 n1->nif.test = list(0);
10766 if (readtoken() != TTHEN)
10767 raise_error_unexpected_syntax(TTHEN);
10768 n1->nif.ifpart = list(0);
10770 while (readtoken() == TELIF) {
10771 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10772 n2 = n2->nif.elsepart;
10774 n2->nif.test = list(0);
10775 if (readtoken() != TTHEN)
10776 raise_error_unexpected_syntax(TTHEN);
10777 n2->nif.ifpart = list(0);
10779 if (lasttoken == TELSE)
10780 n2->nif.elsepart = list(0);
10782 n2->nif.elsepart = NULL;
10790 n1 = stzalloc(sizeof(struct nbinary));
10791 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10792 n1->nbinary.ch1 = list(0);
10795 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10796 got == TWORD ? wordtext : ""));
10797 raise_error_unexpected_syntax(TDO);
10799 n1->nbinary.ch2 = list(0);
10804 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10805 raise_error_syntax("bad for loop variable");
10806 n1 = stzalloc(sizeof(struct nfor));
10808 n1->nfor.var = wordtext;
10809 checkkwd = CHKKWD | CHKALIAS;
10810 if (readtoken() == TIN) {
10812 while (readtoken() == TWORD) {
10813 n2 = stzalloc(sizeof(struct narg));
10815 /*n2->narg.next = NULL; - stzalloc did it */
10816 n2->narg.text = wordtext;
10817 n2->narg.backquote = backquotelist;
10819 app = &n2->narg.next;
10822 n1->nfor.args = ap;
10823 if (lasttoken != TNL && lasttoken != TSEMI)
10824 raise_error_unexpected_syntax(-1);
10826 n2 = stzalloc(sizeof(struct narg));
10828 /*n2->narg.next = NULL; - stzalloc did it */
10829 n2->narg.text = (char *)dolatstr;
10830 /*n2->narg.backquote = NULL;*/
10831 n1->nfor.args = n2;
10833 * Newline or semicolon here is optional (but note
10834 * that the original Bourne shell only allowed NL).
10836 if (lasttoken != TNL && lasttoken != TSEMI)
10839 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10840 if (readtoken() != TDO)
10841 raise_error_unexpected_syntax(TDO);
10842 n1->nfor.body = list(0);
10846 n1 = stzalloc(sizeof(struct ncase));
10848 if (readtoken() != TWORD)
10849 raise_error_unexpected_syntax(TWORD);
10850 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10852 /*n2->narg.next = NULL; - stzalloc did it */
10853 n2->narg.text = wordtext;
10854 n2->narg.backquote = backquotelist;
10856 checkkwd = CHKKWD | CHKALIAS;
10857 } while (readtoken() == TNL);
10858 if (lasttoken != TIN)
10859 raise_error_unexpected_syntax(TIN);
10860 cpp = &n1->ncase.cases;
10862 checkkwd = CHKNL | CHKKWD;
10864 while (t != TESAC) {
10865 if (lasttoken == TLP)
10867 *cpp = cp = stzalloc(sizeof(struct nclist));
10869 app = &cp->nclist.pattern;
10871 *app = ap = stzalloc(sizeof(struct narg));
10873 /*ap->narg.next = NULL; - stzalloc did it */
10874 ap->narg.text = wordtext;
10875 ap->narg.backquote = backquotelist;
10876 if (readtoken() != TPIPE)
10878 app = &ap->narg.next;
10881 //ap->narg.next = NULL;
10882 if (lasttoken != TRP)
10883 raise_error_unexpected_syntax(TRP);
10884 cp->nclist.body = list(2);
10886 cpp = &cp->nclist.next;
10888 checkkwd = CHKNL | CHKKWD;
10892 raise_error_unexpected_syntax(TENDCASE);
10899 n1 = stzalloc(sizeof(struct nredir));
10900 n1->type = NSUBSHELL;
10901 n1->nredir.n = list(0);
10902 /*n1->nredir.redirect = NULL; - stzalloc did it */
10912 return simplecmd();
10915 if (readtoken() != t)
10916 raise_error_unexpected_syntax(t);
10919 /* Now check for redirection which may follow command */
10920 checkkwd = CHKKWD | CHKALIAS;
10922 while (readtoken() == TREDIR) {
10923 *rpp = n2 = redirnode;
10924 rpp = &n2->nfile.next;
10930 if (n1->type != NSUBSHELL) {
10931 n2 = stzalloc(sizeof(struct nredir));
10936 n1->nredir.redirect = redir;
10941 #if ENABLE_ASH_BASH_COMPAT
10942 static int decode_dollar_squote(void)
10944 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10950 p = strchr(C_escapes, c);
10955 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10959 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10961 } else if (c == 'x') { /* \xHH */
10965 } while (isxdigit(c) && --cnt);
10967 if (cnt == 3) { /* \x but next char is "bad" */
10971 } else { /* simple seq like \\ or \t */
10976 c = bb_process_escape_sequence((void*)&p);
10977 } else { /* unrecognized "\z": print both chars unless ' or " */
10978 if (c != '\'' && c != '"') {
10980 c |= 0x100; /* "please encode \, then me" */
10988 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10989 * is not NULL, read a here document. In the latter case, eofmark is the
10990 * word which marks the end of the document and striptabs is true if
10991 * leading tabs should be stripped from the document. The argument c
10992 * is the first character of the input token or document.
10994 * Because C does not have internal subroutines, I have simulated them
10995 * using goto's to implement the subroutine linkage. The following macros
10996 * will run code that appears at the end of readtoken1.
10998 #define CHECKEND() {goto checkend; checkend_return:;}
10999 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11000 #define PARSESUB() {goto parsesub; parsesub_return:;}
11001 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11002 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11003 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11005 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11007 /* NB: syntax parameter fits into smallint */
11008 /* c parameter is an unsigned char or PEOF or PEOA */
11011 char line[EOFMARKLEN + 1];
11012 struct nodelist *bqlist;
11016 smallint prevsyntax; /* syntax before arithmetic */
11017 #if ENABLE_ASH_EXPAND_PRMT
11018 smallint pssyntax; /* we are expanding a prompt string */
11020 int varnest; /* levels of variables expansion */
11021 int arinest; /* levels of arithmetic expansion */
11022 int parenlevel; /* levels of parens in arithmetic */
11023 int dqvarnest; /* levels of variables expansion within double quotes */
11025 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11028 /* Avoid longjmp clobbering */
11034 (void) &parenlevel;
11037 (void) &prevsyntax;
11040 startlinno = g_parsefile->linno;
11044 #if ENABLE_ASH_EXPAND_PRMT
11045 pssyntax = (syntax == PSSYNTAX);
11049 dblquote = (syntax == DQSYNTAX);
11055 STARTSTACKSTR(out);
11057 /* For each line, until end of word */
11058 CHECKEND(); /* set c to PEOF if at end of here document */
11059 for (;;) { /* until end of line or end of word */
11060 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11061 switch (SIT(c, syntax)) {
11062 case CNL: /* '\n' */
11063 if (syntax == BASESYNTAX)
11064 goto endword; /* exit outer loop */
11066 g_parsefile->linno++;
11067 setprompt_if(doprompt, 2);
11069 goto loop; /* continue outer loop */
11074 if (eofmark == NULL || dblquote)
11075 USTPUTC(CTLESC, out);
11076 #if ENABLE_ASH_BASH_COMPAT
11077 if (c == '\\' && bash_dollar_squote) {
11078 c = decode_dollar_squote();
11080 USTPUTC('\\', out);
11081 c = (unsigned char)c;
11087 case CBACK: /* backslash */
11088 c = pgetc_without_PEOA();
11090 USTPUTC(CTLESC, out);
11091 USTPUTC('\\', out);
11093 } else if (c == '\n') {
11094 setprompt_if(doprompt, 2);
11096 #if ENABLE_ASH_EXPAND_PRMT
11097 if (c == '$' && pssyntax) {
11098 USTPUTC(CTLESC, out);
11099 USTPUTC('\\', out);
11102 /* Backslash is retained if we are in "str" and next char isn't special */
11107 && (c != '"' || eofmark != NULL)
11109 USTPUTC(CTLESC, out);
11110 USTPUTC('\\', out);
11112 if (SIT(c, SQSYNTAX) == CCTL)
11113 USTPUTC(CTLESC, out);
11121 if (eofmark == NULL) {
11122 USTPUTC(CTLQUOTEMARK, out);
11130 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11131 if (eofmark != NULL && arinest == 0
11136 if (dqvarnest == 0) {
11137 syntax = BASESYNTAX;
11144 case CVAR: /* '$' */
11145 PARSESUB(); /* parse substitution */
11147 case CENDVAR: /* '}' */
11150 if (dqvarnest > 0) {
11157 #if ENABLE_SH_MATH_SUPPORT
11158 case CLP: /* '(' in arithmetic */
11162 case CRP: /* ')' in arithmetic */
11163 if (parenlevel > 0) {
11166 if (pgetc() == ')') {
11167 if (--arinest == 0) {
11168 syntax = prevsyntax;
11169 dblquote = (syntax == DQSYNTAX);
11174 * unbalanced parens
11175 * (don't 2nd guess - no error)
11183 case CBQUOTE: /* '`' */
11187 goto endword; /* exit outer loop */
11191 if (varnest == 0) {
11192 #if ENABLE_ASH_BASH_COMPAT
11194 if (pgetc() == '>')
11195 c = 0x100 + '>'; /* flag &> */
11199 goto endword; /* exit outer loop */
11201 IF_ASH_ALIAS(if (c != PEOA))
11208 #if ENABLE_SH_MATH_SUPPORT
11209 if (syntax == ARISYNTAX)
11210 raise_error_syntax("missing '))'");
11212 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11213 raise_error_syntax("unterminated quoted string");
11214 if (varnest != 0) {
11215 startlinno = g_parsefile->linno;
11217 raise_error_syntax("missing '}'");
11219 USTPUTC('\0', out);
11220 len = out - (char *)stackblock();
11221 out = stackblock();
11222 if (eofmark == NULL) {
11223 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11226 if (isdigit_str9(out)) {
11227 PARSEREDIR(); /* passed as params: out, c */
11228 lasttoken = TREDIR;
11231 /* else: non-number X seen, interpret it
11232 * as "NNNX>file" = "NNNX >file" */
11236 quoteflag = quotef;
11237 backquotelist = bqlist;
11238 grabstackblock(len);
11242 /* end of readtoken routine */
11245 * Check to see whether we are at the end of the here document. When this
11246 * is called, c is set to the first character of the next input line. If
11247 * we are at the end of the here document, this routine sets the c to PEOF.
11251 #if ENABLE_ASH_ALIAS
11253 c = pgetc_without_PEOA();
11256 while (c == '\t') {
11257 c = pgetc_without_PEOA();
11260 if (c == *eofmark) {
11261 if (pfgets(line, sizeof(line)) != NULL) {
11265 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11267 if (*p == '\n' && *q == '\0') {
11269 g_parsefile->linno++;
11270 needprompt = doprompt;
11272 pushstring(line, NULL);
11277 goto checkend_return;
11281 * Parse a redirection operator. The variable "out" points to a string
11282 * specifying the fd to be redirected. The variable "c" contains the
11283 * first character of the redirection operator.
11286 /* out is already checked to be a valid number or "" */
11287 int fd = (*out == '\0' ? -1 : atoi(out));
11290 np = stzalloc(sizeof(struct nfile));
11295 np->type = NAPPEND;
11297 np->type = NCLOBBER;
11300 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11306 #if ENABLE_ASH_BASH_COMPAT
11307 else if (c == 0x100 + '>') { /* this flags &> redirection */
11309 pgetc(); /* this is '>', no need to check */
11313 else { /* c == '<' */
11314 /*np->nfile.fd = 0; - stzalloc did it */
11318 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11319 np = stzalloc(sizeof(struct nhere));
11320 /*np->nfile.fd = 0; - stzalloc did it */
11323 heredoc = stzalloc(sizeof(struct heredoc));
11324 heredoc->here = np;
11327 heredoc->striptabs = 1;
11329 /*heredoc->striptabs = 0; - stzalloc did it */
11335 np->type = NFROMFD;
11339 np->type = NFROMTO;
11351 goto parseredir_return;
11355 * Parse a substitution. At this point, we have read the dollar sign
11356 * and nothing else.
11359 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11360 * (assuming ascii char codes, as the original implementation did) */
11361 #define is_special(c) \
11362 (((unsigned)(c) - 33 < 32) \
11363 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11365 unsigned char subtype;
11370 if (c > 255 /* PEOA or PEOF */
11371 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11373 #if ENABLE_ASH_BASH_COMPAT
11375 bash_dollar_squote = 1;
11380 } else if (c == '(') {
11381 /* $(command) or $((arith)) */
11382 if (pgetc() == '(') {
11383 #if ENABLE_SH_MATH_SUPPORT
11386 raise_error_syntax("you disabled math support for $((arith)) syntax");
11393 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11394 USTPUTC(CTLVAR, out);
11395 typeloc = out - (char *)stackblock();
11396 USTPUTC(VSNORMAL, out);
11397 subtype = VSNORMAL;
11403 c = '#'; /* ${#} - same as $# */
11405 subtype = VSLENGTH; /* ${#VAR} */
11410 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11411 /* $[{[#]]NAME[}] */
11415 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11416 } else if (isdigit(c)) {
11417 /* $[{[#]]NUM[}] */
11421 } while (isdigit(c));
11422 } else if (is_special(c)) {
11423 /* $[{[#]]<specialchar>[}] */
11428 raise_error_syntax("bad substitution");
11430 if (c != '}' && subtype == VSLENGTH) {
11431 /* ${#VAR didn't end with } */
11437 if (subtype == 0) {
11438 /* ${VAR...} but not $VAR or ${#VAR} */
11439 /* c == first char after VAR */
11443 #if ENABLE_ASH_BASH_COMPAT
11444 if (c == ':' || c == '$' || isdigit(c)) {
11445 //TODO: support more general format ${v:EXPR:EXPR},
11446 // where EXPR follows $(()) rules
11447 subtype = VSSUBSTR;
11449 break; /* "goto do_pungetc" is bigger (!) */
11455 static const char types[] ALIGN1 = "}-+?=";
11456 const char *p = strchr(types, c);
11459 subtype = p - types + VSNORMAL;
11465 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11472 #if ENABLE_ASH_BASH_COMPAT
11474 /* ${v/[/]pattern/repl} */
11475 //TODO: encode pattern and repl separately.
11476 // Currently ${v/$var_with_slash/repl} is horribly broken
11477 subtype = VSREPLACE;
11481 subtype++; /* VSREPLACEALL */
11489 if (dblquote || arinest)
11491 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11492 if (subtype != VSNORMAL) {
11494 if (dblquote || arinest) {
11499 goto parsesub_return;
11503 * Called to parse command substitutions. Newstyle is set if the command
11504 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11505 * list of commands (passed by reference), and savelen is the number of
11506 * characters on the top of the stack which must be preserved.
11509 struct nodelist **nlpp;
11512 char *volatile str;
11513 struct jmploc jmploc;
11514 struct jmploc *volatile savehandler;
11516 smallint saveprompt = 0;
11519 (void) &saveprompt;
11521 savepbq = parsebackquote;
11522 if (setjmp(jmploc.loc)) {
11524 parsebackquote = 0;
11525 exception_handler = savehandler;
11526 longjmp(exception_handler->loc, 1);
11530 savelen = out - (char *)stackblock();
11532 str = ckmalloc(savelen);
11533 memcpy(str, stackblock(), savelen);
11535 savehandler = exception_handler;
11536 exception_handler = &jmploc;
11539 /* We must read until the closing backquote, giving special
11540 treatment to some slashes, and then push the string and
11541 reread it as input, interpreting it normally. */
11546 STARTSTACKSTR(pout);
11550 setprompt_if(needprompt, 2);
11559 g_parsefile->linno++;
11560 setprompt_if(doprompt, 2);
11562 * If eating a newline, avoid putting
11563 * the newline into the new character
11564 * stream (via the STPUTC after the
11569 if (pc != '\\' && pc != '`' && pc != '$'
11570 && (!dblquote || pc != '"')
11572 STPUTC('\\', pout);
11574 if (pc <= 255 /* not PEOA or PEOF */) {
11580 IF_ASH_ALIAS(case PEOA:)
11581 startlinno = g_parsefile->linno;
11582 raise_error_syntax("EOF in backquote substitution");
11585 g_parsefile->linno++;
11586 needprompt = doprompt;
11595 STPUTC('\0', pout);
11596 psavelen = pout - (char *)stackblock();
11597 if (psavelen > 0) {
11598 pstr = grabstackstr(pout);
11599 setinputstring(pstr);
11604 nlpp = &(*nlpp)->next;
11605 *nlpp = stzalloc(sizeof(**nlpp));
11606 /* (*nlpp)->next = NULL; - stzalloc did it */
11607 parsebackquote = oldstyle;
11610 saveprompt = doprompt;
11617 doprompt = saveprompt;
11618 else if (readtoken() != TRP)
11619 raise_error_unexpected_syntax(TRP);
11624 * Start reading from old file again, ignoring any pushed back
11625 * tokens left from the backquote parsing
11630 while (stackblocksize() <= savelen)
11632 STARTSTACKSTR(out);
11634 memcpy(out, str, savelen);
11635 STADJUST(savelen, out);
11641 parsebackquote = savepbq;
11642 exception_handler = savehandler;
11643 if (arinest || dblquote)
11644 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11646 USTPUTC(CTLBACKQ, out);
11648 goto parsebackq_oldreturn;
11649 goto parsebackq_newreturn;
11652 #if ENABLE_SH_MATH_SUPPORT
11654 * Parse an arithmetic expansion (indicate start of one and set state)
11657 if (++arinest == 1) {
11658 prevsyntax = syntax;
11659 syntax = ARISYNTAX;
11660 USTPUTC(CTLARI, out);
11667 * we collapse embedded arithmetic expansion to
11668 * parenthesis, which should be equivalent
11672 goto parsearith_return;
11676 } /* end of readtoken */
11679 * Read the next input token.
11680 * If the token is a word, we set backquotelist to the list of cmds in
11681 * backquotes. We set quoteflag to true if any part of the word was
11683 * If the token is TREDIR, then we set redirnode to a structure containing
11685 * In all cases, the variable startlinno is set to the number of the line
11686 * on which the token starts.
11688 * [Change comment: here documents and internal procedures]
11689 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11690 * word parsing code into a separate routine. In this case, readtoken
11691 * doesn't need to have any internal procedures, but parseword does.
11692 * We could also make parseoperator in essence the main routine, and
11693 * have parseword (readtoken1?) handle both words and redirection.]
11695 #define NEW_xxreadtoken
11696 #ifdef NEW_xxreadtoken
11697 /* singles must be first! */
11698 static const char xxreadtoken_chars[7] ALIGN1 = {
11699 '\n', '(', ')', /* singles */
11700 '&', '|', ';', /* doubles */
11704 #define xxreadtoken_singles 3
11705 #define xxreadtoken_doubles 3
11707 static const char xxreadtoken_tokens[] ALIGN1 = {
11708 TNL, TLP, TRP, /* only single occurrence allowed */
11709 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11710 TEOF, /* corresponds to trailing nul */
11711 TAND, TOR, TENDCASE /* if double occurrence */
11723 setprompt_if(needprompt, 2);
11724 startlinno = g_parsefile->linno;
11725 for (;;) { /* until token or start of word found */
11727 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11731 while ((c = pgetc()) != '\n' && c != PEOF)
11734 } else if (c == '\\') {
11735 if (pgetc() != '\n') {
11737 break; /* return readtoken1(...) */
11739 startlinno = ++g_parsefile->linno;
11740 setprompt_if(doprompt, 2);
11744 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11747 g_parsefile->linno++;
11748 needprompt = doprompt;
11751 p = strchr(xxreadtoken_chars, c);
11753 break; /* return readtoken1(...) */
11755 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11757 if (cc == c) { /* double occurrence? */
11758 p += xxreadtoken_doubles + 1;
11761 #if ENABLE_ASH_BASH_COMPAT
11762 if (c == '&' && cc == '>') /* &> */
11763 break; /* return readtoken1(...) */
11768 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11773 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11775 #else /* old xxreadtoken */
11776 #define RETURN(token) return lasttoken = token
11786 setprompt_if(needprompt, 2);
11787 startlinno = g_parsefile->linno;
11788 for (;;) { /* until token or start of word found */
11791 case ' ': case '\t':
11792 IF_ASH_ALIAS(case PEOA:)
11795 while ((c = pgetc()) != '\n' && c != PEOF)
11800 if (pgetc() == '\n') {
11801 startlinno = ++g_parsefile->linno;
11802 setprompt_if(doprompt, 2);
11808 g_parsefile->linno++;
11809 needprompt = doprompt;
11814 if (pgetc() == '&')
11819 if (pgetc() == '|')
11824 if (pgetc() == ';')
11837 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11840 #endif /* old xxreadtoken */
11847 smallint alreadyseen = tokpushback;
11850 #if ENABLE_ASH_ALIAS
11859 if (checkkwd & CHKNL) {
11866 if (t != TWORD || quoteflag) {
11871 * check for keywords
11873 if (checkkwd & CHKKWD) {
11874 const char *const *pp;
11876 pp = findkwd(wordtext);
11878 lasttoken = t = pp - tokname_array;
11879 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11884 if (checkkwd & CHKALIAS) {
11885 #if ENABLE_ASH_ALIAS
11887 ap = lookupalias(wordtext, 1);
11890 pushstring(ap->val, ap);
11900 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11902 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11914 return tokname_array[t][0];
11918 * Read and parse a command. Returns NODE_EOF on end of file.
11919 * (NULL is a valid parse tree indicating a blank line.)
11921 static union node *
11922 parsecmd(int interact)
11927 doprompt = interact;
11928 setprompt_if(doprompt, doprompt);
11940 * Input any here documents.
11945 struct heredoc *here;
11948 here = heredoclist;
11949 heredoclist = NULL;
11952 setprompt_if(needprompt, 2);
11953 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
11954 here->eofmark, here->striptabs);
11955 n = stzalloc(sizeof(struct narg));
11956 n->narg.type = NARG;
11957 /*n->narg.next = NULL; - stzalloc did it */
11958 n->narg.text = wordtext;
11959 n->narg.backquote = backquotelist;
11960 here->here->nhere.doc = n;
11967 * called by editline -- any expansions to the prompt should be added here.
11969 #if ENABLE_ASH_EXPAND_PRMT
11970 static const char *
11971 expandstr(const char *ps)
11975 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11976 * and token processing _can_ alter it (delete NULs etc). */
11977 setinputstring((char *)ps);
11978 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11981 n.narg.type = NARG;
11982 n.narg.next = NULL;
11983 n.narg.text = wordtext;
11984 n.narg.backquote = backquotelist;
11986 expandarg(&n, NULL, 0);
11987 return stackblock();
11992 * Execute a command or commands contained in a string.
11995 evalstring(char *s, int mask)
11998 struct stackmark smark;
12002 setstackmark(&smark);
12005 while ((n = parsecmd(0)) != NODE_EOF) {
12007 popstackmark(&smark);
12020 * The eval command.
12022 static int FAST_FUNC
12023 evalcmd(int argc UNUSED_PARAM, char **argv)
12032 STARTSTACKSTR(concat);
12034 concat = stack_putstr(p, concat);
12038 STPUTC(' ', concat);
12040 STPUTC('\0', concat);
12041 p = grabstackstr(concat);
12043 evalstring(p, ~SKIPEVAL);
12049 * Read and execute commands.
12050 * "Top" is nonzero for the top level command loop;
12051 * it turns on prompting if the shell is interactive.
12057 struct stackmark smark;
12061 TRACE(("cmdloop(%d) called\n", top));
12065 setstackmark(&smark);
12068 showjobs(stderr, SHOW_CHANGED);
12071 if (iflag && top) {
12073 #if ENABLE_ASH_MAIL
12077 n = parsecmd(inter);
12079 if (DEBUG > 2 && debug && (n != NODE_EOF))
12082 if (n == NODE_EOF) {
12083 if (!top || numeof >= 50)
12085 if (!stoppedjobs()) {
12088 out2str("\nUse \"exit\" to leave shell.\n");
12091 } else if (nflag == 0) {
12092 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12097 popstackmark(&smark);
12102 return skip & SKIPEVAL;
12109 * Take commands from a file. To be compatible we should do a path
12110 * search for the file, which is necessary to find sub-commands.
12113 find_dot_file(char *name)
12116 const char *path = pathval();
12119 /* don't try this for absolute or relative paths */
12120 if (strchr(name, '/'))
12123 /* IIRC standards do not say whether . is to be searched.
12124 * And it is even smaller this way, making it unconditional for now:
12126 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12131 while ((fullname = path_advance(&path, name)) != NULL) {
12133 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12135 * Don't bother freeing here, since it will
12136 * be freed by the caller.
12140 if (fullname != name)
12141 stunalloc(fullname);
12144 /* not found in the PATH */
12145 ash_msg_and_raise_error("%s: not found", name);
12149 static int FAST_FUNC
12150 dotcmd(int argc, char **argv)
12153 struct strlist *sp;
12154 volatile struct shparam saveparam;
12156 for (sp = cmdenviron; sp; sp = sp->next)
12157 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12160 /* bash says: "bash: .: filename argument required" */
12161 return 2; /* bash compat */
12164 /* "false; . empty_file; echo $?" should print 0, not 1: */
12167 fullname = find_dot_file(argv[1]);
12171 if (argc) { /* argc > 0, argv[0] != NULL */
12172 saveparam = shellparam;
12173 shellparam.malloced = 0;
12174 shellparam.nparam = argc;
12175 shellparam.p = argv;
12178 setinputfile(fullname, INPUT_PUSH_FILE);
12179 commandname = fullname;
12184 freeparam(&shellparam);
12185 shellparam = saveparam;
12191 static int FAST_FUNC
12192 exitcmd(int argc UNUSED_PARAM, char **argv)
12197 exitstatus = number(argv[1]);
12198 raise_exception(EXEXIT);
12203 * Read a file containing shell functions.
12206 readcmdfile(char *name)
12208 setinputfile(name, INPUT_PUSH_FILE);
12214 /* ============ find_command inplementation */
12217 * Resolve a command name. If you change this routine, you may have to
12218 * change the shellexec routine as well.
12221 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12223 struct tblentry *cmdp;
12230 struct builtincmd *bcmd;
12232 /* If name contains a slash, don't use PATH or hash table */
12233 if (strchr(name, '/') != NULL) {
12234 entry->u.index = -1;
12235 if (act & DO_ABS) {
12236 while (stat(name, &statb) < 0) {
12238 if (errno == EINTR)
12241 entry->cmdtype = CMDUNKNOWN;
12245 entry->cmdtype = CMDNORMAL;
12249 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12251 updatetbl = (path == pathval());
12254 if (strstr(path, "%builtin") != NULL)
12255 act |= DO_ALTBLTIN;
12258 /* If name is in the table, check answer will be ok */
12259 cmdp = cmdlookup(name, 0);
12260 if (cmdp != NULL) {
12263 switch (cmdp->cmdtype) {
12281 } else if (cmdp->rehash == 0)
12282 /* if not invalidated by cd, we're done */
12286 /* If %builtin not in path, check for builtin next */
12287 bcmd = find_builtin(name);
12289 if (IS_BUILTIN_REGULAR(bcmd))
12290 goto builtin_success;
12291 if (act & DO_ALTPATH) {
12292 if (!(act & DO_ALTBLTIN))
12293 goto builtin_success;
12294 } else if (builtinloc <= 0) {
12295 goto builtin_success;
12299 #if ENABLE_FEATURE_SH_STANDALONE
12301 int applet_no = find_applet_by_name(name);
12302 if (applet_no >= 0) {
12303 entry->cmdtype = CMDNORMAL;
12304 entry->u.index = -2 - applet_no;
12310 /* We have to search path. */
12311 prev = -1; /* where to start */
12312 if (cmdp && cmdp->rehash) { /* doing a rehash */
12313 if (cmdp->cmdtype == CMDBUILTIN)
12316 prev = cmdp->param.index;
12322 while ((fullname = path_advance(&path, name)) != NULL) {
12323 stunalloc(fullname);
12324 /* NB: code below will still use fullname
12325 * despite it being "unallocated" */
12328 if (prefix(pathopt, "builtin")) {
12330 goto builtin_success;
12333 if ((act & DO_NOFUNC)
12334 || !prefix(pathopt, "func")
12335 ) { /* ignore unimplemented options */
12339 /* if rehash, don't redo absolute path names */
12340 if (fullname[0] == '/' && idx <= prev) {
12343 TRACE(("searchexec \"%s\": no change\n", name));
12346 while (stat(fullname, &statb) < 0) {
12348 if (errno == EINTR)
12351 if (errno != ENOENT && errno != ENOTDIR)
12355 e = EACCES; /* if we fail, this will be the error */
12356 if (!S_ISREG(statb.st_mode))
12358 if (pathopt) { /* this is a %func directory */
12359 stalloc(strlen(fullname) + 1);
12360 /* NB: stalloc will return space pointed by fullname
12361 * (because we don't have any intervening allocations
12362 * between stunalloc above and this stalloc) */
12363 readcmdfile(fullname);
12364 cmdp = cmdlookup(name, 0);
12365 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12366 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12367 stunalloc(fullname);
12370 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12372 entry->cmdtype = CMDNORMAL;
12373 entry->u.index = idx;
12377 cmdp = cmdlookup(name, 1);
12378 cmdp->cmdtype = CMDNORMAL;
12379 cmdp->param.index = idx;
12384 /* We failed. If there was an entry for this command, delete it */
12385 if (cmdp && updatetbl)
12386 delete_cmd_entry();
12388 ash_msg("%s: %s", name, errmsg(e, "not found"));
12389 entry->cmdtype = CMDUNKNOWN;
12394 entry->cmdtype = CMDBUILTIN;
12395 entry->u.cmd = bcmd;
12399 cmdp = cmdlookup(name, 1);
12400 cmdp->cmdtype = CMDBUILTIN;
12401 cmdp->param.cmd = bcmd;
12405 entry->cmdtype = cmdp->cmdtype;
12406 entry->u = cmdp->param;
12410 /* ============ trap.c */
12413 * The trap builtin.
12415 static int FAST_FUNC
12416 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12420 int signo, exitcode;
12425 for (signo = 0; signo < NSIG; signo++) {
12426 char *tr = trap_ptr[signo];
12428 /* note: bash adds "SIG", but only if invoked
12429 * as "bash". If called as "sh", or if set -o posix,
12430 * then it prints short signal names.
12431 * We are printing short names: */
12432 out1fmt("trap -- %s %s\n",
12434 get_signame(signo));
12435 /* trap_ptr != trap only if we are in special-cased `trap` code.
12436 * In this case, we will exit very soon, no need to free(). */
12437 /* if (trap_ptr != trap && tp[0]) */
12442 if (trap_ptr != trap) {
12455 signo = get_signum(*ap);
12457 /* Mimic bash message exactly */
12458 ash_msg("%s: invalid signal specification", *ap);
12464 if (LONE_DASH(action))
12467 action = ckstrdup(action);
12471 may_have_traps = 1;
12472 trap[signo] = action;
12483 /* ============ Builtins */
12485 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12487 * Lists available builtins
12489 static int FAST_FUNC
12490 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12496 "Built-in commands:\n"
12497 "------------------\n");
12498 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12499 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12500 builtintab[i].name + 1);
12506 #if ENABLE_FEATURE_SH_STANDALONE
12508 const char *a = applet_names;
12510 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12515 a += strlen(a) + 1;
12520 return EXIT_SUCCESS;
12522 #endif /* FEATURE_SH_EXTRA_QUIET */
12525 * The export and readonly commands.
12527 static int FAST_FUNC
12528 exportcmd(int argc UNUSED_PARAM, char **argv)
12534 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12536 if (nextopt("p") != 'p') {
12541 p = strchr(name, '=');
12545 vp = *findvar(hashvar(name), name);
12551 setvar(name, p, flag);
12552 } while ((name = *++aptr) != NULL);
12556 showvars(argv[0], flag, 0);
12561 * Delete a function if it exists.
12564 unsetfunc(const char *name)
12566 struct tblentry *cmdp;
12568 cmdp = cmdlookup(name, 0);
12569 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12570 delete_cmd_entry();
12574 * The unset builtin command. We unset the function before we unset the
12575 * variable to allow a function to be unset when there is a readonly variable
12576 * with the same name.
12578 static int FAST_FUNC
12579 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12586 while ((i = nextopt("vf")) != 0) {
12590 for (ap = argptr; *ap; ap++) {
12603 static const unsigned char timescmd_str[] ALIGN1 = {
12604 ' ', offsetof(struct tms, tms_utime),
12605 '\n', offsetof(struct tms, tms_stime),
12606 ' ', offsetof(struct tms, tms_cutime),
12607 '\n', offsetof(struct tms, tms_cstime),
12610 static int FAST_FUNC
12611 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12613 unsigned long clk_tck, s, t;
12614 const unsigned char *p;
12617 clk_tck = sysconf(_SC_CLK_TCK);
12622 t = *(clock_t *)(((char *) &buf) + p[1]);
12625 out1fmt("%lum%lu.%03lus%c",
12627 (t * 1000) / clk_tck,
12635 #if ENABLE_SH_MATH_SUPPORT
12637 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12638 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12640 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12642 static int FAST_FUNC
12643 letcmd(int argc UNUSED_PARAM, char **argv)
12649 ash_msg_and_raise_error("expression expected");
12651 i = ash_arith(*argv);
12659 * The read builtin. Options:
12660 * -r Do not interpret '\' specially
12661 * -s Turn off echo (tty only)
12662 * -n NCHARS Read NCHARS max
12663 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12664 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12665 * -u FD Read from given FD instead of fd 0
12666 * This uses unbuffered input, which may be avoidable in some cases.
12667 * TODO: bash also has:
12668 * -a ARRAY Read into array[0],[1],etc
12669 * -d DELIM End on DELIM char, not newline
12670 * -e Use line editing (tty only)
12672 static int FAST_FUNC
12673 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12675 char *opt_n = NULL;
12676 char *opt_p = NULL;
12677 char *opt_t = NULL;
12678 char *opt_u = NULL;
12679 int read_flags = 0;
12683 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12692 read_flags |= BUILTIN_READ_SILENT;
12698 read_flags |= BUILTIN_READ_RAW;
12708 r = shell_builtin_read(setvar2,
12710 bltinlookup("IFS"), /* can be NULL */
12718 if ((uintptr_t)r > 1)
12719 ash_msg_and_raise_error(r);
12721 return (uintptr_t)r;
12724 static int FAST_FUNC
12725 umaskcmd(int argc UNUSED_PARAM, char **argv)
12727 static const char permuser[3] ALIGN1 = "ugo";
12728 static const char permmode[3] ALIGN1 = "rwx";
12729 static const short permmask[] ALIGN2 = {
12730 S_IRUSR, S_IWUSR, S_IXUSR,
12731 S_IRGRP, S_IWGRP, S_IXGRP,
12732 S_IROTH, S_IWOTH, S_IXOTH
12735 /* TODO: use bb_parse_mode() instead */
12740 int symbolic_mode = 0;
12742 while (nextopt("S") != '\0') {
12753 if (symbolic_mode) {
12757 for (i = 0; i < 3; i++) {
12760 *p++ = permuser[i];
12762 for (j = 0; j < 3; j++) {
12763 if ((mask & permmask[3 * i + j]) == 0) {
12764 *p++ = permmode[j];
12772 out1fmt("%.4o\n", mask);
12775 if (isdigit((unsigned char) *ap)) {
12778 if (*ap >= '8' || *ap < '0')
12779 ash_msg_and_raise_error(msg_illnum, argv[1]);
12780 mask = (mask << 3) + (*ap - '0');
12781 } while (*++ap != '\0');
12784 mask = ~mask & 0777;
12785 if (!bb_parse_mode(ap, &mask)) {
12786 ash_msg_and_raise_error("illegal mode: %s", ap);
12788 umask(~mask & 0777);
12794 static int FAST_FUNC
12795 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12797 return shell_builtin_ulimit(argv);
12800 /* ============ main() and helpers */
12803 * Called to exit the shell.
12805 static void exitshell(void) NORETURN;
12813 status = exitstatus;
12814 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12815 if (setjmp(loc.loc)) {
12816 if (exception_type == EXEXIT)
12817 /* dash bug: it just does _exit(exitstatus) here
12818 * but we have to do setjobctl(0) first!
12819 * (bug is still not fixed in dash-0.5.3 - if you run dash
12820 * under Midnight Commander, on exit from dash MC is backgrounded) */
12821 status = exitstatus;
12824 exception_handler = &loc;
12831 flush_stdout_stderr();
12841 /* from input.c: */
12842 /* we will never free this */
12843 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12846 signal(SIGCHLD, SIG_DFL);
12847 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12848 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12850 signal(SIGHUP, SIG_DFL);
12856 struct stat st1, st2;
12859 for (envp = environ; envp && *envp; envp++) {
12860 if (strchr(*envp, '=')) {
12861 setvareq(*envp, VEXPORT|VTEXTFIXED);
12865 setvar("PPID", utoa(getppid()), 0);
12867 p = lookupvar("PWD");
12869 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12870 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12877 * Process the shell command line arguments.
12880 procargs(char **argv)
12883 const char *xminusc;
12888 /* if (xargv[0]) - mmm, this is always true! */
12890 for (i = 0; i < NOPTS; i++)
12894 /* it already printed err message */
12895 raise_exception(EXERROR);
12899 if (*xargv == NULL) {
12901 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12904 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12908 for (i = 0; i < NOPTS; i++)
12909 if (optlist[i] == 2)
12914 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12919 } else if (!sflag) {
12920 setinputfile(*xargv, 0);
12923 commandname = arg0;
12926 shellparam.p = xargv;
12927 #if ENABLE_ASH_GETOPTS
12928 shellparam.optind = 1;
12929 shellparam.optoff = -1;
12931 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12933 shellparam.nparam++;
12940 * Read /etc/profile or .profile.
12943 read_profile(const char *name)
12947 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12956 * This routine is called when an error or an interrupt occurs in an
12957 * interactive shell and control is returned to the main command loop.
12965 /* from input.c: */
12966 g_parsefile->left_in_buffer = 0;
12967 g_parsefile->left_in_line = 0; /* clear input buffer */
12969 /* from parser.c: */
12972 /* from redir.c: */
12973 clearredir(/*drop:*/ 0);
12977 static short profile_buf[16384];
12978 extern int etext();
12982 * Main routine. We initialize things, parse the arguments, execute
12983 * profiles if we're a login shell, and then call cmdloop to execute
12984 * commands. The setjmp call sets up the location to jump to when an
12985 * exception occurs. When an exception occurs the variable "state"
12986 * is used to figure out how far we had gotten.
12988 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12989 int ash_main(int argc UNUSED_PARAM, char **argv)
12991 const char *shinit;
12992 volatile smallint state;
12993 struct jmploc jmploc;
12994 struct stackmark smark;
12996 /* Initialize global data */
13000 #if ENABLE_ASH_ALIAS
13006 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13009 #if ENABLE_FEATURE_EDITING
13010 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13013 if (setjmp(jmploc.loc)) {
13019 e = exception_type;
13023 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13027 outcslow('\n', stderr);
13030 popstackmark(&smark);
13031 FORCE_INT_ON; /* enable interrupts */
13040 exception_handler = &jmploc;
13043 TRACE(("Shell args: "));
13044 trace_puts_args(argv);
13046 rootpid = getpid();
13049 setstackmark(&smark);
13052 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13054 const char *hp = lookupvar("HISTFILE");
13057 hp = lookupvar("HOME");
13059 char *defhp = concat_path_file(hp, ".ash_history");
13060 setvar("HISTFILE", defhp, 0);
13066 if (/* argv[0] && */ argv[0][0] == '-')
13070 read_profile("/etc/profile");
13073 read_profile(".profile");
13079 getuid() == geteuid() && getgid() == getegid() &&
13083 shinit = lookupvar("ENV");
13084 if (shinit != NULL && *shinit != '\0') {
13085 read_profile(shinit);
13091 /* evalstring pushes parsefile stack.
13092 * Ensure we don't falsely claim that 0 (stdin)
13093 * is one of stacked source fds.
13094 * Testcase: ash -c 'exec 1>&0' must not complain. */
13095 // if (!sflag) g_parsefile->pf_fd = -1;
13096 // ^^ not necessary since now we special-case fd 0
13097 // in is_hidden_fd() to not be considered "hidden fd"
13098 evalstring(minusc, 0);
13101 if (sflag || minusc == NULL) {
13102 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13104 const char *hp = lookupvar("HISTFILE");
13106 line_input_state->hist_file = hp;
13109 state4: /* XXX ??? - why isn't this before the "if" statement */
13117 extern void _mcleanup(void);
13121 TRACE(("End of main reached\n"));
13128 * Copyright (c) 1989, 1991, 1993, 1994
13129 * The Regents of the University of California. All rights reserved.
13131 * This code is derived from software contributed to Berkeley by
13132 * Kenneth Almquist.
13134 * Redistribution and use in source and binary forms, with or without
13135 * modification, are permitted provided that the following conditions
13137 * 1. Redistributions of source code must retain the above copyright
13138 * notice, this list of conditions and the following disclaimer.
13139 * 2. Redistributions in binary form must reproduce the above copyright
13140 * notice, this list of conditions and the following disclaimer in the
13141 * documentation and/or other materials provided with the distribution.
13142 * 3. Neither the name of the University nor the names of its contributors
13143 * may be used to endorse or promote products derived from this software
13144 * without specific prior written permission.
13146 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13147 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13148 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13149 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13150 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13151 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13152 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13153 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13154 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13155 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF