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 support for getopts builtin in ash.
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 in 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 in 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 in 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" function 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 *var_value) FAST_FUNC;
1885 # define chkmail() ((void)0)
1887 static void changepath(const char *) FAST_FUNC;
1888 #if ENABLE_ASH_RANDOM_SUPPORT
1889 static void change_random(const char *) FAST_FUNC;
1892 static const struct {
1894 const char *var_text;
1895 void (*var_func)(const char *) FAST_FUNC;
1896 } varinit_data[] = {
1897 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1899 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1900 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1902 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1903 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1904 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1905 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1906 #if ENABLE_ASH_GETOPTS
1907 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1909 #if ENABLE_ASH_RANDOM_SUPPORT
1910 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1912 #if ENABLE_LOCALE_SUPPORT
1913 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1914 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1916 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1917 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1923 struct globals_var {
1924 struct shparam shellparam; /* $@ current positional parameters */
1925 struct redirtab *redirlist;
1927 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1928 struct var *vartab[VTABSIZE];
1929 struct var varinit[ARRAY_SIZE(varinit_data)];
1931 extern struct globals_var *const ash_ptr_to_globals_var;
1932 #define G_var (*ash_ptr_to_globals_var)
1933 #define shellparam (G_var.shellparam )
1934 //#define redirlist (G_var.redirlist )
1935 #define g_nullredirs (G_var.g_nullredirs )
1936 #define preverrout_fd (G_var.preverrout_fd)
1937 #define vartab (G_var.vartab )
1938 #define varinit (G_var.varinit )
1939 #define INIT_G_var() do { \
1941 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1943 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1944 varinit[i].flags = varinit_data[i].flags; \
1945 varinit[i].var_text = varinit_data[i].var_text; \
1946 varinit[i].var_func = varinit_data[i].var_func; \
1950 #define vifs varinit[0]
1952 # define vmail (&vifs)[1]
1953 # define vmpath (&vmail)[1]
1954 # define vpath (&vmpath)[1]
1956 # define vpath (&vifs)[1]
1958 #define vps1 (&vpath)[1]
1959 #define vps2 (&vps1)[1]
1960 #define vps4 (&vps2)[1]
1961 #if ENABLE_ASH_GETOPTS
1962 # define voptind (&vps4)[1]
1963 # if ENABLE_ASH_RANDOM_SUPPORT
1964 # define vrandom (&voptind)[1]
1967 # if ENABLE_ASH_RANDOM_SUPPORT
1968 # define vrandom (&vps4)[1]
1973 * The following macros access the values of the above variables.
1974 * They have to skip over the name. They return the null string
1975 * for unset variables.
1977 #define ifsval() (vifs.var_text + 4)
1978 #define ifsset() ((vifs.flags & VUNSET) == 0)
1980 # define mailval() (vmail.var_text + 5)
1981 # define mpathval() (vmpath.var_text + 9)
1982 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1984 #define pathval() (vpath.var_text + 5)
1985 #define ps1val() (vps1.var_text + 4)
1986 #define ps2val() (vps2.var_text + 4)
1987 #define ps4val() (vps4.var_text + 4)
1988 #if ENABLE_ASH_GETOPTS
1989 # define optindval() (voptind.var_text + 7)
1992 #if ENABLE_ASH_GETOPTS
1993 static void FAST_FUNC
1994 getoptsreset(const char *value)
1996 shellparam.optind = number(value);
1997 shellparam.optoff = -1;
2001 /* math.h has these, otherwise define our private copies */
2002 #if !ENABLE_SH_MATH_SUPPORT
2003 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
2004 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
2006 * Return the pointer to the first char which is not part of a legal variable name
2007 * (a letter or underscore followed by letters, underscores, and digits).
2010 endofname(const char *name)
2012 if (!is_name(*name))
2015 if (!is_in_name(*name))
2023 * Compares two strings up to the first = or '\0'. The first
2024 * string must be terminated by '='; the second may be terminated by
2025 * either '=' or '\0'.
2028 varcmp(const char *p, const char *q)
2032 while ((c = *p) == (d = *q)) {
2047 * Find the appropriate entry in the hash table from the name.
2049 static struct var **
2050 hashvar(const char *p)
2054 hashval = ((unsigned char) *p) << 4;
2055 while (*p && *p != '=')
2056 hashval += (unsigned char) *p++;
2057 return &vartab[hashval % VTABSIZE];
2061 vpcmp(const void *a, const void *b)
2063 return varcmp(*(const char **)a, *(const char **)b);
2067 * This routine initializes the builtin variables.
2077 * PS1 depends on uid
2079 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2080 vps1.var_text = "PS1=\\w \\$ ";
2083 vps1.var_text = "PS1=# ";
2086 end = vp + ARRAY_SIZE(varinit);
2088 vpp = hashvar(vp->var_text);
2091 } while (++vp < end);
2094 static struct var **
2095 findvar(struct var **vpp, const char *name)
2097 for (; *vpp; vpp = &(*vpp)->next) {
2098 if (varcmp((*vpp)->var_text, name) == 0) {
2106 * Find the value of a variable. Returns NULL if not set.
2108 static const char* FAST_FUNC
2109 lookupvar(const char *name)
2113 v = *findvar(hashvar(name), name);
2115 #if ENABLE_ASH_RANDOM_SUPPORT
2117 * Dynamic variables are implemented roughly the same way they are
2118 * in bash. Namely, they're "special" so long as they aren't unset.
2119 * As soon as they're unset, they're no longer dynamic, and dynamic
2120 * lookup will no longer happen at that point. -- PFM.
2122 if (v->flags & VDYNAMIC)
2125 if (!(v->flags & VUNSET))
2126 return var_end(v->var_text);
2132 * Search the environment of a builtin command.
2135 bltinlookup(const char *name)
2139 for (sp = cmdenviron; sp; sp = sp->next) {
2140 if (varcmp(sp->text, name) == 0)
2141 return var_end(sp->text);
2143 return lookupvar(name);
2147 * Same as setvar except that the variable and value are passed in
2148 * the first argument as name=value. Since the first argument will
2149 * be actually stored in the table, it should not be a string that
2151 * Called with interrupts off.
2154 setvareq(char *s, int flags)
2156 struct var *vp, **vpp;
2159 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2160 vp = *findvar(vpp, s);
2162 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2165 if (flags & VNOSAVE)
2168 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2174 if (vp->var_func && !(flags & VNOFUNC))
2175 vp->var_func(var_end(s));
2177 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2178 free((char*)vp->var_text);
2180 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2182 /* variable s is not found */
2185 vp = ckzalloc(sizeof(*vp));
2187 /*vp->func = NULL; - ckzalloc did it */
2190 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2197 * Set the value of a variable. The flags argument is ored with the
2198 * flags of the variable. If val is NULL, the variable is unset.
2201 setvar(const char *name, const char *val, int flags)
2209 q = endofname(name);
2210 p = strchrnul(q, '=');
2212 if (!namelen || p != q)
2213 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2218 vallen = strlen(val);
2222 nameeq = ckmalloc(namelen + vallen + 2);
2223 p = memcpy(nameeq, name, namelen) + namelen;
2226 p = memcpy(p, val, vallen) + vallen;
2229 setvareq(nameeq, flags | VNOSAVE);
2233 static void FAST_FUNC
2234 setvar2(const char *name, const char *val)
2236 setvar(name, val, 0);
2239 #if ENABLE_ASH_GETOPTS
2241 * Safe version of setvar, returns 1 on success 0 on failure.
2244 setvarsafe(const char *name, const char *val, int flags)
2247 volatile int saveint;
2248 struct jmploc *volatile savehandler = exception_handler;
2249 struct jmploc jmploc;
2252 if (setjmp(jmploc.loc))
2255 exception_handler = &jmploc;
2256 setvar(name, val, flags);
2259 exception_handler = savehandler;
2260 RESTORE_INT(saveint);
2266 * Unset the specified variable.
2269 unsetvar(const char *s)
2275 vpp = findvar(hashvar(s), s);
2279 int flags = vp->flags;
2282 if (flags & VREADONLY)
2284 #if ENABLE_ASH_RANDOM_SUPPORT
2285 vp->flags &= ~VDYNAMIC;
2289 if ((flags & VSTRFIXED) == 0) {
2291 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2292 free((char*)vp->var_text);
2298 vp->flags &= ~VEXPORT;
2308 * Process a linked list of variable assignments.
2311 listsetvar(struct strlist *list_set_var, int flags)
2313 struct strlist *lp = list_set_var;
2319 setvareq(lp->text, flags);
2326 * Generate a list of variables satisfying the given conditions.
2329 listvars(int on, int off, char ***end)
2340 for (vp = *vpp; vp; vp = vp->next) {
2341 if ((vp->flags & mask) == on) {
2342 if (ep == stackstrend())
2343 ep = growstackstr();
2344 *ep++ = (char*)vp->var_text;
2347 } while (++vpp < vartab + VTABSIZE);
2348 if (ep == stackstrend())
2349 ep = growstackstr();
2353 return grabstackstr(ep);
2357 /* ============ Path search helper
2359 * The variable path (passed by reference) should be set to the start
2360 * of the path before the first call; path_advance will update
2361 * this value as it proceeds. Successive calls to path_advance will return
2362 * the possible path expansions in sequence. If an option (indicated by
2363 * a percent sign) appears in the path entry then the global variable
2364 * pathopt will be set to point to it; otherwise pathopt will be set to
2367 static const char *pathopt; /* set by path_advance */
2370 path_advance(const char **path, const char *name)
2380 for (p = start; *p && *p != ':' && *p != '%'; p++)
2382 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2383 while (stackblocksize() < len)
2387 memcpy(q, start, p - start);
2395 while (*p && *p != ':')
2402 return stalloc(len);
2406 /* ============ Prompt */
2408 static smallint doprompt; /* if set, prompt the user */
2409 static smallint needprompt; /* true if interactive and at start of line */
2411 #if ENABLE_FEATURE_EDITING
2412 static line_input_t *line_input_state;
2413 static const char *cmdedit_prompt;
2415 putprompt(const char *s)
2417 if (ENABLE_ASH_EXPAND_PRMT) {
2418 free((char*)cmdedit_prompt);
2419 cmdedit_prompt = ckstrdup(s);
2426 putprompt(const char *s)
2432 #if ENABLE_ASH_EXPAND_PRMT
2433 /* expandstr() needs parsing machinery, so it is far away ahead... */
2434 static const char *expandstr(const char *ps);
2436 #define expandstr(s) s
2440 setprompt_if(smallint do_set, int whichprompt)
2443 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2450 switch (whichprompt) {
2460 #if ENABLE_ASH_EXPAND_PRMT
2461 setstackmark(&smark);
2462 stalloc(stackblocksize());
2464 putprompt(expandstr(prompt));
2465 #if ENABLE_ASH_EXPAND_PRMT
2466 popstackmark(&smark);
2471 /* ============ The cd and pwd commands */
2473 #define CD_PHYSICAL 1
2483 while ((i = nextopt("LP")) != '\0') {
2485 flags ^= CD_PHYSICAL;
2494 * Update curdir (the name of the current directory) in response to a
2498 updatepwd(const char *dir)
2505 cdcomppath = ststrdup(dir);
2508 if (curdir == nullstr)
2510 new = stack_putstr(curdir, new);
2512 new = makestrspace(strlen(dir) + 2, new);
2513 lim = (char *)stackblock() + 1;
2517 if (new > lim && *lim == '/')
2522 if (dir[1] == '/' && dir[2] != '/') {
2528 p = strtok(cdcomppath, "/");
2532 if (p[1] == '.' && p[2] == '\0') {
2544 new = stack_putstr(p, new);
2552 return stackblock();
2556 * Find out what the current directory is. If we already know the current
2557 * directory, this routine returns immediately.
2562 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2563 return dir ? dir : nullstr;
2567 setpwd(const char *val, int setold)
2571 oldcur = dir = curdir;
2574 setvar("OLDPWD", oldcur, VEXPORT);
2577 if (physdir != nullstr) {
2578 if (physdir != oldcur)
2582 if (oldcur == val || !val) {
2588 dir = ckstrdup(val);
2589 if (oldcur != dir && oldcur != nullstr) {
2594 setvar("PWD", dir, VEXPORT);
2597 static void hashcd(void);
2600 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2601 * know that the current directory has changed.
2604 docd(const char *dest, int flags)
2606 const char *dir = NULL;
2609 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2612 if (!(flags & CD_PHYSICAL)) {
2613 dir = updatepwd(dest);
2627 static int FAST_FUNC
2628 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2640 dest = bltinlookup("HOME");
2641 else if (LONE_DASH(dest)) {
2642 dest = bltinlookup("OLDPWD");
2664 path = bltinlookup("CDPATH");
2673 p = path_advance(&path, dest);
2674 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2678 if (!docd(p, flags))
2683 ash_msg_and_raise_error("can't cd to %s", dest);
2686 if (flags & CD_PRINT)
2687 out1fmt("%s\n", curdir);
2691 static int FAST_FUNC
2692 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2695 const char *dir = curdir;
2699 if (physdir == nullstr)
2703 out1fmt("%s\n", dir);
2708 /* ============ ... */
2711 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2713 /* Syntax classes */
2714 #define CWORD 0 /* character is nothing special */
2715 #define CNL 1 /* newline character */
2716 #define CBACK 2 /* a backslash character */
2717 #define CSQUOTE 3 /* single quote */
2718 #define CDQUOTE 4 /* double quote */
2719 #define CENDQUOTE 5 /* a terminating quote */
2720 #define CBQUOTE 6 /* backwards single quote */
2721 #define CVAR 7 /* a dollar sign */
2722 #define CENDVAR 8 /* a '}' character */
2723 #define CLP 9 /* a left paren in arithmetic */
2724 #define CRP 10 /* a right paren in arithmetic */
2725 #define CENDFILE 11 /* end of file */
2726 #define CCTL 12 /* like CWORD, except it must be escaped */
2727 #define CSPCL 13 /* these terminate a word */
2728 #define CIGN 14 /* character should be ignored */
2731 #if ENABLE_ASH_ALIAS
2735 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2737 #if ENABLE_SH_MATH_SUPPORT
2738 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2740 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2742 static const uint16_t S_I_T[] = {
2743 #if ENABLE_ASH_ALIAS
2744 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2746 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2747 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2748 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2749 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2750 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2751 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2752 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2753 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2754 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2755 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2756 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2757 #if !USE_SIT_FUNCTION
2758 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2759 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2760 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2764 /* Constants below must match table above */
2766 #if ENABLE_ASH_ALIAS
2767 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2769 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2770 CNL_CNL_CNL_CNL , /* 2 */
2771 CWORD_CCTL_CCTL_CWORD , /* 3 */
2772 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2773 CVAR_CVAR_CWORD_CVAR , /* 5 */
2774 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2775 CSPCL_CWORD_CWORD_CLP , /* 7 */
2776 CSPCL_CWORD_CWORD_CRP , /* 8 */
2777 CBACK_CBACK_CCTL_CBACK , /* 9 */
2778 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2779 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2780 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2781 CWORD_CWORD_CWORD_CWORD , /* 13 */
2782 CCTL_CCTL_CCTL_CCTL , /* 14 */
2785 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2786 * caller must ensure proper cast on it if c is *char_ptr!
2788 /* Values for syntax param */
2789 #define BASESYNTAX 0 /* not in quotes */
2790 #define DQSYNTAX 1 /* in double quotes */
2791 #define SQSYNTAX 2 /* in single quotes */
2792 #define ARISYNTAX 3 /* in arithmetic */
2793 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2795 #if USE_SIT_FUNCTION
2798 SIT(int c, int syntax)
2800 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2801 # if ENABLE_ASH_ALIAS
2802 static const uint8_t syntax_index_table[] ALIGN1 = {
2803 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2804 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2805 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2809 static const uint8_t syntax_index_table[] ALIGN1 = {
2810 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2811 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2812 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2821 # if ENABLE_ASH_ALIAS
2827 /* Cast is purely for paranoia here,
2828 * just in case someone passed signed char to us */
2829 if ((unsigned char)c >= CTL_FIRST
2830 && (unsigned char)c <= CTL_LAST
2834 s = strchrnul(spec_symbls, c);
2837 indx = syntax_index_table[s - spec_symbls];
2839 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2842 #else /* !USE_SIT_FUNCTION */
2844 static const uint8_t syntax_index_table[] = {
2845 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2846 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2856 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2857 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2879 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2880 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2881 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2883 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2884 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2885 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2886 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2887 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2888 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2889 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2890 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2891 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2892 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2893 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2894 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2901 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2904 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2905 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2906 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2907 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2908 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2909 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2910 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2938 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2939 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2940 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2943 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2971 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2972 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2973 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2974 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2976 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2977 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2978 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2979 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2980 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2981 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2982 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2983 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3102 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3103 # if ENABLE_ASH_ALIAS
3104 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3108 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3110 #endif /* !USE_SIT_FUNCTION */
3113 /* ============ Alias handling */
3115 #if ENABLE_ASH_ALIAS
3117 #define ALIASINUSE 1
3128 static struct alias **atab; // [ATABSIZE];
3129 #define INIT_G_alias() do { \
3130 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3134 static struct alias **
3135 __lookupalias(const char *name) {
3136 unsigned int hashval;
3143 ch = (unsigned char)*p;
3147 ch = (unsigned char)*++p;
3149 app = &atab[hashval % ATABSIZE];
3151 for (; *app; app = &(*app)->next) {
3152 if (strcmp(name, (*app)->name) == 0) {
3160 static struct alias *
3161 lookupalias(const char *name, int check)
3163 struct alias *ap = *__lookupalias(name);
3165 if (check && ap && (ap->flag & ALIASINUSE))
3170 static struct alias *
3171 freealias(struct alias *ap)
3175 if (ap->flag & ALIASINUSE) {
3176 ap->flag |= ALIASDEAD;
3188 setalias(const char *name, const char *val)
3190 struct alias *ap, **app;
3192 app = __lookupalias(name);
3196 if (!(ap->flag & ALIASINUSE)) {
3199 ap->val = ckstrdup(val);
3200 ap->flag &= ~ALIASDEAD;
3203 ap = ckzalloc(sizeof(struct alias));
3204 ap->name = ckstrdup(name);
3205 ap->val = ckstrdup(val);
3206 /*ap->flag = 0; - ckzalloc did it */
3207 /*ap->next = NULL;*/
3214 unalias(const char *name)
3218 app = __lookupalias(name);
3222 *app = freealias(*app);
3233 struct alias *ap, **app;
3237 for (i = 0; i < ATABSIZE; i++) {
3239 for (ap = *app; ap; ap = *app) {
3240 *app = freealias(*app);
3250 printalias(const struct alias *ap)
3252 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3256 * TODO - sort output
3258 static int FAST_FUNC
3259 aliascmd(int argc UNUSED_PARAM, char **argv)
3268 for (i = 0; i < ATABSIZE; i++) {
3269 for (ap = atab[i]; ap; ap = ap->next) {
3275 while ((n = *++argv) != NULL) {
3276 v = strchr(n+1, '=');
3277 if (v == NULL) { /* n+1: funny ksh stuff */
3278 ap = *__lookupalias(n);
3280 fprintf(stderr, "%s: %s not found\n", "alias", n);
3293 static int FAST_FUNC
3294 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3298 while ((i = nextopt("a")) != '\0') {
3304 for (i = 0; *argptr; argptr++) {
3305 if (unalias(*argptr)) {
3306 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3314 #endif /* ASH_ALIAS */
3317 /* ============ jobs.c */
3319 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3322 #define FORK_NOJOB 2
3324 /* mode flags for showjob(s) */
3325 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3326 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3327 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3330 * A job structure contains information about a job. A job is either a
3331 * single process or a set of processes contained in a pipeline. In the
3332 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3336 pid_t ps_pid; /* process id */
3337 int ps_status; /* last process status from wait() */
3338 char *ps_cmd; /* text of command being run */
3342 struct procstat ps0; /* status of process */
3343 struct procstat *ps; /* status or processes when more than one */
3345 int stopstatus; /* status of a stopped job */
3348 nprocs: 16, /* number of processes */
3350 #define JOBRUNNING 0 /* at least one proc running */
3351 #define JOBSTOPPED 1 /* all procs are stopped */
3352 #define JOBDONE 2 /* all procs are completed */
3354 sigint: 1, /* job was killed by SIGINT */
3355 jobctl: 1, /* job running under job control */
3357 waited: 1, /* true if this entry has been waited for */
3358 used: 1, /* true if this entry is in used */
3359 changed: 1; /* true if status has changed */
3360 struct job *prev_job; /* previous job */
3363 static struct job *makejob(/*union node *,*/ int);
3364 static int forkshell(struct job *, union node *, int);
3365 static int waitforjob(struct job *);
3368 enum { doing_jobctl = 0 };
3369 #define setjobctl(on) do {} while (0)
3371 static smallint doing_jobctl; //references:8
3372 static void setjobctl(int);
3379 ignoresig(int signo)
3381 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3382 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3383 /* No, need to do it */
3384 signal(signo, SIG_IGN);
3386 sigmode[signo - 1] = S_HARD_IGN;
3390 * Only one usage site - in setsignal()
3393 signal_handler(int signo)
3395 gotsig[signo - 1] = 1;
3397 if (signo == SIGINT && !trap[SIGINT]) {
3398 if (!suppress_int) {
3400 raise_interrupt(); /* does not return */
3404 pending_sig = signo;
3409 * Set the signal handler for the specified signal. The routine figures
3410 * out what it should be set to.
3413 setsignal(int signo)
3416 char cur_act, new_act;
3417 struct sigaction act;
3421 if (t != NULL) { /* trap for this sig is set */
3423 if (t[0] == '\0') /* trap is "": ignore this sig */
3427 if (rootshell && new_act == S_DFL) {
3430 if (iflag || minusc || sflag == 0)
3439 * "In all cases, bash ignores SIGQUIT. Non-builtin
3440 * commands run by bash have signal handlers
3441 * set to the values inherited by the shell
3442 * from its parent". */
3458 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3459 //whereas we have to restore it to what shell got on entry
3460 //from the parent. See comment above
3462 t = &sigmode[signo - 1];
3465 /* current setting is not yet known */
3466 if (sigaction(signo, NULL, &act)) {
3467 /* pretend it worked; maybe we should give a warning,
3468 * but other shells don't. We don't alter sigmode,
3469 * so we retry every time.
3470 * btw, in Linux it never fails. --vda */
3473 if (act.sa_handler == SIG_IGN) {
3474 cur_act = S_HARD_IGN;
3476 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3478 cur_act = S_IGN; /* don't hard ignore these */
3482 if (cur_act == S_HARD_IGN || cur_act == new_act)
3485 act.sa_handler = SIG_DFL;
3488 act.sa_handler = signal_handler;
3489 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3490 sigfillset(&act.sa_mask); /* ditto */
3493 act.sa_handler = SIG_IGN;
3496 sigaction_set(signo, &act);
3501 /* mode flags for set_curjob */
3502 #define CUR_DELETE 2
3503 #define CUR_RUNNING 1
3504 #define CUR_STOPPED 0
3506 /* mode flags for dowait */
3507 #define DOWAIT_NONBLOCK WNOHANG
3508 #define DOWAIT_BLOCK 0
3511 /* pgrp of shell on invocation */
3512 static int initialpgrp; //references:2
3513 static int ttyfd = -1; //5
3516 static struct job *jobtab; //5
3518 static unsigned njobs; //4
3520 static struct job *curjob; //lots
3521 /* number of presumed living untracked jobs */
3522 static int jobless; //4
3525 set_curjob(struct job *jp, unsigned mode)
3528 struct job **jpp, **curp;
3530 /* first remove from list */
3531 jpp = curp = &curjob;
3536 jpp = &jp1->prev_job;
3538 *jpp = jp1->prev_job;
3540 /* Then re-insert in correct position */
3548 /* job being deleted */
3551 /* newly created job or backgrounded job,
3552 put after all stopped jobs. */
3556 if (!jp1 || jp1->state != JOBSTOPPED)
3559 jpp = &jp1->prev_job;
3565 /* newly stopped job - becomes curjob */
3566 jp->prev_job = *jpp;
3574 jobno(const struct job *jp)
3576 return jp - jobtab + 1;
3581 * Convert a job name to a job structure.
3584 #define getjob(name, getctl) getjob(name)
3587 getjob(const char *name, int getctl)
3591 const char *err_msg = "%s: no such job";
3595 char *(*match)(const char *, const char *);
3610 if (c == '+' || c == '%') {
3612 err_msg = "No current job";
3618 err_msg = "No previous job";
3629 jp = jobtab + num - 1;
3644 if (match(jp->ps[0].ps_cmd, p)) {
3648 err_msg = "%s: ambiguous";
3658 err_msg = "job %s not created under job control";
3659 if (getctl && jp->jobctl == 0)
3664 ash_msg_and_raise_error(err_msg, name);
3668 * Mark a job structure as unused.
3671 freejob(struct job *jp)
3673 struct procstat *ps;
3677 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3678 if (ps->ps_cmd != nullstr)
3681 if (jp->ps != &jp->ps0)
3684 set_curjob(jp, CUR_DELETE);
3690 xtcsetpgrp(int fd, pid_t pgrp)
3692 if (tcsetpgrp(fd, pgrp))
3693 ash_msg_and_raise_error("can't set tty process group (%m)");
3697 * Turn job control on and off.
3699 * Note: This code assumes that the third arg to ioctl is a character
3700 * pointer, which is true on Berkeley systems but not System V. Since
3701 * System V doesn't have job control yet, this isn't a problem now.
3703 * Called with interrupts off.
3711 if (on == doing_jobctl || rootshell == 0)
3715 ofd = fd = open(_PATH_TTY, O_RDWR);
3717 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3718 * That sometimes helps to acquire controlling tty.
3719 * Obviously, a workaround for bugs when someone
3720 * failed to provide a controlling tty to bash! :) */
3726 fd = fcntl(fd, F_DUPFD, 10);
3731 /* fd is a tty at this point */
3732 close_on_exec_on(fd);
3733 do { /* while we are in the background */
3734 pgrp = tcgetpgrp(fd);
3737 ash_msg("can't access tty; job control turned off");
3741 if (pgrp == getpgrp())
3752 xtcsetpgrp(fd, pgrp);
3754 /* turning job control off */
3757 /* was xtcsetpgrp, but this can make exiting ash
3758 * loop forever if pty is already deleted */
3759 tcsetpgrp(fd, pgrp);
3773 static int FAST_FUNC
3774 killcmd(int argc, char **argv)
3777 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3779 if (argv[i][0] == '%') {
3780 struct job *jp = getjob(argv[i], 0);
3781 unsigned pid = jp->ps[0].ps_pid;
3782 /* Enough space for ' -NNN<nul>' */
3783 argv[i] = alloca(sizeof(int)*3 + 3);
3784 /* kill_main has matching code to expect
3785 * leading space. Needed to not confuse
3786 * negative pids with "kill -SIGNAL_NO" syntax */
3787 sprintf(argv[i], " -%u", pid);
3789 } while (argv[++i]);
3791 return kill_main(argc, argv);
3795 showpipe(struct job *jp /*, FILE *out*/)
3797 struct procstat *ps;
3798 struct procstat *psend;
3800 psend = jp->ps + jp->nprocs;
3801 for (ps = jp->ps + 1; ps < psend; ps++)
3802 printf(" | %s", ps->ps_cmd);
3803 outcslow('\n', stdout);
3804 flush_stdout_stderr();
3809 restartjob(struct job *jp, int mode)
3811 struct procstat *ps;
3817 if (jp->state == JOBDONE)
3819 jp->state = JOBRUNNING;
3820 pgid = jp->ps[0].ps_pid;
3821 if (mode == FORK_FG)
3822 xtcsetpgrp(ttyfd, pgid);
3823 killpg(pgid, SIGCONT);
3827 if (WIFSTOPPED(ps->ps_status)) {
3833 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3838 static int FAST_FUNC
3839 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3845 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3849 jp = getjob(*argv, 1);
3850 if (mode == FORK_BG) {
3851 set_curjob(jp, CUR_RUNNING);
3852 printf("[%d] ", jobno(jp));
3854 out1str(jp->ps[0].ps_cmd);
3855 showpipe(jp /*, stdout*/);
3856 retval = restartjob(jp, mode);
3857 } while (*argv && *++argv);
3863 sprint_status(char *s, int status, int sigonly)
3869 if (!WIFEXITED(status)) {
3871 if (WIFSTOPPED(status))
3872 st = WSTOPSIG(status);
3875 st = WTERMSIG(status);
3877 if (st == SIGINT || st == SIGPIPE)
3880 if (WIFSTOPPED(status))
3885 col = fmtstr(s, 32, strsignal(st));
3886 if (WCOREDUMP(status)) {
3887 col += fmtstr(s + col, 16, " (core dumped)");
3889 } else if (!sigonly) {
3890 st = WEXITSTATUS(status);
3892 col = fmtstr(s, 16, "Done(%d)", st);
3894 col = fmtstr(s, 16, "Done");
3901 dowait(int wait_flags, struct job *job)
3906 struct job *thisjob;
3909 TRACE(("dowait(0x%x) called\n", wait_flags));
3911 /* Do a wait system call. If job control is compiled in, we accept
3912 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3913 * NB: _not_ safe_waitpid, we need to detect EINTR */
3915 wait_flags |= WUNTRACED;
3916 pid = waitpid(-1, &status, wait_flags);
3917 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3918 pid, status, errno, strerror(errno)));
3924 for (jp = curjob; jp; jp = jp->prev_job) {
3925 struct procstat *ps;
3926 struct procstat *psend;
3927 if (jp->state == JOBDONE)
3931 psend = ps + jp->nprocs;
3933 if (ps->ps_pid == pid) {
3934 TRACE(("Job %d: changing status of proc %d "
3935 "from 0x%x to 0x%x\n",
3936 jobno(jp), pid, ps->ps_status, status));
3937 ps->ps_status = status;
3940 if (ps->ps_status == -1)
3943 if (state == JOBRUNNING)
3945 if (WIFSTOPPED(ps->ps_status)) {
3946 jp->stopstatus = ps->ps_status;
3950 } while (++ps < psend);
3955 if (!WIFSTOPPED(status))
3961 if (state != JOBRUNNING) {
3962 thisjob->changed = 1;
3964 if (thisjob->state != state) {
3965 TRACE(("Job %d: changing state from %d to %d\n",
3966 jobno(thisjob), thisjob->state, state));
3967 thisjob->state = state;
3969 if (state == JOBSTOPPED) {
3970 set_curjob(thisjob, CUR_STOPPED);
3979 if (thisjob && thisjob == job) {
3983 len = sprint_status(s, status, 1);
3994 blocking_wait_with_raise_on_sig(void)
3996 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
3997 if (pid <= 0 && pending_sig)
3998 raise_exception(EXSIG);
4004 showjob(FILE *out, struct job *jp, int mode)
4006 struct procstat *ps;
4007 struct procstat *psend;
4014 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4015 /* just output process (group) id of pipeline */
4016 fprintf(out, "%d\n", ps->ps_pid);
4020 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4025 else if (curjob && jp == curjob->prev_job)
4028 if (mode & SHOW_PIDS)
4029 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4031 psend = ps + jp->nprocs;
4033 if (jp->state == JOBRUNNING) {
4034 strcpy(s + col, "Running");
4035 col += sizeof("Running") - 1;
4037 int status = psend[-1].ps_status;
4038 if (jp->state == JOBSTOPPED)
4039 status = jp->stopstatus;
4040 col += sprint_status(s + col, status, 0);
4042 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4044 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4045 * or prints several "PID | <cmdN>" lines,
4046 * depending on SHOW_PIDS bit.
4047 * We do not print status of individual processes
4048 * between PID and <cmdN>. bash does it, but not very well:
4049 * first line shows overall job status, not process status,
4050 * making it impossible to know 1st process status.
4054 /* for each process */
4057 if (mode & SHOW_PIDS)
4058 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4060 fprintf(out, "%s%*c%s%s",
4062 33 - col >= 0 ? 33 - col : 0, ' ',
4063 ps == jp->ps ? "" : "| ",
4066 } while (++ps != psend);
4067 outcslow('\n', out);
4071 if (jp->state == JOBDONE) {
4072 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4078 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4079 * statuses have changed since the last call to showjobs.
4082 showjobs(FILE *out, int mode)
4086 TRACE(("showjobs(0x%x) called\n", mode));
4088 /* Handle all finished jobs */
4089 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4092 for (jp = curjob; jp; jp = jp->prev_job) {
4093 if (!(mode & SHOW_CHANGED) || jp->changed) {
4094 showjob(out, jp, mode);
4099 static int FAST_FUNC
4100 jobscmd(int argc UNUSED_PARAM, char **argv)
4105 while ((m = nextopt("lp")) != '\0') {
4109 mode |= SHOW_ONLY_PGID;
4115 showjob(stdout, getjob(*argv, 0), mode);
4118 showjobs(stdout, mode);
4125 /* Called only on finished or stopped jobs (no members are running) */
4127 getstatus(struct job *job)
4131 struct procstat *ps;
4133 /* Fetch last member's status */
4134 ps = job->ps + job->nprocs - 1;
4135 status = ps->ps_status;
4137 /* "set -o pipefail" mode: use last _nonzero_ status */
4138 while (status == 0 && --ps >= job->ps)
4139 status = ps->ps_status;
4142 retval = WEXITSTATUS(status);
4143 if (!WIFEXITED(status)) {
4145 retval = WSTOPSIG(status);
4146 if (!WIFSTOPPED(status))
4149 /* XXX: limits number of signals */
4150 retval = WTERMSIG(status);
4152 if (retval == SIGINT)
4158 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4159 jobno(job), job->nprocs, status, retval));
4163 static int FAST_FUNC
4164 waitcmd(int argc UNUSED_PARAM, char **argv)
4171 raise_exception(EXSIG);
4178 /* wait for all jobs */
4182 if (!jp) /* no running procs */
4184 if (jp->state == JOBRUNNING)
4189 blocking_wait_with_raise_on_sig();
4191 * "When bash is waiting for an asynchronous command via
4192 * the wait builtin, the reception of a signal for which a trap
4193 * has been set will cause the wait builtin to return immediately
4194 * with an exit status greater than 128, immediately after which
4195 * the trap is executed."
4197 * blocking_wait_with_raise_on_sig raises signal handlers
4198 * if it gets no pid (pid < 0). However,
4199 * if child sends us a signal *and immediately exits*,
4200 * blocking_wait_with_raise_on_sig gets pid > 0
4201 * and does not handle pending_sig. Check this case: */
4203 raise_exception(EXSIG);
4209 if (**argv != '%') {
4210 pid_t pid = number(*argv);
4215 if (job->ps[job->nprocs - 1].ps_pid == pid)
4217 job = job->prev_job;
4220 job = getjob(*argv, 0);
4221 /* loop until process terminated or stopped */
4222 while (job->state == JOBRUNNING)
4223 blocking_wait_with_raise_on_sig();
4225 retval = getstatus(job);
4238 struct job *jp, *jq;
4240 len = njobs * sizeof(*jp);
4242 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4244 offset = (char *)jp - (char *)jq;
4246 /* Relocate pointers */
4249 jq = (struct job *)((char *)jq + l);
4253 #define joff(p) ((struct job *)((char *)(p) + l))
4254 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4255 if (joff(jp)->ps == &jq->ps0)
4256 jmove(joff(jp)->ps);
4257 if (joff(jp)->prev_job)
4258 jmove(joff(jp)->prev_job);
4268 jp = (struct job *)((char *)jp + len);
4272 } while (--jq >= jp);
4277 * Return a new job structure.
4278 * Called with interrupts off.
4281 makejob(/*union node *node,*/ int nprocs)
4286 for (i = njobs, jp = jobtab; ; jp++) {
4293 if (jp->state != JOBDONE || !jp->waited)
4302 memset(jp, 0, sizeof(*jp));
4304 /* jp->jobctl is a bitfield.
4305 * "jp->jobctl |= jobctl" likely to give awful code */
4309 jp->prev_job = curjob;
4314 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4316 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4323 * Return a string identifying a command (to be printed by the
4326 static char *cmdnextc;
4329 cmdputs(const char *s)
4331 static const char vstype[VSTYPE + 1][3] = {
4332 "", "}", "-", "+", "?", "=",
4333 "%", "%%", "#", "##"
4334 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4337 const char *p, *str;
4341 unsigned char subtype = 0;
4345 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4347 while ((c = *p++) != '\0') {
4355 if ((subtype & VSTYPE) == VSLENGTH)
4359 if (!(subtype & VSQUOTE) == !(quoted & 1))
4365 str = "\"}" + !(quoted & 1);
4372 case CTLBACKQ+CTLQUOTE:
4375 #if ENABLE_SH_MATH_SUPPORT
4390 if ((subtype & VSTYPE) != VSNORMAL)
4392 str = vstype[subtype & VSTYPE];
4393 if (subtype & VSNUL)
4402 /* These can only happen inside quotes */
4415 while ((c = *str++) != '\0') {
4418 } /* while *p++ not NUL */
4421 USTPUTC('"', nextc);
4427 /* cmdtxt() and cmdlist() call each other */
4428 static void cmdtxt(union node *n);
4431 cmdlist(union node *np, int sep)
4433 for (; np; np = np->narg.next) {
4437 if (sep && np->narg.next)
4443 cmdtxt(union node *n)
4446 struct nodelist *lp;
4457 lp = n->npipe.cmdlist;
4475 cmdtxt(n->nbinary.ch1);
4491 cmdtxt(n->nif.test);
4493 if (n->nif.elsepart) {
4494 cmdtxt(n->nif.ifpart);
4496 n = n->nif.elsepart;
4514 cmdtxt(n->nbinary.ch1);
4524 cmdputs(n->nfor.var);
4526 cmdlist(n->nfor.args, 1);
4531 cmdputs(n->narg.text);
4535 cmdlist(n->ncmd.args, 1);
4536 cmdlist(n->ncmd.redirect, 0);
4549 cmdputs(n->ncase.expr->narg.text);
4551 for (np = n->ncase.cases; np; np = np->nclist.next) {
4552 cmdtxt(np->nclist.pattern);
4554 cmdtxt(np->nclist.body);
4568 #if ENABLE_ASH_BASH_COMPAT
4583 cmdputs(utoa(n->nfile.fd));
4585 if (n->type == NTOFD || n->type == NFROMFD) {
4586 cmdputs(utoa(n->ndup.dupfd));
4595 commandtext(union node *n)
4599 STARTSTACKSTR(cmdnextc);
4601 name = stackblock();
4602 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4603 name, cmdnextc, cmdnextc));
4604 return ckstrdup(name);
4609 * Fork off a subshell. If we are doing job control, give the subshell its
4610 * own process group. Jp is a job structure that the job is to be added to.
4611 * N is the command that will be evaluated by the child. Both jp and n may
4612 * be NULL. The mode parameter can be one of the following:
4613 * FORK_FG - Fork off a foreground process.
4614 * FORK_BG - Fork off a background process.
4615 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4616 * process group even if job control is on.
4618 * When job control is turned off, background processes have their standard
4619 * input redirected to /dev/null (except for the second and later processes
4622 * Called with interrupts off.
4625 * Clear traps on a fork.
4632 for (tp = trap; tp < &trap[NSIG]; tp++) {
4633 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4635 if (trap_ptr == trap)
4637 /* else: it "belongs" to trap_ptr vector, don't free */
4639 if ((tp - trap) != 0)
4640 setsignal(tp - trap);
4647 /* Lives far away from here, needed for forkchild */
4648 static void closescript(void);
4650 /* Called after fork(), in child */
4651 static NOINLINE void
4652 forkchild(struct job *jp, union node *n, int mode)
4656 TRACE(("Child shell %d\n", getpid()));
4660 /* man bash: "Non-builtin commands run by bash have signal handlers
4661 * set to the values inherited by the shell from its parent".
4662 * Do we do it correctly? */
4666 if (mode == FORK_NOJOB /* is it `xxx` ? */
4667 && n && n->type == NCMD /* is it single cmd? */
4668 /* && n->ncmd.args->type == NARG - always true? */
4669 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4670 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4671 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4673 TRACE(("Trap hack\n"));
4674 /* Awful hack for `trap` or $(trap).
4676 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4677 * contains an example where "trap" is executed in a subshell:
4679 * save_traps=$(trap)
4681 * eval "$save_traps"
4683 * Standard does not say that "trap" in subshell shall print
4684 * parent shell's traps. It only says that its output
4685 * must have suitable form, but then, in the above example
4686 * (which is not supposed to be normative), it implies that.
4688 * bash (and probably other shell) does implement it
4689 * (traps are reset to defaults, but "trap" still shows them),
4690 * but as a result, "trap" logic is hopelessly messed up:
4693 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4694 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4695 * # true | trap <--- trap is in subshell - no output (ditto)
4696 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4697 * trap -- 'echo Ho' SIGWINCH
4698 * # echo `(trap)` <--- in subshell in subshell - output
4699 * trap -- 'echo Ho' SIGWINCH
4700 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4701 * trap -- 'echo Ho' SIGWINCH
4703 * The rules when to forget and when to not forget traps
4704 * get really complex and nonsensical.
4706 * Our solution: ONLY bare $(trap) or `trap` is special.
4708 /* Save trap handler strings for trap builtin to print */
4709 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4710 /* Fall through into clearing traps */
4714 /* do job control only in root shell */
4716 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4719 if (jp->nprocs == 0)
4722 pgrp = jp->ps[0].ps_pid;
4723 /* this can fail because we are doing it in the parent also */
4725 if (mode == FORK_FG)
4726 xtcsetpgrp(ttyfd, pgrp);
4731 if (mode == FORK_BG) {
4732 /* man bash: "When job control is not in effect,
4733 * asynchronous commands ignore SIGINT and SIGQUIT" */
4736 if (jp->nprocs == 0) {
4738 if (open(bb_dev_null, O_RDONLY) != 0)
4739 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4743 if (iflag) { /* why if iflag only? */
4748 * "In all cases, bash ignores SIGQUIT. Non-builtin
4749 * commands run by bash have signal handlers
4750 * set to the values inherited by the shell
4752 * Take care of the second rule: */
4756 if (n && n->type == NCMD
4757 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4759 TRACE(("Job hack\n"));
4760 /* "jobs": we do not want to clear job list for it,
4761 * instead we remove only _its_ own_ job from job list.
4762 * This makes "jobs .... | cat" more useful.
4768 for (jp = curjob; jp; jp = jp->prev_job)
4773 /* Called after fork(), in parent */
4775 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4778 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4780 TRACE(("In parent shell: child = %d\n", pid));
4782 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4788 if (mode != FORK_NOJOB && jp->jobctl) {
4791 if (jp->nprocs == 0)
4794 pgrp = jp->ps[0].ps_pid;
4795 /* This can fail because we are doing it in the child also */
4799 if (mode == FORK_BG) {
4800 backgndpid = pid; /* set $! */
4801 set_curjob(jp, CUR_RUNNING);
4804 struct procstat *ps = &jp->ps[jp->nprocs++];
4807 ps->ps_cmd = nullstr;
4809 if (doing_jobctl && n)
4810 ps->ps_cmd = commandtext(n);
4816 forkshell(struct job *jp, union node *n, int mode)
4820 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4823 TRACE(("Fork failed, errno=%d", errno));
4826 ash_msg_and_raise_error("can't fork");
4829 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4830 forkchild(jp, n, mode);
4832 forkparent(jp, n, mode, pid);
4838 * Wait for job to finish.
4840 * Under job control we have the problem that while a child process
4841 * is running interrupts generated by the user are sent to the child
4842 * but not to the shell. This means that an infinite loop started by
4843 * an interactive user may be hard to kill. With job control turned off,
4844 * an interactive user may place an interactive program inside a loop.
4845 * If the interactive program catches interrupts, the user doesn't want
4846 * these interrupts to also abort the loop. The approach we take here
4847 * is to have the shell ignore interrupt signals while waiting for a
4848 * foreground process to terminate, and then send itself an interrupt
4849 * signal if the child process was terminated by an interrupt signal.
4850 * Unfortunately, some programs want to do a bit of cleanup and then
4851 * exit on interrupt; unless these processes terminate themselves by
4852 * sending a signal to themselves (instead of calling exit) they will
4853 * confuse this approach.
4855 * Called with interrupts off.
4858 waitforjob(struct job *jp)
4862 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4865 while (jp->state == JOBRUNNING) {
4866 /* In non-interactive shells, we _can_ get
4867 * a keyboard signal here and be EINTRed,
4868 * but we just loop back, waiting for command to complete.
4871 * "If bash is waiting for a command to complete and receives
4872 * a signal for which a trap has been set, the trap
4873 * will not be executed until the command completes."
4875 * Reality is that even if trap is not set, bash
4876 * will not act on the signal until command completes.
4877 * Try this. sleep5intoff.c:
4878 * #include <signal.h>
4879 * #include <unistd.h>
4882 * sigemptyset(&set);
4883 * sigaddset(&set, SIGINT);
4884 * sigaddset(&set, SIGQUIT);
4885 * sigprocmask(SIG_BLOCK, &set, NULL);
4889 * $ bash -c './sleep5intoff; echo hi'
4890 * ^C^C^C^C <--- pressing ^C once a second
4892 * $ bash -c './sleep5intoff; echo hi'
4893 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4896 dowait(DOWAIT_BLOCK, jp);
4903 xtcsetpgrp(ttyfd, rootpid);
4905 * This is truly gross.
4906 * If we're doing job control, then we did a TIOCSPGRP which
4907 * caused us (the shell) to no longer be in the controlling
4908 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4909 * intuit from the subprocess exit status whether a SIGINT
4910 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4912 if (jp->sigint) /* TODO: do the same with all signals */
4913 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4915 if (jp->state == JOBDONE)
4922 * return 1 if there are stopped jobs, otherwise 0
4934 if (jp && jp->state == JOBSTOPPED) {
4935 out2str("You have stopped jobs.\n");
4944 /* ============ redir.c
4946 * Code for dealing with input/output redirection.
4951 #define EMPTY -2 /* marks an unused slot in redirtab */
4952 #define CLOSED -3 /* marks a slot of previously-closed fd */
4955 * Open a file in noclobber mode.
4956 * The code was copied from bash.
4959 noclobberopen(const char *fname)
4962 struct stat finfo, finfo2;
4965 * If the file exists and is a regular file, return an error
4968 r = stat(fname, &finfo);
4969 if (r == 0 && S_ISREG(finfo.st_mode)) {
4975 * If the file was not present (r != 0), make sure we open it
4976 * exclusively so that if it is created before we open it, our open
4977 * will fail. Make sure that we do not truncate an existing file.
4978 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4979 * file was not a regular file, we leave O_EXCL off.
4982 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4983 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4985 /* If the open failed, return the file descriptor right away. */
4990 * OK, the open succeeded, but the file may have been changed from a
4991 * non-regular file to a regular file between the stat and the open.
4992 * We are assuming that the O_EXCL open handles the case where FILENAME
4993 * did not exist and is symlinked to an existing file between the stat
4998 * If we can open it and fstat the file descriptor, and neither check
4999 * revealed that it was a regular file, and the file has not been
5000 * replaced, return the file descriptor.
5002 if (fstat(fd, &finfo2) == 0
5003 && !S_ISREG(finfo2.st_mode)
5004 && finfo.st_dev == finfo2.st_dev
5005 && finfo.st_ino == finfo2.st_ino
5010 /* The file has been replaced. badness. */
5017 * Handle here documents. Normally we fork off a process to write the
5018 * data to a pipe. If the document is short, we can stuff the data in
5019 * the pipe without forking.
5021 /* openhere needs this forward reference */
5022 static void expandhere(union node *arg, int fd);
5024 openhere(union node *redir)
5030 ash_msg_and_raise_error("pipe call failed");
5031 if (redir->type == NHERE) {
5032 len = strlen(redir->nhere.doc->narg.text);
5033 if (len <= PIPE_BUF) {
5034 full_write(pip[1], redir->nhere.doc->narg.text, len);
5038 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5041 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5042 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5043 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5044 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5045 signal(SIGPIPE, SIG_DFL);
5046 if (redir->type == NHERE)
5047 full_write(pip[1], redir->nhere.doc->narg.text, len);
5049 expandhere(redir->nhere.doc, pip[1]);
5050 _exit(EXIT_SUCCESS);
5058 openredirect(union node *redir)
5063 switch (redir->nfile.type) {
5065 fname = redir->nfile.expfname;
5066 f = open(fname, O_RDONLY);
5071 fname = redir->nfile.expfname;
5072 f = open(fname, O_RDWR|O_CREAT, 0666);
5077 #if ENABLE_ASH_BASH_COMPAT
5080 /* Take care of noclobber mode. */
5082 fname = redir->nfile.expfname;
5083 f = noclobberopen(fname);
5090 fname = redir->nfile.expfname;
5091 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5096 fname = redir->nfile.expfname;
5097 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5105 /* Fall through to eliminate warning. */
5106 /* Our single caller does this itself */
5113 f = openhere(redir);
5119 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5121 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5125 * Copy a file descriptor to be >= to. Returns -1
5126 * if the source file descriptor is closed, EMPTY if there are no unused
5127 * file descriptors left.
5129 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5130 * old code was doing close(to) prior to copyfd() to achieve the same */
5132 COPYFD_EXACT = (int)~(INT_MAX),
5133 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5136 copyfd(int from, int to)
5140 if (to & COPYFD_EXACT) {
5141 to &= ~COPYFD_EXACT;
5143 newfd = dup2(from, to);
5145 newfd = fcntl(from, F_DUPFD, to);
5148 if (errno == EMFILE)
5150 /* Happens when source fd is not open: try "echo >&99" */
5151 ash_msg_and_raise_error("%d: %m", from);
5156 /* Struct def and variable are moved down to the first usage site */
5161 struct redirtab *next;
5164 struct two_fd_t two_fd[];
5166 #define redirlist (G_var.redirlist)
5168 static int need_to_remember(struct redirtab *rp, int fd)
5172 if (!rp) /* remembering was not requested */
5175 for (i = 0; i < rp->pair_count; i++) {
5176 if (rp->two_fd[i].orig == fd) {
5177 /* already remembered */
5184 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5185 static int is_hidden_fd(struct redirtab *rp, int fd)
5188 struct parsefile *pf;
5192 /* Check open scripts' fds */
5195 /* We skip pf_fd == 0 case because of the following case:
5196 * $ ash # running ash interactively
5198 * and in script.sh: "exec 9>&0".
5199 * Even though top-level pf_fd _is_ 0,
5200 * it's still ok to use it: "read" builtin uses it,
5201 * why should we cripple "exec" builtin?
5203 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5211 /* Check saved fds of redirects */
5212 fd |= COPYFD_RESTORE;
5213 for (i = 0; i < rp->pair_count; i++) {
5214 if (rp->two_fd[i].copy == fd) {
5222 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5223 * old file descriptors are stashed away so that the redirection can be
5224 * undone by calling popredir.
5226 /* flags passed to redirect */
5227 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5228 #define REDIR_SAVEFD2 03 /* set preverrout */
5230 redirect(union node *redir, int flags)
5232 struct redirtab *sv;
5237 int copied_fd2 = -1;
5247 if (flags & REDIR_PUSH) {
5248 union node *tmp = redir;
5251 #if ENABLE_ASH_BASH_COMPAT
5252 if (tmp->nfile.type == NTO2)
5255 tmp = tmp->nfile.next;
5257 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5258 sv->next = redirlist;
5259 sv->pair_count = sv_pos;
5261 sv->nullredirs = g_nullredirs - 1;
5263 while (sv_pos > 0) {
5265 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5271 fd = redir->nfile.fd;
5272 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5273 right_fd = redir->ndup.dupfd;
5274 //bb_error_msg("doing %d > %d", fd, right_fd);
5275 /* redirect from/to same file descriptor? */
5278 /* "echo >&10" and 10 is a fd opened to a sh script? */
5279 if (is_hidden_fd(sv, right_fd)) {
5280 errno = EBADF; /* as if it is closed */
5281 ash_msg_and_raise_error("%d: %m", right_fd);
5285 newfd = openredirect(redir); /* always >= 0 */
5287 /* Descriptor wasn't open before redirect.
5288 * Mark it for close in the future */
5289 if (need_to_remember(sv, fd)) {
5290 goto remember_to_close;
5295 #if ENABLE_ASH_BASH_COMPAT
5298 if (need_to_remember(sv, fd)) {
5299 /* Copy old descriptor */
5300 /* Careful to not accidentally "save"
5301 * to the same fd as right side fd in N>&M */
5302 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5303 i = fcntl(fd, F_DUPFD, minfd);
5304 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5305 * are closed in popredir() in the child, preventing them from leaking
5306 * into child. (popredir() also cleans up the mess in case of failures)
5311 /* Strange error (e.g. "too many files" EMFILE?) */
5315 ash_msg_and_raise_error("%d: %m", fd);
5318 /* EBADF: it is not open - good, remember to close it */
5321 } else { /* fd is open, save its copy */
5322 /* "exec fd>&-" should not close fds
5323 * which point to script file(s).
5324 * Force them to be restored afterwards */
5325 if (is_hidden_fd(sv, fd))
5326 i |= COPYFD_RESTORE;
5330 sv->two_fd[sv_pos].orig = fd;
5331 sv->two_fd[sv_pos].copy = i;
5335 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5336 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5337 /* Don't want to trigger debugging */
5341 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5343 } else if (fd != newfd) { /* move newfd to fd */
5344 copyfd(newfd, fd | COPYFD_EXACT);
5345 #if ENABLE_ASH_BASH_COMPAT
5346 if (!(redir->nfile.type == NTO2 && fd == 2))
5350 #if ENABLE_ASH_BASH_COMPAT
5351 if (redir->nfile.type == NTO2 && fd == 1) {
5352 /* We already redirected it to fd 1, now copy it to 2 */
5358 } while ((redir = redir->nfile.next) != NULL);
5361 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5362 preverrout_fd = copied_fd2;
5366 * Undo the effects of the last redirection.
5369 popredir(int drop, int restore)
5371 struct redirtab *rp;
5374 if (--g_nullredirs >= 0)
5378 for (i = 0; i < rp->pair_count; i++) {
5379 int fd = rp->two_fd[i].orig;
5380 int copy = rp->two_fd[i].copy;
5381 if (copy == CLOSED) {
5386 if (copy != EMPTY) {
5387 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5388 copy &= ~COPYFD_RESTORE;
5390 copyfd(copy, fd | COPYFD_EXACT);
5392 close(copy & ~COPYFD_RESTORE);
5395 redirlist = rp->next;
5396 g_nullredirs = rp->nullredirs;
5402 * Undo all redirections. Called on error or interrupt.
5406 * Discard all saved file descriptors.
5409 clearredir(int drop)
5415 popredir(drop, /*restore:*/ 0);
5420 redirectsafe(union node *redir, int flags)
5423 volatile int saveint;
5424 struct jmploc *volatile savehandler = exception_handler;
5425 struct jmploc jmploc;
5428 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5429 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5431 exception_handler = &jmploc;
5432 redirect(redir, flags);
5434 exception_handler = savehandler;
5435 if (err && exception_type != EXERROR)
5436 longjmp(exception_handler->loc, 1);
5437 RESTORE_INT(saveint);
5442 /* ============ Routines to expand arguments to commands
5444 * We have to deal with backquotes, shell variables, and file metacharacters.
5447 #if ENABLE_SH_MATH_SUPPORT
5449 ash_arith(const char *s)
5451 arith_state_t math_state;
5454 math_state.lookupvar = lookupvar;
5455 math_state.setvar = setvar2;
5456 //math_state.endofname = endofname;
5459 result = arith(&math_state, s);
5460 if (math_state.errmsg)
5461 ash_msg_and_raise_error(math_state.errmsg);
5471 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5472 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5473 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5474 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5475 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5476 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5477 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5478 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5479 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5483 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5484 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5485 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5486 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5487 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5490 * Structure specifying which parts of the string should be searched
5491 * for IFS characters.
5494 struct ifsregion *next; /* next region in list */
5495 int begoff; /* offset of start of region */
5496 int endoff; /* offset of end of region */
5497 int nulonly; /* search for nul bytes only */
5501 struct strlist *list;
5502 struct strlist **lastp;
5505 /* output of current string */
5506 static char *expdest;
5507 /* list of back quote expressions */
5508 static struct nodelist *argbackq;
5509 /* first struct in list of ifs regions */
5510 static struct ifsregion ifsfirst;
5511 /* last struct in list */
5512 static struct ifsregion *ifslastp;
5513 /* holds expanded arg list */
5514 static struct arglist exparg;
5519 #if !ENABLE_SH_MATH_SUPPORT
5520 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5521 typedef long arith_t;
5522 # define ARITH_FMT "%ld"
5529 expdest = makestrspace(32, expdest);
5530 len = fmtstr(expdest, 32, ARITH_FMT, num);
5531 STADJUST(len, expdest);
5536 esclen(const char *start, const char *p)
5540 while (p > start && (unsigned char)*--p == CTLESC) {
5547 * Remove any CTLESC characters from a string.
5550 rmescapes(char *str, int flag)
5552 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5556 unsigned protect_against_glob;
5559 p = strpbrk(str, qchars);
5565 if (flag & RMESCAPE_ALLOC) {
5566 size_t len = p - str;
5567 size_t fulllen = len + strlen(p) + 1;
5569 if (flag & RMESCAPE_GROW) {
5570 int strloc = str - (char *)stackblock();
5571 r = makestrspace(fulllen, expdest);
5572 /* p and str may be invalidated by makestrspace */
5573 str = (char *)stackblock() + strloc;
5575 } else if (flag & RMESCAPE_HEAP) {
5576 r = ckmalloc(fulllen);
5578 r = stalloc(fulllen);
5582 q = (char *)memcpy(q, str, len) + len;
5586 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5587 globbing = flag & RMESCAPE_GLOB;
5588 protect_against_glob = globbing;
5590 if ((unsigned char)*p == CTLQUOTEMARK) {
5591 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5592 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5593 // Note: both inquotes and protect_against_glob only affect whether
5594 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5595 inquotes = ~inquotes;
5597 protect_against_glob = globbing;
5601 /* naked back slash */
5602 protect_against_glob = 0;
5605 if ((unsigned char)*p == CTLESC) {
5607 if (protect_against_glob && inquotes && *p != '/') {
5611 protect_against_glob = globbing;
5616 if (flag & RMESCAPE_GROW) {
5618 STADJUST(q - r + 1, expdest);
5622 #define pmatch(a, b) !fnmatch((a), (b), 0)
5625 * Prepare a pattern for a expmeta (internal glob(3)) call.
5627 * Returns an stalloced string.
5630 preglob(const char *pattern, int quoted, int flag)
5632 flag |= RMESCAPE_GLOB;
5634 flag |= RMESCAPE_QUOTED;
5636 return rmescapes((char *)pattern, flag);
5640 * Put a string on the stack.
5643 memtodest(const char *p, size_t len, int syntax, int quotes)
5647 q = makestrspace(quotes ? len * 2 : len, q);
5650 unsigned char c = *p++;
5654 int n = SIT(c, syntax);
5655 if (n == CCTL || n == CBACK)
5665 strtodest(const char *p, int syntax, int quotes)
5667 memtodest(p, strlen(p), syntax, quotes);
5671 * Record the fact that we have to scan this region of the
5672 * string for IFS characters.
5675 recordregion(int start, int end, int nulonly)
5677 struct ifsregion *ifsp;
5679 if (ifslastp == NULL) {
5683 ifsp = ckzalloc(sizeof(*ifsp));
5684 /*ifsp->next = NULL; - ckzalloc did it */
5685 ifslastp->next = ifsp;
5689 ifslastp->begoff = start;
5690 ifslastp->endoff = end;
5691 ifslastp->nulonly = nulonly;
5695 removerecordregions(int endoff)
5697 if (ifslastp == NULL)
5700 if (ifsfirst.endoff > endoff) {
5701 while (ifsfirst.next) {
5702 struct ifsregion *ifsp;
5704 ifsp = ifsfirst.next->next;
5705 free(ifsfirst.next);
5706 ifsfirst.next = ifsp;
5709 if (ifsfirst.begoff > endoff) {
5712 ifslastp = &ifsfirst;
5713 ifsfirst.endoff = endoff;
5718 ifslastp = &ifsfirst;
5719 while (ifslastp->next && ifslastp->next->begoff < endoff)
5720 ifslastp = ifslastp->next;
5721 while (ifslastp->next) {
5722 struct ifsregion *ifsp;
5724 ifsp = ifslastp->next->next;
5725 free(ifslastp->next);
5726 ifslastp->next = ifsp;
5729 if (ifslastp->endoff > endoff)
5730 ifslastp->endoff = endoff;
5734 exptilde(char *startp, char *p, int flags)
5740 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5745 while ((c = *++p) != '\0') {
5752 if (flags & EXP_VARTILDE)
5762 if (*name == '\0') {
5763 home = lookupvar("HOME");
5765 pw = getpwnam(name);
5770 if (!home || !*home)
5773 startloc = expdest - (char *)stackblock();
5774 strtodest(home, SQSYNTAX, quotes);
5775 recordregion(startloc, expdest - (char *)stackblock(), 0);
5783 * Execute a command inside back quotes. If it's a builtin command, we
5784 * want to save its output in a block obtained from malloc. Otherwise
5785 * we fork off a subprocess and get the output of the command via a pipe.
5786 * Should be called with interrupts off.
5788 struct backcmd { /* result of evalbackcmd */
5789 int fd; /* file descriptor to read from */
5790 int nleft; /* number of chars in buffer */
5791 char *buf; /* buffer */
5792 struct job *jp; /* job structure for command */
5795 /* These forward decls are needed to use "eval" code for backticks handling: */
5796 static uint8_t back_exitstatus; /* exit status of backquoted command */
5797 #define EV_EXIT 01 /* exit after evaluating tree */
5798 static void evaltree(union node *, int);
5800 static void FAST_FUNC
5801 evalbackcmd(union node *n, struct backcmd *result)
5812 saveherefd = herefd;
5820 ash_msg_and_raise_error("pipe call failed");
5821 jp = makejob(/*n,*/ 1);
5822 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5827 copyfd(pip[1], 1 | COPYFD_EXACT);
5831 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5835 result->fd = pip[0];
5838 herefd = saveherefd;
5840 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5841 result->fd, result->buf, result->nleft, result->jp));
5845 * Expand stuff in backwards quotes.
5848 expbackq(union node *cmd, int quoted, int quotes)
5856 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5857 struct stackmark smark;
5860 setstackmark(&smark);
5862 startloc = dest - (char *)stackblock();
5864 evalbackcmd(cmd, &in);
5865 popstackmark(&smark);
5872 memtodest(p, i, syntax, quotes);
5876 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5877 TRACE(("expbackq: read returns %d\n", i));
5886 back_exitstatus = waitforjob(in.jp);
5890 /* Eat all trailing newlines */
5892 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5897 recordregion(startloc, dest - (char *)stackblock(), 0);
5898 TRACE(("evalbackq: size:%d:'%.*s'\n",
5899 (int)((dest - (char *)stackblock()) - startloc),
5900 (int)((dest - (char *)stackblock()) - startloc),
5901 stackblock() + startloc));
5904 #if ENABLE_SH_MATH_SUPPORT
5906 * Expand arithmetic expression. Backup to start of expression,
5907 * evaluate, place result in (backed up) result, adjust string position.
5920 * This routine is slightly over-complicated for
5921 * efficiency. Next we scan backwards looking for the
5922 * start of arithmetic.
5924 start = stackblock();
5931 while ((unsigned char)*p != CTLARI) {
5935 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5940 esc = esclen(start, p);
5950 removerecordregions(begoff);
5957 rmescapes(p + 2, 0);
5959 len = cvtnum(ash_arith(p + 2));
5962 recordregion(begoff, begoff + len, 0);
5966 /* argstr needs it */
5967 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5970 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5971 * characters to allow for further processing. Otherwise treat
5972 * $@ like $* since no splitting will be performed.
5974 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5975 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5976 * for correct expansion of "B=$A" word.
5979 argstr(char *p, int flags, struct strlist *var_str_list)
5981 static const char spclchars[] ALIGN1 = {
5989 CTLBACKQ | CTLQUOTE,
5990 #if ENABLE_SH_MATH_SUPPORT
5995 const char *reject = spclchars;
5996 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5997 int breakall = flags & EXP_WORD;
6002 if (!(flags & EXP_VARTILDE)) {
6004 } else if (flags & EXP_VARTILDE2) {
6009 if (flags & EXP_TILDE) {
6012 flags &= ~EXP_TILDE;
6015 if ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
6018 p = exptilde(p, q, flags);
6021 startloc = expdest - (char *)stackblock();
6025 length += strcspn(p + length, reject);
6029 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6031 /* c == '=' || c == ':' || c == CTLENDARI */
6037 expdest = stack_nputstr(p, length, expdest);
6038 newloc = expdest - (char *)stackblock();
6039 if (breakall && !inquotes && newloc > startloc) {
6040 recordregion(startloc, newloc, 0);
6051 if (flags & EXP_VARTILDE2) {
6055 flags |= EXP_VARTILDE2;
6060 * sort of a hack - expand tildes in variable
6061 * assignments (after the first '=' and after ':'s).
6070 case CTLENDVAR: /* ??? */
6073 /* "$@" syntax adherence hack */
6075 && memcmp(p, dolatstr, 4) == 0
6076 && ( p[4] == (char)CTLQUOTEMARK
6077 || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
6080 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
6083 inquotes = !inquotes;
6096 p = evalvar(p, flags, var_str_list);
6100 case CTLBACKQ|CTLQUOTE:
6101 expbackq(argbackq->n, c, quotes);
6102 argbackq = argbackq->next;
6104 #if ENABLE_SH_MATH_SUPPORT
6116 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6117 char *pattern, int quotes, int zero)
6126 const char *s = loc2;
6133 match = pmatch(pattern, s);
6138 if (quotes && (unsigned char)*loc == CTLESC)
6147 scanright(char *startp, char *rmesc, char *rmescend,
6148 char *pattern, int quotes, int match_at_start)
6150 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6151 int try2optimize = match_at_start;
6157 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6158 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6159 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6161 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6162 * and on each iteration they go back two/one char until they reach the beginning.
6163 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6165 /* TODO: document in what other circumstances we are called. */
6167 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6170 const char *s = loc2;
6171 if (match_at_start) {
6175 match = pmatch(pattern, s);
6176 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6180 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6182 /* Maybe we can optimize this:
6183 * if pattern ends with unescaped *, we can avoid checking
6184 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6185 * it wont match truncated "raw_value_of_" strings too.
6187 unsigned plen = strlen(pattern);
6188 /* Does it end with "*"? */
6189 if (plen != 0 && pattern[--plen] == '*') {
6190 /* "xxxx*" is not escaped */
6191 /* "xxx\*" is escaped */
6192 /* "xx\\*" is not escaped */
6193 /* "x\\\*" is escaped */
6195 while (plen != 0 && pattern[--plen] == '\\')
6198 break; /* ends with unescaped "*" */
6206 esc = esclen(startp, loc);
6217 static void varunset(const char *, const char *, const char *, int) NORETURN;
6219 varunset(const char *end, const char *var, const char *umsg, int varflags)
6225 msg = "parameter not set";
6227 if ((unsigned char)*end == CTLENDVAR) {
6228 if (varflags & VSNUL)
6234 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6237 #if ENABLE_ASH_BASH_COMPAT
6239 parse_sub_pattern(char *arg, int varflags)
6241 char *idx, *repl = NULL;
6244 //char *org_arg = arg;
6245 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
6252 /* Only the first '/' seen is our separator */
6261 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6262 * The result is a_\_z_c (not a\_\_z_c)!
6264 * Enable debug prints in this function and you'll see:
6265 * ash: arg:'\\b/_\\_z_' varflags:d
6266 * ash: pattern:'\\b' repl:'_\_z_'
6267 * That is, \\b is interpreted as \\b, but \\_ as \_!
6268 * IOW: search pattern and replace string treat backslashes
6269 * differently! That is the reason why we check repl below:
6271 if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
6272 arg++; /* skip both '\', not just first one */
6275 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
6279 #endif /* ENABLE_ASH_BASH_COMPAT */
6282 subevalvar(char *p, char *varname, int strloc, int subtype,
6283 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6285 struct nodelist *saveargbackq = argbackq;
6288 char *rmesc, *rmescend;
6290 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
6291 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6292 int saveherefd = herefd;
6293 int amount, workloc, resetloc;
6295 char *(*scan)(char*, char*, char*, char*, int, int);
6297 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6298 // p, varname, strloc, subtype, startloc, varflags, quotes);
6301 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6303 STPUTC('\0', expdest);
6304 herefd = saveherefd;
6305 argbackq = saveargbackq;
6306 startp = (char *)stackblock() + startloc;
6310 setvar(varname, startp, 0);
6311 amount = startp - expdest;
6312 STADJUST(amount, expdest);
6316 varunset(p, varname, startp, varflags);
6319 #if ENABLE_ASH_BASH_COMPAT
6321 loc = str = stackblock() + strloc;
6322 /* Read POS in ${var:POS:LEN} */
6323 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6324 len = str - startp - 1;
6326 /* *loc != '\0', guaranteed by parser */
6330 /* Adjust the length by the number of escapes */
6331 for (ptr = startp; ptr < (str - 1); ptr++) {
6332 if ((unsigned char)*ptr == CTLESC) {
6340 if (*loc++ == ':') {
6344 /* Skip POS in ${var:POS:LEN} */
6346 while (*loc && *loc != ':') {
6348 * bash complains on: var=qwe; echo ${var:1a:123}
6350 ash_msg_and_raise_error(msg_illnum, str);
6354 if (*loc++ == ':') {
6358 if (pos >= orig_len) {
6362 if (len > (orig_len - pos))
6363 len = orig_len - pos;
6365 for (str = startp; pos; str++, pos--) {
6366 if (quotes && (unsigned char)*str == CTLESC)
6369 for (loc = startp; len; len--) {
6370 if (quotes && (unsigned char)*str == CTLESC)
6375 amount = loc - expdest;
6376 STADJUST(amount, expdest);
6381 resetloc = expdest - (char *)stackblock();
6383 /* We'll comeback here if we grow the stack while handling
6384 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6385 * stack will need rebasing, and we'll need to remove our work
6388 IF_ASH_BASH_COMPAT(restart:)
6390 amount = expdest - ((char *)stackblock() + resetloc);
6391 STADJUST(-amount, expdest);
6392 startp = (char *)stackblock() + startloc;
6395 rmescend = (char *)stackblock() + strloc;
6397 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6398 if (rmesc != startp) {
6400 startp = (char *)stackblock() + startloc;
6404 str = (char *)stackblock() + strloc;
6405 preglob(str, varflags & VSQUOTE, 0);
6406 workloc = expdest - (char *)stackblock();
6408 #if ENABLE_ASH_BASH_COMPAT
6409 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6413 repl = parse_sub_pattern(str, varflags);
6414 //bb_error_msg("repl:'%s'", repl);
6419 /* If there's no pattern to match, return the expansion unmolested */
6428 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6429 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6431 /* No match, advance */
6432 char *restart_detect = stackblock();
6434 STPUTC(*idx, expdest);
6435 if (quotes && (unsigned char)*idx == CTLESC) {
6438 STPUTC(*idx, expdest);
6440 if (stackblock() != restart_detect)
6445 /* continue; - prone to quadratic behavior, smarter code: */
6448 if (str[0] == '*') {
6449 /* Pattern is "*foo". If "*foo" does not match "long_string",
6450 * it would never match "ong_string" etc, no point in trying.
6457 if (subtype == VSREPLACEALL) {
6459 if (quotes && (unsigned char)*idx == CTLESC)
6468 //bb_error_msg("repl:'%s'", repl);
6469 for (loc = (char*)repl; *loc; loc++) {
6470 char *restart_detect = stackblock();
6471 if (quotes && *loc == '\\') {
6472 STPUTC(CTLESC, expdest);
6475 STPUTC(*loc, expdest);
6476 if (stackblock() != restart_detect)
6481 if (subtype == VSREPLACE) {
6482 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6484 char *restart_detect = stackblock();
6485 STPUTC(*idx, expdest);
6486 if (stackblock() != restart_detect)
6495 /* We've put the replaced text into a buffer at workloc, now
6496 * move it to the right place and adjust the stack.
6498 STPUTC('\0', expdest);
6499 startp = (char *)stackblock() + startloc;
6500 memmove(startp, (char *)stackblock() + workloc, len + 1);
6501 //bb_error_msg("startp:'%s'", startp);
6502 amount = expdest - (startp + len);
6503 STADJUST(-amount, expdest);
6506 #endif /* ENABLE_ASH_BASH_COMPAT */
6508 subtype -= VSTRIMRIGHT;
6510 if (subtype < 0 || subtype > 7)
6513 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6514 zero = subtype >> 1;
6515 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6516 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6518 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6521 memmove(startp, loc, str - loc);
6522 loc = startp + (str - loc) - 1;
6525 amount = loc - expdest;
6526 STADJUST(amount, expdest);
6532 * Add the value of a specialized variable to the stack string.
6533 * name parameter (examples):
6534 * ash -c 'echo $1' name:'1='
6535 * ash -c 'echo $qwe' name:'qwe='
6536 * ash -c 'echo $$' name:'$='
6537 * ash -c 'echo ${$}' name:'$='
6538 * ash -c 'echo ${$##q}' name:'$=q'
6539 * ash -c 'echo ${#$}' name:'$='
6540 * note: examples with bad shell syntax:
6541 * ash -c 'echo ${#$1}' name:'$=1'
6542 * ash -c 'echo ${#1#}' name:'1=#'
6544 static NOINLINE ssize_t
6545 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6552 int subtype = varflags & VSTYPE;
6553 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6554 int quoted = varflags & VSQUOTE;
6555 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6565 num = shellparam.nparam;
6573 goto check_1char_name;
6575 expdest = makestrspace(NOPTS, expdest);
6576 for (i = NOPTS - 1; i >= 0; i--) {
6578 USTPUTC(optletters(i), expdest);
6584 /* handles cases similar to ${#$1} */
6585 if (name[2] != '\0')
6586 raise_error_syntax("bad substitution");
6593 if (quoted && (flags & EXP_FULL)) {
6594 /* note: this is not meant as PEOF value */
6595 sep = 1 << CHAR_BIT;
6600 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6601 i = SIT(sep, syntax);
6602 if (quotes && (i == CCTL || i == CBACK))
6608 while ((p = *ap++) != NULL) {
6611 partlen = strlen(p);
6614 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6615 memtodest(p, partlen, syntax, quotes);
6621 if (subtype == VSPLUS || subtype == VSLENGTH) {
6627 /* note: may put NUL despite sep != 0
6628 * (see sep = 1 << CHAR_BIT above) */
6634 } /* case '@' and '*' */
6645 num = atoi(name); /* number(name) fails on ${N#str} etc */
6646 if (num < 0 || num > shellparam.nparam)
6648 p = num ? shellparam.p[num - 1] : arg0;
6651 /* NB: name has form "VAR=..." */
6653 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6654 * which should be considered before we check variables. */
6656 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6660 str = var_str_list->text;
6661 eq = strchr(str, '=');
6662 if (!eq) /* stop at first non-assignment */
6665 if (name_len == (unsigned)(eq - str)
6666 && strncmp(str, name, name_len) == 0
6669 /* goto value; - WRONG! */
6670 /* think "A=1 A=2 B=$A" */
6672 var_str_list = var_str_list->next;
6673 } while (var_str_list);
6677 p = lookupvar(name);
6683 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6684 memtodest(p, len, syntax, quotes);
6688 if (subtype == VSPLUS || subtype == VSLENGTH)
6689 STADJUST(-len, expdest);
6694 * Expand a variable, and return a pointer to the next character in the
6698 evalvar(char *p, int flags, struct strlist *var_str_list)
6709 varflags = (unsigned char) *p++;
6710 subtype = varflags & VSTYPE;
6711 quoted = varflags & VSQUOTE;
6713 easy = (!quoted || (*var == '@' && shellparam.nparam));
6714 startloc = expdest - (char *)stackblock();
6715 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6718 varlen = varvalue(var, varflags, flags, var_str_list);
6719 if (varflags & VSNUL)
6722 if (subtype == VSPLUS) {
6723 varlen = -1 - varlen;
6727 if (subtype == VSMINUS) {
6732 flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
6742 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6744 if (subevalvar(p, var, /* strloc: */ 0,
6745 subtype, startloc, varflags,
6751 * Remove any recorded regions beyond
6754 removerecordregions(startloc);
6764 if (varlen < 0 && uflag)
6765 varunset(p, var, 0, 0);
6767 if (subtype == VSLENGTH) {
6768 cvtnum(varlen > 0 ? varlen : 0);
6772 if (subtype == VSNORMAL) {
6783 case VSTRIMRIGHTMAX:
6784 #if ENABLE_ASH_BASH_COMPAT
6797 * Terminate the string and start recording the pattern
6800 STPUTC('\0', expdest);
6801 patloc = expdest - (char *)stackblock();
6802 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6804 //TODO: | EXP_REDIR too? All other such places do it too
6805 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6808 int amount = expdest - (
6809 (char *)stackblock() + patloc - 1
6811 STADJUST(-amount, expdest);
6813 /* Remove any recorded regions beyond start of variable */
6814 removerecordregions(startloc);
6816 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6820 if (subtype != VSNORMAL) { /* skip to end of alternative */
6823 unsigned char c = *p++;
6826 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6828 argbackq = argbackq->next;
6829 } else if (c == CTLVAR) {
6830 if ((*p++ & VSTYPE) != VSNORMAL)
6832 } else if (c == CTLENDVAR) {
6842 * Break the argument string into pieces based upon IFS and add the
6843 * strings to the argument list. The regions of the string to be
6844 * searched for IFS characters have been stored by recordregion.
6847 ifsbreakup(char *string, struct arglist *arglist)
6849 struct ifsregion *ifsp;
6854 const char *ifs, *realifs;
6859 if (ifslastp != NULL) {
6862 realifs = ifsset() ? ifsval() : defifs;
6865 p = string + ifsp->begoff;
6866 nulonly = ifsp->nulonly;
6867 ifs = nulonly ? nullstr : realifs;
6869 while (p < string + ifsp->endoff) {
6871 if ((unsigned char)*p == CTLESC)
6873 if (!strchr(ifs, *p)) {
6878 ifsspc = (strchr(defifs, *p) != NULL);
6879 /* Ignore IFS whitespace at start */
6880 if (q == start && ifsspc) {
6886 sp = stzalloc(sizeof(*sp));
6888 *arglist->lastp = sp;
6889 arglist->lastp = &sp->next;
6893 if (p >= string + ifsp->endoff) {
6897 if ((unsigned char)*p == CTLESC)
6899 if (strchr(ifs, *p) == NULL) {
6903 if (strchr(defifs, *p) == NULL) {
6918 } while (ifsp != NULL);
6927 sp = stzalloc(sizeof(*sp));
6929 *arglist->lastp = sp;
6930 arglist->lastp = &sp->next;
6936 struct ifsregion *p;
6941 struct ifsregion *ifsp;
6947 ifsfirst.next = NULL;
6952 * Add a file name to the list.
6955 addfname(const char *name)
6959 sp = stzalloc(sizeof(*sp));
6960 sp->text = ststrdup(name);
6962 exparg.lastp = &sp->next;
6966 * Do metacharacter (i.e. *, ?, [...]) expansion.
6969 expmeta(char *expdir, char *enddir, char *name)
6984 for (p = name; *p; p++) {
6985 if (*p == '*' || *p == '?')
6987 else if (*p == '[') {
6994 if (*q == '/' || *q == '\0')
7001 } else if (*p == '\\')
7003 else if (*p == '/') {
7010 if (metaflag == 0) { /* we've reached the end of the file name */
7011 if (enddir != expdir)
7019 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7030 } while (p < start);
7032 if (enddir == expdir) {
7034 } else if (enddir == expdir + 1 && *expdir == '/') {
7043 if (enddir != expdir)
7045 if (*endname == 0) {
7057 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7058 if (dp->d_name[0] == '.' && !matchdot)
7060 if (pmatch(start, dp->d_name)) {
7062 strcpy(enddir, dp->d_name);
7065 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7068 expmeta(expdir, p, endname);
7077 static struct strlist *
7078 msort(struct strlist *list, int len)
7080 struct strlist *p, *q = NULL;
7081 struct strlist **lpp;
7089 for (n = half; --n >= 0;) {
7093 q->next = NULL; /* terminate first half of list */
7094 q = msort(list, half); /* sort first half of list */
7095 p = msort(p, len - half); /* sort second half */
7098 #if ENABLE_LOCALE_SUPPORT
7099 if (strcoll(p->text, q->text) < 0)
7101 if (strcmp(p->text, q->text) < 0)
7125 * Sort the results of file name expansion. It calculates the number of
7126 * strings to sort and then calls msort (short for merge sort) to do the
7129 static struct strlist *
7130 expsort(struct strlist *str)
7136 for (sp = str; sp; sp = sp->next)
7138 return msort(str, len);
7142 expandmeta(struct strlist *str /*, int flag*/)
7144 static const char metachars[] ALIGN1 = {
7147 /* TODO - EXP_REDIR */
7151 struct strlist **savelastp;
7157 if (!strpbrk(str->text, metachars))
7159 savelastp = exparg.lastp;
7162 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7164 int i = strlen(str->text);
7165 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7167 expmeta(expdir, expdir, p);
7172 if (exparg.lastp == savelastp) {
7177 *exparg.lastp = str;
7178 rmescapes(str->text, 0);
7179 exparg.lastp = &str->next;
7181 *exparg.lastp = NULL;
7182 *savelastp = sp = expsort(*savelastp);
7183 while (sp->next != NULL)
7185 exparg.lastp = &sp->next;
7192 * Perform variable substitution and command substitution on an argument,
7193 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7194 * perform splitting and file name expansion. When arglist is NULL, perform
7195 * here document expansion.
7198 expandarg(union node *arg, struct arglist *arglist, int flag)
7203 argbackq = arg->narg.backquote;
7204 STARTSTACKSTR(expdest);
7205 ifsfirst.next = NULL;
7207 argstr(arg->narg.text, flag,
7208 /* var_str_list: */ arglist ? arglist->list : NULL);
7209 p = _STPUTC('\0', expdest);
7211 if (arglist == NULL) {
7212 return; /* here document expanded */
7214 p = grabstackstr(p);
7215 exparg.lastp = &exparg.list;
7219 if (flag & EXP_FULL) {
7220 ifsbreakup(p, &exparg);
7221 *exparg.lastp = NULL;
7222 exparg.lastp = &exparg.list;
7223 expandmeta(exparg.list /*, flag*/);
7225 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7227 sp = stzalloc(sizeof(*sp));
7230 exparg.lastp = &sp->next;
7234 *exparg.lastp = NULL;
7236 *arglist->lastp = exparg.list;
7237 arglist->lastp = exparg.lastp;
7242 * Expand shell variables and backquotes inside a here document.
7245 expandhere(union node *arg, int fd)
7248 expandarg(arg, (struct arglist *)NULL, 0);
7249 full_write(fd, stackblock(), expdest - (char *)stackblock());
7253 * Returns true if the pattern matches the string.
7256 patmatch(char *pattern, const char *string)
7258 return pmatch(preglob(pattern, 0, 0), string);
7262 * See if a pattern matches in a case statement.
7265 casematch(union node *pattern, char *val)
7267 struct stackmark smark;
7270 setstackmark(&smark);
7271 argbackq = pattern->narg.backquote;
7272 STARTSTACKSTR(expdest);
7274 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7275 /* var_str_list: */ NULL);
7276 STACKSTRNUL(expdest);
7277 result = patmatch(stackblock(), val);
7278 popstackmark(&smark);
7283 /* ============ find_command */
7287 int (*builtin)(int, char **) FAST_FUNC;
7288 /* unsigned flags; */
7290 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7291 /* "regular" builtins always take precedence over commands,
7292 * regardless of PATH=....%builtin... position */
7293 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7294 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7297 smallint cmdtype; /* CMDxxx */
7300 /* index >= 0 for commands without path (slashes) */
7301 /* (TODO: what exactly does the value mean? PATH position?) */
7302 /* index == -1 for commands with slashes */
7303 /* index == (-2 - applet_no) for NOFORK applets */
7304 const struct builtincmd *cmd;
7305 struct funcnode *func;
7308 /* values of cmdtype */
7309 #define CMDUNKNOWN -1 /* no entry in table for command */
7310 #define CMDNORMAL 0 /* command is an executable program */
7311 #define CMDFUNCTION 1 /* command is a shell function */
7312 #define CMDBUILTIN 2 /* command is a shell builtin */
7314 /* action to find_command() */
7315 #define DO_ERR 0x01 /* prints errors */
7316 #define DO_ABS 0x02 /* checks absolute paths */
7317 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7318 #define DO_ALTPATH 0x08 /* using alternate path */
7319 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7321 static void find_command(char *, struct cmdentry *, int, const char *);
7324 /* ============ Hashing commands */
7327 * When commands are first encountered, they are entered in a hash table.
7328 * This ensures that a full path search will not have to be done for them
7329 * on each invocation.
7331 * We should investigate converting to a linear search, even though that
7332 * would make the command name "hash" a misnomer.
7336 struct tblentry *next; /* next entry in hash chain */
7337 union param param; /* definition of builtin function */
7338 smallint cmdtype; /* CMDxxx */
7339 char rehash; /* if set, cd done since entry created */
7340 char cmdname[1]; /* name of command */
7343 static struct tblentry **cmdtable;
7344 #define INIT_G_cmdtable() do { \
7345 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7348 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7352 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7356 #if ENABLE_FEATURE_SH_STANDALONE
7357 if (applet_no >= 0) {
7358 if (APPLET_IS_NOEXEC(applet_no)) {
7362 run_applet_no_and_exit(applet_no, argv);
7364 /* re-exec ourselves with the new arguments */
7365 execve(bb_busybox_exec_path, argv, envp);
7366 /* If they called chroot or otherwise made the binary no longer
7367 * executable, fall through */
7374 execve(cmd, argv, envp);
7375 } while (errno == EINTR);
7377 execve(cmd, argv, envp);
7383 if (errno == ENOEXEC) {
7387 for (ap = argv; *ap; ap++)
7389 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7391 ap[0] = cmd = (char *)DEFAULT_SHELL;
7394 while ((*ap++ = *argv++) != NULL)
7403 * Exec a program. Never returns. If you change this routine, you may
7404 * have to change the find_command routine as well.
7406 static void shellexec(char **, const char *, int) NORETURN;
7408 shellexec(char **argv, const char *path, int idx)
7414 #if ENABLE_FEATURE_SH_STANDALONE
7418 clearredir(/*drop:*/ 1);
7419 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7420 if (strchr(argv[0], '/') != NULL
7421 #if ENABLE_FEATURE_SH_STANDALONE
7422 || (applet_no = find_applet_by_name(argv[0])) >= 0
7425 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7429 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7430 if (--idx < 0 && pathopt == NULL) {
7431 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7432 if (errno != ENOENT && errno != ENOTDIR)
7439 /* Map to POSIX errors */
7451 exitstatus = exerrno;
7452 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7453 argv[0], e, suppress_int));
7454 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7459 printentry(struct tblentry *cmdp)
7465 idx = cmdp->param.index;
7468 name = path_advance(&path, cmdp->cmdname);
7470 } while (--idx >= 0);
7471 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7475 * Clear out command entries. The argument specifies the first entry in
7476 * PATH which has changed.
7479 clearcmdentry(int firstchange)
7481 struct tblentry **tblp;
7482 struct tblentry **pp;
7483 struct tblentry *cmdp;
7486 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7488 while ((cmdp = *pp) != NULL) {
7489 if ((cmdp->cmdtype == CMDNORMAL &&
7490 cmdp->param.index >= firstchange)
7491 || (cmdp->cmdtype == CMDBUILTIN &&
7492 builtinloc >= firstchange)
7505 * Locate a command in the command hash table. If "add" is nonzero,
7506 * add the command to the table if it is not already present. The
7507 * variable "lastcmdentry" is set to point to the address of the link
7508 * pointing to the entry, so that delete_cmd_entry can delete the
7511 * Interrupts must be off if called with add != 0.
7513 static struct tblentry **lastcmdentry;
7515 static struct tblentry *
7516 cmdlookup(const char *name, int add)
7518 unsigned int hashval;
7520 struct tblentry *cmdp;
7521 struct tblentry **pp;
7524 hashval = (unsigned char)*p << 4;
7526 hashval += (unsigned char)*p++;
7528 pp = &cmdtable[hashval % CMDTABLESIZE];
7529 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7530 if (strcmp(cmdp->cmdname, name) == 0)
7534 if (add && cmdp == NULL) {
7535 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7537 /* + 1 - already done because
7538 * tblentry::cmdname is char[1] */);
7539 /*cmdp->next = NULL; - ckzalloc did it */
7540 cmdp->cmdtype = CMDUNKNOWN;
7541 strcpy(cmdp->cmdname, name);
7548 * Delete the command entry returned on the last lookup.
7551 delete_cmd_entry(void)
7553 struct tblentry *cmdp;
7556 cmdp = *lastcmdentry;
7557 *lastcmdentry = cmdp->next;
7558 if (cmdp->cmdtype == CMDFUNCTION)
7559 freefunc(cmdp->param.func);
7565 * Add a new command entry, replacing any existing command entry for
7566 * the same name - except special builtins.
7569 addcmdentry(char *name, struct cmdentry *entry)
7571 struct tblentry *cmdp;
7573 cmdp = cmdlookup(name, 1);
7574 if (cmdp->cmdtype == CMDFUNCTION) {
7575 freefunc(cmdp->param.func);
7577 cmdp->cmdtype = entry->cmdtype;
7578 cmdp->param = entry->u;
7582 static int FAST_FUNC
7583 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7585 struct tblentry **pp;
7586 struct tblentry *cmdp;
7588 struct cmdentry entry;
7591 if (nextopt("r") != '\0') {
7596 if (*argptr == NULL) {
7597 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7598 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7599 if (cmdp->cmdtype == CMDNORMAL)
7607 while ((name = *argptr) != NULL) {
7608 cmdp = cmdlookup(name, 0);
7610 && (cmdp->cmdtype == CMDNORMAL
7611 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7615 find_command(name, &entry, DO_ERR, pathval());
7616 if (entry.cmdtype == CMDUNKNOWN)
7624 * Called when a cd is done. Marks all commands so the next time they
7625 * are executed they will be rehashed.
7630 struct tblentry **pp;
7631 struct tblentry *cmdp;
7633 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7634 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7635 if (cmdp->cmdtype == CMDNORMAL
7636 || (cmdp->cmdtype == CMDBUILTIN
7637 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7647 * Fix command hash table when PATH changed.
7648 * Called before PATH is changed. The argument is the new value of PATH;
7649 * pathval() still returns the old value at this point.
7650 * Called with interrupts off.
7652 static void FAST_FUNC
7653 changepath(const char *new)
7661 firstchange = 9999; /* assume no change */
7667 if ((*old == '\0' && *new == ':')
7668 || (*old == ':' && *new == '\0')
7672 old = new; /* ignore subsequent differences */
7676 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7683 if (builtinloc < 0 && idx_bltin >= 0)
7684 builtinloc = idx_bltin; /* zap builtins */
7685 if (builtinloc >= 0 && idx_bltin < 0)
7687 clearcmdentry(firstchange);
7688 builtinloc = idx_bltin;
7703 #define TENDBQUOTE 12
7720 typedef smallint token_id_t;
7722 /* first char is indicating which tokens mark the end of a list */
7723 static const char *const tokname_array[] = {
7737 #define KWDOFFSET 13
7738 /* the following are keywords */
7757 /* Wrapper around strcmp for qsort/bsearch/... */
7759 pstrcmp(const void *a, const void *b)
7761 return strcmp((char*) a, (*(char**) b) + 1);
7764 static const char *const *
7765 findkwd(const char *s)
7767 return bsearch(s, tokname_array + KWDOFFSET,
7768 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7769 sizeof(tokname_array[0]), pstrcmp);
7773 * Locate and print what a word is...
7776 describe_command(char *command, int describe_command_verbose)
7778 struct cmdentry entry;
7779 struct tblentry *cmdp;
7780 #if ENABLE_ASH_ALIAS
7781 const struct alias *ap;
7783 const char *path = pathval();
7785 if (describe_command_verbose) {
7789 /* First look at the keywords */
7790 if (findkwd(command)) {
7791 out1str(describe_command_verbose ? " is a shell keyword" : command);
7795 #if ENABLE_ASH_ALIAS
7796 /* Then look at the aliases */
7797 ap = lookupalias(command, 0);
7799 if (!describe_command_verbose) {
7804 out1fmt(" is an alias for %s", ap->val);
7808 /* Then check if it is a tracked alias */
7809 cmdp = cmdlookup(command, 0);
7811 entry.cmdtype = cmdp->cmdtype;
7812 entry.u = cmdp->param;
7814 /* Finally use brute force */
7815 find_command(command, &entry, DO_ABS, path);
7818 switch (entry.cmdtype) {
7820 int j = entry.u.index;
7826 p = path_advance(&path, command);
7830 if (describe_command_verbose) {
7832 (cmdp ? " a tracked alias for" : nullstr), p
7841 if (describe_command_verbose) {
7842 out1str(" is a shell function");
7849 if (describe_command_verbose) {
7850 out1fmt(" is a %sshell builtin",
7851 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7852 "special " : nullstr
7860 if (describe_command_verbose) {
7861 out1str(": not found\n");
7870 static int FAST_FUNC
7871 typecmd(int argc UNUSED_PARAM, char **argv)
7877 /* type -p ... ? (we don't bother checking for 'p') */
7878 if (argv[1] && argv[1][0] == '-') {
7883 err |= describe_command(argv[i++], verbose);
7888 #if ENABLE_ASH_CMDCMD
7889 static int FAST_FUNC
7890 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7898 while ((c = nextopt("pvV")) != '\0')
7900 verify |= VERIFY_VERBOSE;
7902 verify |= VERIFY_BRIEF;
7907 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7908 if (verify && (*argptr != NULL)) {
7909 return describe_command(*argptr, verify - VERIFY_BRIEF);
7917 /* ============ eval.c */
7919 static int funcblocksize; /* size of structures in function */
7920 static int funcstringsize; /* size of strings in node */
7921 static void *funcblock; /* block to allocate function from */
7922 static char *funcstring; /* block to allocate strings from */
7924 /* flags in argument to evaltree */
7925 #define EV_EXIT 01 /* exit after evaluating tree */
7926 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7927 #define EV_BACKCMD 04 /* command executing within back quotes */
7929 static const uint8_t nodesize[N_NUMBER] = {
7930 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7931 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7932 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7933 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7934 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7935 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7936 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7937 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7938 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7939 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7940 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7941 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7942 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7943 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7944 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7945 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7946 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7947 #if ENABLE_ASH_BASH_COMPAT
7948 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7950 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7951 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7952 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7953 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7954 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7955 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7956 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7957 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7958 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7961 static void calcsize(union node *n);
7964 sizenodelist(struct nodelist *lp)
7967 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7974 calcsize(union node *n)
7978 funcblocksize += nodesize[n->type];
7981 calcsize(n->ncmd.redirect);
7982 calcsize(n->ncmd.args);
7983 calcsize(n->ncmd.assign);
7986 sizenodelist(n->npipe.cmdlist);
7991 calcsize(n->nredir.redirect);
7992 calcsize(n->nredir.n);
7999 calcsize(n->nbinary.ch2);
8000 calcsize(n->nbinary.ch1);
8003 calcsize(n->nif.elsepart);
8004 calcsize(n->nif.ifpart);
8005 calcsize(n->nif.test);
8008 funcstringsize += strlen(n->nfor.var) + 1;
8009 calcsize(n->nfor.body);
8010 calcsize(n->nfor.args);
8013 calcsize(n->ncase.cases);
8014 calcsize(n->ncase.expr);
8017 calcsize(n->nclist.body);
8018 calcsize(n->nclist.pattern);
8019 calcsize(n->nclist.next);
8023 sizenodelist(n->narg.backquote);
8024 funcstringsize += strlen(n->narg.text) + 1;
8025 calcsize(n->narg.next);
8028 #if ENABLE_ASH_BASH_COMPAT
8035 calcsize(n->nfile.fname);
8036 calcsize(n->nfile.next);
8040 calcsize(n->ndup.vname);
8041 calcsize(n->ndup.next);
8045 calcsize(n->nhere.doc);
8046 calcsize(n->nhere.next);
8049 calcsize(n->nnot.com);
8055 nodeckstrdup(char *s)
8057 char *rtn = funcstring;
8059 strcpy(funcstring, s);
8060 funcstring += strlen(s) + 1;
8064 static union node *copynode(union node *);
8066 static struct nodelist *
8067 copynodelist(struct nodelist *lp)
8069 struct nodelist *start;
8070 struct nodelist **lpp;
8075 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8076 (*lpp)->n = copynode(lp->n);
8078 lpp = &(*lpp)->next;
8085 copynode(union node *n)
8092 funcblock = (char *) funcblock + nodesize[n->type];
8096 new->ncmd.redirect = copynode(n->ncmd.redirect);
8097 new->ncmd.args = copynode(n->ncmd.args);
8098 new->ncmd.assign = copynode(n->ncmd.assign);
8101 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8102 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8107 new->nredir.redirect = copynode(n->nredir.redirect);
8108 new->nredir.n = copynode(n->nredir.n);
8115 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8116 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8119 new->nif.elsepart = copynode(n->nif.elsepart);
8120 new->nif.ifpart = copynode(n->nif.ifpart);
8121 new->nif.test = copynode(n->nif.test);
8124 new->nfor.var = nodeckstrdup(n->nfor.var);
8125 new->nfor.body = copynode(n->nfor.body);
8126 new->nfor.args = copynode(n->nfor.args);
8129 new->ncase.cases = copynode(n->ncase.cases);
8130 new->ncase.expr = copynode(n->ncase.expr);
8133 new->nclist.body = copynode(n->nclist.body);
8134 new->nclist.pattern = copynode(n->nclist.pattern);
8135 new->nclist.next = copynode(n->nclist.next);
8139 new->narg.backquote = copynodelist(n->narg.backquote);
8140 new->narg.text = nodeckstrdup(n->narg.text);
8141 new->narg.next = copynode(n->narg.next);
8144 #if ENABLE_ASH_BASH_COMPAT
8151 new->nfile.fname = copynode(n->nfile.fname);
8152 new->nfile.fd = n->nfile.fd;
8153 new->nfile.next = copynode(n->nfile.next);
8157 new->ndup.vname = copynode(n->ndup.vname);
8158 new->ndup.dupfd = n->ndup.dupfd;
8159 new->ndup.fd = n->ndup.fd;
8160 new->ndup.next = copynode(n->ndup.next);
8164 new->nhere.doc = copynode(n->nhere.doc);
8165 new->nhere.fd = n->nhere.fd;
8166 new->nhere.next = copynode(n->nhere.next);
8169 new->nnot.com = copynode(n->nnot.com);
8172 new->type = n->type;
8177 * Make a copy of a parse tree.
8179 static struct funcnode *
8180 copyfunc(union node *n)
8185 funcblocksize = offsetof(struct funcnode, n);
8188 blocksize = funcblocksize;
8189 f = ckmalloc(blocksize + funcstringsize);
8190 funcblock = (char *) f + offsetof(struct funcnode, n);
8191 funcstring = (char *) f + blocksize;
8198 * Define a shell function.
8201 defun(char *name, union node *func)
8203 struct cmdentry entry;
8206 entry.cmdtype = CMDFUNCTION;
8207 entry.u.func = copyfunc(func);
8208 addcmdentry(name, &entry);
8212 /* Reasons for skipping commands (see comment on breakcmd routine) */
8213 #define SKIPBREAK (1 << 0)
8214 #define SKIPCONT (1 << 1)
8215 #define SKIPFUNC (1 << 2)
8216 #define SKIPFILE (1 << 3)
8217 #define SKIPEVAL (1 << 4)
8218 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8219 static int skipcount; /* number of levels to skip */
8220 static int funcnest; /* depth of function calls */
8221 static int loopnest; /* current loop nesting level */
8223 /* Forward decl way out to parsing code - dotrap needs it */
8224 static int evalstring(char *s, int mask);
8226 /* Called to execute a trap.
8227 * Single callsite - at the end of evaltree().
8228 * If we return non-zero, evaltree raises EXEXIT exception.
8230 * Perhaps we should avoid entering new trap handlers
8231 * while we are executing a trap handler. [is it a TODO?]
8240 savestatus = exitstatus;
8244 TRACE(("dotrap entered\n"));
8245 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8252 /* non-trapped SIGINT is handled separately by raise_interrupt,
8253 * don't upset it by resetting gotsig[SIGINT-1] */
8254 if (sig == SIGINT && !t)
8257 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8261 want_exexit = evalstring(t, SKIPEVAL);
8262 exitstatus = savestatus;
8264 TRACE(("dotrap returns %d\n", want_exexit));
8269 TRACE(("dotrap returns 0\n"));
8273 /* forward declarations - evaluation is fairly recursive business... */
8274 static void evalloop(union node *, int);
8275 static void evalfor(union node *, int);
8276 static void evalcase(union node *, int);
8277 static void evalsubshell(union node *, int);
8278 static void expredir(union node *);
8279 static void evalpipe(union node *, int);
8280 static void evalcommand(union node *, int);
8281 static int evalbltin(const struct builtincmd *, int, char **);
8282 static void prehash(union node *);
8285 * Evaluate a parse tree. The value is left in the global variable
8289 evaltree(union node *n, int flags)
8291 struct jmploc *volatile savehandler = exception_handler;
8292 struct jmploc jmploc;
8294 void (*evalfn)(union node *, int);
8298 SAVE_INT(int_level);
8301 TRACE(("evaltree(NULL) called\n"));
8304 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8306 exception_handler = &jmploc;
8308 int err = setjmp(jmploc.loc);
8310 /* if it was a signal, check for trap handlers */
8311 if (exception_type == EXSIG) {
8312 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8313 exception_type, err));
8316 /* continue on the way out */
8317 TRACE(("exception %d in evaltree, propagating err=%d\n",
8318 exception_type, err));
8319 exception_handler = savehandler;
8320 longjmp(exception_handler->loc, err);
8327 out1fmt("Node type = %d\n", n->type);
8332 evaltree(n->nnot.com, EV_TESTED);
8333 status = !exitstatus;
8336 expredir(n->nredir.redirect);
8337 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8339 evaltree(n->nredir.n, flags & EV_TESTED);
8340 status = exitstatus;
8342 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8345 evalfn = evalcommand;
8347 if (eflag && !(flags & EV_TESTED))
8359 evalfn = evalsubshell;
8372 #error NAND + 1 != NOR
8374 #if NOR + 1 != NSEMI
8375 #error NOR + 1 != NSEMI
8377 unsigned is_or = n->type - NAND;
8380 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8382 if (!exitstatus == is_or)
8395 evaltree(n->nif.test, EV_TESTED);
8398 if (exitstatus == 0) {
8402 if (n->nif.elsepart) {
8403 n = n->nif.elsepart;
8408 defun(n->narg.text, n->narg.next);
8412 exitstatus = status;
8417 exception_handler = savehandler;
8420 /* Order of checks below is important:
8421 * signal handlers trigger before exit caused by "set -e".
8423 if (pending_sig && dotrap())
8425 if (checkexit & exitstatus)
8426 evalskip |= SKIPEVAL;
8428 if (flags & EV_EXIT) {
8430 raise_exception(EXEXIT);
8433 RESTORE_INT(int_level);
8434 TRACE(("leaving evaltree (no interrupts)\n"));
8437 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8440 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8443 evalloop(union node *n, int flags)
8453 evaltree(n->nbinary.ch1, EV_TESTED);
8456 if (evalskip == SKIPCONT && --skipcount <= 0) {
8460 if (evalskip == SKIPBREAK && --skipcount <= 0)
8465 if (n->type != NWHILE)
8469 evaltree(n->nbinary.ch2, flags);
8470 status = exitstatus;
8475 exitstatus = status;
8479 evalfor(union node *n, int flags)
8481 struct arglist arglist;
8484 struct stackmark smark;
8486 setstackmark(&smark);
8487 arglist.list = NULL;
8488 arglist.lastp = &arglist.list;
8489 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8490 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8495 *arglist.lastp = NULL;
8500 for (sp = arglist.list; sp; sp = sp->next) {
8501 setvar(n->nfor.var, sp->text, 0);
8502 evaltree(n->nfor.body, flags);
8504 if (evalskip == SKIPCONT && --skipcount <= 0) {
8508 if (evalskip == SKIPBREAK && --skipcount <= 0)
8515 popstackmark(&smark);
8519 evalcase(union node *n, int flags)
8523 struct arglist arglist;
8524 struct stackmark smark;
8526 setstackmark(&smark);
8527 arglist.list = NULL;
8528 arglist.lastp = &arglist.list;
8529 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8531 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8532 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8533 if (casematch(patp, arglist.list->text)) {
8534 if (evalskip == 0) {
8535 evaltree(cp->nclist.body, flags);
8542 popstackmark(&smark);
8546 * Kick off a subshell to evaluate a tree.
8549 evalsubshell(union node *n, int flags)
8552 int backgnd = (n->type == NBACKGND);
8555 expredir(n->nredir.redirect);
8556 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8559 jp = makejob(/*n,*/ 1);
8560 if (forkshell(jp, n, backgnd) == 0) {
8565 flags &= ~EV_TESTED;
8567 redirect(n->nredir.redirect, 0);
8568 evaltreenr(n->nredir.n, flags);
8573 status = waitforjob(jp);
8574 exitstatus = status;
8579 * Compute the names of the files in a redirection list.
8581 static void fixredir(union node *, const char *, int);
8583 expredir(union node *n)
8587 for (redir = n; redir; redir = redir->nfile.next) {
8591 fn.lastp = &fn.list;
8592 switch (redir->type) {
8596 #if ENABLE_ASH_BASH_COMPAT
8601 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8602 #if ENABLE_ASH_BASH_COMPAT
8605 redir->nfile.expfname = fn.list->text;
8608 case NTOFD: /* >& */
8609 if (redir->ndup.vname) {
8610 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8611 if (fn.list == NULL)
8612 ash_msg_and_raise_error("redir error");
8613 #if ENABLE_ASH_BASH_COMPAT
8614 //FIXME: we used expandarg with different args!
8615 if (!isdigit_str9(fn.list->text)) {
8616 /* >&file, not >&fd */
8617 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8618 ash_msg_and_raise_error("redir error");
8620 goto store_expfname;
8623 fixredir(redir, fn.list->text, 1);
8631 * Evaluate a pipeline. All the processes in the pipeline are children
8632 * of the process creating the pipeline. (This differs from some versions
8633 * of the shell, which make the last process in a pipeline the parent
8637 evalpipe(union node *n, int flags)
8640 struct nodelist *lp;
8645 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8647 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8651 jp = makejob(/*n,*/ pipelen);
8653 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8657 if (pipe(pip) < 0) {
8659 ash_msg_and_raise_error("pipe call failed");
8662 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8675 evaltreenr(lp->n, flags);
8681 /* Don't want to trigger debugging */
8685 if (n->npipe.pipe_backgnd == 0) {
8686 exitstatus = waitforjob(jp);
8687 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8693 * Controls whether the shell is interactive or not.
8696 setinteractive(int on)
8698 static smallint is_interactive;
8700 if (++on == is_interactive)
8702 is_interactive = on;
8706 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8707 if (is_interactive > 1) {
8708 /* Looks like they want an interactive shell */
8709 static smallint did_banner;
8712 /* note: ash and hush share this string */
8713 out1fmt("\n\n%s %s\n"
8714 "Enter 'help' for a list of built-in commands."
8717 "built-in shell (ash)"
8731 setinteractive(iflag);
8733 #if ENABLE_FEATURE_EDITING_VI
8735 line_input_state->flags |= VI_MODE;
8737 line_input_state->flags &= ~VI_MODE;
8739 viflag = 0; /* forcibly keep the option off */
8743 static struct localvar *localvars;
8746 * Called after a function returns.
8747 * Interrupts must be off.
8752 struct localvar *lvp;
8755 while ((lvp = localvars) != NULL) {
8756 localvars = lvp->next;
8758 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8759 if (vp == NULL) { /* $- saved */
8760 memcpy(optlist, lvp->text, sizeof(optlist));
8761 free((char*)lvp->text);
8763 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8764 unsetvar(vp->var_text);
8767 vp->var_func(var_end(lvp->text));
8768 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8769 free((char*)vp->var_text);
8770 vp->flags = lvp->flags;
8771 vp->var_text = lvp->text;
8778 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8780 volatile struct shparam saveparam;
8781 struct localvar *volatile savelocalvars;
8782 struct jmploc *volatile savehandler;
8783 struct jmploc jmploc;
8786 saveparam = shellparam;
8787 savelocalvars = localvars;
8788 e = setjmp(jmploc.loc);
8793 savehandler = exception_handler;
8794 exception_handler = &jmploc;
8796 shellparam.malloced = 0;
8800 shellparam.nparam = argc - 1;
8801 shellparam.p = argv + 1;
8802 #if ENABLE_ASH_GETOPTS
8803 shellparam.optind = 1;
8804 shellparam.optoff = -1;
8806 evaltree(&func->n, flags & EV_TESTED);
8812 localvars = savelocalvars;
8813 freeparam(&shellparam);
8814 shellparam = saveparam;
8815 exception_handler = savehandler;
8817 evalskip &= ~SKIPFUNC;
8821 #if ENABLE_ASH_CMDCMD
8823 parse_command_args(char **argv, const char **path)
8836 if (c == '-' && !*cp) {
8843 *path = bb_default_path;
8846 /* run 'typecmd' for other options */
8857 * Make a variable a local variable. When a variable is made local, it's
8858 * value and flags are saved in a localvar structure. The saved values
8859 * will be restored when the shell function returns. We handle the name
8860 * "-" as a special case.
8865 struct localvar *lvp;
8870 lvp = ckzalloc(sizeof(struct localvar));
8871 if (LONE_DASH(name)) {
8873 p = ckmalloc(sizeof(optlist));
8874 lvp->text = memcpy(p, optlist, sizeof(optlist));
8879 vpp = hashvar(name);
8880 vp = *findvar(vpp, name);
8881 eq = strchr(name, '=');
8884 setvareq(name, VSTRFIXED);
8886 setvar(name, NULL, VSTRFIXED);
8887 vp = *vpp; /* the new variable */
8888 lvp->flags = VUNSET;
8890 lvp->text = vp->var_text;
8891 lvp->flags = vp->flags;
8892 vp->flags |= VSTRFIXED|VTEXTFIXED;
8898 lvp->next = localvars;
8904 * The "local" command.
8906 static int FAST_FUNC
8907 localcmd(int argc UNUSED_PARAM, char **argv)
8912 while ((name = *argv++) != NULL) {
8918 static int FAST_FUNC
8919 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8924 static int FAST_FUNC
8925 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8930 static int FAST_FUNC
8931 execcmd(int argc UNUSED_PARAM, char **argv)
8934 iflag = 0; /* exit on error */
8937 shellexec(argv + 1, pathval(), 0);
8943 * The return command.
8945 static int FAST_FUNC
8946 returncmd(int argc UNUSED_PARAM, char **argv)
8949 * If called outside a function, do what ksh does;
8950 * skip the rest of the file.
8952 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8953 return argv[1] ? number(argv[1]) : exitstatus;
8956 /* Forward declarations for builtintab[] */
8957 static int breakcmd(int, char **) FAST_FUNC;
8958 static int dotcmd(int, char **) FAST_FUNC;
8959 static int evalcmd(int, char **) FAST_FUNC;
8960 static int exitcmd(int, char **) FAST_FUNC;
8961 static int exportcmd(int, char **) FAST_FUNC;
8962 #if ENABLE_ASH_GETOPTS
8963 static int getoptscmd(int, char **) FAST_FUNC;
8965 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8966 static int helpcmd(int, char **) FAST_FUNC;
8968 #if ENABLE_SH_MATH_SUPPORT
8969 static int letcmd(int, char **) FAST_FUNC;
8971 static int readcmd(int, char **) FAST_FUNC;
8972 static int setcmd(int, char **) FAST_FUNC;
8973 static int shiftcmd(int, char **) FAST_FUNC;
8974 static int timescmd(int, char **) FAST_FUNC;
8975 static int trapcmd(int, char **) FAST_FUNC;
8976 static int umaskcmd(int, char **) FAST_FUNC;
8977 static int unsetcmd(int, char **) FAST_FUNC;
8978 static int ulimitcmd(int, char **) FAST_FUNC;
8980 #define BUILTIN_NOSPEC "0"
8981 #define BUILTIN_SPECIAL "1"
8982 #define BUILTIN_REGULAR "2"
8983 #define BUILTIN_SPEC_REG "3"
8984 #define BUILTIN_ASSIGN "4"
8985 #define BUILTIN_SPEC_ASSG "5"
8986 #define BUILTIN_REG_ASSG "6"
8987 #define BUILTIN_SPEC_REG_ASSG "7"
8989 /* Stubs for calling non-FAST_FUNC's */
8990 #if ENABLE_ASH_BUILTIN_ECHO
8991 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8993 #if ENABLE_ASH_BUILTIN_PRINTF
8994 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8996 #if ENABLE_ASH_BUILTIN_TEST
8997 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9000 /* Keep these in proper order since it is searched via bsearch() */
9001 static const struct builtincmd builtintab[] = {
9002 { BUILTIN_SPEC_REG "." , dotcmd },
9003 { BUILTIN_SPEC_REG ":" , truecmd },
9004 #if ENABLE_ASH_BUILTIN_TEST
9005 { BUILTIN_REGULAR "[" , testcmd },
9006 #if ENABLE_ASH_BASH_COMPAT
9007 { BUILTIN_REGULAR "[[" , testcmd },
9010 #if ENABLE_ASH_ALIAS
9011 { BUILTIN_REG_ASSG "alias" , aliascmd },
9014 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9016 { BUILTIN_SPEC_REG "break" , breakcmd },
9017 { BUILTIN_REGULAR "cd" , cdcmd },
9018 { BUILTIN_NOSPEC "chdir" , cdcmd },
9019 #if ENABLE_ASH_CMDCMD
9020 { BUILTIN_REGULAR "command" , commandcmd },
9022 { BUILTIN_SPEC_REG "continue", breakcmd },
9023 #if ENABLE_ASH_BUILTIN_ECHO
9024 { BUILTIN_REGULAR "echo" , echocmd },
9026 { BUILTIN_SPEC_REG "eval" , evalcmd },
9027 { BUILTIN_SPEC_REG "exec" , execcmd },
9028 { BUILTIN_SPEC_REG "exit" , exitcmd },
9029 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9030 { BUILTIN_REGULAR "false" , falsecmd },
9032 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9034 #if ENABLE_ASH_GETOPTS
9035 { BUILTIN_REGULAR "getopts" , getoptscmd },
9037 { BUILTIN_NOSPEC "hash" , hashcmd },
9038 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9039 { BUILTIN_NOSPEC "help" , helpcmd },
9042 { BUILTIN_REGULAR "jobs" , jobscmd },
9043 { BUILTIN_REGULAR "kill" , killcmd },
9045 #if ENABLE_SH_MATH_SUPPORT
9046 { BUILTIN_NOSPEC "let" , letcmd },
9048 { BUILTIN_ASSIGN "local" , localcmd },
9049 #if ENABLE_ASH_BUILTIN_PRINTF
9050 { BUILTIN_REGULAR "printf" , printfcmd },
9052 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9053 { BUILTIN_REGULAR "read" , readcmd },
9054 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9055 { BUILTIN_SPEC_REG "return" , returncmd },
9056 { BUILTIN_SPEC_REG "set" , setcmd },
9057 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9058 #if ENABLE_ASH_BASH_COMPAT
9059 { BUILTIN_SPEC_REG "source" , dotcmd },
9061 #if ENABLE_ASH_BUILTIN_TEST
9062 { BUILTIN_REGULAR "test" , testcmd },
9064 { BUILTIN_SPEC_REG "times" , timescmd },
9065 { BUILTIN_SPEC_REG "trap" , trapcmd },
9066 { BUILTIN_REGULAR "true" , truecmd },
9067 { BUILTIN_NOSPEC "type" , typecmd },
9068 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9069 { BUILTIN_REGULAR "umask" , umaskcmd },
9070 #if ENABLE_ASH_ALIAS
9071 { BUILTIN_REGULAR "unalias" , unaliascmd },
9073 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9074 { BUILTIN_REGULAR "wait" , waitcmd },
9077 /* Should match the above table! */
9078 #define COMMANDCMD (builtintab + \
9080 1 * ENABLE_ASH_BUILTIN_TEST + \
9081 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9082 1 * ENABLE_ASH_ALIAS + \
9083 1 * ENABLE_ASH_JOB_CONTROL + \
9085 #define EXECCMD (builtintab + \
9087 1 * ENABLE_ASH_BUILTIN_TEST + \
9088 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9089 1 * ENABLE_ASH_ALIAS + \
9090 1 * ENABLE_ASH_JOB_CONTROL + \
9092 1 * ENABLE_ASH_CMDCMD + \
9094 ENABLE_ASH_BUILTIN_ECHO + \
9098 * Search the table of builtin commands.
9100 static struct builtincmd *
9101 find_builtin(const char *name)
9103 struct builtincmd *bp;
9106 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9113 * Execute a simple command.
9116 isassignment(const char *p)
9118 const char *q = endofname(p);
9123 static int FAST_FUNC
9124 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9126 /* Preserve exitstatus of a previous possible redirection
9127 * as POSIX mandates */
9128 return back_exitstatus;
9131 evalcommand(union node *cmd, int flags)
9133 static const struct builtincmd null_bltin = {
9134 "\0\0", bltincmd /* why three NULs? */
9136 struct stackmark smark;
9138 struct arglist arglist;
9139 struct arglist varlist;
9142 const struct strlist *sp;
9143 struct cmdentry cmdentry;
9150 struct builtincmd *bcmd;
9151 smallint cmd_is_exec;
9152 smallint pseudovarflag = 0;
9154 /* First expand the arguments. */
9155 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9156 setstackmark(&smark);
9157 back_exitstatus = 0;
9159 cmdentry.cmdtype = CMDBUILTIN;
9160 cmdentry.u.cmd = &null_bltin;
9161 varlist.lastp = &varlist.list;
9162 *varlist.lastp = NULL;
9163 arglist.lastp = &arglist.list;
9164 *arglist.lastp = NULL;
9167 if (cmd->ncmd.args) {
9168 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9169 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9172 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9173 struct strlist **spp;
9175 spp = arglist.lastp;
9176 if (pseudovarflag && isassignment(argp->narg.text))
9177 expandarg(argp, &arglist, EXP_VARTILDE);
9179 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9181 for (sp = *spp; sp; sp = sp->next)
9185 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9186 for (sp = arglist.list; sp; sp = sp->next) {
9187 TRACE(("evalcommand arg: %s\n", sp->text));
9188 *nargv++ = sp->text;
9193 if (iflag && funcnest == 0 && argc > 0)
9194 lastarg = nargv[-1];
9197 expredir(cmd->ncmd.redirect);
9198 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9200 path = vpath.var_text;
9201 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9202 struct strlist **spp;
9205 spp = varlist.lastp;
9206 expandarg(argp, &varlist, EXP_VARTILDE);
9209 * Modify the command lookup path, if a PATH= assignment
9213 if (varcmp(p, path) == 0)
9217 /* Print the command if xflag is set. */
9220 const char *p = " %s" + 1;
9222 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9224 for (n = 0; n < 2; n++) {
9226 fdprintf(preverrout_fd, p, sp->text);
9232 safe_write(preverrout_fd, "\n", 1);
9238 /* Now locate the command. */
9240 const char *oldpath;
9241 int cmd_flag = DO_ERR;
9246 find_command(argv[0], &cmdentry, cmd_flag, path);
9247 if (cmdentry.cmdtype == CMDUNKNOWN) {
9248 flush_stdout_stderr();
9253 /* implement bltin and command here */
9254 if (cmdentry.cmdtype != CMDBUILTIN)
9257 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9258 if (cmdentry.u.cmd == EXECCMD)
9260 #if ENABLE_ASH_CMDCMD
9261 if (cmdentry.u.cmd == COMMANDCMD) {
9263 nargv = parse_command_args(argv, &path);
9266 argc -= nargv - argv;
9268 cmd_flag |= DO_NOFUNC;
9276 /* We have a redirection error. */
9278 raise_exception(EXERROR);
9280 exitstatus = status;
9284 /* Execute the command. */
9285 switch (cmdentry.cmdtype) {
9288 #if ENABLE_FEATURE_SH_NOFORK
9289 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9290 * around run_nofork_applet() call.
9291 * (2) Should this check also be done in forkshell()?
9292 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9294 /* find_command() encodes applet_no as (-2 - applet_no) */
9295 int applet_no = (- cmdentry.u.index - 2);
9296 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9297 listsetvar(varlist.list, VEXPORT|VSTACK);
9298 /* run <applet>_main() */
9299 exitstatus = run_nofork_applet(applet_no, argv);
9303 /* Can we avoid forking off? For example, very last command
9304 * in a script or a subshell does not need forking,
9305 * we can just exec it.
9307 if (!(flags & EV_EXIT) || may_have_traps) {
9308 /* No, forking off a child is necessary */
9310 jp = makejob(/*cmd,*/ 1);
9311 if (forkshell(jp, cmd, FORK_FG) != 0) {
9313 exitstatus = waitforjob(jp);
9315 TRACE(("forked child exited with %d\n", exitstatus));
9320 /* fall through to exec'ing external program */
9322 listsetvar(varlist.list, VEXPORT|VSTACK);
9323 shellexec(argv, path, cmdentry.u.index);
9327 cmdenviron = varlist.list;
9329 struct strlist *list = cmdenviron;
9331 if (spclbltin > 0 || argc == 0) {
9333 if (cmd_is_exec && argc > 1)
9336 listsetvar(list, i);
9338 /* Tight loop with builtins only:
9339 * "while kill -0 $child; do true; done"
9340 * will never exit even if $child died, unless we do this
9341 * to reap the zombie and make kill detect that it's gone: */
9342 dowait(DOWAIT_NONBLOCK, NULL);
9344 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9346 int i = exception_type;
9351 exit_status = 128 + SIGINT;
9353 exit_status = 128 + pending_sig;
9354 exitstatus = exit_status;
9355 if (i == EXINT || spclbltin > 0) {
9357 longjmp(exception_handler->loc, 1);
9364 listsetvar(varlist.list, 0);
9365 /* See above for the rationale */
9366 dowait(DOWAIT_NONBLOCK, NULL);
9367 if (evalfun(cmdentry.u.func, argc, argv, flags))
9374 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9376 /* dsl: I think this is intended to be used to support
9377 * '_' in 'vi' command mode during line editing...
9378 * However I implemented that within libedit itself.
9380 setvar("_", lastarg, 0);
9382 popstackmark(&smark);
9386 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9388 char *volatile savecmdname;
9389 struct jmploc *volatile savehandler;
9390 struct jmploc jmploc;
9393 savecmdname = commandname;
9394 i = setjmp(jmploc.loc);
9397 savehandler = exception_handler;
9398 exception_handler = &jmploc;
9399 commandname = argv[0];
9401 optptr = NULL; /* initialize nextopt */
9402 exitstatus = (*cmd->builtin)(argc, argv);
9403 flush_stdout_stderr();
9405 exitstatus |= ferror(stdout);
9407 commandname = savecmdname;
9408 exception_handler = savehandler;
9414 goodname(const char *p)
9416 return endofname(p)[0] == '\0';
9421 * Search for a command. This is called before we fork so that the
9422 * location of the command will be available in the parent as well as
9423 * the child. The check for "goodname" is an overly conservative
9424 * check that the name will not be subject to expansion.
9427 prehash(union node *n)
9429 struct cmdentry entry;
9431 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9432 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9436 /* ============ Builtin commands
9438 * Builtin commands whose functions are closely tied to evaluation
9439 * are implemented here.
9443 * Handle break and continue commands. Break, continue, and return are
9444 * all handled by setting the evalskip flag. The evaluation routines
9445 * above all check this flag, and if it is set they start skipping
9446 * commands rather than executing them. The variable skipcount is
9447 * the number of loops to break/continue, or the number of function
9448 * levels to return. (The latter is always 1.) It should probably
9449 * be an error to break out of more loops than exist, but it isn't
9450 * in the standard shell so we don't make it one here.
9452 static int FAST_FUNC
9453 breakcmd(int argc UNUSED_PARAM, char **argv)
9455 int n = argv[1] ? number(argv[1]) : 1;
9458 ash_msg_and_raise_error(msg_illnum, argv[1]);
9462 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9469 /* ============ input.c
9471 * This implements the input routines used by the parser.
9475 INPUT_PUSH_FILE = 1,
9476 INPUT_NOFILE_OK = 2,
9479 static smallint checkkwd;
9480 /* values of checkkwd variable */
9481 #define CHKALIAS 0x1
9486 * Push a string back onto the input at this current parsefile level.
9487 * We handle aliases this way.
9489 #if !ENABLE_ASH_ALIAS
9490 #define pushstring(s, ap) pushstring(s)
9493 pushstring(char *s, struct alias *ap)
9500 if (g_parsefile->strpush) {
9501 sp = ckzalloc(sizeof(*sp));
9502 sp->prev = g_parsefile->strpush;
9504 sp = &(g_parsefile->basestrpush);
9506 g_parsefile->strpush = sp;
9507 sp->prev_string = g_parsefile->next_to_pgetc;
9508 sp->prev_left_in_line = g_parsefile->left_in_line;
9509 #if ENABLE_ASH_ALIAS
9512 ap->flag |= ALIASINUSE;
9516 g_parsefile->next_to_pgetc = s;
9517 g_parsefile->left_in_line = len;
9524 struct strpush *sp = g_parsefile->strpush;
9527 #if ENABLE_ASH_ALIAS
9529 if (g_parsefile->next_to_pgetc[-1] == ' '
9530 || g_parsefile->next_to_pgetc[-1] == '\t'
9532 checkkwd |= CHKALIAS;
9534 if (sp->string != sp->ap->val) {
9537 sp->ap->flag &= ~ALIASINUSE;
9538 if (sp->ap->flag & ALIASDEAD) {
9539 unalias(sp->ap->name);
9543 g_parsefile->next_to_pgetc = sp->prev_string;
9544 g_parsefile->left_in_line = sp->prev_left_in_line;
9545 g_parsefile->strpush = sp->prev;
9546 if (sp != &(g_parsefile->basestrpush))
9551 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9552 //it peeks whether it is &>, and then pushes back both chars.
9553 //This function needs to save last *next_to_pgetc to buf[0]
9554 //to make two pungetc() reliable. Currently,
9555 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9560 char *buf = g_parsefile->buf;
9562 g_parsefile->next_to_pgetc = buf;
9563 #if ENABLE_FEATURE_EDITING
9565 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9566 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9568 # if ENABLE_FEATURE_TAB_COMPLETION
9569 line_input_state->path_lookup = pathval();
9571 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9573 /* Ctrl+C pressed */
9582 if (nr < 0 && errno == 0) {
9583 /* Ctrl+D pressed */
9588 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9591 #if 0 /* disabled: nonblock_safe_read() handles this problem */
9593 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9594 int flags = fcntl(0, F_GETFL);
9595 if (flags >= 0 && (flags & O_NONBLOCK)) {
9596 flags &= ~O_NONBLOCK;
9597 if (fcntl(0, F_SETFL, flags) >= 0) {
9598 out2str("sh: turning off NDELAY mode\n");
9609 * Refill the input buffer and return the next input character:
9611 * 1) If a string was pushed back on the input, pop it;
9612 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9613 * or we are reading from a string so we can't refill the buffer,
9615 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9616 * 4) Process input up to the next newline, deleting nul characters.
9618 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9619 #define pgetc_debug(...) ((void)0)
9626 while (g_parsefile->strpush) {
9627 #if ENABLE_ASH_ALIAS
9628 if (g_parsefile->left_in_line == -1
9629 && g_parsefile->strpush->ap
9630 && g_parsefile->next_to_pgetc[-1] != ' '
9631 && g_parsefile->next_to_pgetc[-1] != '\t'
9633 pgetc_debug("preadbuffer PEOA");
9638 /* try "pgetc" now: */
9639 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9640 g_parsefile->left_in_line,
9641 g_parsefile->next_to_pgetc,
9642 g_parsefile->next_to_pgetc);
9643 if (--g_parsefile->left_in_line >= 0)
9644 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9646 /* on both branches above g_parsefile->left_in_line < 0.
9647 * "pgetc" needs refilling.
9650 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9651 * pungetc() may increment it a few times.
9652 * Assuming it won't increment it to less than -90.
9654 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9655 pgetc_debug("preadbuffer PEOF1");
9656 /* even in failure keep left_in_line and next_to_pgetc
9657 * in lock step, for correct multi-layer pungetc.
9658 * left_in_line was decremented before preadbuffer(),
9659 * must inc next_to_pgetc: */
9660 g_parsefile->next_to_pgetc++;
9664 more = g_parsefile->left_in_buffer;
9666 flush_stdout_stderr();
9670 /* don't try reading again */
9671 g_parsefile->left_in_line = -99;
9672 pgetc_debug("preadbuffer PEOF2");
9673 g_parsefile->next_to_pgetc++;
9678 /* Find out where's the end of line.
9679 * Set g_parsefile->left_in_line
9680 * and g_parsefile->left_in_buffer acordingly.
9681 * NUL chars are deleted.
9683 q = g_parsefile->next_to_pgetc;
9691 memmove(q, q + 1, more);
9695 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9701 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9702 if (g_parsefile->left_in_line < 0)
9707 g_parsefile->left_in_buffer = more;
9712 out2str(g_parsefile->next_to_pgetc);
9716 pgetc_debug("preadbuffer at %d:%p'%s'",
9717 g_parsefile->left_in_line,
9718 g_parsefile->next_to_pgetc,
9719 g_parsefile->next_to_pgetc);
9720 return (unsigned char)*g_parsefile->next_to_pgetc++;
9723 #define pgetc_as_macro() \
9724 (--g_parsefile->left_in_line >= 0 \
9725 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9732 pgetc_debug("pgetc_fast at %d:%p'%s'",
9733 g_parsefile->left_in_line,
9734 g_parsefile->next_to_pgetc,
9735 g_parsefile->next_to_pgetc);
9736 return pgetc_as_macro();
9739 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9740 # define pgetc_fast() pgetc()
9742 # define pgetc_fast() pgetc_as_macro()
9745 #if ENABLE_ASH_ALIAS
9747 pgetc_without_PEOA(void)
9751 pgetc_debug("pgetc_fast at %d:%p'%s'",
9752 g_parsefile->left_in_line,
9753 g_parsefile->next_to_pgetc,
9754 g_parsefile->next_to_pgetc);
9756 } while (c == PEOA);
9760 # define pgetc_without_PEOA() pgetc()
9764 * Read a line from the script.
9767 pfgets(char *line, int len)
9773 while (--nleft > 0) {
9774 c = pgetc_without_PEOA();
9789 * Undo the last call to pgetc. Only one character may be pushed back.
9790 * PEOF may be pushed back.
9795 g_parsefile->left_in_line++;
9796 g_parsefile->next_to_pgetc--;
9797 pgetc_debug("pushed back to %d:%p'%s'",
9798 g_parsefile->left_in_line,
9799 g_parsefile->next_to_pgetc,
9800 g_parsefile->next_to_pgetc);
9804 * To handle the "." command, a stack of input files is used. Pushfile
9805 * adds a new entry to the stack and popfile restores the previous level.
9810 struct parsefile *pf;
9812 pf = ckzalloc(sizeof(*pf));
9813 pf->prev = g_parsefile;
9815 /*pf->strpush = NULL; - ckzalloc did it */
9816 /*pf->basestrpush.prev = NULL;*/
9823 struct parsefile *pf = g_parsefile;
9831 g_parsefile = pf->prev;
9837 * Return to top level.
9842 while (g_parsefile != &basepf)
9847 * Close the file(s) that the shell is reading commands from. Called
9848 * after a fork is done.
9854 if (g_parsefile->pf_fd > 0) {
9855 close(g_parsefile->pf_fd);
9856 g_parsefile->pf_fd = 0;
9861 * Like setinputfile, but takes an open file descriptor. Call this with
9865 setinputfd(int fd, int push)
9867 close_on_exec_on(fd);
9870 g_parsefile->buf = NULL;
9872 g_parsefile->pf_fd = fd;
9873 if (g_parsefile->buf == NULL)
9874 g_parsefile->buf = ckmalloc(IBUFSIZ);
9875 g_parsefile->left_in_buffer = 0;
9876 g_parsefile->left_in_line = 0;
9877 g_parsefile->linno = 1;
9881 * Set the input to take input from a file. If push is set, push the
9882 * old input onto the stack first.
9885 setinputfile(const char *fname, int flags)
9891 fd = open(fname, O_RDONLY);
9893 if (flags & INPUT_NOFILE_OK)
9895 ash_msg_and_raise_error("can't open '%s'", fname);
9898 fd2 = copyfd(fd, 10);
9901 ash_msg_and_raise_error("out of file descriptors");
9904 setinputfd(fd, flags & INPUT_PUSH_FILE);
9911 * Like setinputfile, but takes input from a string.
9914 setinputstring(char *string)
9918 g_parsefile->next_to_pgetc = string;
9919 g_parsefile->left_in_line = strlen(string);
9920 g_parsefile->buf = NULL;
9921 g_parsefile->linno = 1;
9926 /* ============ mail.c
9928 * Routines to check for mail.
9933 #define MAXMBOXES 10
9935 /* times of mailboxes */
9936 static time_t mailtime[MAXMBOXES];
9937 /* Set if MAIL or MAILPATH is changed. */
9938 static smallint mail_var_path_changed;
9941 * Print appropriate message(s) if mail has arrived.
9942 * If mail_var_path_changed is set,
9943 * then the value of MAIL has mail_var_path_changed,
9944 * so we just update the values.
9953 struct stackmark smark;
9956 setstackmark(&smark);
9957 mpath = mpathset() ? mpathval() : mailval();
9958 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9959 p = path_advance(&mpath, nullstr);
9964 for (q = p; *q; q++)
9970 q[-1] = '\0'; /* delete trailing '/' */
9971 if (stat(p, &statb) < 0) {
9975 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9978 pathopt ? pathopt : "you have mail"
9981 *mtp = statb.st_mtime;
9983 mail_var_path_changed = 0;
9984 popstackmark(&smark);
9987 static void FAST_FUNC
9988 changemail(const char *val UNUSED_PARAM)
9990 mail_var_path_changed = 1;
9993 #endif /* ASH_MAIL */
9996 /* ============ ??? */
9999 * Set the shell parameters.
10002 setparam(char **argv)
10008 for (nparam = 0; argv[nparam]; nparam++)
10010 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10012 *ap++ = ckstrdup(*argv++);
10015 freeparam(&shellparam);
10016 shellparam.malloced = 1;
10017 shellparam.nparam = nparam;
10018 shellparam.p = newparam;
10019 #if ENABLE_ASH_GETOPTS
10020 shellparam.optind = 1;
10021 shellparam.optoff = -1;
10026 * Process shell options. The global variable argptr contains a pointer
10027 * to the argument list; we advance it past the options.
10029 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10030 * For a non-interactive shell, an error condition encountered
10031 * by a special built-in ... shall cause the shell to write a diagnostic message
10032 * to standard error and exit as shown in the following table:
10033 * Error Special Built-In
10035 * Utility syntax error (option or operand error) Shall exit
10037 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10038 * we see that bash does not do that (set "finishes" with error code 1 instead,
10039 * and shell continues), and people rely on this behavior!
10041 * set -o barfoo 2>/dev/null
10044 * Oh well. Let's mimic that.
10047 plus_minus_o(char *name, int val)
10052 for (i = 0; i < NOPTS; i++) {
10053 if (strcmp(name, optnames(i)) == 0) {
10058 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10061 for (i = 0; i < NOPTS; i++) {
10063 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10065 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10071 setoption(int flag, int val)
10075 for (i = 0; i < NOPTS; i++) {
10076 if (optletters(i) == flag) {
10081 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10085 options(int cmdline)
10093 while ((p = *argptr) != NULL) {
10095 if (c != '-' && c != '+')
10098 val = 0; /* val = 0 if c == '+' */
10101 if (p[0] == '\0' || LONE_DASH(p)) {
10103 /* "-" means turn off -x and -v */
10106 /* "--" means reset params */
10107 else if (*argptr == NULL)
10110 break; /* "-" or "--" terminates options */
10113 /* first char was + or - */
10114 while ((c = *p++) != '\0') {
10115 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10116 if (c == 'c' && cmdline) {
10117 minusc = p; /* command is after shell args */
10118 } else if (c == 'o') {
10119 if (plus_minus_o(*argptr, val)) {
10120 /* it already printed err message */
10121 return 1; /* error */
10125 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10127 /* bash does not accept +-login, we also won't */
10128 } else if (cmdline && val && (c == '-')) { /* long options */
10129 if (strcmp(p, "login") == 0)
10141 * The shift builtin command.
10143 static int FAST_FUNC
10144 shiftcmd(int argc UNUSED_PARAM, char **argv)
10151 n = number(argv[1]);
10152 if (n > shellparam.nparam)
10153 n = 0; /* bash compat, was = shellparam.nparam; */
10155 shellparam.nparam -= n;
10156 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10157 if (shellparam.malloced)
10160 ap2 = shellparam.p;
10161 while ((*ap2++ = *ap1++) != NULL)
10163 #if ENABLE_ASH_GETOPTS
10164 shellparam.optind = 1;
10165 shellparam.optoff = -1;
10172 * POSIX requires that 'set' (but not export or readonly) output the
10173 * variables in lexicographic order - by the locale's collating order (sigh).
10174 * Maybe we could keep them in an ordered balanced binary tree
10175 * instead of hashed lists.
10176 * For now just roll 'em through qsort for printing...
10179 showvars(const char *sep_prefix, int on, int off)
10182 char **ep, **epend;
10184 ep = listvars(on, off, &epend);
10185 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10187 sep = *sep_prefix ? " " : sep_prefix;
10189 for (; ep < epend; ep++) {
10193 p = strchrnul(*ep, '=');
10196 q = single_quote(++p);
10197 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10203 * The set command builtin.
10205 static int FAST_FUNC
10206 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10211 return showvars(nullstr, 0, VUNSET);
10214 if (!options(0)) { /* if no parse error... */
10217 if (*argptr != NULL) {
10225 #if ENABLE_ASH_RANDOM_SUPPORT
10226 static void FAST_FUNC
10227 change_random(const char *value)
10231 if (value == NULL) {
10232 /* "get", generate */
10233 t = next_random(&random_gen);
10234 /* set without recursion */
10235 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10236 vrandom.flags &= ~VNOFUNC;
10239 t = strtoul(value, NULL, 10);
10240 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10245 #if ENABLE_ASH_GETOPTS
10247 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10256 if (*param_optind < 1)
10258 optnext = optfirst + *param_optind - 1;
10260 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10263 p = optnext[-1] + *optoff;
10264 if (p == NULL || *p == '\0') {
10265 /* Current word is done, advance */
10267 if (p == NULL || *p != '-' || *++p == '\0') {
10274 if (LONE_DASH(p)) /* check for "--" */
10279 for (q = optstr; *q != c;) {
10281 if (optstr[0] == ':') {
10284 err |= setvarsafe("OPTARG", s, 0);
10286 fprintf(stderr, "Illegal option -%c\n", c);
10287 unsetvar("OPTARG");
10297 if (*p == '\0' && (p = *optnext) == NULL) {
10298 if (optstr[0] == ':') {
10301 err |= setvarsafe("OPTARG", s, 0);
10304 fprintf(stderr, "No arg for -%c option\n", c);
10305 unsetvar("OPTARG");
10313 err |= setvarsafe("OPTARG", p, 0);
10316 err |= setvarsafe("OPTARG", nullstr, 0);
10318 *optoff = p ? p - *(optnext - 1) : -1;
10319 *param_optind = optnext - optfirst + 1;
10320 fmtstr(s, sizeof(s), "%d", *param_optind);
10321 err |= setvarsafe("OPTIND", s, VNOFUNC);
10324 err |= setvarsafe(optvar, s, 0);
10328 flush_stdout_stderr();
10329 raise_exception(EXERROR);
10335 * The getopts builtin. Shellparam.optnext points to the next argument
10336 * to be processed. Shellparam.optptr points to the next character to
10337 * be processed in the current argument. If shellparam.optnext is NULL,
10338 * then it's the first time getopts has been called.
10340 static int FAST_FUNC
10341 getoptscmd(int argc, char **argv)
10346 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10348 optbase = shellparam.p;
10349 if (shellparam.optind > shellparam.nparam + 1) {
10350 shellparam.optind = 1;
10351 shellparam.optoff = -1;
10354 optbase = &argv[3];
10355 if (shellparam.optind > argc - 2) {
10356 shellparam.optind = 1;
10357 shellparam.optoff = -1;
10361 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10362 &shellparam.optoff);
10364 #endif /* ASH_GETOPTS */
10367 /* ============ Shell parser */
10370 struct heredoc *next; /* next here document in list */
10371 union node *here; /* redirection node */
10372 char *eofmark; /* string indicating end of input */
10373 smallint striptabs; /* if set, strip leading tabs */
10376 static smallint tokpushback; /* last token pushed back */
10377 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10378 static smallint quoteflag; /* set if (part of) last token was quoted */
10379 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10380 static struct heredoc *heredoclist; /* list of here documents to read */
10381 static char *wordtext; /* text of last word returned by readtoken */
10382 static struct nodelist *backquotelist;
10383 static union node *redirnode;
10384 static struct heredoc *heredoc;
10386 static const char *
10387 tokname(char *buf, int tok)
10390 return tokname_array[tok] + 1;
10391 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10395 /* raise_error_unexpected_syntax:
10396 * Called when an unexpected token is read during the parse. The argument
10397 * is the token that is expected, or -1 if more than one type of token can
10398 * occur at this point.
10400 static void raise_error_unexpected_syntax(int) NORETURN;
10402 raise_error_unexpected_syntax(int token)
10408 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10410 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10411 raise_error_syntax(msg);
10415 #define EOFMARKLEN 79
10417 /* parsing is heavily cross-recursive, need these forward decls */
10418 static union node *andor(void);
10419 static union node *pipeline(void);
10420 static union node *parse_command(void);
10421 static void parseheredoc(void);
10422 static char peektoken(void);
10423 static int readtoken(void);
10425 static union node *
10428 union node *n1, *n2, *n3;
10431 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10432 if (nlflag == 2 && peektoken())
10438 if (tok == TBACKGND) {
10439 if (n2->type == NPIPE) {
10440 n2->npipe.pipe_backgnd = 1;
10442 if (n2->type != NREDIR) {
10443 n3 = stzalloc(sizeof(struct nredir));
10445 /*n3->nredir.redirect = NULL; - stzalloc did it */
10448 n2->type = NBACKGND;
10454 n3 = stzalloc(sizeof(struct nbinary));
10456 n3->nbinary.ch1 = n1;
10457 n3->nbinary.ch2 = n2;
10473 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10481 pungetc(); /* push back EOF on input */
10485 raise_error_unexpected_syntax(-1);
10492 static union node *
10495 union node *n1, *n2, *n3;
10503 } else if (t == TOR) {
10509 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10511 n3 = stzalloc(sizeof(struct nbinary));
10513 n3->nbinary.ch1 = n1;
10514 n3->nbinary.ch2 = n2;
10519 static union node *
10522 union node *n1, *n2, *pipenode;
10523 struct nodelist *lp, *prev;
10527 TRACE(("pipeline: entered\n"));
10528 if (readtoken() == TNOT) {
10530 checkkwd = CHKKWD | CHKALIAS;
10533 n1 = parse_command();
10534 if (readtoken() == TPIPE) {
10535 pipenode = stzalloc(sizeof(struct npipe));
10536 pipenode->type = NPIPE;
10537 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10538 lp = stzalloc(sizeof(struct nodelist));
10539 pipenode->npipe.cmdlist = lp;
10543 lp = stzalloc(sizeof(struct nodelist));
10544 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10545 lp->n = parse_command();
10547 } while (readtoken() == TPIPE);
10553 n2 = stzalloc(sizeof(struct nnot));
10561 static union node *
10566 n = stzalloc(sizeof(struct narg));
10568 /*n->narg.next = NULL; - stzalloc did it */
10569 n->narg.text = wordtext;
10570 n->narg.backquote = backquotelist;
10575 fixredir(union node *n, const char *text, int err)
10579 TRACE(("Fix redir %s %d\n", text, err));
10581 n->ndup.vname = NULL;
10583 fd = bb_strtou(text, NULL, 10);
10584 if (!errno && fd >= 0)
10585 n->ndup.dupfd = fd;
10586 else if (LONE_DASH(text))
10587 n->ndup.dupfd = -1;
10590 raise_error_syntax("bad fd number");
10591 n->ndup.vname = makename();
10596 * Returns true if the text contains nothing to expand (no dollar signs
10600 noexpand(const char *text)
10604 while ((c = *text++) != '\0') {
10605 if (c == CTLQUOTEMARK)
10609 else if (SIT(c, BASESYNTAX) == CCTL)
10618 union node *n = redirnode;
10620 if (readtoken() != TWORD)
10621 raise_error_unexpected_syntax(-1);
10622 if (n->type == NHERE) {
10623 struct heredoc *here = heredoc;
10627 if (quoteflag == 0)
10629 TRACE(("Here document %d\n", n->type));
10630 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10631 raise_error_syntax("illegal eof marker for << redirection");
10632 rmescapes(wordtext, 0);
10633 here->eofmark = wordtext;
10635 if (heredoclist == NULL)
10636 heredoclist = here;
10638 for (p = heredoclist; p->next; p = p->next)
10642 } else if (n->type == NTOFD || n->type == NFROMFD) {
10643 fixredir(n, wordtext, 0);
10645 n->nfile.fname = makename();
10649 static union node *
10652 union node *args, **app;
10653 union node *n = NULL;
10654 union node *vars, **vpp;
10655 union node **rpp, *redir;
10657 #if ENABLE_ASH_BASH_COMPAT
10658 smallint double_brackets_flag = 0;
10668 savecheckkwd = CHKALIAS;
10671 checkkwd = savecheckkwd;
10674 #if ENABLE_ASH_BASH_COMPAT
10675 case TAND: /* "&&" */
10676 case TOR: /* "||" */
10677 if (!double_brackets_flag) {
10681 wordtext = (char *) (t == TAND ? "-a" : "-o");
10684 n = stzalloc(sizeof(struct narg));
10686 /*n->narg.next = NULL; - stzalloc did it */
10687 n->narg.text = wordtext;
10688 #if ENABLE_ASH_BASH_COMPAT
10689 if (strcmp("[[", wordtext) == 0)
10690 double_brackets_flag = 1;
10691 else if (strcmp("]]", wordtext) == 0)
10692 double_brackets_flag = 0;
10694 n->narg.backquote = backquotelist;
10695 if (savecheckkwd && isassignment(wordtext)) {
10697 vpp = &n->narg.next;
10700 app = &n->narg.next;
10705 *rpp = n = redirnode;
10706 rpp = &n->nfile.next;
10707 parsefname(); /* read name of redirection file */
10710 if (args && app == &args->narg.next
10713 struct builtincmd *bcmd;
10716 /* We have a function */
10717 if (readtoken() != TRP)
10718 raise_error_unexpected_syntax(TRP);
10719 name = n->narg.text;
10720 if (!goodname(name)
10721 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10723 raise_error_syntax("bad function name");
10726 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10727 n->narg.next = parse_command();
10740 n = stzalloc(sizeof(struct ncmd));
10742 n->ncmd.args = args;
10743 n->ncmd.assign = vars;
10744 n->ncmd.redirect = redir;
10748 static union node *
10749 parse_command(void)
10751 union node *n1, *n2;
10752 union node *ap, **app;
10753 union node *cp, **cpp;
10754 union node *redir, **rpp;
10761 switch (readtoken()) {
10763 raise_error_unexpected_syntax(-1);
10766 n1 = stzalloc(sizeof(struct nif));
10768 n1->nif.test = list(0);
10769 if (readtoken() != TTHEN)
10770 raise_error_unexpected_syntax(TTHEN);
10771 n1->nif.ifpart = list(0);
10773 while (readtoken() == TELIF) {
10774 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10775 n2 = n2->nif.elsepart;
10777 n2->nif.test = list(0);
10778 if (readtoken() != TTHEN)
10779 raise_error_unexpected_syntax(TTHEN);
10780 n2->nif.ifpart = list(0);
10782 if (lasttoken == TELSE)
10783 n2->nif.elsepart = list(0);
10785 n2->nif.elsepart = NULL;
10793 n1 = stzalloc(sizeof(struct nbinary));
10794 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10795 n1->nbinary.ch1 = list(0);
10798 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10799 got == TWORD ? wordtext : ""));
10800 raise_error_unexpected_syntax(TDO);
10802 n1->nbinary.ch2 = list(0);
10807 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10808 raise_error_syntax("bad for loop variable");
10809 n1 = stzalloc(sizeof(struct nfor));
10811 n1->nfor.var = wordtext;
10812 checkkwd = CHKKWD | CHKALIAS;
10813 if (readtoken() == TIN) {
10815 while (readtoken() == TWORD) {
10816 n2 = stzalloc(sizeof(struct narg));
10818 /*n2->narg.next = NULL; - stzalloc did it */
10819 n2->narg.text = wordtext;
10820 n2->narg.backquote = backquotelist;
10822 app = &n2->narg.next;
10825 n1->nfor.args = ap;
10826 if (lasttoken != TNL && lasttoken != TSEMI)
10827 raise_error_unexpected_syntax(-1);
10829 n2 = stzalloc(sizeof(struct narg));
10831 /*n2->narg.next = NULL; - stzalloc did it */
10832 n2->narg.text = (char *)dolatstr;
10833 /*n2->narg.backquote = NULL;*/
10834 n1->nfor.args = n2;
10836 * Newline or semicolon here is optional (but note
10837 * that the original Bourne shell only allowed NL).
10839 if (lasttoken != TNL && lasttoken != TSEMI)
10842 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10843 if (readtoken() != TDO)
10844 raise_error_unexpected_syntax(TDO);
10845 n1->nfor.body = list(0);
10849 n1 = stzalloc(sizeof(struct ncase));
10851 if (readtoken() != TWORD)
10852 raise_error_unexpected_syntax(TWORD);
10853 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10855 /*n2->narg.next = NULL; - stzalloc did it */
10856 n2->narg.text = wordtext;
10857 n2->narg.backquote = backquotelist;
10859 checkkwd = CHKKWD | CHKALIAS;
10860 } while (readtoken() == TNL);
10861 if (lasttoken != TIN)
10862 raise_error_unexpected_syntax(TIN);
10863 cpp = &n1->ncase.cases;
10865 checkkwd = CHKNL | CHKKWD;
10867 while (t != TESAC) {
10868 if (lasttoken == TLP)
10870 *cpp = cp = stzalloc(sizeof(struct nclist));
10872 app = &cp->nclist.pattern;
10874 *app = ap = stzalloc(sizeof(struct narg));
10876 /*ap->narg.next = NULL; - stzalloc did it */
10877 ap->narg.text = wordtext;
10878 ap->narg.backquote = backquotelist;
10879 if (readtoken() != TPIPE)
10881 app = &ap->narg.next;
10884 //ap->narg.next = NULL;
10885 if (lasttoken != TRP)
10886 raise_error_unexpected_syntax(TRP);
10887 cp->nclist.body = list(2);
10889 cpp = &cp->nclist.next;
10891 checkkwd = CHKNL | CHKKWD;
10895 raise_error_unexpected_syntax(TENDCASE);
10902 n1 = stzalloc(sizeof(struct nredir));
10903 n1->type = NSUBSHELL;
10904 n1->nredir.n = list(0);
10905 /*n1->nredir.redirect = NULL; - stzalloc did it */
10915 return simplecmd();
10918 if (readtoken() != t)
10919 raise_error_unexpected_syntax(t);
10922 /* Now check for redirection which may follow command */
10923 checkkwd = CHKKWD | CHKALIAS;
10925 while (readtoken() == TREDIR) {
10926 *rpp = n2 = redirnode;
10927 rpp = &n2->nfile.next;
10933 if (n1->type != NSUBSHELL) {
10934 n2 = stzalloc(sizeof(struct nredir));
10939 n1->nredir.redirect = redir;
10944 #if ENABLE_ASH_BASH_COMPAT
10945 static int decode_dollar_squote(void)
10947 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10953 p = strchr(C_escapes, c);
10958 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10962 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10964 } else if (c == 'x') { /* \xHH */
10968 } while (isxdigit(c) && --cnt);
10970 if (cnt == 3) { /* \x but next char is "bad" */
10974 } else { /* simple seq like \\ or \t */
10979 c = bb_process_escape_sequence((void*)&p);
10980 } else { /* unrecognized "\z": print both chars unless ' or " */
10981 if (c != '\'' && c != '"') {
10983 c |= 0x100; /* "please encode \, then me" */
10991 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10992 * is not NULL, read a here document. In the latter case, eofmark is the
10993 * word which marks the end of the document and striptabs is true if
10994 * leading tabs should be stripped from the document. The argument c
10995 * is the first character of the input token or document.
10997 * Because C does not have internal subroutines, I have simulated them
10998 * using goto's to implement the subroutine linkage. The following macros
10999 * will run code that appears at the end of readtoken1.
11001 #define CHECKEND() {goto checkend; checkend_return:;}
11002 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11003 #define PARSESUB() {goto parsesub; parsesub_return:;}
11004 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11005 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11006 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11008 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11010 /* NB: syntax parameter fits into smallint */
11011 /* c parameter is an unsigned char or PEOF or PEOA */
11014 char line[EOFMARKLEN + 1];
11015 struct nodelist *bqlist;
11019 smallint prevsyntax; /* syntax before arithmetic */
11020 #if ENABLE_ASH_EXPAND_PRMT
11021 smallint pssyntax; /* we are expanding a prompt string */
11023 int varnest; /* levels of variables expansion */
11024 int arinest; /* levels of arithmetic expansion */
11025 int parenlevel; /* levels of parens in arithmetic */
11026 int dqvarnest; /* levels of variables expansion within double quotes */
11028 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11031 /* Avoid longjmp clobbering */
11037 (void) &parenlevel;
11040 (void) &prevsyntax;
11043 startlinno = g_parsefile->linno;
11047 #if ENABLE_ASH_EXPAND_PRMT
11048 pssyntax = (syntax == PSSYNTAX);
11052 dblquote = (syntax == DQSYNTAX);
11058 STARTSTACKSTR(out);
11060 /* For each line, until end of word */
11061 CHECKEND(); /* set c to PEOF if at end of here document */
11062 for (;;) { /* until end of line or end of word */
11063 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11064 switch (SIT(c, syntax)) {
11065 case CNL: /* '\n' */
11066 if (syntax == BASESYNTAX)
11067 goto endword; /* exit outer loop */
11069 g_parsefile->linno++;
11070 setprompt_if(doprompt, 2);
11072 goto loop; /* continue outer loop */
11077 if (eofmark == NULL || dblquote)
11078 USTPUTC(CTLESC, out);
11079 #if ENABLE_ASH_BASH_COMPAT
11080 if (c == '\\' && bash_dollar_squote) {
11081 c = decode_dollar_squote();
11083 USTPUTC('\\', out);
11084 c = (unsigned char)c;
11090 case CBACK: /* backslash */
11091 c = pgetc_without_PEOA();
11093 USTPUTC(CTLESC, out);
11094 USTPUTC('\\', out);
11096 } else if (c == '\n') {
11097 setprompt_if(doprompt, 2);
11099 #if ENABLE_ASH_EXPAND_PRMT
11100 if (c == '$' && pssyntax) {
11101 USTPUTC(CTLESC, out);
11102 USTPUTC('\\', out);
11105 /* Backslash is retained if we are in "str" and next char isn't special */
11110 && (c != '"' || eofmark != NULL)
11112 USTPUTC(CTLESC, out);
11113 USTPUTC('\\', out);
11115 if (SIT(c, SQSYNTAX) == CCTL)
11116 USTPUTC(CTLESC, out);
11124 if (eofmark == NULL) {
11125 USTPUTC(CTLQUOTEMARK, out);
11133 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11134 if (eofmark != NULL && arinest == 0
11139 if (dqvarnest == 0) {
11140 syntax = BASESYNTAX;
11147 case CVAR: /* '$' */
11148 PARSESUB(); /* parse substitution */
11150 case CENDVAR: /* '}' */
11153 if (dqvarnest > 0) {
11160 #if ENABLE_SH_MATH_SUPPORT
11161 case CLP: /* '(' in arithmetic */
11165 case CRP: /* ')' in arithmetic */
11166 if (parenlevel > 0) {
11169 if (pgetc() == ')') {
11170 if (--arinest == 0) {
11171 syntax = prevsyntax;
11172 dblquote = (syntax == DQSYNTAX);
11177 * unbalanced parens
11178 * (don't 2nd guess - no error)
11186 case CBQUOTE: /* '`' */
11190 goto endword; /* exit outer loop */
11194 if (varnest == 0) {
11195 #if ENABLE_ASH_BASH_COMPAT
11197 if (pgetc() == '>')
11198 c = 0x100 + '>'; /* flag &> */
11202 goto endword; /* exit outer loop */
11204 IF_ASH_ALIAS(if (c != PEOA))
11211 #if ENABLE_SH_MATH_SUPPORT
11212 if (syntax == ARISYNTAX)
11213 raise_error_syntax("missing '))'");
11215 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11216 raise_error_syntax("unterminated quoted string");
11217 if (varnest != 0) {
11218 startlinno = g_parsefile->linno;
11220 raise_error_syntax("missing '}'");
11222 USTPUTC('\0', out);
11223 len = out - (char *)stackblock();
11224 out = stackblock();
11225 if (eofmark == NULL) {
11226 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11229 if (isdigit_str9(out)) {
11230 PARSEREDIR(); /* passed as params: out, c */
11231 lasttoken = TREDIR;
11234 /* else: non-number X seen, interpret it
11235 * as "NNNX>file" = "NNNX >file" */
11239 quoteflag = quotef;
11240 backquotelist = bqlist;
11241 grabstackblock(len);
11245 /* end of readtoken routine */
11248 * Check to see whether we are at the end of the here document. When this
11249 * is called, c is set to the first character of the next input line. If
11250 * we are at the end of the here document, this routine sets the c to PEOF.
11254 #if ENABLE_ASH_ALIAS
11256 c = pgetc_without_PEOA();
11259 while (c == '\t') {
11260 c = pgetc_without_PEOA();
11263 if (c == *eofmark) {
11264 if (pfgets(line, sizeof(line)) != NULL) {
11268 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11270 if (*p == '\n' && *q == '\0') {
11272 g_parsefile->linno++;
11273 needprompt = doprompt;
11275 pushstring(line, NULL);
11280 goto checkend_return;
11284 * Parse a redirection operator. The variable "out" points to a string
11285 * specifying the fd to be redirected. The variable "c" contains the
11286 * first character of the redirection operator.
11289 /* out is already checked to be a valid number or "" */
11290 int fd = (*out == '\0' ? -1 : atoi(out));
11293 np = stzalloc(sizeof(struct nfile));
11298 np->type = NAPPEND;
11300 np->type = NCLOBBER;
11303 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11309 #if ENABLE_ASH_BASH_COMPAT
11310 else if (c == 0x100 + '>') { /* this flags &> redirection */
11312 pgetc(); /* this is '>', no need to check */
11316 else { /* c == '<' */
11317 /*np->nfile.fd = 0; - stzalloc did it */
11321 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11322 np = stzalloc(sizeof(struct nhere));
11323 /*np->nfile.fd = 0; - stzalloc did it */
11326 heredoc = stzalloc(sizeof(struct heredoc));
11327 heredoc->here = np;
11330 heredoc->striptabs = 1;
11332 /*heredoc->striptabs = 0; - stzalloc did it */
11338 np->type = NFROMFD;
11342 np->type = NFROMTO;
11354 goto parseredir_return;
11358 * Parse a substitution. At this point, we have read the dollar sign
11359 * and nothing else.
11362 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11363 * (assuming ascii char codes, as the original implementation did) */
11364 #define is_special(c) \
11365 (((unsigned)(c) - 33 < 32) \
11366 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11368 unsigned char subtype;
11373 if (c > 255 /* PEOA or PEOF */
11374 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11376 #if ENABLE_ASH_BASH_COMPAT
11378 bash_dollar_squote = 1;
11383 } else if (c == '(') {
11384 /* $(command) or $((arith)) */
11385 if (pgetc() == '(') {
11386 #if ENABLE_SH_MATH_SUPPORT
11389 raise_error_syntax("you disabled math support for $((arith)) syntax");
11396 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11397 USTPUTC(CTLVAR, out);
11398 typeloc = out - (char *)stackblock();
11399 USTPUTC(VSNORMAL, out);
11400 subtype = VSNORMAL;
11406 c = '#'; /* ${#} - same as $# */
11408 subtype = VSLENGTH; /* ${#VAR} */
11413 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11414 /* $[{[#]]NAME[}] */
11418 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11419 } else if (isdigit(c)) {
11420 /* $[{[#]]NUM[}] */
11424 } while (isdigit(c));
11425 } else if (is_special(c)) {
11426 /* $[{[#]]<specialchar>[}] */
11431 raise_error_syntax("bad substitution");
11433 if (c != '}' && subtype == VSLENGTH) {
11434 /* ${#VAR didn't end with } */
11440 if (subtype == 0) {
11441 /* ${VAR...} but not $VAR or ${#VAR} */
11442 /* c == first char after VAR */
11446 #if ENABLE_ASH_BASH_COMPAT
11447 if (c == ':' || c == '$' || isdigit(c)) {
11448 //TODO: support more general format ${v:EXPR:EXPR},
11449 // where EXPR follows $(()) rules
11450 subtype = VSSUBSTR;
11452 break; /* "goto do_pungetc" is bigger (!) */
11458 static const char types[] ALIGN1 = "}-+?=";
11459 const char *p = strchr(types, c);
11462 subtype = p - types + VSNORMAL;
11468 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11475 #if ENABLE_ASH_BASH_COMPAT
11477 /* ${v/[/]pattern/repl} */
11478 //TODO: encode pattern and repl separately.
11479 // Currently ${v/$var_with_slash/repl} is horribly broken
11480 subtype = VSREPLACE;
11484 subtype++; /* VSREPLACEALL */
11492 if (dblquote || arinest)
11494 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11495 if (subtype != VSNORMAL) {
11497 if (dblquote || arinest) {
11502 goto parsesub_return;
11506 * Called to parse command substitutions. Newstyle is set if the command
11507 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11508 * list of commands (passed by reference), and savelen is the number of
11509 * characters on the top of the stack which must be preserved.
11512 struct nodelist **nlpp;
11515 char *volatile str;
11516 struct jmploc jmploc;
11517 struct jmploc *volatile savehandler;
11519 smallint saveprompt = 0;
11522 (void) &saveprompt;
11524 savepbq = parsebackquote;
11525 if (setjmp(jmploc.loc)) {
11527 parsebackquote = 0;
11528 exception_handler = savehandler;
11529 longjmp(exception_handler->loc, 1);
11533 savelen = out - (char *)stackblock();
11535 str = ckmalloc(savelen);
11536 memcpy(str, stackblock(), savelen);
11538 savehandler = exception_handler;
11539 exception_handler = &jmploc;
11542 /* We must read until the closing backquote, giving special
11543 treatment to some slashes, and then push the string and
11544 reread it as input, interpreting it normally. */
11549 STARTSTACKSTR(pout);
11553 setprompt_if(needprompt, 2);
11562 g_parsefile->linno++;
11563 setprompt_if(doprompt, 2);
11565 * If eating a newline, avoid putting
11566 * the newline into the new character
11567 * stream (via the STPUTC after the
11572 if (pc != '\\' && pc != '`' && pc != '$'
11573 && (!dblquote || pc != '"')
11575 STPUTC('\\', pout);
11577 if (pc <= 255 /* not PEOA or PEOF */) {
11583 IF_ASH_ALIAS(case PEOA:)
11584 startlinno = g_parsefile->linno;
11585 raise_error_syntax("EOF in backquote substitution");
11588 g_parsefile->linno++;
11589 needprompt = doprompt;
11598 STPUTC('\0', pout);
11599 psavelen = pout - (char *)stackblock();
11600 if (psavelen > 0) {
11601 pstr = grabstackstr(pout);
11602 setinputstring(pstr);
11607 nlpp = &(*nlpp)->next;
11608 *nlpp = stzalloc(sizeof(**nlpp));
11609 /* (*nlpp)->next = NULL; - stzalloc did it */
11610 parsebackquote = oldstyle;
11613 saveprompt = doprompt;
11620 doprompt = saveprompt;
11621 else if (readtoken() != TRP)
11622 raise_error_unexpected_syntax(TRP);
11627 * Start reading from old file again, ignoring any pushed back
11628 * tokens left from the backquote parsing
11633 while (stackblocksize() <= savelen)
11635 STARTSTACKSTR(out);
11637 memcpy(out, str, savelen);
11638 STADJUST(savelen, out);
11644 parsebackquote = savepbq;
11645 exception_handler = savehandler;
11646 if (arinest || dblquote)
11647 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11649 USTPUTC(CTLBACKQ, out);
11651 goto parsebackq_oldreturn;
11652 goto parsebackq_newreturn;
11655 #if ENABLE_SH_MATH_SUPPORT
11657 * Parse an arithmetic expansion (indicate start of one and set state)
11660 if (++arinest == 1) {
11661 prevsyntax = syntax;
11662 syntax = ARISYNTAX;
11663 USTPUTC(CTLARI, out);
11670 * we collapse embedded arithmetic expansion to
11671 * parenthesis, which should be equivalent
11675 goto parsearith_return;
11679 } /* end of readtoken */
11682 * Read the next input token.
11683 * If the token is a word, we set backquotelist to the list of cmds in
11684 * backquotes. We set quoteflag to true if any part of the word was
11686 * If the token is TREDIR, then we set redirnode to a structure containing
11688 * In all cases, the variable startlinno is set to the number of the line
11689 * on which the token starts.
11691 * [Change comment: here documents and internal procedures]
11692 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11693 * word parsing code into a separate routine. In this case, readtoken
11694 * doesn't need to have any internal procedures, but parseword does.
11695 * We could also make parseoperator in essence the main routine, and
11696 * have parseword (readtoken1?) handle both words and redirection.]
11698 #define NEW_xxreadtoken
11699 #ifdef NEW_xxreadtoken
11700 /* singles must be first! */
11701 static const char xxreadtoken_chars[7] ALIGN1 = {
11702 '\n', '(', ')', /* singles */
11703 '&', '|', ';', /* doubles */
11707 #define xxreadtoken_singles 3
11708 #define xxreadtoken_doubles 3
11710 static const char xxreadtoken_tokens[] ALIGN1 = {
11711 TNL, TLP, TRP, /* only single occurrence allowed */
11712 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11713 TEOF, /* corresponds to trailing nul */
11714 TAND, TOR, TENDCASE /* if double occurrence */
11726 setprompt_if(needprompt, 2);
11727 startlinno = g_parsefile->linno;
11728 for (;;) { /* until token or start of word found */
11730 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11734 while ((c = pgetc()) != '\n' && c != PEOF)
11737 } else if (c == '\\') {
11738 if (pgetc() != '\n') {
11740 break; /* return readtoken1(...) */
11742 startlinno = ++g_parsefile->linno;
11743 setprompt_if(doprompt, 2);
11747 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11750 g_parsefile->linno++;
11751 needprompt = doprompt;
11754 p = strchr(xxreadtoken_chars, c);
11756 break; /* return readtoken1(...) */
11758 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11760 if (cc == c) { /* double occurrence? */
11761 p += xxreadtoken_doubles + 1;
11764 #if ENABLE_ASH_BASH_COMPAT
11765 if (c == '&' && cc == '>') /* &> */
11766 break; /* return readtoken1(...) */
11771 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11776 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11778 #else /* old xxreadtoken */
11779 #define RETURN(token) return lasttoken = token
11789 setprompt_if(needprompt, 2);
11790 startlinno = g_parsefile->linno;
11791 for (;;) { /* until token or start of word found */
11794 case ' ': case '\t':
11795 IF_ASH_ALIAS(case PEOA:)
11798 while ((c = pgetc()) != '\n' && c != PEOF)
11803 if (pgetc() == '\n') {
11804 startlinno = ++g_parsefile->linno;
11805 setprompt_if(doprompt, 2);
11811 g_parsefile->linno++;
11812 needprompt = doprompt;
11817 if (pgetc() == '&')
11822 if (pgetc() == '|')
11827 if (pgetc() == ';')
11840 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11843 #endif /* old xxreadtoken */
11850 smallint alreadyseen = tokpushback;
11853 #if ENABLE_ASH_ALIAS
11862 if (checkkwd & CHKNL) {
11869 if (t != TWORD || quoteflag) {
11874 * check for keywords
11876 if (checkkwd & CHKKWD) {
11877 const char *const *pp;
11879 pp = findkwd(wordtext);
11881 lasttoken = t = pp - tokname_array;
11882 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11887 if (checkkwd & CHKALIAS) {
11888 #if ENABLE_ASH_ALIAS
11890 ap = lookupalias(wordtext, 1);
11893 pushstring(ap->val, ap);
11903 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11905 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11917 return tokname_array[t][0];
11921 * Read and parse a command. Returns NODE_EOF on end of file.
11922 * (NULL is a valid parse tree indicating a blank line.)
11924 static union node *
11925 parsecmd(int interact)
11930 doprompt = interact;
11931 setprompt_if(doprompt, doprompt);
11943 * Input any here documents.
11948 struct heredoc *here;
11951 here = heredoclist;
11952 heredoclist = NULL;
11955 setprompt_if(needprompt, 2);
11956 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
11957 here->eofmark, here->striptabs);
11958 n = stzalloc(sizeof(struct narg));
11959 n->narg.type = NARG;
11960 /*n->narg.next = NULL; - stzalloc did it */
11961 n->narg.text = wordtext;
11962 n->narg.backquote = backquotelist;
11963 here->here->nhere.doc = n;
11970 * called by editline -- any expansions to the prompt should be added here.
11972 #if ENABLE_ASH_EXPAND_PRMT
11973 static const char *
11974 expandstr(const char *ps)
11978 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11979 * and token processing _can_ alter it (delete NULs etc). */
11980 setinputstring((char *)ps);
11981 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11984 n.narg.type = NARG;
11985 n.narg.next = NULL;
11986 n.narg.text = wordtext;
11987 n.narg.backquote = backquotelist;
11989 expandarg(&n, NULL, 0);
11990 return stackblock();
11995 * Execute a command or commands contained in a string.
11998 evalstring(char *s, int mask)
12001 struct stackmark smark;
12005 setstackmark(&smark);
12008 while ((n = parsecmd(0)) != NODE_EOF) {
12010 popstackmark(&smark);
12023 * The eval command.
12025 static int FAST_FUNC
12026 evalcmd(int argc UNUSED_PARAM, char **argv)
12035 STARTSTACKSTR(concat);
12037 concat = stack_putstr(p, concat);
12041 STPUTC(' ', concat);
12043 STPUTC('\0', concat);
12044 p = grabstackstr(concat);
12046 evalstring(p, ~SKIPEVAL);
12052 * Read and execute commands.
12053 * "Top" is nonzero for the top level command loop;
12054 * it turns on prompting if the shell is interactive.
12060 struct stackmark smark;
12064 TRACE(("cmdloop(%d) called\n", top));
12068 setstackmark(&smark);
12071 showjobs(stderr, SHOW_CHANGED);
12074 if (iflag && top) {
12078 n = parsecmd(inter);
12080 if (DEBUG > 2 && debug && (n != NODE_EOF))
12083 if (n == NODE_EOF) {
12084 if (!top || numeof >= 50)
12086 if (!stoppedjobs()) {
12089 out2str("\nUse \"exit\" to leave shell.\n");
12092 } else if (nflag == 0) {
12093 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12098 popstackmark(&smark);
12103 return skip & SKIPEVAL;
12110 * Take commands from a file. To be compatible we should do a path
12111 * search for the file, which is necessary to find sub-commands.
12114 find_dot_file(char *name)
12117 const char *path = pathval();
12120 /* don't try this for absolute or relative paths */
12121 if (strchr(name, '/'))
12124 /* IIRC standards do not say whether . is to be searched.
12125 * And it is even smaller this way, making it unconditional for now:
12127 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12132 while ((fullname = path_advance(&path, name)) != NULL) {
12134 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12136 * Don't bother freeing here, since it will
12137 * be freed by the caller.
12141 if (fullname != name)
12142 stunalloc(fullname);
12145 /* not found in the PATH */
12146 ash_msg_and_raise_error("%s: not found", name);
12150 static int FAST_FUNC
12151 dotcmd(int argc, char **argv)
12154 struct strlist *sp;
12155 volatile struct shparam saveparam;
12157 for (sp = cmdenviron; sp; sp = sp->next)
12158 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12161 /* bash says: "bash: .: filename argument required" */
12162 return 2; /* bash compat */
12165 /* "false; . empty_file; echo $?" should print 0, not 1: */
12168 fullname = find_dot_file(argv[1]);
12172 if (argc) { /* argc > 0, argv[0] != NULL */
12173 saveparam = shellparam;
12174 shellparam.malloced = 0;
12175 shellparam.nparam = argc;
12176 shellparam.p = argv;
12179 setinputfile(fullname, INPUT_PUSH_FILE);
12180 commandname = fullname;
12185 freeparam(&shellparam);
12186 shellparam = saveparam;
12192 static int FAST_FUNC
12193 exitcmd(int argc UNUSED_PARAM, char **argv)
12198 exitstatus = number(argv[1]);
12199 raise_exception(EXEXIT);
12204 * Read a file containing shell functions.
12207 readcmdfile(char *name)
12209 setinputfile(name, INPUT_PUSH_FILE);
12215 /* ============ find_command inplementation */
12218 * Resolve a command name. If you change this routine, you may have to
12219 * change the shellexec routine as well.
12222 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12224 struct tblentry *cmdp;
12231 struct builtincmd *bcmd;
12233 /* If name contains a slash, don't use PATH or hash table */
12234 if (strchr(name, '/') != NULL) {
12235 entry->u.index = -1;
12236 if (act & DO_ABS) {
12237 while (stat(name, &statb) < 0) {
12239 if (errno == EINTR)
12242 entry->cmdtype = CMDUNKNOWN;
12246 entry->cmdtype = CMDNORMAL;
12250 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12252 updatetbl = (path == pathval());
12255 if (strstr(path, "%builtin") != NULL)
12256 act |= DO_ALTBLTIN;
12259 /* If name is in the table, check answer will be ok */
12260 cmdp = cmdlookup(name, 0);
12261 if (cmdp != NULL) {
12264 switch (cmdp->cmdtype) {
12282 } else if (cmdp->rehash == 0)
12283 /* if not invalidated by cd, we're done */
12287 /* If %builtin not in path, check for builtin next */
12288 bcmd = find_builtin(name);
12290 if (IS_BUILTIN_REGULAR(bcmd))
12291 goto builtin_success;
12292 if (act & DO_ALTPATH) {
12293 if (!(act & DO_ALTBLTIN))
12294 goto builtin_success;
12295 } else if (builtinloc <= 0) {
12296 goto builtin_success;
12300 #if ENABLE_FEATURE_SH_STANDALONE
12302 int applet_no = find_applet_by_name(name);
12303 if (applet_no >= 0) {
12304 entry->cmdtype = CMDNORMAL;
12305 entry->u.index = -2 - applet_no;
12311 /* We have to search path. */
12312 prev = -1; /* where to start */
12313 if (cmdp && cmdp->rehash) { /* doing a rehash */
12314 if (cmdp->cmdtype == CMDBUILTIN)
12317 prev = cmdp->param.index;
12323 while ((fullname = path_advance(&path, name)) != NULL) {
12324 stunalloc(fullname);
12325 /* NB: code below will still use fullname
12326 * despite it being "unallocated" */
12329 if (prefix(pathopt, "builtin")) {
12331 goto builtin_success;
12334 if ((act & DO_NOFUNC)
12335 || !prefix(pathopt, "func")
12336 ) { /* ignore unimplemented options */
12340 /* if rehash, don't redo absolute path names */
12341 if (fullname[0] == '/' && idx <= prev) {
12344 TRACE(("searchexec \"%s\": no change\n", name));
12347 while (stat(fullname, &statb) < 0) {
12349 if (errno == EINTR)
12352 if (errno != ENOENT && errno != ENOTDIR)
12356 e = EACCES; /* if we fail, this will be the error */
12357 if (!S_ISREG(statb.st_mode))
12359 if (pathopt) { /* this is a %func directory */
12360 stalloc(strlen(fullname) + 1);
12361 /* NB: stalloc will return space pointed by fullname
12362 * (because we don't have any intervening allocations
12363 * between stunalloc above and this stalloc) */
12364 readcmdfile(fullname);
12365 cmdp = cmdlookup(name, 0);
12366 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12367 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12368 stunalloc(fullname);
12371 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12373 entry->cmdtype = CMDNORMAL;
12374 entry->u.index = idx;
12378 cmdp = cmdlookup(name, 1);
12379 cmdp->cmdtype = CMDNORMAL;
12380 cmdp->param.index = idx;
12385 /* We failed. If there was an entry for this command, delete it */
12386 if (cmdp && updatetbl)
12387 delete_cmd_entry();
12389 ash_msg("%s: %s", name, errmsg(e, "not found"));
12390 entry->cmdtype = CMDUNKNOWN;
12395 entry->cmdtype = CMDBUILTIN;
12396 entry->u.cmd = bcmd;
12400 cmdp = cmdlookup(name, 1);
12401 cmdp->cmdtype = CMDBUILTIN;
12402 cmdp->param.cmd = bcmd;
12406 entry->cmdtype = cmdp->cmdtype;
12407 entry->u = cmdp->param;
12411 /* ============ trap.c */
12414 * The trap builtin.
12416 static int FAST_FUNC
12417 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12421 int signo, exitcode;
12426 for (signo = 0; signo < NSIG; signo++) {
12427 char *tr = trap_ptr[signo];
12429 /* note: bash adds "SIG", but only if invoked
12430 * as "bash". If called as "sh", or if set -o posix,
12431 * then it prints short signal names.
12432 * We are printing short names: */
12433 out1fmt("trap -- %s %s\n",
12435 get_signame(signo));
12436 /* trap_ptr != trap only if we are in special-cased `trap` code.
12437 * In this case, we will exit very soon, no need to free(). */
12438 /* if (trap_ptr != trap && tp[0]) */
12443 if (trap_ptr != trap) {
12456 signo = get_signum(*ap);
12458 /* Mimic bash message exactly */
12459 ash_msg("%s: invalid signal specification", *ap);
12465 if (LONE_DASH(action))
12468 action = ckstrdup(action);
12472 may_have_traps = 1;
12473 trap[signo] = action;
12484 /* ============ Builtins */
12486 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12488 * Lists available builtins
12490 static int FAST_FUNC
12491 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12497 "Built-in commands:\n"
12498 "------------------\n");
12499 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12500 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12501 builtintab[i].name + 1);
12507 #if ENABLE_FEATURE_SH_STANDALONE
12509 const char *a = applet_names;
12511 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12516 a += strlen(a) + 1;
12521 return EXIT_SUCCESS;
12523 #endif /* FEATURE_SH_EXTRA_QUIET */
12526 * The export and readonly commands.
12528 static int FAST_FUNC
12529 exportcmd(int argc UNUSED_PARAM, char **argv)
12535 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12537 if (nextopt("p") != 'p') {
12542 p = strchr(name, '=');
12546 vp = *findvar(hashvar(name), name);
12552 setvar(name, p, flag);
12553 } while ((name = *++aptr) != NULL);
12557 showvars(argv[0], flag, 0);
12562 * Delete a function if it exists.
12565 unsetfunc(const char *name)
12567 struct tblentry *cmdp;
12569 cmdp = cmdlookup(name, 0);
12570 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12571 delete_cmd_entry();
12575 * The unset builtin command. We unset the function before we unset the
12576 * variable to allow a function to be unset when there is a readonly variable
12577 * with the same name.
12579 static int FAST_FUNC
12580 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12587 while ((i = nextopt("vf")) != 0) {
12591 for (ap = argptr; *ap; ap++) {
12604 static const unsigned char timescmd_str[] ALIGN1 = {
12605 ' ', offsetof(struct tms, tms_utime),
12606 '\n', offsetof(struct tms, tms_stime),
12607 ' ', offsetof(struct tms, tms_cutime),
12608 '\n', offsetof(struct tms, tms_cstime),
12611 static int FAST_FUNC
12612 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12614 unsigned long clk_tck, s, t;
12615 const unsigned char *p;
12618 clk_tck = sysconf(_SC_CLK_TCK);
12623 t = *(clock_t *)(((char *) &buf) + p[1]);
12626 out1fmt("%lum%lu.%03lus%c",
12628 (t * 1000) / clk_tck,
12636 #if ENABLE_SH_MATH_SUPPORT
12638 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12639 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12641 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12643 static int FAST_FUNC
12644 letcmd(int argc UNUSED_PARAM, char **argv)
12650 ash_msg_and_raise_error("expression expected");
12652 i = ash_arith(*argv);
12660 * The read builtin. Options:
12661 * -r Do not interpret '\' specially
12662 * -s Turn off echo (tty only)
12663 * -n NCHARS Read NCHARS max
12664 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12665 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12666 * -u FD Read from given FD instead of fd 0
12667 * This uses unbuffered input, which may be avoidable in some cases.
12668 * TODO: bash also has:
12669 * -a ARRAY Read into array[0],[1],etc
12670 * -d DELIM End on DELIM char, not newline
12671 * -e Use line editing (tty only)
12673 static int FAST_FUNC
12674 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12676 char *opt_n = NULL;
12677 char *opt_p = NULL;
12678 char *opt_t = NULL;
12679 char *opt_u = NULL;
12680 int read_flags = 0;
12684 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12693 read_flags |= BUILTIN_READ_SILENT;
12699 read_flags |= BUILTIN_READ_RAW;
12709 r = shell_builtin_read(setvar2,
12711 bltinlookup("IFS"), /* can be NULL */
12719 if ((uintptr_t)r > 1)
12720 ash_msg_and_raise_error(r);
12722 return (uintptr_t)r;
12725 static int FAST_FUNC
12726 umaskcmd(int argc UNUSED_PARAM, char **argv)
12728 static const char permuser[3] ALIGN1 = "ugo";
12729 static const char permmode[3] ALIGN1 = "rwx";
12730 static const short permmask[] ALIGN2 = {
12731 S_IRUSR, S_IWUSR, S_IXUSR,
12732 S_IRGRP, S_IWGRP, S_IXGRP,
12733 S_IROTH, S_IWOTH, S_IXOTH
12736 /* TODO: use bb_parse_mode() instead */
12741 int symbolic_mode = 0;
12743 while (nextopt("S") != '\0') {
12754 if (symbolic_mode) {
12758 for (i = 0; i < 3; i++) {
12761 *p++ = permuser[i];
12763 for (j = 0; j < 3; j++) {
12764 if ((mask & permmask[3 * i + j]) == 0) {
12765 *p++ = permmode[j];
12773 out1fmt("%.4o\n", mask);
12776 if (isdigit((unsigned char) *ap)) {
12779 if (*ap >= '8' || *ap < '0')
12780 ash_msg_and_raise_error(msg_illnum, argv[1]);
12781 mask = (mask << 3) + (*ap - '0');
12782 } while (*++ap != '\0');
12785 mask = ~mask & 0777;
12786 if (!bb_parse_mode(ap, &mask)) {
12787 ash_msg_and_raise_error("illegal mode: %s", ap);
12789 umask(~mask & 0777);
12795 static int FAST_FUNC
12796 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12798 return shell_builtin_ulimit(argv);
12801 /* ============ main() and helpers */
12804 * Called to exit the shell.
12806 static void exitshell(void) NORETURN;
12814 status = exitstatus;
12815 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12816 if (setjmp(loc.loc)) {
12817 if (exception_type == EXEXIT)
12818 /* dash bug: it just does _exit(exitstatus) here
12819 * but we have to do setjobctl(0) first!
12820 * (bug is still not fixed in dash-0.5.3 - if you run dash
12821 * under Midnight Commander, on exit from dash MC is backgrounded) */
12822 status = exitstatus;
12825 exception_handler = &loc;
12832 flush_stdout_stderr();
12842 /* from input.c: */
12843 /* we will never free this */
12844 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12847 signal(SIGCHLD, SIG_DFL);
12848 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12849 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12851 signal(SIGHUP, SIG_DFL);
12857 struct stat st1, st2;
12860 for (envp = environ; envp && *envp; envp++) {
12861 if (strchr(*envp, '=')) {
12862 setvareq(*envp, VEXPORT|VTEXTFIXED);
12866 setvar("PPID", utoa(getppid()), 0);
12868 p = lookupvar("PWD");
12870 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12871 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12878 * Process the shell command line arguments.
12881 procargs(char **argv)
12884 const char *xminusc;
12889 /* if (xargv[0]) - mmm, this is always true! */
12891 for (i = 0; i < NOPTS; i++)
12895 /* it already printed err message */
12896 raise_exception(EXERROR);
12900 if (*xargv == NULL) {
12902 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12905 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12909 for (i = 0; i < NOPTS; i++)
12910 if (optlist[i] == 2)
12915 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12920 } else if (!sflag) {
12921 setinputfile(*xargv, 0);
12924 commandname = arg0;
12927 shellparam.p = xargv;
12928 #if ENABLE_ASH_GETOPTS
12929 shellparam.optind = 1;
12930 shellparam.optoff = -1;
12932 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12934 shellparam.nparam++;
12941 * Read /etc/profile or .profile.
12944 read_profile(const char *name)
12948 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12957 * This routine is called when an error or an interrupt occurs in an
12958 * interactive shell and control is returned to the main command loop.
12966 /* from input.c: */
12967 g_parsefile->left_in_buffer = 0;
12968 g_parsefile->left_in_line = 0; /* clear input buffer */
12970 /* from parser.c: */
12973 /* from redir.c: */
12974 clearredir(/*drop:*/ 0);
12978 static short profile_buf[16384];
12979 extern int etext();
12983 * Main routine. We initialize things, parse the arguments, execute
12984 * profiles if we're a login shell, and then call cmdloop to execute
12985 * commands. The setjmp call sets up the location to jump to when an
12986 * exception occurs. When an exception occurs the variable "state"
12987 * is used to figure out how far we had gotten.
12989 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12990 int ash_main(int argc UNUSED_PARAM, char **argv)
12992 const char *shinit;
12993 volatile smallint state;
12994 struct jmploc jmploc;
12995 struct stackmark smark;
12997 /* Initialize global data */
13001 #if ENABLE_ASH_ALIAS
13007 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13010 #if ENABLE_FEATURE_EDITING
13011 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13014 if (setjmp(jmploc.loc)) {
13020 e = exception_type;
13024 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13028 outcslow('\n', stderr);
13031 popstackmark(&smark);
13032 FORCE_INT_ON; /* enable interrupts */
13041 exception_handler = &jmploc;
13044 TRACE(("Shell args: "));
13045 trace_puts_args(argv);
13047 rootpid = getpid();
13050 setstackmark(&smark);
13053 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13055 const char *hp = lookupvar("HISTFILE");
13058 hp = lookupvar("HOME");
13060 char *defhp = concat_path_file(hp, ".ash_history");
13061 setvar("HISTFILE", defhp, 0);
13067 if (argv[0] && argv[0][0] == '-')
13071 read_profile("/etc/profile");
13074 read_profile(".profile");
13080 getuid() == geteuid() && getgid() == getegid() &&
13084 shinit = lookupvar("ENV");
13085 if (shinit != NULL && *shinit != '\0') {
13086 read_profile(shinit);
13092 /* evalstring pushes parsefile stack.
13093 * Ensure we don't falsely claim that 0 (stdin)
13094 * is one of stacked source fds.
13095 * Testcase: ash -c 'exec 1>&0' must not complain. */
13096 // if (!sflag) g_parsefile->pf_fd = -1;
13097 // ^^ not necessary since now we special-case fd 0
13098 // in is_hidden_fd() to not be considered "hidden fd"
13099 evalstring(minusc, 0);
13102 if (sflag || minusc == NULL) {
13103 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13105 const char *hp = lookupvar("HISTFILE");
13107 line_input_state->hist_file = hp;
13110 state4: /* XXX ??? - why isn't this before the "if" statement */
13118 extern void _mcleanup(void);
13122 TRACE(("End of main reached\n"));
13129 * Copyright (c) 1989, 1991, 1993, 1994
13130 * The Regents of the University of California. All rights reserved.
13132 * This code is derived from software contributed to Berkeley by
13133 * Kenneth Almquist.
13135 * Redistribution and use in source and binary forms, with or without
13136 * modification, are permitted provided that the following conditions
13138 * 1. Redistributions of source code must retain the above copyright
13139 * notice, this list of conditions and the following disclaimer.
13140 * 2. Redistributions in binary form must reproduce the above copyright
13141 * notice, this list of conditions and the following disclaimer in the
13142 * documentation and/or other materials provided with the distribution.
13143 * 3. Neither the name of the University nor the names of its contributors
13144 * may be used to endorse or promote products derived from this software
13145 * without specific prior written permission.
13147 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13148 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13149 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13150 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13151 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13152 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13153 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13154 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13155 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13156 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF