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
106 //config: of idle time.
108 //config:config ASH_JOB_CONTROL
109 //config: bool "Job control"
111 //config: depends on ASH
113 //config: Enable job control in the ash shell.
115 //config:config ASH_ALIAS
116 //config: bool "Alias support"
118 //config: depends on ASH
120 //config: Enable alias support in the ash shell.
122 //config:config ASH_GETOPTS
123 //config: bool "Builtin getopt to parse positional parameters"
125 //config: depends on ASH
127 //config: Enable support for getopts builtin in ash.
129 //config:config ASH_BUILTIN_ECHO
130 //config: bool "Builtin version of 'echo'"
132 //config: depends on ASH
134 //config: Enable support for echo builtin in ash.
136 //config:config ASH_BUILTIN_PRINTF
137 //config: bool "Builtin version of 'printf'"
139 //config: depends on ASH
141 //config: Enable support for printf builtin in ash.
143 //config:config ASH_BUILTIN_TEST
144 //config: bool "Builtin version of 'test'"
146 //config: depends on ASH
148 //config: Enable support for test builtin in ash.
150 //config:config ASH_CMDCMD
151 //config: bool "'command' command to override shell builtins"
153 //config: depends on ASH
155 //config: Enable support for the ash 'command' builtin, which allows
156 //config: you to run the specified command with the specified arguments,
157 //config: even when there is an ash builtin command with the same name.
159 //config:config ASH_MAIL
160 //config: bool "Check for new mail on interactive shells"
162 //config: depends on ASH
164 //config: Enable "check for new mail" function in the ash shell.
166 //config:config ASH_OPTIMIZE_FOR_SIZE
167 //config: bool "Optimize for size instead of speed"
169 //config: depends on ASH
171 //config: Compile ash for reduced size at the price of speed.
173 //config:config ASH_RANDOM_SUPPORT
174 //config: bool "Pseudorandom generator and $RANDOM variable"
176 //config: depends on ASH
178 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
179 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
180 //config: You can reset the generator by using a specified start value.
181 //config: After "unset RANDOM" the generator will switch off and this
182 //config: variable will no longer have special treatment.
184 //config:config ASH_EXPAND_PRMT
185 //config: bool "Expand prompt string"
187 //config: depends on ASH
189 //config: "PS#" may contain volatile content, such as backquote commands.
190 //config: This option recreates the prompt string from the environment
191 //config: variable each time it is displayed.
194 //usage:#define ash_trivial_usage NOUSAGE_STR
195 //usage:#define ash_full_usage ""
196 //usage:#define sh_trivial_usage NOUSAGE_STR
197 //usage:#define sh_full_usage ""
198 //usage:#define bash_trivial_usage NOUSAGE_STR
199 //usage:#define bash_full_usage ""
202 /* ============ Hash table sizes. Configurable. */
206 #define CMDTABLESIZE 31 /* should be prime */
209 /* ============ Shell options */
211 static const char *const optletters_optnames[] = {
226 #if ENABLE_ASH_BASH_COMPAT
235 #define optletters(n) optletters_optnames[n][0]
236 #define optnames(n) (optletters_optnames[n] + 1)
238 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
241 /* ============ Misc data */
243 #define msg_illnum "Illegal number: %s"
246 * We enclose jmp_buf in a structure so that we can declare pointers to
247 * jump locations. The global variable handler contains the location to
248 * jump to when an exception occurs, and the global variable exception_type
249 * contains a code identifying the exception. To implement nested
250 * exception handlers, the user should save the value of handler on entry
251 * to an inner scope, set handler to point to a jmploc structure for the
252 * inner scope, and restore handler on exit from the scope.
258 struct globals_misc {
259 /* pid of main shell */
261 /* shell level: 0 for the main shell, 1 for its children, and so on */
263 #define rootshell (!shlvl)
264 char *minusc; /* argument to -c option */
266 char *curdir; // = nullstr; /* current working directory */
267 char *physdir; // = nullstr; /* physical working directory */
269 char *arg0; /* value of $0 */
271 struct jmploc *exception_handler;
273 volatile int suppress_int; /* counter */
274 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
275 /* last pending signal */
276 volatile /*sig_atomic_t*/ smallint pending_sig;
277 smallint exception_type; /* kind of exception (0..5) */
279 #define EXINT 0 /* SIGINT received */
280 #define EXERROR 1 /* a generic error */
281 #define EXSHELLPROC 2 /* execute a shell procedure */
282 #define EXEXEC 3 /* command execution failed */
283 #define EXEXIT 4 /* exit the shell */
284 #define EXSIG 5 /* trapped signal in wait(1) */
287 char nullstr[1]; /* zero length string */
290 #define eflag optlist[0]
291 #define fflag optlist[1]
292 #define Iflag optlist[2]
293 #define iflag optlist[3]
294 #define mflag optlist[4]
295 #define nflag optlist[5]
296 #define sflag optlist[6]
297 #define xflag optlist[7]
298 #define vflag optlist[8]
299 #define Cflag optlist[9]
300 #define aflag optlist[10]
301 #define bflag optlist[11]
302 #define uflag optlist[12]
303 #define viflag optlist[13]
304 #if ENABLE_ASH_BASH_COMPAT
305 # define pipefail optlist[14]
310 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
311 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
314 /* trap handler commands */
316 * Sigmode records the current value of the signal handlers for the various
317 * modes. A value of zero means that the current handler is not known.
318 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
320 char sigmode[NSIG - 1];
321 #define S_DFL 1 /* default signal handling (SIG_DFL) */
322 #define S_CATCH 2 /* signal is caught */
323 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
324 #define S_HARD_IGN 4 /* signal is ignored permenantly */
326 /* indicates specified signal received */
327 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
328 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
330 char **trap_ptr; /* used only by "trap hack" */
332 /* Rarely referenced stuff */
333 #if ENABLE_ASH_RANDOM_SUPPORT
336 pid_t backgndpid; /* pid of last background process */
337 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
339 extern struct globals_misc *const ash_ptr_to_globals_misc;
340 #define G_misc (*ash_ptr_to_globals_misc)
341 #define rootpid (G_misc.rootpid )
342 #define shlvl (G_misc.shlvl )
343 #define minusc (G_misc.minusc )
344 #define curdir (G_misc.curdir )
345 #define physdir (G_misc.physdir )
346 #define arg0 (G_misc.arg0 )
347 #define exception_handler (G_misc.exception_handler)
348 #define exception_type (G_misc.exception_type )
349 #define suppress_int (G_misc.suppress_int )
350 #define pending_int (G_misc.pending_int )
351 #define pending_sig (G_misc.pending_sig )
352 #define isloginsh (G_misc.isloginsh )
353 #define nullstr (G_misc.nullstr )
354 #define optlist (G_misc.optlist )
355 #define sigmode (G_misc.sigmode )
356 #define gotsig (G_misc.gotsig )
357 #define may_have_traps (G_misc.may_have_traps )
358 #define trap (G_misc.trap )
359 #define trap_ptr (G_misc.trap_ptr )
360 #define random_gen (G_misc.random_gen )
361 #define backgndpid (G_misc.backgndpid )
362 #define job_warning (G_misc.job_warning)
363 #define INIT_G_misc() do { \
364 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
372 /* ============ DEBUG */
374 static void trace_printf(const char *fmt, ...);
375 static void trace_vprintf(const char *fmt, va_list va);
376 # define TRACE(param) trace_printf param
377 # define TRACEV(param) trace_vprintf param
378 # define close(fd) do { \
380 if (close(dfd) < 0) \
381 bb_error_msg("bug on %d: closing %d(0x%x)", \
382 __LINE__, dfd, dfd); \
385 # define TRACE(param)
386 # define TRACEV(param)
390 /* ============ Utility functions */
391 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
393 static int isdigit_str9(const char *str)
395 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
396 while (--maxlen && isdigit(*str))
398 return (*str == '\0');
401 static const char *var_end(const char *var)
410 /* ============ Interrupts / exceptions */
412 * These macros allow the user to suspend the handling of interrupt signals
413 * over a period of time. This is similar to SIGHOLD or to sigblock, but
414 * much more efficient and portable. (But hacking the kernel is so much
415 * more fun than worrying about efficiency and portability. :-))
417 #define INT_OFF do { \
423 * Called to raise an exception. Since C doesn't include exceptions, we
424 * just do a longjmp to the exception handler. The type of exception is
425 * stored in the global variable "exception_type".
427 static void raise_exception(int) NORETURN;
429 raise_exception(int e)
432 if (exception_handler == NULL)
437 longjmp(exception_handler->loc, 1);
440 #define raise_exception(e) do { \
441 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
442 raise_exception(e); \
447 * Called from trap.c when a SIGINT is received. (If the user specifies
448 * that SIGINT is to be trapped or ignored using the trap builtin, then
449 * this routine is not called.) Suppressint is nonzero when interrupts
450 * are held using the INT_OFF macro. (The test for iflag is just
451 * defensive programming.)
453 static void raise_interrupt(void) NORETURN;
455 raise_interrupt(void)
460 /* Signal is not automatically unmasked after it is raised,
461 * do it ourself - unmask all signals */
462 sigprocmask_allsigs(SIG_UNBLOCK);
463 /* pending_sig = 0; - now done in signal_handler() */
466 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
467 if (!(rootshell && iflag)) {
468 /* Kill ourself with SIGINT */
469 signal(SIGINT, SIG_DFL);
474 raise_exception(ex_type);
478 #define raise_interrupt() do { \
479 TRACE(("raising interrupt on line %d\n", __LINE__)); \
484 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
488 if (--suppress_int == 0 && pending_int) {
492 #define INT_ON int_on()
493 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
501 #define FORCE_INT_ON force_int_on()
503 #define SAVE_INT(v) ((v) = suppress_int)
505 #define RESTORE_INT(v) do { \
507 suppress_int = (v); \
508 if (suppress_int == 0 && pending_int) \
513 /* ============ Stdout/stderr output */
516 outstr(const char *p, FILE *file)
524 flush_stdout_stderr(void)
532 outcslow(int c, FILE *dest)
540 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
542 out1fmt(const char *fmt, ...)
549 r = vprintf(fmt, ap);
555 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
557 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
564 ret = vsnprintf(outbuf, length, fmt, ap);
571 out1str(const char *p)
577 out2str(const char *p)
580 flush_stdout_stderr();
584 /* ============ Parser structures */
586 /* control characters in argument strings */
587 #define CTL_FIRST CTLESC
588 #define CTLESC ((unsigned char)'\201') /* escape next character */
589 #define CTLVAR ((unsigned char)'\202') /* variable defn */
590 #define CTLENDVAR ((unsigned char)'\203')
591 #define CTLBACKQ ((unsigned char)'\204')
592 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
593 /* CTLBACKQ | CTLQUOTE == '\205' */
594 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
595 #define CTLENDARI ((unsigned char)'\207')
596 #define CTLQUOTEMARK ((unsigned char)'\210')
597 #define CTL_LAST CTLQUOTEMARK
599 /* variable substitution byte (follows CTLVAR) */
600 #define VSTYPE 0x0f /* type of variable substitution */
601 #define VSNUL 0x10 /* colon--treat the empty string as unset */
602 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
604 /* values of VSTYPE field */
605 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
606 #define VSMINUS 0x2 /* ${var-text} */
607 #define VSPLUS 0x3 /* ${var+text} */
608 #define VSQUESTION 0x4 /* ${var?message} */
609 #define VSASSIGN 0x5 /* ${var=text} */
610 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
611 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
612 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
613 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
614 #define VSLENGTH 0xa /* ${#var} */
615 #if ENABLE_ASH_BASH_COMPAT
616 #define VSSUBSTR 0xc /* ${var:position:length} */
617 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
618 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
621 static const char dolatstr[] ALIGN1 = {
622 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
642 #if ENABLE_ASH_BASH_COMPAT
659 smallint type; /* Nxxxx */
662 union node *redirect;
667 smallint pipe_backgnd;
668 struct nodelist *cmdlist;
674 union node *redirect;
687 union node *elsepart;
714 struct nodelist *backquote;
717 /* nfile and ndup layout must match!
718 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
719 * that it is actually NTO2 (>&file), and change its type.
736 char *_unused_expfname;
755 struct nredir nredir;
756 struct nbinary nbinary;
760 struct nclist nclist;
769 * NODE_EOF is returned by parsecmd when it encounters an end of file.
770 * It must be distinct from NULL.
772 #define NODE_EOF ((union node *) -1L)
775 struct nodelist *next;
788 freefunc(struct funcnode *f)
790 if (f && --f->count < 0)
795 /* ============ Debugging output */
799 static FILE *tracefile;
802 trace_printf(const char *fmt, ...)
809 fprintf(tracefile, "%u ", (int) time(NULL));
811 fprintf(tracefile, "[%u] ", (int) getpid());
813 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
815 vfprintf(tracefile, fmt, va);
820 trace_vprintf(const char *fmt, va_list va)
825 fprintf(tracefile, "%u ", (int) time(NULL));
827 fprintf(tracefile, "[%u] ", (int) getpid());
829 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
830 vfprintf(tracefile, fmt, va);
834 trace_puts(const char *s)
842 trace_puts_quoted(char *s)
849 putc('"', tracefile);
850 for (p = s; *p; p++) {
851 switch ((unsigned char)*p) {
852 case '\n': c = 'n'; goto backslash;
853 case '\t': c = 't'; goto backslash;
854 case '\r': c = 'r'; goto backslash;
855 case '\"': c = '\"'; goto backslash;
856 case '\\': c = '\\'; goto backslash;
857 case CTLESC: c = 'e'; goto backslash;
858 case CTLVAR: c = 'v'; goto backslash;
859 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
860 case CTLBACKQ: c = 'q'; goto backslash;
861 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
863 putc('\\', tracefile);
867 if (*p >= ' ' && *p <= '~')
870 putc('\\', tracefile);
871 putc((*p >> 6) & 03, tracefile);
872 putc((*p >> 3) & 07, tracefile);
873 putc(*p & 07, tracefile);
878 putc('"', tracefile);
882 trace_puts_args(char **ap)
889 trace_puts_quoted(*ap);
891 putc('\n', tracefile);
894 putc(' ', tracefile);
909 /* leave open because libedit might be using it */
912 strcpy(s, "./trace");
914 if (!freopen(s, "a", tracefile)) {
915 fprintf(stderr, "Can't re-open %s\n", s);
920 tracefile = fopen(s, "a");
921 if (tracefile == NULL) {
922 fprintf(stderr, "Can't open %s\n", s);
928 flags = fcntl(fileno(tracefile), F_GETFL);
930 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
932 setlinebuf(tracefile);
933 fputs("\nTracing started.\n", tracefile);
937 indent(int amount, char *pfx, FILE *fp)
941 for (i = 0; i < amount; i++) {
942 if (pfx && i == amount - 1)
948 /* little circular references here... */
949 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
952 sharg(union node *arg, FILE *fp)
955 struct nodelist *bqlist;
956 unsigned char subtype;
958 if (arg->type != NARG) {
959 out1fmt("<node type %d>\n", arg->type);
962 bqlist = arg->narg.backquote;
963 for (p = arg->narg.text; *p; p++) {
964 switch ((unsigned char)*p) {
973 if (subtype == VSLENGTH)
984 switch (subtype & VSTYPE) {
1010 case VSTRIMRIGHTMAX:
1017 out1fmt("<subtype %d>", subtype);
1024 case CTLBACKQ|CTLQUOTE:
1027 shtree(bqlist->n, -1, NULL, fp);
1038 shcmd(union node *cmd, FILE *fp)
1046 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1052 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1056 switch (np->nfile.type) {
1057 case NTO: s = ">>"+1; dftfd = 1; break;
1058 case NCLOBBER: s = ">|"; dftfd = 1; break;
1059 case NAPPEND: s = ">>"; dftfd = 1; break;
1060 #if ENABLE_ASH_BASH_COMPAT
1063 case NTOFD: s = ">&"; dftfd = 1; break;
1064 case NFROM: s = "<"; break;
1065 case NFROMFD: s = "<&"; break;
1066 case NFROMTO: s = "<>"; break;
1067 default: s = "*error*"; break;
1069 if (np->nfile.fd != dftfd)
1070 fprintf(fp, "%d", np->nfile.fd);
1072 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1073 fprintf(fp, "%d", np->ndup.dupfd);
1075 sharg(np->nfile.fname, fp);
1082 shtree(union node *n, int ind, char *pfx, FILE *fp)
1084 struct nodelist *lp;
1090 indent(ind, pfx, fp);
1092 if (n == NODE_EOF) {
1107 shtree(n->nbinary.ch1, ind, NULL, fp);
1110 shtree(n->nbinary.ch2, ind, NULL, fp);
1118 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1119 shtree(lp->n, 0, NULL, fp);
1123 if (n->npipe.pipe_backgnd)
1129 fprintf(fp, "<node type %d>", n->type);
1137 showtree(union node *n)
1139 trace_puts("showtree called\n");
1140 shtree(n, 1, NULL, stderr);
1146 /* ============ Parser data */
1149 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1152 struct strlist *next;
1159 struct strpush *prev; /* preceding string on stack */
1161 int prev_left_in_line;
1162 #if ENABLE_ASH_ALIAS
1163 struct alias *ap; /* if push was associated with an alias */
1165 char *string; /* remember the string since it may change */
1169 struct parsefile *prev; /* preceding file on stack */
1170 int linno; /* current line */
1171 int pf_fd; /* file descriptor (or -1 if string) */
1172 int left_in_line; /* number of chars left in this line */
1173 int left_in_buffer; /* number of chars left in this buffer past the line */
1174 char *next_to_pgetc; /* next char in buffer */
1175 char *buf; /* input buffer */
1176 struct strpush *strpush; /* for pushing strings at this level */
1177 struct strpush basestrpush; /* so pushing one is fast */
1180 static struct parsefile basepf; /* top level input file */
1181 static struct parsefile *g_parsefile = &basepf; /* current input file */
1182 static int startlinno; /* line # where last token started */
1183 static char *commandname; /* currently executing command */
1184 static struct strlist *cmdenviron; /* environment for builtin command */
1185 static uint8_t exitstatus; /* exit status of last command */
1188 /* ============ Message printing */
1191 ash_vmsg(const char *msg, va_list ap)
1193 fprintf(stderr, "%s: ", arg0);
1195 if (strcmp(arg0, commandname))
1196 fprintf(stderr, "%s: ", commandname);
1197 if (!iflag || g_parsefile->pf_fd > 0)
1198 fprintf(stderr, "line %d: ", startlinno);
1200 vfprintf(stderr, msg, ap);
1201 outcslow('\n', stderr);
1205 * Exverror is called to raise the error exception. If the second argument
1206 * is not NULL then error prints an error message using printf style
1207 * formatting. It then raises the error exception.
1209 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1211 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1215 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1217 TRACE(("\") pid=%d\n", getpid()));
1219 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1224 flush_stdout_stderr();
1225 raise_exception(cond);
1229 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1231 ash_msg_and_raise_error(const char *msg, ...)
1236 ash_vmsg_and_raise(EXERROR, msg, ap);
1241 static void raise_error_syntax(const char *) NORETURN;
1243 raise_error_syntax(const char *msg)
1245 ash_msg_and_raise_error("syntax error: %s", msg);
1249 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1251 ash_msg_and_raise(int cond, const char *msg, ...)
1256 ash_vmsg_and_raise(cond, msg, ap);
1262 * error/warning routines for external builtins
1265 ash_msg(const char *fmt, ...)
1275 * Return a string describing an error. The returned string may be a
1276 * pointer to a static buffer that will be overwritten on the next call.
1277 * Action describes the operation that got the error.
1280 errmsg(int e, const char *em)
1282 if (e == ENOENT || e == ENOTDIR) {
1289 /* ============ Memory allocation */
1292 /* I consider these wrappers nearly useless:
1293 * ok, they return you to nearest exception handler, but
1294 * how much memory do you leak in the process, making
1295 * memory starvation worse?
1298 ckrealloc(void * p, size_t nbytes)
1300 p = realloc(p, nbytes);
1302 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1307 ckmalloc(size_t nbytes)
1309 return ckrealloc(NULL, nbytes);
1313 ckzalloc(size_t nbytes)
1315 return memset(ckmalloc(nbytes), 0, nbytes);
1319 ckstrdup(const char *s)
1321 char *p = strdup(s);
1323 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1327 /* Using bbox equivalents. They exit if out of memory */
1328 # define ckrealloc xrealloc
1329 # define ckmalloc xmalloc
1330 # define ckzalloc xzalloc
1331 # define ckstrdup xstrdup
1335 * It appears that grabstackstr() will barf with such alignments
1336 * because stalloc() will return a string allocated in a new stackblock.
1338 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1340 /* Most machines require the value returned from malloc to be aligned
1341 * in some way. The following macro will get this right
1342 * on many machines. */
1343 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1344 /* Minimum size of a block */
1345 MINSIZE = SHELL_ALIGN(504),
1348 struct stack_block {
1349 struct stack_block *prev;
1350 char space[MINSIZE];
1354 struct stack_block *stackp;
1357 struct stackmark *marknext;
1361 struct globals_memstack {
1362 struct stack_block *g_stackp; // = &stackbase;
1363 struct stackmark *markp;
1364 char *g_stacknxt; // = stackbase.space;
1365 char *sstrend; // = stackbase.space + MINSIZE;
1366 size_t g_stacknleft; // = MINSIZE;
1367 int herefd; // = -1;
1368 struct stack_block stackbase;
1370 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1371 #define G_memstack (*ash_ptr_to_globals_memstack)
1372 #define g_stackp (G_memstack.g_stackp )
1373 #define markp (G_memstack.markp )
1374 #define g_stacknxt (G_memstack.g_stacknxt )
1375 #define sstrend (G_memstack.sstrend )
1376 #define g_stacknleft (G_memstack.g_stacknleft)
1377 #define herefd (G_memstack.herefd )
1378 #define stackbase (G_memstack.stackbase )
1379 #define INIT_G_memstack() do { \
1380 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1382 g_stackp = &stackbase; \
1383 g_stacknxt = stackbase.space; \
1384 g_stacknleft = MINSIZE; \
1385 sstrend = stackbase.space + MINSIZE; \
1390 #define stackblock() ((void *)g_stacknxt)
1391 #define stackblocksize() g_stacknleft
1394 * Parse trees for commands are allocated in lifo order, so we use a stack
1395 * to make this more efficient, and also to avoid all sorts of exception
1396 * handling code to handle interrupts in the middle of a parse.
1398 * The size 504 was chosen because the Ultrix malloc handles that size
1402 stalloc(size_t nbytes)
1407 aligned = SHELL_ALIGN(nbytes);
1408 if (aligned > g_stacknleft) {
1411 struct stack_block *sp;
1413 blocksize = aligned;
1414 if (blocksize < MINSIZE)
1415 blocksize = MINSIZE;
1416 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1417 if (len < blocksize)
1418 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1421 sp->prev = g_stackp;
1422 g_stacknxt = sp->space;
1423 g_stacknleft = blocksize;
1424 sstrend = g_stacknxt + blocksize;
1429 g_stacknxt += aligned;
1430 g_stacknleft -= aligned;
1435 stzalloc(size_t nbytes)
1437 return memset(stalloc(nbytes), 0, nbytes);
1444 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1445 write(STDERR_FILENO, "stunalloc\n", 10);
1449 g_stacknleft += g_stacknxt - (char *)p;
1454 * Like strdup but works with the ash stack.
1457 ststrdup(const char *p)
1459 size_t len = strlen(p) + 1;
1460 return memcpy(stalloc(len), p, len);
1464 setstackmark(struct stackmark *mark)
1466 mark->stackp = g_stackp;
1467 mark->stacknxt = g_stacknxt;
1468 mark->stacknleft = g_stacknleft;
1469 mark->marknext = markp;
1474 popstackmark(struct stackmark *mark)
1476 struct stack_block *sp;
1482 markp = mark->marknext;
1483 while (g_stackp != mark->stackp) {
1485 g_stackp = sp->prev;
1488 g_stacknxt = mark->stacknxt;
1489 g_stacknleft = mark->stacknleft;
1490 sstrend = mark->stacknxt + mark->stacknleft;
1495 * When the parser reads in a string, it wants to stick the string on the
1496 * stack and only adjust the stack pointer when it knows how big the
1497 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1498 * of space on top of the stack and stackblocklen returns the length of
1499 * this block. Growstackblock will grow this space by at least one byte,
1500 * possibly moving it (like realloc). Grabstackblock actually allocates the
1501 * part of the block that has been used.
1504 growstackblock(void)
1508 newlen = g_stacknleft * 2;
1509 if (newlen < g_stacknleft)
1510 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1514 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1515 struct stack_block *oldstackp;
1516 struct stackmark *xmark;
1517 struct stack_block *sp;
1518 struct stack_block *prevstackp;
1522 oldstackp = g_stackp;
1524 prevstackp = sp->prev;
1525 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1526 sp = ckrealloc(sp, grosslen);
1527 sp->prev = prevstackp;
1529 g_stacknxt = sp->space;
1530 g_stacknleft = newlen;
1531 sstrend = sp->space + newlen;
1534 * Stack marks pointing to the start of the old block
1535 * must be relocated to point to the new block
1538 while (xmark != NULL && xmark->stackp == oldstackp) {
1539 xmark->stackp = g_stackp;
1540 xmark->stacknxt = g_stacknxt;
1541 xmark->stacknleft = g_stacknleft;
1542 xmark = xmark->marknext;
1546 char *oldspace = g_stacknxt;
1547 size_t oldlen = g_stacknleft;
1548 char *p = stalloc(newlen);
1550 /* free the space we just allocated */
1551 g_stacknxt = memcpy(p, oldspace, oldlen);
1552 g_stacknleft += newlen;
1557 grabstackblock(size_t len)
1559 len = SHELL_ALIGN(len);
1561 g_stacknleft -= len;
1565 * The following routines are somewhat easier to use than the above.
1566 * The user declares a variable of type STACKSTR, which may be declared
1567 * to be a register. The macro STARTSTACKSTR initializes things. Then
1568 * the user uses the macro STPUTC to add characters to the string. In
1569 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1570 * grown as necessary. When the user is done, she can just leave the
1571 * string there and refer to it using stackblock(). Or she can allocate
1572 * the space for it using grabstackstr(). If it is necessary to allow
1573 * someone else to use the stack temporarily and then continue to grow
1574 * the string, the user should use grabstack to allocate the space, and
1575 * then call ungrabstr(p) to return to the previous mode of operation.
1577 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1578 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1579 * is space for at least one character.
1584 size_t len = stackblocksize();
1585 if (herefd >= 0 && len >= 1024) {
1586 full_write(herefd, stackblock(), len);
1587 return stackblock();
1590 return (char *)stackblock() + len;
1594 * Called from CHECKSTRSPACE.
1597 makestrspace(size_t newlen, char *p)
1599 size_t len = p - g_stacknxt;
1600 size_t size = stackblocksize();
1605 size = stackblocksize();
1607 if (nleft >= newlen)
1611 return (char *)stackblock() + len;
1615 stack_nputstr(const char *s, size_t n, char *p)
1617 p = makestrspace(n, p);
1618 p = (char *)memcpy(p, s, n) + n;
1623 stack_putstr(const char *s, char *p)
1625 return stack_nputstr(s, strlen(s), p);
1629 _STPUTC(int c, char *p)
1637 #define STARTSTACKSTR(p) ((p) = stackblock())
1638 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1639 #define CHECKSTRSPACE(n, p) do { \
1642 size_t m = sstrend - q; \
1644 (p) = makestrspace(l, q); \
1646 #define USTPUTC(c, p) (*(p)++ = (c))
1647 #define STACKSTRNUL(p) do { \
1648 if ((p) == sstrend) \
1649 (p) = growstackstr(); \
1652 #define STUNPUTC(p) (--(p))
1653 #define STTOPC(p) ((p)[-1])
1654 #define STADJUST(amount, p) ((p) += (amount))
1656 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1657 #define ungrabstackstr(s, p) stunalloc(s)
1658 #define stackstrend() ((void *)sstrend)
1661 /* ============ String helpers */
1664 * prefix -- see if pfx is a prefix of string.
1667 prefix(const char *string, const char *pfx)
1670 if (*pfx++ != *string++)
1673 return (char *) string;
1677 * Check for a valid number. This should be elsewhere.
1680 is_number(const char *p)
1685 } while (*++p != '\0');
1690 * Convert a string of digits to an integer, printing an error message on
1694 number(const char *s)
1697 ash_msg_and_raise_error(msg_illnum, s);
1702 * Produce a possibly single quoted string suitable as input to the shell.
1703 * The return string is allocated on the stack.
1706 single_quote(const char *s)
1716 len = strchrnul(s, '\'') - s;
1718 q = p = makestrspace(len + 3, p);
1721 q = (char *)memcpy(q, s, len) + len;
1730 do len++; while (*++s == '\'');
1732 q = p = makestrspace(len + 3, p);
1735 q = (char *)memcpy(q, s - len, len) + len;
1743 return stackblock();
1747 /* ============ nextopt */
1749 static char **argptr; /* argument list for builtin commands */
1750 static char *optionarg; /* set by nextopt (like getopt) */
1751 static char *optptr; /* used by nextopt */
1754 * XXX - should get rid of. Have all builtins use getopt(3).
1755 * The library getopt must have the BSD extension static variable
1756 * "optreset", otherwise it can't be used within the shell safely.
1758 * Standard option processing (a la getopt) for builtin routines.
1759 * The only argument that is passed to nextopt is the option string;
1760 * the other arguments are unnecessary. It returns the character,
1761 * or '\0' on end of input.
1764 nextopt(const char *optstring)
1771 if (p == NULL || *p == '\0') {
1772 /* We ate entire "-param", take next one */
1778 if (*++p == '\0') /* just "-" ? */
1781 if (LONE_DASH(p)) /* "--" ? */
1783 /* p => next "-param" */
1785 /* p => some option char in the middle of a "-param" */
1787 for (q = optstring; *q != c;) {
1789 ash_msg_and_raise_error("illegal option -%c", c);
1797 ash_msg_and_raise_error("no arg for -%c option", c);
1807 /* ============ Shell variables */
1810 * The parsefile structure pointed to by the global variable parsefile
1811 * contains information about the current file being read.
1814 int nparam; /* # of positional parameters (without $0) */
1815 #if ENABLE_ASH_GETOPTS
1816 int optind; /* next parameter to be processed by getopts */
1817 int optoff; /* used by getopts */
1819 unsigned char malloced; /* if parameter list dynamically allocated */
1820 char **p; /* parameter list */
1824 * Free the list of positional parameters.
1827 freeparam(volatile struct shparam *param)
1829 if (param->malloced) {
1831 ap = ap1 = param->p;
1838 #if ENABLE_ASH_GETOPTS
1839 static void FAST_FUNC getoptsreset(const char *value);
1843 struct var *next; /* next entry in hash list */
1844 int flags; /* flags are defined above */
1845 const char *var_text; /* name=value */
1846 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1847 /* the variable gets set/unset */
1851 struct localvar *next; /* next local variable in list */
1852 struct var *vp; /* the variable that was made local */
1853 int flags; /* saved flags */
1854 const char *text; /* saved text */
1858 #define VEXPORT 0x01 /* variable is exported */
1859 #define VREADONLY 0x02 /* variable cannot be modified */
1860 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1861 #define VTEXTFIXED 0x08 /* text is statically allocated */
1862 #define VSTACK 0x10 /* text is allocated on the stack */
1863 #define VUNSET 0x20 /* the variable is not set */
1864 #define VNOFUNC 0x40 /* don't call the callback function */
1865 #define VNOSET 0x80 /* do not set variable - just readonly test */
1866 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1867 #if ENABLE_ASH_RANDOM_SUPPORT
1868 # define VDYNAMIC 0x200 /* dynamic variable */
1874 /* Need to be before varinit_data[] */
1875 #if ENABLE_LOCALE_SUPPORT
1876 static void FAST_FUNC
1877 change_lc_all(const char *value)
1879 if (value && *value != '\0')
1880 setlocale(LC_ALL, value);
1882 static void FAST_FUNC
1883 change_lc_ctype(const char *value)
1885 if (value && *value != '\0')
1886 setlocale(LC_CTYPE, value);
1890 static void chkmail(void);
1891 static void changemail(const char *var_value) FAST_FUNC;
1893 # define chkmail() ((void)0)
1895 static void changepath(const char *) FAST_FUNC;
1896 #if ENABLE_ASH_RANDOM_SUPPORT
1897 static void change_random(const char *) FAST_FUNC;
1900 static const struct {
1902 const char *var_text;
1903 void (*var_func)(const char *) FAST_FUNC;
1904 } varinit_data[] = {
1905 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1907 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1908 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1910 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1911 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1912 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1913 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1914 #if ENABLE_ASH_GETOPTS
1915 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1917 #if ENABLE_ASH_RANDOM_SUPPORT
1918 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1920 #if ENABLE_LOCALE_SUPPORT
1921 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1922 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1924 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1925 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1931 struct globals_var {
1932 struct shparam shellparam; /* $@ current positional parameters */
1933 struct redirtab *redirlist;
1935 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1936 struct var *vartab[VTABSIZE];
1937 struct var varinit[ARRAY_SIZE(varinit_data)];
1939 extern struct globals_var *const ash_ptr_to_globals_var;
1940 #define G_var (*ash_ptr_to_globals_var)
1941 #define shellparam (G_var.shellparam )
1942 //#define redirlist (G_var.redirlist )
1943 #define g_nullredirs (G_var.g_nullredirs )
1944 #define preverrout_fd (G_var.preverrout_fd)
1945 #define vartab (G_var.vartab )
1946 #define varinit (G_var.varinit )
1947 #define INIT_G_var() do { \
1949 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1951 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1952 varinit[i].flags = varinit_data[i].flags; \
1953 varinit[i].var_text = varinit_data[i].var_text; \
1954 varinit[i].var_func = varinit_data[i].var_func; \
1958 #define vifs varinit[0]
1960 # define vmail (&vifs)[1]
1961 # define vmpath (&vmail)[1]
1962 # define vpath (&vmpath)[1]
1964 # define vpath (&vifs)[1]
1966 #define vps1 (&vpath)[1]
1967 #define vps2 (&vps1)[1]
1968 #define vps4 (&vps2)[1]
1969 #if ENABLE_ASH_GETOPTS
1970 # define voptind (&vps4)[1]
1971 # if ENABLE_ASH_RANDOM_SUPPORT
1972 # define vrandom (&voptind)[1]
1975 # if ENABLE_ASH_RANDOM_SUPPORT
1976 # define vrandom (&vps4)[1]
1981 * The following macros access the values of the above variables.
1982 * They have to skip over the name. They return the null string
1983 * for unset variables.
1985 #define ifsval() (vifs.var_text + 4)
1986 #define ifsset() ((vifs.flags & VUNSET) == 0)
1988 # define mailval() (vmail.var_text + 5)
1989 # define mpathval() (vmpath.var_text + 9)
1990 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1992 #define pathval() (vpath.var_text + 5)
1993 #define ps1val() (vps1.var_text + 4)
1994 #define ps2val() (vps2.var_text + 4)
1995 #define ps4val() (vps4.var_text + 4)
1996 #if ENABLE_ASH_GETOPTS
1997 # define optindval() (voptind.var_text + 7)
2000 #if ENABLE_ASH_GETOPTS
2001 static void FAST_FUNC
2002 getoptsreset(const char *value)
2004 shellparam.optind = number(value);
2005 shellparam.optoff = -1;
2009 /* math.h has these, otherwise define our private copies */
2010 #if !ENABLE_SH_MATH_SUPPORT
2011 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
2012 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
2014 * Return the pointer to the first char which is not part of a legal variable name
2015 * (a letter or underscore followed by letters, underscores, and digits).
2018 endofname(const char *name)
2020 if (!is_name(*name))
2023 if (!is_in_name(*name))
2031 * Compares two strings up to the first = or '\0'. The first
2032 * string must be terminated by '='; the second may be terminated by
2033 * either '=' or '\0'.
2036 varcmp(const char *p, const char *q)
2040 while ((c = *p) == (d = *q)) {
2055 * Find the appropriate entry in the hash table from the name.
2057 static struct var **
2058 hashvar(const char *p)
2062 hashval = ((unsigned char) *p) << 4;
2063 while (*p && *p != '=')
2064 hashval += (unsigned char) *p++;
2065 return &vartab[hashval % VTABSIZE];
2069 vpcmp(const void *a, const void *b)
2071 return varcmp(*(const char **)a, *(const char **)b);
2075 * This routine initializes the builtin variables.
2085 * PS1 depends on uid
2087 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2088 vps1.var_text = "PS1=\\w \\$ ";
2091 vps1.var_text = "PS1=# ";
2094 end = vp + ARRAY_SIZE(varinit);
2096 vpp = hashvar(vp->var_text);
2099 } while (++vp < end);
2102 static struct var **
2103 findvar(struct var **vpp, const char *name)
2105 for (; *vpp; vpp = &(*vpp)->next) {
2106 if (varcmp((*vpp)->var_text, name) == 0) {
2114 * Find the value of a variable. Returns NULL if not set.
2116 static const char* FAST_FUNC
2117 lookupvar(const char *name)
2121 v = *findvar(hashvar(name), name);
2123 #if ENABLE_ASH_RANDOM_SUPPORT
2125 * Dynamic variables are implemented roughly the same way they are
2126 * in bash. Namely, they're "special" so long as they aren't unset.
2127 * As soon as they're unset, they're no longer dynamic, and dynamic
2128 * lookup will no longer happen at that point. -- PFM.
2130 if (v->flags & VDYNAMIC)
2133 if (!(v->flags & VUNSET))
2134 return var_end(v->var_text);
2140 * Search the environment of a builtin command.
2143 bltinlookup(const char *name)
2147 for (sp = cmdenviron; sp; sp = sp->next) {
2148 if (varcmp(sp->text, name) == 0)
2149 return var_end(sp->text);
2151 return lookupvar(name);
2155 * Same as setvar except that the variable and value are passed in
2156 * the first argument as name=value. Since the first argument will
2157 * be actually stored in the table, it should not be a string that
2159 * Called with interrupts off.
2162 setvareq(char *s, int flags)
2164 struct var *vp, **vpp;
2167 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2168 vp = *findvar(vpp, s);
2170 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2173 if (flags & VNOSAVE)
2176 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2182 if (vp->var_func && !(flags & VNOFUNC))
2183 vp->var_func(var_end(s));
2185 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2186 free((char*)vp->var_text);
2188 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2190 /* variable s is not found */
2193 vp = ckzalloc(sizeof(*vp));
2195 /*vp->func = NULL; - ckzalloc did it */
2198 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2205 * Set the value of a variable. The flags argument is ored with the
2206 * flags of the variable. If val is NULL, the variable is unset.
2209 setvar(const char *name, const char *val, int flags)
2217 q = endofname(name);
2218 p = strchrnul(q, '=');
2220 if (!namelen || p != q)
2221 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2226 vallen = strlen(val);
2230 nameeq = ckmalloc(namelen + vallen + 2);
2231 p = memcpy(nameeq, name, namelen) + namelen;
2234 p = memcpy(p, val, vallen) + vallen;
2237 setvareq(nameeq, flags | VNOSAVE);
2241 static void FAST_FUNC
2242 setvar2(const char *name, const char *val)
2244 setvar(name, val, 0);
2247 #if ENABLE_ASH_GETOPTS
2249 * Safe version of setvar, returns 1 on success 0 on failure.
2252 setvarsafe(const char *name, const char *val, int flags)
2255 volatile int saveint;
2256 struct jmploc *volatile savehandler = exception_handler;
2257 struct jmploc jmploc;
2260 if (setjmp(jmploc.loc))
2263 exception_handler = &jmploc;
2264 setvar(name, val, flags);
2267 exception_handler = savehandler;
2268 RESTORE_INT(saveint);
2274 * Unset the specified variable.
2277 unsetvar(const char *s)
2283 vpp = findvar(hashvar(s), s);
2287 int flags = vp->flags;
2290 if (flags & VREADONLY)
2292 #if ENABLE_ASH_RANDOM_SUPPORT
2293 vp->flags &= ~VDYNAMIC;
2297 if ((flags & VSTRFIXED) == 0) {
2299 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2300 free((char*)vp->var_text);
2306 vp->flags &= ~VEXPORT;
2316 * Process a linked list of variable assignments.
2319 listsetvar(struct strlist *list_set_var, int flags)
2321 struct strlist *lp = list_set_var;
2327 setvareq(lp->text, flags);
2334 * Generate a list of variables satisfying the given conditions.
2337 listvars(int on, int off, char ***end)
2348 for (vp = *vpp; vp; vp = vp->next) {
2349 if ((vp->flags & mask) == on) {
2350 if (ep == stackstrend())
2351 ep = growstackstr();
2352 *ep++ = (char*)vp->var_text;
2355 } while (++vpp < vartab + VTABSIZE);
2356 if (ep == stackstrend())
2357 ep = growstackstr();
2361 return grabstackstr(ep);
2365 /* ============ Path search helper
2367 * The variable path (passed by reference) should be set to the start
2368 * of the path before the first call; path_advance will update
2369 * this value as it proceeds. Successive calls to path_advance will return
2370 * the possible path expansions in sequence. If an option (indicated by
2371 * a percent sign) appears in the path entry then the global variable
2372 * pathopt will be set to point to it; otherwise pathopt will be set to
2375 static const char *pathopt; /* set by path_advance */
2378 path_advance(const char **path, const char *name)
2388 for (p = start; *p && *p != ':' && *p != '%'; p++)
2390 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2391 while (stackblocksize() < len)
2395 memcpy(q, start, p - start);
2403 while (*p && *p != ':')
2410 return stalloc(len);
2414 /* ============ Prompt */
2416 static smallint doprompt; /* if set, prompt the user */
2417 static smallint needprompt; /* true if interactive and at start of line */
2419 #if ENABLE_FEATURE_EDITING
2420 static line_input_t *line_input_state;
2421 static const char *cmdedit_prompt;
2423 putprompt(const char *s)
2425 if (ENABLE_ASH_EXPAND_PRMT) {
2426 free((char*)cmdedit_prompt);
2427 cmdedit_prompt = ckstrdup(s);
2434 putprompt(const char *s)
2440 #if ENABLE_ASH_EXPAND_PRMT
2441 /* expandstr() needs parsing machinery, so it is far away ahead... */
2442 static const char *expandstr(const char *ps);
2444 #define expandstr(s) s
2448 setprompt_if(smallint do_set, int whichprompt)
2451 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2458 switch (whichprompt) {
2468 #if ENABLE_ASH_EXPAND_PRMT
2469 setstackmark(&smark);
2470 stalloc(stackblocksize());
2472 putprompt(expandstr(prompt));
2473 #if ENABLE_ASH_EXPAND_PRMT
2474 popstackmark(&smark);
2479 /* ============ The cd and pwd commands */
2481 #define CD_PHYSICAL 1
2491 while ((i = nextopt("LP")) != '\0') {
2493 flags ^= CD_PHYSICAL;
2502 * Update curdir (the name of the current directory) in response to a
2506 updatepwd(const char *dir)
2513 cdcomppath = ststrdup(dir);
2516 if (curdir == nullstr)
2518 new = stack_putstr(curdir, new);
2520 new = makestrspace(strlen(dir) + 2, new);
2521 lim = (char *)stackblock() + 1;
2525 if (new > lim && *lim == '/')
2530 if (dir[1] == '/' && dir[2] != '/') {
2536 p = strtok(cdcomppath, "/");
2540 if (p[1] == '.' && p[2] == '\0') {
2552 new = stack_putstr(p, new);
2560 return stackblock();
2564 * Find out what the current directory is. If we already know the current
2565 * directory, this routine returns immediately.
2570 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2571 return dir ? dir : nullstr;
2575 setpwd(const char *val, int setold)
2579 oldcur = dir = curdir;
2582 setvar("OLDPWD", oldcur, VEXPORT);
2585 if (physdir != nullstr) {
2586 if (physdir != oldcur)
2590 if (oldcur == val || !val) {
2596 dir = ckstrdup(val);
2597 if (oldcur != dir && oldcur != nullstr) {
2602 setvar("PWD", dir, VEXPORT);
2605 static void hashcd(void);
2608 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2609 * know that the current directory has changed.
2612 docd(const char *dest, int flags)
2614 const char *dir = NULL;
2617 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2620 if (!(flags & CD_PHYSICAL)) {
2621 dir = updatepwd(dest);
2635 static int FAST_FUNC
2636 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2648 dest = bltinlookup("HOME");
2649 else if (LONE_DASH(dest)) {
2650 dest = bltinlookup("OLDPWD");
2672 path = bltinlookup("CDPATH");
2681 p = path_advance(&path, dest);
2682 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2686 if (!docd(p, flags))
2691 ash_msg_and_raise_error("can't cd to %s", dest);
2694 if (flags & CD_PRINT)
2695 out1fmt("%s\n", curdir);
2699 static int FAST_FUNC
2700 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2703 const char *dir = curdir;
2707 if (physdir == nullstr)
2711 out1fmt("%s\n", dir);
2716 /* ============ ... */
2719 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2721 /* Syntax classes */
2722 #define CWORD 0 /* character is nothing special */
2723 #define CNL 1 /* newline character */
2724 #define CBACK 2 /* a backslash character */
2725 #define CSQUOTE 3 /* single quote */
2726 #define CDQUOTE 4 /* double quote */
2727 #define CENDQUOTE 5 /* a terminating quote */
2728 #define CBQUOTE 6 /* backwards single quote */
2729 #define CVAR 7 /* a dollar sign */
2730 #define CENDVAR 8 /* a '}' character */
2731 #define CLP 9 /* a left paren in arithmetic */
2732 #define CRP 10 /* a right paren in arithmetic */
2733 #define CENDFILE 11 /* end of file */
2734 #define CCTL 12 /* like CWORD, except it must be escaped */
2735 #define CSPCL 13 /* these terminate a word */
2736 #define CIGN 14 /* character should be ignored */
2739 #if ENABLE_ASH_ALIAS
2743 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2745 #if ENABLE_SH_MATH_SUPPORT
2746 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2748 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2750 static const uint16_t S_I_T[] = {
2751 #if ENABLE_ASH_ALIAS
2752 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2754 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2755 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2756 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2757 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2758 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2759 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2760 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2761 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2762 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2763 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2764 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2765 #if !USE_SIT_FUNCTION
2766 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2767 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2768 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2772 /* Constants below must match table above */
2774 #if ENABLE_ASH_ALIAS
2775 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2777 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2778 CNL_CNL_CNL_CNL , /* 2 */
2779 CWORD_CCTL_CCTL_CWORD , /* 3 */
2780 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2781 CVAR_CVAR_CWORD_CVAR , /* 5 */
2782 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2783 CSPCL_CWORD_CWORD_CLP , /* 7 */
2784 CSPCL_CWORD_CWORD_CRP , /* 8 */
2785 CBACK_CBACK_CCTL_CBACK , /* 9 */
2786 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2787 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2788 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2789 CWORD_CWORD_CWORD_CWORD , /* 13 */
2790 CCTL_CCTL_CCTL_CCTL , /* 14 */
2793 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2794 * caller must ensure proper cast on it if c is *char_ptr!
2796 /* Values for syntax param */
2797 #define BASESYNTAX 0 /* not in quotes */
2798 #define DQSYNTAX 1 /* in double quotes */
2799 #define SQSYNTAX 2 /* in single quotes */
2800 #define ARISYNTAX 3 /* in arithmetic */
2801 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2803 #if USE_SIT_FUNCTION
2806 SIT(int c, int syntax)
2808 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2809 # if ENABLE_ASH_ALIAS
2810 static const uint8_t syntax_index_table[] ALIGN1 = {
2811 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2812 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2813 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2817 static const uint8_t syntax_index_table[] ALIGN1 = {
2818 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2819 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2820 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2829 # if ENABLE_ASH_ALIAS
2835 /* Cast is purely for paranoia here,
2836 * just in case someone passed signed char to us */
2837 if ((unsigned char)c >= CTL_FIRST
2838 && (unsigned char)c <= CTL_LAST
2842 s = strchrnul(spec_symbls, c);
2845 indx = syntax_index_table[s - spec_symbls];
2847 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2850 #else /* !USE_SIT_FUNCTION */
2852 static const uint8_t syntax_index_table[] = {
2853 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2854 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2864 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2865 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2887 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2888 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2889 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2890 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2891 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2893 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2894 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2895 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2896 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2897 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2899 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2900 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2901 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2902 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2904 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2905 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2913 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2914 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2915 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2916 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2917 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2918 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2946 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2947 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2948 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2951 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2979 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2980 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2981 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2982 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2984 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2985 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2986 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2987 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2988 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2989 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2990 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2991 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3110 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3111 # if ENABLE_ASH_ALIAS
3112 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3116 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3118 #endif /* !USE_SIT_FUNCTION */
3121 /* ============ Alias handling */
3123 #if ENABLE_ASH_ALIAS
3125 #define ALIASINUSE 1
3136 static struct alias **atab; // [ATABSIZE];
3137 #define INIT_G_alias() do { \
3138 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3142 static struct alias **
3143 __lookupalias(const char *name) {
3144 unsigned int hashval;
3151 ch = (unsigned char)*p;
3155 ch = (unsigned char)*++p;
3157 app = &atab[hashval % ATABSIZE];
3159 for (; *app; app = &(*app)->next) {
3160 if (strcmp(name, (*app)->name) == 0) {
3168 static struct alias *
3169 lookupalias(const char *name, int check)
3171 struct alias *ap = *__lookupalias(name);
3173 if (check && ap && (ap->flag & ALIASINUSE))
3178 static struct alias *
3179 freealias(struct alias *ap)
3183 if (ap->flag & ALIASINUSE) {
3184 ap->flag |= ALIASDEAD;
3196 setalias(const char *name, const char *val)
3198 struct alias *ap, **app;
3200 app = __lookupalias(name);
3204 if (!(ap->flag & ALIASINUSE)) {
3207 ap->val = ckstrdup(val);
3208 ap->flag &= ~ALIASDEAD;
3211 ap = ckzalloc(sizeof(struct alias));
3212 ap->name = ckstrdup(name);
3213 ap->val = ckstrdup(val);
3214 /*ap->flag = 0; - ckzalloc did it */
3215 /*ap->next = NULL;*/
3222 unalias(const char *name)
3226 app = __lookupalias(name);
3230 *app = freealias(*app);
3241 struct alias *ap, **app;
3245 for (i = 0; i < ATABSIZE; i++) {
3247 for (ap = *app; ap; ap = *app) {
3248 *app = freealias(*app);
3258 printalias(const struct alias *ap)
3260 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3264 * TODO - sort output
3266 static int FAST_FUNC
3267 aliascmd(int argc UNUSED_PARAM, char **argv)
3276 for (i = 0; i < ATABSIZE; i++) {
3277 for (ap = atab[i]; ap; ap = ap->next) {
3283 while ((n = *++argv) != NULL) {
3284 v = strchr(n+1, '=');
3285 if (v == NULL) { /* n+1: funny ksh stuff */
3286 ap = *__lookupalias(n);
3288 fprintf(stderr, "%s: %s not found\n", "alias", n);
3301 static int FAST_FUNC
3302 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3306 while ((i = nextopt("a")) != '\0') {
3312 for (i = 0; *argptr; argptr++) {
3313 if (unalias(*argptr)) {
3314 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3322 #endif /* ASH_ALIAS */
3325 /* ============ jobs.c */
3327 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3330 #define FORK_NOJOB 2
3332 /* mode flags for showjob(s) */
3333 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3334 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3335 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3338 * A job structure contains information about a job. A job is either a
3339 * single process or a set of processes contained in a pipeline. In the
3340 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3344 pid_t ps_pid; /* process id */
3345 int ps_status; /* last process status from wait() */
3346 char *ps_cmd; /* text of command being run */
3350 struct procstat ps0; /* status of process */
3351 struct procstat *ps; /* status or processes when more than one */
3353 int stopstatus; /* status of a stopped job */
3356 nprocs: 16, /* number of processes */
3358 #define JOBRUNNING 0 /* at least one proc running */
3359 #define JOBSTOPPED 1 /* all procs are stopped */
3360 #define JOBDONE 2 /* all procs are completed */
3362 sigint: 1, /* job was killed by SIGINT */
3363 jobctl: 1, /* job running under job control */
3365 waited: 1, /* true if this entry has been waited for */
3366 used: 1, /* true if this entry is in used */
3367 changed: 1; /* true if status has changed */
3368 struct job *prev_job; /* previous job */
3371 static struct job *makejob(/*union node *,*/ int);
3372 static int forkshell(struct job *, union node *, int);
3373 static int waitforjob(struct job *);
3376 enum { doing_jobctl = 0 };
3377 #define setjobctl(on) do {} while (0)
3379 static smallint doing_jobctl; //references:8
3380 static void setjobctl(int);
3387 ignoresig(int signo)
3389 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3390 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3391 /* No, need to do it */
3392 signal(signo, SIG_IGN);
3394 sigmode[signo - 1] = S_HARD_IGN;
3398 * Only one usage site - in setsignal()
3401 signal_handler(int signo)
3403 gotsig[signo - 1] = 1;
3405 if (signo == SIGINT && !trap[SIGINT]) {
3406 if (!suppress_int) {
3408 raise_interrupt(); /* does not return */
3412 pending_sig = signo;
3417 * Set the signal handler for the specified signal. The routine figures
3418 * out what it should be set to.
3421 setsignal(int signo)
3424 char cur_act, new_act;
3425 struct sigaction act;
3429 if (t != NULL) { /* trap for this sig is set */
3431 if (t[0] == '\0') /* trap is "": ignore this sig */
3435 if (rootshell && new_act == S_DFL) {
3438 if (iflag || minusc || sflag == 0)
3447 * "In all cases, bash ignores SIGQUIT. Non-builtin
3448 * commands run by bash have signal handlers
3449 * set to the values inherited by the shell
3450 * from its parent". */
3466 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3467 //whereas we have to restore it to what shell got on entry
3468 //from the parent. See comment above
3470 t = &sigmode[signo - 1];
3473 /* current setting is not yet known */
3474 if (sigaction(signo, NULL, &act)) {
3475 /* pretend it worked; maybe we should give a warning,
3476 * but other shells don't. We don't alter sigmode,
3477 * so we retry every time.
3478 * btw, in Linux it never fails. --vda */
3481 if (act.sa_handler == SIG_IGN) {
3482 cur_act = S_HARD_IGN;
3484 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3486 cur_act = S_IGN; /* don't hard ignore these */
3490 if (cur_act == S_HARD_IGN || cur_act == new_act)
3493 act.sa_handler = SIG_DFL;
3496 act.sa_handler = signal_handler;
3497 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3498 sigfillset(&act.sa_mask); /* ditto */
3501 act.sa_handler = SIG_IGN;
3504 sigaction_set(signo, &act);
3509 /* mode flags for set_curjob */
3510 #define CUR_DELETE 2
3511 #define CUR_RUNNING 1
3512 #define CUR_STOPPED 0
3514 /* mode flags for dowait */
3515 #define DOWAIT_NONBLOCK WNOHANG
3516 #define DOWAIT_BLOCK 0
3519 /* pgrp of shell on invocation */
3520 static int initialpgrp; //references:2
3521 static int ttyfd = -1; //5
3524 static struct job *jobtab; //5
3526 static unsigned njobs; //4
3528 static struct job *curjob; //lots
3529 /* number of presumed living untracked jobs */
3530 static int jobless; //4
3533 set_curjob(struct job *jp, unsigned mode)
3536 struct job **jpp, **curp;
3538 /* first remove from list */
3539 jpp = curp = &curjob;
3544 jpp = &jp1->prev_job;
3546 *jpp = jp1->prev_job;
3548 /* Then re-insert in correct position */
3556 /* job being deleted */
3559 /* newly created job or backgrounded job,
3560 put after all stopped jobs. */
3564 if (!jp1 || jp1->state != JOBSTOPPED)
3567 jpp = &jp1->prev_job;
3573 /* newly stopped job - becomes curjob */
3574 jp->prev_job = *jpp;
3582 jobno(const struct job *jp)
3584 return jp - jobtab + 1;
3589 * Convert a job name to a job structure.
3592 #define getjob(name, getctl) getjob(name)
3595 getjob(const char *name, int getctl)
3599 const char *err_msg = "%s: no such job";
3603 char *(*match)(const char *, const char *);
3618 if (c == '+' || c == '%') {
3620 err_msg = "No current job";
3626 err_msg = "No previous job";
3637 jp = jobtab + num - 1;
3652 if (match(jp->ps[0].ps_cmd, p)) {
3656 err_msg = "%s: ambiguous";
3666 err_msg = "job %s not created under job control";
3667 if (getctl && jp->jobctl == 0)
3672 ash_msg_and_raise_error(err_msg, name);
3676 * Mark a job structure as unused.
3679 freejob(struct job *jp)
3681 struct procstat *ps;
3685 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3686 if (ps->ps_cmd != nullstr)
3689 if (jp->ps != &jp->ps0)
3692 set_curjob(jp, CUR_DELETE);
3698 xtcsetpgrp(int fd, pid_t pgrp)
3700 if (tcsetpgrp(fd, pgrp))
3701 ash_msg_and_raise_error("can't set tty process group (%m)");
3705 * Turn job control on and off.
3707 * Note: This code assumes that the third arg to ioctl is a character
3708 * pointer, which is true on Berkeley systems but not System V. Since
3709 * System V doesn't have job control yet, this isn't a problem now.
3711 * Called with interrupts off.
3719 if (on == doing_jobctl || rootshell == 0)
3723 ofd = fd = open(_PATH_TTY, O_RDWR);
3725 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3726 * That sometimes helps to acquire controlling tty.
3727 * Obviously, a workaround for bugs when someone
3728 * failed to provide a controlling tty to bash! :) */
3734 fd = fcntl(fd, F_DUPFD, 10);
3739 /* fd is a tty at this point */
3740 close_on_exec_on(fd);
3741 do { /* while we are in the background */
3742 pgrp = tcgetpgrp(fd);
3745 ash_msg("can't access tty; job control turned off");
3749 if (pgrp == getpgrp())
3760 xtcsetpgrp(fd, pgrp);
3762 /* turning job control off */
3765 /* was xtcsetpgrp, but this can make exiting ash
3766 * loop forever if pty is already deleted */
3767 tcsetpgrp(fd, pgrp);
3781 static int FAST_FUNC
3782 killcmd(int argc, char **argv)
3785 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3787 if (argv[i][0] == '%') {
3788 struct job *jp = getjob(argv[i], 0);
3789 unsigned pid = jp->ps[0].ps_pid;
3790 /* Enough space for ' -NNN<nul>' */
3791 argv[i] = alloca(sizeof(int)*3 + 3);
3792 /* kill_main has matching code to expect
3793 * leading space. Needed to not confuse
3794 * negative pids with "kill -SIGNAL_NO" syntax */
3795 sprintf(argv[i], " -%u", pid);
3797 } while (argv[++i]);
3799 return kill_main(argc, argv);
3803 showpipe(struct job *jp /*, FILE *out*/)
3805 struct procstat *ps;
3806 struct procstat *psend;
3808 psend = jp->ps + jp->nprocs;
3809 for (ps = jp->ps + 1; ps < psend; ps++)
3810 printf(" | %s", ps->ps_cmd);
3811 outcslow('\n', stdout);
3812 flush_stdout_stderr();
3817 restartjob(struct job *jp, int mode)
3819 struct procstat *ps;
3825 if (jp->state == JOBDONE)
3827 jp->state = JOBRUNNING;
3828 pgid = jp->ps[0].ps_pid;
3829 if (mode == FORK_FG)
3830 xtcsetpgrp(ttyfd, pgid);
3831 killpg(pgid, SIGCONT);
3835 if (WIFSTOPPED(ps->ps_status)) {
3841 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3846 static int FAST_FUNC
3847 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3853 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3857 jp = getjob(*argv, 1);
3858 if (mode == FORK_BG) {
3859 set_curjob(jp, CUR_RUNNING);
3860 printf("[%d] ", jobno(jp));
3862 out1str(jp->ps[0].ps_cmd);
3863 showpipe(jp /*, stdout*/);
3864 retval = restartjob(jp, mode);
3865 } while (*argv && *++argv);
3871 sprint_status(char *s, int status, int sigonly)
3877 if (!WIFEXITED(status)) {
3879 if (WIFSTOPPED(status))
3880 st = WSTOPSIG(status);
3883 st = WTERMSIG(status);
3885 if (st == SIGINT || st == SIGPIPE)
3888 if (WIFSTOPPED(status))
3893 col = fmtstr(s, 32, strsignal(st));
3894 if (WCOREDUMP(status)) {
3895 col += fmtstr(s + col, 16, " (core dumped)");
3897 } else if (!sigonly) {
3898 st = WEXITSTATUS(status);
3900 col = fmtstr(s, 16, "Done(%d)", st);
3902 col = fmtstr(s, 16, "Done");
3909 dowait(int wait_flags, struct job *job)
3914 struct job *thisjob;
3917 TRACE(("dowait(0x%x) called\n", wait_flags));
3919 /* Do a wait system call. If job control is compiled in, we accept
3920 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3921 * NB: _not_ safe_waitpid, we need to detect EINTR */
3923 wait_flags |= WUNTRACED;
3924 pid = waitpid(-1, &status, wait_flags);
3925 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3926 pid, status, errno, strerror(errno)));
3932 for (jp = curjob; jp; jp = jp->prev_job) {
3933 struct procstat *ps;
3934 struct procstat *psend;
3935 if (jp->state == JOBDONE)
3939 psend = ps + jp->nprocs;
3941 if (ps->ps_pid == pid) {
3942 TRACE(("Job %d: changing status of proc %d "
3943 "from 0x%x to 0x%x\n",
3944 jobno(jp), pid, ps->ps_status, status));
3945 ps->ps_status = status;
3948 if (ps->ps_status == -1)
3951 if (state == JOBRUNNING)
3953 if (WIFSTOPPED(ps->ps_status)) {
3954 jp->stopstatus = ps->ps_status;
3958 } while (++ps < psend);
3963 if (!WIFSTOPPED(status))
3969 if (state != JOBRUNNING) {
3970 thisjob->changed = 1;
3972 if (thisjob->state != state) {
3973 TRACE(("Job %d: changing state from %d to %d\n",
3974 jobno(thisjob), thisjob->state, state));
3975 thisjob->state = state;
3977 if (state == JOBSTOPPED) {
3978 set_curjob(thisjob, CUR_STOPPED);
3987 if (thisjob && thisjob == job) {
3991 len = sprint_status(s, status, 1);
4002 blocking_wait_with_raise_on_sig(void)
4004 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4005 if (pid <= 0 && pending_sig)
4006 raise_exception(EXSIG);
4012 showjob(FILE *out, struct job *jp, int mode)
4014 struct procstat *ps;
4015 struct procstat *psend;
4022 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4023 /* just output process (group) id of pipeline */
4024 fprintf(out, "%d\n", ps->ps_pid);
4028 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4033 else if (curjob && jp == curjob->prev_job)
4036 if (mode & SHOW_PIDS)
4037 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4039 psend = ps + jp->nprocs;
4041 if (jp->state == JOBRUNNING) {
4042 strcpy(s + col, "Running");
4043 col += sizeof("Running") - 1;
4045 int status = psend[-1].ps_status;
4046 if (jp->state == JOBSTOPPED)
4047 status = jp->stopstatus;
4048 col += sprint_status(s + col, status, 0);
4050 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4052 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4053 * or prints several "PID | <cmdN>" lines,
4054 * depending on SHOW_PIDS bit.
4055 * We do not print status of individual processes
4056 * between PID and <cmdN>. bash does it, but not very well:
4057 * first line shows overall job status, not process status,
4058 * making it impossible to know 1st process status.
4062 /* for each process */
4065 if (mode & SHOW_PIDS)
4066 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4068 fprintf(out, "%s%*c%s%s",
4070 33 - col >= 0 ? 33 - col : 0, ' ',
4071 ps == jp->ps ? "" : "| ",
4074 } while (++ps != psend);
4075 outcslow('\n', out);
4079 if (jp->state == JOBDONE) {
4080 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4086 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4087 * statuses have changed since the last call to showjobs.
4090 showjobs(FILE *out, int mode)
4094 TRACE(("showjobs(0x%x) called\n", mode));
4096 /* Handle all finished jobs */
4097 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4100 for (jp = curjob; jp; jp = jp->prev_job) {
4101 if (!(mode & SHOW_CHANGED) || jp->changed) {
4102 showjob(out, jp, mode);
4107 static int FAST_FUNC
4108 jobscmd(int argc UNUSED_PARAM, char **argv)
4113 while ((m = nextopt("lp")) != '\0') {
4117 mode |= SHOW_ONLY_PGID;
4123 showjob(stdout, getjob(*argv, 0), mode);
4126 showjobs(stdout, mode);
4133 /* Called only on finished or stopped jobs (no members are running) */
4135 getstatus(struct job *job)
4139 struct procstat *ps;
4141 /* Fetch last member's status */
4142 ps = job->ps + job->nprocs - 1;
4143 status = ps->ps_status;
4145 /* "set -o pipefail" mode: use last _nonzero_ status */
4146 while (status == 0 && --ps >= job->ps)
4147 status = ps->ps_status;
4150 retval = WEXITSTATUS(status);
4151 if (!WIFEXITED(status)) {
4153 retval = WSTOPSIG(status);
4154 if (!WIFSTOPPED(status))
4157 /* XXX: limits number of signals */
4158 retval = WTERMSIG(status);
4160 if (retval == SIGINT)
4166 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4167 jobno(job), job->nprocs, status, retval));
4171 static int FAST_FUNC
4172 waitcmd(int argc UNUSED_PARAM, char **argv)
4179 raise_exception(EXSIG);
4186 /* wait for all jobs */
4190 if (!jp) /* no running procs */
4192 if (jp->state == JOBRUNNING)
4197 blocking_wait_with_raise_on_sig();
4199 * "When bash is waiting for an asynchronous command via
4200 * the wait builtin, the reception of a signal for which a trap
4201 * has been set will cause the wait builtin to return immediately
4202 * with an exit status greater than 128, immediately after which
4203 * the trap is executed."
4205 * blocking_wait_with_raise_on_sig raises signal handlers
4206 * if it gets no pid (pid < 0). However,
4207 * if child sends us a signal *and immediately exits*,
4208 * blocking_wait_with_raise_on_sig gets pid > 0
4209 * and does not handle pending_sig. Check this case: */
4211 raise_exception(EXSIG);
4217 if (**argv != '%') {
4218 pid_t pid = number(*argv);
4223 if (job->ps[job->nprocs - 1].ps_pid == pid)
4225 job = job->prev_job;
4228 job = getjob(*argv, 0);
4229 /* loop until process terminated or stopped */
4230 while (job->state == JOBRUNNING)
4231 blocking_wait_with_raise_on_sig();
4233 retval = getstatus(job);
4246 struct job *jp, *jq;
4248 len = njobs * sizeof(*jp);
4250 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4252 offset = (char *)jp - (char *)jq;
4254 /* Relocate pointers */
4257 jq = (struct job *)((char *)jq + l);
4261 #define joff(p) ((struct job *)((char *)(p) + l))
4262 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4263 if (joff(jp)->ps == &jq->ps0)
4264 jmove(joff(jp)->ps);
4265 if (joff(jp)->prev_job)
4266 jmove(joff(jp)->prev_job);
4276 jp = (struct job *)((char *)jp + len);
4280 } while (--jq >= jp);
4285 * Return a new job structure.
4286 * Called with interrupts off.
4289 makejob(/*union node *node,*/ int nprocs)
4294 for (i = njobs, jp = jobtab; ; jp++) {
4301 if (jp->state != JOBDONE || !jp->waited)
4310 memset(jp, 0, sizeof(*jp));
4312 /* jp->jobctl is a bitfield.
4313 * "jp->jobctl |= jobctl" likely to give awful code */
4317 jp->prev_job = curjob;
4322 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4324 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4331 * Return a string identifying a command (to be printed by the
4334 static char *cmdnextc;
4337 cmdputs(const char *s)
4339 static const char vstype[VSTYPE + 1][3] = {
4340 "", "}", "-", "+", "?", "=",
4341 "%", "%%", "#", "##"
4342 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4345 const char *p, *str;
4349 unsigned char subtype = 0;
4353 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4355 while ((c = *p++) != '\0') {
4363 if ((subtype & VSTYPE) == VSLENGTH)
4367 if (!(subtype & VSQUOTE) == !(quoted & 1))
4373 str = "\"}" + !(quoted & 1);
4380 case CTLBACKQ+CTLQUOTE:
4383 #if ENABLE_SH_MATH_SUPPORT
4398 if ((subtype & VSTYPE) != VSNORMAL)
4400 str = vstype[subtype & VSTYPE];
4401 if (subtype & VSNUL)
4410 /* These can only happen inside quotes */
4423 while ((c = *str++) != '\0') {
4426 } /* while *p++ not NUL */
4429 USTPUTC('"', nextc);
4435 /* cmdtxt() and cmdlist() call each other */
4436 static void cmdtxt(union node *n);
4439 cmdlist(union node *np, int sep)
4441 for (; np; np = np->narg.next) {
4445 if (sep && np->narg.next)
4451 cmdtxt(union node *n)
4454 struct nodelist *lp;
4465 lp = n->npipe.cmdlist;
4483 cmdtxt(n->nbinary.ch1);
4499 cmdtxt(n->nif.test);
4501 if (n->nif.elsepart) {
4502 cmdtxt(n->nif.ifpart);
4504 n = n->nif.elsepart;
4522 cmdtxt(n->nbinary.ch1);
4532 cmdputs(n->nfor.var);
4534 cmdlist(n->nfor.args, 1);
4539 cmdputs(n->narg.text);
4543 cmdlist(n->ncmd.args, 1);
4544 cmdlist(n->ncmd.redirect, 0);
4557 cmdputs(n->ncase.expr->narg.text);
4559 for (np = n->ncase.cases; np; np = np->nclist.next) {
4560 cmdtxt(np->nclist.pattern);
4562 cmdtxt(np->nclist.body);
4576 #if ENABLE_ASH_BASH_COMPAT
4591 cmdputs(utoa(n->nfile.fd));
4593 if (n->type == NTOFD || n->type == NFROMFD) {
4594 cmdputs(utoa(n->ndup.dupfd));
4603 commandtext(union node *n)
4607 STARTSTACKSTR(cmdnextc);
4609 name = stackblock();
4610 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4611 name, cmdnextc, cmdnextc));
4612 return ckstrdup(name);
4617 * Fork off a subshell. If we are doing job control, give the subshell its
4618 * own process group. Jp is a job structure that the job is to be added to.
4619 * N is the command that will be evaluated by the child. Both jp and n may
4620 * be NULL. The mode parameter can be one of the following:
4621 * FORK_FG - Fork off a foreground process.
4622 * FORK_BG - Fork off a background process.
4623 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4624 * process group even if job control is on.
4626 * When job control is turned off, background processes have their standard
4627 * input redirected to /dev/null (except for the second and later processes
4630 * Called with interrupts off.
4633 * Clear traps on a fork.
4640 for (tp = trap; tp < &trap[NSIG]; tp++) {
4641 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4643 if (trap_ptr == trap)
4645 /* else: it "belongs" to trap_ptr vector, don't free */
4647 if ((tp - trap) != 0)
4648 setsignal(tp - trap);
4655 /* Lives far away from here, needed for forkchild */
4656 static void closescript(void);
4658 /* Called after fork(), in child */
4659 static NOINLINE void
4660 forkchild(struct job *jp, union node *n, int mode)
4664 TRACE(("Child shell %d\n", getpid()));
4668 /* man bash: "Non-builtin commands run by bash have signal handlers
4669 * set to the values inherited by the shell from its parent".
4670 * Do we do it correctly? */
4674 if (mode == FORK_NOJOB /* is it `xxx` ? */
4675 && n && n->type == NCMD /* is it single cmd? */
4676 /* && n->ncmd.args->type == NARG - always true? */
4677 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4678 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4679 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4681 TRACE(("Trap hack\n"));
4682 /* Awful hack for `trap` or $(trap).
4684 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4685 * contains an example where "trap" is executed in a subshell:
4687 * save_traps=$(trap)
4689 * eval "$save_traps"
4691 * Standard does not say that "trap" in subshell shall print
4692 * parent shell's traps. It only says that its output
4693 * must have suitable form, but then, in the above example
4694 * (which is not supposed to be normative), it implies that.
4696 * bash (and probably other shell) does implement it
4697 * (traps are reset to defaults, but "trap" still shows them),
4698 * but as a result, "trap" logic is hopelessly messed up:
4701 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4702 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4703 * # true | trap <--- trap is in subshell - no output (ditto)
4704 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4705 * trap -- 'echo Ho' SIGWINCH
4706 * # echo `(trap)` <--- in subshell in subshell - output
4707 * trap -- 'echo Ho' SIGWINCH
4708 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4709 * trap -- 'echo Ho' SIGWINCH
4711 * The rules when to forget and when to not forget traps
4712 * get really complex and nonsensical.
4714 * Our solution: ONLY bare $(trap) or `trap` is special.
4716 /* Save trap handler strings for trap builtin to print */
4717 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4718 /* Fall through into clearing traps */
4722 /* do job control only in root shell */
4724 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4727 if (jp->nprocs == 0)
4730 pgrp = jp->ps[0].ps_pid;
4731 /* this can fail because we are doing it in the parent also */
4733 if (mode == FORK_FG)
4734 xtcsetpgrp(ttyfd, pgrp);
4739 if (mode == FORK_BG) {
4740 /* man bash: "When job control is not in effect,
4741 * asynchronous commands ignore SIGINT and SIGQUIT" */
4744 if (jp->nprocs == 0) {
4746 if (open(bb_dev_null, O_RDONLY) != 0)
4747 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4751 if (iflag) { /* why if iflag only? */
4756 * "In all cases, bash ignores SIGQUIT. Non-builtin
4757 * commands run by bash have signal handlers
4758 * set to the values inherited by the shell
4760 * Take care of the second rule: */
4764 if (n && n->type == NCMD
4765 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4767 TRACE(("Job hack\n"));
4768 /* "jobs": we do not want to clear job list for it,
4769 * instead we remove only _its_ own_ job from job list.
4770 * This makes "jobs .... | cat" more useful.
4776 for (jp = curjob; jp; jp = jp->prev_job)
4781 /* Called after fork(), in parent */
4783 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4786 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4788 TRACE(("In parent shell: child = %d\n", pid));
4790 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4796 if (mode != FORK_NOJOB && jp->jobctl) {
4799 if (jp->nprocs == 0)
4802 pgrp = jp->ps[0].ps_pid;
4803 /* This can fail because we are doing it in the child also */
4807 if (mode == FORK_BG) {
4808 backgndpid = pid; /* set $! */
4809 set_curjob(jp, CUR_RUNNING);
4812 struct procstat *ps = &jp->ps[jp->nprocs++];
4815 ps->ps_cmd = nullstr;
4817 if (doing_jobctl && n)
4818 ps->ps_cmd = commandtext(n);
4824 forkshell(struct job *jp, union node *n, int mode)
4828 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4831 TRACE(("Fork failed, errno=%d", errno));
4834 ash_msg_and_raise_error("can't fork");
4837 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4838 forkchild(jp, n, mode);
4840 forkparent(jp, n, mode, pid);
4846 * Wait for job to finish.
4848 * Under job control we have the problem that while a child process
4849 * is running interrupts generated by the user are sent to the child
4850 * but not to the shell. This means that an infinite loop started by
4851 * an interactive user may be hard to kill. With job control turned off,
4852 * an interactive user may place an interactive program inside a loop.
4853 * If the interactive program catches interrupts, the user doesn't want
4854 * these interrupts to also abort the loop. The approach we take here
4855 * is to have the shell ignore interrupt signals while waiting for a
4856 * foreground process to terminate, and then send itself an interrupt
4857 * signal if the child process was terminated by an interrupt signal.
4858 * Unfortunately, some programs want to do a bit of cleanup and then
4859 * exit on interrupt; unless these processes terminate themselves by
4860 * sending a signal to themselves (instead of calling exit) they will
4861 * confuse this approach.
4863 * Called with interrupts off.
4866 waitforjob(struct job *jp)
4870 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4873 while (jp->state == JOBRUNNING) {
4874 /* In non-interactive shells, we _can_ get
4875 * a keyboard signal here and be EINTRed,
4876 * but we just loop back, waiting for command to complete.
4879 * "If bash is waiting for a command to complete and receives
4880 * a signal for which a trap has been set, the trap
4881 * will not be executed until the command completes."
4883 * Reality is that even if trap is not set, bash
4884 * will not act on the signal until command completes.
4885 * Try this. sleep5intoff.c:
4886 * #include <signal.h>
4887 * #include <unistd.h>
4890 * sigemptyset(&set);
4891 * sigaddset(&set, SIGINT);
4892 * sigaddset(&set, SIGQUIT);
4893 * sigprocmask(SIG_BLOCK, &set, NULL);
4897 * $ bash -c './sleep5intoff; echo hi'
4898 * ^C^C^C^C <--- pressing ^C once a second
4900 * $ bash -c './sleep5intoff; echo hi'
4901 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4904 dowait(DOWAIT_BLOCK, jp);
4911 xtcsetpgrp(ttyfd, rootpid);
4913 * This is truly gross.
4914 * If we're doing job control, then we did a TIOCSPGRP which
4915 * caused us (the shell) to no longer be in the controlling
4916 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4917 * intuit from the subprocess exit status whether a SIGINT
4918 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4920 if (jp->sigint) /* TODO: do the same with all signals */
4921 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4923 if (jp->state == JOBDONE)
4930 * return 1 if there are stopped jobs, otherwise 0
4942 if (jp && jp->state == JOBSTOPPED) {
4943 out2str("You have stopped jobs.\n");
4952 /* ============ redir.c
4954 * Code for dealing with input/output redirection.
4959 #define EMPTY -2 /* marks an unused slot in redirtab */
4960 #define CLOSED -3 /* marks a slot of previously-closed fd */
4963 * Open a file in noclobber mode.
4964 * The code was copied from bash.
4967 noclobberopen(const char *fname)
4970 struct stat finfo, finfo2;
4973 * If the file exists and is a regular file, return an error
4976 r = stat(fname, &finfo);
4977 if (r == 0 && S_ISREG(finfo.st_mode)) {
4983 * If the file was not present (r != 0), make sure we open it
4984 * exclusively so that if it is created before we open it, our open
4985 * will fail. Make sure that we do not truncate an existing file.
4986 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4987 * file was not a regular file, we leave O_EXCL off.
4990 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4991 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4993 /* If the open failed, return the file descriptor right away. */
4998 * OK, the open succeeded, but the file may have been changed from a
4999 * non-regular file to a regular file between the stat and the open.
5000 * We are assuming that the O_EXCL open handles the case where FILENAME
5001 * did not exist and is symlinked to an existing file between the stat
5006 * If we can open it and fstat the file descriptor, and neither check
5007 * revealed that it was a regular file, and the file has not been
5008 * replaced, return the file descriptor.
5010 if (fstat(fd, &finfo2) == 0
5011 && !S_ISREG(finfo2.st_mode)
5012 && finfo.st_dev == finfo2.st_dev
5013 && finfo.st_ino == finfo2.st_ino
5018 /* The file has been replaced. badness. */
5025 * Handle here documents. Normally we fork off a process to write the
5026 * data to a pipe. If the document is short, we can stuff the data in
5027 * the pipe without forking.
5029 /* openhere needs this forward reference */
5030 static void expandhere(union node *arg, int fd);
5032 openhere(union node *redir)
5038 ash_msg_and_raise_error("pipe call failed");
5039 if (redir->type == NHERE) {
5040 len = strlen(redir->nhere.doc->narg.text);
5041 if (len <= PIPE_BUF) {
5042 full_write(pip[1], redir->nhere.doc->narg.text, len);
5046 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5049 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5050 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5051 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5052 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5053 signal(SIGPIPE, SIG_DFL);
5054 if (redir->type == NHERE)
5055 full_write(pip[1], redir->nhere.doc->narg.text, len);
5057 expandhere(redir->nhere.doc, pip[1]);
5058 _exit(EXIT_SUCCESS);
5066 openredirect(union node *redir)
5071 switch (redir->nfile.type) {
5073 fname = redir->nfile.expfname;
5074 f = open(fname, O_RDONLY);
5079 fname = redir->nfile.expfname;
5080 f = open(fname, O_RDWR|O_CREAT, 0666);
5085 #if ENABLE_ASH_BASH_COMPAT
5088 /* Take care of noclobber mode. */
5090 fname = redir->nfile.expfname;
5091 f = noclobberopen(fname);
5098 fname = redir->nfile.expfname;
5099 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5104 fname = redir->nfile.expfname;
5105 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5113 /* Fall through to eliminate warning. */
5114 /* Our single caller does this itself */
5121 f = openhere(redir);
5127 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5129 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5133 * Copy a file descriptor to be >= to. Returns -1
5134 * if the source file descriptor is closed, EMPTY if there are no unused
5135 * file descriptors left.
5137 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5138 * old code was doing close(to) prior to copyfd() to achieve the same */
5140 COPYFD_EXACT = (int)~(INT_MAX),
5141 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5144 copyfd(int from, int to)
5148 if (to & COPYFD_EXACT) {
5149 to &= ~COPYFD_EXACT;
5151 newfd = dup2(from, to);
5153 newfd = fcntl(from, F_DUPFD, to);
5156 if (errno == EMFILE)
5158 /* Happens when source fd is not open: try "echo >&99" */
5159 ash_msg_and_raise_error("%d: %m", from);
5164 /* Struct def and variable are moved down to the first usage site */
5169 struct redirtab *next;
5172 struct two_fd_t two_fd[];
5174 #define redirlist (G_var.redirlist)
5176 static int need_to_remember(struct redirtab *rp, int fd)
5180 if (!rp) /* remembering was not requested */
5183 for (i = 0; i < rp->pair_count; i++) {
5184 if (rp->two_fd[i].orig == fd) {
5185 /* already remembered */
5192 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5193 static int is_hidden_fd(struct redirtab *rp, int fd)
5196 struct parsefile *pf;
5200 /* Check open scripts' fds */
5203 /* We skip pf_fd == 0 case because of the following case:
5204 * $ ash # running ash interactively
5206 * and in script.sh: "exec 9>&0".
5207 * Even though top-level pf_fd _is_ 0,
5208 * it's still ok to use it: "read" builtin uses it,
5209 * why should we cripple "exec" builtin?
5211 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5219 /* Check saved fds of redirects */
5220 fd |= COPYFD_RESTORE;
5221 for (i = 0; i < rp->pair_count; i++) {
5222 if (rp->two_fd[i].copy == fd) {
5230 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5231 * old file descriptors are stashed away so that the redirection can be
5232 * undone by calling popredir.
5234 /* flags passed to redirect */
5235 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5236 #define REDIR_SAVEFD2 03 /* set preverrout */
5238 redirect(union node *redir, int flags)
5240 struct redirtab *sv;
5245 int copied_fd2 = -1;
5255 if (flags & REDIR_PUSH) {
5256 union node *tmp = redir;
5259 #if ENABLE_ASH_BASH_COMPAT
5260 if (tmp->nfile.type == NTO2)
5263 tmp = tmp->nfile.next;
5265 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5266 sv->next = redirlist;
5267 sv->pair_count = sv_pos;
5269 sv->nullredirs = g_nullredirs - 1;
5271 while (sv_pos > 0) {
5273 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5279 fd = redir->nfile.fd;
5280 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5281 right_fd = redir->ndup.dupfd;
5282 //bb_error_msg("doing %d > %d", fd, right_fd);
5283 /* redirect from/to same file descriptor? */
5286 /* "echo >&10" and 10 is a fd opened to a sh script? */
5287 if (is_hidden_fd(sv, right_fd)) {
5288 errno = EBADF; /* as if it is closed */
5289 ash_msg_and_raise_error("%d: %m", right_fd);
5293 newfd = openredirect(redir); /* always >= 0 */
5295 /* Descriptor wasn't open before redirect.
5296 * Mark it for close in the future */
5297 if (need_to_remember(sv, fd)) {
5298 goto remember_to_close;
5303 #if ENABLE_ASH_BASH_COMPAT
5306 if (need_to_remember(sv, fd)) {
5307 /* Copy old descriptor */
5308 /* Careful to not accidentally "save"
5309 * to the same fd as right side fd in N>&M */
5310 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5311 i = fcntl(fd, F_DUPFD, minfd);
5312 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5313 * are closed in popredir() in the child, preventing them from leaking
5314 * into child. (popredir() also cleans up the mess in case of failures)
5319 /* Strange error (e.g. "too many files" EMFILE?) */
5323 ash_msg_and_raise_error("%d: %m", fd);
5326 /* EBADF: it is not open - good, remember to close it */
5329 } else { /* fd is open, save its copy */
5330 /* "exec fd>&-" should not close fds
5331 * which point to script file(s).
5332 * Force them to be restored afterwards */
5333 if (is_hidden_fd(sv, fd))
5334 i |= COPYFD_RESTORE;
5338 sv->two_fd[sv_pos].orig = fd;
5339 sv->two_fd[sv_pos].copy = i;
5343 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5344 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5345 /* Don't want to trigger debugging */
5349 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5351 } else if (fd != newfd) { /* move newfd to fd */
5352 copyfd(newfd, fd | COPYFD_EXACT);
5353 #if ENABLE_ASH_BASH_COMPAT
5354 if (!(redir->nfile.type == NTO2 && fd == 2))
5358 #if ENABLE_ASH_BASH_COMPAT
5359 if (redir->nfile.type == NTO2 && fd == 1) {
5360 /* We already redirected it to fd 1, now copy it to 2 */
5366 } while ((redir = redir->nfile.next) != NULL);
5369 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5370 preverrout_fd = copied_fd2;
5374 * Undo the effects of the last redirection.
5377 popredir(int drop, int restore)
5379 struct redirtab *rp;
5382 if (--g_nullredirs >= 0)
5386 for (i = 0; i < rp->pair_count; i++) {
5387 int fd = rp->two_fd[i].orig;
5388 int copy = rp->two_fd[i].copy;
5389 if (copy == CLOSED) {
5394 if (copy != EMPTY) {
5395 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5396 copy &= ~COPYFD_RESTORE;
5398 copyfd(copy, fd | COPYFD_EXACT);
5400 close(copy & ~COPYFD_RESTORE);
5403 redirlist = rp->next;
5404 g_nullredirs = rp->nullredirs;
5410 * Undo all redirections. Called on error or interrupt.
5414 * Discard all saved file descriptors.
5417 clearredir(int drop)
5423 popredir(drop, /*restore:*/ 0);
5428 redirectsafe(union node *redir, int flags)
5431 volatile int saveint;
5432 struct jmploc *volatile savehandler = exception_handler;
5433 struct jmploc jmploc;
5436 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5437 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5439 exception_handler = &jmploc;
5440 redirect(redir, flags);
5442 exception_handler = savehandler;
5443 if (err && exception_type != EXERROR)
5444 longjmp(exception_handler->loc, 1);
5445 RESTORE_INT(saveint);
5450 /* ============ Routines to expand arguments to commands
5452 * We have to deal with backquotes, shell variables, and file metacharacters.
5455 #if ENABLE_SH_MATH_SUPPORT
5457 ash_arith(const char *s)
5459 arith_state_t math_state;
5462 math_state.lookupvar = lookupvar;
5463 math_state.setvar = setvar2;
5464 //math_state.endofname = endofname;
5467 result = arith(&math_state, s);
5468 if (math_state.errmsg)
5469 ash_msg_and_raise_error(math_state.errmsg);
5479 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5480 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5481 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5482 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5483 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5484 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5485 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5486 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5487 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5491 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5492 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5493 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5494 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5495 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5498 * Structure specifying which parts of the string should be searched
5499 * for IFS characters.
5502 struct ifsregion *next; /* next region in list */
5503 int begoff; /* offset of start of region */
5504 int endoff; /* offset of end of region */
5505 int nulonly; /* search for nul bytes only */
5509 struct strlist *list;
5510 struct strlist **lastp;
5513 /* output of current string */
5514 static char *expdest;
5515 /* list of back quote expressions */
5516 static struct nodelist *argbackq;
5517 /* first struct in list of ifs regions */
5518 static struct ifsregion ifsfirst;
5519 /* last struct in list */
5520 static struct ifsregion *ifslastp;
5521 /* holds expanded arg list */
5522 static struct arglist exparg;
5527 #if !ENABLE_SH_MATH_SUPPORT
5528 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5529 typedef long arith_t;
5530 # define ARITH_FMT "%ld"
5537 expdest = makestrspace(32, expdest);
5538 len = fmtstr(expdest, 32, ARITH_FMT, num);
5539 STADJUST(len, expdest);
5544 esclen(const char *start, const char *p)
5548 while (p > start && (unsigned char)*--p == CTLESC) {
5555 * Remove any CTLESC characters from a string.
5558 rmescapes(char *str, int flag)
5560 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5564 unsigned protect_against_glob;
5567 p = strpbrk(str, qchars);
5573 if (flag & RMESCAPE_ALLOC) {
5574 size_t len = p - str;
5575 size_t fulllen = len + strlen(p) + 1;
5577 if (flag & RMESCAPE_GROW) {
5578 int strloc = str - (char *)stackblock();
5579 r = makestrspace(fulllen, expdest);
5580 /* p and str may be invalidated by makestrspace */
5581 str = (char *)stackblock() + strloc;
5583 } else if (flag & RMESCAPE_HEAP) {
5584 r = ckmalloc(fulllen);
5586 r = stalloc(fulllen);
5590 q = (char *)memcpy(q, str, len) + len;
5594 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5595 globbing = flag & RMESCAPE_GLOB;
5596 protect_against_glob = globbing;
5598 if ((unsigned char)*p == CTLQUOTEMARK) {
5599 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5600 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5601 // Note: both inquotes and protect_against_glob only affect whether
5602 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5603 inquotes = ~inquotes;
5605 protect_against_glob = globbing;
5609 /* naked back slash */
5610 protect_against_glob = 0;
5613 if ((unsigned char)*p == CTLESC) {
5615 if (protect_against_glob && inquotes && *p != '/') {
5619 protect_against_glob = globbing;
5624 if (flag & RMESCAPE_GROW) {
5626 STADJUST(q - r + 1, expdest);
5630 #define pmatch(a, b) !fnmatch((a), (b), 0)
5633 * Prepare a pattern for a expmeta (internal glob(3)) call.
5635 * Returns an stalloced string.
5638 preglob(const char *pattern, int quoted, int flag)
5640 flag |= RMESCAPE_GLOB;
5642 flag |= RMESCAPE_QUOTED;
5644 return rmescapes((char *)pattern, flag);
5648 * Put a string on the stack.
5651 memtodest(const char *p, size_t len, int syntax, int quotes)
5655 q = makestrspace(quotes ? len * 2 : len, q);
5658 unsigned char c = *p++;
5662 int n = SIT(c, syntax);
5663 if (n == CCTL || n == CBACK)
5673 strtodest(const char *p, int syntax, int quotes)
5675 memtodest(p, strlen(p), syntax, quotes);
5679 * Record the fact that we have to scan this region of the
5680 * string for IFS characters.
5683 recordregion(int start, int end, int nulonly)
5685 struct ifsregion *ifsp;
5687 if (ifslastp == NULL) {
5691 ifsp = ckzalloc(sizeof(*ifsp));
5692 /*ifsp->next = NULL; - ckzalloc did it */
5693 ifslastp->next = ifsp;
5697 ifslastp->begoff = start;
5698 ifslastp->endoff = end;
5699 ifslastp->nulonly = nulonly;
5703 removerecordregions(int endoff)
5705 if (ifslastp == NULL)
5708 if (ifsfirst.endoff > endoff) {
5709 while (ifsfirst.next) {
5710 struct ifsregion *ifsp;
5712 ifsp = ifsfirst.next->next;
5713 free(ifsfirst.next);
5714 ifsfirst.next = ifsp;
5717 if (ifsfirst.begoff > endoff) {
5720 ifslastp = &ifsfirst;
5721 ifsfirst.endoff = endoff;
5726 ifslastp = &ifsfirst;
5727 while (ifslastp->next && ifslastp->next->begoff < endoff)
5728 ifslastp = ifslastp->next;
5729 while (ifslastp->next) {
5730 struct ifsregion *ifsp;
5732 ifsp = ifslastp->next->next;
5733 free(ifslastp->next);
5734 ifslastp->next = ifsp;
5737 if (ifslastp->endoff > endoff)
5738 ifslastp->endoff = endoff;
5742 exptilde(char *startp, char *p, int flags)
5748 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5753 while ((c = *++p) != '\0') {
5760 if (flags & EXP_VARTILDE)
5770 if (*name == '\0') {
5771 home = lookupvar("HOME");
5773 pw = getpwnam(name);
5778 if (!home || !*home)
5781 startloc = expdest - (char *)stackblock();
5782 strtodest(home, SQSYNTAX, quotes);
5783 recordregion(startloc, expdest - (char *)stackblock(), 0);
5791 * Execute a command inside back quotes. If it's a builtin command, we
5792 * want to save its output in a block obtained from malloc. Otherwise
5793 * we fork off a subprocess and get the output of the command via a pipe.
5794 * Should be called with interrupts off.
5796 struct backcmd { /* result of evalbackcmd */
5797 int fd; /* file descriptor to read from */
5798 int nleft; /* number of chars in buffer */
5799 char *buf; /* buffer */
5800 struct job *jp; /* job structure for command */
5803 /* These forward decls are needed to use "eval" code for backticks handling: */
5804 static uint8_t back_exitstatus; /* exit status of backquoted command */
5805 #define EV_EXIT 01 /* exit after evaluating tree */
5806 static void evaltree(union node *, int);
5808 static void FAST_FUNC
5809 evalbackcmd(union node *n, struct backcmd *result)
5820 saveherefd = herefd;
5828 ash_msg_and_raise_error("pipe call failed");
5829 jp = makejob(/*n,*/ 1);
5830 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5835 copyfd(pip[1], 1 | COPYFD_EXACT);
5839 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5843 result->fd = pip[0];
5846 herefd = saveherefd;
5848 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5849 result->fd, result->buf, result->nleft, result->jp));
5853 * Expand stuff in backwards quotes.
5856 expbackq(union node *cmd, int quoted, int quotes)
5864 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5865 struct stackmark smark;
5868 setstackmark(&smark);
5870 startloc = dest - (char *)stackblock();
5872 evalbackcmd(cmd, &in);
5873 popstackmark(&smark);
5880 memtodest(p, i, syntax, quotes);
5884 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5885 TRACE(("expbackq: read returns %d\n", i));
5894 back_exitstatus = waitforjob(in.jp);
5898 /* Eat all trailing newlines */
5900 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5905 recordregion(startloc, dest - (char *)stackblock(), 0);
5906 TRACE(("evalbackq: size:%d:'%.*s'\n",
5907 (int)((dest - (char *)stackblock()) - startloc),
5908 (int)((dest - (char *)stackblock()) - startloc),
5909 stackblock() + startloc));
5912 #if ENABLE_SH_MATH_SUPPORT
5914 * Expand arithmetic expression. Backup to start of expression,
5915 * evaluate, place result in (backed up) result, adjust string position.
5928 * This routine is slightly over-complicated for
5929 * efficiency. Next we scan backwards looking for the
5930 * start of arithmetic.
5932 start = stackblock();
5939 while ((unsigned char)*p != CTLARI) {
5943 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5948 esc = esclen(start, p);
5958 removerecordregions(begoff);
5965 rmescapes(p + 2, 0);
5967 len = cvtnum(ash_arith(p + 2));
5970 recordregion(begoff, begoff + len, 0);
5974 /* argstr needs it */
5975 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5978 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5979 * characters to allow for further processing. Otherwise treat
5980 * $@ like $* since no splitting will be performed.
5982 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5983 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5984 * for correct expansion of "B=$A" word.
5987 argstr(char *p, int flags, struct strlist *var_str_list)
5989 static const char spclchars[] ALIGN1 = {
5997 CTLBACKQ | CTLQUOTE,
5998 #if ENABLE_SH_MATH_SUPPORT
6003 const char *reject = spclchars;
6004 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
6005 int breakall = flags & EXP_WORD;
6010 if (!(flags & EXP_VARTILDE)) {
6012 } else if (flags & EXP_VARTILDE2) {
6017 if (flags & EXP_TILDE) {
6020 flags &= ~EXP_TILDE;
6023 if ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
6026 p = exptilde(p, q, flags);
6029 startloc = expdest - (char *)stackblock();
6033 length += strcspn(p + length, reject);
6037 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6039 /* c == '=' || c == ':' || c == CTLENDARI */
6045 expdest = stack_nputstr(p, length, expdest);
6046 newloc = expdest - (char *)stackblock();
6047 if (breakall && !inquotes && newloc > startloc) {
6048 recordregion(startloc, newloc, 0);
6059 if (flags & EXP_VARTILDE2) {
6063 flags |= EXP_VARTILDE2;
6068 * sort of a hack - expand tildes in variable
6069 * assignments (after the first '=' and after ':'s).
6078 case CTLENDVAR: /* ??? */
6081 /* "$@" syntax adherence hack */
6083 && memcmp(p, dolatstr, 4) == 0
6084 && ( p[4] == (char)CTLQUOTEMARK
6085 || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
6088 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
6091 inquotes = !inquotes;
6104 p = evalvar(p, flags, var_str_list);
6108 case CTLBACKQ|CTLQUOTE:
6109 expbackq(argbackq->n, c, quotes);
6110 argbackq = argbackq->next;
6112 #if ENABLE_SH_MATH_SUPPORT
6124 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6125 char *pattern, int quotes, int zero)
6134 const char *s = loc2;
6141 match = pmatch(pattern, s);
6146 if (quotes && (unsigned char)*loc == CTLESC)
6155 scanright(char *startp, char *rmesc, char *rmescend,
6156 char *pattern, int quotes, int match_at_start)
6158 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6159 int try2optimize = match_at_start;
6165 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6166 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6167 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6169 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6170 * and on each iteration they go back two/one char until they reach the beginning.
6171 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6173 /* TODO: document in what other circumstances we are called. */
6175 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6178 const char *s = loc2;
6179 if (match_at_start) {
6183 match = pmatch(pattern, s);
6184 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6188 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6190 /* Maybe we can optimize this:
6191 * if pattern ends with unescaped *, we can avoid checking
6192 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6193 * it wont match truncated "raw_value_of_" strings too.
6195 unsigned plen = strlen(pattern);
6196 /* Does it end with "*"? */
6197 if (plen != 0 && pattern[--plen] == '*') {
6198 /* "xxxx*" is not escaped */
6199 /* "xxx\*" is escaped */
6200 /* "xx\\*" is not escaped */
6201 /* "x\\\*" is escaped */
6203 while (plen != 0 && pattern[--plen] == '\\')
6206 break; /* ends with unescaped "*" */
6214 esc = esclen(startp, loc);
6225 static void varunset(const char *, const char *, const char *, int) NORETURN;
6227 varunset(const char *end, const char *var, const char *umsg, int varflags)
6233 msg = "parameter not set";
6235 if ((unsigned char)*end == CTLENDVAR) {
6236 if (varflags & VSNUL)
6242 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6245 #if ENABLE_ASH_BASH_COMPAT
6247 parse_sub_pattern(char *arg, int varflags)
6249 char *idx, *repl = NULL;
6252 //char *org_arg = arg;
6253 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
6260 /* Only the first '/' seen is our separator */
6269 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6270 * The result is a_\_z_c (not a\_\_z_c)!
6272 * Enable debug prints in this function and you'll see:
6273 * ash: arg:'\\b/_\\_z_' varflags:d
6274 * ash: pattern:'\\b' repl:'_\_z_'
6275 * That is, \\b is interpreted as \\b, but \\_ as \_!
6276 * IOW: search pattern and replace string treat backslashes
6277 * differently! That is the reason why we check repl below:
6279 if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
6280 arg++; /* skip both '\', not just first one */
6283 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
6287 #endif /* ENABLE_ASH_BASH_COMPAT */
6290 subevalvar(char *p, char *varname, int strloc, int subtype,
6291 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6293 struct nodelist *saveargbackq = argbackq;
6296 char *rmesc, *rmescend;
6298 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
6299 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6300 int saveherefd = herefd;
6301 int amount, workloc, resetloc;
6303 char *(*scan)(char*, char*, char*, char*, int, int);
6305 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6306 // p, varname, strloc, subtype, startloc, varflags, quotes);
6309 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6311 STPUTC('\0', expdest);
6312 herefd = saveherefd;
6313 argbackq = saveargbackq;
6314 startp = (char *)stackblock() + startloc;
6318 setvar(varname, startp, 0);
6319 amount = startp - expdest;
6320 STADJUST(amount, expdest);
6324 varunset(p, varname, startp, varflags);
6327 #if ENABLE_ASH_BASH_COMPAT
6329 loc = str = stackblock() + strloc;
6330 /* Read POS in ${var:POS:LEN} */
6331 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6332 len = str - startp - 1;
6334 /* *loc != '\0', guaranteed by parser */
6338 /* Adjust the length by the number of escapes */
6339 for (ptr = startp; ptr < (str - 1); ptr++) {
6340 if ((unsigned char)*ptr == CTLESC) {
6348 if (*loc++ == ':') {
6352 /* Skip POS in ${var:POS:LEN} */
6354 while (*loc && *loc != ':') {
6356 * bash complains on: var=qwe; echo ${var:1a:123}
6358 ash_msg_and_raise_error(msg_illnum, str);
6362 if (*loc++ == ':') {
6366 if (pos >= orig_len) {
6370 if (len > (orig_len - pos))
6371 len = orig_len - pos;
6373 for (str = startp; pos; str++, pos--) {
6374 if (quotes && (unsigned char)*str == CTLESC)
6377 for (loc = startp; len; len--) {
6378 if (quotes && (unsigned char)*str == CTLESC)
6383 amount = loc - expdest;
6384 STADJUST(amount, expdest);
6389 resetloc = expdest - (char *)stackblock();
6391 /* We'll comeback here if we grow the stack while handling
6392 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6393 * stack will need rebasing, and we'll need to remove our work
6396 IF_ASH_BASH_COMPAT(restart:)
6398 amount = expdest - ((char *)stackblock() + resetloc);
6399 STADJUST(-amount, expdest);
6400 startp = (char *)stackblock() + startloc;
6403 rmescend = (char *)stackblock() + strloc;
6405 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6406 if (rmesc != startp) {
6408 startp = (char *)stackblock() + startloc;
6412 str = (char *)stackblock() + strloc;
6413 preglob(str, varflags & VSQUOTE, 0);
6414 workloc = expdest - (char *)stackblock();
6416 #if ENABLE_ASH_BASH_COMPAT
6417 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6421 repl = parse_sub_pattern(str, varflags);
6422 //bb_error_msg("repl:'%s'", repl);
6427 /* If there's no pattern to match, return the expansion unmolested */
6436 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6437 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6439 /* No match, advance */
6440 char *restart_detect = stackblock();
6442 STPUTC(*idx, expdest);
6443 if (quotes && (unsigned char)*idx == CTLESC) {
6446 STPUTC(*idx, expdest);
6448 if (stackblock() != restart_detect)
6453 /* continue; - prone to quadratic behavior, smarter code: */
6456 if (str[0] == '*') {
6457 /* Pattern is "*foo". If "*foo" does not match "long_string",
6458 * it would never match "ong_string" etc, no point in trying.
6465 if (subtype == VSREPLACEALL) {
6467 if (quotes && (unsigned char)*idx == CTLESC)
6476 //bb_error_msg("repl:'%s'", repl);
6477 for (loc = (char*)repl; *loc; loc++) {
6478 char *restart_detect = stackblock();
6479 if (quotes && *loc == '\\') {
6480 STPUTC(CTLESC, expdest);
6483 STPUTC(*loc, expdest);
6484 if (stackblock() != restart_detect)
6489 if (subtype == VSREPLACE) {
6490 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6492 char *restart_detect = stackblock();
6493 STPUTC(*idx, expdest);
6494 if (stackblock() != restart_detect)
6503 /* We've put the replaced text into a buffer at workloc, now
6504 * move it to the right place and adjust the stack.
6506 STPUTC('\0', expdest);
6507 startp = (char *)stackblock() + startloc;
6508 memmove(startp, (char *)stackblock() + workloc, len + 1);
6509 //bb_error_msg("startp:'%s'", startp);
6510 amount = expdest - (startp + len);
6511 STADJUST(-amount, expdest);
6514 #endif /* ENABLE_ASH_BASH_COMPAT */
6516 subtype -= VSTRIMRIGHT;
6518 if (subtype < 0 || subtype > 7)
6521 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6522 zero = subtype >> 1;
6523 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6524 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6526 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6529 memmove(startp, loc, str - loc);
6530 loc = startp + (str - loc) - 1;
6533 amount = loc - expdest;
6534 STADJUST(amount, expdest);
6540 * Add the value of a specialized variable to the stack string.
6541 * name parameter (examples):
6542 * ash -c 'echo $1' name:'1='
6543 * ash -c 'echo $qwe' name:'qwe='
6544 * ash -c 'echo $$' name:'$='
6545 * ash -c 'echo ${$}' name:'$='
6546 * ash -c 'echo ${$##q}' name:'$=q'
6547 * ash -c 'echo ${#$}' name:'$='
6548 * note: examples with bad shell syntax:
6549 * ash -c 'echo ${#$1}' name:'$=1'
6550 * ash -c 'echo ${#1#}' name:'1=#'
6552 static NOINLINE ssize_t
6553 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6560 int subtype = varflags & VSTYPE;
6561 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6562 int quoted = varflags & VSQUOTE;
6563 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6573 num = shellparam.nparam;
6581 goto check_1char_name;
6583 expdest = makestrspace(NOPTS, expdest);
6584 for (i = NOPTS - 1; i >= 0; i--) {
6586 USTPUTC(optletters(i), expdest);
6592 /* handles cases similar to ${#$1} */
6593 if (name[2] != '\0')
6594 raise_error_syntax("bad substitution");
6601 if (quoted && (flags & EXP_FULL)) {
6602 /* note: this is not meant as PEOF value */
6603 sep = 1 << CHAR_BIT;
6608 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6609 i = SIT(sep, syntax);
6610 if (quotes && (i == CCTL || i == CBACK))
6616 while ((p = *ap++) != NULL) {
6619 partlen = strlen(p);
6622 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6623 memtodest(p, partlen, syntax, quotes);
6629 if (subtype == VSPLUS || subtype == VSLENGTH) {
6635 /* note: may put NUL despite sep != 0
6636 * (see sep = 1 << CHAR_BIT above) */
6642 } /* case '@' and '*' */
6653 num = atoi(name); /* number(name) fails on ${N#str} etc */
6654 if (num < 0 || num > shellparam.nparam)
6656 p = num ? shellparam.p[num - 1] : arg0;
6659 /* NB: name has form "VAR=..." */
6661 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6662 * which should be considered before we check variables. */
6664 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6668 str = var_str_list->text;
6669 eq = strchr(str, '=');
6670 if (!eq) /* stop at first non-assignment */
6673 if (name_len == (unsigned)(eq - str)
6674 && strncmp(str, name, name_len) == 0
6677 /* goto value; - WRONG! */
6678 /* think "A=1 A=2 B=$A" */
6680 var_str_list = var_str_list->next;
6681 } while (var_str_list);
6685 p = lookupvar(name);
6691 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6692 memtodest(p, len, syntax, quotes);
6696 if (subtype == VSPLUS || subtype == VSLENGTH)
6697 STADJUST(-len, expdest);
6702 * Expand a variable, and return a pointer to the next character in the
6706 evalvar(char *p, int flags, struct strlist *var_str_list)
6717 varflags = (unsigned char) *p++;
6718 subtype = varflags & VSTYPE;
6719 quoted = varflags & VSQUOTE;
6721 easy = (!quoted || (*var == '@' && shellparam.nparam));
6722 startloc = expdest - (char *)stackblock();
6723 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6726 varlen = varvalue(var, varflags, flags, var_str_list);
6727 if (varflags & VSNUL)
6730 if (subtype == VSPLUS) {
6731 varlen = -1 - varlen;
6735 if (subtype == VSMINUS) {
6740 flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
6750 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6752 if (subevalvar(p, var, /* strloc: */ 0,
6753 subtype, startloc, varflags,
6759 * Remove any recorded regions beyond
6762 removerecordregions(startloc);
6772 if (varlen < 0 && uflag)
6773 varunset(p, var, 0, 0);
6775 if (subtype == VSLENGTH) {
6776 cvtnum(varlen > 0 ? varlen : 0);
6780 if (subtype == VSNORMAL) {
6791 case VSTRIMRIGHTMAX:
6792 #if ENABLE_ASH_BASH_COMPAT
6805 * Terminate the string and start recording the pattern
6808 STPUTC('\0', expdest);
6809 patloc = expdest - (char *)stackblock();
6810 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6812 //TODO: | EXP_REDIR too? All other such places do it too
6813 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6816 int amount = expdest - (
6817 (char *)stackblock() + patloc - 1
6819 STADJUST(-amount, expdest);
6821 /* Remove any recorded regions beyond start of variable */
6822 removerecordregions(startloc);
6824 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6828 if (subtype != VSNORMAL) { /* skip to end of alternative */
6831 unsigned char c = *p++;
6834 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6836 argbackq = argbackq->next;
6837 } else if (c == CTLVAR) {
6838 if ((*p++ & VSTYPE) != VSNORMAL)
6840 } else if (c == CTLENDVAR) {
6850 * Break the argument string into pieces based upon IFS and add the
6851 * strings to the argument list. The regions of the string to be
6852 * searched for IFS characters have been stored by recordregion.
6855 ifsbreakup(char *string, struct arglist *arglist)
6857 struct ifsregion *ifsp;
6862 const char *ifs, *realifs;
6867 if (ifslastp != NULL) {
6870 realifs = ifsset() ? ifsval() : defifs;
6873 p = string + ifsp->begoff;
6874 nulonly = ifsp->nulonly;
6875 ifs = nulonly ? nullstr : realifs;
6877 while (p < string + ifsp->endoff) {
6879 if ((unsigned char)*p == CTLESC)
6881 if (!strchr(ifs, *p)) {
6886 ifsspc = (strchr(defifs, *p) != NULL);
6887 /* Ignore IFS whitespace at start */
6888 if (q == start && ifsspc) {
6894 sp = stzalloc(sizeof(*sp));
6896 *arglist->lastp = sp;
6897 arglist->lastp = &sp->next;
6901 if (p >= string + ifsp->endoff) {
6905 if ((unsigned char)*p == CTLESC)
6907 if (strchr(ifs, *p) == NULL) {
6911 if (strchr(defifs, *p) == NULL) {
6926 } while (ifsp != NULL);
6935 sp = stzalloc(sizeof(*sp));
6937 *arglist->lastp = sp;
6938 arglist->lastp = &sp->next;
6944 struct ifsregion *p;
6949 struct ifsregion *ifsp;
6955 ifsfirst.next = NULL;
6960 * Add a file name to the list.
6963 addfname(const char *name)
6967 sp = stzalloc(sizeof(*sp));
6968 sp->text = ststrdup(name);
6970 exparg.lastp = &sp->next;
6974 * Do metacharacter (i.e. *, ?, [...]) expansion.
6977 expmeta(char *expdir, char *enddir, char *name)
6992 for (p = name; *p; p++) {
6993 if (*p == '*' || *p == '?')
6995 else if (*p == '[') {
7002 if (*q == '/' || *q == '\0')
7009 } else if (*p == '\\')
7011 else if (*p == '/') {
7018 if (metaflag == 0) { /* we've reached the end of the file name */
7019 if (enddir != expdir)
7027 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7038 } while (p < start);
7040 if (enddir == expdir) {
7042 } else if (enddir == expdir + 1 && *expdir == '/') {
7051 if (enddir != expdir)
7053 if (*endname == 0) {
7065 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7066 if (dp->d_name[0] == '.' && !matchdot)
7068 if (pmatch(start, dp->d_name)) {
7070 strcpy(enddir, dp->d_name);
7073 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7076 expmeta(expdir, p, endname);
7085 static struct strlist *
7086 msort(struct strlist *list, int len)
7088 struct strlist *p, *q = NULL;
7089 struct strlist **lpp;
7097 for (n = half; --n >= 0;) {
7101 q->next = NULL; /* terminate first half of list */
7102 q = msort(list, half); /* sort first half of list */
7103 p = msort(p, len - half); /* sort second half */
7106 #if ENABLE_LOCALE_SUPPORT
7107 if (strcoll(p->text, q->text) < 0)
7109 if (strcmp(p->text, q->text) < 0)
7133 * Sort the results of file name expansion. It calculates the number of
7134 * strings to sort and then calls msort (short for merge sort) to do the
7137 static struct strlist *
7138 expsort(struct strlist *str)
7144 for (sp = str; sp; sp = sp->next)
7146 return msort(str, len);
7150 expandmeta(struct strlist *str /*, int flag*/)
7152 static const char metachars[] ALIGN1 = {
7155 /* TODO - EXP_REDIR */
7159 struct strlist **savelastp;
7165 if (!strpbrk(str->text, metachars))
7167 savelastp = exparg.lastp;
7170 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7172 int i = strlen(str->text);
7173 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7175 expmeta(expdir, expdir, p);
7180 if (exparg.lastp == savelastp) {
7185 *exparg.lastp = str;
7186 rmescapes(str->text, 0);
7187 exparg.lastp = &str->next;
7189 *exparg.lastp = NULL;
7190 *savelastp = sp = expsort(*savelastp);
7191 while (sp->next != NULL)
7193 exparg.lastp = &sp->next;
7200 * Perform variable substitution and command substitution on an argument,
7201 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7202 * perform splitting and file name expansion. When arglist is NULL, perform
7203 * here document expansion.
7206 expandarg(union node *arg, struct arglist *arglist, int flag)
7211 argbackq = arg->narg.backquote;
7212 STARTSTACKSTR(expdest);
7213 ifsfirst.next = NULL;
7215 argstr(arg->narg.text, flag,
7216 /* var_str_list: */ arglist ? arglist->list : NULL);
7217 p = _STPUTC('\0', expdest);
7219 if (arglist == NULL) {
7220 return; /* here document expanded */
7222 p = grabstackstr(p);
7223 exparg.lastp = &exparg.list;
7227 if (flag & EXP_FULL) {
7228 ifsbreakup(p, &exparg);
7229 *exparg.lastp = NULL;
7230 exparg.lastp = &exparg.list;
7231 expandmeta(exparg.list /*, flag*/);
7233 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7235 sp = stzalloc(sizeof(*sp));
7238 exparg.lastp = &sp->next;
7242 *exparg.lastp = NULL;
7244 *arglist->lastp = exparg.list;
7245 arglist->lastp = exparg.lastp;
7250 * Expand shell variables and backquotes inside a here document.
7253 expandhere(union node *arg, int fd)
7256 expandarg(arg, (struct arglist *)NULL, 0);
7257 full_write(fd, stackblock(), expdest - (char *)stackblock());
7261 * Returns true if the pattern matches the string.
7264 patmatch(char *pattern, const char *string)
7266 return pmatch(preglob(pattern, 0, 0), string);
7270 * See if a pattern matches in a case statement.
7273 casematch(union node *pattern, char *val)
7275 struct stackmark smark;
7278 setstackmark(&smark);
7279 argbackq = pattern->narg.backquote;
7280 STARTSTACKSTR(expdest);
7282 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7283 /* var_str_list: */ NULL);
7284 STACKSTRNUL(expdest);
7285 result = patmatch(stackblock(), val);
7286 popstackmark(&smark);
7291 /* ============ find_command */
7295 int (*builtin)(int, char **) FAST_FUNC;
7296 /* unsigned flags; */
7298 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7299 /* "regular" builtins always take precedence over commands,
7300 * regardless of PATH=....%builtin... position */
7301 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7302 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7305 smallint cmdtype; /* CMDxxx */
7308 /* index >= 0 for commands without path (slashes) */
7309 /* (TODO: what exactly does the value mean? PATH position?) */
7310 /* index == -1 for commands with slashes */
7311 /* index == (-2 - applet_no) for NOFORK applets */
7312 const struct builtincmd *cmd;
7313 struct funcnode *func;
7316 /* values of cmdtype */
7317 #define CMDUNKNOWN -1 /* no entry in table for command */
7318 #define CMDNORMAL 0 /* command is an executable program */
7319 #define CMDFUNCTION 1 /* command is a shell function */
7320 #define CMDBUILTIN 2 /* command is a shell builtin */
7322 /* action to find_command() */
7323 #define DO_ERR 0x01 /* prints errors */
7324 #define DO_ABS 0x02 /* checks absolute paths */
7325 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7326 #define DO_ALTPATH 0x08 /* using alternate path */
7327 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7329 static void find_command(char *, struct cmdentry *, int, const char *);
7332 /* ============ Hashing commands */
7335 * When commands are first encountered, they are entered in a hash table.
7336 * This ensures that a full path search will not have to be done for them
7337 * on each invocation.
7339 * We should investigate converting to a linear search, even though that
7340 * would make the command name "hash" a misnomer.
7344 struct tblentry *next; /* next entry in hash chain */
7345 union param param; /* definition of builtin function */
7346 smallint cmdtype; /* CMDxxx */
7347 char rehash; /* if set, cd done since entry created */
7348 char cmdname[1]; /* name of command */
7351 static struct tblentry **cmdtable;
7352 #define INIT_G_cmdtable() do { \
7353 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7356 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7360 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7364 #if ENABLE_FEATURE_SH_STANDALONE
7365 if (applet_no >= 0) {
7366 if (APPLET_IS_NOEXEC(applet_no)) {
7370 run_applet_no_and_exit(applet_no, argv);
7372 /* re-exec ourselves with the new arguments */
7373 execve(bb_busybox_exec_path, argv, envp);
7374 /* If they called chroot or otherwise made the binary no longer
7375 * executable, fall through */
7382 execve(cmd, argv, envp);
7383 } while (errno == EINTR);
7385 execve(cmd, argv, envp);
7391 if (errno == ENOEXEC) {
7395 for (ap = argv; *ap; ap++)
7397 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7399 ap[0] = cmd = (char *)DEFAULT_SHELL;
7402 while ((*ap++ = *argv++) != NULL)
7411 * Exec a program. Never returns. If you change this routine, you may
7412 * have to change the find_command routine as well.
7414 static void shellexec(char **, const char *, int) NORETURN;
7416 shellexec(char **argv, const char *path, int idx)
7422 #if ENABLE_FEATURE_SH_STANDALONE
7426 clearredir(/*drop:*/ 1);
7427 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7428 if (strchr(argv[0], '/') != NULL
7429 #if ENABLE_FEATURE_SH_STANDALONE
7430 || (applet_no = find_applet_by_name(argv[0])) >= 0
7433 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7437 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7438 if (--idx < 0 && pathopt == NULL) {
7439 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7440 if (errno != ENOENT && errno != ENOTDIR)
7447 /* Map to POSIX errors */
7459 exitstatus = exerrno;
7460 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7461 argv[0], e, suppress_int));
7462 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7467 printentry(struct tblentry *cmdp)
7473 idx = cmdp->param.index;
7476 name = path_advance(&path, cmdp->cmdname);
7478 } while (--idx >= 0);
7479 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7483 * Clear out command entries. The argument specifies the first entry in
7484 * PATH which has changed.
7487 clearcmdentry(int firstchange)
7489 struct tblentry **tblp;
7490 struct tblentry **pp;
7491 struct tblentry *cmdp;
7494 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7496 while ((cmdp = *pp) != NULL) {
7497 if ((cmdp->cmdtype == CMDNORMAL &&
7498 cmdp->param.index >= firstchange)
7499 || (cmdp->cmdtype == CMDBUILTIN &&
7500 builtinloc >= firstchange)
7513 * Locate a command in the command hash table. If "add" is nonzero,
7514 * add the command to the table if it is not already present. The
7515 * variable "lastcmdentry" is set to point to the address of the link
7516 * pointing to the entry, so that delete_cmd_entry can delete the
7519 * Interrupts must be off if called with add != 0.
7521 static struct tblentry **lastcmdentry;
7523 static struct tblentry *
7524 cmdlookup(const char *name, int add)
7526 unsigned int hashval;
7528 struct tblentry *cmdp;
7529 struct tblentry **pp;
7532 hashval = (unsigned char)*p << 4;
7534 hashval += (unsigned char)*p++;
7536 pp = &cmdtable[hashval % CMDTABLESIZE];
7537 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7538 if (strcmp(cmdp->cmdname, name) == 0)
7542 if (add && cmdp == NULL) {
7543 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7545 /* + 1 - already done because
7546 * tblentry::cmdname is char[1] */);
7547 /*cmdp->next = NULL; - ckzalloc did it */
7548 cmdp->cmdtype = CMDUNKNOWN;
7549 strcpy(cmdp->cmdname, name);
7556 * Delete the command entry returned on the last lookup.
7559 delete_cmd_entry(void)
7561 struct tblentry *cmdp;
7564 cmdp = *lastcmdentry;
7565 *lastcmdentry = cmdp->next;
7566 if (cmdp->cmdtype == CMDFUNCTION)
7567 freefunc(cmdp->param.func);
7573 * Add a new command entry, replacing any existing command entry for
7574 * the same name - except special builtins.
7577 addcmdentry(char *name, struct cmdentry *entry)
7579 struct tblentry *cmdp;
7581 cmdp = cmdlookup(name, 1);
7582 if (cmdp->cmdtype == CMDFUNCTION) {
7583 freefunc(cmdp->param.func);
7585 cmdp->cmdtype = entry->cmdtype;
7586 cmdp->param = entry->u;
7590 static int FAST_FUNC
7591 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7593 struct tblentry **pp;
7594 struct tblentry *cmdp;
7596 struct cmdentry entry;
7599 if (nextopt("r") != '\0') {
7604 if (*argptr == NULL) {
7605 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7606 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7607 if (cmdp->cmdtype == CMDNORMAL)
7615 while ((name = *argptr) != NULL) {
7616 cmdp = cmdlookup(name, 0);
7618 && (cmdp->cmdtype == CMDNORMAL
7619 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7623 find_command(name, &entry, DO_ERR, pathval());
7624 if (entry.cmdtype == CMDUNKNOWN)
7632 * Called when a cd is done. Marks all commands so the next time they
7633 * are executed they will be rehashed.
7638 struct tblentry **pp;
7639 struct tblentry *cmdp;
7641 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7642 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7643 if (cmdp->cmdtype == CMDNORMAL
7644 || (cmdp->cmdtype == CMDBUILTIN
7645 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7655 * Fix command hash table when PATH changed.
7656 * Called before PATH is changed. The argument is the new value of PATH;
7657 * pathval() still returns the old value at this point.
7658 * Called with interrupts off.
7660 static void FAST_FUNC
7661 changepath(const char *new)
7669 firstchange = 9999; /* assume no change */
7675 if ((*old == '\0' && *new == ':')
7676 || (*old == ':' && *new == '\0')
7680 old = new; /* ignore subsequent differences */
7684 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7691 if (builtinloc < 0 && idx_bltin >= 0)
7692 builtinloc = idx_bltin; /* zap builtins */
7693 if (builtinloc >= 0 && idx_bltin < 0)
7695 clearcmdentry(firstchange);
7696 builtinloc = idx_bltin;
7711 #define TENDBQUOTE 12
7728 typedef smallint token_id_t;
7730 /* first char is indicating which tokens mark the end of a list */
7731 static const char *const tokname_array[] = {
7745 #define KWDOFFSET 13
7746 /* the following are keywords */
7765 /* Wrapper around strcmp for qsort/bsearch/... */
7767 pstrcmp(const void *a, const void *b)
7769 return strcmp((char*) a, (*(char**) b) + 1);
7772 static const char *const *
7773 findkwd(const char *s)
7775 return bsearch(s, tokname_array + KWDOFFSET,
7776 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7777 sizeof(tokname_array[0]), pstrcmp);
7781 * Locate and print what a word is...
7784 describe_command(char *command, int describe_command_verbose)
7786 struct cmdentry entry;
7787 struct tblentry *cmdp;
7788 #if ENABLE_ASH_ALIAS
7789 const struct alias *ap;
7791 const char *path = pathval();
7793 if (describe_command_verbose) {
7797 /* First look at the keywords */
7798 if (findkwd(command)) {
7799 out1str(describe_command_verbose ? " is a shell keyword" : command);
7803 #if ENABLE_ASH_ALIAS
7804 /* Then look at the aliases */
7805 ap = lookupalias(command, 0);
7807 if (!describe_command_verbose) {
7812 out1fmt(" is an alias for %s", ap->val);
7816 /* Then check if it is a tracked alias */
7817 cmdp = cmdlookup(command, 0);
7819 entry.cmdtype = cmdp->cmdtype;
7820 entry.u = cmdp->param;
7822 /* Finally use brute force */
7823 find_command(command, &entry, DO_ABS, path);
7826 switch (entry.cmdtype) {
7828 int j = entry.u.index;
7834 p = path_advance(&path, command);
7838 if (describe_command_verbose) {
7840 (cmdp ? " a tracked alias for" : nullstr), p
7849 if (describe_command_verbose) {
7850 out1str(" is a shell function");
7857 if (describe_command_verbose) {
7858 out1fmt(" is a %sshell builtin",
7859 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7860 "special " : nullstr
7868 if (describe_command_verbose) {
7869 out1str(": not found\n");
7878 static int FAST_FUNC
7879 typecmd(int argc UNUSED_PARAM, char **argv)
7885 /* type -p ... ? (we don't bother checking for 'p') */
7886 if (argv[1] && argv[1][0] == '-') {
7891 err |= describe_command(argv[i++], verbose);
7896 #if ENABLE_ASH_CMDCMD
7897 static int FAST_FUNC
7898 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7906 while ((c = nextopt("pvV")) != '\0')
7908 verify |= VERIFY_VERBOSE;
7910 verify |= VERIFY_BRIEF;
7915 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7916 if (verify && (*argptr != NULL)) {
7917 return describe_command(*argptr, verify - VERIFY_BRIEF);
7925 /* ============ eval.c */
7927 static int funcblocksize; /* size of structures in function */
7928 static int funcstringsize; /* size of strings in node */
7929 static void *funcblock; /* block to allocate function from */
7930 static char *funcstring; /* block to allocate strings from */
7932 /* flags in argument to evaltree */
7933 #define EV_EXIT 01 /* exit after evaluating tree */
7934 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7935 #define EV_BACKCMD 04 /* command executing within back quotes */
7937 static const uint8_t nodesize[N_NUMBER] = {
7938 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7939 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7940 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7941 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7942 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7943 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7944 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7945 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7946 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7947 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7948 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7949 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7950 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7951 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7952 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7953 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7954 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7955 #if ENABLE_ASH_BASH_COMPAT
7956 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7958 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7959 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7960 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7961 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7962 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7963 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7964 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7965 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7966 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7969 static void calcsize(union node *n);
7972 sizenodelist(struct nodelist *lp)
7975 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7982 calcsize(union node *n)
7986 funcblocksize += nodesize[n->type];
7989 calcsize(n->ncmd.redirect);
7990 calcsize(n->ncmd.args);
7991 calcsize(n->ncmd.assign);
7994 sizenodelist(n->npipe.cmdlist);
7999 calcsize(n->nredir.redirect);
8000 calcsize(n->nredir.n);
8007 calcsize(n->nbinary.ch2);
8008 calcsize(n->nbinary.ch1);
8011 calcsize(n->nif.elsepart);
8012 calcsize(n->nif.ifpart);
8013 calcsize(n->nif.test);
8016 funcstringsize += strlen(n->nfor.var) + 1;
8017 calcsize(n->nfor.body);
8018 calcsize(n->nfor.args);
8021 calcsize(n->ncase.cases);
8022 calcsize(n->ncase.expr);
8025 calcsize(n->nclist.body);
8026 calcsize(n->nclist.pattern);
8027 calcsize(n->nclist.next);
8031 sizenodelist(n->narg.backquote);
8032 funcstringsize += strlen(n->narg.text) + 1;
8033 calcsize(n->narg.next);
8036 #if ENABLE_ASH_BASH_COMPAT
8043 calcsize(n->nfile.fname);
8044 calcsize(n->nfile.next);
8048 calcsize(n->ndup.vname);
8049 calcsize(n->ndup.next);
8053 calcsize(n->nhere.doc);
8054 calcsize(n->nhere.next);
8057 calcsize(n->nnot.com);
8063 nodeckstrdup(char *s)
8065 char *rtn = funcstring;
8067 strcpy(funcstring, s);
8068 funcstring += strlen(s) + 1;
8072 static union node *copynode(union node *);
8074 static struct nodelist *
8075 copynodelist(struct nodelist *lp)
8077 struct nodelist *start;
8078 struct nodelist **lpp;
8083 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8084 (*lpp)->n = copynode(lp->n);
8086 lpp = &(*lpp)->next;
8093 copynode(union node *n)
8100 funcblock = (char *) funcblock + nodesize[n->type];
8104 new->ncmd.redirect = copynode(n->ncmd.redirect);
8105 new->ncmd.args = copynode(n->ncmd.args);
8106 new->ncmd.assign = copynode(n->ncmd.assign);
8109 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8110 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8115 new->nredir.redirect = copynode(n->nredir.redirect);
8116 new->nredir.n = copynode(n->nredir.n);
8123 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8124 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8127 new->nif.elsepart = copynode(n->nif.elsepart);
8128 new->nif.ifpart = copynode(n->nif.ifpart);
8129 new->nif.test = copynode(n->nif.test);
8132 new->nfor.var = nodeckstrdup(n->nfor.var);
8133 new->nfor.body = copynode(n->nfor.body);
8134 new->nfor.args = copynode(n->nfor.args);
8137 new->ncase.cases = copynode(n->ncase.cases);
8138 new->ncase.expr = copynode(n->ncase.expr);
8141 new->nclist.body = copynode(n->nclist.body);
8142 new->nclist.pattern = copynode(n->nclist.pattern);
8143 new->nclist.next = copynode(n->nclist.next);
8147 new->narg.backquote = copynodelist(n->narg.backquote);
8148 new->narg.text = nodeckstrdup(n->narg.text);
8149 new->narg.next = copynode(n->narg.next);
8152 #if ENABLE_ASH_BASH_COMPAT
8159 new->nfile.fname = copynode(n->nfile.fname);
8160 new->nfile.fd = n->nfile.fd;
8161 new->nfile.next = copynode(n->nfile.next);
8165 new->ndup.vname = copynode(n->ndup.vname);
8166 new->ndup.dupfd = n->ndup.dupfd;
8167 new->ndup.fd = n->ndup.fd;
8168 new->ndup.next = copynode(n->ndup.next);
8172 new->nhere.doc = copynode(n->nhere.doc);
8173 new->nhere.fd = n->nhere.fd;
8174 new->nhere.next = copynode(n->nhere.next);
8177 new->nnot.com = copynode(n->nnot.com);
8180 new->type = n->type;
8185 * Make a copy of a parse tree.
8187 static struct funcnode *
8188 copyfunc(union node *n)
8193 funcblocksize = offsetof(struct funcnode, n);
8196 blocksize = funcblocksize;
8197 f = ckmalloc(blocksize + funcstringsize);
8198 funcblock = (char *) f + offsetof(struct funcnode, n);
8199 funcstring = (char *) f + blocksize;
8206 * Define a shell function.
8209 defun(char *name, union node *func)
8211 struct cmdentry entry;
8214 entry.cmdtype = CMDFUNCTION;
8215 entry.u.func = copyfunc(func);
8216 addcmdentry(name, &entry);
8220 /* Reasons for skipping commands (see comment on breakcmd routine) */
8221 #define SKIPBREAK (1 << 0)
8222 #define SKIPCONT (1 << 1)
8223 #define SKIPFUNC (1 << 2)
8224 #define SKIPFILE (1 << 3)
8225 #define SKIPEVAL (1 << 4)
8226 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8227 static int skipcount; /* number of levels to skip */
8228 static int funcnest; /* depth of function calls */
8229 static int loopnest; /* current loop nesting level */
8231 /* Forward decl way out to parsing code - dotrap needs it */
8232 static int evalstring(char *s, int mask);
8234 /* Called to execute a trap.
8235 * Single callsite - at the end of evaltree().
8236 * If we return non-zero, evaltree raises EXEXIT exception.
8238 * Perhaps we should avoid entering new trap handlers
8239 * while we are executing a trap handler. [is it a TODO?]
8248 savestatus = exitstatus;
8252 TRACE(("dotrap entered\n"));
8253 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8260 /* non-trapped SIGINT is handled separately by raise_interrupt,
8261 * don't upset it by resetting gotsig[SIGINT-1] */
8262 if (sig == SIGINT && !t)
8265 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8269 want_exexit = evalstring(t, SKIPEVAL);
8270 exitstatus = savestatus;
8272 TRACE(("dotrap returns %d\n", want_exexit));
8277 TRACE(("dotrap returns 0\n"));
8281 /* forward declarations - evaluation is fairly recursive business... */
8282 static void evalloop(union node *, int);
8283 static void evalfor(union node *, int);
8284 static void evalcase(union node *, int);
8285 static void evalsubshell(union node *, int);
8286 static void expredir(union node *);
8287 static void evalpipe(union node *, int);
8288 static void evalcommand(union node *, int);
8289 static int evalbltin(const struct builtincmd *, int, char **);
8290 static void prehash(union node *);
8293 * Evaluate a parse tree. The value is left in the global variable
8297 evaltree(union node *n, int flags)
8299 struct jmploc *volatile savehandler = exception_handler;
8300 struct jmploc jmploc;
8302 void (*evalfn)(union node *, int);
8306 SAVE_INT(int_level);
8309 TRACE(("evaltree(NULL) called\n"));
8312 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8314 exception_handler = &jmploc;
8316 int err = setjmp(jmploc.loc);
8318 /* if it was a signal, check for trap handlers */
8319 if (exception_type == EXSIG) {
8320 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8321 exception_type, err));
8324 /* continue on the way out */
8325 TRACE(("exception %d in evaltree, propagating err=%d\n",
8326 exception_type, err));
8327 exception_handler = savehandler;
8328 longjmp(exception_handler->loc, err);
8335 out1fmt("Node type = %d\n", n->type);
8340 evaltree(n->nnot.com, EV_TESTED);
8341 status = !exitstatus;
8344 expredir(n->nredir.redirect);
8345 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8347 evaltree(n->nredir.n, flags & EV_TESTED);
8348 status = exitstatus;
8350 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8353 evalfn = evalcommand;
8355 if (eflag && !(flags & EV_TESTED))
8367 evalfn = evalsubshell;
8380 #error NAND + 1 != NOR
8382 #if NOR + 1 != NSEMI
8383 #error NOR + 1 != NSEMI
8385 unsigned is_or = n->type - NAND;
8388 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8390 if (!exitstatus == is_or)
8403 evaltree(n->nif.test, EV_TESTED);
8406 if (exitstatus == 0) {
8410 if (n->nif.elsepart) {
8411 n = n->nif.elsepart;
8416 defun(n->narg.text, n->narg.next);
8420 exitstatus = status;
8425 exception_handler = savehandler;
8428 /* Order of checks below is important:
8429 * signal handlers trigger before exit caused by "set -e".
8431 if (pending_sig && dotrap())
8433 if (checkexit & exitstatus)
8434 evalskip |= SKIPEVAL;
8436 if (flags & EV_EXIT) {
8438 raise_exception(EXEXIT);
8441 RESTORE_INT(int_level);
8442 TRACE(("leaving evaltree (no interrupts)\n"));
8445 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8448 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8451 evalloop(union node *n, int flags)
8461 evaltree(n->nbinary.ch1, EV_TESTED);
8464 if (evalskip == SKIPCONT && --skipcount <= 0) {
8468 if (evalskip == SKIPBREAK && --skipcount <= 0)
8473 if (n->type != NWHILE)
8477 evaltree(n->nbinary.ch2, flags);
8478 status = exitstatus;
8483 exitstatus = status;
8487 evalfor(union node *n, int flags)
8489 struct arglist arglist;
8492 struct stackmark smark;
8494 setstackmark(&smark);
8495 arglist.list = NULL;
8496 arglist.lastp = &arglist.list;
8497 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8498 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8503 *arglist.lastp = NULL;
8508 for (sp = arglist.list; sp; sp = sp->next) {
8509 setvar(n->nfor.var, sp->text, 0);
8510 evaltree(n->nfor.body, flags);
8512 if (evalskip == SKIPCONT && --skipcount <= 0) {
8516 if (evalskip == SKIPBREAK && --skipcount <= 0)
8523 popstackmark(&smark);
8527 evalcase(union node *n, int flags)
8531 struct arglist arglist;
8532 struct stackmark smark;
8534 setstackmark(&smark);
8535 arglist.list = NULL;
8536 arglist.lastp = &arglist.list;
8537 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8539 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8540 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8541 if (casematch(patp, arglist.list->text)) {
8542 if (evalskip == 0) {
8543 evaltree(cp->nclist.body, flags);
8550 popstackmark(&smark);
8554 * Kick off a subshell to evaluate a tree.
8557 evalsubshell(union node *n, int flags)
8560 int backgnd = (n->type == NBACKGND);
8563 expredir(n->nredir.redirect);
8564 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8567 jp = makejob(/*n,*/ 1);
8568 if (forkshell(jp, n, backgnd) == 0) {
8573 flags &= ~EV_TESTED;
8575 redirect(n->nredir.redirect, 0);
8576 evaltreenr(n->nredir.n, flags);
8581 status = waitforjob(jp);
8582 exitstatus = status;
8587 * Compute the names of the files in a redirection list.
8589 static void fixredir(union node *, const char *, int);
8591 expredir(union node *n)
8595 for (redir = n; redir; redir = redir->nfile.next) {
8599 fn.lastp = &fn.list;
8600 switch (redir->type) {
8604 #if ENABLE_ASH_BASH_COMPAT
8609 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8610 #if ENABLE_ASH_BASH_COMPAT
8613 redir->nfile.expfname = fn.list->text;
8616 case NTOFD: /* >& */
8617 if (redir->ndup.vname) {
8618 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8619 if (fn.list == NULL)
8620 ash_msg_and_raise_error("redir error");
8621 #if ENABLE_ASH_BASH_COMPAT
8622 //FIXME: we used expandarg with different args!
8623 if (!isdigit_str9(fn.list->text)) {
8624 /* >&file, not >&fd */
8625 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8626 ash_msg_and_raise_error("redir error");
8628 goto store_expfname;
8631 fixredir(redir, fn.list->text, 1);
8639 * Evaluate a pipeline. All the processes in the pipeline are children
8640 * of the process creating the pipeline. (This differs from some versions
8641 * of the shell, which make the last process in a pipeline the parent
8645 evalpipe(union node *n, int flags)
8648 struct nodelist *lp;
8653 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8655 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8659 jp = makejob(/*n,*/ pipelen);
8661 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8665 if (pipe(pip) < 0) {
8667 ash_msg_and_raise_error("pipe call failed");
8670 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8683 evaltreenr(lp->n, flags);
8689 /* Don't want to trigger debugging */
8693 if (n->npipe.pipe_backgnd == 0) {
8694 exitstatus = waitforjob(jp);
8695 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8701 * Controls whether the shell is interactive or not.
8704 setinteractive(int on)
8706 static smallint is_interactive;
8708 if (++on == is_interactive)
8710 is_interactive = on;
8714 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8715 if (is_interactive > 1) {
8716 /* Looks like they want an interactive shell */
8717 static smallint did_banner;
8720 /* note: ash and hush share this string */
8721 out1fmt("\n\n%s %s\n"
8722 "Enter 'help' for a list of built-in commands."
8725 "built-in shell (ash)"
8739 setinteractive(iflag);
8741 #if ENABLE_FEATURE_EDITING_VI
8743 line_input_state->flags |= VI_MODE;
8745 line_input_state->flags &= ~VI_MODE;
8747 viflag = 0; /* forcibly keep the option off */
8751 static struct localvar *localvars;
8754 * Called after a function returns.
8755 * Interrupts must be off.
8760 struct localvar *lvp;
8763 while ((lvp = localvars) != NULL) {
8764 localvars = lvp->next;
8766 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8767 if (vp == NULL) { /* $- saved */
8768 memcpy(optlist, lvp->text, sizeof(optlist));
8769 free((char*)lvp->text);
8771 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8772 unsetvar(vp->var_text);
8775 vp->var_func(var_end(lvp->text));
8776 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8777 free((char*)vp->var_text);
8778 vp->flags = lvp->flags;
8779 vp->var_text = lvp->text;
8786 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8788 volatile struct shparam saveparam;
8789 struct localvar *volatile savelocalvars;
8790 struct jmploc *volatile savehandler;
8791 struct jmploc jmploc;
8794 saveparam = shellparam;
8795 savelocalvars = localvars;
8796 e = setjmp(jmploc.loc);
8801 savehandler = exception_handler;
8802 exception_handler = &jmploc;
8804 shellparam.malloced = 0;
8808 shellparam.nparam = argc - 1;
8809 shellparam.p = argv + 1;
8810 #if ENABLE_ASH_GETOPTS
8811 shellparam.optind = 1;
8812 shellparam.optoff = -1;
8814 evaltree(&func->n, flags & EV_TESTED);
8820 localvars = savelocalvars;
8821 freeparam(&shellparam);
8822 shellparam = saveparam;
8823 exception_handler = savehandler;
8825 evalskip &= ~SKIPFUNC;
8829 #if ENABLE_ASH_CMDCMD
8831 parse_command_args(char **argv, const char **path)
8844 if (c == '-' && !*cp) {
8851 *path = bb_default_path;
8854 /* run 'typecmd' for other options */
8865 * Make a variable a local variable. When a variable is made local, it's
8866 * value and flags are saved in a localvar structure. The saved values
8867 * will be restored when the shell function returns. We handle the name
8868 * "-" as a special case.
8873 struct localvar *lvp;
8878 lvp = ckzalloc(sizeof(struct localvar));
8879 if (LONE_DASH(name)) {
8881 p = ckmalloc(sizeof(optlist));
8882 lvp->text = memcpy(p, optlist, sizeof(optlist));
8887 vpp = hashvar(name);
8888 vp = *findvar(vpp, name);
8889 eq = strchr(name, '=');
8892 setvareq(name, VSTRFIXED);
8894 setvar(name, NULL, VSTRFIXED);
8895 vp = *vpp; /* the new variable */
8896 lvp->flags = VUNSET;
8898 lvp->text = vp->var_text;
8899 lvp->flags = vp->flags;
8900 vp->flags |= VSTRFIXED|VTEXTFIXED;
8906 lvp->next = localvars;
8912 * The "local" command.
8914 static int FAST_FUNC
8915 localcmd(int argc UNUSED_PARAM, char **argv)
8920 while ((name = *argv++) != NULL) {
8926 static int FAST_FUNC
8927 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8932 static int FAST_FUNC
8933 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8938 static int FAST_FUNC
8939 execcmd(int argc UNUSED_PARAM, char **argv)
8942 iflag = 0; /* exit on error */
8945 shellexec(argv + 1, pathval(), 0);
8951 * The return command.
8953 static int FAST_FUNC
8954 returncmd(int argc UNUSED_PARAM, char **argv)
8957 * If called outside a function, do what ksh does;
8958 * skip the rest of the file.
8960 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8961 return argv[1] ? number(argv[1]) : exitstatus;
8964 /* Forward declarations for builtintab[] */
8965 static int breakcmd(int, char **) FAST_FUNC;
8966 static int dotcmd(int, char **) FAST_FUNC;
8967 static int evalcmd(int, char **) FAST_FUNC;
8968 static int exitcmd(int, char **) FAST_FUNC;
8969 static int exportcmd(int, char **) FAST_FUNC;
8970 #if ENABLE_ASH_GETOPTS
8971 static int getoptscmd(int, char **) FAST_FUNC;
8973 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8974 static int helpcmd(int, char **) FAST_FUNC;
8976 #if ENABLE_SH_MATH_SUPPORT
8977 static int letcmd(int, char **) FAST_FUNC;
8979 static int readcmd(int, char **) FAST_FUNC;
8980 static int setcmd(int, char **) FAST_FUNC;
8981 static int shiftcmd(int, char **) FAST_FUNC;
8982 static int timescmd(int, char **) FAST_FUNC;
8983 static int trapcmd(int, char **) FAST_FUNC;
8984 static int umaskcmd(int, char **) FAST_FUNC;
8985 static int unsetcmd(int, char **) FAST_FUNC;
8986 static int ulimitcmd(int, char **) FAST_FUNC;
8988 #define BUILTIN_NOSPEC "0"
8989 #define BUILTIN_SPECIAL "1"
8990 #define BUILTIN_REGULAR "2"
8991 #define BUILTIN_SPEC_REG "3"
8992 #define BUILTIN_ASSIGN "4"
8993 #define BUILTIN_SPEC_ASSG "5"
8994 #define BUILTIN_REG_ASSG "6"
8995 #define BUILTIN_SPEC_REG_ASSG "7"
8997 /* Stubs for calling non-FAST_FUNC's */
8998 #if ENABLE_ASH_BUILTIN_ECHO
8999 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9001 #if ENABLE_ASH_BUILTIN_PRINTF
9002 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9004 #if ENABLE_ASH_BUILTIN_TEST
9005 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9008 /* Keep these in proper order since it is searched via bsearch() */
9009 static const struct builtincmd builtintab[] = {
9010 { BUILTIN_SPEC_REG "." , dotcmd },
9011 { BUILTIN_SPEC_REG ":" , truecmd },
9012 #if ENABLE_ASH_BUILTIN_TEST
9013 { BUILTIN_REGULAR "[" , testcmd },
9014 #if ENABLE_ASH_BASH_COMPAT
9015 { BUILTIN_REGULAR "[[" , testcmd },
9018 #if ENABLE_ASH_ALIAS
9019 { BUILTIN_REG_ASSG "alias" , aliascmd },
9022 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9024 { BUILTIN_SPEC_REG "break" , breakcmd },
9025 { BUILTIN_REGULAR "cd" , cdcmd },
9026 { BUILTIN_NOSPEC "chdir" , cdcmd },
9027 #if ENABLE_ASH_CMDCMD
9028 { BUILTIN_REGULAR "command" , commandcmd },
9030 { BUILTIN_SPEC_REG "continue", breakcmd },
9031 #if ENABLE_ASH_BUILTIN_ECHO
9032 { BUILTIN_REGULAR "echo" , echocmd },
9034 { BUILTIN_SPEC_REG "eval" , evalcmd },
9035 { BUILTIN_SPEC_REG "exec" , execcmd },
9036 { BUILTIN_SPEC_REG "exit" , exitcmd },
9037 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9038 { BUILTIN_REGULAR "false" , falsecmd },
9040 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9042 #if ENABLE_ASH_GETOPTS
9043 { BUILTIN_REGULAR "getopts" , getoptscmd },
9045 { BUILTIN_NOSPEC "hash" , hashcmd },
9046 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9047 { BUILTIN_NOSPEC "help" , helpcmd },
9050 { BUILTIN_REGULAR "jobs" , jobscmd },
9051 { BUILTIN_REGULAR "kill" , killcmd },
9053 #if ENABLE_SH_MATH_SUPPORT
9054 { BUILTIN_NOSPEC "let" , letcmd },
9056 { BUILTIN_ASSIGN "local" , localcmd },
9057 #if ENABLE_ASH_BUILTIN_PRINTF
9058 { BUILTIN_REGULAR "printf" , printfcmd },
9060 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9061 { BUILTIN_REGULAR "read" , readcmd },
9062 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9063 { BUILTIN_SPEC_REG "return" , returncmd },
9064 { BUILTIN_SPEC_REG "set" , setcmd },
9065 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9066 #if ENABLE_ASH_BASH_COMPAT
9067 { BUILTIN_SPEC_REG "source" , dotcmd },
9069 #if ENABLE_ASH_BUILTIN_TEST
9070 { BUILTIN_REGULAR "test" , testcmd },
9072 { BUILTIN_SPEC_REG "times" , timescmd },
9073 { BUILTIN_SPEC_REG "trap" , trapcmd },
9074 { BUILTIN_REGULAR "true" , truecmd },
9075 { BUILTIN_NOSPEC "type" , typecmd },
9076 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9077 { BUILTIN_REGULAR "umask" , umaskcmd },
9078 #if ENABLE_ASH_ALIAS
9079 { BUILTIN_REGULAR "unalias" , unaliascmd },
9081 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9082 { BUILTIN_REGULAR "wait" , waitcmd },
9085 /* Should match the above table! */
9086 #define COMMANDCMD (builtintab + \
9088 1 * ENABLE_ASH_BUILTIN_TEST + \
9089 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9090 1 * ENABLE_ASH_ALIAS + \
9091 1 * ENABLE_ASH_JOB_CONTROL + \
9093 #define EXECCMD (builtintab + \
9095 1 * ENABLE_ASH_BUILTIN_TEST + \
9096 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9097 1 * ENABLE_ASH_ALIAS + \
9098 1 * ENABLE_ASH_JOB_CONTROL + \
9100 1 * ENABLE_ASH_CMDCMD + \
9102 ENABLE_ASH_BUILTIN_ECHO + \
9106 * Search the table of builtin commands.
9108 static struct builtincmd *
9109 find_builtin(const char *name)
9111 struct builtincmd *bp;
9114 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9121 * Execute a simple command.
9124 isassignment(const char *p)
9126 const char *q = endofname(p);
9131 static int FAST_FUNC
9132 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9134 /* Preserve exitstatus of a previous possible redirection
9135 * as POSIX mandates */
9136 return back_exitstatus;
9139 evalcommand(union node *cmd, int flags)
9141 static const struct builtincmd null_bltin = {
9142 "\0\0", bltincmd /* why three NULs? */
9144 struct stackmark smark;
9146 struct arglist arglist;
9147 struct arglist varlist;
9150 const struct strlist *sp;
9151 struct cmdentry cmdentry;
9158 struct builtincmd *bcmd;
9159 smallint cmd_is_exec;
9160 smallint pseudovarflag = 0;
9162 /* First expand the arguments. */
9163 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9164 setstackmark(&smark);
9165 back_exitstatus = 0;
9167 cmdentry.cmdtype = CMDBUILTIN;
9168 cmdentry.u.cmd = &null_bltin;
9169 varlist.lastp = &varlist.list;
9170 *varlist.lastp = NULL;
9171 arglist.lastp = &arglist.list;
9172 *arglist.lastp = NULL;
9175 if (cmd->ncmd.args) {
9176 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9177 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9180 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9181 struct strlist **spp;
9183 spp = arglist.lastp;
9184 if (pseudovarflag && isassignment(argp->narg.text))
9185 expandarg(argp, &arglist, EXP_VARTILDE);
9187 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9189 for (sp = *spp; sp; sp = sp->next)
9193 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9194 for (sp = arglist.list; sp; sp = sp->next) {
9195 TRACE(("evalcommand arg: %s\n", sp->text));
9196 *nargv++ = sp->text;
9201 if (iflag && funcnest == 0 && argc > 0)
9202 lastarg = nargv[-1];
9205 expredir(cmd->ncmd.redirect);
9206 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9208 path = vpath.var_text;
9209 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9210 struct strlist **spp;
9213 spp = varlist.lastp;
9214 expandarg(argp, &varlist, EXP_VARTILDE);
9217 * Modify the command lookup path, if a PATH= assignment
9221 if (varcmp(p, path) == 0)
9225 /* Print the command if xflag is set. */
9228 const char *p = " %s" + 1;
9230 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9232 for (n = 0; n < 2; n++) {
9234 fdprintf(preverrout_fd, p, sp->text);
9240 safe_write(preverrout_fd, "\n", 1);
9246 /* Now locate the command. */
9248 const char *oldpath;
9249 int cmd_flag = DO_ERR;
9254 find_command(argv[0], &cmdentry, cmd_flag, path);
9255 if (cmdentry.cmdtype == CMDUNKNOWN) {
9256 flush_stdout_stderr();
9261 /* implement bltin and command here */
9262 if (cmdentry.cmdtype != CMDBUILTIN)
9265 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9266 if (cmdentry.u.cmd == EXECCMD)
9268 #if ENABLE_ASH_CMDCMD
9269 if (cmdentry.u.cmd == COMMANDCMD) {
9271 nargv = parse_command_args(argv, &path);
9274 argc -= nargv - argv;
9276 cmd_flag |= DO_NOFUNC;
9284 /* We have a redirection error. */
9286 raise_exception(EXERROR);
9288 exitstatus = status;
9292 /* Execute the command. */
9293 switch (cmdentry.cmdtype) {
9296 #if ENABLE_FEATURE_SH_NOFORK
9297 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9298 * around run_nofork_applet() call.
9299 * (2) Should this check also be done in forkshell()?
9300 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9302 /* find_command() encodes applet_no as (-2 - applet_no) */
9303 int applet_no = (- cmdentry.u.index - 2);
9304 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9305 listsetvar(varlist.list, VEXPORT|VSTACK);
9306 /* run <applet>_main() */
9307 exitstatus = run_nofork_applet(applet_no, argv);
9311 /* Can we avoid forking off? For example, very last command
9312 * in a script or a subshell does not need forking,
9313 * we can just exec it.
9315 if (!(flags & EV_EXIT) || may_have_traps) {
9316 /* No, forking off a child is necessary */
9318 jp = makejob(/*cmd,*/ 1);
9319 if (forkshell(jp, cmd, FORK_FG) != 0) {
9321 exitstatus = waitforjob(jp);
9323 TRACE(("forked child exited with %d\n", exitstatus));
9328 /* fall through to exec'ing external program */
9330 listsetvar(varlist.list, VEXPORT|VSTACK);
9331 shellexec(argv, path, cmdentry.u.index);
9335 cmdenviron = varlist.list;
9337 struct strlist *list = cmdenviron;
9339 if (spclbltin > 0 || argc == 0) {
9341 if (cmd_is_exec && argc > 1)
9344 listsetvar(list, i);
9346 /* Tight loop with builtins only:
9347 * "while kill -0 $child; do true; done"
9348 * will never exit even if $child died, unless we do this
9349 * to reap the zombie and make kill detect that it's gone: */
9350 dowait(DOWAIT_NONBLOCK, NULL);
9352 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9354 int i = exception_type;
9359 exit_status = 128 + SIGINT;
9361 exit_status = 128 + pending_sig;
9362 exitstatus = exit_status;
9363 if (i == EXINT || spclbltin > 0) {
9365 longjmp(exception_handler->loc, 1);
9372 listsetvar(varlist.list, 0);
9373 /* See above for the rationale */
9374 dowait(DOWAIT_NONBLOCK, NULL);
9375 if (evalfun(cmdentry.u.func, argc, argv, flags))
9382 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9384 /* dsl: I think this is intended to be used to support
9385 * '_' in 'vi' command mode during line editing...
9386 * However I implemented that within libedit itself.
9388 setvar("_", lastarg, 0);
9390 popstackmark(&smark);
9394 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9396 char *volatile savecmdname;
9397 struct jmploc *volatile savehandler;
9398 struct jmploc jmploc;
9401 savecmdname = commandname;
9402 i = setjmp(jmploc.loc);
9405 savehandler = exception_handler;
9406 exception_handler = &jmploc;
9407 commandname = argv[0];
9409 optptr = NULL; /* initialize nextopt */
9410 exitstatus = (*cmd->builtin)(argc, argv);
9411 flush_stdout_stderr();
9413 exitstatus |= ferror(stdout);
9415 commandname = savecmdname;
9416 exception_handler = savehandler;
9422 goodname(const char *p)
9424 return endofname(p)[0] == '\0';
9429 * Search for a command. This is called before we fork so that the
9430 * location of the command will be available in the parent as well as
9431 * the child. The check for "goodname" is an overly conservative
9432 * check that the name will not be subject to expansion.
9435 prehash(union node *n)
9437 struct cmdentry entry;
9439 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9440 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9444 /* ============ Builtin commands
9446 * Builtin commands whose functions are closely tied to evaluation
9447 * are implemented here.
9451 * Handle break and continue commands. Break, continue, and return are
9452 * all handled by setting the evalskip flag. The evaluation routines
9453 * above all check this flag, and if it is set they start skipping
9454 * commands rather than executing them. The variable skipcount is
9455 * the number of loops to break/continue, or the number of function
9456 * levels to return. (The latter is always 1.) It should probably
9457 * be an error to break out of more loops than exist, but it isn't
9458 * in the standard shell so we don't make it one here.
9460 static int FAST_FUNC
9461 breakcmd(int argc UNUSED_PARAM, char **argv)
9463 int n = argv[1] ? number(argv[1]) : 1;
9466 ash_msg_and_raise_error(msg_illnum, argv[1]);
9470 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9477 /* ============ input.c
9479 * This implements the input routines used by the parser.
9483 INPUT_PUSH_FILE = 1,
9484 INPUT_NOFILE_OK = 2,
9487 static smallint checkkwd;
9488 /* values of checkkwd variable */
9489 #define CHKALIAS 0x1
9494 * Push a string back onto the input at this current parsefile level.
9495 * We handle aliases this way.
9497 #if !ENABLE_ASH_ALIAS
9498 #define pushstring(s, ap) pushstring(s)
9501 pushstring(char *s, struct alias *ap)
9508 if (g_parsefile->strpush) {
9509 sp = ckzalloc(sizeof(*sp));
9510 sp->prev = g_parsefile->strpush;
9512 sp = &(g_parsefile->basestrpush);
9514 g_parsefile->strpush = sp;
9515 sp->prev_string = g_parsefile->next_to_pgetc;
9516 sp->prev_left_in_line = g_parsefile->left_in_line;
9517 #if ENABLE_ASH_ALIAS
9520 ap->flag |= ALIASINUSE;
9524 g_parsefile->next_to_pgetc = s;
9525 g_parsefile->left_in_line = len;
9532 struct strpush *sp = g_parsefile->strpush;
9535 #if ENABLE_ASH_ALIAS
9537 if (g_parsefile->next_to_pgetc[-1] == ' '
9538 || g_parsefile->next_to_pgetc[-1] == '\t'
9540 checkkwd |= CHKALIAS;
9542 if (sp->string != sp->ap->val) {
9545 sp->ap->flag &= ~ALIASINUSE;
9546 if (sp->ap->flag & ALIASDEAD) {
9547 unalias(sp->ap->name);
9551 g_parsefile->next_to_pgetc = sp->prev_string;
9552 g_parsefile->left_in_line = sp->prev_left_in_line;
9553 g_parsefile->strpush = sp->prev;
9554 if (sp != &(g_parsefile->basestrpush))
9559 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9560 //it peeks whether it is &>, and then pushes back both chars.
9561 //This function needs to save last *next_to_pgetc to buf[0]
9562 //to make two pungetc() reliable. Currently,
9563 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9568 char *buf = g_parsefile->buf;
9570 g_parsefile->next_to_pgetc = buf;
9571 #if ENABLE_FEATURE_EDITING
9573 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9574 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9576 # if ENABLE_FEATURE_TAB_COMPLETION
9577 line_input_state->path_lookup = pathval();
9579 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9581 /* Ctrl+C pressed */
9590 if (nr < 0 && errno == 0) {
9591 /* Ctrl+D pressed */
9596 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9599 #if 0 /* disabled: nonblock_safe_read() handles this problem */
9601 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9602 int flags = fcntl(0, F_GETFL);
9603 if (flags >= 0 && (flags & O_NONBLOCK)) {
9604 flags &= ~O_NONBLOCK;
9605 if (fcntl(0, F_SETFL, flags) >= 0) {
9606 out2str("sh: turning off NDELAY mode\n");
9617 * Refill the input buffer and return the next input character:
9619 * 1) If a string was pushed back on the input, pop it;
9620 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9621 * or we are reading from a string so we can't refill the buffer,
9623 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9624 * 4) Process input up to the next newline, deleting nul characters.
9626 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9627 #define pgetc_debug(...) ((void)0)
9634 while (g_parsefile->strpush) {
9635 #if ENABLE_ASH_ALIAS
9636 if (g_parsefile->left_in_line == -1
9637 && g_parsefile->strpush->ap
9638 && g_parsefile->next_to_pgetc[-1] != ' '
9639 && g_parsefile->next_to_pgetc[-1] != '\t'
9641 pgetc_debug("preadbuffer PEOA");
9646 /* try "pgetc" now: */
9647 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9648 g_parsefile->left_in_line,
9649 g_parsefile->next_to_pgetc,
9650 g_parsefile->next_to_pgetc);
9651 if (--g_parsefile->left_in_line >= 0)
9652 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9654 /* on both branches above g_parsefile->left_in_line < 0.
9655 * "pgetc" needs refilling.
9658 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9659 * pungetc() may increment it a few times.
9660 * Assuming it won't increment it to less than -90.
9662 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9663 pgetc_debug("preadbuffer PEOF1");
9664 /* even in failure keep left_in_line and next_to_pgetc
9665 * in lock step, for correct multi-layer pungetc.
9666 * left_in_line was decremented before preadbuffer(),
9667 * must inc next_to_pgetc: */
9668 g_parsefile->next_to_pgetc++;
9672 more = g_parsefile->left_in_buffer;
9674 flush_stdout_stderr();
9678 /* don't try reading again */
9679 g_parsefile->left_in_line = -99;
9680 pgetc_debug("preadbuffer PEOF2");
9681 g_parsefile->next_to_pgetc++;
9686 /* Find out where's the end of line.
9687 * Set g_parsefile->left_in_line
9688 * and g_parsefile->left_in_buffer acordingly.
9689 * NUL chars are deleted.
9691 q = g_parsefile->next_to_pgetc;
9699 memmove(q, q + 1, more);
9703 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9709 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9710 if (g_parsefile->left_in_line < 0)
9715 g_parsefile->left_in_buffer = more;
9720 out2str(g_parsefile->next_to_pgetc);
9724 pgetc_debug("preadbuffer at %d:%p'%s'",
9725 g_parsefile->left_in_line,
9726 g_parsefile->next_to_pgetc,
9727 g_parsefile->next_to_pgetc);
9728 return (unsigned char)*g_parsefile->next_to_pgetc++;
9731 #define pgetc_as_macro() \
9732 (--g_parsefile->left_in_line >= 0 \
9733 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9740 pgetc_debug("pgetc_fast at %d:%p'%s'",
9741 g_parsefile->left_in_line,
9742 g_parsefile->next_to_pgetc,
9743 g_parsefile->next_to_pgetc);
9744 return pgetc_as_macro();
9747 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9748 # define pgetc_fast() pgetc()
9750 # define pgetc_fast() pgetc_as_macro()
9753 #if ENABLE_ASH_ALIAS
9755 pgetc_without_PEOA(void)
9759 pgetc_debug("pgetc_fast at %d:%p'%s'",
9760 g_parsefile->left_in_line,
9761 g_parsefile->next_to_pgetc,
9762 g_parsefile->next_to_pgetc);
9764 } while (c == PEOA);
9768 # define pgetc_without_PEOA() pgetc()
9772 * Read a line from the script.
9775 pfgets(char *line, int len)
9781 while (--nleft > 0) {
9782 c = pgetc_without_PEOA();
9797 * Undo the last call to pgetc. Only one character may be pushed back.
9798 * PEOF may be pushed back.
9803 g_parsefile->left_in_line++;
9804 g_parsefile->next_to_pgetc--;
9805 pgetc_debug("pushed back to %d:%p'%s'",
9806 g_parsefile->left_in_line,
9807 g_parsefile->next_to_pgetc,
9808 g_parsefile->next_to_pgetc);
9812 * To handle the "." command, a stack of input files is used. Pushfile
9813 * adds a new entry to the stack and popfile restores the previous level.
9818 struct parsefile *pf;
9820 pf = ckzalloc(sizeof(*pf));
9821 pf->prev = g_parsefile;
9823 /*pf->strpush = NULL; - ckzalloc did it */
9824 /*pf->basestrpush.prev = NULL;*/
9831 struct parsefile *pf = g_parsefile;
9839 g_parsefile = pf->prev;
9845 * Return to top level.
9850 while (g_parsefile != &basepf)
9855 * Close the file(s) that the shell is reading commands from. Called
9856 * after a fork is done.
9862 if (g_parsefile->pf_fd > 0) {
9863 close(g_parsefile->pf_fd);
9864 g_parsefile->pf_fd = 0;
9869 * Like setinputfile, but takes an open file descriptor. Call this with
9873 setinputfd(int fd, int push)
9875 close_on_exec_on(fd);
9878 g_parsefile->buf = NULL;
9880 g_parsefile->pf_fd = fd;
9881 if (g_parsefile->buf == NULL)
9882 g_parsefile->buf = ckmalloc(IBUFSIZ);
9883 g_parsefile->left_in_buffer = 0;
9884 g_parsefile->left_in_line = 0;
9885 g_parsefile->linno = 1;
9889 * Set the input to take input from a file. If push is set, push the
9890 * old input onto the stack first.
9893 setinputfile(const char *fname, int flags)
9899 fd = open(fname, O_RDONLY);
9901 if (flags & INPUT_NOFILE_OK)
9903 ash_msg_and_raise_error("can't open '%s'", fname);
9906 fd2 = copyfd(fd, 10);
9909 ash_msg_and_raise_error("out of file descriptors");
9912 setinputfd(fd, flags & INPUT_PUSH_FILE);
9919 * Like setinputfile, but takes input from a string.
9922 setinputstring(char *string)
9926 g_parsefile->next_to_pgetc = string;
9927 g_parsefile->left_in_line = strlen(string);
9928 g_parsefile->buf = NULL;
9929 g_parsefile->linno = 1;
9934 /* ============ mail.c
9936 * Routines to check for mail.
9941 #define MAXMBOXES 10
9943 /* times of mailboxes */
9944 static time_t mailtime[MAXMBOXES];
9945 /* Set if MAIL or MAILPATH is changed. */
9946 static smallint mail_var_path_changed;
9949 * Print appropriate message(s) if mail has arrived.
9950 * If mail_var_path_changed is set,
9951 * then the value of MAIL has mail_var_path_changed,
9952 * so we just update the values.
9961 struct stackmark smark;
9964 setstackmark(&smark);
9965 mpath = mpathset() ? mpathval() : mailval();
9966 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9967 p = path_advance(&mpath, nullstr);
9972 for (q = p; *q; q++)
9978 q[-1] = '\0'; /* delete trailing '/' */
9979 if (stat(p, &statb) < 0) {
9983 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9986 pathopt ? pathopt : "you have mail"
9989 *mtp = statb.st_mtime;
9991 mail_var_path_changed = 0;
9992 popstackmark(&smark);
9995 static void FAST_FUNC
9996 changemail(const char *val UNUSED_PARAM)
9998 mail_var_path_changed = 1;
10001 #endif /* ASH_MAIL */
10004 /* ============ ??? */
10007 * Set the shell parameters.
10010 setparam(char **argv)
10016 for (nparam = 0; argv[nparam]; nparam++)
10018 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10020 *ap++ = ckstrdup(*argv++);
10023 freeparam(&shellparam);
10024 shellparam.malloced = 1;
10025 shellparam.nparam = nparam;
10026 shellparam.p = newparam;
10027 #if ENABLE_ASH_GETOPTS
10028 shellparam.optind = 1;
10029 shellparam.optoff = -1;
10034 * Process shell options. The global variable argptr contains a pointer
10035 * to the argument list; we advance it past the options.
10037 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10038 * For a non-interactive shell, an error condition encountered
10039 * by a special built-in ... shall cause the shell to write a diagnostic message
10040 * to standard error and exit as shown in the following table:
10041 * Error Special Built-In
10043 * Utility syntax error (option or operand error) Shall exit
10045 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10046 * we see that bash does not do that (set "finishes" with error code 1 instead,
10047 * and shell continues), and people rely on this behavior!
10049 * set -o barfoo 2>/dev/null
10052 * Oh well. Let's mimic that.
10055 plus_minus_o(char *name, int val)
10060 for (i = 0; i < NOPTS; i++) {
10061 if (strcmp(name, optnames(i)) == 0) {
10066 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10069 for (i = 0; i < NOPTS; i++) {
10071 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10073 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10079 setoption(int flag, int val)
10083 for (i = 0; i < NOPTS; i++) {
10084 if (optletters(i) == flag) {
10089 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10093 options(int cmdline)
10101 while ((p = *argptr) != NULL) {
10103 if (c != '-' && c != '+')
10106 val = 0; /* val = 0 if c == '+' */
10109 if (p[0] == '\0' || LONE_DASH(p)) {
10111 /* "-" means turn off -x and -v */
10114 /* "--" means reset params */
10115 else if (*argptr == NULL)
10118 break; /* "-" or "--" terminates options */
10121 /* first char was + or - */
10122 while ((c = *p++) != '\0') {
10123 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10124 if (c == 'c' && cmdline) {
10125 minusc = p; /* command is after shell args */
10126 } else if (c == 'o') {
10127 if (plus_minus_o(*argptr, val)) {
10128 /* it already printed err message */
10129 return 1; /* error */
10133 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10135 /* bash does not accept +-login, we also won't */
10136 } else if (cmdline && val && (c == '-')) { /* long options */
10137 if (strcmp(p, "login") == 0)
10149 * The shift builtin command.
10151 static int FAST_FUNC
10152 shiftcmd(int argc UNUSED_PARAM, char **argv)
10159 n = number(argv[1]);
10160 if (n > shellparam.nparam)
10161 n = 0; /* bash compat, was = shellparam.nparam; */
10163 shellparam.nparam -= n;
10164 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10165 if (shellparam.malloced)
10168 ap2 = shellparam.p;
10169 while ((*ap2++ = *ap1++) != NULL)
10171 #if ENABLE_ASH_GETOPTS
10172 shellparam.optind = 1;
10173 shellparam.optoff = -1;
10180 * POSIX requires that 'set' (but not export or readonly) output the
10181 * variables in lexicographic order - by the locale's collating order (sigh).
10182 * Maybe we could keep them in an ordered balanced binary tree
10183 * instead of hashed lists.
10184 * For now just roll 'em through qsort for printing...
10187 showvars(const char *sep_prefix, int on, int off)
10190 char **ep, **epend;
10192 ep = listvars(on, off, &epend);
10193 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10195 sep = *sep_prefix ? " " : sep_prefix;
10197 for (; ep < epend; ep++) {
10201 p = strchrnul(*ep, '=');
10204 q = single_quote(++p);
10205 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10211 * The set command builtin.
10213 static int FAST_FUNC
10214 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10219 return showvars(nullstr, 0, VUNSET);
10222 if (!options(0)) { /* if no parse error... */
10225 if (*argptr != NULL) {
10233 #if ENABLE_ASH_RANDOM_SUPPORT
10234 static void FAST_FUNC
10235 change_random(const char *value)
10239 if (value == NULL) {
10240 /* "get", generate */
10241 t = next_random(&random_gen);
10242 /* set without recursion */
10243 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10244 vrandom.flags &= ~VNOFUNC;
10247 t = strtoul(value, NULL, 10);
10248 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10253 #if ENABLE_ASH_GETOPTS
10255 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10264 if (*param_optind < 1)
10266 optnext = optfirst + *param_optind - 1;
10268 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10271 p = optnext[-1] + *optoff;
10272 if (p == NULL || *p == '\0') {
10273 /* Current word is done, advance */
10275 if (p == NULL || *p != '-' || *++p == '\0') {
10282 if (LONE_DASH(p)) /* check for "--" */
10287 for (q = optstr; *q != c;) {
10289 if (optstr[0] == ':') {
10292 err |= setvarsafe("OPTARG", s, 0);
10294 fprintf(stderr, "Illegal option -%c\n", c);
10295 unsetvar("OPTARG");
10305 if (*p == '\0' && (p = *optnext) == NULL) {
10306 if (optstr[0] == ':') {
10309 err |= setvarsafe("OPTARG", s, 0);
10312 fprintf(stderr, "No arg for -%c option\n", c);
10313 unsetvar("OPTARG");
10321 err |= setvarsafe("OPTARG", p, 0);
10324 err |= setvarsafe("OPTARG", nullstr, 0);
10326 *optoff = p ? p - *(optnext - 1) : -1;
10327 *param_optind = optnext - optfirst + 1;
10328 fmtstr(s, sizeof(s), "%d", *param_optind);
10329 err |= setvarsafe("OPTIND", s, VNOFUNC);
10332 err |= setvarsafe(optvar, s, 0);
10336 flush_stdout_stderr();
10337 raise_exception(EXERROR);
10343 * The getopts builtin. Shellparam.optnext points to the next argument
10344 * to be processed. Shellparam.optptr points to the next character to
10345 * be processed in the current argument. If shellparam.optnext is NULL,
10346 * then it's the first time getopts has been called.
10348 static int FAST_FUNC
10349 getoptscmd(int argc, char **argv)
10354 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10356 optbase = shellparam.p;
10357 if (shellparam.optind > shellparam.nparam + 1) {
10358 shellparam.optind = 1;
10359 shellparam.optoff = -1;
10362 optbase = &argv[3];
10363 if (shellparam.optind > argc - 2) {
10364 shellparam.optind = 1;
10365 shellparam.optoff = -1;
10369 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10370 &shellparam.optoff);
10372 #endif /* ASH_GETOPTS */
10375 /* ============ Shell parser */
10378 struct heredoc *next; /* next here document in list */
10379 union node *here; /* redirection node */
10380 char *eofmark; /* string indicating end of input */
10381 smallint striptabs; /* if set, strip leading tabs */
10384 static smallint tokpushback; /* last token pushed back */
10385 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10386 static smallint quoteflag; /* set if (part of) last token was quoted */
10387 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10388 static struct heredoc *heredoclist; /* list of here documents to read */
10389 static char *wordtext; /* text of last word returned by readtoken */
10390 static struct nodelist *backquotelist;
10391 static union node *redirnode;
10392 static struct heredoc *heredoc;
10394 static const char *
10395 tokname(char *buf, int tok)
10398 return tokname_array[tok] + 1;
10399 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10403 /* raise_error_unexpected_syntax:
10404 * Called when an unexpected token is read during the parse. The argument
10405 * is the token that is expected, or -1 if more than one type of token can
10406 * occur at this point.
10408 static void raise_error_unexpected_syntax(int) NORETURN;
10410 raise_error_unexpected_syntax(int token)
10416 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10418 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10419 raise_error_syntax(msg);
10423 #define EOFMARKLEN 79
10425 /* parsing is heavily cross-recursive, need these forward decls */
10426 static union node *andor(void);
10427 static union node *pipeline(void);
10428 static union node *parse_command(void);
10429 static void parseheredoc(void);
10430 static char peektoken(void);
10431 static int readtoken(void);
10433 static union node *
10436 union node *n1, *n2, *n3;
10439 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10440 if (nlflag == 2 && peektoken())
10446 if (tok == TBACKGND) {
10447 if (n2->type == NPIPE) {
10448 n2->npipe.pipe_backgnd = 1;
10450 if (n2->type != NREDIR) {
10451 n3 = stzalloc(sizeof(struct nredir));
10453 /*n3->nredir.redirect = NULL; - stzalloc did it */
10456 n2->type = NBACKGND;
10462 n3 = stzalloc(sizeof(struct nbinary));
10464 n3->nbinary.ch1 = n1;
10465 n3->nbinary.ch2 = n2;
10481 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10489 pungetc(); /* push back EOF on input */
10493 raise_error_unexpected_syntax(-1);
10500 static union node *
10503 union node *n1, *n2, *n3;
10511 } else if (t == TOR) {
10517 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10519 n3 = stzalloc(sizeof(struct nbinary));
10521 n3->nbinary.ch1 = n1;
10522 n3->nbinary.ch2 = n2;
10527 static union node *
10530 union node *n1, *n2, *pipenode;
10531 struct nodelist *lp, *prev;
10535 TRACE(("pipeline: entered\n"));
10536 if (readtoken() == TNOT) {
10538 checkkwd = CHKKWD | CHKALIAS;
10541 n1 = parse_command();
10542 if (readtoken() == TPIPE) {
10543 pipenode = stzalloc(sizeof(struct npipe));
10544 pipenode->type = NPIPE;
10545 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10546 lp = stzalloc(sizeof(struct nodelist));
10547 pipenode->npipe.cmdlist = lp;
10551 lp = stzalloc(sizeof(struct nodelist));
10552 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10553 lp->n = parse_command();
10555 } while (readtoken() == TPIPE);
10561 n2 = stzalloc(sizeof(struct nnot));
10569 static union node *
10574 n = stzalloc(sizeof(struct narg));
10576 /*n->narg.next = NULL; - stzalloc did it */
10577 n->narg.text = wordtext;
10578 n->narg.backquote = backquotelist;
10583 fixredir(union node *n, const char *text, int err)
10587 TRACE(("Fix redir %s %d\n", text, err));
10589 n->ndup.vname = NULL;
10591 fd = bb_strtou(text, NULL, 10);
10592 if (!errno && fd >= 0)
10593 n->ndup.dupfd = fd;
10594 else if (LONE_DASH(text))
10595 n->ndup.dupfd = -1;
10598 raise_error_syntax("bad fd number");
10599 n->ndup.vname = makename();
10604 * Returns true if the text contains nothing to expand (no dollar signs
10608 noexpand(const char *text)
10612 while ((c = *text++) != '\0') {
10613 if (c == CTLQUOTEMARK)
10617 else if (SIT(c, BASESYNTAX) == CCTL)
10626 union node *n = redirnode;
10628 if (readtoken() != TWORD)
10629 raise_error_unexpected_syntax(-1);
10630 if (n->type == NHERE) {
10631 struct heredoc *here = heredoc;
10635 if (quoteflag == 0)
10637 TRACE(("Here document %d\n", n->type));
10638 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10639 raise_error_syntax("illegal eof marker for << redirection");
10640 rmescapes(wordtext, 0);
10641 here->eofmark = wordtext;
10643 if (heredoclist == NULL)
10644 heredoclist = here;
10646 for (p = heredoclist; p->next; p = p->next)
10650 } else if (n->type == NTOFD || n->type == NFROMFD) {
10651 fixredir(n, wordtext, 0);
10653 n->nfile.fname = makename();
10657 static union node *
10660 union node *args, **app;
10661 union node *n = NULL;
10662 union node *vars, **vpp;
10663 union node **rpp, *redir;
10665 #if ENABLE_ASH_BASH_COMPAT
10666 smallint double_brackets_flag = 0;
10676 savecheckkwd = CHKALIAS;
10679 checkkwd = savecheckkwd;
10682 #if ENABLE_ASH_BASH_COMPAT
10683 case TAND: /* "&&" */
10684 case TOR: /* "||" */
10685 if (!double_brackets_flag) {
10689 wordtext = (char *) (t == TAND ? "-a" : "-o");
10692 n = stzalloc(sizeof(struct narg));
10694 /*n->narg.next = NULL; - stzalloc did it */
10695 n->narg.text = wordtext;
10696 #if ENABLE_ASH_BASH_COMPAT
10697 if (strcmp("[[", wordtext) == 0)
10698 double_brackets_flag = 1;
10699 else if (strcmp("]]", wordtext) == 0)
10700 double_brackets_flag = 0;
10702 n->narg.backquote = backquotelist;
10703 if (savecheckkwd && isassignment(wordtext)) {
10705 vpp = &n->narg.next;
10708 app = &n->narg.next;
10713 *rpp = n = redirnode;
10714 rpp = &n->nfile.next;
10715 parsefname(); /* read name of redirection file */
10718 if (args && app == &args->narg.next
10721 struct builtincmd *bcmd;
10724 /* We have a function */
10725 if (readtoken() != TRP)
10726 raise_error_unexpected_syntax(TRP);
10727 name = n->narg.text;
10728 if (!goodname(name)
10729 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10731 raise_error_syntax("bad function name");
10734 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10735 n->narg.next = parse_command();
10748 n = stzalloc(sizeof(struct ncmd));
10750 n->ncmd.args = args;
10751 n->ncmd.assign = vars;
10752 n->ncmd.redirect = redir;
10756 static union node *
10757 parse_command(void)
10759 union node *n1, *n2;
10760 union node *ap, **app;
10761 union node *cp, **cpp;
10762 union node *redir, **rpp;
10769 switch (readtoken()) {
10771 raise_error_unexpected_syntax(-1);
10774 n1 = stzalloc(sizeof(struct nif));
10776 n1->nif.test = list(0);
10777 if (readtoken() != TTHEN)
10778 raise_error_unexpected_syntax(TTHEN);
10779 n1->nif.ifpart = list(0);
10781 while (readtoken() == TELIF) {
10782 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10783 n2 = n2->nif.elsepart;
10785 n2->nif.test = list(0);
10786 if (readtoken() != TTHEN)
10787 raise_error_unexpected_syntax(TTHEN);
10788 n2->nif.ifpart = list(0);
10790 if (lasttoken == TELSE)
10791 n2->nif.elsepart = list(0);
10793 n2->nif.elsepart = NULL;
10801 n1 = stzalloc(sizeof(struct nbinary));
10802 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10803 n1->nbinary.ch1 = list(0);
10806 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10807 got == TWORD ? wordtext : ""));
10808 raise_error_unexpected_syntax(TDO);
10810 n1->nbinary.ch2 = list(0);
10815 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10816 raise_error_syntax("bad for loop variable");
10817 n1 = stzalloc(sizeof(struct nfor));
10819 n1->nfor.var = wordtext;
10820 checkkwd = CHKKWD | CHKALIAS;
10821 if (readtoken() == TIN) {
10823 while (readtoken() == TWORD) {
10824 n2 = stzalloc(sizeof(struct narg));
10826 /*n2->narg.next = NULL; - stzalloc did it */
10827 n2->narg.text = wordtext;
10828 n2->narg.backquote = backquotelist;
10830 app = &n2->narg.next;
10833 n1->nfor.args = ap;
10834 if (lasttoken != TNL && lasttoken != TSEMI)
10835 raise_error_unexpected_syntax(-1);
10837 n2 = stzalloc(sizeof(struct narg));
10839 /*n2->narg.next = NULL; - stzalloc did it */
10840 n2->narg.text = (char *)dolatstr;
10841 /*n2->narg.backquote = NULL;*/
10842 n1->nfor.args = n2;
10844 * Newline or semicolon here is optional (but note
10845 * that the original Bourne shell only allowed NL).
10847 if (lasttoken != TNL && lasttoken != TSEMI)
10850 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10851 if (readtoken() != TDO)
10852 raise_error_unexpected_syntax(TDO);
10853 n1->nfor.body = list(0);
10857 n1 = stzalloc(sizeof(struct ncase));
10859 if (readtoken() != TWORD)
10860 raise_error_unexpected_syntax(TWORD);
10861 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10863 /*n2->narg.next = NULL; - stzalloc did it */
10864 n2->narg.text = wordtext;
10865 n2->narg.backquote = backquotelist;
10867 checkkwd = CHKKWD | CHKALIAS;
10868 } while (readtoken() == TNL);
10869 if (lasttoken != TIN)
10870 raise_error_unexpected_syntax(TIN);
10871 cpp = &n1->ncase.cases;
10873 checkkwd = CHKNL | CHKKWD;
10875 while (t != TESAC) {
10876 if (lasttoken == TLP)
10878 *cpp = cp = stzalloc(sizeof(struct nclist));
10880 app = &cp->nclist.pattern;
10882 *app = ap = stzalloc(sizeof(struct narg));
10884 /*ap->narg.next = NULL; - stzalloc did it */
10885 ap->narg.text = wordtext;
10886 ap->narg.backquote = backquotelist;
10887 if (readtoken() != TPIPE)
10889 app = &ap->narg.next;
10892 //ap->narg.next = NULL;
10893 if (lasttoken != TRP)
10894 raise_error_unexpected_syntax(TRP);
10895 cp->nclist.body = list(2);
10897 cpp = &cp->nclist.next;
10899 checkkwd = CHKNL | CHKKWD;
10903 raise_error_unexpected_syntax(TENDCASE);
10910 n1 = stzalloc(sizeof(struct nredir));
10911 n1->type = NSUBSHELL;
10912 n1->nredir.n = list(0);
10913 /*n1->nredir.redirect = NULL; - stzalloc did it */
10923 return simplecmd();
10926 if (readtoken() != t)
10927 raise_error_unexpected_syntax(t);
10930 /* Now check for redirection which may follow command */
10931 checkkwd = CHKKWD | CHKALIAS;
10933 while (readtoken() == TREDIR) {
10934 *rpp = n2 = redirnode;
10935 rpp = &n2->nfile.next;
10941 if (n1->type != NSUBSHELL) {
10942 n2 = stzalloc(sizeof(struct nredir));
10947 n1->nredir.redirect = redir;
10952 #if ENABLE_ASH_BASH_COMPAT
10953 static int decode_dollar_squote(void)
10955 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10961 p = strchr(C_escapes, c);
10966 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10970 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10972 } else if (c == 'x') { /* \xHH */
10976 } while (isxdigit(c) && --cnt);
10978 if (cnt == 3) { /* \x but next char is "bad" */
10982 } else { /* simple seq like \\ or \t */
10987 c = bb_process_escape_sequence((void*)&p);
10988 } else { /* unrecognized "\z": print both chars unless ' or " */
10989 if (c != '\'' && c != '"') {
10991 c |= 0x100; /* "please encode \, then me" */
10999 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11000 * is not NULL, read a here document. In the latter case, eofmark is the
11001 * word which marks the end of the document and striptabs is true if
11002 * leading tabs should be stripped from the document. The argument c
11003 * is the first character of the input token or document.
11005 * Because C does not have internal subroutines, I have simulated them
11006 * using goto's to implement the subroutine linkage. The following macros
11007 * will run code that appears at the end of readtoken1.
11009 #define CHECKEND() {goto checkend; checkend_return:;}
11010 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11011 #define PARSESUB() {goto parsesub; parsesub_return:;}
11012 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11013 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11014 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11016 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11018 /* NB: syntax parameter fits into smallint */
11019 /* c parameter is an unsigned char or PEOF or PEOA */
11022 char line[EOFMARKLEN + 1];
11023 struct nodelist *bqlist;
11027 smallint prevsyntax; /* syntax before arithmetic */
11028 #if ENABLE_ASH_EXPAND_PRMT
11029 smallint pssyntax; /* we are expanding a prompt string */
11031 int varnest; /* levels of variables expansion */
11032 int arinest; /* levels of arithmetic expansion */
11033 int parenlevel; /* levels of parens in arithmetic */
11034 int dqvarnest; /* levels of variables expansion within double quotes */
11036 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11039 /* Avoid longjmp clobbering */
11045 (void) &parenlevel;
11048 (void) &prevsyntax;
11051 startlinno = g_parsefile->linno;
11055 #if ENABLE_ASH_EXPAND_PRMT
11056 pssyntax = (syntax == PSSYNTAX);
11060 dblquote = (syntax == DQSYNTAX);
11066 STARTSTACKSTR(out);
11068 /* For each line, until end of word */
11069 CHECKEND(); /* set c to PEOF if at end of here document */
11070 for (;;) { /* until end of line or end of word */
11071 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11072 switch (SIT(c, syntax)) {
11073 case CNL: /* '\n' */
11074 if (syntax == BASESYNTAX)
11075 goto endword; /* exit outer loop */
11077 g_parsefile->linno++;
11078 setprompt_if(doprompt, 2);
11080 goto loop; /* continue outer loop */
11085 if (eofmark == NULL || dblquote)
11086 USTPUTC(CTLESC, out);
11087 #if ENABLE_ASH_BASH_COMPAT
11088 if (c == '\\' && bash_dollar_squote) {
11089 c = decode_dollar_squote();
11091 USTPUTC('\\', out);
11092 c = (unsigned char)c;
11098 case CBACK: /* backslash */
11099 c = pgetc_without_PEOA();
11101 USTPUTC(CTLESC, out);
11102 USTPUTC('\\', out);
11104 } else if (c == '\n') {
11105 setprompt_if(doprompt, 2);
11107 #if ENABLE_ASH_EXPAND_PRMT
11108 if (c == '$' && pssyntax) {
11109 USTPUTC(CTLESC, out);
11110 USTPUTC('\\', out);
11113 /* Backslash is retained if we are in "str" and next char isn't special */
11118 && (c != '"' || eofmark != NULL)
11120 USTPUTC(CTLESC, out);
11121 USTPUTC('\\', out);
11123 if (SIT(c, SQSYNTAX) == CCTL)
11124 USTPUTC(CTLESC, out);
11132 if (eofmark == NULL) {
11133 USTPUTC(CTLQUOTEMARK, out);
11141 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11142 if (eofmark != NULL && arinest == 0
11147 if (dqvarnest == 0) {
11148 syntax = BASESYNTAX;
11155 case CVAR: /* '$' */
11156 PARSESUB(); /* parse substitution */
11158 case CENDVAR: /* '}' */
11161 if (dqvarnest > 0) {
11168 #if ENABLE_SH_MATH_SUPPORT
11169 case CLP: /* '(' in arithmetic */
11173 case CRP: /* ')' in arithmetic */
11174 if (parenlevel > 0) {
11177 if (pgetc() == ')') {
11178 if (--arinest == 0) {
11179 syntax = prevsyntax;
11180 dblquote = (syntax == DQSYNTAX);
11185 * unbalanced parens
11186 * (don't 2nd guess - no error)
11194 case CBQUOTE: /* '`' */
11198 goto endword; /* exit outer loop */
11202 if (varnest == 0) {
11203 #if ENABLE_ASH_BASH_COMPAT
11205 if (pgetc() == '>')
11206 c = 0x100 + '>'; /* flag &> */
11210 goto endword; /* exit outer loop */
11212 IF_ASH_ALIAS(if (c != PEOA))
11219 #if ENABLE_SH_MATH_SUPPORT
11220 if (syntax == ARISYNTAX)
11221 raise_error_syntax("missing '))'");
11223 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11224 raise_error_syntax("unterminated quoted string");
11225 if (varnest != 0) {
11226 startlinno = g_parsefile->linno;
11228 raise_error_syntax("missing '}'");
11230 USTPUTC('\0', out);
11231 len = out - (char *)stackblock();
11232 out = stackblock();
11233 if (eofmark == NULL) {
11234 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11237 if (isdigit_str9(out)) {
11238 PARSEREDIR(); /* passed as params: out, c */
11239 lasttoken = TREDIR;
11242 /* else: non-number X seen, interpret it
11243 * as "NNNX>file" = "NNNX >file" */
11247 quoteflag = quotef;
11248 backquotelist = bqlist;
11249 grabstackblock(len);
11253 /* end of readtoken routine */
11256 * Check to see whether we are at the end of the here document. When this
11257 * is called, c is set to the first character of the next input line. If
11258 * we are at the end of the here document, this routine sets the c to PEOF.
11262 #if ENABLE_ASH_ALIAS
11264 c = pgetc_without_PEOA();
11267 while (c == '\t') {
11268 c = pgetc_without_PEOA();
11271 if (c == *eofmark) {
11272 if (pfgets(line, sizeof(line)) != NULL) {
11276 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11278 if (*p == '\n' && *q == '\0') {
11280 g_parsefile->linno++;
11281 needprompt = doprompt;
11283 pushstring(line, NULL);
11288 goto checkend_return;
11292 * Parse a redirection operator. The variable "out" points to a string
11293 * specifying the fd to be redirected. The variable "c" contains the
11294 * first character of the redirection operator.
11297 /* out is already checked to be a valid number or "" */
11298 int fd = (*out == '\0' ? -1 : atoi(out));
11301 np = stzalloc(sizeof(struct nfile));
11306 np->type = NAPPEND;
11308 np->type = NCLOBBER;
11311 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11317 #if ENABLE_ASH_BASH_COMPAT
11318 else if (c == 0x100 + '>') { /* this flags &> redirection */
11320 pgetc(); /* this is '>', no need to check */
11324 else { /* c == '<' */
11325 /*np->nfile.fd = 0; - stzalloc did it */
11329 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11330 np = stzalloc(sizeof(struct nhere));
11331 /*np->nfile.fd = 0; - stzalloc did it */
11334 heredoc = stzalloc(sizeof(struct heredoc));
11335 heredoc->here = np;
11338 heredoc->striptabs = 1;
11340 /*heredoc->striptabs = 0; - stzalloc did it */
11346 np->type = NFROMFD;
11350 np->type = NFROMTO;
11362 goto parseredir_return;
11366 * Parse a substitution. At this point, we have read the dollar sign
11367 * and nothing else.
11370 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11371 * (assuming ascii char codes, as the original implementation did) */
11372 #define is_special(c) \
11373 (((unsigned)(c) - 33 < 32) \
11374 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11376 unsigned char subtype;
11381 if (c > 255 /* PEOA or PEOF */
11382 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11384 #if ENABLE_ASH_BASH_COMPAT
11386 bash_dollar_squote = 1;
11391 } else if (c == '(') {
11392 /* $(command) or $((arith)) */
11393 if (pgetc() == '(') {
11394 #if ENABLE_SH_MATH_SUPPORT
11397 raise_error_syntax("you disabled math support for $((arith)) syntax");
11404 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11405 USTPUTC(CTLVAR, out);
11406 typeloc = out - (char *)stackblock();
11407 USTPUTC(VSNORMAL, out);
11408 subtype = VSNORMAL;
11414 c = '#'; /* ${#} - same as $# */
11416 subtype = VSLENGTH; /* ${#VAR} */
11421 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11422 /* $[{[#]]NAME[}] */
11426 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11427 } else if (isdigit(c)) {
11428 /* $[{[#]]NUM[}] */
11432 } while (isdigit(c));
11433 } else if (is_special(c)) {
11434 /* $[{[#]]<specialchar>[}] */
11439 raise_error_syntax("bad substitution");
11441 if (c != '}' && subtype == VSLENGTH) {
11442 /* ${#VAR didn't end with } */
11448 if (subtype == 0) {
11449 /* ${VAR...} but not $VAR or ${#VAR} */
11450 /* c == first char after VAR */
11454 #if ENABLE_ASH_BASH_COMPAT
11455 if (c == ':' || c == '$' || isdigit(c)) {
11456 //TODO: support more general format ${v:EXPR:EXPR},
11457 // where EXPR follows $(()) rules
11458 subtype = VSSUBSTR;
11460 break; /* "goto do_pungetc" is bigger (!) */
11466 static const char types[] ALIGN1 = "}-+?=";
11467 const char *p = strchr(types, c);
11470 subtype = p - types + VSNORMAL;
11476 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11483 #if ENABLE_ASH_BASH_COMPAT
11485 /* ${v/[/]pattern/repl} */
11486 //TODO: encode pattern and repl separately.
11487 // Currently ${v/$var_with_slash/repl} is horribly broken
11488 subtype = VSREPLACE;
11492 subtype++; /* VSREPLACEALL */
11500 if (dblquote || arinest)
11502 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11503 if (subtype != VSNORMAL) {
11505 if (dblquote || arinest) {
11510 goto parsesub_return;
11514 * Called to parse command substitutions. Newstyle is set if the command
11515 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11516 * list of commands (passed by reference), and savelen is the number of
11517 * characters on the top of the stack which must be preserved.
11520 struct nodelist **nlpp;
11523 char *volatile str;
11524 struct jmploc jmploc;
11525 struct jmploc *volatile savehandler;
11527 smallint saveprompt = 0;
11530 (void) &saveprompt;
11532 savepbq = parsebackquote;
11533 if (setjmp(jmploc.loc)) {
11535 parsebackquote = 0;
11536 exception_handler = savehandler;
11537 longjmp(exception_handler->loc, 1);
11541 savelen = out - (char *)stackblock();
11543 str = ckmalloc(savelen);
11544 memcpy(str, stackblock(), savelen);
11546 savehandler = exception_handler;
11547 exception_handler = &jmploc;
11550 /* We must read until the closing backquote, giving special
11551 treatment to some slashes, and then push the string and
11552 reread it as input, interpreting it normally. */
11557 STARTSTACKSTR(pout);
11561 setprompt_if(needprompt, 2);
11570 g_parsefile->linno++;
11571 setprompt_if(doprompt, 2);
11573 * If eating a newline, avoid putting
11574 * the newline into the new character
11575 * stream (via the STPUTC after the
11580 if (pc != '\\' && pc != '`' && pc != '$'
11581 && (!dblquote || pc != '"')
11583 STPUTC('\\', pout);
11585 if (pc <= 255 /* not PEOA or PEOF */) {
11591 IF_ASH_ALIAS(case PEOA:)
11592 startlinno = g_parsefile->linno;
11593 raise_error_syntax("EOF in backquote substitution");
11596 g_parsefile->linno++;
11597 needprompt = doprompt;
11606 STPUTC('\0', pout);
11607 psavelen = pout - (char *)stackblock();
11608 if (psavelen > 0) {
11609 pstr = grabstackstr(pout);
11610 setinputstring(pstr);
11615 nlpp = &(*nlpp)->next;
11616 *nlpp = stzalloc(sizeof(**nlpp));
11617 /* (*nlpp)->next = NULL; - stzalloc did it */
11618 parsebackquote = oldstyle;
11621 saveprompt = doprompt;
11628 doprompt = saveprompt;
11629 else if (readtoken() != TRP)
11630 raise_error_unexpected_syntax(TRP);
11635 * Start reading from old file again, ignoring any pushed back
11636 * tokens left from the backquote parsing
11641 while (stackblocksize() <= savelen)
11643 STARTSTACKSTR(out);
11645 memcpy(out, str, savelen);
11646 STADJUST(savelen, out);
11652 parsebackquote = savepbq;
11653 exception_handler = savehandler;
11654 if (arinest || dblquote)
11655 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11657 USTPUTC(CTLBACKQ, out);
11659 goto parsebackq_oldreturn;
11660 goto parsebackq_newreturn;
11663 #if ENABLE_SH_MATH_SUPPORT
11665 * Parse an arithmetic expansion (indicate start of one and set state)
11668 if (++arinest == 1) {
11669 prevsyntax = syntax;
11670 syntax = ARISYNTAX;
11671 USTPUTC(CTLARI, out);
11678 * we collapse embedded arithmetic expansion to
11679 * parenthesis, which should be equivalent
11683 goto parsearith_return;
11687 } /* end of readtoken */
11690 * Read the next input token.
11691 * If the token is a word, we set backquotelist to the list of cmds in
11692 * backquotes. We set quoteflag to true if any part of the word was
11694 * If the token is TREDIR, then we set redirnode to a structure containing
11696 * In all cases, the variable startlinno is set to the number of the line
11697 * on which the token starts.
11699 * [Change comment: here documents and internal procedures]
11700 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11701 * word parsing code into a separate routine. In this case, readtoken
11702 * doesn't need to have any internal procedures, but parseword does.
11703 * We could also make parseoperator in essence the main routine, and
11704 * have parseword (readtoken1?) handle both words and redirection.]
11706 #define NEW_xxreadtoken
11707 #ifdef NEW_xxreadtoken
11708 /* singles must be first! */
11709 static const char xxreadtoken_chars[7] ALIGN1 = {
11710 '\n', '(', ')', /* singles */
11711 '&', '|', ';', /* doubles */
11715 #define xxreadtoken_singles 3
11716 #define xxreadtoken_doubles 3
11718 static const char xxreadtoken_tokens[] ALIGN1 = {
11719 TNL, TLP, TRP, /* only single occurrence allowed */
11720 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11721 TEOF, /* corresponds to trailing nul */
11722 TAND, TOR, TENDCASE /* if double occurrence */
11734 setprompt_if(needprompt, 2);
11735 startlinno = g_parsefile->linno;
11736 for (;;) { /* until token or start of word found */
11738 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11742 while ((c = pgetc()) != '\n' && c != PEOF)
11745 } else if (c == '\\') {
11746 if (pgetc() != '\n') {
11748 break; /* return readtoken1(...) */
11750 startlinno = ++g_parsefile->linno;
11751 setprompt_if(doprompt, 2);
11755 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11758 g_parsefile->linno++;
11759 needprompt = doprompt;
11762 p = strchr(xxreadtoken_chars, c);
11764 break; /* return readtoken1(...) */
11766 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11768 if (cc == c) { /* double occurrence? */
11769 p += xxreadtoken_doubles + 1;
11772 #if ENABLE_ASH_BASH_COMPAT
11773 if (c == '&' && cc == '>') /* &> */
11774 break; /* return readtoken1(...) */
11779 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11784 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11786 #else /* old xxreadtoken */
11787 #define RETURN(token) return lasttoken = token
11797 setprompt_if(needprompt, 2);
11798 startlinno = g_parsefile->linno;
11799 for (;;) { /* until token or start of word found */
11802 case ' ': case '\t':
11803 IF_ASH_ALIAS(case PEOA:)
11806 while ((c = pgetc()) != '\n' && c != PEOF)
11811 if (pgetc() == '\n') {
11812 startlinno = ++g_parsefile->linno;
11813 setprompt_if(doprompt, 2);
11819 g_parsefile->linno++;
11820 needprompt = doprompt;
11825 if (pgetc() == '&')
11830 if (pgetc() == '|')
11835 if (pgetc() == ';')
11848 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11851 #endif /* old xxreadtoken */
11858 smallint alreadyseen = tokpushback;
11861 #if ENABLE_ASH_ALIAS
11870 if (checkkwd & CHKNL) {
11877 if (t != TWORD || quoteflag) {
11882 * check for keywords
11884 if (checkkwd & CHKKWD) {
11885 const char *const *pp;
11887 pp = findkwd(wordtext);
11889 lasttoken = t = pp - tokname_array;
11890 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11895 if (checkkwd & CHKALIAS) {
11896 #if ENABLE_ASH_ALIAS
11898 ap = lookupalias(wordtext, 1);
11901 pushstring(ap->val, ap);
11911 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11913 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11925 return tokname_array[t][0];
11929 * Read and parse a command. Returns NODE_EOF on end of file.
11930 * (NULL is a valid parse tree indicating a blank line.)
11932 static union node *
11933 parsecmd(int interact)
11938 doprompt = interact;
11939 setprompt_if(doprompt, doprompt);
11951 * Input any here documents.
11956 struct heredoc *here;
11959 here = heredoclist;
11960 heredoclist = NULL;
11963 setprompt_if(needprompt, 2);
11964 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
11965 here->eofmark, here->striptabs);
11966 n = stzalloc(sizeof(struct narg));
11967 n->narg.type = NARG;
11968 /*n->narg.next = NULL; - stzalloc did it */
11969 n->narg.text = wordtext;
11970 n->narg.backquote = backquotelist;
11971 here->here->nhere.doc = n;
11978 * called by editline -- any expansions to the prompt should be added here.
11980 #if ENABLE_ASH_EXPAND_PRMT
11981 static const char *
11982 expandstr(const char *ps)
11986 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11987 * and token processing _can_ alter it (delete NULs etc). */
11988 setinputstring((char *)ps);
11989 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11992 n.narg.type = NARG;
11993 n.narg.next = NULL;
11994 n.narg.text = wordtext;
11995 n.narg.backquote = backquotelist;
11997 expandarg(&n, NULL, 0);
11998 return stackblock();
12003 * Execute a command or commands contained in a string.
12006 evalstring(char *s, int mask)
12009 struct stackmark smark;
12013 setstackmark(&smark);
12016 while ((n = parsecmd(0)) != NODE_EOF) {
12018 popstackmark(&smark);
12031 * The eval command.
12033 static int FAST_FUNC
12034 evalcmd(int argc UNUSED_PARAM, char **argv)
12043 STARTSTACKSTR(concat);
12045 concat = stack_putstr(p, concat);
12049 STPUTC(' ', concat);
12051 STPUTC('\0', concat);
12052 p = grabstackstr(concat);
12054 evalstring(p, ~SKIPEVAL);
12059 #if ENABLE_ASH_IDLE_TIMEOUT
12060 static smallint timed_out;
12062 static void alrm_sighandler(int sig UNUSED_PARAM)
12064 /* Close stdin, making interactive command reading stop.
12065 * Otherwise, timeout doesn't trigger until <Enter> is pressed.
12069 open("/dev/null", O_RDONLY);
12077 * Read and execute commands.
12078 * "Top" is nonzero for the top level command loop;
12079 * it turns on prompting if the shell is interactive.
12085 struct stackmark smark;
12089 TRACE(("cmdloop(%d) called\n", top));
12092 #if ENABLE_ASH_IDLE_TIMEOUT
12093 int tmout_seconds = 0;
12095 if (top && iflag) {
12096 const char *tmout_var = lookupvar("TMOUT");
12098 tmout_seconds = atoi(tmout_var);
12099 if (tmout_seconds > 0) {
12100 signal(SIGALRM, alrm_sighandler);
12101 alarm(tmout_seconds);
12107 setstackmark(&smark);
12110 showjobs(stderr, SHOW_CHANGED);
12113 if (iflag && top) {
12117 n = parsecmd(inter);
12118 #if ENABLE_ASH_IDLE_TIMEOUT
12120 printf("\007timed out waiting for input: auto-logout\n");
12123 if (tmout_seconds > 0)
12127 if (DEBUG > 2 && debug && (n != NODE_EOF))
12130 if (n == NODE_EOF) {
12131 if (!top || numeof >= 50)
12133 if (!stoppedjobs()) {
12136 out2str("\nUse \"exit\" to leave shell.\n");
12139 } else if (nflag == 0) {
12140 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12145 popstackmark(&smark);
12150 return skip & SKIPEVAL;
12157 * Take commands from a file. To be compatible we should do a path
12158 * search for the file, which is necessary to find sub-commands.
12161 find_dot_file(char *name)
12164 const char *path = pathval();
12167 /* don't try this for absolute or relative paths */
12168 if (strchr(name, '/'))
12171 /* IIRC standards do not say whether . is to be searched.
12172 * And it is even smaller this way, making it unconditional for now:
12174 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12179 while ((fullname = path_advance(&path, name)) != NULL) {
12181 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12183 * Don't bother freeing here, since it will
12184 * be freed by the caller.
12188 if (fullname != name)
12189 stunalloc(fullname);
12192 /* not found in the PATH */
12193 ash_msg_and_raise_error("%s: not found", name);
12197 static int FAST_FUNC
12198 dotcmd(int argc, char **argv)
12201 struct strlist *sp;
12202 volatile struct shparam saveparam;
12204 for (sp = cmdenviron; sp; sp = sp->next)
12205 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12208 /* bash says: "bash: .: filename argument required" */
12209 return 2; /* bash compat */
12212 /* "false; . empty_file; echo $?" should print 0, not 1: */
12215 fullname = find_dot_file(argv[1]);
12219 if (argc) { /* argc > 0, argv[0] != NULL */
12220 saveparam = shellparam;
12221 shellparam.malloced = 0;
12222 shellparam.nparam = argc;
12223 shellparam.p = argv;
12226 setinputfile(fullname, INPUT_PUSH_FILE);
12227 commandname = fullname;
12232 freeparam(&shellparam);
12233 shellparam = saveparam;
12239 static int FAST_FUNC
12240 exitcmd(int argc UNUSED_PARAM, char **argv)
12245 exitstatus = number(argv[1]);
12246 raise_exception(EXEXIT);
12251 * Read a file containing shell functions.
12254 readcmdfile(char *name)
12256 setinputfile(name, INPUT_PUSH_FILE);
12262 /* ============ find_command inplementation */
12265 * Resolve a command name. If you change this routine, you may have to
12266 * change the shellexec routine as well.
12269 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12271 struct tblentry *cmdp;
12278 struct builtincmd *bcmd;
12280 /* If name contains a slash, don't use PATH or hash table */
12281 if (strchr(name, '/') != NULL) {
12282 entry->u.index = -1;
12283 if (act & DO_ABS) {
12284 while (stat(name, &statb) < 0) {
12286 if (errno == EINTR)
12289 entry->cmdtype = CMDUNKNOWN;
12293 entry->cmdtype = CMDNORMAL;
12297 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12299 updatetbl = (path == pathval());
12302 if (strstr(path, "%builtin") != NULL)
12303 act |= DO_ALTBLTIN;
12306 /* If name is in the table, check answer will be ok */
12307 cmdp = cmdlookup(name, 0);
12308 if (cmdp != NULL) {
12311 switch (cmdp->cmdtype) {
12329 } else if (cmdp->rehash == 0)
12330 /* if not invalidated by cd, we're done */
12334 /* If %builtin not in path, check for builtin next */
12335 bcmd = find_builtin(name);
12337 if (IS_BUILTIN_REGULAR(bcmd))
12338 goto builtin_success;
12339 if (act & DO_ALTPATH) {
12340 if (!(act & DO_ALTBLTIN))
12341 goto builtin_success;
12342 } else if (builtinloc <= 0) {
12343 goto builtin_success;
12347 #if ENABLE_FEATURE_SH_STANDALONE
12349 int applet_no = find_applet_by_name(name);
12350 if (applet_no >= 0) {
12351 entry->cmdtype = CMDNORMAL;
12352 entry->u.index = -2 - applet_no;
12358 /* We have to search path. */
12359 prev = -1; /* where to start */
12360 if (cmdp && cmdp->rehash) { /* doing a rehash */
12361 if (cmdp->cmdtype == CMDBUILTIN)
12364 prev = cmdp->param.index;
12370 while ((fullname = path_advance(&path, name)) != NULL) {
12371 stunalloc(fullname);
12372 /* NB: code below will still use fullname
12373 * despite it being "unallocated" */
12376 if (prefix(pathopt, "builtin")) {
12378 goto builtin_success;
12381 if ((act & DO_NOFUNC)
12382 || !prefix(pathopt, "func")
12383 ) { /* ignore unimplemented options */
12387 /* if rehash, don't redo absolute path names */
12388 if (fullname[0] == '/' && idx <= prev) {
12391 TRACE(("searchexec \"%s\": no change\n", name));
12394 while (stat(fullname, &statb) < 0) {
12396 if (errno == EINTR)
12399 if (errno != ENOENT && errno != ENOTDIR)
12403 e = EACCES; /* if we fail, this will be the error */
12404 if (!S_ISREG(statb.st_mode))
12406 if (pathopt) { /* this is a %func directory */
12407 stalloc(strlen(fullname) + 1);
12408 /* NB: stalloc will return space pointed by fullname
12409 * (because we don't have any intervening allocations
12410 * between stunalloc above and this stalloc) */
12411 readcmdfile(fullname);
12412 cmdp = cmdlookup(name, 0);
12413 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12414 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12415 stunalloc(fullname);
12418 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12420 entry->cmdtype = CMDNORMAL;
12421 entry->u.index = idx;
12425 cmdp = cmdlookup(name, 1);
12426 cmdp->cmdtype = CMDNORMAL;
12427 cmdp->param.index = idx;
12432 /* We failed. If there was an entry for this command, delete it */
12433 if (cmdp && updatetbl)
12434 delete_cmd_entry();
12436 ash_msg("%s: %s", name, errmsg(e, "not found"));
12437 entry->cmdtype = CMDUNKNOWN;
12442 entry->cmdtype = CMDBUILTIN;
12443 entry->u.cmd = bcmd;
12447 cmdp = cmdlookup(name, 1);
12448 cmdp->cmdtype = CMDBUILTIN;
12449 cmdp->param.cmd = bcmd;
12453 entry->cmdtype = cmdp->cmdtype;
12454 entry->u = cmdp->param;
12458 /* ============ trap.c */
12461 * The trap builtin.
12463 static int FAST_FUNC
12464 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12468 int signo, exitcode;
12473 for (signo = 0; signo < NSIG; signo++) {
12474 char *tr = trap_ptr[signo];
12476 /* note: bash adds "SIG", but only if invoked
12477 * as "bash". If called as "sh", or if set -o posix,
12478 * then it prints short signal names.
12479 * We are printing short names: */
12480 out1fmt("trap -- %s %s\n",
12482 get_signame(signo));
12483 /* trap_ptr != trap only if we are in special-cased `trap` code.
12484 * In this case, we will exit very soon, no need to free(). */
12485 /* if (trap_ptr != trap && tp[0]) */
12490 if (trap_ptr != trap) {
12503 signo = get_signum(*ap);
12505 /* Mimic bash message exactly */
12506 ash_msg("%s: invalid signal specification", *ap);
12512 if (LONE_DASH(action))
12515 action = ckstrdup(action);
12519 may_have_traps = 1;
12520 trap[signo] = action;
12531 /* ============ Builtins */
12533 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12535 * Lists available builtins
12537 static int FAST_FUNC
12538 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12544 "Built-in commands:\n"
12545 "------------------\n");
12546 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12547 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12548 builtintab[i].name + 1);
12554 #if ENABLE_FEATURE_SH_STANDALONE
12556 const char *a = applet_names;
12558 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12563 a += strlen(a) + 1;
12568 return EXIT_SUCCESS;
12570 #endif /* FEATURE_SH_EXTRA_QUIET */
12573 * The export and readonly commands.
12575 static int FAST_FUNC
12576 exportcmd(int argc UNUSED_PARAM, char **argv)
12582 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12584 if (nextopt("p") != 'p') {
12589 p = strchr(name, '=');
12593 vp = *findvar(hashvar(name), name);
12599 setvar(name, p, flag);
12600 } while ((name = *++aptr) != NULL);
12604 showvars(argv[0], flag, 0);
12609 * Delete a function if it exists.
12612 unsetfunc(const char *name)
12614 struct tblentry *cmdp;
12616 cmdp = cmdlookup(name, 0);
12617 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12618 delete_cmd_entry();
12622 * The unset builtin command. We unset the function before we unset the
12623 * variable to allow a function to be unset when there is a readonly variable
12624 * with the same name.
12626 static int FAST_FUNC
12627 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12634 while ((i = nextopt("vf")) != 0) {
12638 for (ap = argptr; *ap; ap++) {
12651 static const unsigned char timescmd_str[] ALIGN1 = {
12652 ' ', offsetof(struct tms, tms_utime),
12653 '\n', offsetof(struct tms, tms_stime),
12654 ' ', offsetof(struct tms, tms_cutime),
12655 '\n', offsetof(struct tms, tms_cstime),
12658 static int FAST_FUNC
12659 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12661 unsigned long clk_tck, s, t;
12662 const unsigned char *p;
12665 clk_tck = sysconf(_SC_CLK_TCK);
12670 t = *(clock_t *)(((char *) &buf) + p[1]);
12673 out1fmt("%lum%lu.%03lus%c",
12675 (t * 1000) / clk_tck,
12683 #if ENABLE_SH_MATH_SUPPORT
12685 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12686 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12688 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12690 static int FAST_FUNC
12691 letcmd(int argc UNUSED_PARAM, char **argv)
12697 ash_msg_and_raise_error("expression expected");
12699 i = ash_arith(*argv);
12707 * The read builtin. Options:
12708 * -r Do not interpret '\' specially
12709 * -s Turn off echo (tty only)
12710 * -n NCHARS Read NCHARS max
12711 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12712 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12713 * -u FD Read from given FD instead of fd 0
12714 * This uses unbuffered input, which may be avoidable in some cases.
12715 * TODO: bash also has:
12716 * -a ARRAY Read into array[0],[1],etc
12717 * -d DELIM End on DELIM char, not newline
12718 * -e Use line editing (tty only)
12720 static int FAST_FUNC
12721 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12723 char *opt_n = NULL;
12724 char *opt_p = NULL;
12725 char *opt_t = NULL;
12726 char *opt_u = NULL;
12727 int read_flags = 0;
12731 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12740 read_flags |= BUILTIN_READ_SILENT;
12746 read_flags |= BUILTIN_READ_RAW;
12756 r = shell_builtin_read(setvar2,
12758 bltinlookup("IFS"), /* can be NULL */
12766 if ((uintptr_t)r > 1)
12767 ash_msg_and_raise_error(r);
12769 return (uintptr_t)r;
12772 static int FAST_FUNC
12773 umaskcmd(int argc UNUSED_PARAM, char **argv)
12775 static const char permuser[3] ALIGN1 = "ugo";
12776 static const char permmode[3] ALIGN1 = "rwx";
12777 static const short permmask[] ALIGN2 = {
12778 S_IRUSR, S_IWUSR, S_IXUSR,
12779 S_IRGRP, S_IWGRP, S_IXGRP,
12780 S_IROTH, S_IWOTH, S_IXOTH
12783 /* TODO: use bb_parse_mode() instead */
12788 int symbolic_mode = 0;
12790 while (nextopt("S") != '\0') {
12801 if (symbolic_mode) {
12805 for (i = 0; i < 3; i++) {
12808 *p++ = permuser[i];
12810 for (j = 0; j < 3; j++) {
12811 if ((mask & permmask[3 * i + j]) == 0) {
12812 *p++ = permmode[j];
12820 out1fmt("%.4o\n", mask);
12823 if (isdigit((unsigned char) *ap)) {
12826 if (*ap >= '8' || *ap < '0')
12827 ash_msg_and_raise_error(msg_illnum, argv[1]);
12828 mask = (mask << 3) + (*ap - '0');
12829 } while (*++ap != '\0');
12832 mask = ~mask & 0777;
12833 if (!bb_parse_mode(ap, &mask)) {
12834 ash_msg_and_raise_error("illegal mode: %s", ap);
12836 umask(~mask & 0777);
12842 static int FAST_FUNC
12843 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12845 return shell_builtin_ulimit(argv);
12848 /* ============ main() and helpers */
12851 * Called to exit the shell.
12853 static void exitshell(void) NORETURN;
12861 status = exitstatus;
12862 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12863 if (setjmp(loc.loc)) {
12864 if (exception_type == EXEXIT)
12865 /* dash bug: it just does _exit(exitstatus) here
12866 * but we have to do setjobctl(0) first!
12867 * (bug is still not fixed in dash-0.5.3 - if you run dash
12868 * under Midnight Commander, on exit from dash MC is backgrounded) */
12869 status = exitstatus;
12872 exception_handler = &loc;
12879 flush_stdout_stderr();
12889 /* from input.c: */
12890 /* we will never free this */
12891 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12894 signal(SIGCHLD, SIG_DFL);
12895 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12896 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12898 signal(SIGHUP, SIG_DFL);
12904 struct stat st1, st2;
12907 for (envp = environ; envp && *envp; envp++) {
12908 if (strchr(*envp, '=')) {
12909 setvareq(*envp, VEXPORT|VTEXTFIXED);
12913 setvar("PPID", utoa(getppid()), 0);
12915 p = lookupvar("PWD");
12917 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12918 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12925 * Process the shell command line arguments.
12928 procargs(char **argv)
12931 const char *xminusc;
12936 /* if (xargv[0]) - mmm, this is always true! */
12938 for (i = 0; i < NOPTS; i++)
12942 /* it already printed err message */
12943 raise_exception(EXERROR);
12947 if (*xargv == NULL) {
12949 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12952 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12956 for (i = 0; i < NOPTS; i++)
12957 if (optlist[i] == 2)
12962 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12967 } else if (!sflag) {
12968 setinputfile(*xargv, 0);
12971 commandname = arg0;
12974 shellparam.p = xargv;
12975 #if ENABLE_ASH_GETOPTS
12976 shellparam.optind = 1;
12977 shellparam.optoff = -1;
12979 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12981 shellparam.nparam++;
12988 * Read /etc/profile or .profile.
12991 read_profile(const char *name)
12995 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13004 * This routine is called when an error or an interrupt occurs in an
13005 * interactive shell and control is returned to the main command loop.
13013 /* from input.c: */
13014 g_parsefile->left_in_buffer = 0;
13015 g_parsefile->left_in_line = 0; /* clear input buffer */
13017 /* from parser.c: */
13020 /* from redir.c: */
13021 clearredir(/*drop:*/ 0);
13025 static short profile_buf[16384];
13026 extern int etext();
13030 * Main routine. We initialize things, parse the arguments, execute
13031 * profiles if we're a login shell, and then call cmdloop to execute
13032 * commands. The setjmp call sets up the location to jump to when an
13033 * exception occurs. When an exception occurs the variable "state"
13034 * is used to figure out how far we had gotten.
13036 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13037 int ash_main(int argc UNUSED_PARAM, char **argv)
13039 const char *shinit;
13040 volatile smallint state;
13041 struct jmploc jmploc;
13042 struct stackmark smark;
13044 /* Initialize global data */
13048 #if ENABLE_ASH_ALIAS
13054 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13057 #if ENABLE_FEATURE_EDITING
13058 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13061 if (setjmp(jmploc.loc)) {
13067 e = exception_type;
13071 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13075 outcslow('\n', stderr);
13078 popstackmark(&smark);
13079 FORCE_INT_ON; /* enable interrupts */
13088 exception_handler = &jmploc;
13091 TRACE(("Shell args: "));
13092 trace_puts_args(argv);
13094 rootpid = getpid();
13097 setstackmark(&smark);
13100 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13102 const char *hp = lookupvar("HISTFILE");
13105 hp = lookupvar("HOME");
13107 char *defhp = concat_path_file(hp, ".ash_history");
13108 setvar("HISTFILE", defhp, 0);
13114 if (argv[0] && argv[0][0] == '-')
13118 read_profile("/etc/profile");
13121 read_profile(".profile");
13127 getuid() == geteuid() && getgid() == getegid() &&
13131 shinit = lookupvar("ENV");
13132 if (shinit != NULL && *shinit != '\0') {
13133 read_profile(shinit);
13139 /* evalstring pushes parsefile stack.
13140 * Ensure we don't falsely claim that 0 (stdin)
13141 * is one of stacked source fds.
13142 * Testcase: ash -c 'exec 1>&0' must not complain. */
13143 // if (!sflag) g_parsefile->pf_fd = -1;
13144 // ^^ not necessary since now we special-case fd 0
13145 // in is_hidden_fd() to not be considered "hidden fd"
13146 evalstring(minusc, 0);
13149 if (sflag || minusc == NULL) {
13150 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13152 const char *hp = lookupvar("HISTFILE");
13154 line_input_state->hist_file = hp;
13157 state4: /* XXX ??? - why isn't this before the "if" statement */
13165 extern void _mcleanup(void);
13169 TRACE(("End of main reached\n"));
13176 * Copyright (c) 1989, 1991, 1993, 1994
13177 * The Regents of the University of California. All rights reserved.
13179 * This code is derived from software contributed to Berkeley by
13180 * Kenneth Almquist.
13182 * Redistribution and use in source and binary forms, with or without
13183 * modification, are permitted provided that the following conditions
13185 * 1. Redistributions of source code must retain the above copyright
13186 * notice, this list of conditions and the following disclaimer.
13187 * 2. Redistributions in binary form must reproduce the above copyright
13188 * notice, this list of conditions and the following disclaimer in the
13189 * documentation and/or other materials provided with the distribution.
13190 * 3. Neither the name of the University nor the names of its contributors
13191 * may be used to endorse or promote products derived from this software
13192 * without specific prior written permission.
13194 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13195 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13196 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13197 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13198 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13199 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13200 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13201 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13202 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13203 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF