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_IDLE_TIMEOUT
101 //config: bool "Idle timeout variable"
103 //config: depends on ASH
105 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
107 //config:config ASH_JOB_CONTROL
108 //config: bool "Job control"
110 //config: depends on ASH
112 //config: Enable job control in the ash shell.
114 //config:config ASH_ALIAS
115 //config: bool "Alias support"
117 //config: depends on ASH
119 //config: Enable alias support in the ash shell.
121 //config:config ASH_GETOPTS
122 //config: bool "Builtin getopt to parse positional parameters"
124 //config: depends on ASH
126 //config: Enable support for getopts builtin in ash.
128 //config:config ASH_BUILTIN_ECHO
129 //config: bool "Builtin version of 'echo'"
131 //config: depends on ASH
133 //config: Enable support for echo builtin in ash.
135 //config:config ASH_BUILTIN_PRINTF
136 //config: bool "Builtin version of 'printf'"
138 //config: depends on ASH
140 //config: Enable support for printf builtin in ash.
142 //config:config ASH_BUILTIN_TEST
143 //config: bool "Builtin version of 'test'"
145 //config: depends on ASH
147 //config: Enable support for test builtin in ash.
149 //config:config ASH_CMDCMD
150 //config: bool "'command' command to override shell builtins"
152 //config: depends on ASH
154 //config: Enable support for the ash 'command' builtin, which allows
155 //config: you to run the specified command with the specified arguments,
156 //config: even when there is an ash builtin command with the same name.
158 //config:config ASH_MAIL
159 //config: bool "Check for new mail on interactive shells"
161 //config: depends on ASH
163 //config: Enable "check for new mail" function in the ash shell.
165 //config:config ASH_OPTIMIZE_FOR_SIZE
166 //config: bool "Optimize for size instead of speed"
168 //config: depends on ASH
170 //config: Compile ash for reduced size at the price of speed.
172 //config:config ASH_RANDOM_SUPPORT
173 //config: bool "Pseudorandom generator and $RANDOM variable"
175 //config: depends on ASH
177 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
178 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
179 //config: You can reset the generator by using a specified start value.
180 //config: After "unset RANDOM" the generator will switch off and this
181 //config: variable will no longer have special treatment.
183 //config:config ASH_EXPAND_PRMT
184 //config: bool "Expand prompt string"
186 //config: depends on ASH
188 //config: "PS#" may contain volatile content, such as backquote commands.
189 //config: This option recreates the prompt string from the environment
190 //config: variable each time it is displayed.
193 //usage:#define ash_trivial_usage NOUSAGE_STR
194 //usage:#define ash_full_usage ""
195 //usage:#define sh_trivial_usage NOUSAGE_STR
196 //usage:#define sh_full_usage ""
197 //usage:#define bash_trivial_usage NOUSAGE_STR
198 //usage:#define bash_full_usage ""
201 /* ============ Hash table sizes. Configurable. */
205 #define CMDTABLESIZE 31 /* should be prime */
208 /* ============ Shell options */
210 static const char *const optletters_optnames[] = {
225 #if ENABLE_ASH_BASH_COMPAT
234 #define optletters(n) optletters_optnames[n][0]
235 #define optnames(n) (optletters_optnames[n] + 1)
237 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
240 /* ============ Misc data */
242 #define msg_illnum "Illegal number: %s"
245 * We enclose jmp_buf in a structure so that we can declare pointers to
246 * jump locations. The global variable handler contains the location to
247 * jump to when an exception occurs, and the global variable exception_type
248 * contains a code identifying the exception. To implement nested
249 * exception handlers, the user should save the value of handler on entry
250 * to an inner scope, set handler to point to a jmploc structure for the
251 * inner scope, and restore handler on exit from the scope.
257 struct globals_misc {
258 /* pid of main shell */
260 /* shell level: 0 for the main shell, 1 for its children, and so on */
262 #define rootshell (!shlvl)
263 char *minusc; /* argument to -c option */
265 char *curdir; // = nullstr; /* current working directory */
266 char *physdir; // = nullstr; /* physical working directory */
268 char *arg0; /* value of $0 */
270 struct jmploc *exception_handler;
272 volatile int suppress_int; /* counter */
273 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
274 /* last pending signal */
275 volatile /*sig_atomic_t*/ smallint pending_sig;
276 smallint exception_type; /* kind of exception (0..5) */
278 #define EXINT 0 /* SIGINT received */
279 #define EXERROR 1 /* a generic error */
280 #define EXSHELLPROC 2 /* execute a shell procedure */
281 #define EXEXEC 3 /* command execution failed */
282 #define EXEXIT 4 /* exit the shell */
283 #define EXSIG 5 /* trapped signal in wait(1) */
286 char nullstr[1]; /* zero length string */
289 #define eflag optlist[0]
290 #define fflag optlist[1]
291 #define Iflag optlist[2]
292 #define iflag optlist[3]
293 #define mflag optlist[4]
294 #define nflag optlist[5]
295 #define sflag optlist[6]
296 #define xflag optlist[7]
297 #define vflag optlist[8]
298 #define Cflag optlist[9]
299 #define aflag optlist[10]
300 #define bflag optlist[11]
301 #define uflag optlist[12]
302 #define viflag optlist[13]
303 #if ENABLE_ASH_BASH_COMPAT
304 # define pipefail optlist[14]
309 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
310 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
313 /* trap handler commands */
315 * Sigmode records the current value of the signal handlers for the various
316 * modes. A value of zero means that the current handler is not known.
317 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
319 char sigmode[NSIG - 1];
320 #define S_DFL 1 /* default signal handling (SIG_DFL) */
321 #define S_CATCH 2 /* signal is caught */
322 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
323 #define S_HARD_IGN 4 /* signal is ignored permenantly */
325 /* indicates specified signal received */
326 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
327 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
329 char **trap_ptr; /* used only by "trap hack" */
331 /* Rarely referenced stuff */
332 #if ENABLE_ASH_RANDOM_SUPPORT
335 pid_t backgndpid; /* pid of last background process */
336 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
338 extern struct globals_misc *const ash_ptr_to_globals_misc;
339 #define G_misc (*ash_ptr_to_globals_misc)
340 #define rootpid (G_misc.rootpid )
341 #define shlvl (G_misc.shlvl )
342 #define minusc (G_misc.minusc )
343 #define curdir (G_misc.curdir )
344 #define physdir (G_misc.physdir )
345 #define arg0 (G_misc.arg0 )
346 #define exception_handler (G_misc.exception_handler)
347 #define exception_type (G_misc.exception_type )
348 #define suppress_int (G_misc.suppress_int )
349 #define pending_int (G_misc.pending_int )
350 #define pending_sig (G_misc.pending_sig )
351 #define isloginsh (G_misc.isloginsh )
352 #define nullstr (G_misc.nullstr )
353 #define optlist (G_misc.optlist )
354 #define sigmode (G_misc.sigmode )
355 #define gotsig (G_misc.gotsig )
356 #define may_have_traps (G_misc.may_have_traps )
357 #define trap (G_misc.trap )
358 #define trap_ptr (G_misc.trap_ptr )
359 #define random_gen (G_misc.random_gen )
360 #define backgndpid (G_misc.backgndpid )
361 #define job_warning (G_misc.job_warning)
362 #define INIT_G_misc() do { \
363 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
371 /* ============ DEBUG */
373 static void trace_printf(const char *fmt, ...);
374 static void trace_vprintf(const char *fmt, va_list va);
375 # define TRACE(param) trace_printf param
376 # define TRACEV(param) trace_vprintf param
377 # define close(fd) do { \
379 if (close(dfd) < 0) \
380 bb_error_msg("bug on %d: closing %d(0x%x)", \
381 __LINE__, dfd, dfd); \
384 # define TRACE(param)
385 # define TRACEV(param)
389 /* ============ Utility functions */
390 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
392 static int isdigit_str9(const char *str)
394 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
395 while (--maxlen && isdigit(*str))
397 return (*str == '\0');
400 static const char *var_end(const char *var)
409 /* ============ Interrupts / exceptions */
411 static void exitshell(void) NORETURN;
414 * These macros allow the user to suspend the handling of interrupt signals
415 * over a period of time. This is similar to SIGHOLD or to sigblock, but
416 * much more efficient and portable. (But hacking the kernel is so much
417 * more fun than worrying about efficiency and portability. :-))
419 #define INT_OFF do { \
425 * Called to raise an exception. Since C doesn't include exceptions, we
426 * just do a longjmp to the exception handler. The type of exception is
427 * stored in the global variable "exception_type".
429 static void raise_exception(int) NORETURN;
431 raise_exception(int e)
434 if (exception_handler == NULL)
439 longjmp(exception_handler->loc, 1);
442 #define raise_exception(e) do { \
443 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
444 raise_exception(e); \
449 * Called from trap.c when a SIGINT is received. (If the user specifies
450 * that SIGINT is to be trapped or ignored using the trap builtin, then
451 * this routine is not called.) Suppressint is nonzero when interrupts
452 * are held using the INT_OFF macro. (The test for iflag is just
453 * defensive programming.)
455 static void raise_interrupt(void) NORETURN;
457 raise_interrupt(void)
462 /* Signal is not automatically unmasked after it is raised,
463 * do it ourself - unmask all signals */
464 sigprocmask_allsigs(SIG_UNBLOCK);
465 /* pending_sig = 0; - now done in signal_handler() */
468 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
469 if (!(rootshell && iflag)) {
470 /* Kill ourself with SIGINT */
471 signal(SIGINT, SIG_DFL);
476 raise_exception(ex_type);
480 #define raise_interrupt() do { \
481 TRACE(("raising interrupt on line %d\n", __LINE__)); \
486 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
490 if (--suppress_int == 0 && pending_int) {
494 #define INT_ON int_on()
495 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
503 #define FORCE_INT_ON force_int_on()
505 #define SAVE_INT(v) ((v) = suppress_int)
507 #define RESTORE_INT(v) do { \
509 suppress_int = (v); \
510 if (suppress_int == 0 && pending_int) \
515 /* ============ Stdout/stderr output */
518 outstr(const char *p, FILE *file)
526 flush_stdout_stderr(void)
534 outcslow(int c, FILE *dest)
542 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
544 out1fmt(const char *fmt, ...)
551 r = vprintf(fmt, ap);
557 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
559 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
566 ret = vsnprintf(outbuf, length, fmt, ap);
573 out1str(const char *p)
579 out2str(const char *p)
582 flush_stdout_stderr();
586 /* ============ Parser structures */
588 /* control characters in argument strings */
589 #define CTL_FIRST CTLESC
590 #define CTLESC ((unsigned char)'\201') /* escape next character */
591 #define CTLVAR ((unsigned char)'\202') /* variable defn */
592 #define CTLENDVAR ((unsigned char)'\203')
593 #define CTLBACKQ ((unsigned char)'\204')
594 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
595 /* CTLBACKQ | CTLQUOTE == '\205' */
596 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
597 #define CTLENDARI ((unsigned char)'\207')
598 #define CTLQUOTEMARK ((unsigned char)'\210')
599 #define CTL_LAST CTLQUOTEMARK
601 /* variable substitution byte (follows CTLVAR) */
602 #define VSTYPE 0x0f /* type of variable substitution */
603 #define VSNUL 0x10 /* colon--treat the empty string as unset */
604 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
606 /* values of VSTYPE field */
607 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
608 #define VSMINUS 0x2 /* ${var-text} */
609 #define VSPLUS 0x3 /* ${var+text} */
610 #define VSQUESTION 0x4 /* ${var?message} */
611 #define VSASSIGN 0x5 /* ${var=text} */
612 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
613 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
614 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
615 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
616 #define VSLENGTH 0xa /* ${#var} */
617 #if ENABLE_ASH_BASH_COMPAT
618 #define VSSUBSTR 0xc /* ${var:position:length} */
619 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
620 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
623 static const char dolatstr[] ALIGN1 = {
624 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
644 #if ENABLE_ASH_BASH_COMPAT
661 smallint type; /* Nxxxx */
664 union node *redirect;
669 smallint pipe_backgnd;
670 struct nodelist *cmdlist;
676 union node *redirect;
689 union node *elsepart;
716 struct nodelist *backquote;
719 /* nfile and ndup layout must match!
720 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
721 * that it is actually NTO2 (>&file), and change its type.
738 char *_unused_expfname;
757 struct nredir nredir;
758 struct nbinary nbinary;
762 struct nclist nclist;
771 * NODE_EOF is returned by parsecmd when it encounters an end of file.
772 * It must be distinct from NULL.
774 #define NODE_EOF ((union node *) -1L)
777 struct nodelist *next;
790 freefunc(struct funcnode *f)
792 if (f && --f->count < 0)
797 /* ============ Debugging output */
801 static FILE *tracefile;
804 trace_printf(const char *fmt, ...)
811 fprintf(tracefile, "%u ", (int) time(NULL));
813 fprintf(tracefile, "[%u] ", (int) getpid());
815 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
817 vfprintf(tracefile, fmt, va);
822 trace_vprintf(const char *fmt, va_list va)
827 fprintf(tracefile, "%u ", (int) time(NULL));
829 fprintf(tracefile, "[%u] ", (int) getpid());
831 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
832 vfprintf(tracefile, fmt, va);
836 trace_puts(const char *s)
844 trace_puts_quoted(char *s)
851 putc('"', tracefile);
852 for (p = s; *p; p++) {
853 switch ((unsigned char)*p) {
854 case '\n': c = 'n'; goto backslash;
855 case '\t': c = 't'; goto backslash;
856 case '\r': c = 'r'; goto backslash;
857 case '\"': c = '\"'; goto backslash;
858 case '\\': c = '\\'; goto backslash;
859 case CTLESC: c = 'e'; goto backslash;
860 case CTLVAR: c = 'v'; goto backslash;
861 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
862 case CTLBACKQ: c = 'q'; goto backslash;
863 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
865 putc('\\', tracefile);
869 if (*p >= ' ' && *p <= '~')
872 putc('\\', tracefile);
873 putc((*p >> 6) & 03, tracefile);
874 putc((*p >> 3) & 07, tracefile);
875 putc(*p & 07, tracefile);
880 putc('"', tracefile);
884 trace_puts_args(char **ap)
891 trace_puts_quoted(*ap);
893 putc('\n', tracefile);
896 putc(' ', tracefile);
911 /* leave open because libedit might be using it */
914 strcpy(s, "./trace");
916 if (!freopen(s, "a", tracefile)) {
917 fprintf(stderr, "Can't re-open %s\n", s);
922 tracefile = fopen(s, "a");
923 if (tracefile == NULL) {
924 fprintf(stderr, "Can't open %s\n", s);
930 flags = fcntl(fileno(tracefile), F_GETFL);
932 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
934 setlinebuf(tracefile);
935 fputs("\nTracing started.\n", tracefile);
939 indent(int amount, char *pfx, FILE *fp)
943 for (i = 0; i < amount; i++) {
944 if (pfx && i == amount - 1)
950 /* little circular references here... */
951 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
954 sharg(union node *arg, FILE *fp)
957 struct nodelist *bqlist;
958 unsigned char subtype;
960 if (arg->type != NARG) {
961 out1fmt("<node type %d>\n", arg->type);
964 bqlist = arg->narg.backquote;
965 for (p = arg->narg.text; *p; p++) {
966 switch ((unsigned char)*p) {
975 if (subtype == VSLENGTH)
986 switch (subtype & VSTYPE) {
1012 case VSTRIMRIGHTMAX:
1019 out1fmt("<subtype %d>", subtype);
1026 case CTLBACKQ|CTLQUOTE:
1029 shtree(bqlist->n, -1, NULL, fp);
1040 shcmd(union node *cmd, FILE *fp)
1048 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1054 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1058 switch (np->nfile.type) {
1059 case NTO: s = ">>"+1; dftfd = 1; break;
1060 case NCLOBBER: s = ">|"; dftfd = 1; break;
1061 case NAPPEND: s = ">>"; dftfd = 1; break;
1062 #if ENABLE_ASH_BASH_COMPAT
1065 case NTOFD: s = ">&"; dftfd = 1; break;
1066 case NFROM: s = "<"; break;
1067 case NFROMFD: s = "<&"; break;
1068 case NFROMTO: s = "<>"; break;
1069 default: s = "*error*"; break;
1071 if (np->nfile.fd != dftfd)
1072 fprintf(fp, "%d", np->nfile.fd);
1074 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1075 fprintf(fp, "%d", np->ndup.dupfd);
1077 sharg(np->nfile.fname, fp);
1084 shtree(union node *n, int ind, char *pfx, FILE *fp)
1086 struct nodelist *lp;
1092 indent(ind, pfx, fp);
1094 if (n == NODE_EOF) {
1109 shtree(n->nbinary.ch1, ind, NULL, fp);
1112 shtree(n->nbinary.ch2, ind, NULL, fp);
1120 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1121 shtree(lp->n, 0, NULL, fp);
1125 if (n->npipe.pipe_backgnd)
1131 fprintf(fp, "<node type %d>", n->type);
1139 showtree(union node *n)
1141 trace_puts("showtree called\n");
1142 shtree(n, 1, NULL, stderr);
1148 /* ============ Parser data */
1151 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1154 struct strlist *next;
1161 struct strpush *prev; /* preceding string on stack */
1163 int prev_left_in_line;
1164 #if ENABLE_ASH_ALIAS
1165 struct alias *ap; /* if push was associated with an alias */
1167 char *string; /* remember the string since it may change */
1171 struct parsefile *prev; /* preceding file on stack */
1172 int linno; /* current line */
1173 int pf_fd; /* file descriptor (or -1 if string) */
1174 int left_in_line; /* number of chars left in this line */
1175 int left_in_buffer; /* number of chars left in this buffer past the line */
1176 char *next_to_pgetc; /* next char in buffer */
1177 char *buf; /* input buffer */
1178 struct strpush *strpush; /* for pushing strings at this level */
1179 struct strpush basestrpush; /* so pushing one is fast */
1182 static struct parsefile basepf; /* top level input file */
1183 static struct parsefile *g_parsefile = &basepf; /* current input file */
1184 static int startlinno; /* line # where last token started */
1185 static char *commandname; /* currently executing command */
1186 static struct strlist *cmdenviron; /* environment for builtin command */
1187 static uint8_t exitstatus; /* exit status of last command */
1190 /* ============ Message printing */
1193 ash_vmsg(const char *msg, va_list ap)
1195 fprintf(stderr, "%s: ", arg0);
1197 if (strcmp(arg0, commandname))
1198 fprintf(stderr, "%s: ", commandname);
1199 if (!iflag || g_parsefile->pf_fd > 0)
1200 fprintf(stderr, "line %d: ", startlinno);
1202 vfprintf(stderr, msg, ap);
1203 outcslow('\n', stderr);
1207 * Exverror is called to raise the error exception. If the second argument
1208 * is not NULL then error prints an error message using printf style
1209 * formatting. It then raises the error exception.
1211 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1213 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1217 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1219 TRACE(("\") pid=%d\n", getpid()));
1221 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1226 flush_stdout_stderr();
1227 raise_exception(cond);
1231 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1233 ash_msg_and_raise_error(const char *msg, ...)
1238 ash_vmsg_and_raise(EXERROR, msg, ap);
1243 static void raise_error_syntax(const char *) NORETURN;
1245 raise_error_syntax(const char *msg)
1247 ash_msg_and_raise_error("syntax error: %s", msg);
1251 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1253 ash_msg_and_raise(int cond, const char *msg, ...)
1258 ash_vmsg_and_raise(cond, msg, ap);
1264 * error/warning routines for external builtins
1267 ash_msg(const char *fmt, ...)
1277 * Return a string describing an error. The returned string may be a
1278 * pointer to a static buffer that will be overwritten on the next call.
1279 * Action describes the operation that got the error.
1282 errmsg(int e, const char *em)
1284 if (e == ENOENT || e == ENOTDIR) {
1291 /* ============ Memory allocation */
1294 /* I consider these wrappers nearly useless:
1295 * ok, they return you to nearest exception handler, but
1296 * how much memory do you leak in the process, making
1297 * memory starvation worse?
1300 ckrealloc(void * p, size_t nbytes)
1302 p = realloc(p, nbytes);
1304 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1309 ckmalloc(size_t nbytes)
1311 return ckrealloc(NULL, nbytes);
1315 ckzalloc(size_t nbytes)
1317 return memset(ckmalloc(nbytes), 0, nbytes);
1321 ckstrdup(const char *s)
1323 char *p = strdup(s);
1325 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1329 /* Using bbox equivalents. They exit if out of memory */
1330 # define ckrealloc xrealloc
1331 # define ckmalloc xmalloc
1332 # define ckzalloc xzalloc
1333 # define ckstrdup xstrdup
1337 * It appears that grabstackstr() will barf with such alignments
1338 * because stalloc() will return a string allocated in a new stackblock.
1340 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1342 /* Most machines require the value returned from malloc to be aligned
1343 * in some way. The following macro will get this right
1344 * on many machines. */
1345 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1346 /* Minimum size of a block */
1347 MINSIZE = SHELL_ALIGN(504),
1350 struct stack_block {
1351 struct stack_block *prev;
1352 char space[MINSIZE];
1356 struct stack_block *stackp;
1359 struct stackmark *marknext;
1363 struct globals_memstack {
1364 struct stack_block *g_stackp; // = &stackbase;
1365 struct stackmark *markp;
1366 char *g_stacknxt; // = stackbase.space;
1367 char *sstrend; // = stackbase.space + MINSIZE;
1368 size_t g_stacknleft; // = MINSIZE;
1369 int herefd; // = -1;
1370 struct stack_block stackbase;
1372 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1373 #define G_memstack (*ash_ptr_to_globals_memstack)
1374 #define g_stackp (G_memstack.g_stackp )
1375 #define markp (G_memstack.markp )
1376 #define g_stacknxt (G_memstack.g_stacknxt )
1377 #define sstrend (G_memstack.sstrend )
1378 #define g_stacknleft (G_memstack.g_stacknleft)
1379 #define herefd (G_memstack.herefd )
1380 #define stackbase (G_memstack.stackbase )
1381 #define INIT_G_memstack() do { \
1382 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1384 g_stackp = &stackbase; \
1385 g_stacknxt = stackbase.space; \
1386 g_stacknleft = MINSIZE; \
1387 sstrend = stackbase.space + MINSIZE; \
1392 #define stackblock() ((void *)g_stacknxt)
1393 #define stackblocksize() g_stacknleft
1396 * Parse trees for commands are allocated in lifo order, so we use a stack
1397 * to make this more efficient, and also to avoid all sorts of exception
1398 * handling code to handle interrupts in the middle of a parse.
1400 * The size 504 was chosen because the Ultrix malloc handles that size
1404 stalloc(size_t nbytes)
1409 aligned = SHELL_ALIGN(nbytes);
1410 if (aligned > g_stacknleft) {
1413 struct stack_block *sp;
1415 blocksize = aligned;
1416 if (blocksize < MINSIZE)
1417 blocksize = MINSIZE;
1418 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1419 if (len < blocksize)
1420 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1423 sp->prev = g_stackp;
1424 g_stacknxt = sp->space;
1425 g_stacknleft = blocksize;
1426 sstrend = g_stacknxt + blocksize;
1431 g_stacknxt += aligned;
1432 g_stacknleft -= aligned;
1437 stzalloc(size_t nbytes)
1439 return memset(stalloc(nbytes), 0, nbytes);
1446 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1447 write(STDERR_FILENO, "stunalloc\n", 10);
1451 g_stacknleft += g_stacknxt - (char *)p;
1456 * Like strdup but works with the ash stack.
1459 ststrdup(const char *p)
1461 size_t len = strlen(p) + 1;
1462 return memcpy(stalloc(len), p, len);
1466 setstackmark(struct stackmark *mark)
1468 mark->stackp = g_stackp;
1469 mark->stacknxt = g_stacknxt;
1470 mark->stacknleft = g_stacknleft;
1471 mark->marknext = markp;
1476 popstackmark(struct stackmark *mark)
1478 struct stack_block *sp;
1484 markp = mark->marknext;
1485 while (g_stackp != mark->stackp) {
1487 g_stackp = sp->prev;
1490 g_stacknxt = mark->stacknxt;
1491 g_stacknleft = mark->stacknleft;
1492 sstrend = mark->stacknxt + mark->stacknleft;
1497 * When the parser reads in a string, it wants to stick the string on the
1498 * stack and only adjust the stack pointer when it knows how big the
1499 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1500 * of space on top of the stack and stackblocklen returns the length of
1501 * this block. Growstackblock will grow this space by at least one byte,
1502 * possibly moving it (like realloc). Grabstackblock actually allocates the
1503 * part of the block that has been used.
1506 growstackblock(void)
1510 newlen = g_stacknleft * 2;
1511 if (newlen < g_stacknleft)
1512 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1516 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1517 struct stack_block *oldstackp;
1518 struct stackmark *xmark;
1519 struct stack_block *sp;
1520 struct stack_block *prevstackp;
1524 oldstackp = g_stackp;
1526 prevstackp = sp->prev;
1527 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1528 sp = ckrealloc(sp, grosslen);
1529 sp->prev = prevstackp;
1531 g_stacknxt = sp->space;
1532 g_stacknleft = newlen;
1533 sstrend = sp->space + newlen;
1536 * Stack marks pointing to the start of the old block
1537 * must be relocated to point to the new block
1540 while (xmark != NULL && xmark->stackp == oldstackp) {
1541 xmark->stackp = g_stackp;
1542 xmark->stacknxt = g_stacknxt;
1543 xmark->stacknleft = g_stacknleft;
1544 xmark = xmark->marknext;
1548 char *oldspace = g_stacknxt;
1549 size_t oldlen = g_stacknleft;
1550 char *p = stalloc(newlen);
1552 /* free the space we just allocated */
1553 g_stacknxt = memcpy(p, oldspace, oldlen);
1554 g_stacknleft += newlen;
1559 grabstackblock(size_t len)
1561 len = SHELL_ALIGN(len);
1563 g_stacknleft -= len;
1567 * The following routines are somewhat easier to use than the above.
1568 * The user declares a variable of type STACKSTR, which may be declared
1569 * to be a register. The macro STARTSTACKSTR initializes things. Then
1570 * the user uses the macro STPUTC to add characters to the string. In
1571 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1572 * grown as necessary. When the user is done, she can just leave the
1573 * string there and refer to it using stackblock(). Or she can allocate
1574 * the space for it using grabstackstr(). If it is necessary to allow
1575 * someone else to use the stack temporarily and then continue to grow
1576 * the string, the user should use grabstack to allocate the space, and
1577 * then call ungrabstr(p) to return to the previous mode of operation.
1579 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1580 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1581 * is space for at least one character.
1586 size_t len = stackblocksize();
1587 if (herefd >= 0 && len >= 1024) {
1588 full_write(herefd, stackblock(), len);
1589 return stackblock();
1592 return (char *)stackblock() + len;
1596 * Called from CHECKSTRSPACE.
1599 makestrspace(size_t newlen, char *p)
1601 size_t len = p - g_stacknxt;
1602 size_t size = stackblocksize();
1607 size = stackblocksize();
1609 if (nleft >= newlen)
1613 return (char *)stackblock() + len;
1617 stack_nputstr(const char *s, size_t n, char *p)
1619 p = makestrspace(n, p);
1620 p = (char *)memcpy(p, s, n) + n;
1625 stack_putstr(const char *s, char *p)
1627 return stack_nputstr(s, strlen(s), p);
1631 _STPUTC(int c, char *p)
1639 #define STARTSTACKSTR(p) ((p) = stackblock())
1640 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1641 #define CHECKSTRSPACE(n, p) do { \
1644 size_t m = sstrend - q; \
1646 (p) = makestrspace(l, q); \
1648 #define USTPUTC(c, p) (*(p)++ = (c))
1649 #define STACKSTRNUL(p) do { \
1650 if ((p) == sstrend) \
1651 (p) = growstackstr(); \
1654 #define STUNPUTC(p) (--(p))
1655 #define STTOPC(p) ((p)[-1])
1656 #define STADJUST(amount, p) ((p) += (amount))
1658 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1659 #define ungrabstackstr(s, p) stunalloc(s)
1660 #define stackstrend() ((void *)sstrend)
1663 /* ============ String helpers */
1666 * prefix -- see if pfx is a prefix of string.
1669 prefix(const char *string, const char *pfx)
1672 if (*pfx++ != *string++)
1675 return (char *) string;
1679 * Check for a valid number. This should be elsewhere.
1682 is_number(const char *p)
1687 } while (*++p != '\0');
1692 * Convert a string of digits to an integer, printing an error message on
1696 number(const char *s)
1699 ash_msg_and_raise_error(msg_illnum, s);
1704 * Produce a possibly single quoted string suitable as input to the shell.
1705 * The return string is allocated on the stack.
1708 single_quote(const char *s)
1718 len = strchrnul(s, '\'') - s;
1720 q = p = makestrspace(len + 3, p);
1723 q = (char *)memcpy(q, s, len) + len;
1732 do len++; while (*++s == '\'');
1734 q = p = makestrspace(len + 3, p);
1737 q = (char *)memcpy(q, s - len, len) + len;
1745 return stackblock();
1749 /* ============ nextopt */
1751 static char **argptr; /* argument list for builtin commands */
1752 static char *optionarg; /* set by nextopt (like getopt) */
1753 static char *optptr; /* used by nextopt */
1756 * XXX - should get rid of. Have all builtins use getopt(3).
1757 * The library getopt must have the BSD extension static variable
1758 * "optreset", otherwise it can't be used within the shell safely.
1760 * Standard option processing (a la getopt) for builtin routines.
1761 * The only argument that is passed to nextopt is the option string;
1762 * the other arguments are unnecessary. It returns the character,
1763 * or '\0' on end of input.
1766 nextopt(const char *optstring)
1773 if (p == NULL || *p == '\0') {
1774 /* We ate entire "-param", take next one */
1780 if (*++p == '\0') /* just "-" ? */
1783 if (LONE_DASH(p)) /* "--" ? */
1785 /* p => next "-param" */
1787 /* p => some option char in the middle of a "-param" */
1789 for (q = optstring; *q != c;) {
1791 ash_msg_and_raise_error("illegal option -%c", c);
1799 ash_msg_and_raise_error("no arg for -%c option", c);
1809 /* ============ Shell variables */
1812 * The parsefile structure pointed to by the global variable parsefile
1813 * contains information about the current file being read.
1816 int nparam; /* # of positional parameters (without $0) */
1817 #if ENABLE_ASH_GETOPTS
1818 int optind; /* next parameter to be processed by getopts */
1819 int optoff; /* used by getopts */
1821 unsigned char malloced; /* if parameter list dynamically allocated */
1822 char **p; /* parameter list */
1826 * Free the list of positional parameters.
1829 freeparam(volatile struct shparam *param)
1831 if (param->malloced) {
1833 ap = ap1 = param->p;
1840 #if ENABLE_ASH_GETOPTS
1841 static void FAST_FUNC getoptsreset(const char *value);
1845 struct var *next; /* next entry in hash list */
1846 int flags; /* flags are defined above */
1847 const char *var_text; /* name=value */
1848 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1849 /* the variable gets set/unset */
1853 struct localvar *next; /* next local variable in list */
1854 struct var *vp; /* the variable that was made local */
1855 int flags; /* saved flags */
1856 const char *text; /* saved text */
1860 #define VEXPORT 0x01 /* variable is exported */
1861 #define VREADONLY 0x02 /* variable cannot be modified */
1862 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1863 #define VTEXTFIXED 0x08 /* text is statically allocated */
1864 #define VSTACK 0x10 /* text is allocated on the stack */
1865 #define VUNSET 0x20 /* the variable is not set */
1866 #define VNOFUNC 0x40 /* don't call the callback function */
1867 #define VNOSET 0x80 /* do not set variable - just readonly test */
1868 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1869 #if ENABLE_ASH_RANDOM_SUPPORT
1870 # define VDYNAMIC 0x200 /* dynamic variable */
1876 /* Need to be before varinit_data[] */
1877 #if ENABLE_LOCALE_SUPPORT
1878 static void FAST_FUNC
1879 change_lc_all(const char *value)
1881 if (value && *value != '\0')
1882 setlocale(LC_ALL, value);
1884 static void FAST_FUNC
1885 change_lc_ctype(const char *value)
1887 if (value && *value != '\0')
1888 setlocale(LC_CTYPE, value);
1892 static void chkmail(void);
1893 static void changemail(const char *var_value) FAST_FUNC;
1895 # define chkmail() ((void)0)
1897 static void changepath(const char *) FAST_FUNC;
1898 #if ENABLE_ASH_RANDOM_SUPPORT
1899 static void change_random(const char *) FAST_FUNC;
1902 static const struct {
1904 const char *var_text;
1905 void (*var_func)(const char *) FAST_FUNC;
1906 } varinit_data[] = {
1907 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1909 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1910 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1912 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1913 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1914 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1915 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1916 #if ENABLE_ASH_GETOPTS
1917 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1919 #if ENABLE_ASH_RANDOM_SUPPORT
1920 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1922 #if ENABLE_LOCALE_SUPPORT
1923 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1924 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1926 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1927 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1933 struct globals_var {
1934 struct shparam shellparam; /* $@ current positional parameters */
1935 struct redirtab *redirlist;
1937 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1938 struct var *vartab[VTABSIZE];
1939 struct var varinit[ARRAY_SIZE(varinit_data)];
1941 extern struct globals_var *const ash_ptr_to_globals_var;
1942 #define G_var (*ash_ptr_to_globals_var)
1943 #define shellparam (G_var.shellparam )
1944 //#define redirlist (G_var.redirlist )
1945 #define g_nullredirs (G_var.g_nullredirs )
1946 #define preverrout_fd (G_var.preverrout_fd)
1947 #define vartab (G_var.vartab )
1948 #define varinit (G_var.varinit )
1949 #define INIT_G_var() do { \
1951 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1953 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1954 varinit[i].flags = varinit_data[i].flags; \
1955 varinit[i].var_text = varinit_data[i].var_text; \
1956 varinit[i].var_func = varinit_data[i].var_func; \
1960 #define vifs varinit[0]
1962 # define vmail (&vifs)[1]
1963 # define vmpath (&vmail)[1]
1964 # define vpath (&vmpath)[1]
1966 # define vpath (&vifs)[1]
1968 #define vps1 (&vpath)[1]
1969 #define vps2 (&vps1)[1]
1970 #define vps4 (&vps2)[1]
1971 #if ENABLE_ASH_GETOPTS
1972 # define voptind (&vps4)[1]
1973 # if ENABLE_ASH_RANDOM_SUPPORT
1974 # define vrandom (&voptind)[1]
1977 # if ENABLE_ASH_RANDOM_SUPPORT
1978 # define vrandom (&vps4)[1]
1983 * The following macros access the values of the above variables.
1984 * They have to skip over the name. They return the null string
1985 * for unset variables.
1987 #define ifsval() (vifs.var_text + 4)
1988 #define ifsset() ((vifs.flags & VUNSET) == 0)
1990 # define mailval() (vmail.var_text + 5)
1991 # define mpathval() (vmpath.var_text + 9)
1992 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1994 #define pathval() (vpath.var_text + 5)
1995 #define ps1val() (vps1.var_text + 4)
1996 #define ps2val() (vps2.var_text + 4)
1997 #define ps4val() (vps4.var_text + 4)
1998 #if ENABLE_ASH_GETOPTS
1999 # define optindval() (voptind.var_text + 7)
2002 #if ENABLE_ASH_GETOPTS
2003 static void FAST_FUNC
2004 getoptsreset(const char *value)
2006 shellparam.optind = number(value);
2007 shellparam.optoff = -1;
2011 /* math.h has these, otherwise define our private copies */
2012 #if !ENABLE_SH_MATH_SUPPORT
2013 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
2014 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
2016 * Return the pointer to the first char which is not part of a legal variable name
2017 * (a letter or underscore followed by letters, underscores, and digits).
2020 endofname(const char *name)
2022 if (!is_name(*name))
2025 if (!is_in_name(*name))
2033 * Compares two strings up to the first = or '\0'. The first
2034 * string must be terminated by '='; the second may be terminated by
2035 * either '=' or '\0'.
2038 varcmp(const char *p, const char *q)
2042 while ((c = *p) == (d = *q)) {
2057 * Find the appropriate entry in the hash table from the name.
2059 static struct var **
2060 hashvar(const char *p)
2064 hashval = ((unsigned char) *p) << 4;
2065 while (*p && *p != '=')
2066 hashval += (unsigned char) *p++;
2067 return &vartab[hashval % VTABSIZE];
2071 vpcmp(const void *a, const void *b)
2073 return varcmp(*(const char **)a, *(const char **)b);
2077 * This routine initializes the builtin variables.
2087 * PS1 depends on uid
2089 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2090 vps1.var_text = "PS1=\\w \\$ ";
2093 vps1.var_text = "PS1=# ";
2096 end = vp + ARRAY_SIZE(varinit);
2098 vpp = hashvar(vp->var_text);
2101 } while (++vp < end);
2104 static struct var **
2105 findvar(struct var **vpp, const char *name)
2107 for (; *vpp; vpp = &(*vpp)->next) {
2108 if (varcmp((*vpp)->var_text, name) == 0) {
2116 * Find the value of a variable. Returns NULL if not set.
2118 static const char* FAST_FUNC
2119 lookupvar(const char *name)
2123 v = *findvar(hashvar(name), name);
2125 #if ENABLE_ASH_RANDOM_SUPPORT
2127 * Dynamic variables are implemented roughly the same way they are
2128 * in bash. Namely, they're "special" so long as they aren't unset.
2129 * As soon as they're unset, they're no longer dynamic, and dynamic
2130 * lookup will no longer happen at that point. -- PFM.
2132 if (v->flags & VDYNAMIC)
2135 if (!(v->flags & VUNSET))
2136 return var_end(v->var_text);
2142 * Search the environment of a builtin command.
2145 bltinlookup(const char *name)
2149 for (sp = cmdenviron; sp; sp = sp->next) {
2150 if (varcmp(sp->text, name) == 0)
2151 return var_end(sp->text);
2153 return lookupvar(name);
2157 * Same as setvar except that the variable and value are passed in
2158 * the first argument as name=value. Since the first argument will
2159 * be actually stored in the table, it should not be a string that
2161 * Called with interrupts off.
2164 setvareq(char *s, int flags)
2166 struct var *vp, **vpp;
2169 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2170 vp = *findvar(vpp, s);
2172 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2175 if (flags & VNOSAVE)
2178 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2184 if (vp->var_func && !(flags & VNOFUNC))
2185 vp->var_func(var_end(s));
2187 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2188 free((char*)vp->var_text);
2190 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2192 /* variable s is not found */
2195 vp = ckzalloc(sizeof(*vp));
2197 /*vp->func = NULL; - ckzalloc did it */
2200 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2207 * Set the value of a variable. The flags argument is ored with the
2208 * flags of the variable. If val is NULL, the variable is unset.
2211 setvar(const char *name, const char *val, int flags)
2219 q = endofname(name);
2220 p = strchrnul(q, '=');
2222 if (!namelen || p != q)
2223 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2228 vallen = strlen(val);
2232 nameeq = ckmalloc(namelen + vallen + 2);
2233 p = memcpy(nameeq, name, namelen) + namelen;
2236 p = memcpy(p, val, vallen) + vallen;
2239 setvareq(nameeq, flags | VNOSAVE);
2243 static void FAST_FUNC
2244 setvar2(const char *name, const char *val)
2246 setvar(name, val, 0);
2249 #if ENABLE_ASH_GETOPTS
2251 * Safe version of setvar, returns 1 on success 0 on failure.
2254 setvarsafe(const char *name, const char *val, int flags)
2257 volatile int saveint;
2258 struct jmploc *volatile savehandler = exception_handler;
2259 struct jmploc jmploc;
2262 if (setjmp(jmploc.loc))
2265 exception_handler = &jmploc;
2266 setvar(name, val, flags);
2269 exception_handler = savehandler;
2270 RESTORE_INT(saveint);
2276 * Unset the specified variable.
2279 unsetvar(const char *s)
2285 vpp = findvar(hashvar(s), s);
2289 int flags = vp->flags;
2292 if (flags & VREADONLY)
2294 #if ENABLE_ASH_RANDOM_SUPPORT
2295 vp->flags &= ~VDYNAMIC;
2299 if ((flags & VSTRFIXED) == 0) {
2301 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2302 free((char*)vp->var_text);
2308 vp->flags &= ~VEXPORT;
2318 * Process a linked list of variable assignments.
2321 listsetvar(struct strlist *list_set_var, int flags)
2323 struct strlist *lp = list_set_var;
2329 setvareq(lp->text, flags);
2336 * Generate a list of variables satisfying the given conditions.
2339 listvars(int on, int off, char ***end)
2350 for (vp = *vpp; vp; vp = vp->next) {
2351 if ((vp->flags & mask) == on) {
2352 if (ep == stackstrend())
2353 ep = growstackstr();
2354 *ep++ = (char*)vp->var_text;
2357 } while (++vpp < vartab + VTABSIZE);
2358 if (ep == stackstrend())
2359 ep = growstackstr();
2363 return grabstackstr(ep);
2367 /* ============ Path search helper
2369 * The variable path (passed by reference) should be set to the start
2370 * of the path before the first call; path_advance will update
2371 * this value as it proceeds. Successive calls to path_advance will return
2372 * the possible path expansions in sequence. If an option (indicated by
2373 * a percent sign) appears in the path entry then the global variable
2374 * pathopt will be set to point to it; otherwise pathopt will be set to
2377 static const char *pathopt; /* set by path_advance */
2380 path_advance(const char **path, const char *name)
2390 for (p = start; *p && *p != ':' && *p != '%'; p++)
2392 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2393 while (stackblocksize() < len)
2397 memcpy(q, start, p - start);
2405 while (*p && *p != ':')
2412 return stalloc(len);
2416 /* ============ Prompt */
2418 static smallint doprompt; /* if set, prompt the user */
2419 static smallint needprompt; /* true if interactive and at start of line */
2421 #if ENABLE_FEATURE_EDITING
2422 static line_input_t *line_input_state;
2423 static const char *cmdedit_prompt;
2425 putprompt(const char *s)
2427 if (ENABLE_ASH_EXPAND_PRMT) {
2428 free((char*)cmdedit_prompt);
2429 cmdedit_prompt = ckstrdup(s);
2436 putprompt(const char *s)
2442 #if ENABLE_ASH_EXPAND_PRMT
2443 /* expandstr() needs parsing machinery, so it is far away ahead... */
2444 static const char *expandstr(const char *ps);
2446 #define expandstr(s) s
2450 setprompt_if(smallint do_set, int whichprompt)
2453 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2460 switch (whichprompt) {
2470 #if ENABLE_ASH_EXPAND_PRMT
2471 setstackmark(&smark);
2472 stalloc(stackblocksize());
2474 putprompt(expandstr(prompt));
2475 #if ENABLE_ASH_EXPAND_PRMT
2476 popstackmark(&smark);
2481 /* ============ The cd and pwd commands */
2483 #define CD_PHYSICAL 1
2493 while ((i = nextopt("LP")) != '\0') {
2495 flags ^= CD_PHYSICAL;
2504 * Update curdir (the name of the current directory) in response to a
2508 updatepwd(const char *dir)
2515 cdcomppath = ststrdup(dir);
2518 if (curdir == nullstr)
2520 new = stack_putstr(curdir, new);
2522 new = makestrspace(strlen(dir) + 2, new);
2523 lim = (char *)stackblock() + 1;
2527 if (new > lim && *lim == '/')
2532 if (dir[1] == '/' && dir[2] != '/') {
2538 p = strtok(cdcomppath, "/");
2542 if (p[1] == '.' && p[2] == '\0') {
2554 new = stack_putstr(p, new);
2562 return stackblock();
2566 * Find out what the current directory is. If we already know the current
2567 * directory, this routine returns immediately.
2572 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2573 return dir ? dir : nullstr;
2577 setpwd(const char *val, int setold)
2581 oldcur = dir = curdir;
2584 setvar("OLDPWD", oldcur, VEXPORT);
2587 if (physdir != nullstr) {
2588 if (physdir != oldcur)
2592 if (oldcur == val || !val) {
2598 dir = ckstrdup(val);
2599 if (oldcur != dir && oldcur != nullstr) {
2604 setvar("PWD", dir, VEXPORT);
2607 static void hashcd(void);
2610 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2611 * know that the current directory has changed.
2614 docd(const char *dest, int flags)
2616 const char *dir = NULL;
2619 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2622 if (!(flags & CD_PHYSICAL)) {
2623 dir = updatepwd(dest);
2637 static int FAST_FUNC
2638 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2650 dest = bltinlookup("HOME");
2651 else if (LONE_DASH(dest)) {
2652 dest = bltinlookup("OLDPWD");
2674 path = bltinlookup("CDPATH");
2683 p = path_advance(&path, dest);
2684 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2688 if (!docd(p, flags))
2693 ash_msg_and_raise_error("can't cd to %s", dest);
2696 if (flags & CD_PRINT)
2697 out1fmt("%s\n", curdir);
2701 static int FAST_FUNC
2702 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2705 const char *dir = curdir;
2709 if (physdir == nullstr)
2713 out1fmt("%s\n", dir);
2718 /* ============ ... */
2721 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2723 /* Syntax classes */
2724 #define CWORD 0 /* character is nothing special */
2725 #define CNL 1 /* newline character */
2726 #define CBACK 2 /* a backslash character */
2727 #define CSQUOTE 3 /* single quote */
2728 #define CDQUOTE 4 /* double quote */
2729 #define CENDQUOTE 5 /* a terminating quote */
2730 #define CBQUOTE 6 /* backwards single quote */
2731 #define CVAR 7 /* a dollar sign */
2732 #define CENDVAR 8 /* a '}' character */
2733 #define CLP 9 /* a left paren in arithmetic */
2734 #define CRP 10 /* a right paren in arithmetic */
2735 #define CENDFILE 11 /* end of file */
2736 #define CCTL 12 /* like CWORD, except it must be escaped */
2737 #define CSPCL 13 /* these terminate a word */
2738 #define CIGN 14 /* character should be ignored */
2741 #if ENABLE_ASH_ALIAS
2745 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2747 #if ENABLE_SH_MATH_SUPPORT
2748 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2750 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2752 static const uint16_t S_I_T[] = {
2753 #if ENABLE_ASH_ALIAS
2754 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2756 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2757 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2758 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2759 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2760 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2761 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2762 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2763 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2764 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2765 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2766 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2767 #if !USE_SIT_FUNCTION
2768 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2769 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2770 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2774 /* Constants below must match table above */
2776 #if ENABLE_ASH_ALIAS
2777 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2779 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2780 CNL_CNL_CNL_CNL , /* 2 */
2781 CWORD_CCTL_CCTL_CWORD , /* 3 */
2782 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2783 CVAR_CVAR_CWORD_CVAR , /* 5 */
2784 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2785 CSPCL_CWORD_CWORD_CLP , /* 7 */
2786 CSPCL_CWORD_CWORD_CRP , /* 8 */
2787 CBACK_CBACK_CCTL_CBACK , /* 9 */
2788 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2789 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2790 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2791 CWORD_CWORD_CWORD_CWORD , /* 13 */
2792 CCTL_CCTL_CCTL_CCTL , /* 14 */
2795 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2796 * caller must ensure proper cast on it if c is *char_ptr!
2798 /* Values for syntax param */
2799 #define BASESYNTAX 0 /* not in quotes */
2800 #define DQSYNTAX 1 /* in double quotes */
2801 #define SQSYNTAX 2 /* in single quotes */
2802 #define ARISYNTAX 3 /* in arithmetic */
2803 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2805 #if USE_SIT_FUNCTION
2808 SIT(int c, int syntax)
2810 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2811 # if ENABLE_ASH_ALIAS
2812 static const uint8_t syntax_index_table[] ALIGN1 = {
2813 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2814 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2815 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2819 static const uint8_t syntax_index_table[] ALIGN1 = {
2820 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2821 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2822 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2831 # if ENABLE_ASH_ALIAS
2837 /* Cast is purely for paranoia here,
2838 * just in case someone passed signed char to us */
2839 if ((unsigned char)c >= CTL_FIRST
2840 && (unsigned char)c <= CTL_LAST
2844 s = strchrnul(spec_symbls, c);
2847 indx = syntax_index_table[s - spec_symbls];
2849 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2852 #else /* !USE_SIT_FUNCTION */
2854 static const uint8_t syntax_index_table[] = {
2855 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2856 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2866 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2867 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2889 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2890 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2891 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2893 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2895 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2896 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2897 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2898 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2899 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2901 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2902 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2903 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2904 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2905 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2915 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2916 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2917 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2918 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2919 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2920 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2948 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2949 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2950 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2953 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2981 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2982 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2983 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2984 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2986 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2987 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2988 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2989 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2990 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2991 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2992 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2993 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3112 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3113 # if ENABLE_ASH_ALIAS
3114 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3118 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3120 #endif /* !USE_SIT_FUNCTION */
3123 /* ============ Alias handling */
3125 #if ENABLE_ASH_ALIAS
3127 #define ALIASINUSE 1
3138 static struct alias **atab; // [ATABSIZE];
3139 #define INIT_G_alias() do { \
3140 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3144 static struct alias **
3145 __lookupalias(const char *name) {
3146 unsigned int hashval;
3153 ch = (unsigned char)*p;
3157 ch = (unsigned char)*++p;
3159 app = &atab[hashval % ATABSIZE];
3161 for (; *app; app = &(*app)->next) {
3162 if (strcmp(name, (*app)->name) == 0) {
3170 static struct alias *
3171 lookupalias(const char *name, int check)
3173 struct alias *ap = *__lookupalias(name);
3175 if (check && ap && (ap->flag & ALIASINUSE))
3180 static struct alias *
3181 freealias(struct alias *ap)
3185 if (ap->flag & ALIASINUSE) {
3186 ap->flag |= ALIASDEAD;
3198 setalias(const char *name, const char *val)
3200 struct alias *ap, **app;
3202 app = __lookupalias(name);
3206 if (!(ap->flag & ALIASINUSE)) {
3209 ap->val = ckstrdup(val);
3210 ap->flag &= ~ALIASDEAD;
3213 ap = ckzalloc(sizeof(struct alias));
3214 ap->name = ckstrdup(name);
3215 ap->val = ckstrdup(val);
3216 /*ap->flag = 0; - ckzalloc did it */
3217 /*ap->next = NULL;*/
3224 unalias(const char *name)
3228 app = __lookupalias(name);
3232 *app = freealias(*app);
3243 struct alias *ap, **app;
3247 for (i = 0; i < ATABSIZE; i++) {
3249 for (ap = *app; ap; ap = *app) {
3250 *app = freealias(*app);
3260 printalias(const struct alias *ap)
3262 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3266 * TODO - sort output
3268 static int FAST_FUNC
3269 aliascmd(int argc UNUSED_PARAM, char **argv)
3278 for (i = 0; i < ATABSIZE; i++) {
3279 for (ap = atab[i]; ap; ap = ap->next) {
3285 while ((n = *++argv) != NULL) {
3286 v = strchr(n+1, '=');
3287 if (v == NULL) { /* n+1: funny ksh stuff */
3288 ap = *__lookupalias(n);
3290 fprintf(stderr, "%s: %s not found\n", "alias", n);
3303 static int FAST_FUNC
3304 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3308 while ((i = nextopt("a")) != '\0') {
3314 for (i = 0; *argptr; argptr++) {
3315 if (unalias(*argptr)) {
3316 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3324 #endif /* ASH_ALIAS */
3327 /* ============ jobs.c */
3329 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3332 #define FORK_NOJOB 2
3334 /* mode flags for showjob(s) */
3335 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3336 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3337 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3340 * A job structure contains information about a job. A job is either a
3341 * single process or a set of processes contained in a pipeline. In the
3342 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3346 pid_t ps_pid; /* process id */
3347 int ps_status; /* last process status from wait() */
3348 char *ps_cmd; /* text of command being run */
3352 struct procstat ps0; /* status of process */
3353 struct procstat *ps; /* status or processes when more than one */
3355 int stopstatus; /* status of a stopped job */
3358 nprocs: 16, /* number of processes */
3360 #define JOBRUNNING 0 /* at least one proc running */
3361 #define JOBSTOPPED 1 /* all procs are stopped */
3362 #define JOBDONE 2 /* all procs are completed */
3364 sigint: 1, /* job was killed by SIGINT */
3365 jobctl: 1, /* job running under job control */
3367 waited: 1, /* true if this entry has been waited for */
3368 used: 1, /* true if this entry is in used */
3369 changed: 1; /* true if status has changed */
3370 struct job *prev_job; /* previous job */
3373 static struct job *makejob(/*union node *,*/ int);
3374 static int forkshell(struct job *, union node *, int);
3375 static int waitforjob(struct job *);
3378 enum { doing_jobctl = 0 };
3379 #define setjobctl(on) do {} while (0)
3381 static smallint doing_jobctl; //references:8
3382 static void setjobctl(int);
3389 ignoresig(int signo)
3391 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3392 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3393 /* No, need to do it */
3394 signal(signo, SIG_IGN);
3396 sigmode[signo - 1] = S_HARD_IGN;
3400 * Only one usage site - in setsignal()
3403 signal_handler(int signo)
3405 gotsig[signo - 1] = 1;
3407 if (signo == SIGINT && !trap[SIGINT]) {
3408 if (!suppress_int) {
3410 raise_interrupt(); /* does not return */
3414 pending_sig = signo;
3419 * Set the signal handler for the specified signal. The routine figures
3420 * out what it should be set to.
3423 setsignal(int signo)
3426 char cur_act, new_act;
3427 struct sigaction act;
3431 if (t != NULL) { /* trap for this sig is set */
3433 if (t[0] == '\0') /* trap is "": ignore this sig */
3437 if (rootshell && new_act == S_DFL) {
3440 if (iflag || minusc || sflag == 0)
3449 * "In all cases, bash ignores SIGQUIT. Non-builtin
3450 * commands run by bash have signal handlers
3451 * set to the values inherited by the shell
3452 * from its parent". */
3468 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3469 //whereas we have to restore it to what shell got on entry
3470 //from the parent. See comment above
3472 t = &sigmode[signo - 1];
3475 /* current setting is not yet known */
3476 if (sigaction(signo, NULL, &act)) {
3477 /* pretend it worked; maybe we should give a warning,
3478 * but other shells don't. We don't alter sigmode,
3479 * so we retry every time.
3480 * btw, in Linux it never fails. --vda */
3483 if (act.sa_handler == SIG_IGN) {
3484 cur_act = S_HARD_IGN;
3486 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3488 cur_act = S_IGN; /* don't hard ignore these */
3492 if (cur_act == S_HARD_IGN || cur_act == new_act)
3495 act.sa_handler = SIG_DFL;
3498 act.sa_handler = signal_handler;
3499 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3500 sigfillset(&act.sa_mask); /* ditto */
3503 act.sa_handler = SIG_IGN;
3506 sigaction_set(signo, &act);
3511 /* mode flags for set_curjob */
3512 #define CUR_DELETE 2
3513 #define CUR_RUNNING 1
3514 #define CUR_STOPPED 0
3516 /* mode flags for dowait */
3517 #define DOWAIT_NONBLOCK WNOHANG
3518 #define DOWAIT_BLOCK 0
3521 /* pgrp of shell on invocation */
3522 static int initialpgrp; //references:2
3523 static int ttyfd = -1; //5
3526 static struct job *jobtab; //5
3528 static unsigned njobs; //4
3530 static struct job *curjob; //lots
3531 /* number of presumed living untracked jobs */
3532 static int jobless; //4
3535 set_curjob(struct job *jp, unsigned mode)
3538 struct job **jpp, **curp;
3540 /* first remove from list */
3541 jpp = curp = &curjob;
3546 jpp = &jp1->prev_job;
3548 *jpp = jp1->prev_job;
3550 /* Then re-insert in correct position */
3558 /* job being deleted */
3561 /* newly created job or backgrounded job,
3562 put after all stopped jobs. */
3566 if (!jp1 || jp1->state != JOBSTOPPED)
3569 jpp = &jp1->prev_job;
3575 /* newly stopped job - becomes curjob */
3576 jp->prev_job = *jpp;
3584 jobno(const struct job *jp)
3586 return jp - jobtab + 1;
3591 * Convert a job name to a job structure.
3594 #define getjob(name, getctl) getjob(name)
3597 getjob(const char *name, int getctl)
3601 const char *err_msg = "%s: no such job";
3605 char *(*match)(const char *, const char *);
3620 if (c == '+' || c == '%') {
3622 err_msg = "No current job";
3628 err_msg = "No previous job";
3639 jp = jobtab + num - 1;
3654 if (match(jp->ps[0].ps_cmd, p)) {
3658 err_msg = "%s: ambiguous";
3668 err_msg = "job %s not created under job control";
3669 if (getctl && jp->jobctl == 0)
3674 ash_msg_and_raise_error(err_msg, name);
3678 * Mark a job structure as unused.
3681 freejob(struct job *jp)
3683 struct procstat *ps;
3687 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3688 if (ps->ps_cmd != nullstr)
3691 if (jp->ps != &jp->ps0)
3694 set_curjob(jp, CUR_DELETE);
3700 xtcsetpgrp(int fd, pid_t pgrp)
3702 if (tcsetpgrp(fd, pgrp))
3703 ash_msg_and_raise_error("can't set tty process group (%m)");
3707 * Turn job control on and off.
3709 * Note: This code assumes that the third arg to ioctl is a character
3710 * pointer, which is true on Berkeley systems but not System V. Since
3711 * System V doesn't have job control yet, this isn't a problem now.
3713 * Called with interrupts off.
3721 if (on == doing_jobctl || rootshell == 0)
3725 ofd = fd = open(_PATH_TTY, O_RDWR);
3727 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3728 * That sometimes helps to acquire controlling tty.
3729 * Obviously, a workaround for bugs when someone
3730 * failed to provide a controlling tty to bash! :) */
3736 fd = fcntl(fd, F_DUPFD, 10);
3741 /* fd is a tty at this point */
3742 close_on_exec_on(fd);
3743 do { /* while we are in the background */
3744 pgrp = tcgetpgrp(fd);
3747 ash_msg("can't access tty; job control turned off");
3751 if (pgrp == getpgrp())
3762 xtcsetpgrp(fd, pgrp);
3764 /* turning job control off */
3767 /* was xtcsetpgrp, but this can make exiting ash
3768 * loop forever if pty is already deleted */
3769 tcsetpgrp(fd, pgrp);
3783 static int FAST_FUNC
3784 killcmd(int argc, char **argv)
3787 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3789 if (argv[i][0] == '%') {
3790 struct job *jp = getjob(argv[i], 0);
3791 unsigned pid = jp->ps[0].ps_pid;
3792 /* Enough space for ' -NNN<nul>' */
3793 argv[i] = alloca(sizeof(int)*3 + 3);
3794 /* kill_main has matching code to expect
3795 * leading space. Needed to not confuse
3796 * negative pids with "kill -SIGNAL_NO" syntax */
3797 sprintf(argv[i], " -%u", pid);
3799 } while (argv[++i]);
3801 return kill_main(argc, argv);
3805 showpipe(struct job *jp /*, FILE *out*/)
3807 struct procstat *ps;
3808 struct procstat *psend;
3810 psend = jp->ps + jp->nprocs;
3811 for (ps = jp->ps + 1; ps < psend; ps++)
3812 printf(" | %s", ps->ps_cmd);
3813 outcslow('\n', stdout);
3814 flush_stdout_stderr();
3819 restartjob(struct job *jp, int mode)
3821 struct procstat *ps;
3827 if (jp->state == JOBDONE)
3829 jp->state = JOBRUNNING;
3830 pgid = jp->ps[0].ps_pid;
3831 if (mode == FORK_FG)
3832 xtcsetpgrp(ttyfd, pgid);
3833 killpg(pgid, SIGCONT);
3837 if (WIFSTOPPED(ps->ps_status)) {
3843 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3848 static int FAST_FUNC
3849 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3855 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3859 jp = getjob(*argv, 1);
3860 if (mode == FORK_BG) {
3861 set_curjob(jp, CUR_RUNNING);
3862 printf("[%d] ", jobno(jp));
3864 out1str(jp->ps[0].ps_cmd);
3865 showpipe(jp /*, stdout*/);
3866 retval = restartjob(jp, mode);
3867 } while (*argv && *++argv);
3873 sprint_status(char *s, int status, int sigonly)
3879 if (!WIFEXITED(status)) {
3881 if (WIFSTOPPED(status))
3882 st = WSTOPSIG(status);
3885 st = WTERMSIG(status);
3887 if (st == SIGINT || st == SIGPIPE)
3890 if (WIFSTOPPED(status))
3895 col = fmtstr(s, 32, strsignal(st));
3896 if (WCOREDUMP(status)) {
3897 col += fmtstr(s + col, 16, " (core dumped)");
3899 } else if (!sigonly) {
3900 st = WEXITSTATUS(status);
3902 col = fmtstr(s, 16, "Done(%d)", st);
3904 col = fmtstr(s, 16, "Done");
3911 dowait(int wait_flags, struct job *job)
3916 struct job *thisjob;
3919 TRACE(("dowait(0x%x) called\n", wait_flags));
3921 /* Do a wait system call. If job control is compiled in, we accept
3922 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3923 * NB: _not_ safe_waitpid, we need to detect EINTR */
3925 wait_flags |= WUNTRACED;
3926 pid = waitpid(-1, &status, wait_flags);
3927 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3928 pid, status, errno, strerror(errno)));
3934 for (jp = curjob; jp; jp = jp->prev_job) {
3935 struct procstat *ps;
3936 struct procstat *psend;
3937 if (jp->state == JOBDONE)
3941 psend = ps + jp->nprocs;
3943 if (ps->ps_pid == pid) {
3944 TRACE(("Job %d: changing status of proc %d "
3945 "from 0x%x to 0x%x\n",
3946 jobno(jp), pid, ps->ps_status, status));
3947 ps->ps_status = status;
3950 if (ps->ps_status == -1)
3953 if (state == JOBRUNNING)
3955 if (WIFSTOPPED(ps->ps_status)) {
3956 jp->stopstatus = ps->ps_status;
3960 } while (++ps < psend);
3965 if (!WIFSTOPPED(status))
3971 if (state != JOBRUNNING) {
3972 thisjob->changed = 1;
3974 if (thisjob->state != state) {
3975 TRACE(("Job %d: changing state from %d to %d\n",
3976 jobno(thisjob), thisjob->state, state));
3977 thisjob->state = state;
3979 if (state == JOBSTOPPED) {
3980 set_curjob(thisjob, CUR_STOPPED);
3989 if (thisjob && thisjob == job) {
3993 len = sprint_status(s, status, 1);
4004 blocking_wait_with_raise_on_sig(void)
4006 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4007 if (pid <= 0 && pending_sig)
4008 raise_exception(EXSIG);
4014 showjob(FILE *out, struct job *jp, int mode)
4016 struct procstat *ps;
4017 struct procstat *psend;
4024 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4025 /* just output process (group) id of pipeline */
4026 fprintf(out, "%d\n", ps->ps_pid);
4030 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4035 else if (curjob && jp == curjob->prev_job)
4038 if (mode & SHOW_PIDS)
4039 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4041 psend = ps + jp->nprocs;
4043 if (jp->state == JOBRUNNING) {
4044 strcpy(s + col, "Running");
4045 col += sizeof("Running") - 1;
4047 int status = psend[-1].ps_status;
4048 if (jp->state == JOBSTOPPED)
4049 status = jp->stopstatus;
4050 col += sprint_status(s + col, status, 0);
4052 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4054 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4055 * or prints several "PID | <cmdN>" lines,
4056 * depending on SHOW_PIDS bit.
4057 * We do not print status of individual processes
4058 * between PID and <cmdN>. bash does it, but not very well:
4059 * first line shows overall job status, not process status,
4060 * making it impossible to know 1st process status.
4064 /* for each process */
4067 if (mode & SHOW_PIDS)
4068 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4070 fprintf(out, "%s%*c%s%s",
4072 33 - col >= 0 ? 33 - col : 0, ' ',
4073 ps == jp->ps ? "" : "| ",
4076 } while (++ps != psend);
4077 outcslow('\n', out);
4081 if (jp->state == JOBDONE) {
4082 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4088 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4089 * statuses have changed since the last call to showjobs.
4092 showjobs(FILE *out, int mode)
4096 TRACE(("showjobs(0x%x) called\n", mode));
4098 /* Handle all finished jobs */
4099 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4102 for (jp = curjob; jp; jp = jp->prev_job) {
4103 if (!(mode & SHOW_CHANGED) || jp->changed) {
4104 showjob(out, jp, mode);
4109 static int FAST_FUNC
4110 jobscmd(int argc UNUSED_PARAM, char **argv)
4115 while ((m = nextopt("lp")) != '\0') {
4119 mode |= SHOW_ONLY_PGID;
4125 showjob(stdout, getjob(*argv, 0), mode);
4128 showjobs(stdout, mode);
4135 /* Called only on finished or stopped jobs (no members are running) */
4137 getstatus(struct job *job)
4141 struct procstat *ps;
4143 /* Fetch last member's status */
4144 ps = job->ps + job->nprocs - 1;
4145 status = ps->ps_status;
4147 /* "set -o pipefail" mode: use last _nonzero_ status */
4148 while (status == 0 && --ps >= job->ps)
4149 status = ps->ps_status;
4152 retval = WEXITSTATUS(status);
4153 if (!WIFEXITED(status)) {
4155 retval = WSTOPSIG(status);
4156 if (!WIFSTOPPED(status))
4159 /* XXX: limits number of signals */
4160 retval = WTERMSIG(status);
4162 if (retval == SIGINT)
4168 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4169 jobno(job), job->nprocs, status, retval));
4173 static int FAST_FUNC
4174 waitcmd(int argc UNUSED_PARAM, char **argv)
4181 raise_exception(EXSIG);
4188 /* wait for all jobs */
4192 if (!jp) /* no running procs */
4194 if (jp->state == JOBRUNNING)
4199 blocking_wait_with_raise_on_sig();
4201 * "When bash is waiting for an asynchronous command via
4202 * the wait builtin, the reception of a signal for which a trap
4203 * has been set will cause the wait builtin to return immediately
4204 * with an exit status greater than 128, immediately after which
4205 * the trap is executed."
4207 * blocking_wait_with_raise_on_sig raises signal handlers
4208 * if it gets no pid (pid < 0). However,
4209 * if child sends us a signal *and immediately exits*,
4210 * blocking_wait_with_raise_on_sig gets pid > 0
4211 * and does not handle pending_sig. Check this case: */
4213 raise_exception(EXSIG);
4219 if (**argv != '%') {
4220 pid_t pid = number(*argv);
4225 if (job->ps[job->nprocs - 1].ps_pid == pid)
4227 job = job->prev_job;
4230 job = getjob(*argv, 0);
4231 /* loop until process terminated or stopped */
4232 while (job->state == JOBRUNNING)
4233 blocking_wait_with_raise_on_sig();
4235 retval = getstatus(job);
4248 struct job *jp, *jq;
4250 len = njobs * sizeof(*jp);
4252 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4254 offset = (char *)jp - (char *)jq;
4256 /* Relocate pointers */
4259 jq = (struct job *)((char *)jq + l);
4263 #define joff(p) ((struct job *)((char *)(p) + l))
4264 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4265 if (joff(jp)->ps == &jq->ps0)
4266 jmove(joff(jp)->ps);
4267 if (joff(jp)->prev_job)
4268 jmove(joff(jp)->prev_job);
4278 jp = (struct job *)((char *)jp + len);
4282 } while (--jq >= jp);
4287 * Return a new job structure.
4288 * Called with interrupts off.
4291 makejob(/*union node *node,*/ int nprocs)
4296 for (i = njobs, jp = jobtab; ; jp++) {
4303 if (jp->state != JOBDONE || !jp->waited)
4312 memset(jp, 0, sizeof(*jp));
4314 /* jp->jobctl is a bitfield.
4315 * "jp->jobctl |= jobctl" likely to give awful code */
4319 jp->prev_job = curjob;
4324 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4326 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4333 * Return a string identifying a command (to be printed by the
4336 static char *cmdnextc;
4339 cmdputs(const char *s)
4341 static const char vstype[VSTYPE + 1][3] = {
4342 "", "}", "-", "+", "?", "=",
4343 "%", "%%", "#", "##"
4344 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4347 const char *p, *str;
4351 unsigned char subtype = 0;
4355 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4357 while ((c = *p++) != '\0') {
4365 if ((subtype & VSTYPE) == VSLENGTH)
4369 if (!(subtype & VSQUOTE) == !(quoted & 1))
4375 str = "\"}" + !(quoted & 1);
4382 case CTLBACKQ+CTLQUOTE:
4385 #if ENABLE_SH_MATH_SUPPORT
4400 if ((subtype & VSTYPE) != VSNORMAL)
4402 str = vstype[subtype & VSTYPE];
4403 if (subtype & VSNUL)
4412 /* These can only happen inside quotes */
4425 while ((c = *str++) != '\0') {
4428 } /* while *p++ not NUL */
4431 USTPUTC('"', nextc);
4437 /* cmdtxt() and cmdlist() call each other */
4438 static void cmdtxt(union node *n);
4441 cmdlist(union node *np, int sep)
4443 for (; np; np = np->narg.next) {
4447 if (sep && np->narg.next)
4453 cmdtxt(union node *n)
4456 struct nodelist *lp;
4467 lp = n->npipe.cmdlist;
4485 cmdtxt(n->nbinary.ch1);
4501 cmdtxt(n->nif.test);
4503 if (n->nif.elsepart) {
4504 cmdtxt(n->nif.ifpart);
4506 n = n->nif.elsepart;
4524 cmdtxt(n->nbinary.ch1);
4534 cmdputs(n->nfor.var);
4536 cmdlist(n->nfor.args, 1);
4541 cmdputs(n->narg.text);
4545 cmdlist(n->ncmd.args, 1);
4546 cmdlist(n->ncmd.redirect, 0);
4559 cmdputs(n->ncase.expr->narg.text);
4561 for (np = n->ncase.cases; np; np = np->nclist.next) {
4562 cmdtxt(np->nclist.pattern);
4564 cmdtxt(np->nclist.body);
4578 #if ENABLE_ASH_BASH_COMPAT
4593 cmdputs(utoa(n->nfile.fd));
4595 if (n->type == NTOFD || n->type == NFROMFD) {
4596 cmdputs(utoa(n->ndup.dupfd));
4605 commandtext(union node *n)
4609 STARTSTACKSTR(cmdnextc);
4611 name = stackblock();
4612 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4613 name, cmdnextc, cmdnextc));
4614 return ckstrdup(name);
4619 * Fork off a subshell. If we are doing job control, give the subshell its
4620 * own process group. Jp is a job structure that the job is to be added to.
4621 * N is the command that will be evaluated by the child. Both jp and n may
4622 * be NULL. The mode parameter can be one of the following:
4623 * FORK_FG - Fork off a foreground process.
4624 * FORK_BG - Fork off a background process.
4625 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4626 * process group even if job control is on.
4628 * When job control is turned off, background processes have their standard
4629 * input redirected to /dev/null (except for the second and later processes
4632 * Called with interrupts off.
4635 * Clear traps on a fork.
4642 for (tp = trap; tp < &trap[NSIG]; tp++) {
4643 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4645 if (trap_ptr == trap)
4647 /* else: it "belongs" to trap_ptr vector, don't free */
4649 if ((tp - trap) != 0)
4650 setsignal(tp - trap);
4657 /* Lives far away from here, needed for forkchild */
4658 static void closescript(void);
4660 /* Called after fork(), in child */
4661 static NOINLINE void
4662 forkchild(struct job *jp, union node *n, int mode)
4666 TRACE(("Child shell %d\n", getpid()));
4670 /* man bash: "Non-builtin commands run by bash have signal handlers
4671 * set to the values inherited by the shell from its parent".
4672 * Do we do it correctly? */
4676 if (mode == FORK_NOJOB /* is it `xxx` ? */
4677 && n && n->type == NCMD /* is it single cmd? */
4678 /* && n->ncmd.args->type == NARG - always true? */
4679 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4680 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4681 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4683 TRACE(("Trap hack\n"));
4684 /* Awful hack for `trap` or $(trap).
4686 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4687 * contains an example where "trap" is executed in a subshell:
4689 * save_traps=$(trap)
4691 * eval "$save_traps"
4693 * Standard does not say that "trap" in subshell shall print
4694 * parent shell's traps. It only says that its output
4695 * must have suitable form, but then, in the above example
4696 * (which is not supposed to be normative), it implies that.
4698 * bash (and probably other shell) does implement it
4699 * (traps are reset to defaults, but "trap" still shows them),
4700 * but as a result, "trap" logic is hopelessly messed up:
4703 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4704 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4705 * # true | trap <--- trap is in subshell - no output (ditto)
4706 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4707 * trap -- 'echo Ho' SIGWINCH
4708 * # echo `(trap)` <--- in subshell in subshell - output
4709 * trap -- 'echo Ho' SIGWINCH
4710 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4711 * trap -- 'echo Ho' SIGWINCH
4713 * The rules when to forget and when to not forget traps
4714 * get really complex and nonsensical.
4716 * Our solution: ONLY bare $(trap) or `trap` is special.
4718 /* Save trap handler strings for trap builtin to print */
4719 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4720 /* Fall through into clearing traps */
4724 /* do job control only in root shell */
4726 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4729 if (jp->nprocs == 0)
4732 pgrp = jp->ps[0].ps_pid;
4733 /* this can fail because we are doing it in the parent also */
4735 if (mode == FORK_FG)
4736 xtcsetpgrp(ttyfd, pgrp);
4741 if (mode == FORK_BG) {
4742 /* man bash: "When job control is not in effect,
4743 * asynchronous commands ignore SIGINT and SIGQUIT" */
4746 if (jp->nprocs == 0) {
4748 if (open(bb_dev_null, O_RDONLY) != 0)
4749 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4753 if (iflag) { /* why if iflag only? */
4758 * "In all cases, bash ignores SIGQUIT. Non-builtin
4759 * commands run by bash have signal handlers
4760 * set to the values inherited by the shell
4762 * Take care of the second rule: */
4766 if (n && n->type == NCMD
4767 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4769 TRACE(("Job hack\n"));
4770 /* "jobs": we do not want to clear job list for it,
4771 * instead we remove only _its_ own_ job from job list.
4772 * This makes "jobs .... | cat" more useful.
4778 for (jp = curjob; jp; jp = jp->prev_job)
4783 /* Called after fork(), in parent */
4785 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4788 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4790 TRACE(("In parent shell: child = %d\n", pid));
4792 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4798 if (mode != FORK_NOJOB && jp->jobctl) {
4801 if (jp->nprocs == 0)
4804 pgrp = jp->ps[0].ps_pid;
4805 /* This can fail because we are doing it in the child also */
4809 if (mode == FORK_BG) {
4810 backgndpid = pid; /* set $! */
4811 set_curjob(jp, CUR_RUNNING);
4814 struct procstat *ps = &jp->ps[jp->nprocs++];
4817 ps->ps_cmd = nullstr;
4819 if (doing_jobctl && n)
4820 ps->ps_cmd = commandtext(n);
4826 forkshell(struct job *jp, union node *n, int mode)
4830 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4833 TRACE(("Fork failed, errno=%d", errno));
4836 ash_msg_and_raise_error("can't fork");
4839 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4840 forkchild(jp, n, mode);
4842 forkparent(jp, n, mode, pid);
4848 * Wait for job to finish.
4850 * Under job control we have the problem that while a child process
4851 * is running interrupts generated by the user are sent to the child
4852 * but not to the shell. This means that an infinite loop started by
4853 * an interactive user may be hard to kill. With job control turned off,
4854 * an interactive user may place an interactive program inside a loop.
4855 * If the interactive program catches interrupts, the user doesn't want
4856 * these interrupts to also abort the loop. The approach we take here
4857 * is to have the shell ignore interrupt signals while waiting for a
4858 * foreground process to terminate, and then send itself an interrupt
4859 * signal if the child process was terminated by an interrupt signal.
4860 * Unfortunately, some programs want to do a bit of cleanup and then
4861 * exit on interrupt; unless these processes terminate themselves by
4862 * sending a signal to themselves (instead of calling exit) they will
4863 * confuse this approach.
4865 * Called with interrupts off.
4868 waitforjob(struct job *jp)
4872 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4875 while (jp->state == JOBRUNNING) {
4876 /* In non-interactive shells, we _can_ get
4877 * a keyboard signal here and be EINTRed,
4878 * but we just loop back, waiting for command to complete.
4881 * "If bash is waiting for a command to complete and receives
4882 * a signal for which a trap has been set, the trap
4883 * will not be executed until the command completes."
4885 * Reality is that even if trap is not set, bash
4886 * will not act on the signal until command completes.
4887 * Try this. sleep5intoff.c:
4888 * #include <signal.h>
4889 * #include <unistd.h>
4892 * sigemptyset(&set);
4893 * sigaddset(&set, SIGINT);
4894 * sigaddset(&set, SIGQUIT);
4895 * sigprocmask(SIG_BLOCK, &set, NULL);
4899 * $ bash -c './sleep5intoff; echo hi'
4900 * ^C^C^C^C <--- pressing ^C once a second
4902 * $ bash -c './sleep5intoff; echo hi'
4903 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4906 dowait(DOWAIT_BLOCK, jp);
4913 xtcsetpgrp(ttyfd, rootpid);
4915 * This is truly gross.
4916 * If we're doing job control, then we did a TIOCSPGRP which
4917 * caused us (the shell) to no longer be in the controlling
4918 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4919 * intuit from the subprocess exit status whether a SIGINT
4920 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4922 if (jp->sigint) /* TODO: do the same with all signals */
4923 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4925 if (jp->state == JOBDONE)
4932 * return 1 if there are stopped jobs, otherwise 0
4944 if (jp && jp->state == JOBSTOPPED) {
4945 out2str("You have stopped jobs.\n");
4954 /* ============ redir.c
4956 * Code for dealing with input/output redirection.
4961 #define EMPTY -2 /* marks an unused slot in redirtab */
4962 #define CLOSED -3 /* marks a slot of previously-closed fd */
4965 * Open a file in noclobber mode.
4966 * The code was copied from bash.
4969 noclobberopen(const char *fname)
4972 struct stat finfo, finfo2;
4975 * If the file exists and is a regular file, return an error
4978 r = stat(fname, &finfo);
4979 if (r == 0 && S_ISREG(finfo.st_mode)) {
4985 * If the file was not present (r != 0), make sure we open it
4986 * exclusively so that if it is created before we open it, our open
4987 * will fail. Make sure that we do not truncate an existing file.
4988 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4989 * file was not a regular file, we leave O_EXCL off.
4992 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4993 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4995 /* If the open failed, return the file descriptor right away. */
5000 * OK, the open succeeded, but the file may have been changed from a
5001 * non-regular file to a regular file between the stat and the open.
5002 * We are assuming that the O_EXCL open handles the case where FILENAME
5003 * did not exist and is symlinked to an existing file between the stat
5008 * If we can open it and fstat the file descriptor, and neither check
5009 * revealed that it was a regular file, and the file has not been
5010 * replaced, return the file descriptor.
5012 if (fstat(fd, &finfo2) == 0
5013 && !S_ISREG(finfo2.st_mode)
5014 && finfo.st_dev == finfo2.st_dev
5015 && finfo.st_ino == finfo2.st_ino
5020 /* The file has been replaced. badness. */
5027 * Handle here documents. Normally we fork off a process to write the
5028 * data to a pipe. If the document is short, we can stuff the data in
5029 * the pipe without forking.
5031 /* openhere needs this forward reference */
5032 static void expandhere(union node *arg, int fd);
5034 openhere(union node *redir)
5040 ash_msg_and_raise_error("pipe call failed");
5041 if (redir->type == NHERE) {
5042 len = strlen(redir->nhere.doc->narg.text);
5043 if (len <= PIPE_BUF) {
5044 full_write(pip[1], redir->nhere.doc->narg.text, len);
5048 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5051 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5052 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5053 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5054 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5055 signal(SIGPIPE, SIG_DFL);
5056 if (redir->type == NHERE)
5057 full_write(pip[1], redir->nhere.doc->narg.text, len);
5059 expandhere(redir->nhere.doc, pip[1]);
5060 _exit(EXIT_SUCCESS);
5068 openredirect(union node *redir)
5073 switch (redir->nfile.type) {
5075 fname = redir->nfile.expfname;
5076 f = open(fname, O_RDONLY);
5081 fname = redir->nfile.expfname;
5082 f = open(fname, O_RDWR|O_CREAT, 0666);
5087 #if ENABLE_ASH_BASH_COMPAT
5090 /* Take care of noclobber mode. */
5092 fname = redir->nfile.expfname;
5093 f = noclobberopen(fname);
5100 fname = redir->nfile.expfname;
5101 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5106 fname = redir->nfile.expfname;
5107 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5115 /* Fall through to eliminate warning. */
5116 /* Our single caller does this itself */
5123 f = openhere(redir);
5129 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5131 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5135 * Copy a file descriptor to be >= to. Returns -1
5136 * if the source file descriptor is closed, EMPTY if there are no unused
5137 * file descriptors left.
5139 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5140 * old code was doing close(to) prior to copyfd() to achieve the same */
5142 COPYFD_EXACT = (int)~(INT_MAX),
5143 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5146 copyfd(int from, int to)
5150 if (to & COPYFD_EXACT) {
5151 to &= ~COPYFD_EXACT;
5153 newfd = dup2(from, to);
5155 newfd = fcntl(from, F_DUPFD, to);
5158 if (errno == EMFILE)
5160 /* Happens when source fd is not open: try "echo >&99" */
5161 ash_msg_and_raise_error("%d: %m", from);
5166 /* Struct def and variable are moved down to the first usage site */
5171 struct redirtab *next;
5174 struct two_fd_t two_fd[];
5176 #define redirlist (G_var.redirlist)
5178 static int need_to_remember(struct redirtab *rp, int fd)
5182 if (!rp) /* remembering was not requested */
5185 for (i = 0; i < rp->pair_count; i++) {
5186 if (rp->two_fd[i].orig == fd) {
5187 /* already remembered */
5194 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5195 static int is_hidden_fd(struct redirtab *rp, int fd)
5198 struct parsefile *pf;
5202 /* Check open scripts' fds */
5205 /* We skip pf_fd == 0 case because of the following case:
5206 * $ ash # running ash interactively
5208 * and in script.sh: "exec 9>&0".
5209 * Even though top-level pf_fd _is_ 0,
5210 * it's still ok to use it: "read" builtin uses it,
5211 * why should we cripple "exec" builtin?
5213 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5221 /* Check saved fds of redirects */
5222 fd |= COPYFD_RESTORE;
5223 for (i = 0; i < rp->pair_count; i++) {
5224 if (rp->two_fd[i].copy == fd) {
5232 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5233 * old file descriptors are stashed away so that the redirection can be
5234 * undone by calling popredir.
5236 /* flags passed to redirect */
5237 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5238 #define REDIR_SAVEFD2 03 /* set preverrout */
5240 redirect(union node *redir, int flags)
5242 struct redirtab *sv;
5247 int copied_fd2 = -1;
5257 if (flags & REDIR_PUSH) {
5258 union node *tmp = redir;
5261 #if ENABLE_ASH_BASH_COMPAT
5262 if (tmp->nfile.type == NTO2)
5265 tmp = tmp->nfile.next;
5267 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5268 sv->next = redirlist;
5269 sv->pair_count = sv_pos;
5271 sv->nullredirs = g_nullredirs - 1;
5273 while (sv_pos > 0) {
5275 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5281 fd = redir->nfile.fd;
5282 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5283 right_fd = redir->ndup.dupfd;
5284 //bb_error_msg("doing %d > %d", fd, right_fd);
5285 /* redirect from/to same file descriptor? */
5288 /* "echo >&10" and 10 is a fd opened to a sh script? */
5289 if (is_hidden_fd(sv, right_fd)) {
5290 errno = EBADF; /* as if it is closed */
5291 ash_msg_and_raise_error("%d: %m", right_fd);
5295 newfd = openredirect(redir); /* always >= 0 */
5297 /* Descriptor wasn't open before redirect.
5298 * Mark it for close in the future */
5299 if (need_to_remember(sv, fd)) {
5300 goto remember_to_close;
5305 #if ENABLE_ASH_BASH_COMPAT
5308 if (need_to_remember(sv, fd)) {
5309 /* Copy old descriptor */
5310 /* Careful to not accidentally "save"
5311 * to the same fd as right side fd in N>&M */
5312 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5313 i = fcntl(fd, F_DUPFD, minfd);
5314 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5315 * are closed in popredir() in the child, preventing them from leaking
5316 * into child. (popredir() also cleans up the mess in case of failures)
5321 /* Strange error (e.g. "too many files" EMFILE?) */
5325 ash_msg_and_raise_error("%d: %m", fd);
5328 /* EBADF: it is not open - good, remember to close it */
5331 } else { /* fd is open, save its copy */
5332 /* "exec fd>&-" should not close fds
5333 * which point to script file(s).
5334 * Force them to be restored afterwards */
5335 if (is_hidden_fd(sv, fd))
5336 i |= COPYFD_RESTORE;
5340 sv->two_fd[sv_pos].orig = fd;
5341 sv->two_fd[sv_pos].copy = i;
5345 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5346 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5347 /* Don't want to trigger debugging */
5351 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5353 } else if (fd != newfd) { /* move newfd to fd */
5354 copyfd(newfd, fd | COPYFD_EXACT);
5355 #if ENABLE_ASH_BASH_COMPAT
5356 if (!(redir->nfile.type == NTO2 && fd == 2))
5360 #if ENABLE_ASH_BASH_COMPAT
5361 if (redir->nfile.type == NTO2 && fd == 1) {
5362 /* We already redirected it to fd 1, now copy it to 2 */
5368 } while ((redir = redir->nfile.next) != NULL);
5371 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5372 preverrout_fd = copied_fd2;
5376 * Undo the effects of the last redirection.
5379 popredir(int drop, int restore)
5381 struct redirtab *rp;
5384 if (--g_nullredirs >= 0)
5388 for (i = 0; i < rp->pair_count; i++) {
5389 int fd = rp->two_fd[i].orig;
5390 int copy = rp->two_fd[i].copy;
5391 if (copy == CLOSED) {
5396 if (copy != EMPTY) {
5397 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5398 copy &= ~COPYFD_RESTORE;
5400 copyfd(copy, fd | COPYFD_EXACT);
5402 close(copy & ~COPYFD_RESTORE);
5405 redirlist = rp->next;
5406 g_nullredirs = rp->nullredirs;
5412 * Undo all redirections. Called on error or interrupt.
5416 * Discard all saved file descriptors.
5419 clearredir(int drop)
5425 popredir(drop, /*restore:*/ 0);
5430 redirectsafe(union node *redir, int flags)
5433 volatile int saveint;
5434 struct jmploc *volatile savehandler = exception_handler;
5435 struct jmploc jmploc;
5438 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5439 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5441 exception_handler = &jmploc;
5442 redirect(redir, flags);
5444 exception_handler = savehandler;
5445 if (err && exception_type != EXERROR)
5446 longjmp(exception_handler->loc, 1);
5447 RESTORE_INT(saveint);
5452 /* ============ Routines to expand arguments to commands
5454 * We have to deal with backquotes, shell variables, and file metacharacters.
5457 #if ENABLE_SH_MATH_SUPPORT
5459 ash_arith(const char *s)
5461 arith_state_t math_state;
5464 math_state.lookupvar = lookupvar;
5465 math_state.setvar = setvar2;
5466 //math_state.endofname = endofname;
5469 result = arith(&math_state, s);
5470 if (math_state.errmsg)
5471 ash_msg_and_raise_error(math_state.errmsg);
5481 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5482 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5483 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5484 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5485 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5486 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5487 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5488 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5489 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5493 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5494 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5495 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5496 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5497 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5500 * Structure specifying which parts of the string should be searched
5501 * for IFS characters.
5504 struct ifsregion *next; /* next region in list */
5505 int begoff; /* offset of start of region */
5506 int endoff; /* offset of end of region */
5507 int nulonly; /* search for nul bytes only */
5511 struct strlist *list;
5512 struct strlist **lastp;
5515 /* output of current string */
5516 static char *expdest;
5517 /* list of back quote expressions */
5518 static struct nodelist *argbackq;
5519 /* first struct in list of ifs regions */
5520 static struct ifsregion ifsfirst;
5521 /* last struct in list */
5522 static struct ifsregion *ifslastp;
5523 /* holds expanded arg list */
5524 static struct arglist exparg;
5529 #if !ENABLE_SH_MATH_SUPPORT
5530 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5531 typedef long arith_t;
5532 # define ARITH_FMT "%ld"
5539 expdest = makestrspace(32, expdest);
5540 len = fmtstr(expdest, 32, ARITH_FMT, num);
5541 STADJUST(len, expdest);
5546 esclen(const char *start, const char *p)
5550 while (p > start && (unsigned char)*--p == CTLESC) {
5557 * Remove any CTLESC characters from a string.
5560 rmescapes(char *str, int flag)
5562 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5566 unsigned protect_against_glob;
5569 p = strpbrk(str, qchars);
5575 if (flag & RMESCAPE_ALLOC) {
5576 size_t len = p - str;
5577 size_t fulllen = len + strlen(p) + 1;
5579 if (flag & RMESCAPE_GROW) {
5580 int strloc = str - (char *)stackblock();
5581 r = makestrspace(fulllen, expdest);
5582 /* p and str may be invalidated by makestrspace */
5583 str = (char *)stackblock() + strloc;
5585 } else if (flag & RMESCAPE_HEAP) {
5586 r = ckmalloc(fulllen);
5588 r = stalloc(fulllen);
5592 q = (char *)memcpy(q, str, len) + len;
5596 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5597 globbing = flag & RMESCAPE_GLOB;
5598 protect_against_glob = globbing;
5600 if ((unsigned char)*p == CTLQUOTEMARK) {
5601 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5602 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5603 // Note: both inquotes and protect_against_glob only affect whether
5604 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5605 inquotes = ~inquotes;
5607 protect_against_glob = globbing;
5611 /* naked back slash */
5612 protect_against_glob = 0;
5615 if ((unsigned char)*p == CTLESC) {
5617 if (protect_against_glob && inquotes && *p != '/') {
5621 protect_against_glob = globbing;
5626 if (flag & RMESCAPE_GROW) {
5628 STADJUST(q - r + 1, expdest);
5632 #define pmatch(a, b) !fnmatch((a), (b), 0)
5635 * Prepare a pattern for a expmeta (internal glob(3)) call.
5637 * Returns an stalloced string.
5640 preglob(const char *pattern, int quoted, int flag)
5642 flag |= RMESCAPE_GLOB;
5644 flag |= RMESCAPE_QUOTED;
5646 return rmescapes((char *)pattern, flag);
5650 * Put a string on the stack.
5653 memtodest(const char *p, size_t len, int syntax, int quotes)
5657 q = makestrspace(quotes ? len * 2 : len, q);
5660 unsigned char c = *p++;
5664 int n = SIT(c, syntax);
5665 if (n == CCTL || n == CBACK)
5675 strtodest(const char *p, int syntax, int quotes)
5677 memtodest(p, strlen(p), syntax, quotes);
5681 * Record the fact that we have to scan this region of the
5682 * string for IFS characters.
5685 recordregion(int start, int end, int nulonly)
5687 struct ifsregion *ifsp;
5689 if (ifslastp == NULL) {
5693 ifsp = ckzalloc(sizeof(*ifsp));
5694 /*ifsp->next = NULL; - ckzalloc did it */
5695 ifslastp->next = ifsp;
5699 ifslastp->begoff = start;
5700 ifslastp->endoff = end;
5701 ifslastp->nulonly = nulonly;
5705 removerecordregions(int endoff)
5707 if (ifslastp == NULL)
5710 if (ifsfirst.endoff > endoff) {
5711 while (ifsfirst.next) {
5712 struct ifsregion *ifsp;
5714 ifsp = ifsfirst.next->next;
5715 free(ifsfirst.next);
5716 ifsfirst.next = ifsp;
5719 if (ifsfirst.begoff > endoff) {
5722 ifslastp = &ifsfirst;
5723 ifsfirst.endoff = endoff;
5728 ifslastp = &ifsfirst;
5729 while (ifslastp->next && ifslastp->next->begoff < endoff)
5730 ifslastp = ifslastp->next;
5731 while (ifslastp->next) {
5732 struct ifsregion *ifsp;
5734 ifsp = ifslastp->next->next;
5735 free(ifslastp->next);
5736 ifslastp->next = ifsp;
5739 if (ifslastp->endoff > endoff)
5740 ifslastp->endoff = endoff;
5744 exptilde(char *startp, char *p, int flags)
5750 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5755 while ((c = *++p) != '\0') {
5762 if (flags & EXP_VARTILDE)
5772 if (*name == '\0') {
5773 home = lookupvar("HOME");
5775 pw = getpwnam(name);
5780 if (!home || !*home)
5783 startloc = expdest - (char *)stackblock();
5784 strtodest(home, SQSYNTAX, quotes);
5785 recordregion(startloc, expdest - (char *)stackblock(), 0);
5793 * Execute a command inside back quotes. If it's a builtin command, we
5794 * want to save its output in a block obtained from malloc. Otherwise
5795 * we fork off a subprocess and get the output of the command via a pipe.
5796 * Should be called with interrupts off.
5798 struct backcmd { /* result of evalbackcmd */
5799 int fd; /* file descriptor to read from */
5800 int nleft; /* number of chars in buffer */
5801 char *buf; /* buffer */
5802 struct job *jp; /* job structure for command */
5805 /* These forward decls are needed to use "eval" code for backticks handling: */
5806 static uint8_t back_exitstatus; /* exit status of backquoted command */
5807 #define EV_EXIT 01 /* exit after evaluating tree */
5808 static void evaltree(union node *, int);
5810 static void FAST_FUNC
5811 evalbackcmd(union node *n, struct backcmd *result)
5822 saveherefd = herefd;
5830 ash_msg_and_raise_error("pipe call failed");
5831 jp = makejob(/*n,*/ 1);
5832 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5837 copyfd(pip[1], 1 | COPYFD_EXACT);
5841 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5845 result->fd = pip[0];
5848 herefd = saveherefd;
5850 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5851 result->fd, result->buf, result->nleft, result->jp));
5855 * Expand stuff in backwards quotes.
5858 expbackq(union node *cmd, int quoted, int quotes)
5866 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5867 struct stackmark smark;
5870 setstackmark(&smark);
5872 startloc = dest - (char *)stackblock();
5874 evalbackcmd(cmd, &in);
5875 popstackmark(&smark);
5882 memtodest(p, i, syntax, quotes);
5886 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5887 TRACE(("expbackq: read returns %d\n", i));
5896 back_exitstatus = waitforjob(in.jp);
5900 /* Eat all trailing newlines */
5902 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5907 recordregion(startloc, dest - (char *)stackblock(), 0);
5908 TRACE(("evalbackq: size:%d:'%.*s'\n",
5909 (int)((dest - (char *)stackblock()) - startloc),
5910 (int)((dest - (char *)stackblock()) - startloc),
5911 stackblock() + startloc));
5914 #if ENABLE_SH_MATH_SUPPORT
5916 * Expand arithmetic expression. Backup to start of expression,
5917 * evaluate, place result in (backed up) result, adjust string position.
5930 * This routine is slightly over-complicated for
5931 * efficiency. Next we scan backwards looking for the
5932 * start of arithmetic.
5934 start = stackblock();
5941 while ((unsigned char)*p != CTLARI) {
5945 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5950 esc = esclen(start, p);
5960 removerecordregions(begoff);
5967 rmescapes(p + 2, 0);
5969 len = cvtnum(ash_arith(p + 2));
5972 recordregion(begoff, begoff + len, 0);
5976 /* argstr needs it */
5977 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5980 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5981 * characters to allow for further processing. Otherwise treat
5982 * $@ like $* since no splitting will be performed.
5984 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5985 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5986 * for correct expansion of "B=$A" word.
5989 argstr(char *p, int flags, struct strlist *var_str_list)
5991 static const char spclchars[] ALIGN1 = {
5999 CTLBACKQ | CTLQUOTE,
6000 #if ENABLE_SH_MATH_SUPPORT
6005 const char *reject = spclchars;
6006 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
6007 int breakall = flags & EXP_WORD;
6012 if (!(flags & EXP_VARTILDE)) {
6014 } else if (flags & EXP_VARTILDE2) {
6019 if (flags & EXP_TILDE) {
6022 flags &= ~EXP_TILDE;
6025 if ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
6028 p = exptilde(p, q, flags);
6031 startloc = expdest - (char *)stackblock();
6035 length += strcspn(p + length, reject);
6039 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6041 /* c == '=' || c == ':' || c == CTLENDARI */
6047 expdest = stack_nputstr(p, length, expdest);
6048 newloc = expdest - (char *)stackblock();
6049 if (breakall && !inquotes && newloc > startloc) {
6050 recordregion(startloc, newloc, 0);
6061 if (flags & EXP_VARTILDE2) {
6065 flags |= EXP_VARTILDE2;
6070 * sort of a hack - expand tildes in variable
6071 * assignments (after the first '=' and after ':'s).
6080 case CTLENDVAR: /* ??? */
6083 /* "$@" syntax adherence hack */
6085 && memcmp(p, dolatstr, 4) == 0
6086 && ( p[4] == (char)CTLQUOTEMARK
6087 || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
6090 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
6093 inquotes = !inquotes;
6106 p = evalvar(p, flags, var_str_list);
6110 case CTLBACKQ|CTLQUOTE:
6111 expbackq(argbackq->n, c, quotes);
6112 argbackq = argbackq->next;
6114 #if ENABLE_SH_MATH_SUPPORT
6126 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6127 char *pattern, int quotes, int zero)
6136 const char *s = loc2;
6143 match = pmatch(pattern, s);
6148 if (quotes && (unsigned char)*loc == CTLESC)
6157 scanright(char *startp, char *rmesc, char *rmescend,
6158 char *pattern, int quotes, int match_at_start)
6160 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6161 int try2optimize = match_at_start;
6167 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6168 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6169 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6171 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6172 * and on each iteration they go back two/one char until they reach the beginning.
6173 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6175 /* TODO: document in what other circumstances we are called. */
6177 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6180 const char *s = loc2;
6181 if (match_at_start) {
6185 match = pmatch(pattern, s);
6186 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6190 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6192 /* Maybe we can optimize this:
6193 * if pattern ends with unescaped *, we can avoid checking
6194 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6195 * it wont match truncated "raw_value_of_" strings too.
6197 unsigned plen = strlen(pattern);
6198 /* Does it end with "*"? */
6199 if (plen != 0 && pattern[--plen] == '*') {
6200 /* "xxxx*" is not escaped */
6201 /* "xxx\*" is escaped */
6202 /* "xx\\*" is not escaped */
6203 /* "x\\\*" is escaped */
6205 while (plen != 0 && pattern[--plen] == '\\')
6208 break; /* ends with unescaped "*" */
6216 esc = esclen(startp, loc);
6227 static void varunset(const char *, const char *, const char *, int) NORETURN;
6229 varunset(const char *end, const char *var, const char *umsg, int varflags)
6235 msg = "parameter not set";
6237 if ((unsigned char)*end == CTLENDVAR) {
6238 if (varflags & VSNUL)
6244 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6247 #if ENABLE_ASH_BASH_COMPAT
6249 parse_sub_pattern(char *arg, int varflags)
6251 char *idx, *repl = NULL;
6254 //char *org_arg = arg;
6255 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
6262 /* Only the first '/' seen is our separator */
6271 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6272 * The result is a_\_z_c (not a\_\_z_c)!
6274 * Enable debug prints in this function and you'll see:
6275 * ash: arg:'\\b/_\\_z_' varflags:d
6276 * ash: pattern:'\\b' repl:'_\_z_'
6277 * That is, \\b is interpreted as \\b, but \\_ as \_!
6278 * IOW: search pattern and replace string treat backslashes
6279 * differently! That is the reason why we check repl below:
6281 if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
6282 arg++; /* skip both '\', not just first one */
6285 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
6289 #endif /* ENABLE_ASH_BASH_COMPAT */
6292 subevalvar(char *p, char *varname, int strloc, int subtype,
6293 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6295 struct nodelist *saveargbackq = argbackq;
6298 char *rmesc, *rmescend;
6300 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
6301 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6302 int saveherefd = herefd;
6303 int amount, workloc, resetloc;
6305 char *(*scan)(char*, char*, char*, char*, int, int);
6307 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6308 // p, varname, strloc, subtype, startloc, varflags, quotes);
6311 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6313 STPUTC('\0', expdest);
6314 herefd = saveherefd;
6315 argbackq = saveargbackq;
6316 startp = (char *)stackblock() + startloc;
6320 setvar(varname, startp, 0);
6321 amount = startp - expdest;
6322 STADJUST(amount, expdest);
6326 varunset(p, varname, startp, varflags);
6329 #if ENABLE_ASH_BASH_COMPAT
6331 loc = str = stackblock() + strloc;
6332 /* Read POS in ${var:POS:LEN} */
6333 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6334 len = str - startp - 1;
6336 /* *loc != '\0', guaranteed by parser */
6340 /* Adjust the length by the number of escapes */
6341 for (ptr = startp; ptr < (str - 1); ptr++) {
6342 if ((unsigned char)*ptr == CTLESC) {
6350 if (*loc++ == ':') {
6354 /* Skip POS in ${var:POS:LEN} */
6356 while (*loc && *loc != ':') {
6358 * bash complains on: var=qwe; echo ${var:1a:123}
6360 ash_msg_and_raise_error(msg_illnum, str);
6364 if (*loc++ == ':') {
6368 if (pos >= orig_len) {
6372 if (len > (orig_len - pos))
6373 len = orig_len - pos;
6375 for (str = startp; pos; str++, pos--) {
6376 if (quotes && (unsigned char)*str == CTLESC)
6379 for (loc = startp; len; len--) {
6380 if (quotes && (unsigned char)*str == CTLESC)
6385 amount = loc - expdest;
6386 STADJUST(amount, expdest);
6391 resetloc = expdest - (char *)stackblock();
6393 /* We'll comeback here if we grow the stack while handling
6394 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6395 * stack will need rebasing, and we'll need to remove our work
6398 IF_ASH_BASH_COMPAT(restart:)
6400 amount = expdest - ((char *)stackblock() + resetloc);
6401 STADJUST(-amount, expdest);
6402 startp = (char *)stackblock() + startloc;
6405 rmescend = (char *)stackblock() + strloc;
6407 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6408 if (rmesc != startp) {
6410 startp = (char *)stackblock() + startloc;
6414 str = (char *)stackblock() + strloc;
6415 preglob(str, varflags & VSQUOTE, 0);
6416 workloc = expdest - (char *)stackblock();
6418 #if ENABLE_ASH_BASH_COMPAT
6419 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6423 repl = parse_sub_pattern(str, varflags);
6424 //bb_error_msg("repl:'%s'", repl);
6429 /* If there's no pattern to match, return the expansion unmolested */
6438 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6439 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6441 /* No match, advance */
6442 char *restart_detect = stackblock();
6444 STPUTC(*idx, expdest);
6445 if (quotes && (unsigned char)*idx == CTLESC) {
6448 STPUTC(*idx, expdest);
6450 if (stackblock() != restart_detect)
6455 /* continue; - prone to quadratic behavior, smarter code: */
6458 if (str[0] == '*') {
6459 /* Pattern is "*foo". If "*foo" does not match "long_string",
6460 * it would never match "ong_string" etc, no point in trying.
6467 if (subtype == VSREPLACEALL) {
6469 if (quotes && (unsigned char)*idx == CTLESC)
6478 //bb_error_msg("repl:'%s'", repl);
6479 for (loc = (char*)repl; *loc; loc++) {
6480 char *restart_detect = stackblock();
6481 if (quotes && *loc == '\\') {
6482 STPUTC(CTLESC, expdest);
6485 STPUTC(*loc, expdest);
6486 if (stackblock() != restart_detect)
6491 if (subtype == VSREPLACE) {
6492 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6494 char *restart_detect = stackblock();
6495 STPUTC(*idx, expdest);
6496 if (stackblock() != restart_detect)
6505 /* We've put the replaced text into a buffer at workloc, now
6506 * move it to the right place and adjust the stack.
6508 STPUTC('\0', expdest);
6509 startp = (char *)stackblock() + startloc;
6510 memmove(startp, (char *)stackblock() + workloc, len + 1);
6511 //bb_error_msg("startp:'%s'", startp);
6512 amount = expdest - (startp + len);
6513 STADJUST(-amount, expdest);
6516 #endif /* ENABLE_ASH_BASH_COMPAT */
6518 subtype -= VSTRIMRIGHT;
6520 if (subtype < 0 || subtype > 7)
6523 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6524 zero = subtype >> 1;
6525 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6526 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6528 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6531 memmove(startp, loc, str - loc);
6532 loc = startp + (str - loc) - 1;
6535 amount = loc - expdest;
6536 STADJUST(amount, expdest);
6542 * Add the value of a specialized variable to the stack string.
6543 * name parameter (examples):
6544 * ash -c 'echo $1' name:'1='
6545 * ash -c 'echo $qwe' name:'qwe='
6546 * ash -c 'echo $$' name:'$='
6547 * ash -c 'echo ${$}' name:'$='
6548 * ash -c 'echo ${$##q}' name:'$=q'
6549 * ash -c 'echo ${#$}' name:'$='
6550 * note: examples with bad shell syntax:
6551 * ash -c 'echo ${#$1}' name:'$=1'
6552 * ash -c 'echo ${#1#}' name:'1=#'
6554 static NOINLINE ssize_t
6555 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6562 int subtype = varflags & VSTYPE;
6563 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6564 int quoted = varflags & VSQUOTE;
6565 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6575 num = shellparam.nparam;
6583 goto check_1char_name;
6585 expdest = makestrspace(NOPTS, expdest);
6586 for (i = NOPTS - 1; i >= 0; i--) {
6588 USTPUTC(optletters(i), expdest);
6594 /* handles cases similar to ${#$1} */
6595 if (name[2] != '\0')
6596 raise_error_syntax("bad substitution");
6603 if (quoted && (flags & EXP_FULL)) {
6604 /* note: this is not meant as PEOF value */
6605 sep = 1 << CHAR_BIT;
6610 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6611 i = SIT(sep, syntax);
6612 if (quotes && (i == CCTL || i == CBACK))
6618 while ((p = *ap++) != NULL) {
6621 partlen = strlen(p);
6624 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6625 memtodest(p, partlen, syntax, quotes);
6631 if (subtype == VSPLUS || subtype == VSLENGTH) {
6637 /* note: may put NUL despite sep != 0
6638 * (see sep = 1 << CHAR_BIT above) */
6644 } /* case '@' and '*' */
6655 num = atoi(name); /* number(name) fails on ${N#str} etc */
6656 if (num < 0 || num > shellparam.nparam)
6658 p = num ? shellparam.p[num - 1] : arg0;
6661 /* NB: name has form "VAR=..." */
6663 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6664 * which should be considered before we check variables. */
6666 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6670 str = var_str_list->text;
6671 eq = strchr(str, '=');
6672 if (!eq) /* stop at first non-assignment */
6675 if (name_len == (unsigned)(eq - str)
6676 && strncmp(str, name, name_len) == 0
6679 /* goto value; - WRONG! */
6680 /* think "A=1 A=2 B=$A" */
6682 var_str_list = var_str_list->next;
6683 } while (var_str_list);
6687 p = lookupvar(name);
6693 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6694 memtodest(p, len, syntax, quotes);
6698 if (subtype == VSPLUS || subtype == VSLENGTH)
6699 STADJUST(-len, expdest);
6704 * Expand a variable, and return a pointer to the next character in the
6708 evalvar(char *p, int flags, struct strlist *var_str_list)
6719 varflags = (unsigned char) *p++;
6720 subtype = varflags & VSTYPE;
6721 quoted = varflags & VSQUOTE;
6723 easy = (!quoted || (*var == '@' && shellparam.nparam));
6724 startloc = expdest - (char *)stackblock();
6725 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6728 varlen = varvalue(var, varflags, flags, var_str_list);
6729 if (varflags & VSNUL)
6732 if (subtype == VSPLUS) {
6733 varlen = -1 - varlen;
6737 if (subtype == VSMINUS) {
6742 flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
6752 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6754 if (subevalvar(p, var, /* strloc: */ 0,
6755 subtype, startloc, varflags,
6761 * Remove any recorded regions beyond
6764 removerecordregions(startloc);
6774 if (varlen < 0 && uflag)
6775 varunset(p, var, 0, 0);
6777 if (subtype == VSLENGTH) {
6778 cvtnum(varlen > 0 ? varlen : 0);
6782 if (subtype == VSNORMAL) {
6793 case VSTRIMRIGHTMAX:
6794 #if ENABLE_ASH_BASH_COMPAT
6807 * Terminate the string and start recording the pattern
6810 STPUTC('\0', expdest);
6811 patloc = expdest - (char *)stackblock();
6812 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6814 //TODO: | EXP_REDIR too? All other such places do it too
6815 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6818 int amount = expdest - (
6819 (char *)stackblock() + patloc - 1
6821 STADJUST(-amount, expdest);
6823 /* Remove any recorded regions beyond start of variable */
6824 removerecordregions(startloc);
6826 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6830 if (subtype != VSNORMAL) { /* skip to end of alternative */
6833 unsigned char c = *p++;
6836 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6838 argbackq = argbackq->next;
6839 } else if (c == CTLVAR) {
6840 if ((*p++ & VSTYPE) != VSNORMAL)
6842 } else if (c == CTLENDVAR) {
6852 * Break the argument string into pieces based upon IFS and add the
6853 * strings to the argument list. The regions of the string to be
6854 * searched for IFS characters have been stored by recordregion.
6857 ifsbreakup(char *string, struct arglist *arglist)
6859 struct ifsregion *ifsp;
6864 const char *ifs, *realifs;
6869 if (ifslastp != NULL) {
6872 realifs = ifsset() ? ifsval() : defifs;
6875 p = string + ifsp->begoff;
6876 nulonly = ifsp->nulonly;
6877 ifs = nulonly ? nullstr : realifs;
6879 while (p < string + ifsp->endoff) {
6881 if ((unsigned char)*p == CTLESC)
6883 if (!strchr(ifs, *p)) {
6888 ifsspc = (strchr(defifs, *p) != NULL);
6889 /* Ignore IFS whitespace at start */
6890 if (q == start && ifsspc) {
6896 sp = stzalloc(sizeof(*sp));
6898 *arglist->lastp = sp;
6899 arglist->lastp = &sp->next;
6903 if (p >= string + ifsp->endoff) {
6907 if ((unsigned char)*p == CTLESC)
6909 if (strchr(ifs, *p) == NULL) {
6913 if (strchr(defifs, *p) == NULL) {
6928 } while (ifsp != NULL);
6937 sp = stzalloc(sizeof(*sp));
6939 *arglist->lastp = sp;
6940 arglist->lastp = &sp->next;
6946 struct ifsregion *p;
6951 struct ifsregion *ifsp;
6957 ifsfirst.next = NULL;
6962 * Add a file name to the list.
6965 addfname(const char *name)
6969 sp = stzalloc(sizeof(*sp));
6970 sp->text = ststrdup(name);
6972 exparg.lastp = &sp->next;
6976 * Do metacharacter (i.e. *, ?, [...]) expansion.
6979 expmeta(char *expdir, char *enddir, char *name)
6994 for (p = name; *p; p++) {
6995 if (*p == '*' || *p == '?')
6997 else if (*p == '[') {
7004 if (*q == '/' || *q == '\0')
7011 } else if (*p == '\\')
7013 else if (*p == '/') {
7020 if (metaflag == 0) { /* we've reached the end of the file name */
7021 if (enddir != expdir)
7029 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7040 } while (p < start);
7042 if (enddir == expdir) {
7044 } else if (enddir == expdir + 1 && *expdir == '/') {
7053 if (enddir != expdir)
7055 if (*endname == 0) {
7067 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7068 if (dp->d_name[0] == '.' && !matchdot)
7070 if (pmatch(start, dp->d_name)) {
7072 strcpy(enddir, dp->d_name);
7075 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7078 expmeta(expdir, p, endname);
7087 static struct strlist *
7088 msort(struct strlist *list, int len)
7090 struct strlist *p, *q = NULL;
7091 struct strlist **lpp;
7099 for (n = half; --n >= 0;) {
7103 q->next = NULL; /* terminate first half of list */
7104 q = msort(list, half); /* sort first half of list */
7105 p = msort(p, len - half); /* sort second half */
7108 #if ENABLE_LOCALE_SUPPORT
7109 if (strcoll(p->text, q->text) < 0)
7111 if (strcmp(p->text, q->text) < 0)
7135 * Sort the results of file name expansion. It calculates the number of
7136 * strings to sort and then calls msort (short for merge sort) to do the
7139 static struct strlist *
7140 expsort(struct strlist *str)
7146 for (sp = str; sp; sp = sp->next)
7148 return msort(str, len);
7152 expandmeta(struct strlist *str /*, int flag*/)
7154 static const char metachars[] ALIGN1 = {
7157 /* TODO - EXP_REDIR */
7161 struct strlist **savelastp;
7167 if (!strpbrk(str->text, metachars))
7169 savelastp = exparg.lastp;
7172 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7174 int i = strlen(str->text);
7175 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7177 expmeta(expdir, expdir, p);
7182 if (exparg.lastp == savelastp) {
7187 *exparg.lastp = str;
7188 rmescapes(str->text, 0);
7189 exparg.lastp = &str->next;
7191 *exparg.lastp = NULL;
7192 *savelastp = sp = expsort(*savelastp);
7193 while (sp->next != NULL)
7195 exparg.lastp = &sp->next;
7202 * Perform variable substitution and command substitution on an argument,
7203 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7204 * perform splitting and file name expansion. When arglist is NULL, perform
7205 * here document expansion.
7208 expandarg(union node *arg, struct arglist *arglist, int flag)
7213 argbackq = arg->narg.backquote;
7214 STARTSTACKSTR(expdest);
7215 ifsfirst.next = NULL;
7217 argstr(arg->narg.text, flag,
7218 /* var_str_list: */ arglist ? arglist->list : NULL);
7219 p = _STPUTC('\0', expdest);
7221 if (arglist == NULL) {
7222 return; /* here document expanded */
7224 p = grabstackstr(p);
7225 exparg.lastp = &exparg.list;
7229 if (flag & EXP_FULL) {
7230 ifsbreakup(p, &exparg);
7231 *exparg.lastp = NULL;
7232 exparg.lastp = &exparg.list;
7233 expandmeta(exparg.list /*, flag*/);
7235 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7237 sp = stzalloc(sizeof(*sp));
7240 exparg.lastp = &sp->next;
7244 *exparg.lastp = NULL;
7246 *arglist->lastp = exparg.list;
7247 arglist->lastp = exparg.lastp;
7252 * Expand shell variables and backquotes inside a here document.
7255 expandhere(union node *arg, int fd)
7258 expandarg(arg, (struct arglist *)NULL, 0);
7259 full_write(fd, stackblock(), expdest - (char *)stackblock());
7263 * Returns true if the pattern matches the string.
7266 patmatch(char *pattern, const char *string)
7268 return pmatch(preglob(pattern, 0, 0), string);
7272 * See if a pattern matches in a case statement.
7275 casematch(union node *pattern, char *val)
7277 struct stackmark smark;
7280 setstackmark(&smark);
7281 argbackq = pattern->narg.backquote;
7282 STARTSTACKSTR(expdest);
7284 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7285 /* var_str_list: */ NULL);
7286 STACKSTRNUL(expdest);
7287 result = patmatch(stackblock(), val);
7288 popstackmark(&smark);
7293 /* ============ find_command */
7297 int (*builtin)(int, char **) FAST_FUNC;
7298 /* unsigned flags; */
7300 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7301 /* "regular" builtins always take precedence over commands,
7302 * regardless of PATH=....%builtin... position */
7303 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7304 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7307 smallint cmdtype; /* CMDxxx */
7310 /* index >= 0 for commands without path (slashes) */
7311 /* (TODO: what exactly does the value mean? PATH position?) */
7312 /* index == -1 for commands with slashes */
7313 /* index == (-2 - applet_no) for NOFORK applets */
7314 const struct builtincmd *cmd;
7315 struct funcnode *func;
7318 /* values of cmdtype */
7319 #define CMDUNKNOWN -1 /* no entry in table for command */
7320 #define CMDNORMAL 0 /* command is an executable program */
7321 #define CMDFUNCTION 1 /* command is a shell function */
7322 #define CMDBUILTIN 2 /* command is a shell builtin */
7324 /* action to find_command() */
7325 #define DO_ERR 0x01 /* prints errors */
7326 #define DO_ABS 0x02 /* checks absolute paths */
7327 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7328 #define DO_ALTPATH 0x08 /* using alternate path */
7329 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7331 static void find_command(char *, struct cmdentry *, int, const char *);
7334 /* ============ Hashing commands */
7337 * When commands are first encountered, they are entered in a hash table.
7338 * This ensures that a full path search will not have to be done for them
7339 * on each invocation.
7341 * We should investigate converting to a linear search, even though that
7342 * would make the command name "hash" a misnomer.
7346 struct tblentry *next; /* next entry in hash chain */
7347 union param param; /* definition of builtin function */
7348 smallint cmdtype; /* CMDxxx */
7349 char rehash; /* if set, cd done since entry created */
7350 char cmdname[1]; /* name of command */
7353 static struct tblentry **cmdtable;
7354 #define INIT_G_cmdtable() do { \
7355 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7358 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7362 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7366 #if ENABLE_FEATURE_SH_STANDALONE
7367 if (applet_no >= 0) {
7368 if (APPLET_IS_NOEXEC(applet_no)) {
7372 run_applet_no_and_exit(applet_no, argv);
7374 /* re-exec ourselves with the new arguments */
7375 execve(bb_busybox_exec_path, argv, envp);
7376 /* If they called chroot or otherwise made the binary no longer
7377 * executable, fall through */
7384 execve(cmd, argv, envp);
7385 } while (errno == EINTR);
7387 execve(cmd, argv, envp);
7393 if (errno == ENOEXEC) {
7397 for (ap = argv; *ap; ap++)
7399 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7401 ap[0] = cmd = (char *)DEFAULT_SHELL;
7404 while ((*ap++ = *argv++) != NULL)
7413 * Exec a program. Never returns. If you change this routine, you may
7414 * have to change the find_command routine as well.
7416 static void shellexec(char **, const char *, int) NORETURN;
7418 shellexec(char **argv, const char *path, int idx)
7424 #if ENABLE_FEATURE_SH_STANDALONE
7428 clearredir(/*drop:*/ 1);
7429 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7430 if (strchr(argv[0], '/') != NULL
7431 #if ENABLE_FEATURE_SH_STANDALONE
7432 || (applet_no = find_applet_by_name(argv[0])) >= 0
7435 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7439 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7440 if (--idx < 0 && pathopt == NULL) {
7441 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7442 if (errno != ENOENT && errno != ENOTDIR)
7449 /* Map to POSIX errors */
7461 exitstatus = exerrno;
7462 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7463 argv[0], e, suppress_int));
7464 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7469 printentry(struct tblentry *cmdp)
7475 idx = cmdp->param.index;
7478 name = path_advance(&path, cmdp->cmdname);
7480 } while (--idx >= 0);
7481 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7485 * Clear out command entries. The argument specifies the first entry in
7486 * PATH which has changed.
7489 clearcmdentry(int firstchange)
7491 struct tblentry **tblp;
7492 struct tblentry **pp;
7493 struct tblentry *cmdp;
7496 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7498 while ((cmdp = *pp) != NULL) {
7499 if ((cmdp->cmdtype == CMDNORMAL &&
7500 cmdp->param.index >= firstchange)
7501 || (cmdp->cmdtype == CMDBUILTIN &&
7502 builtinloc >= firstchange)
7515 * Locate a command in the command hash table. If "add" is nonzero,
7516 * add the command to the table if it is not already present. The
7517 * variable "lastcmdentry" is set to point to the address of the link
7518 * pointing to the entry, so that delete_cmd_entry can delete the
7521 * Interrupts must be off if called with add != 0.
7523 static struct tblentry **lastcmdentry;
7525 static struct tblentry *
7526 cmdlookup(const char *name, int add)
7528 unsigned int hashval;
7530 struct tblentry *cmdp;
7531 struct tblentry **pp;
7534 hashval = (unsigned char)*p << 4;
7536 hashval += (unsigned char)*p++;
7538 pp = &cmdtable[hashval % CMDTABLESIZE];
7539 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7540 if (strcmp(cmdp->cmdname, name) == 0)
7544 if (add && cmdp == NULL) {
7545 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7547 /* + 1 - already done because
7548 * tblentry::cmdname is char[1] */);
7549 /*cmdp->next = NULL; - ckzalloc did it */
7550 cmdp->cmdtype = CMDUNKNOWN;
7551 strcpy(cmdp->cmdname, name);
7558 * Delete the command entry returned on the last lookup.
7561 delete_cmd_entry(void)
7563 struct tblentry *cmdp;
7566 cmdp = *lastcmdentry;
7567 *lastcmdentry = cmdp->next;
7568 if (cmdp->cmdtype == CMDFUNCTION)
7569 freefunc(cmdp->param.func);
7575 * Add a new command entry, replacing any existing command entry for
7576 * the same name - except special builtins.
7579 addcmdentry(char *name, struct cmdentry *entry)
7581 struct tblentry *cmdp;
7583 cmdp = cmdlookup(name, 1);
7584 if (cmdp->cmdtype == CMDFUNCTION) {
7585 freefunc(cmdp->param.func);
7587 cmdp->cmdtype = entry->cmdtype;
7588 cmdp->param = entry->u;
7592 static int FAST_FUNC
7593 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7595 struct tblentry **pp;
7596 struct tblentry *cmdp;
7598 struct cmdentry entry;
7601 if (nextopt("r") != '\0') {
7606 if (*argptr == NULL) {
7607 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7608 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7609 if (cmdp->cmdtype == CMDNORMAL)
7617 while ((name = *argptr) != NULL) {
7618 cmdp = cmdlookup(name, 0);
7620 && (cmdp->cmdtype == CMDNORMAL
7621 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7625 find_command(name, &entry, DO_ERR, pathval());
7626 if (entry.cmdtype == CMDUNKNOWN)
7634 * Called when a cd is done. Marks all commands so the next time they
7635 * are executed they will be rehashed.
7640 struct tblentry **pp;
7641 struct tblentry *cmdp;
7643 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7644 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7645 if (cmdp->cmdtype == CMDNORMAL
7646 || (cmdp->cmdtype == CMDBUILTIN
7647 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7657 * Fix command hash table when PATH changed.
7658 * Called before PATH is changed. The argument is the new value of PATH;
7659 * pathval() still returns the old value at this point.
7660 * Called with interrupts off.
7662 static void FAST_FUNC
7663 changepath(const char *new)
7671 firstchange = 9999; /* assume no change */
7677 if ((*old == '\0' && *new == ':')
7678 || (*old == ':' && *new == '\0')
7682 old = new; /* ignore subsequent differences */
7686 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7693 if (builtinloc < 0 && idx_bltin >= 0)
7694 builtinloc = idx_bltin; /* zap builtins */
7695 if (builtinloc >= 0 && idx_bltin < 0)
7697 clearcmdentry(firstchange);
7698 builtinloc = idx_bltin;
7713 #define TENDBQUOTE 12
7730 typedef smallint token_id_t;
7732 /* first char is indicating which tokens mark the end of a list */
7733 static const char *const tokname_array[] = {
7747 #define KWDOFFSET 13
7748 /* the following are keywords */
7767 /* Wrapper around strcmp for qsort/bsearch/... */
7769 pstrcmp(const void *a, const void *b)
7771 return strcmp((char*) a, (*(char**) b) + 1);
7774 static const char *const *
7775 findkwd(const char *s)
7777 return bsearch(s, tokname_array + KWDOFFSET,
7778 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7779 sizeof(tokname_array[0]), pstrcmp);
7783 * Locate and print what a word is...
7786 describe_command(char *command, int describe_command_verbose)
7788 struct cmdentry entry;
7789 struct tblentry *cmdp;
7790 #if ENABLE_ASH_ALIAS
7791 const struct alias *ap;
7793 const char *path = pathval();
7795 if (describe_command_verbose) {
7799 /* First look at the keywords */
7800 if (findkwd(command)) {
7801 out1str(describe_command_verbose ? " is a shell keyword" : command);
7805 #if ENABLE_ASH_ALIAS
7806 /* Then look at the aliases */
7807 ap = lookupalias(command, 0);
7809 if (!describe_command_verbose) {
7814 out1fmt(" is an alias for %s", ap->val);
7818 /* Then check if it is a tracked alias */
7819 cmdp = cmdlookup(command, 0);
7821 entry.cmdtype = cmdp->cmdtype;
7822 entry.u = cmdp->param;
7824 /* Finally use brute force */
7825 find_command(command, &entry, DO_ABS, path);
7828 switch (entry.cmdtype) {
7830 int j = entry.u.index;
7836 p = path_advance(&path, command);
7840 if (describe_command_verbose) {
7842 (cmdp ? " a tracked alias for" : nullstr), p
7851 if (describe_command_verbose) {
7852 out1str(" is a shell function");
7859 if (describe_command_verbose) {
7860 out1fmt(" is a %sshell builtin",
7861 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7862 "special " : nullstr
7870 if (describe_command_verbose) {
7871 out1str(": not found\n");
7880 static int FAST_FUNC
7881 typecmd(int argc UNUSED_PARAM, char **argv)
7887 /* type -p ... ? (we don't bother checking for 'p') */
7888 if (argv[1] && argv[1][0] == '-') {
7893 err |= describe_command(argv[i++], verbose);
7898 #if ENABLE_ASH_CMDCMD
7899 static int FAST_FUNC
7900 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7908 while ((c = nextopt("pvV")) != '\0')
7910 verify |= VERIFY_VERBOSE;
7912 verify |= VERIFY_BRIEF;
7917 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7918 if (verify && (*argptr != NULL)) {
7919 return describe_command(*argptr, verify - VERIFY_BRIEF);
7927 /* ============ eval.c */
7929 static int funcblocksize; /* size of structures in function */
7930 static int funcstringsize; /* size of strings in node */
7931 static void *funcblock; /* block to allocate function from */
7932 static char *funcstring; /* block to allocate strings from */
7934 /* flags in argument to evaltree */
7935 #define EV_EXIT 01 /* exit after evaluating tree */
7936 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7937 #define EV_BACKCMD 04 /* command executing within back quotes */
7939 static const uint8_t nodesize[N_NUMBER] = {
7940 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7941 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7942 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7943 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7944 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7945 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7946 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7947 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7948 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7949 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7950 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7951 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7952 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7953 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7954 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7955 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7956 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7957 #if ENABLE_ASH_BASH_COMPAT
7958 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7960 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7961 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7962 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7963 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7964 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7965 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7966 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7967 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7968 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7971 static void calcsize(union node *n);
7974 sizenodelist(struct nodelist *lp)
7977 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7984 calcsize(union node *n)
7988 funcblocksize += nodesize[n->type];
7991 calcsize(n->ncmd.redirect);
7992 calcsize(n->ncmd.args);
7993 calcsize(n->ncmd.assign);
7996 sizenodelist(n->npipe.cmdlist);
8001 calcsize(n->nredir.redirect);
8002 calcsize(n->nredir.n);
8009 calcsize(n->nbinary.ch2);
8010 calcsize(n->nbinary.ch1);
8013 calcsize(n->nif.elsepart);
8014 calcsize(n->nif.ifpart);
8015 calcsize(n->nif.test);
8018 funcstringsize += strlen(n->nfor.var) + 1;
8019 calcsize(n->nfor.body);
8020 calcsize(n->nfor.args);
8023 calcsize(n->ncase.cases);
8024 calcsize(n->ncase.expr);
8027 calcsize(n->nclist.body);
8028 calcsize(n->nclist.pattern);
8029 calcsize(n->nclist.next);
8033 sizenodelist(n->narg.backquote);
8034 funcstringsize += strlen(n->narg.text) + 1;
8035 calcsize(n->narg.next);
8038 #if ENABLE_ASH_BASH_COMPAT
8045 calcsize(n->nfile.fname);
8046 calcsize(n->nfile.next);
8050 calcsize(n->ndup.vname);
8051 calcsize(n->ndup.next);
8055 calcsize(n->nhere.doc);
8056 calcsize(n->nhere.next);
8059 calcsize(n->nnot.com);
8065 nodeckstrdup(char *s)
8067 char *rtn = funcstring;
8069 strcpy(funcstring, s);
8070 funcstring += strlen(s) + 1;
8074 static union node *copynode(union node *);
8076 static struct nodelist *
8077 copynodelist(struct nodelist *lp)
8079 struct nodelist *start;
8080 struct nodelist **lpp;
8085 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8086 (*lpp)->n = copynode(lp->n);
8088 lpp = &(*lpp)->next;
8095 copynode(union node *n)
8102 funcblock = (char *) funcblock + nodesize[n->type];
8106 new->ncmd.redirect = copynode(n->ncmd.redirect);
8107 new->ncmd.args = copynode(n->ncmd.args);
8108 new->ncmd.assign = copynode(n->ncmd.assign);
8111 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8112 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8117 new->nredir.redirect = copynode(n->nredir.redirect);
8118 new->nredir.n = copynode(n->nredir.n);
8125 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8126 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8129 new->nif.elsepart = copynode(n->nif.elsepart);
8130 new->nif.ifpart = copynode(n->nif.ifpart);
8131 new->nif.test = copynode(n->nif.test);
8134 new->nfor.var = nodeckstrdup(n->nfor.var);
8135 new->nfor.body = copynode(n->nfor.body);
8136 new->nfor.args = copynode(n->nfor.args);
8139 new->ncase.cases = copynode(n->ncase.cases);
8140 new->ncase.expr = copynode(n->ncase.expr);
8143 new->nclist.body = copynode(n->nclist.body);
8144 new->nclist.pattern = copynode(n->nclist.pattern);
8145 new->nclist.next = copynode(n->nclist.next);
8149 new->narg.backquote = copynodelist(n->narg.backquote);
8150 new->narg.text = nodeckstrdup(n->narg.text);
8151 new->narg.next = copynode(n->narg.next);
8154 #if ENABLE_ASH_BASH_COMPAT
8161 new->nfile.fname = copynode(n->nfile.fname);
8162 new->nfile.fd = n->nfile.fd;
8163 new->nfile.next = copynode(n->nfile.next);
8167 new->ndup.vname = copynode(n->ndup.vname);
8168 new->ndup.dupfd = n->ndup.dupfd;
8169 new->ndup.fd = n->ndup.fd;
8170 new->ndup.next = copynode(n->ndup.next);
8174 new->nhere.doc = copynode(n->nhere.doc);
8175 new->nhere.fd = n->nhere.fd;
8176 new->nhere.next = copynode(n->nhere.next);
8179 new->nnot.com = copynode(n->nnot.com);
8182 new->type = n->type;
8187 * Make a copy of a parse tree.
8189 static struct funcnode *
8190 copyfunc(union node *n)
8195 funcblocksize = offsetof(struct funcnode, n);
8198 blocksize = funcblocksize;
8199 f = ckmalloc(blocksize + funcstringsize);
8200 funcblock = (char *) f + offsetof(struct funcnode, n);
8201 funcstring = (char *) f + blocksize;
8208 * Define a shell function.
8211 defun(char *name, union node *func)
8213 struct cmdentry entry;
8216 entry.cmdtype = CMDFUNCTION;
8217 entry.u.func = copyfunc(func);
8218 addcmdentry(name, &entry);
8222 /* Reasons for skipping commands (see comment on breakcmd routine) */
8223 #define SKIPBREAK (1 << 0)
8224 #define SKIPCONT (1 << 1)
8225 #define SKIPFUNC (1 << 2)
8226 #define SKIPFILE (1 << 3)
8227 #define SKIPEVAL (1 << 4)
8228 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8229 static int skipcount; /* number of levels to skip */
8230 static int funcnest; /* depth of function calls */
8231 static int loopnest; /* current loop nesting level */
8233 /* Forward decl way out to parsing code - dotrap needs it */
8234 static int evalstring(char *s, int mask);
8236 /* Called to execute a trap.
8237 * Single callsite - at the end of evaltree().
8238 * If we return non-zero, evaltree raises EXEXIT exception.
8240 * Perhaps we should avoid entering new trap handlers
8241 * while we are executing a trap handler. [is it a TODO?]
8250 savestatus = exitstatus;
8254 TRACE(("dotrap entered\n"));
8255 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8262 /* non-trapped SIGINT is handled separately by raise_interrupt,
8263 * don't upset it by resetting gotsig[SIGINT-1] */
8264 if (sig == SIGINT && !t)
8267 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8271 want_exexit = evalstring(t, SKIPEVAL);
8272 exitstatus = savestatus;
8274 TRACE(("dotrap returns %d\n", want_exexit));
8279 TRACE(("dotrap returns 0\n"));
8283 /* forward declarations - evaluation is fairly recursive business... */
8284 static void evalloop(union node *, int);
8285 static void evalfor(union node *, int);
8286 static void evalcase(union node *, int);
8287 static void evalsubshell(union node *, int);
8288 static void expredir(union node *);
8289 static void evalpipe(union node *, int);
8290 static void evalcommand(union node *, int);
8291 static int evalbltin(const struct builtincmd *, int, char **);
8292 static void prehash(union node *);
8295 * Evaluate a parse tree. The value is left in the global variable
8299 evaltree(union node *n, int flags)
8301 struct jmploc *volatile savehandler = exception_handler;
8302 struct jmploc jmploc;
8304 void (*evalfn)(union node *, int);
8308 SAVE_INT(int_level);
8311 TRACE(("evaltree(NULL) called\n"));
8314 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8316 exception_handler = &jmploc;
8318 int err = setjmp(jmploc.loc);
8320 /* if it was a signal, check for trap handlers */
8321 if (exception_type == EXSIG) {
8322 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8323 exception_type, err));
8326 /* continue on the way out */
8327 TRACE(("exception %d in evaltree, propagating err=%d\n",
8328 exception_type, err));
8329 exception_handler = savehandler;
8330 longjmp(exception_handler->loc, err);
8337 out1fmt("Node type = %d\n", n->type);
8342 evaltree(n->nnot.com, EV_TESTED);
8343 status = !exitstatus;
8346 expredir(n->nredir.redirect);
8347 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8349 evaltree(n->nredir.n, flags & EV_TESTED);
8350 status = exitstatus;
8352 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8355 evalfn = evalcommand;
8357 if (eflag && !(flags & EV_TESTED))
8369 evalfn = evalsubshell;
8382 #error NAND + 1 != NOR
8384 #if NOR + 1 != NSEMI
8385 #error NOR + 1 != NSEMI
8387 unsigned is_or = n->type - NAND;
8390 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8392 if (!exitstatus == is_or)
8405 evaltree(n->nif.test, EV_TESTED);
8408 if (exitstatus == 0) {
8412 if (n->nif.elsepart) {
8413 n = n->nif.elsepart;
8418 defun(n->narg.text, n->narg.next);
8422 exitstatus = status;
8427 exception_handler = savehandler;
8430 /* Order of checks below is important:
8431 * signal handlers trigger before exit caused by "set -e".
8433 if (pending_sig && dotrap())
8435 if (checkexit & exitstatus)
8436 evalskip |= SKIPEVAL;
8438 if (flags & EV_EXIT) {
8440 raise_exception(EXEXIT);
8443 RESTORE_INT(int_level);
8444 TRACE(("leaving evaltree (no interrupts)\n"));
8447 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8450 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8453 evalloop(union node *n, int flags)
8463 evaltree(n->nbinary.ch1, EV_TESTED);
8466 if (evalskip == SKIPCONT && --skipcount <= 0) {
8470 if (evalskip == SKIPBREAK && --skipcount <= 0)
8475 if (n->type != NWHILE)
8479 evaltree(n->nbinary.ch2, flags);
8480 status = exitstatus;
8485 exitstatus = status;
8489 evalfor(union node *n, int flags)
8491 struct arglist arglist;
8494 struct stackmark smark;
8496 setstackmark(&smark);
8497 arglist.list = NULL;
8498 arglist.lastp = &arglist.list;
8499 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8500 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8505 *arglist.lastp = NULL;
8510 for (sp = arglist.list; sp; sp = sp->next) {
8511 setvar(n->nfor.var, sp->text, 0);
8512 evaltree(n->nfor.body, flags);
8514 if (evalskip == SKIPCONT && --skipcount <= 0) {
8518 if (evalskip == SKIPBREAK && --skipcount <= 0)
8525 popstackmark(&smark);
8529 evalcase(union node *n, int flags)
8533 struct arglist arglist;
8534 struct stackmark smark;
8536 setstackmark(&smark);
8537 arglist.list = NULL;
8538 arglist.lastp = &arglist.list;
8539 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8541 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8542 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8543 if (casematch(patp, arglist.list->text)) {
8544 if (evalskip == 0) {
8545 evaltree(cp->nclist.body, flags);
8552 popstackmark(&smark);
8556 * Kick off a subshell to evaluate a tree.
8559 evalsubshell(union node *n, int flags)
8562 int backgnd = (n->type == NBACKGND);
8565 expredir(n->nredir.redirect);
8566 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8569 jp = makejob(/*n,*/ 1);
8570 if (forkshell(jp, n, backgnd) == 0) {
8575 flags &= ~EV_TESTED;
8577 redirect(n->nredir.redirect, 0);
8578 evaltreenr(n->nredir.n, flags);
8583 status = waitforjob(jp);
8584 exitstatus = status;
8589 * Compute the names of the files in a redirection list.
8591 static void fixredir(union node *, const char *, int);
8593 expredir(union node *n)
8597 for (redir = n; redir; redir = redir->nfile.next) {
8601 fn.lastp = &fn.list;
8602 switch (redir->type) {
8606 #if ENABLE_ASH_BASH_COMPAT
8611 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8612 #if ENABLE_ASH_BASH_COMPAT
8615 redir->nfile.expfname = fn.list->text;
8618 case NTOFD: /* >& */
8619 if (redir->ndup.vname) {
8620 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8621 if (fn.list == NULL)
8622 ash_msg_and_raise_error("redir error");
8623 #if ENABLE_ASH_BASH_COMPAT
8624 //FIXME: we used expandarg with different args!
8625 if (!isdigit_str9(fn.list->text)) {
8626 /* >&file, not >&fd */
8627 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8628 ash_msg_and_raise_error("redir error");
8630 goto store_expfname;
8633 fixredir(redir, fn.list->text, 1);
8641 * Evaluate a pipeline. All the processes in the pipeline are children
8642 * of the process creating the pipeline. (This differs from some versions
8643 * of the shell, which make the last process in a pipeline the parent
8647 evalpipe(union node *n, int flags)
8650 struct nodelist *lp;
8655 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8657 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8661 jp = makejob(/*n,*/ pipelen);
8663 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8667 if (pipe(pip) < 0) {
8669 ash_msg_and_raise_error("pipe call failed");
8672 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8685 evaltreenr(lp->n, flags);
8691 /* Don't want to trigger debugging */
8695 if (n->npipe.pipe_backgnd == 0) {
8696 exitstatus = waitforjob(jp);
8697 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8703 * Controls whether the shell is interactive or not.
8706 setinteractive(int on)
8708 static smallint is_interactive;
8710 if (++on == is_interactive)
8712 is_interactive = on;
8716 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8717 if (is_interactive > 1) {
8718 /* Looks like they want an interactive shell */
8719 static smallint did_banner;
8722 /* note: ash and hush share this string */
8723 out1fmt("\n\n%s %s\n"
8724 "Enter 'help' for a list of built-in commands."
8727 "built-in shell (ash)"
8741 setinteractive(iflag);
8743 #if ENABLE_FEATURE_EDITING_VI
8745 line_input_state->flags |= VI_MODE;
8747 line_input_state->flags &= ~VI_MODE;
8749 viflag = 0; /* forcibly keep the option off */
8753 static struct localvar *localvars;
8756 * Called after a function returns.
8757 * Interrupts must be off.
8762 struct localvar *lvp;
8765 while ((lvp = localvars) != NULL) {
8766 localvars = lvp->next;
8768 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8769 if (vp == NULL) { /* $- saved */
8770 memcpy(optlist, lvp->text, sizeof(optlist));
8771 free((char*)lvp->text);
8773 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8774 unsetvar(vp->var_text);
8777 vp->var_func(var_end(lvp->text));
8778 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8779 free((char*)vp->var_text);
8780 vp->flags = lvp->flags;
8781 vp->var_text = lvp->text;
8788 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8790 volatile struct shparam saveparam;
8791 struct localvar *volatile savelocalvars;
8792 struct jmploc *volatile savehandler;
8793 struct jmploc jmploc;
8796 saveparam = shellparam;
8797 savelocalvars = localvars;
8798 e = setjmp(jmploc.loc);
8803 savehandler = exception_handler;
8804 exception_handler = &jmploc;
8806 shellparam.malloced = 0;
8810 shellparam.nparam = argc - 1;
8811 shellparam.p = argv + 1;
8812 #if ENABLE_ASH_GETOPTS
8813 shellparam.optind = 1;
8814 shellparam.optoff = -1;
8816 evaltree(&func->n, flags & EV_TESTED);
8822 localvars = savelocalvars;
8823 freeparam(&shellparam);
8824 shellparam = saveparam;
8825 exception_handler = savehandler;
8827 evalskip &= ~SKIPFUNC;
8831 #if ENABLE_ASH_CMDCMD
8833 parse_command_args(char **argv, const char **path)
8846 if (c == '-' && !*cp) {
8853 *path = bb_default_path;
8856 /* run 'typecmd' for other options */
8867 * Make a variable a local variable. When a variable is made local, it's
8868 * value and flags are saved in a localvar structure. The saved values
8869 * will be restored when the shell function returns. We handle the name
8870 * "-" as a special case.
8875 struct localvar *lvp;
8880 lvp = ckzalloc(sizeof(struct localvar));
8881 if (LONE_DASH(name)) {
8883 p = ckmalloc(sizeof(optlist));
8884 lvp->text = memcpy(p, optlist, sizeof(optlist));
8889 vpp = hashvar(name);
8890 vp = *findvar(vpp, name);
8891 eq = strchr(name, '=');
8894 setvareq(name, VSTRFIXED);
8896 setvar(name, NULL, VSTRFIXED);
8897 vp = *vpp; /* the new variable */
8898 lvp->flags = VUNSET;
8900 lvp->text = vp->var_text;
8901 lvp->flags = vp->flags;
8902 vp->flags |= VSTRFIXED|VTEXTFIXED;
8908 lvp->next = localvars;
8914 * The "local" command.
8916 static int FAST_FUNC
8917 localcmd(int argc UNUSED_PARAM, char **argv)
8922 while ((name = *argv++) != NULL) {
8928 static int FAST_FUNC
8929 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8934 static int FAST_FUNC
8935 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8940 static int FAST_FUNC
8941 execcmd(int argc UNUSED_PARAM, char **argv)
8944 iflag = 0; /* exit on error */
8947 shellexec(argv + 1, pathval(), 0);
8953 * The return command.
8955 static int FAST_FUNC
8956 returncmd(int argc UNUSED_PARAM, char **argv)
8959 * If called outside a function, do what ksh does;
8960 * skip the rest of the file.
8962 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8963 return argv[1] ? number(argv[1]) : exitstatus;
8966 /* Forward declarations for builtintab[] */
8967 static int breakcmd(int, char **) FAST_FUNC;
8968 static int dotcmd(int, char **) FAST_FUNC;
8969 static int evalcmd(int, char **) FAST_FUNC;
8970 static int exitcmd(int, char **) FAST_FUNC;
8971 static int exportcmd(int, char **) FAST_FUNC;
8972 #if ENABLE_ASH_GETOPTS
8973 static int getoptscmd(int, char **) FAST_FUNC;
8975 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8976 static int helpcmd(int, char **) FAST_FUNC;
8978 #if ENABLE_SH_MATH_SUPPORT
8979 static int letcmd(int, char **) FAST_FUNC;
8981 static int readcmd(int, char **) FAST_FUNC;
8982 static int setcmd(int, char **) FAST_FUNC;
8983 static int shiftcmd(int, char **) FAST_FUNC;
8984 static int timescmd(int, char **) FAST_FUNC;
8985 static int trapcmd(int, char **) FAST_FUNC;
8986 static int umaskcmd(int, char **) FAST_FUNC;
8987 static int unsetcmd(int, char **) FAST_FUNC;
8988 static int ulimitcmd(int, char **) FAST_FUNC;
8990 #define BUILTIN_NOSPEC "0"
8991 #define BUILTIN_SPECIAL "1"
8992 #define BUILTIN_REGULAR "2"
8993 #define BUILTIN_SPEC_REG "3"
8994 #define BUILTIN_ASSIGN "4"
8995 #define BUILTIN_SPEC_ASSG "5"
8996 #define BUILTIN_REG_ASSG "6"
8997 #define BUILTIN_SPEC_REG_ASSG "7"
8999 /* Stubs for calling non-FAST_FUNC's */
9000 #if ENABLE_ASH_BUILTIN_ECHO
9001 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9003 #if ENABLE_ASH_BUILTIN_PRINTF
9004 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9006 #if ENABLE_ASH_BUILTIN_TEST
9007 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9010 /* Keep these in proper order since it is searched via bsearch() */
9011 static const struct builtincmd builtintab[] = {
9012 { BUILTIN_SPEC_REG "." , dotcmd },
9013 { BUILTIN_SPEC_REG ":" , truecmd },
9014 #if ENABLE_ASH_BUILTIN_TEST
9015 { BUILTIN_REGULAR "[" , testcmd },
9016 #if ENABLE_ASH_BASH_COMPAT
9017 { BUILTIN_REGULAR "[[" , testcmd },
9020 #if ENABLE_ASH_ALIAS
9021 { BUILTIN_REG_ASSG "alias" , aliascmd },
9024 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9026 { BUILTIN_SPEC_REG "break" , breakcmd },
9027 { BUILTIN_REGULAR "cd" , cdcmd },
9028 { BUILTIN_NOSPEC "chdir" , cdcmd },
9029 #if ENABLE_ASH_CMDCMD
9030 { BUILTIN_REGULAR "command" , commandcmd },
9032 { BUILTIN_SPEC_REG "continue", breakcmd },
9033 #if ENABLE_ASH_BUILTIN_ECHO
9034 { BUILTIN_REGULAR "echo" , echocmd },
9036 { BUILTIN_SPEC_REG "eval" , evalcmd },
9037 { BUILTIN_SPEC_REG "exec" , execcmd },
9038 { BUILTIN_SPEC_REG "exit" , exitcmd },
9039 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9040 { BUILTIN_REGULAR "false" , falsecmd },
9042 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9044 #if ENABLE_ASH_GETOPTS
9045 { BUILTIN_REGULAR "getopts" , getoptscmd },
9047 { BUILTIN_NOSPEC "hash" , hashcmd },
9048 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9049 { BUILTIN_NOSPEC "help" , helpcmd },
9052 { BUILTIN_REGULAR "jobs" , jobscmd },
9053 { BUILTIN_REGULAR "kill" , killcmd },
9055 #if ENABLE_SH_MATH_SUPPORT
9056 { BUILTIN_NOSPEC "let" , letcmd },
9058 { BUILTIN_ASSIGN "local" , localcmd },
9059 #if ENABLE_ASH_BUILTIN_PRINTF
9060 { BUILTIN_REGULAR "printf" , printfcmd },
9062 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9063 { BUILTIN_REGULAR "read" , readcmd },
9064 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9065 { BUILTIN_SPEC_REG "return" , returncmd },
9066 { BUILTIN_SPEC_REG "set" , setcmd },
9067 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9068 #if ENABLE_ASH_BASH_COMPAT
9069 { BUILTIN_SPEC_REG "source" , dotcmd },
9071 #if ENABLE_ASH_BUILTIN_TEST
9072 { BUILTIN_REGULAR "test" , testcmd },
9074 { BUILTIN_SPEC_REG "times" , timescmd },
9075 { BUILTIN_SPEC_REG "trap" , trapcmd },
9076 { BUILTIN_REGULAR "true" , truecmd },
9077 { BUILTIN_NOSPEC "type" , typecmd },
9078 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9079 { BUILTIN_REGULAR "umask" , umaskcmd },
9080 #if ENABLE_ASH_ALIAS
9081 { BUILTIN_REGULAR "unalias" , unaliascmd },
9083 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9084 { BUILTIN_REGULAR "wait" , waitcmd },
9087 /* Should match the above table! */
9088 #define COMMANDCMD (builtintab + \
9090 1 * ENABLE_ASH_BUILTIN_TEST + \
9091 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9092 1 * ENABLE_ASH_ALIAS + \
9093 1 * ENABLE_ASH_JOB_CONTROL + \
9095 #define EXECCMD (builtintab + \
9097 1 * ENABLE_ASH_BUILTIN_TEST + \
9098 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9099 1 * ENABLE_ASH_ALIAS + \
9100 1 * ENABLE_ASH_JOB_CONTROL + \
9102 1 * ENABLE_ASH_CMDCMD + \
9104 ENABLE_ASH_BUILTIN_ECHO + \
9108 * Search the table of builtin commands.
9110 static struct builtincmd *
9111 find_builtin(const char *name)
9113 struct builtincmd *bp;
9116 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9123 * Execute a simple command.
9126 isassignment(const char *p)
9128 const char *q = endofname(p);
9133 static int FAST_FUNC
9134 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9136 /* Preserve exitstatus of a previous possible redirection
9137 * as POSIX mandates */
9138 return back_exitstatus;
9141 evalcommand(union node *cmd, int flags)
9143 static const struct builtincmd null_bltin = {
9144 "\0\0", bltincmd /* why three NULs? */
9146 struct stackmark smark;
9148 struct arglist arglist;
9149 struct arglist varlist;
9152 const struct strlist *sp;
9153 struct cmdentry cmdentry;
9160 struct builtincmd *bcmd;
9161 smallint cmd_is_exec;
9162 smallint pseudovarflag = 0;
9164 /* First expand the arguments. */
9165 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9166 setstackmark(&smark);
9167 back_exitstatus = 0;
9169 cmdentry.cmdtype = CMDBUILTIN;
9170 cmdentry.u.cmd = &null_bltin;
9171 varlist.lastp = &varlist.list;
9172 *varlist.lastp = NULL;
9173 arglist.lastp = &arglist.list;
9174 *arglist.lastp = NULL;
9177 if (cmd->ncmd.args) {
9178 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9179 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9182 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9183 struct strlist **spp;
9185 spp = arglist.lastp;
9186 if (pseudovarflag && isassignment(argp->narg.text))
9187 expandarg(argp, &arglist, EXP_VARTILDE);
9189 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9191 for (sp = *spp; sp; sp = sp->next)
9195 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9196 for (sp = arglist.list; sp; sp = sp->next) {
9197 TRACE(("evalcommand arg: %s\n", sp->text));
9198 *nargv++ = sp->text;
9203 if (iflag && funcnest == 0 && argc > 0)
9204 lastarg = nargv[-1];
9207 expredir(cmd->ncmd.redirect);
9208 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9210 path = vpath.var_text;
9211 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9212 struct strlist **spp;
9215 spp = varlist.lastp;
9216 expandarg(argp, &varlist, EXP_VARTILDE);
9219 * Modify the command lookup path, if a PATH= assignment
9223 if (varcmp(p, path) == 0)
9227 /* Print the command if xflag is set. */
9230 const char *p = " %s" + 1;
9232 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9234 for (n = 0; n < 2; n++) {
9236 fdprintf(preverrout_fd, p, sp->text);
9242 safe_write(preverrout_fd, "\n", 1);
9248 /* Now locate the command. */
9250 const char *oldpath;
9251 int cmd_flag = DO_ERR;
9256 find_command(argv[0], &cmdentry, cmd_flag, path);
9257 if (cmdentry.cmdtype == CMDUNKNOWN) {
9258 flush_stdout_stderr();
9263 /* implement bltin and command here */
9264 if (cmdentry.cmdtype != CMDBUILTIN)
9267 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9268 if (cmdentry.u.cmd == EXECCMD)
9270 #if ENABLE_ASH_CMDCMD
9271 if (cmdentry.u.cmd == COMMANDCMD) {
9273 nargv = parse_command_args(argv, &path);
9276 argc -= nargv - argv;
9278 cmd_flag |= DO_NOFUNC;
9286 /* We have a redirection error. */
9288 raise_exception(EXERROR);
9290 exitstatus = status;
9294 /* Execute the command. */
9295 switch (cmdentry.cmdtype) {
9298 #if ENABLE_FEATURE_SH_NOFORK
9299 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9300 * around run_nofork_applet() call.
9301 * (2) Should this check also be done in forkshell()?
9302 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9304 /* find_command() encodes applet_no as (-2 - applet_no) */
9305 int applet_no = (- cmdentry.u.index - 2);
9306 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9307 listsetvar(varlist.list, VEXPORT|VSTACK);
9308 /* run <applet>_main() */
9309 exitstatus = run_nofork_applet(applet_no, argv);
9313 /* Can we avoid forking off? For example, very last command
9314 * in a script or a subshell does not need forking,
9315 * we can just exec it.
9317 if (!(flags & EV_EXIT) || may_have_traps) {
9318 /* No, forking off a child is necessary */
9320 jp = makejob(/*cmd,*/ 1);
9321 if (forkshell(jp, cmd, FORK_FG) != 0) {
9323 exitstatus = waitforjob(jp);
9325 TRACE(("forked child exited with %d\n", exitstatus));
9330 /* fall through to exec'ing external program */
9332 listsetvar(varlist.list, VEXPORT|VSTACK);
9333 shellexec(argv, path, cmdentry.u.index);
9337 cmdenviron = varlist.list;
9339 struct strlist *list = cmdenviron;
9341 if (spclbltin > 0 || argc == 0) {
9343 if (cmd_is_exec && argc > 1)
9346 listsetvar(list, i);
9348 /* Tight loop with builtins only:
9349 * "while kill -0 $child; do true; done"
9350 * will never exit even if $child died, unless we do this
9351 * to reap the zombie and make kill detect that it's gone: */
9352 dowait(DOWAIT_NONBLOCK, NULL);
9354 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9356 int i = exception_type;
9361 exit_status = 128 + SIGINT;
9363 exit_status = 128 + pending_sig;
9364 exitstatus = exit_status;
9365 if (i == EXINT || spclbltin > 0) {
9367 longjmp(exception_handler->loc, 1);
9374 listsetvar(varlist.list, 0);
9375 /* See above for the rationale */
9376 dowait(DOWAIT_NONBLOCK, NULL);
9377 if (evalfun(cmdentry.u.func, argc, argv, flags))
9384 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9386 /* dsl: I think this is intended to be used to support
9387 * '_' in 'vi' command mode during line editing...
9388 * However I implemented that within libedit itself.
9390 setvar("_", lastarg, 0);
9392 popstackmark(&smark);
9396 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9398 char *volatile savecmdname;
9399 struct jmploc *volatile savehandler;
9400 struct jmploc jmploc;
9403 savecmdname = commandname;
9404 i = setjmp(jmploc.loc);
9407 savehandler = exception_handler;
9408 exception_handler = &jmploc;
9409 commandname = argv[0];
9411 optptr = NULL; /* initialize nextopt */
9412 exitstatus = (*cmd->builtin)(argc, argv);
9413 flush_stdout_stderr();
9415 exitstatus |= ferror(stdout);
9417 commandname = savecmdname;
9418 exception_handler = savehandler;
9424 goodname(const char *p)
9426 return endofname(p)[0] == '\0';
9431 * Search for a command. This is called before we fork so that the
9432 * location of the command will be available in the parent as well as
9433 * the child. The check for "goodname" is an overly conservative
9434 * check that the name will not be subject to expansion.
9437 prehash(union node *n)
9439 struct cmdentry entry;
9441 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9442 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9446 /* ============ Builtin commands
9448 * Builtin commands whose functions are closely tied to evaluation
9449 * are implemented here.
9453 * Handle break and continue commands. Break, continue, and return are
9454 * all handled by setting the evalskip flag. The evaluation routines
9455 * above all check this flag, and if it is set they start skipping
9456 * commands rather than executing them. The variable skipcount is
9457 * the number of loops to break/continue, or the number of function
9458 * levels to return. (The latter is always 1.) It should probably
9459 * be an error to break out of more loops than exist, but it isn't
9460 * in the standard shell so we don't make it one here.
9462 static int FAST_FUNC
9463 breakcmd(int argc UNUSED_PARAM, char **argv)
9465 int n = argv[1] ? number(argv[1]) : 1;
9468 ash_msg_and_raise_error(msg_illnum, argv[1]);
9472 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9479 /* ============ input.c
9481 * This implements the input routines used by the parser.
9485 INPUT_PUSH_FILE = 1,
9486 INPUT_NOFILE_OK = 2,
9489 static smallint checkkwd;
9490 /* values of checkkwd variable */
9491 #define CHKALIAS 0x1
9496 * Push a string back onto the input at this current parsefile level.
9497 * We handle aliases this way.
9499 #if !ENABLE_ASH_ALIAS
9500 #define pushstring(s, ap) pushstring(s)
9503 pushstring(char *s, struct alias *ap)
9510 if (g_parsefile->strpush) {
9511 sp = ckzalloc(sizeof(*sp));
9512 sp->prev = g_parsefile->strpush;
9514 sp = &(g_parsefile->basestrpush);
9516 g_parsefile->strpush = sp;
9517 sp->prev_string = g_parsefile->next_to_pgetc;
9518 sp->prev_left_in_line = g_parsefile->left_in_line;
9519 #if ENABLE_ASH_ALIAS
9522 ap->flag |= ALIASINUSE;
9526 g_parsefile->next_to_pgetc = s;
9527 g_parsefile->left_in_line = len;
9534 struct strpush *sp = g_parsefile->strpush;
9537 #if ENABLE_ASH_ALIAS
9539 if (g_parsefile->next_to_pgetc[-1] == ' '
9540 || g_parsefile->next_to_pgetc[-1] == '\t'
9542 checkkwd |= CHKALIAS;
9544 if (sp->string != sp->ap->val) {
9547 sp->ap->flag &= ~ALIASINUSE;
9548 if (sp->ap->flag & ALIASDEAD) {
9549 unalias(sp->ap->name);
9553 g_parsefile->next_to_pgetc = sp->prev_string;
9554 g_parsefile->left_in_line = sp->prev_left_in_line;
9555 g_parsefile->strpush = sp->prev;
9556 if (sp != &(g_parsefile->basestrpush))
9561 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9562 //it peeks whether it is &>, and then pushes back both chars.
9563 //This function needs to save last *next_to_pgetc to buf[0]
9564 //to make two pungetc() reliable. Currently,
9565 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9570 char *buf = g_parsefile->buf;
9572 g_parsefile->next_to_pgetc = buf;
9573 #if ENABLE_FEATURE_EDITING
9575 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9576 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9579 # if ENABLE_ASH_IDLE_TIMEOUT
9581 const char *tmout_var = lookupvar("TMOUT");
9583 timeout = atoi(tmout_var) * 1000;
9589 # if ENABLE_FEATURE_TAB_COMPLETION
9590 line_input_state->path_lookup = pathval();
9592 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9594 /* Ctrl+C pressed */
9605 /* Ctrl+D pressed */
9608 # if ENABLE_ASH_IDLE_TIMEOUT
9609 else if (errno == EAGAIN && timeout > 0) {
9610 printf("\007timed out waiting for input: auto-logout\n");
9617 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9620 #if 0 /* disabled: nonblock_safe_read() handles this problem */
9622 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9623 int flags = fcntl(0, F_GETFL);
9624 if (flags >= 0 && (flags & O_NONBLOCK)) {
9625 flags &= ~O_NONBLOCK;
9626 if (fcntl(0, F_SETFL, flags) >= 0) {
9627 out2str("sh: turning off NDELAY mode\n");
9638 * Refill the input buffer and return the next input character:
9640 * 1) If a string was pushed back on the input, pop it;
9641 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9642 * or we are reading from a string so we can't refill the buffer,
9644 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9645 * 4) Process input up to the next newline, deleting nul characters.
9647 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9648 #define pgetc_debug(...) ((void)0)
9655 while (g_parsefile->strpush) {
9656 #if ENABLE_ASH_ALIAS
9657 if (g_parsefile->left_in_line == -1
9658 && g_parsefile->strpush->ap
9659 && g_parsefile->next_to_pgetc[-1] != ' '
9660 && g_parsefile->next_to_pgetc[-1] != '\t'
9662 pgetc_debug("preadbuffer PEOA");
9667 /* try "pgetc" now: */
9668 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9669 g_parsefile->left_in_line,
9670 g_parsefile->next_to_pgetc,
9671 g_parsefile->next_to_pgetc);
9672 if (--g_parsefile->left_in_line >= 0)
9673 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9675 /* on both branches above g_parsefile->left_in_line < 0.
9676 * "pgetc" needs refilling.
9679 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9680 * pungetc() may increment it a few times.
9681 * Assuming it won't increment it to less than -90.
9683 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9684 pgetc_debug("preadbuffer PEOF1");
9685 /* even in failure keep left_in_line and next_to_pgetc
9686 * in lock step, for correct multi-layer pungetc.
9687 * left_in_line was decremented before preadbuffer(),
9688 * must inc next_to_pgetc: */
9689 g_parsefile->next_to_pgetc++;
9693 more = g_parsefile->left_in_buffer;
9695 flush_stdout_stderr();
9699 /* don't try reading again */
9700 g_parsefile->left_in_line = -99;
9701 pgetc_debug("preadbuffer PEOF2");
9702 g_parsefile->next_to_pgetc++;
9707 /* Find out where's the end of line.
9708 * Set g_parsefile->left_in_line
9709 * and g_parsefile->left_in_buffer acordingly.
9710 * NUL chars are deleted.
9712 q = g_parsefile->next_to_pgetc;
9720 memmove(q, q + 1, more);
9724 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9730 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9731 if (g_parsefile->left_in_line < 0)
9736 g_parsefile->left_in_buffer = more;
9741 out2str(g_parsefile->next_to_pgetc);
9745 pgetc_debug("preadbuffer at %d:%p'%s'",
9746 g_parsefile->left_in_line,
9747 g_parsefile->next_to_pgetc,
9748 g_parsefile->next_to_pgetc);
9749 return (unsigned char)*g_parsefile->next_to_pgetc++;
9752 #define pgetc_as_macro() \
9753 (--g_parsefile->left_in_line >= 0 \
9754 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9761 pgetc_debug("pgetc_fast at %d:%p'%s'",
9762 g_parsefile->left_in_line,
9763 g_parsefile->next_to_pgetc,
9764 g_parsefile->next_to_pgetc);
9765 return pgetc_as_macro();
9768 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9769 # define pgetc_fast() pgetc()
9771 # define pgetc_fast() pgetc_as_macro()
9774 #if ENABLE_ASH_ALIAS
9776 pgetc_without_PEOA(void)
9780 pgetc_debug("pgetc_fast at %d:%p'%s'",
9781 g_parsefile->left_in_line,
9782 g_parsefile->next_to_pgetc,
9783 g_parsefile->next_to_pgetc);
9785 } while (c == PEOA);
9789 # define pgetc_without_PEOA() pgetc()
9793 * Read a line from the script.
9796 pfgets(char *line, int len)
9802 while (--nleft > 0) {
9803 c = pgetc_without_PEOA();
9818 * Undo the last call to pgetc. Only one character may be pushed back.
9819 * PEOF may be pushed back.
9824 g_parsefile->left_in_line++;
9825 g_parsefile->next_to_pgetc--;
9826 pgetc_debug("pushed back to %d:%p'%s'",
9827 g_parsefile->left_in_line,
9828 g_parsefile->next_to_pgetc,
9829 g_parsefile->next_to_pgetc);
9833 * To handle the "." command, a stack of input files is used. Pushfile
9834 * adds a new entry to the stack and popfile restores the previous level.
9839 struct parsefile *pf;
9841 pf = ckzalloc(sizeof(*pf));
9842 pf->prev = g_parsefile;
9844 /*pf->strpush = NULL; - ckzalloc did it */
9845 /*pf->basestrpush.prev = NULL;*/
9852 struct parsefile *pf = g_parsefile;
9860 g_parsefile = pf->prev;
9866 * Return to top level.
9871 while (g_parsefile != &basepf)
9876 * Close the file(s) that the shell is reading commands from. Called
9877 * after a fork is done.
9883 if (g_parsefile->pf_fd > 0) {
9884 close(g_parsefile->pf_fd);
9885 g_parsefile->pf_fd = 0;
9890 * Like setinputfile, but takes an open file descriptor. Call this with
9894 setinputfd(int fd, int push)
9896 close_on_exec_on(fd);
9899 g_parsefile->buf = NULL;
9901 g_parsefile->pf_fd = fd;
9902 if (g_parsefile->buf == NULL)
9903 g_parsefile->buf = ckmalloc(IBUFSIZ);
9904 g_parsefile->left_in_buffer = 0;
9905 g_parsefile->left_in_line = 0;
9906 g_parsefile->linno = 1;
9910 * Set the input to take input from a file. If push is set, push the
9911 * old input onto the stack first.
9914 setinputfile(const char *fname, int flags)
9920 fd = open(fname, O_RDONLY);
9922 if (flags & INPUT_NOFILE_OK)
9924 ash_msg_and_raise_error("can't open '%s'", fname);
9927 fd2 = copyfd(fd, 10);
9930 ash_msg_and_raise_error("out of file descriptors");
9933 setinputfd(fd, flags & INPUT_PUSH_FILE);
9940 * Like setinputfile, but takes input from a string.
9943 setinputstring(char *string)
9947 g_parsefile->next_to_pgetc = string;
9948 g_parsefile->left_in_line = strlen(string);
9949 g_parsefile->buf = NULL;
9950 g_parsefile->linno = 1;
9955 /* ============ mail.c
9957 * Routines to check for mail.
9962 #define MAXMBOXES 10
9964 /* times of mailboxes */
9965 static time_t mailtime[MAXMBOXES];
9966 /* Set if MAIL or MAILPATH is changed. */
9967 static smallint mail_var_path_changed;
9970 * Print appropriate message(s) if mail has arrived.
9971 * If mail_var_path_changed is set,
9972 * then the value of MAIL has mail_var_path_changed,
9973 * so we just update the values.
9982 struct stackmark smark;
9985 setstackmark(&smark);
9986 mpath = mpathset() ? mpathval() : mailval();
9987 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9988 p = path_advance(&mpath, nullstr);
9993 for (q = p; *q; q++)
9999 q[-1] = '\0'; /* delete trailing '/' */
10000 if (stat(p, &statb) < 0) {
10004 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
10007 pathopt ? pathopt : "you have mail"
10010 *mtp = statb.st_mtime;
10012 mail_var_path_changed = 0;
10013 popstackmark(&smark);
10016 static void FAST_FUNC
10017 changemail(const char *val UNUSED_PARAM)
10019 mail_var_path_changed = 1;
10022 #endif /* ASH_MAIL */
10025 /* ============ ??? */
10028 * Set the shell parameters.
10031 setparam(char **argv)
10037 for (nparam = 0; argv[nparam]; nparam++)
10039 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10041 *ap++ = ckstrdup(*argv++);
10044 freeparam(&shellparam);
10045 shellparam.malloced = 1;
10046 shellparam.nparam = nparam;
10047 shellparam.p = newparam;
10048 #if ENABLE_ASH_GETOPTS
10049 shellparam.optind = 1;
10050 shellparam.optoff = -1;
10055 * Process shell options. The global variable argptr contains a pointer
10056 * to the argument list; we advance it past the options.
10058 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10059 * For a non-interactive shell, an error condition encountered
10060 * by a special built-in ... shall cause the shell to write a diagnostic message
10061 * to standard error and exit as shown in the following table:
10062 * Error Special Built-In
10064 * Utility syntax error (option or operand error) Shall exit
10066 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10067 * we see that bash does not do that (set "finishes" with error code 1 instead,
10068 * and shell continues), and people rely on this behavior!
10070 * set -o barfoo 2>/dev/null
10073 * Oh well. Let's mimic that.
10076 plus_minus_o(char *name, int val)
10081 for (i = 0; i < NOPTS; i++) {
10082 if (strcmp(name, optnames(i)) == 0) {
10087 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10090 for (i = 0; i < NOPTS; i++) {
10092 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10094 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10100 setoption(int flag, int val)
10104 for (i = 0; i < NOPTS; i++) {
10105 if (optletters(i) == flag) {
10110 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10114 options(int cmdline)
10122 while ((p = *argptr) != NULL) {
10124 if (c != '-' && c != '+')
10127 val = 0; /* val = 0 if c == '+' */
10130 if (p[0] == '\0' || LONE_DASH(p)) {
10132 /* "-" means turn off -x and -v */
10135 /* "--" means reset params */
10136 else if (*argptr == NULL)
10139 break; /* "-" or "--" terminates options */
10142 /* first char was + or - */
10143 while ((c = *p++) != '\0') {
10144 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10145 if (c == 'c' && cmdline) {
10146 minusc = p; /* command is after shell args */
10147 } else if (c == 'o') {
10148 if (plus_minus_o(*argptr, val)) {
10149 /* it already printed err message */
10150 return 1; /* error */
10154 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10156 /* bash does not accept +-login, we also won't */
10157 } else if (cmdline && val && (c == '-')) { /* long options */
10158 if (strcmp(p, "login") == 0)
10170 * The shift builtin command.
10172 static int FAST_FUNC
10173 shiftcmd(int argc UNUSED_PARAM, char **argv)
10180 n = number(argv[1]);
10181 if (n > shellparam.nparam)
10182 n = 0; /* bash compat, was = shellparam.nparam; */
10184 shellparam.nparam -= n;
10185 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10186 if (shellparam.malloced)
10189 ap2 = shellparam.p;
10190 while ((*ap2++ = *ap1++) != NULL)
10192 #if ENABLE_ASH_GETOPTS
10193 shellparam.optind = 1;
10194 shellparam.optoff = -1;
10201 * POSIX requires that 'set' (but not export or readonly) output the
10202 * variables in lexicographic order - by the locale's collating order (sigh).
10203 * Maybe we could keep them in an ordered balanced binary tree
10204 * instead of hashed lists.
10205 * For now just roll 'em through qsort for printing...
10208 showvars(const char *sep_prefix, int on, int off)
10211 char **ep, **epend;
10213 ep = listvars(on, off, &epend);
10214 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10216 sep = *sep_prefix ? " " : sep_prefix;
10218 for (; ep < epend; ep++) {
10222 p = strchrnul(*ep, '=');
10225 q = single_quote(++p);
10226 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10232 * The set command builtin.
10234 static int FAST_FUNC
10235 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10240 return showvars(nullstr, 0, VUNSET);
10243 if (!options(0)) { /* if no parse error... */
10246 if (*argptr != NULL) {
10254 #if ENABLE_ASH_RANDOM_SUPPORT
10255 static void FAST_FUNC
10256 change_random(const char *value)
10260 if (value == NULL) {
10261 /* "get", generate */
10262 t = next_random(&random_gen);
10263 /* set without recursion */
10264 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10265 vrandom.flags &= ~VNOFUNC;
10268 t = strtoul(value, NULL, 10);
10269 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10274 #if ENABLE_ASH_GETOPTS
10276 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10285 if (*param_optind < 1)
10287 optnext = optfirst + *param_optind - 1;
10289 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10292 p = optnext[-1] + *optoff;
10293 if (p == NULL || *p == '\0') {
10294 /* Current word is done, advance */
10296 if (p == NULL || *p != '-' || *++p == '\0') {
10303 if (LONE_DASH(p)) /* check for "--" */
10308 for (q = optstr; *q != c;) {
10310 if (optstr[0] == ':') {
10313 err |= setvarsafe("OPTARG", s, 0);
10315 fprintf(stderr, "Illegal option -%c\n", c);
10316 unsetvar("OPTARG");
10326 if (*p == '\0' && (p = *optnext) == NULL) {
10327 if (optstr[0] == ':') {
10330 err |= setvarsafe("OPTARG", s, 0);
10333 fprintf(stderr, "No arg for -%c option\n", c);
10334 unsetvar("OPTARG");
10342 err |= setvarsafe("OPTARG", p, 0);
10345 err |= setvarsafe("OPTARG", nullstr, 0);
10347 *optoff = p ? p - *(optnext - 1) : -1;
10348 *param_optind = optnext - optfirst + 1;
10349 fmtstr(s, sizeof(s), "%d", *param_optind);
10350 err |= setvarsafe("OPTIND", s, VNOFUNC);
10353 err |= setvarsafe(optvar, s, 0);
10357 flush_stdout_stderr();
10358 raise_exception(EXERROR);
10364 * The getopts builtin. Shellparam.optnext points to the next argument
10365 * to be processed. Shellparam.optptr points to the next character to
10366 * be processed in the current argument. If shellparam.optnext is NULL,
10367 * then it's the first time getopts has been called.
10369 static int FAST_FUNC
10370 getoptscmd(int argc, char **argv)
10375 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10377 optbase = shellparam.p;
10378 if (shellparam.optind > shellparam.nparam + 1) {
10379 shellparam.optind = 1;
10380 shellparam.optoff = -1;
10383 optbase = &argv[3];
10384 if (shellparam.optind > argc - 2) {
10385 shellparam.optind = 1;
10386 shellparam.optoff = -1;
10390 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10391 &shellparam.optoff);
10393 #endif /* ASH_GETOPTS */
10396 /* ============ Shell parser */
10399 struct heredoc *next; /* next here document in list */
10400 union node *here; /* redirection node */
10401 char *eofmark; /* string indicating end of input */
10402 smallint striptabs; /* if set, strip leading tabs */
10405 static smallint tokpushback; /* last token pushed back */
10406 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10407 static smallint quoteflag; /* set if (part of) last token was quoted */
10408 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10409 static struct heredoc *heredoclist; /* list of here documents to read */
10410 static char *wordtext; /* text of last word returned by readtoken */
10411 static struct nodelist *backquotelist;
10412 static union node *redirnode;
10413 static struct heredoc *heredoc;
10415 static const char *
10416 tokname(char *buf, int tok)
10419 return tokname_array[tok] + 1;
10420 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10424 /* raise_error_unexpected_syntax:
10425 * Called when an unexpected token is read during the parse. The argument
10426 * is the token that is expected, or -1 if more than one type of token can
10427 * occur at this point.
10429 static void raise_error_unexpected_syntax(int) NORETURN;
10431 raise_error_unexpected_syntax(int token)
10437 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10439 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10440 raise_error_syntax(msg);
10444 #define EOFMARKLEN 79
10446 /* parsing is heavily cross-recursive, need these forward decls */
10447 static union node *andor(void);
10448 static union node *pipeline(void);
10449 static union node *parse_command(void);
10450 static void parseheredoc(void);
10451 static char peektoken(void);
10452 static int readtoken(void);
10454 static union node *
10457 union node *n1, *n2, *n3;
10460 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10461 if (nlflag == 2 && peektoken())
10467 if (tok == TBACKGND) {
10468 if (n2->type == NPIPE) {
10469 n2->npipe.pipe_backgnd = 1;
10471 if (n2->type != NREDIR) {
10472 n3 = stzalloc(sizeof(struct nredir));
10474 /*n3->nredir.redirect = NULL; - stzalloc did it */
10477 n2->type = NBACKGND;
10483 n3 = stzalloc(sizeof(struct nbinary));
10485 n3->nbinary.ch1 = n1;
10486 n3->nbinary.ch2 = n2;
10502 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10510 pungetc(); /* push back EOF on input */
10514 raise_error_unexpected_syntax(-1);
10521 static union node *
10524 union node *n1, *n2, *n3;
10532 } else if (t == TOR) {
10538 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10540 n3 = stzalloc(sizeof(struct nbinary));
10542 n3->nbinary.ch1 = n1;
10543 n3->nbinary.ch2 = n2;
10548 static union node *
10551 union node *n1, *n2, *pipenode;
10552 struct nodelist *lp, *prev;
10556 TRACE(("pipeline: entered\n"));
10557 if (readtoken() == TNOT) {
10559 checkkwd = CHKKWD | CHKALIAS;
10562 n1 = parse_command();
10563 if (readtoken() == TPIPE) {
10564 pipenode = stzalloc(sizeof(struct npipe));
10565 pipenode->type = NPIPE;
10566 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10567 lp = stzalloc(sizeof(struct nodelist));
10568 pipenode->npipe.cmdlist = lp;
10572 lp = stzalloc(sizeof(struct nodelist));
10573 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10574 lp->n = parse_command();
10576 } while (readtoken() == TPIPE);
10582 n2 = stzalloc(sizeof(struct nnot));
10590 static union node *
10595 n = stzalloc(sizeof(struct narg));
10597 /*n->narg.next = NULL; - stzalloc did it */
10598 n->narg.text = wordtext;
10599 n->narg.backquote = backquotelist;
10604 fixredir(union node *n, const char *text, int err)
10608 TRACE(("Fix redir %s %d\n", text, err));
10610 n->ndup.vname = NULL;
10612 fd = bb_strtou(text, NULL, 10);
10613 if (!errno && fd >= 0)
10614 n->ndup.dupfd = fd;
10615 else if (LONE_DASH(text))
10616 n->ndup.dupfd = -1;
10619 raise_error_syntax("bad fd number");
10620 n->ndup.vname = makename();
10625 * Returns true if the text contains nothing to expand (no dollar signs
10629 noexpand(const char *text)
10633 while ((c = *text++) != '\0') {
10634 if (c == CTLQUOTEMARK)
10638 else if (SIT(c, BASESYNTAX) == CCTL)
10647 union node *n = redirnode;
10649 if (readtoken() != TWORD)
10650 raise_error_unexpected_syntax(-1);
10651 if (n->type == NHERE) {
10652 struct heredoc *here = heredoc;
10656 if (quoteflag == 0)
10658 TRACE(("Here document %d\n", n->type));
10659 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10660 raise_error_syntax("illegal eof marker for << redirection");
10661 rmescapes(wordtext, 0);
10662 here->eofmark = wordtext;
10664 if (heredoclist == NULL)
10665 heredoclist = here;
10667 for (p = heredoclist; p->next; p = p->next)
10671 } else if (n->type == NTOFD || n->type == NFROMFD) {
10672 fixredir(n, wordtext, 0);
10674 n->nfile.fname = makename();
10678 static union node *
10681 union node *args, **app;
10682 union node *n = NULL;
10683 union node *vars, **vpp;
10684 union node **rpp, *redir;
10686 #if ENABLE_ASH_BASH_COMPAT
10687 smallint double_brackets_flag = 0;
10697 savecheckkwd = CHKALIAS;
10700 checkkwd = savecheckkwd;
10703 #if ENABLE_ASH_BASH_COMPAT
10704 case TAND: /* "&&" */
10705 case TOR: /* "||" */
10706 if (!double_brackets_flag) {
10710 wordtext = (char *) (t == TAND ? "-a" : "-o");
10713 n = stzalloc(sizeof(struct narg));
10715 /*n->narg.next = NULL; - stzalloc did it */
10716 n->narg.text = wordtext;
10717 #if ENABLE_ASH_BASH_COMPAT
10718 if (strcmp("[[", wordtext) == 0)
10719 double_brackets_flag = 1;
10720 else if (strcmp("]]", wordtext) == 0)
10721 double_brackets_flag = 0;
10723 n->narg.backquote = backquotelist;
10724 if (savecheckkwd && isassignment(wordtext)) {
10726 vpp = &n->narg.next;
10729 app = &n->narg.next;
10734 *rpp = n = redirnode;
10735 rpp = &n->nfile.next;
10736 parsefname(); /* read name of redirection file */
10739 if (args && app == &args->narg.next
10742 struct builtincmd *bcmd;
10745 /* We have a function */
10746 if (readtoken() != TRP)
10747 raise_error_unexpected_syntax(TRP);
10748 name = n->narg.text;
10749 if (!goodname(name)
10750 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10752 raise_error_syntax("bad function name");
10755 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10756 n->narg.next = parse_command();
10769 n = stzalloc(sizeof(struct ncmd));
10771 n->ncmd.args = args;
10772 n->ncmd.assign = vars;
10773 n->ncmd.redirect = redir;
10777 static union node *
10778 parse_command(void)
10780 union node *n1, *n2;
10781 union node *ap, **app;
10782 union node *cp, **cpp;
10783 union node *redir, **rpp;
10790 switch (readtoken()) {
10792 raise_error_unexpected_syntax(-1);
10795 n1 = stzalloc(sizeof(struct nif));
10797 n1->nif.test = list(0);
10798 if (readtoken() != TTHEN)
10799 raise_error_unexpected_syntax(TTHEN);
10800 n1->nif.ifpart = list(0);
10802 while (readtoken() == TELIF) {
10803 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10804 n2 = n2->nif.elsepart;
10806 n2->nif.test = list(0);
10807 if (readtoken() != TTHEN)
10808 raise_error_unexpected_syntax(TTHEN);
10809 n2->nif.ifpart = list(0);
10811 if (lasttoken == TELSE)
10812 n2->nif.elsepart = list(0);
10814 n2->nif.elsepart = NULL;
10822 n1 = stzalloc(sizeof(struct nbinary));
10823 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10824 n1->nbinary.ch1 = list(0);
10827 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10828 got == TWORD ? wordtext : ""));
10829 raise_error_unexpected_syntax(TDO);
10831 n1->nbinary.ch2 = list(0);
10836 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10837 raise_error_syntax("bad for loop variable");
10838 n1 = stzalloc(sizeof(struct nfor));
10840 n1->nfor.var = wordtext;
10841 checkkwd = CHKKWD | CHKALIAS;
10842 if (readtoken() == TIN) {
10844 while (readtoken() == TWORD) {
10845 n2 = stzalloc(sizeof(struct narg));
10847 /*n2->narg.next = NULL; - stzalloc did it */
10848 n2->narg.text = wordtext;
10849 n2->narg.backquote = backquotelist;
10851 app = &n2->narg.next;
10854 n1->nfor.args = ap;
10855 if (lasttoken != TNL && lasttoken != TSEMI)
10856 raise_error_unexpected_syntax(-1);
10858 n2 = stzalloc(sizeof(struct narg));
10860 /*n2->narg.next = NULL; - stzalloc did it */
10861 n2->narg.text = (char *)dolatstr;
10862 /*n2->narg.backquote = NULL;*/
10863 n1->nfor.args = n2;
10865 * Newline or semicolon here is optional (but note
10866 * that the original Bourne shell only allowed NL).
10868 if (lasttoken != TNL && lasttoken != TSEMI)
10871 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10872 if (readtoken() != TDO)
10873 raise_error_unexpected_syntax(TDO);
10874 n1->nfor.body = list(0);
10878 n1 = stzalloc(sizeof(struct ncase));
10880 if (readtoken() != TWORD)
10881 raise_error_unexpected_syntax(TWORD);
10882 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10884 /*n2->narg.next = NULL; - stzalloc did it */
10885 n2->narg.text = wordtext;
10886 n2->narg.backquote = backquotelist;
10888 checkkwd = CHKKWD | CHKALIAS;
10889 } while (readtoken() == TNL);
10890 if (lasttoken != TIN)
10891 raise_error_unexpected_syntax(TIN);
10892 cpp = &n1->ncase.cases;
10894 checkkwd = CHKNL | CHKKWD;
10896 while (t != TESAC) {
10897 if (lasttoken == TLP)
10899 *cpp = cp = stzalloc(sizeof(struct nclist));
10901 app = &cp->nclist.pattern;
10903 *app = ap = stzalloc(sizeof(struct narg));
10905 /*ap->narg.next = NULL; - stzalloc did it */
10906 ap->narg.text = wordtext;
10907 ap->narg.backquote = backquotelist;
10908 if (readtoken() != TPIPE)
10910 app = &ap->narg.next;
10913 //ap->narg.next = NULL;
10914 if (lasttoken != TRP)
10915 raise_error_unexpected_syntax(TRP);
10916 cp->nclist.body = list(2);
10918 cpp = &cp->nclist.next;
10920 checkkwd = CHKNL | CHKKWD;
10924 raise_error_unexpected_syntax(TENDCASE);
10931 n1 = stzalloc(sizeof(struct nredir));
10932 n1->type = NSUBSHELL;
10933 n1->nredir.n = list(0);
10934 /*n1->nredir.redirect = NULL; - stzalloc did it */
10944 return simplecmd();
10947 if (readtoken() != t)
10948 raise_error_unexpected_syntax(t);
10951 /* Now check for redirection which may follow command */
10952 checkkwd = CHKKWD | CHKALIAS;
10954 while (readtoken() == TREDIR) {
10955 *rpp = n2 = redirnode;
10956 rpp = &n2->nfile.next;
10962 if (n1->type != NSUBSHELL) {
10963 n2 = stzalloc(sizeof(struct nredir));
10968 n1->nredir.redirect = redir;
10973 #if ENABLE_ASH_BASH_COMPAT
10974 static int decode_dollar_squote(void)
10976 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10982 p = strchr(C_escapes, c);
10987 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10991 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10993 } else if (c == 'x') { /* \xHH */
10997 } while (isxdigit(c) && --cnt);
10999 if (cnt == 3) { /* \x but next char is "bad" */
11003 } else { /* simple seq like \\ or \t */
11008 c = bb_process_escape_sequence((void*)&p);
11009 } else { /* unrecognized "\z": print both chars unless ' or " */
11010 if (c != '\'' && c != '"') {
11012 c |= 0x100; /* "please encode \, then me" */
11020 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11021 * is not NULL, read a here document. In the latter case, eofmark is the
11022 * word which marks the end of the document and striptabs is true if
11023 * leading tabs should be stripped from the document. The argument c
11024 * is the first character of the input token or document.
11026 * Because C does not have internal subroutines, I have simulated them
11027 * using goto's to implement the subroutine linkage. The following macros
11028 * will run code that appears at the end of readtoken1.
11030 #define CHECKEND() {goto checkend; checkend_return:;}
11031 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11032 #define PARSESUB() {goto parsesub; parsesub_return:;}
11033 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11034 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11035 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11037 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11039 /* NB: syntax parameter fits into smallint */
11040 /* c parameter is an unsigned char or PEOF or PEOA */
11043 char line[EOFMARKLEN + 1];
11044 struct nodelist *bqlist;
11048 smallint prevsyntax; /* syntax before arithmetic */
11049 #if ENABLE_ASH_EXPAND_PRMT
11050 smallint pssyntax; /* we are expanding a prompt string */
11052 int varnest; /* levels of variables expansion */
11053 int arinest; /* levels of arithmetic expansion */
11054 int parenlevel; /* levels of parens in arithmetic */
11055 int dqvarnest; /* levels of variables expansion within double quotes */
11057 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11060 /* Avoid longjmp clobbering */
11066 (void) &parenlevel;
11069 (void) &prevsyntax;
11072 startlinno = g_parsefile->linno;
11076 #if ENABLE_ASH_EXPAND_PRMT
11077 pssyntax = (syntax == PSSYNTAX);
11081 dblquote = (syntax == DQSYNTAX);
11087 STARTSTACKSTR(out);
11089 /* For each line, until end of word */
11090 CHECKEND(); /* set c to PEOF if at end of here document */
11091 for (;;) { /* until end of line or end of word */
11092 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11093 switch (SIT(c, syntax)) {
11094 case CNL: /* '\n' */
11095 if (syntax == BASESYNTAX)
11096 goto endword; /* exit outer loop */
11098 g_parsefile->linno++;
11099 setprompt_if(doprompt, 2);
11101 goto loop; /* continue outer loop */
11106 if (eofmark == NULL || dblquote)
11107 USTPUTC(CTLESC, out);
11108 #if ENABLE_ASH_BASH_COMPAT
11109 if (c == '\\' && bash_dollar_squote) {
11110 c = decode_dollar_squote();
11112 USTPUTC('\\', out);
11113 c = (unsigned char)c;
11119 case CBACK: /* backslash */
11120 c = pgetc_without_PEOA();
11122 USTPUTC(CTLESC, out);
11123 USTPUTC('\\', out);
11125 } else if (c == '\n') {
11126 setprompt_if(doprompt, 2);
11128 #if ENABLE_ASH_EXPAND_PRMT
11129 if (c == '$' && pssyntax) {
11130 USTPUTC(CTLESC, out);
11131 USTPUTC('\\', out);
11134 /* Backslash is retained if we are in "str" and next char isn't special */
11139 && (c != '"' || eofmark != NULL)
11141 USTPUTC(CTLESC, out);
11142 USTPUTC('\\', out);
11144 if (SIT(c, SQSYNTAX) == CCTL)
11145 USTPUTC(CTLESC, out);
11153 if (eofmark == NULL) {
11154 USTPUTC(CTLQUOTEMARK, out);
11162 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11163 if (eofmark != NULL && arinest == 0
11168 if (dqvarnest == 0) {
11169 syntax = BASESYNTAX;
11176 case CVAR: /* '$' */
11177 PARSESUB(); /* parse substitution */
11179 case CENDVAR: /* '}' */
11182 if (dqvarnest > 0) {
11189 #if ENABLE_SH_MATH_SUPPORT
11190 case CLP: /* '(' in arithmetic */
11194 case CRP: /* ')' in arithmetic */
11195 if (parenlevel > 0) {
11198 if (pgetc() == ')') {
11199 if (--arinest == 0) {
11200 syntax = prevsyntax;
11201 dblquote = (syntax == DQSYNTAX);
11206 * unbalanced parens
11207 * (don't 2nd guess - no error)
11215 case CBQUOTE: /* '`' */
11219 goto endword; /* exit outer loop */
11223 if (varnest == 0) {
11224 #if ENABLE_ASH_BASH_COMPAT
11226 if (pgetc() == '>')
11227 c = 0x100 + '>'; /* flag &> */
11231 goto endword; /* exit outer loop */
11233 IF_ASH_ALIAS(if (c != PEOA))
11240 #if ENABLE_SH_MATH_SUPPORT
11241 if (syntax == ARISYNTAX)
11242 raise_error_syntax("missing '))'");
11244 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11245 raise_error_syntax("unterminated quoted string");
11246 if (varnest != 0) {
11247 startlinno = g_parsefile->linno;
11249 raise_error_syntax("missing '}'");
11251 USTPUTC('\0', out);
11252 len = out - (char *)stackblock();
11253 out = stackblock();
11254 if (eofmark == NULL) {
11255 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11258 if (isdigit_str9(out)) {
11259 PARSEREDIR(); /* passed as params: out, c */
11260 lasttoken = TREDIR;
11263 /* else: non-number X seen, interpret it
11264 * as "NNNX>file" = "NNNX >file" */
11268 quoteflag = quotef;
11269 backquotelist = bqlist;
11270 grabstackblock(len);
11274 /* end of readtoken routine */
11277 * Check to see whether we are at the end of the here document. When this
11278 * is called, c is set to the first character of the next input line. If
11279 * we are at the end of the here document, this routine sets the c to PEOF.
11283 #if ENABLE_ASH_ALIAS
11285 c = pgetc_without_PEOA();
11288 while (c == '\t') {
11289 c = pgetc_without_PEOA();
11292 if (c == *eofmark) {
11293 if (pfgets(line, sizeof(line)) != NULL) {
11297 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11299 if (*p == '\n' && *q == '\0') {
11301 g_parsefile->linno++;
11302 needprompt = doprompt;
11304 pushstring(line, NULL);
11309 goto checkend_return;
11313 * Parse a redirection operator. The variable "out" points to a string
11314 * specifying the fd to be redirected. The variable "c" contains the
11315 * first character of the redirection operator.
11318 /* out is already checked to be a valid number or "" */
11319 int fd = (*out == '\0' ? -1 : atoi(out));
11322 np = stzalloc(sizeof(struct nfile));
11327 np->type = NAPPEND;
11329 np->type = NCLOBBER;
11332 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11338 #if ENABLE_ASH_BASH_COMPAT
11339 else if (c == 0x100 + '>') { /* this flags &> redirection */
11341 pgetc(); /* this is '>', no need to check */
11345 else { /* c == '<' */
11346 /*np->nfile.fd = 0; - stzalloc did it */
11350 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11351 np = stzalloc(sizeof(struct nhere));
11352 /*np->nfile.fd = 0; - stzalloc did it */
11355 heredoc = stzalloc(sizeof(struct heredoc));
11356 heredoc->here = np;
11359 heredoc->striptabs = 1;
11361 /*heredoc->striptabs = 0; - stzalloc did it */
11367 np->type = NFROMFD;
11371 np->type = NFROMTO;
11383 goto parseredir_return;
11387 * Parse a substitution. At this point, we have read the dollar sign
11388 * and nothing else.
11391 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11392 * (assuming ascii char codes, as the original implementation did) */
11393 #define is_special(c) \
11394 (((unsigned)(c) - 33 < 32) \
11395 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11397 unsigned char subtype;
11402 if (c > 255 /* PEOA or PEOF */
11403 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11405 #if ENABLE_ASH_BASH_COMPAT
11407 bash_dollar_squote = 1;
11412 } else if (c == '(') {
11413 /* $(command) or $((arith)) */
11414 if (pgetc() == '(') {
11415 #if ENABLE_SH_MATH_SUPPORT
11418 raise_error_syntax("you disabled math support for $((arith)) syntax");
11425 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11426 USTPUTC(CTLVAR, out);
11427 typeloc = out - (char *)stackblock();
11428 USTPUTC(VSNORMAL, out);
11429 subtype = VSNORMAL;
11435 c = '#'; /* ${#} - same as $# */
11437 subtype = VSLENGTH; /* ${#VAR} */
11442 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11443 /* $[{[#]]NAME[}] */
11447 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11448 } else if (isdigit(c)) {
11449 /* $[{[#]]NUM[}] */
11453 } while (isdigit(c));
11454 } else if (is_special(c)) {
11455 /* $[{[#]]<specialchar>[}] */
11460 raise_error_syntax("bad substitution");
11462 if (c != '}' && subtype == VSLENGTH) {
11463 /* ${#VAR didn't end with } */
11469 if (subtype == 0) {
11470 /* ${VAR...} but not $VAR or ${#VAR} */
11471 /* c == first char after VAR */
11475 #if ENABLE_ASH_BASH_COMPAT
11476 if (c == ':' || c == '$' || isdigit(c)) {
11477 //TODO: support more general format ${v:EXPR:EXPR},
11478 // where EXPR follows $(()) rules
11479 subtype = VSSUBSTR;
11481 break; /* "goto do_pungetc" is bigger (!) */
11487 static const char types[] ALIGN1 = "}-+?=";
11488 const char *p = strchr(types, c);
11491 subtype = p - types + VSNORMAL;
11497 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11504 #if ENABLE_ASH_BASH_COMPAT
11506 /* ${v/[/]pattern/repl} */
11507 //TODO: encode pattern and repl separately.
11508 // Currently ${v/$var_with_slash/repl} is horribly broken
11509 subtype = VSREPLACE;
11513 subtype++; /* VSREPLACEALL */
11521 if (dblquote || arinest)
11523 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11524 if (subtype != VSNORMAL) {
11526 if (dblquote || arinest) {
11531 goto parsesub_return;
11535 * Called to parse command substitutions. Newstyle is set if the command
11536 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11537 * list of commands (passed by reference), and savelen is the number of
11538 * characters on the top of the stack which must be preserved.
11541 struct nodelist **nlpp;
11544 char *volatile str;
11545 struct jmploc jmploc;
11546 struct jmploc *volatile savehandler;
11548 smallint saveprompt = 0;
11551 (void) &saveprompt;
11553 savepbq = parsebackquote;
11554 if (setjmp(jmploc.loc)) {
11556 parsebackquote = 0;
11557 exception_handler = savehandler;
11558 longjmp(exception_handler->loc, 1);
11562 savelen = out - (char *)stackblock();
11564 str = ckmalloc(savelen);
11565 memcpy(str, stackblock(), savelen);
11567 savehandler = exception_handler;
11568 exception_handler = &jmploc;
11571 /* We must read until the closing backquote, giving special
11572 treatment to some slashes, and then push the string and
11573 reread it as input, interpreting it normally. */
11578 STARTSTACKSTR(pout);
11582 setprompt_if(needprompt, 2);
11591 g_parsefile->linno++;
11592 setprompt_if(doprompt, 2);
11594 * If eating a newline, avoid putting
11595 * the newline into the new character
11596 * stream (via the STPUTC after the
11601 if (pc != '\\' && pc != '`' && pc != '$'
11602 && (!dblquote || pc != '"')
11604 STPUTC('\\', pout);
11606 if (pc <= 255 /* not PEOA or PEOF */) {
11612 IF_ASH_ALIAS(case PEOA:)
11613 startlinno = g_parsefile->linno;
11614 raise_error_syntax("EOF in backquote substitution");
11617 g_parsefile->linno++;
11618 needprompt = doprompt;
11627 STPUTC('\0', pout);
11628 psavelen = pout - (char *)stackblock();
11629 if (psavelen > 0) {
11630 pstr = grabstackstr(pout);
11631 setinputstring(pstr);
11636 nlpp = &(*nlpp)->next;
11637 *nlpp = stzalloc(sizeof(**nlpp));
11638 /* (*nlpp)->next = NULL; - stzalloc did it */
11639 parsebackquote = oldstyle;
11642 saveprompt = doprompt;
11649 doprompt = saveprompt;
11650 else if (readtoken() != TRP)
11651 raise_error_unexpected_syntax(TRP);
11656 * Start reading from old file again, ignoring any pushed back
11657 * tokens left from the backquote parsing
11662 while (stackblocksize() <= savelen)
11664 STARTSTACKSTR(out);
11666 memcpy(out, str, savelen);
11667 STADJUST(savelen, out);
11673 parsebackquote = savepbq;
11674 exception_handler = savehandler;
11675 if (arinest || dblquote)
11676 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11678 USTPUTC(CTLBACKQ, out);
11680 goto parsebackq_oldreturn;
11681 goto parsebackq_newreturn;
11684 #if ENABLE_SH_MATH_SUPPORT
11686 * Parse an arithmetic expansion (indicate start of one and set state)
11689 if (++arinest == 1) {
11690 prevsyntax = syntax;
11691 syntax = ARISYNTAX;
11692 USTPUTC(CTLARI, out);
11699 * we collapse embedded arithmetic expansion to
11700 * parenthesis, which should be equivalent
11704 goto parsearith_return;
11708 } /* end of readtoken */
11711 * Read the next input token.
11712 * If the token is a word, we set backquotelist to the list of cmds in
11713 * backquotes. We set quoteflag to true if any part of the word was
11715 * If the token is TREDIR, then we set redirnode to a structure containing
11717 * In all cases, the variable startlinno is set to the number of the line
11718 * on which the token starts.
11720 * [Change comment: here documents and internal procedures]
11721 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11722 * word parsing code into a separate routine. In this case, readtoken
11723 * doesn't need to have any internal procedures, but parseword does.
11724 * We could also make parseoperator in essence the main routine, and
11725 * have parseword (readtoken1?) handle both words and redirection.]
11727 #define NEW_xxreadtoken
11728 #ifdef NEW_xxreadtoken
11729 /* singles must be first! */
11730 static const char xxreadtoken_chars[7] ALIGN1 = {
11731 '\n', '(', ')', /* singles */
11732 '&', '|', ';', /* doubles */
11736 #define xxreadtoken_singles 3
11737 #define xxreadtoken_doubles 3
11739 static const char xxreadtoken_tokens[] ALIGN1 = {
11740 TNL, TLP, TRP, /* only single occurrence allowed */
11741 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11742 TEOF, /* corresponds to trailing nul */
11743 TAND, TOR, TENDCASE /* if double occurrence */
11755 setprompt_if(needprompt, 2);
11756 startlinno = g_parsefile->linno;
11757 for (;;) { /* until token or start of word found */
11759 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11763 while ((c = pgetc()) != '\n' && c != PEOF)
11766 } else if (c == '\\') {
11767 if (pgetc() != '\n') {
11769 break; /* return readtoken1(...) */
11771 startlinno = ++g_parsefile->linno;
11772 setprompt_if(doprompt, 2);
11776 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11779 g_parsefile->linno++;
11780 needprompt = doprompt;
11783 p = strchr(xxreadtoken_chars, c);
11785 break; /* return readtoken1(...) */
11787 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11789 if (cc == c) { /* double occurrence? */
11790 p += xxreadtoken_doubles + 1;
11793 #if ENABLE_ASH_BASH_COMPAT
11794 if (c == '&' && cc == '>') /* &> */
11795 break; /* return readtoken1(...) */
11800 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11805 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11807 #else /* old xxreadtoken */
11808 #define RETURN(token) return lasttoken = token
11818 setprompt_if(needprompt, 2);
11819 startlinno = g_parsefile->linno;
11820 for (;;) { /* until token or start of word found */
11823 case ' ': case '\t':
11824 IF_ASH_ALIAS(case PEOA:)
11827 while ((c = pgetc()) != '\n' && c != PEOF)
11832 if (pgetc() == '\n') {
11833 startlinno = ++g_parsefile->linno;
11834 setprompt_if(doprompt, 2);
11840 g_parsefile->linno++;
11841 needprompt = doprompt;
11846 if (pgetc() == '&')
11851 if (pgetc() == '|')
11856 if (pgetc() == ';')
11869 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11872 #endif /* old xxreadtoken */
11879 smallint alreadyseen = tokpushback;
11882 #if ENABLE_ASH_ALIAS
11891 if (checkkwd & CHKNL) {
11898 if (t != TWORD || quoteflag) {
11903 * check for keywords
11905 if (checkkwd & CHKKWD) {
11906 const char *const *pp;
11908 pp = findkwd(wordtext);
11910 lasttoken = t = pp - tokname_array;
11911 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11916 if (checkkwd & CHKALIAS) {
11917 #if ENABLE_ASH_ALIAS
11919 ap = lookupalias(wordtext, 1);
11922 pushstring(ap->val, ap);
11932 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11934 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11946 return tokname_array[t][0];
11950 * Read and parse a command. Returns NODE_EOF on end of file.
11951 * (NULL is a valid parse tree indicating a blank line.)
11953 static union node *
11954 parsecmd(int interact)
11959 doprompt = interact;
11960 setprompt_if(doprompt, doprompt);
11972 * Input any here documents.
11977 struct heredoc *here;
11980 here = heredoclist;
11981 heredoclist = NULL;
11984 setprompt_if(needprompt, 2);
11985 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
11986 here->eofmark, here->striptabs);
11987 n = stzalloc(sizeof(struct narg));
11988 n->narg.type = NARG;
11989 /*n->narg.next = NULL; - stzalloc did it */
11990 n->narg.text = wordtext;
11991 n->narg.backquote = backquotelist;
11992 here->here->nhere.doc = n;
11999 * called by editline -- any expansions to the prompt should be added here.
12001 #if ENABLE_ASH_EXPAND_PRMT
12002 static const char *
12003 expandstr(const char *ps)
12007 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12008 * and token processing _can_ alter it (delete NULs etc). */
12009 setinputstring((char *)ps);
12010 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12013 n.narg.type = NARG;
12014 n.narg.next = NULL;
12015 n.narg.text = wordtext;
12016 n.narg.backquote = backquotelist;
12018 expandarg(&n, NULL, 0);
12019 return stackblock();
12024 * Execute a command or commands contained in a string.
12027 evalstring(char *s, int mask)
12030 struct stackmark smark;
12034 setstackmark(&smark);
12037 while ((n = parsecmd(0)) != NODE_EOF) {
12039 popstackmark(&smark);
12052 * The eval command.
12054 static int FAST_FUNC
12055 evalcmd(int argc UNUSED_PARAM, char **argv)
12064 STARTSTACKSTR(concat);
12066 concat = stack_putstr(p, concat);
12070 STPUTC(' ', concat);
12072 STPUTC('\0', concat);
12073 p = grabstackstr(concat);
12075 evalstring(p, ~SKIPEVAL);
12081 * Read and execute commands.
12082 * "Top" is nonzero for the top level command loop;
12083 * it turns on prompting if the shell is interactive.
12089 struct stackmark smark;
12093 TRACE(("cmdloop(%d) called\n", top));
12097 setstackmark(&smark);
12100 showjobs(stderr, SHOW_CHANGED);
12103 if (iflag && top) {
12107 n = parsecmd(inter);
12109 if (DEBUG > 2 && debug && (n != NODE_EOF))
12112 if (n == NODE_EOF) {
12113 if (!top || numeof >= 50)
12115 if (!stoppedjobs()) {
12118 out2str("\nUse \"exit\" to leave shell.\n");
12121 } else if (nflag == 0) {
12122 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12127 popstackmark(&smark);
12132 return skip & SKIPEVAL;
12139 * Take commands from a file. To be compatible we should do a path
12140 * search for the file, which is necessary to find sub-commands.
12143 find_dot_file(char *name)
12146 const char *path = pathval();
12149 /* don't try this for absolute or relative paths */
12150 if (strchr(name, '/'))
12153 /* IIRC standards do not say whether . is to be searched.
12154 * And it is even smaller this way, making it unconditional for now:
12156 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12161 while ((fullname = path_advance(&path, name)) != NULL) {
12163 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12165 * Don't bother freeing here, since it will
12166 * be freed by the caller.
12170 if (fullname != name)
12171 stunalloc(fullname);
12174 /* not found in the PATH */
12175 ash_msg_and_raise_error("%s: not found", name);
12179 static int FAST_FUNC
12180 dotcmd(int argc, char **argv)
12183 struct strlist *sp;
12184 volatile struct shparam saveparam;
12186 for (sp = cmdenviron; sp; sp = sp->next)
12187 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12190 /* bash says: "bash: .: filename argument required" */
12191 return 2; /* bash compat */
12194 /* "false; . empty_file; echo $?" should print 0, not 1: */
12197 fullname = find_dot_file(argv[1]);
12201 if (argc) { /* argc > 0, argv[0] != NULL */
12202 saveparam = shellparam;
12203 shellparam.malloced = 0;
12204 shellparam.nparam = argc;
12205 shellparam.p = argv;
12208 setinputfile(fullname, INPUT_PUSH_FILE);
12209 commandname = fullname;
12214 freeparam(&shellparam);
12215 shellparam = saveparam;
12221 static int FAST_FUNC
12222 exitcmd(int argc UNUSED_PARAM, char **argv)
12227 exitstatus = number(argv[1]);
12228 raise_exception(EXEXIT);
12233 * Read a file containing shell functions.
12236 readcmdfile(char *name)
12238 setinputfile(name, INPUT_PUSH_FILE);
12244 /* ============ find_command inplementation */
12247 * Resolve a command name. If you change this routine, you may have to
12248 * change the shellexec routine as well.
12251 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12253 struct tblentry *cmdp;
12260 struct builtincmd *bcmd;
12262 /* If name contains a slash, don't use PATH or hash table */
12263 if (strchr(name, '/') != NULL) {
12264 entry->u.index = -1;
12265 if (act & DO_ABS) {
12266 while (stat(name, &statb) < 0) {
12268 if (errno == EINTR)
12271 entry->cmdtype = CMDUNKNOWN;
12275 entry->cmdtype = CMDNORMAL;
12279 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12281 updatetbl = (path == pathval());
12284 if (strstr(path, "%builtin") != NULL)
12285 act |= DO_ALTBLTIN;
12288 /* If name is in the table, check answer will be ok */
12289 cmdp = cmdlookup(name, 0);
12290 if (cmdp != NULL) {
12293 switch (cmdp->cmdtype) {
12311 } else if (cmdp->rehash == 0)
12312 /* if not invalidated by cd, we're done */
12316 /* If %builtin not in path, check for builtin next */
12317 bcmd = find_builtin(name);
12319 if (IS_BUILTIN_REGULAR(bcmd))
12320 goto builtin_success;
12321 if (act & DO_ALTPATH) {
12322 if (!(act & DO_ALTBLTIN))
12323 goto builtin_success;
12324 } else if (builtinloc <= 0) {
12325 goto builtin_success;
12329 #if ENABLE_FEATURE_SH_STANDALONE
12331 int applet_no = find_applet_by_name(name);
12332 if (applet_no >= 0) {
12333 entry->cmdtype = CMDNORMAL;
12334 entry->u.index = -2 - applet_no;
12340 /* We have to search path. */
12341 prev = -1; /* where to start */
12342 if (cmdp && cmdp->rehash) { /* doing a rehash */
12343 if (cmdp->cmdtype == CMDBUILTIN)
12346 prev = cmdp->param.index;
12352 while ((fullname = path_advance(&path, name)) != NULL) {
12353 stunalloc(fullname);
12354 /* NB: code below will still use fullname
12355 * despite it being "unallocated" */
12358 if (prefix(pathopt, "builtin")) {
12360 goto builtin_success;
12363 if ((act & DO_NOFUNC)
12364 || !prefix(pathopt, "func")
12365 ) { /* ignore unimplemented options */
12369 /* if rehash, don't redo absolute path names */
12370 if (fullname[0] == '/' && idx <= prev) {
12373 TRACE(("searchexec \"%s\": no change\n", name));
12376 while (stat(fullname, &statb) < 0) {
12378 if (errno == EINTR)
12381 if (errno != ENOENT && errno != ENOTDIR)
12385 e = EACCES; /* if we fail, this will be the error */
12386 if (!S_ISREG(statb.st_mode))
12388 if (pathopt) { /* this is a %func directory */
12389 stalloc(strlen(fullname) + 1);
12390 /* NB: stalloc will return space pointed by fullname
12391 * (because we don't have any intervening allocations
12392 * between stunalloc above and this stalloc) */
12393 readcmdfile(fullname);
12394 cmdp = cmdlookup(name, 0);
12395 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12396 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12397 stunalloc(fullname);
12400 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12402 entry->cmdtype = CMDNORMAL;
12403 entry->u.index = idx;
12407 cmdp = cmdlookup(name, 1);
12408 cmdp->cmdtype = CMDNORMAL;
12409 cmdp->param.index = idx;
12414 /* We failed. If there was an entry for this command, delete it */
12415 if (cmdp && updatetbl)
12416 delete_cmd_entry();
12418 ash_msg("%s: %s", name, errmsg(e, "not found"));
12419 entry->cmdtype = CMDUNKNOWN;
12424 entry->cmdtype = CMDBUILTIN;
12425 entry->u.cmd = bcmd;
12429 cmdp = cmdlookup(name, 1);
12430 cmdp->cmdtype = CMDBUILTIN;
12431 cmdp->param.cmd = bcmd;
12435 entry->cmdtype = cmdp->cmdtype;
12436 entry->u = cmdp->param;
12440 /* ============ trap.c */
12443 * The trap builtin.
12445 static int FAST_FUNC
12446 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12450 int signo, exitcode;
12455 for (signo = 0; signo < NSIG; signo++) {
12456 char *tr = trap_ptr[signo];
12458 /* note: bash adds "SIG", but only if invoked
12459 * as "bash". If called as "sh", or if set -o posix,
12460 * then it prints short signal names.
12461 * We are printing short names: */
12462 out1fmt("trap -- %s %s\n",
12464 get_signame(signo));
12465 /* trap_ptr != trap only if we are in special-cased `trap` code.
12466 * In this case, we will exit very soon, no need to free(). */
12467 /* if (trap_ptr != trap && tp[0]) */
12472 if (trap_ptr != trap) {
12485 signo = get_signum(*ap);
12487 /* Mimic bash message exactly */
12488 ash_msg("%s: invalid signal specification", *ap);
12494 if (LONE_DASH(action))
12497 action = ckstrdup(action);
12501 may_have_traps = 1;
12502 trap[signo] = action;
12513 /* ============ Builtins */
12515 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12517 * Lists available builtins
12519 static int FAST_FUNC
12520 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12526 "Built-in commands:\n"
12527 "------------------\n");
12528 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12529 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12530 builtintab[i].name + 1);
12536 #if ENABLE_FEATURE_SH_STANDALONE
12538 const char *a = applet_names;
12540 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12545 a += strlen(a) + 1;
12550 return EXIT_SUCCESS;
12552 #endif /* FEATURE_SH_EXTRA_QUIET */
12555 * The export and readonly commands.
12557 static int FAST_FUNC
12558 exportcmd(int argc UNUSED_PARAM, char **argv)
12564 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12566 if (nextopt("p") != 'p') {
12571 p = strchr(name, '=');
12575 vp = *findvar(hashvar(name), name);
12581 setvar(name, p, flag);
12582 } while ((name = *++aptr) != NULL);
12586 showvars(argv[0], flag, 0);
12591 * Delete a function if it exists.
12594 unsetfunc(const char *name)
12596 struct tblentry *cmdp;
12598 cmdp = cmdlookup(name, 0);
12599 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12600 delete_cmd_entry();
12604 * The unset builtin command. We unset the function before we unset the
12605 * variable to allow a function to be unset when there is a readonly variable
12606 * with the same name.
12608 static int FAST_FUNC
12609 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12616 while ((i = nextopt("vf")) != 0) {
12620 for (ap = argptr; *ap; ap++) {
12633 static const unsigned char timescmd_str[] ALIGN1 = {
12634 ' ', offsetof(struct tms, tms_utime),
12635 '\n', offsetof(struct tms, tms_stime),
12636 ' ', offsetof(struct tms, tms_cutime),
12637 '\n', offsetof(struct tms, tms_cstime),
12640 static int FAST_FUNC
12641 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12643 unsigned long clk_tck, s, t;
12644 const unsigned char *p;
12647 clk_tck = sysconf(_SC_CLK_TCK);
12652 t = *(clock_t *)(((char *) &buf) + p[1]);
12655 out1fmt("%lum%lu.%03lus%c",
12657 (t * 1000) / clk_tck,
12665 #if ENABLE_SH_MATH_SUPPORT
12667 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12668 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12670 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12672 static int FAST_FUNC
12673 letcmd(int argc UNUSED_PARAM, char **argv)
12679 ash_msg_and_raise_error("expression expected");
12681 i = ash_arith(*argv);
12689 * The read builtin. Options:
12690 * -r Do not interpret '\' specially
12691 * -s Turn off echo (tty only)
12692 * -n NCHARS Read NCHARS max
12693 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12694 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12695 * -u FD Read from given FD instead of fd 0
12696 * This uses unbuffered input, which may be avoidable in some cases.
12697 * TODO: bash also has:
12698 * -a ARRAY Read into array[0],[1],etc
12699 * -d DELIM End on DELIM char, not newline
12700 * -e Use line editing (tty only)
12702 static int FAST_FUNC
12703 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12705 char *opt_n = NULL;
12706 char *opt_p = NULL;
12707 char *opt_t = NULL;
12708 char *opt_u = NULL;
12709 int read_flags = 0;
12713 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12722 read_flags |= BUILTIN_READ_SILENT;
12728 read_flags |= BUILTIN_READ_RAW;
12738 r = shell_builtin_read(setvar2,
12740 bltinlookup("IFS"), /* can be NULL */
12748 if ((uintptr_t)r > 1)
12749 ash_msg_and_raise_error(r);
12751 return (uintptr_t)r;
12754 static int FAST_FUNC
12755 umaskcmd(int argc UNUSED_PARAM, char **argv)
12757 static const char permuser[3] ALIGN1 = "ugo";
12758 static const char permmode[3] ALIGN1 = "rwx";
12759 static const short permmask[] ALIGN2 = {
12760 S_IRUSR, S_IWUSR, S_IXUSR,
12761 S_IRGRP, S_IWGRP, S_IXGRP,
12762 S_IROTH, S_IWOTH, S_IXOTH
12765 /* TODO: use bb_parse_mode() instead */
12770 int symbolic_mode = 0;
12772 while (nextopt("S") != '\0') {
12783 if (symbolic_mode) {
12787 for (i = 0; i < 3; i++) {
12790 *p++ = permuser[i];
12792 for (j = 0; j < 3; j++) {
12793 if ((mask & permmask[3 * i + j]) == 0) {
12794 *p++ = permmode[j];
12802 out1fmt("%.4o\n", mask);
12805 if (isdigit((unsigned char) *ap)) {
12808 if (*ap >= '8' || *ap < '0')
12809 ash_msg_and_raise_error(msg_illnum, argv[1]);
12810 mask = (mask << 3) + (*ap - '0');
12811 } while (*++ap != '\0');
12814 mask = ~mask & 0777;
12815 if (!bb_parse_mode(ap, &mask)) {
12816 ash_msg_and_raise_error("illegal mode: %s", ap);
12818 umask(~mask & 0777);
12824 static int FAST_FUNC
12825 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12827 return shell_builtin_ulimit(argv);
12830 /* ============ main() and helpers */
12833 * Called to exit the shell.
12842 status = exitstatus;
12843 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12844 if (setjmp(loc.loc)) {
12845 if (exception_type == EXEXIT)
12846 /* dash bug: it just does _exit(exitstatus) here
12847 * but we have to do setjobctl(0) first!
12848 * (bug is still not fixed in dash-0.5.3 - if you run dash
12849 * under Midnight Commander, on exit from dash MC is backgrounded) */
12850 status = exitstatus;
12853 exception_handler = &loc;
12860 flush_stdout_stderr();
12870 /* from input.c: */
12871 /* we will never free this */
12872 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12875 signal(SIGCHLD, SIG_DFL);
12876 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12877 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12879 signal(SIGHUP, SIG_DFL);
12885 struct stat st1, st2;
12888 for (envp = environ; envp && *envp; envp++) {
12889 if (strchr(*envp, '=')) {
12890 setvareq(*envp, VEXPORT|VTEXTFIXED);
12894 setvar("PPID", utoa(getppid()), 0);
12896 p = lookupvar("PWD");
12898 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12899 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12906 * Process the shell command line arguments.
12909 procargs(char **argv)
12912 const char *xminusc;
12917 /* if (xargv[0]) - mmm, this is always true! */
12919 for (i = 0; i < NOPTS; i++)
12923 /* it already printed err message */
12924 raise_exception(EXERROR);
12928 if (*xargv == NULL) {
12930 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12933 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12937 for (i = 0; i < NOPTS; i++)
12938 if (optlist[i] == 2)
12943 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12948 } else if (!sflag) {
12949 setinputfile(*xargv, 0);
12952 commandname = arg0;
12955 shellparam.p = xargv;
12956 #if ENABLE_ASH_GETOPTS
12957 shellparam.optind = 1;
12958 shellparam.optoff = -1;
12960 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12962 shellparam.nparam++;
12969 * Read /etc/profile or .profile.
12972 read_profile(const char *name)
12976 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12985 * This routine is called when an error or an interrupt occurs in an
12986 * interactive shell and control is returned to the main command loop.
12994 /* from input.c: */
12995 g_parsefile->left_in_buffer = 0;
12996 g_parsefile->left_in_line = 0; /* clear input buffer */
12998 /* from parser.c: */
13001 /* from redir.c: */
13002 clearredir(/*drop:*/ 0);
13006 static short profile_buf[16384];
13007 extern int etext();
13011 * Main routine. We initialize things, parse the arguments, execute
13012 * profiles if we're a login shell, and then call cmdloop to execute
13013 * commands. The setjmp call sets up the location to jump to when an
13014 * exception occurs. When an exception occurs the variable "state"
13015 * is used to figure out how far we had gotten.
13017 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13018 int ash_main(int argc UNUSED_PARAM, char **argv)
13020 const char *shinit;
13021 volatile smallint state;
13022 struct jmploc jmploc;
13023 struct stackmark smark;
13025 /* Initialize global data */
13029 #if ENABLE_ASH_ALIAS
13035 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13038 #if ENABLE_FEATURE_EDITING
13039 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13042 if (setjmp(jmploc.loc)) {
13048 e = exception_type;
13052 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13056 outcslow('\n', stderr);
13059 popstackmark(&smark);
13060 FORCE_INT_ON; /* enable interrupts */
13069 exception_handler = &jmploc;
13072 TRACE(("Shell args: "));
13073 trace_puts_args(argv);
13075 rootpid = getpid();
13078 setstackmark(&smark);
13081 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13083 const char *hp = lookupvar("HISTFILE");
13086 hp = lookupvar("HOME");
13088 char *defhp = concat_path_file(hp, ".ash_history");
13089 setvar("HISTFILE", defhp, 0);
13095 if (argv[0] && argv[0][0] == '-')
13099 read_profile("/etc/profile");
13102 read_profile(".profile");
13108 getuid() == geteuid() && getgid() == getegid() &&
13112 shinit = lookupvar("ENV");
13113 if (shinit != NULL && *shinit != '\0') {
13114 read_profile(shinit);
13120 /* evalstring pushes parsefile stack.
13121 * Ensure we don't falsely claim that 0 (stdin)
13122 * is one of stacked source fds.
13123 * Testcase: ash -c 'exec 1>&0' must not complain. */
13124 // if (!sflag) g_parsefile->pf_fd = -1;
13125 // ^^ not necessary since now we special-case fd 0
13126 // in is_hidden_fd() to not be considered "hidden fd"
13127 evalstring(minusc, 0);
13130 if (sflag || minusc == NULL) {
13131 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13133 const char *hp = lookupvar("HISTFILE");
13135 line_input_state->hist_file = hp;
13138 state4: /* XXX ??? - why isn't this before the "if" statement */
13146 extern void _mcleanup(void);
13150 TRACE(("End of main reached\n"));
13157 * Copyright (c) 1989, 1991, 1993, 1994
13158 * The Regents of the University of California. All rights reserved.
13160 * This code is derived from software contributed to Berkeley by
13161 * Kenneth Almquist.
13163 * Redistribution and use in source and binary forms, with or without
13164 * modification, are permitted provided that the following conditions
13166 * 1. Redistributions of source code must retain the above copyright
13167 * notice, this list of conditions and the following disclaimer.
13168 * 2. Redistributions in binary form must reproduce the above copyright
13169 * notice, this list of conditions and the following disclaimer in the
13170 * documentation and/or other materials provided with the distribution.
13171 * 3. Neither the name of the University nor the names of its contributors
13172 * may be used to endorse or promote products derived from this software
13173 * without specific prior written permission.
13175 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13176 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13177 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13178 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13179 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13180 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13181 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13182 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13183 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13184 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF