1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * Copyright (c) 1989, 1991, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
9 * was re-ported from NetBSD and debianized.
11 * This code is derived from software contributed to Berkeley by
14 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
16 * Original BSD copyright notice is retained at the end of this file.
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 */
39 #define JOBS ENABLE_ASH_JOB_CONTROL
47 #include "busybox.h" /* for applet_names */
48 //TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
49 //#include "applet_tables.h" doesn't work
54 #if ENABLE_ASH_RANDOM_SUPPORT
57 # define CLEAR_RANDOM_T(rnd) ((void)0)
60 #if defined SINGLE_APPLET_MAIN
61 /* STANDALONE does not make sense, and won't compile */
62 # undef CONFIG_FEATURE_SH_STANDALONE
63 # undef ENABLE_FEATURE_SH_STANDALONE
64 # undef IF_FEATURE_SH_STANDALONE
65 # undef IF_NOT_FEATURE_SH_STANDALONE(...)
66 # define ENABLE_FEATURE_SH_STANDALONE 0
67 # define IF_FEATURE_SH_STANDALONE(...)
68 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
72 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
75 #if defined(__uClinux__)
76 # error "Do not even bother, ash will not run on NOMMU machine"
80 /* ============ Hash table sizes. Configurable. */
84 #define CMDTABLESIZE 31 /* should be prime */
87 /* ============ Shell options */
89 static const char *const optletters_optnames[] = {
110 #define optletters(n) optletters_optnames[(n)][0]
111 #define optnames(n) (&optletters_optnames[(n)][1])
113 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
116 /* ============ Misc data */
118 static const char homestr[] ALIGN1 = "HOME";
119 static const char snlfmt[] ALIGN1 = "%s\n";
120 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
123 * We enclose jmp_buf in a structure so that we can declare pointers to
124 * jump locations. The global variable handler contains the location to
125 * jump to when an exception occurs, and the global variable exception_type
126 * contains a code identifying the exception. To implement nested
127 * exception handlers, the user should save the value of handler on entry
128 * to an inner scope, set handler to point to a jmploc structure for the
129 * inner scope, and restore handler on exit from the scope.
135 struct globals_misc {
136 /* pid of main shell */
138 /* shell level: 0 for the main shell, 1 for its children, and so on */
140 #define rootshell (!shlvl)
141 char *minusc; /* argument to -c option */
143 char *curdir; // = nullstr; /* current working directory */
144 char *physdir; // = nullstr; /* physical working directory */
146 char *arg0; /* value of $0 */
148 struct jmploc *exception_handler;
150 volatile int suppress_int; /* counter */
151 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
152 /* last pending signal */
153 volatile /*sig_atomic_t*/ smallint pending_sig;
154 smallint exception_type; /* kind of exception (0..5) */
156 #define EXINT 0 /* SIGINT received */
157 #define EXERROR 1 /* a generic error */
158 #define EXSHELLPROC 2 /* execute a shell procedure */
159 #define EXEXEC 3 /* command execution failed */
160 #define EXEXIT 4 /* exit the shell */
161 #define EXSIG 5 /* trapped signal in wait(1) */
164 char nullstr[1]; /* zero length string */
167 #define eflag optlist[0]
168 #define fflag optlist[1]
169 #define Iflag optlist[2]
170 #define iflag optlist[3]
171 #define mflag optlist[4]
172 #define nflag optlist[5]
173 #define sflag optlist[6]
174 #define xflag optlist[7]
175 #define vflag optlist[8]
176 #define Cflag optlist[9]
177 #define aflag optlist[10]
178 #define bflag optlist[11]
179 #define uflag optlist[12]
180 #define viflag optlist[13]
182 #define nolog optlist[14]
183 #define debug optlist[15]
186 /* trap handler commands */
188 * Sigmode records the current value of the signal handlers for the various
189 * modes. A value of zero means that the current handler is not known.
190 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
192 char sigmode[NSIG - 1];
193 #define S_DFL 1 /* default signal handling (SIG_DFL) */
194 #define S_CATCH 2 /* signal is caught */
195 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
196 #define S_HARD_IGN 4 /* signal is ignored permenantly */
198 /* indicates specified signal received */
199 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
201 char **trap_ptr; /* used only by "trap hack" */
203 /* Rarely referenced stuff */
204 #if ENABLE_ASH_RANDOM_SUPPORT
207 pid_t backgndpid; /* pid of last background process */
208 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
210 extern struct globals_misc *const ash_ptr_to_globals_misc;
211 #define G_misc (*ash_ptr_to_globals_misc)
212 #define rootpid (G_misc.rootpid )
213 #define shlvl (G_misc.shlvl )
214 #define minusc (G_misc.minusc )
215 #define curdir (G_misc.curdir )
216 #define physdir (G_misc.physdir )
217 #define arg0 (G_misc.arg0 )
218 #define exception_handler (G_misc.exception_handler)
219 #define exception_type (G_misc.exception_type )
220 #define suppress_int (G_misc.suppress_int )
221 #define pending_int (G_misc.pending_int )
222 #define pending_sig (G_misc.pending_sig )
223 #define isloginsh (G_misc.isloginsh )
224 #define nullstr (G_misc.nullstr )
225 #define optlist (G_misc.optlist )
226 #define sigmode (G_misc.sigmode )
227 #define gotsig (G_misc.gotsig )
228 #define trap (G_misc.trap )
229 #define trap_ptr (G_misc.trap_ptr )
230 #define random_gen (G_misc.random_gen )
231 #define backgndpid (G_misc.backgndpid )
232 #define job_warning (G_misc.job_warning)
233 #define INIT_G_misc() do { \
234 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
242 /* ============ DEBUG */
244 static void trace_printf(const char *fmt, ...);
245 static void trace_vprintf(const char *fmt, va_list va);
246 # define TRACE(param) trace_printf param
247 # define TRACEV(param) trace_vprintf param
248 # define close(fd) do { \
250 if (close(dfd) < 0) \
251 bb_error_msg("bug on %d: closing %d(0x%x)", \
252 __LINE__, dfd, dfd); \
255 # define TRACE(param)
256 # define TRACEV(param)
260 /* ============ Utility functions */
261 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
263 static int isdigit_str9(const char *str)
265 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
266 while (--maxlen && isdigit(*str))
268 return (*str == '\0');
272 /* ============ Interrupts / exceptions */
274 * These macros allow the user to suspend the handling of interrupt signals
275 * over a period of time. This is similar to SIGHOLD or to sigblock, but
276 * much more efficient and portable. (But hacking the kernel is so much
277 * more fun than worrying about efficiency and portability. :-))
279 #define INT_OFF do { \
285 * Called to raise an exception. Since C doesn't include exceptions, we
286 * just do a longjmp to the exception handler. The type of exception is
287 * stored in the global variable "exception_type".
289 static void raise_exception(int) NORETURN;
291 raise_exception(int e)
294 if (exception_handler == NULL)
299 longjmp(exception_handler->loc, 1);
302 #define raise_exception(e) do { \
303 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
304 raise_exception(e); \
309 * Called from trap.c when a SIGINT is received. (If the user specifies
310 * that SIGINT is to be trapped or ignored using the trap builtin, then
311 * this routine is not called.) Suppressint is nonzero when interrupts
312 * are held using the INT_OFF macro. (The test for iflag is just
313 * defensive programming.)
315 static void raise_interrupt(void) NORETURN;
317 raise_interrupt(void)
322 /* Signal is not automatically unmasked after it is raised,
323 * do it ourself - unmask all signals */
324 sigprocmask_allsigs(SIG_UNBLOCK);
325 /* pending_sig = 0; - now done in onsig() */
328 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
329 if (!(rootshell && iflag)) {
330 /* Kill ourself with SIGINT */
331 signal(SIGINT, SIG_DFL);
336 raise_exception(ex_type);
340 #define raise_interrupt() do { \
341 TRACE(("raising interrupt on line %d\n", __LINE__)); \
346 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
350 if (--suppress_int == 0 && pending_int) {
354 #define INT_ON int_on()
355 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
363 #define FORCE_INT_ON force_int_on()
365 #define SAVE_INT(v) ((v) = suppress_int)
367 #define RESTORE_INT(v) do { \
369 suppress_int = (v); \
370 if (suppress_int == 0 && pending_int) \
375 /* ============ Stdout/stderr output */
378 outstr(const char *p, FILE *file)
386 flush_stdout_stderr(void)
394 outcslow(int c, FILE *dest)
402 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
404 out1fmt(const char *fmt, ...)
411 r = vprintf(fmt, ap);
417 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
419 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
426 ret = vsnprintf(outbuf, length, fmt, ap);
433 out1str(const char *p)
439 out2str(const char *p)
442 flush_stdout_stderr();
446 /* ============ Parser structures */
448 /* control characters in argument strings */
449 #define CTLESC ((unsigned char)'\201') /* escape next character */
450 #define CTLVAR ((unsigned char)'\202') /* variable defn */
451 #define CTLENDVAR ((unsigned char)'\203')
452 #define CTLBACKQ ((unsigned char)'\204')
453 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
454 /* CTLBACKQ | CTLQUOTE == '\205' */
455 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
456 #define CTLENDARI ((unsigned char)'\207')
457 #define CTLQUOTEMARK ((unsigned char)'\210')
459 /* variable substitution byte (follows CTLVAR) */
460 #define VSTYPE 0x0f /* type of variable substitution */
461 #define VSNUL 0x10 /* colon--treat the empty string as unset */
462 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
464 /* values of VSTYPE field */
465 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
466 #define VSMINUS 0x2 /* ${var-text} */
467 #define VSPLUS 0x3 /* ${var+text} */
468 #define VSQUESTION 0x4 /* ${var?message} */
469 #define VSASSIGN 0x5 /* ${var=text} */
470 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
471 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
472 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
473 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
474 #define VSLENGTH 0xa /* ${#var} */
475 #if ENABLE_ASH_BASH_COMPAT
476 #define VSSUBSTR 0xc /* ${var:position:length} */
477 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
478 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
481 static const char dolatstr[] ALIGN1 = {
482 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
502 #if ENABLE_ASH_BASH_COMPAT
519 smallint type; /* Nxxxx */
522 union node *redirect;
527 smallint pipe_backgnd;
528 struct nodelist *cmdlist;
534 union node *redirect;
547 union node *elsepart;
574 struct nodelist *backquote;
577 /* nfile and ndup layout must match!
578 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
579 * that it is actually NTO2 (>&file), and change its type.
596 char *_unused_expfname;
615 struct nredir nredir;
616 struct nbinary nbinary;
620 struct nclist nclist;
629 * NODE_EOF is returned by parsecmd when it encounters an end of file.
630 * It must be distinct from NULL.
632 #define NODE_EOF ((union node *) -1L)
635 struct nodelist *next;
648 freefunc(struct funcnode *f)
650 if (f && --f->count < 0)
655 /* ============ Debugging output */
659 static FILE *tracefile;
662 trace_printf(const char *fmt, ...)
669 fprintf(tracefile, "%u ", (int) time(NULL));
671 fprintf(tracefile, "[%u] ", (int) getpid());
673 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
675 vfprintf(tracefile, fmt, va);
680 trace_vprintf(const char *fmt, va_list va)
685 fprintf(tracefile, "%u ", (int) time(NULL));
687 fprintf(tracefile, "[%u] ", (int) getpid());
689 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
690 vfprintf(tracefile, fmt, va);
694 trace_puts(const char *s)
702 trace_puts_quoted(char *s)
709 putc('"', tracefile);
710 for (p = s; *p; p++) {
711 switch ((unsigned char)*p) {
712 case '\n': c = 'n'; goto backslash;
713 case '\t': c = 't'; goto backslash;
714 case '\r': c = 'r'; goto backslash;
715 case '\"': c = '\"'; goto backslash;
716 case '\\': c = '\\'; goto backslash;
717 case CTLESC: c = 'e'; goto backslash;
718 case CTLVAR: c = 'v'; goto backslash;
719 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
720 case CTLBACKQ: c = 'q'; goto backslash;
721 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
723 putc('\\', tracefile);
727 if (*p >= ' ' && *p <= '~')
730 putc('\\', tracefile);
731 putc((*p >> 6) & 03, tracefile);
732 putc((*p >> 3) & 07, tracefile);
733 putc(*p & 07, tracefile);
738 putc('"', tracefile);
742 trace_puts_args(char **ap)
749 trace_puts_quoted(*ap);
751 putc('\n', tracefile);
754 putc(' ', tracefile);
769 /* leave open because libedit might be using it */
772 strcpy(s, "./trace");
774 if (!freopen(s, "a", tracefile)) {
775 fprintf(stderr, "Can't re-open %s\n", s);
780 tracefile = fopen(s, "a");
781 if (tracefile == NULL) {
782 fprintf(stderr, "Can't open %s\n", s);
788 flags = fcntl(fileno(tracefile), F_GETFL);
790 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
792 setlinebuf(tracefile);
793 fputs("\nTracing started.\n", tracefile);
797 indent(int amount, char *pfx, FILE *fp)
801 for (i = 0; i < amount; i++) {
802 if (pfx && i == amount - 1)
808 /* little circular references here... */
809 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
812 sharg(union node *arg, FILE *fp)
815 struct nodelist *bqlist;
816 unsigned char subtype;
818 if (arg->type != NARG) {
819 out1fmt("<node type %d>\n", arg->type);
822 bqlist = arg->narg.backquote;
823 for (p = arg->narg.text; *p; p++) {
824 switch ((unsigned char)*p) {
832 if (subtype == VSLENGTH)
841 switch (subtype & VSTYPE) {
874 out1fmt("<subtype %d>", subtype);
881 case CTLBACKQ|CTLQUOTE:
884 shtree(bqlist->n, -1, NULL, fp);
895 shcmd(union node *cmd, FILE *fp)
903 for (np = cmd->ncmd.args; np; np = np->narg.next) {
909 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
913 switch (np->nfile.type) {
914 case NTO: s = ">>"+1; dftfd = 1; break;
915 case NCLOBBER: s = ">|"; dftfd = 1; break;
916 case NAPPEND: s = ">>"; dftfd = 1; break;
917 #if ENABLE_ASH_BASH_COMPAT
920 case NTOFD: s = ">&"; dftfd = 1; break;
921 case NFROM: s = "<"; break;
922 case NFROMFD: s = "<&"; break;
923 case NFROMTO: s = "<>"; break;
924 default: s = "*error*"; break;
926 if (np->nfile.fd != dftfd)
927 fprintf(fp, "%d", np->nfile.fd);
929 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
930 fprintf(fp, "%d", np->ndup.dupfd);
932 sharg(np->nfile.fname, fp);
939 shtree(union node *n, int ind, char *pfx, FILE *fp)
947 indent(ind, pfx, fp);
964 shtree(n->nbinary.ch1, ind, NULL, fp);
967 shtree(n->nbinary.ch2, ind, NULL, fp);
975 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
976 shtree(lp->n, 0, NULL, fp);
980 if (n->npipe.pipe_backgnd)
986 fprintf(fp, "<node type %d>", n->type);
994 showtree(union node *n)
996 trace_puts("showtree called\n");
997 shtree(n, 1, NULL, stderr);
1003 /* ============ Parser data */
1006 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1009 struct strlist *next;
1016 struct strpush *prev; /* preceding string on stack */
1018 int prev_left_in_line;
1019 #if ENABLE_ASH_ALIAS
1020 struct alias *ap; /* if push was associated with an alias */
1022 char *string; /* remember the string since it may change */
1026 struct parsefile *prev; /* preceding file on stack */
1027 int linno; /* current line */
1028 int fd; /* file descriptor (or -1 if string) */
1029 int left_in_line; /* number of chars left in this line */
1030 int left_in_buffer; /* number of chars left in this buffer past the line */
1031 char *next_to_pgetc; /* next char in buffer */
1032 char *buf; /* input buffer */
1033 struct strpush *strpush; /* for pushing strings at this level */
1034 struct strpush basestrpush; /* so pushing one is fast */
1037 static struct parsefile basepf; /* top level input file */
1038 static struct parsefile *g_parsefile = &basepf; /* current input file */
1039 static int startlinno; /* line # where last token started */
1040 static char *commandname; /* currently executing command */
1041 static struct strlist *cmdenviron; /* environment for builtin command */
1042 static uint8_t exitstatus; /* exit status of last command */
1045 /* ============ Message printing */
1048 ash_vmsg(const char *msg, va_list ap)
1050 fprintf(stderr, "%s: ", arg0);
1052 if (strcmp(arg0, commandname))
1053 fprintf(stderr, "%s: ", commandname);
1054 if (!iflag || g_parsefile->fd)
1055 fprintf(stderr, "line %d: ", startlinno);
1057 vfprintf(stderr, msg, ap);
1058 outcslow('\n', stderr);
1062 * Exverror is called to raise the error exception. If the second argument
1063 * is not NULL then error prints an error message using printf style
1064 * formatting. It then raises the error exception.
1066 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1068 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1072 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1074 TRACE(("\") pid=%d\n", getpid()));
1076 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1081 flush_stdout_stderr();
1082 raise_exception(cond);
1086 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1088 ash_msg_and_raise_error(const char *msg, ...)
1093 ash_vmsg_and_raise(EXERROR, msg, ap);
1098 static void raise_error_syntax(const char *) NORETURN;
1100 raise_error_syntax(const char *msg)
1102 ash_msg_and_raise_error("syntax error: %s", msg);
1106 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1108 ash_msg_and_raise(int cond, const char *msg, ...)
1113 ash_vmsg_and_raise(cond, msg, ap);
1119 * error/warning routines for external builtins
1122 ash_msg(const char *fmt, ...)
1132 * Return a string describing an error. The returned string may be a
1133 * pointer to a static buffer that will be overwritten on the next call.
1134 * Action describes the operation that got the error.
1137 errmsg(int e, const char *em)
1139 if (e == ENOENT || e == ENOTDIR) {
1146 /* ============ Memory allocation */
1149 /* I consider these wrappers nearly useless:
1150 * ok, they return you to nearest exception handler, but
1151 * how much memory do you leak in the process, making
1152 * memory starvation worse?
1155 ckrealloc(void * p, size_t nbytes)
1157 p = realloc(p, nbytes);
1159 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1164 ckmalloc(size_t nbytes)
1166 return ckrealloc(NULL, nbytes);
1170 ckzalloc(size_t nbytes)
1172 return memset(ckmalloc(nbytes), 0, nbytes);
1176 ckstrdup(const char *s)
1178 char *p = strdup(s);
1180 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1184 /* Using bbox equivalents. They exit if out of memory */
1185 # define ckrealloc xrealloc
1186 # define ckmalloc xmalloc
1187 # define ckzalloc xzalloc
1188 # define ckstrdup xstrdup
1192 * It appears that grabstackstr() will barf with such alignments
1193 * because stalloc() will return a string allocated in a new stackblock.
1195 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1197 /* Most machines require the value returned from malloc to be aligned
1198 * in some way. The following macro will get this right
1199 * on many machines. */
1200 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1201 /* Minimum size of a block */
1202 MINSIZE = SHELL_ALIGN(504),
1205 struct stack_block {
1206 struct stack_block *prev;
1207 char space[MINSIZE];
1211 struct stack_block *stackp;
1214 struct stackmark *marknext;
1218 struct globals_memstack {
1219 struct stack_block *g_stackp; // = &stackbase;
1220 struct stackmark *markp;
1221 char *g_stacknxt; // = stackbase.space;
1222 char *sstrend; // = stackbase.space + MINSIZE;
1223 size_t g_stacknleft; // = MINSIZE;
1224 int herefd; // = -1;
1225 struct stack_block stackbase;
1227 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1228 #define G_memstack (*ash_ptr_to_globals_memstack)
1229 #define g_stackp (G_memstack.g_stackp )
1230 #define markp (G_memstack.markp )
1231 #define g_stacknxt (G_memstack.g_stacknxt )
1232 #define sstrend (G_memstack.sstrend )
1233 #define g_stacknleft (G_memstack.g_stacknleft)
1234 #define herefd (G_memstack.herefd )
1235 #define stackbase (G_memstack.stackbase )
1236 #define INIT_G_memstack() do { \
1237 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1239 g_stackp = &stackbase; \
1240 g_stacknxt = stackbase.space; \
1241 g_stacknleft = MINSIZE; \
1242 sstrend = stackbase.space + MINSIZE; \
1247 #define stackblock() ((void *)g_stacknxt)
1248 #define stackblocksize() g_stacknleft
1251 * Parse trees for commands are allocated in lifo order, so we use a stack
1252 * to make this more efficient, and also to avoid all sorts of exception
1253 * handling code to handle interrupts in the middle of a parse.
1255 * The size 504 was chosen because the Ultrix malloc handles that size
1259 stalloc(size_t nbytes)
1264 aligned = SHELL_ALIGN(nbytes);
1265 if (aligned > g_stacknleft) {
1268 struct stack_block *sp;
1270 blocksize = aligned;
1271 if (blocksize < MINSIZE)
1272 blocksize = MINSIZE;
1273 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1274 if (len < blocksize)
1275 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1278 sp->prev = g_stackp;
1279 g_stacknxt = sp->space;
1280 g_stacknleft = blocksize;
1281 sstrend = g_stacknxt + blocksize;
1286 g_stacknxt += aligned;
1287 g_stacknleft -= aligned;
1292 stzalloc(size_t nbytes)
1294 return memset(stalloc(nbytes), 0, nbytes);
1301 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1302 write(STDERR_FILENO, "stunalloc\n", 10);
1306 g_stacknleft += g_stacknxt - (char *)p;
1311 * Like strdup but works with the ash stack.
1314 ststrdup(const char *p)
1316 size_t len = strlen(p) + 1;
1317 return memcpy(stalloc(len), p, len);
1321 setstackmark(struct stackmark *mark)
1323 mark->stackp = g_stackp;
1324 mark->stacknxt = g_stacknxt;
1325 mark->stacknleft = g_stacknleft;
1326 mark->marknext = markp;
1331 popstackmark(struct stackmark *mark)
1333 struct stack_block *sp;
1339 markp = mark->marknext;
1340 while (g_stackp != mark->stackp) {
1342 g_stackp = sp->prev;
1345 g_stacknxt = mark->stacknxt;
1346 g_stacknleft = mark->stacknleft;
1347 sstrend = mark->stacknxt + mark->stacknleft;
1352 * When the parser reads in a string, it wants to stick the string on the
1353 * stack and only adjust the stack pointer when it knows how big the
1354 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1355 * of space on top of the stack and stackblocklen returns the length of
1356 * this block. Growstackblock will grow this space by at least one byte,
1357 * possibly moving it (like realloc). Grabstackblock actually allocates the
1358 * part of the block that has been used.
1361 growstackblock(void)
1365 newlen = g_stacknleft * 2;
1366 if (newlen < g_stacknleft)
1367 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1371 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1372 struct stack_block *oldstackp;
1373 struct stackmark *xmark;
1374 struct stack_block *sp;
1375 struct stack_block *prevstackp;
1379 oldstackp = g_stackp;
1381 prevstackp = sp->prev;
1382 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1383 sp = ckrealloc(sp, grosslen);
1384 sp->prev = prevstackp;
1386 g_stacknxt = sp->space;
1387 g_stacknleft = newlen;
1388 sstrend = sp->space + newlen;
1391 * Stack marks pointing to the start of the old block
1392 * must be relocated to point to the new block
1395 while (xmark != NULL && xmark->stackp == oldstackp) {
1396 xmark->stackp = g_stackp;
1397 xmark->stacknxt = g_stacknxt;
1398 xmark->stacknleft = g_stacknleft;
1399 xmark = xmark->marknext;
1403 char *oldspace = g_stacknxt;
1404 size_t oldlen = g_stacknleft;
1405 char *p = stalloc(newlen);
1407 /* free the space we just allocated */
1408 g_stacknxt = memcpy(p, oldspace, oldlen);
1409 g_stacknleft += newlen;
1414 grabstackblock(size_t len)
1416 len = SHELL_ALIGN(len);
1418 g_stacknleft -= len;
1422 * The following routines are somewhat easier to use than the above.
1423 * The user declares a variable of type STACKSTR, which may be declared
1424 * to be a register. The macro STARTSTACKSTR initializes things. Then
1425 * the user uses the macro STPUTC to add characters to the string. In
1426 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1427 * grown as necessary. When the user is done, she can just leave the
1428 * string there and refer to it using stackblock(). Or she can allocate
1429 * the space for it using grabstackstr(). If it is necessary to allow
1430 * someone else to use the stack temporarily and then continue to grow
1431 * the string, the user should use grabstack to allocate the space, and
1432 * then call ungrabstr(p) to return to the previous mode of operation.
1434 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1435 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1436 * is space for at least one character.
1441 size_t len = stackblocksize();
1442 if (herefd >= 0 && len >= 1024) {
1443 full_write(herefd, stackblock(), len);
1444 return stackblock();
1447 return (char *)stackblock() + len;
1451 * Called from CHECKSTRSPACE.
1454 makestrspace(size_t newlen, char *p)
1456 size_t len = p - g_stacknxt;
1457 size_t size = stackblocksize();
1462 size = stackblocksize();
1464 if (nleft >= newlen)
1468 return (char *)stackblock() + len;
1472 stack_nputstr(const char *s, size_t n, char *p)
1474 p = makestrspace(n, p);
1475 p = (char *)memcpy(p, s, n) + n;
1480 stack_putstr(const char *s, char *p)
1482 return stack_nputstr(s, strlen(s), p);
1486 _STPUTC(int c, char *p)
1494 #define STARTSTACKSTR(p) ((p) = stackblock())
1495 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1496 #define CHECKSTRSPACE(n, p) do { \
1499 size_t m = sstrend - q; \
1501 (p) = makestrspace(l, q); \
1503 #define USTPUTC(c, p) (*(p)++ = (c))
1504 #define STACKSTRNUL(p) do { \
1505 if ((p) == sstrend) \
1506 (p) = growstackstr(); \
1509 #define STUNPUTC(p) (--(p))
1510 #define STTOPC(p) ((p)[-1])
1511 #define STADJUST(amount, p) ((p) += (amount))
1513 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1514 #define ungrabstackstr(s, p) stunalloc(s)
1515 #define stackstrend() ((void *)sstrend)
1518 /* ============ String helpers */
1521 * prefix -- see if pfx is a prefix of string.
1524 prefix(const char *string, const char *pfx)
1527 if (*pfx++ != *string++)
1530 return (char *) string;
1534 * Check for a valid number. This should be elsewhere.
1537 is_number(const char *p)
1542 } while (*++p != '\0');
1547 * Convert a string of digits to an integer, printing an error message on
1551 number(const char *s)
1554 ash_msg_and_raise_error(msg_illnum, s);
1559 * Produce a possibly single quoted string suitable as input to the shell.
1560 * The return string is allocated on the stack.
1563 single_quote(const char *s)
1573 len = strchrnul(s, '\'') - s;
1575 q = p = makestrspace(len + 3, p);
1578 q = (char *)memcpy(q, s, len) + len;
1587 do len++; while (*++s == '\'');
1589 q = p = makestrspace(len + 3, p);
1592 q = (char *)memcpy(q, s - len, len) + len;
1600 return stackblock();
1604 /* ============ nextopt */
1606 static char **argptr; /* argument list for builtin commands */
1607 static char *optionarg; /* set by nextopt (like getopt) */
1608 static char *optptr; /* used by nextopt */
1611 * XXX - should get rid of. Have all builtins use getopt(3).
1612 * The library getopt must have the BSD extension static variable
1613 * "optreset", otherwise it can't be used within the shell safely.
1615 * Standard option processing (a la getopt) for builtin routines.
1616 * The only argument that is passed to nextopt is the option string;
1617 * the other arguments are unnecessary. It returns the character,
1618 * or '\0' on end of input.
1621 nextopt(const char *optstring)
1628 if (p == NULL || *p == '\0') {
1629 /* We ate entire "-param", take next one */
1635 if (*++p == '\0') /* just "-" ? */
1638 if (LONE_DASH(p)) /* "--" ? */
1640 /* p => next "-param" */
1642 /* p => some option char in the middle of a "-param" */
1644 for (q = optstring; *q != c;) {
1646 ash_msg_and_raise_error("illegal option -%c", c);
1654 ash_msg_and_raise_error("no arg for -%c option", c);
1664 /* ============ Shell variables */
1667 * The parsefile structure pointed to by the global variable parsefile
1668 * contains information about the current file being read.
1671 int nparam; /* # of positional parameters (without $0) */
1672 #if ENABLE_ASH_GETOPTS
1673 int optind; /* next parameter to be processed by getopts */
1674 int optoff; /* used by getopts */
1676 unsigned char malloced; /* if parameter list dynamically allocated */
1677 char **p; /* parameter list */
1681 * Free the list of positional parameters.
1684 freeparam(volatile struct shparam *param)
1686 if (param->malloced) {
1688 ap = ap1 = param->p;
1695 #if ENABLE_ASH_GETOPTS
1696 static void FAST_FUNC getoptsreset(const char *value);
1700 struct var *next; /* next entry in hash list */
1701 int flags; /* flags are defined above */
1702 const char *text; /* name=value */
1703 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1704 /* the variable gets set/unset */
1708 struct localvar *next; /* next local variable in list */
1709 struct var *vp; /* the variable that was made local */
1710 int flags; /* saved flags */
1711 const char *text; /* saved text */
1715 #define VEXPORT 0x01 /* variable is exported */
1716 #define VREADONLY 0x02 /* variable cannot be modified */
1717 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1718 #define VTEXTFIXED 0x08 /* text is statically allocated */
1719 #define VSTACK 0x10 /* text is allocated on the stack */
1720 #define VUNSET 0x20 /* the variable is not set */
1721 #define VNOFUNC 0x40 /* don't call the callback function */
1722 #define VNOSET 0x80 /* do not set variable - just readonly test */
1723 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1724 #if ENABLE_ASH_RANDOM_SUPPORT
1725 # define VDYNAMIC 0x200 /* dynamic variable */
1731 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1732 #define defifs (defifsvar + 4)
1734 static const char defifs[] ALIGN1 = " \t\n";
1738 /* Need to be before varinit_data[] */
1739 #if ENABLE_LOCALE_SUPPORT
1740 static void FAST_FUNC
1741 change_lc_all(const char *value)
1743 if (value && *value != '\0')
1744 setlocale(LC_ALL, value);
1746 static void FAST_FUNC
1747 change_lc_ctype(const char *value)
1749 if (value && *value != '\0')
1750 setlocale(LC_CTYPE, value);
1754 static void chkmail(void);
1755 static void changemail(const char *) FAST_FUNC;
1757 static void changepath(const char *) FAST_FUNC;
1758 #if ENABLE_ASH_RANDOM_SUPPORT
1759 static void change_random(const char *) FAST_FUNC;
1762 static const struct {
1765 void (*func)(const char *) FAST_FUNC;
1766 } varinit_data[] = {
1768 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1770 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1773 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1774 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1776 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1777 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1778 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1779 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1780 #if ENABLE_ASH_GETOPTS
1781 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1783 #if ENABLE_ASH_RANDOM_SUPPORT
1784 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1786 #if ENABLE_LOCALE_SUPPORT
1787 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1788 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1790 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1791 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1797 struct globals_var {
1798 struct shparam shellparam; /* $@ current positional parameters */
1799 struct redirtab *redirlist;
1801 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1802 struct var *vartab[VTABSIZE];
1803 struct var varinit[ARRAY_SIZE(varinit_data)];
1805 extern struct globals_var *const ash_ptr_to_globals_var;
1806 #define G_var (*ash_ptr_to_globals_var)
1807 #define shellparam (G_var.shellparam )
1808 //#define redirlist (G_var.redirlist )
1809 #define g_nullredirs (G_var.g_nullredirs )
1810 #define preverrout_fd (G_var.preverrout_fd)
1811 #define vartab (G_var.vartab )
1812 #define varinit (G_var.varinit )
1813 #define INIT_G_var() do { \
1815 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1817 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1818 varinit[i].flags = varinit_data[i].flags; \
1819 varinit[i].text = varinit_data[i].text; \
1820 varinit[i].func = varinit_data[i].func; \
1824 #define vifs varinit[0]
1826 # define vmail (&vifs)[1]
1827 # define vmpath (&vmail)[1]
1828 # define vpath (&vmpath)[1]
1830 # define vpath (&vifs)[1]
1832 #define vps1 (&vpath)[1]
1833 #define vps2 (&vps1)[1]
1834 #define vps4 (&vps2)[1]
1835 #if ENABLE_ASH_GETOPTS
1836 # define voptind (&vps4)[1]
1837 # if ENABLE_ASH_RANDOM_SUPPORT
1838 # define vrandom (&voptind)[1]
1841 # if ENABLE_ASH_RANDOM_SUPPORT
1842 # define vrandom (&vps4)[1]
1847 * The following macros access the values of the above variables.
1848 * They have to skip over the name. They return the null string
1849 * for unset variables.
1851 #define ifsval() (vifs.text + 4)
1852 #define ifsset() ((vifs.flags & VUNSET) == 0)
1854 # define mailval() (vmail.text + 5)
1855 # define mpathval() (vmpath.text + 9)
1856 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1858 #define pathval() (vpath.text + 5)
1859 #define ps1val() (vps1.text + 4)
1860 #define ps2val() (vps2.text + 4)
1861 #define ps4val() (vps4.text + 4)
1862 #if ENABLE_ASH_GETOPTS
1863 # define optindval() (voptind.text + 7)
1867 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1868 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1870 #if ENABLE_ASH_GETOPTS
1871 static void FAST_FUNC
1872 getoptsreset(const char *value)
1874 shellparam.optind = number(value);
1875 shellparam.optoff = -1;
1880 * Return of a legal variable name (a letter or underscore followed by zero or
1881 * more letters, underscores, and digits).
1884 endofname(const char *name)
1892 if (!is_in_name(*p))
1899 * Compares two strings up to the first = or '\0'. The first
1900 * string must be terminated by '='; the second may be terminated by
1901 * either '=' or '\0'.
1904 varcmp(const char *p, const char *q)
1908 while ((c = *p) == (d = *q)) {
1923 varequal(const char *a, const char *b)
1925 return !varcmp(a, b);
1929 * Find the appropriate entry in the hash table from the name.
1931 static struct var **
1932 hashvar(const char *p)
1936 hashval = ((unsigned char) *p) << 4;
1937 while (*p && *p != '=')
1938 hashval += (unsigned char) *p++;
1939 return &vartab[hashval % VTABSIZE];
1943 vpcmp(const void *a, const void *b)
1945 return varcmp(*(const char **)a, *(const char **)b);
1949 * This routine initializes the builtin variables.
1959 * PS1 depends on uid
1961 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1962 vps1.text = "PS1=\\w \\$ ";
1965 vps1.text = "PS1=# ";
1968 end = vp + ARRAY_SIZE(varinit);
1970 vpp = hashvar(vp->text);
1973 } while (++vp < end);
1976 static struct var **
1977 findvar(struct var **vpp, const char *name)
1979 for (; *vpp; vpp = &(*vpp)->next) {
1980 if (varequal((*vpp)->text, name)) {
1988 * Find the value of a variable. Returns NULL if not set.
1991 lookupvar(const char *name)
1995 v = *findvar(hashvar(name), name);
1997 #if ENABLE_ASH_RANDOM_SUPPORT
1999 * Dynamic variables are implemented roughly the same way they are
2000 * in bash. Namely, they're "special" so long as they aren't unset.
2001 * As soon as they're unset, they're no longer dynamic, and dynamic
2002 * lookup will no longer happen at that point. -- PFM.
2004 if ((v->flags & VDYNAMIC))
2007 if (!(v->flags & VUNSET))
2008 return strchrnul(v->text, '=') + 1;
2014 * Search the environment of a builtin command.
2017 bltinlookup(const char *name)
2021 for (sp = cmdenviron; sp; sp = sp->next) {
2022 if (varequal(sp->text, name))
2023 return strchrnul(sp->text, '=') + 1;
2025 return lookupvar(name);
2029 * Same as setvar except that the variable and value are passed in
2030 * the first argument as name=value. Since the first argument will
2031 * be actually stored in the table, it should not be a string that
2033 * Called with interrupts off.
2036 setvareq(char *s, int flags)
2038 struct var *vp, **vpp;
2041 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2042 vp = *findvar(vpp, s);
2044 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2047 if (flags & VNOSAVE)
2050 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2056 if (vp->func && (flags & VNOFUNC) == 0)
2057 (*vp->func)(strchrnul(s, '=') + 1);
2059 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2060 free((char*)vp->text);
2062 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2067 vp = ckzalloc(sizeof(*vp));
2069 /*vp->func = NULL; - ckzalloc did it */
2072 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2079 * Set the value of a variable. The flags argument is ored with the
2080 * flags of the variable. If val is NULL, the variable is unset.
2083 setvar(const char *name, const char *val, int flags)
2090 q = endofname(name);
2091 p = strchrnul(q, '=');
2093 if (!namelen || p != q)
2094 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2099 vallen = strlen(val);
2102 nameeq = ckmalloc(namelen + vallen + 2);
2103 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2106 p = (char *)memcpy(p, val, vallen) + vallen;
2109 setvareq(nameeq, flags | VNOSAVE);
2113 #if ENABLE_ASH_GETOPTS
2115 * Safe version of setvar, returns 1 on success 0 on failure.
2118 setvarsafe(const char *name, const char *val, int flags)
2121 volatile int saveint;
2122 struct jmploc *volatile savehandler = exception_handler;
2123 struct jmploc jmploc;
2126 if (setjmp(jmploc.loc))
2129 exception_handler = &jmploc;
2130 setvar(name, val, flags);
2133 exception_handler = savehandler;
2134 RESTORE_INT(saveint);
2140 * Unset the specified variable.
2143 unsetvar(const char *s)
2149 vpp = findvar(hashvar(s), s);
2153 int flags = vp->flags;
2156 if (flags & VREADONLY)
2158 #if ENABLE_ASH_RANDOM_SUPPORT
2159 vp->flags &= ~VDYNAMIC;
2163 if ((flags & VSTRFIXED) == 0) {
2165 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2166 free((char*)vp->text);
2172 vp->flags &= ~VEXPORT;
2182 * Process a linked list of variable assignments.
2185 listsetvar(struct strlist *list_set_var, int flags)
2187 struct strlist *lp = list_set_var;
2193 setvareq(lp->text, flags);
2200 * Generate a list of variables satisfying the given conditions.
2203 listvars(int on, int off, char ***end)
2214 for (vp = *vpp; vp; vp = vp->next) {
2215 if ((vp->flags & mask) == on) {
2216 if (ep == stackstrend())
2217 ep = growstackstr();
2218 *ep++ = (char *) vp->text;
2221 } while (++vpp < vartab + VTABSIZE);
2222 if (ep == stackstrend())
2223 ep = growstackstr();
2227 return grabstackstr(ep);
2231 /* ============ Path search helper
2233 * The variable path (passed by reference) should be set to the start
2234 * of the path before the first call; path_advance will update
2235 * this value as it proceeds. Successive calls to path_advance will return
2236 * the possible path expansions in sequence. If an option (indicated by
2237 * a percent sign) appears in the path entry then the global variable
2238 * pathopt will be set to point to it; otherwise pathopt will be set to
2241 static const char *pathopt; /* set by path_advance */
2244 path_advance(const char **path, const char *name)
2254 for (p = start; *p && *p != ':' && *p != '%'; p++)
2256 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2257 while (stackblocksize() < len)
2261 memcpy(q, start, p - start);
2269 while (*p && *p != ':')
2276 return stalloc(len);
2280 /* ============ Prompt */
2282 static smallint doprompt; /* if set, prompt the user */
2283 static smallint needprompt; /* true if interactive and at start of line */
2285 #if ENABLE_FEATURE_EDITING
2286 static line_input_t *line_input_state;
2287 static const char *cmdedit_prompt;
2289 putprompt(const char *s)
2291 if (ENABLE_ASH_EXPAND_PRMT) {
2292 free((char*)cmdedit_prompt);
2293 cmdedit_prompt = ckstrdup(s);
2300 putprompt(const char *s)
2306 #if ENABLE_ASH_EXPAND_PRMT
2307 /* expandstr() needs parsing machinery, so it is far away ahead... */
2308 static const char *expandstr(const char *ps);
2310 #define expandstr(s) s
2314 setprompt(int whichprompt)
2317 #if ENABLE_ASH_EXPAND_PRMT
2318 struct stackmark smark;
2323 switch (whichprompt) {
2333 #if ENABLE_ASH_EXPAND_PRMT
2334 setstackmark(&smark);
2335 stalloc(stackblocksize());
2337 putprompt(expandstr(prompt));
2338 #if ENABLE_ASH_EXPAND_PRMT
2339 popstackmark(&smark);
2344 /* ============ The cd and pwd commands */
2346 #define CD_PHYSICAL 1
2356 while ((i = nextopt("LP")) != '\0') {
2358 flags ^= CD_PHYSICAL;
2367 * Update curdir (the name of the current directory) in response to a
2371 updatepwd(const char *dir)
2378 cdcomppath = ststrdup(dir);
2381 if (curdir == nullstr)
2383 new = stack_putstr(curdir, new);
2385 new = makestrspace(strlen(dir) + 2, new);
2386 lim = (char *)stackblock() + 1;
2390 if (new > lim && *lim == '/')
2395 if (dir[1] == '/' && dir[2] != '/') {
2401 p = strtok(cdcomppath, "/");
2405 if (p[1] == '.' && p[2] == '\0') {
2417 new = stack_putstr(p, new);
2425 return stackblock();
2429 * Find out what the current directory is. If we already know the current
2430 * directory, this routine returns immediately.
2435 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2436 return dir ? dir : nullstr;
2440 setpwd(const char *val, int setold)
2444 oldcur = dir = curdir;
2447 setvar("OLDPWD", oldcur, VEXPORT);
2450 if (physdir != nullstr) {
2451 if (physdir != oldcur)
2455 if (oldcur == val || !val) {
2461 dir = ckstrdup(val);
2462 if (oldcur != dir && oldcur != nullstr) {
2467 setvar("PWD", dir, VEXPORT);
2470 static void hashcd(void);
2473 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2474 * know that the current directory has changed.
2477 docd(const char *dest, int flags)
2479 const char *dir = 0;
2482 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2485 if (!(flags & CD_PHYSICAL)) {
2486 dir = updatepwd(dest);
2500 static int FAST_FUNC
2501 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2513 dest = bltinlookup(homestr);
2514 else if (LONE_DASH(dest)) {
2515 dest = bltinlookup("OLDPWD");
2537 path = bltinlookup("CDPATH");
2546 p = path_advance(&path, dest);
2547 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2551 if (!docd(p, flags))
2556 ash_msg_and_raise_error("can't cd to %s", dest);
2559 if (flags & CD_PRINT)
2560 out1fmt(snlfmt, curdir);
2564 static int FAST_FUNC
2565 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2568 const char *dir = curdir;
2572 if (physdir == nullstr)
2576 out1fmt(snlfmt, dir);
2581 /* ============ ... */
2584 #define IBUFSIZ COMMON_BUFSIZE
2585 /* buffer for top level input file */
2586 #define basebuf bb_common_bufsiz1
2588 /* Syntax classes */
2589 #define CWORD 0 /* character is nothing special */
2590 #define CNL 1 /* newline character */
2591 #define CBACK 2 /* a backslash character */
2592 #define CSQUOTE 3 /* single quote */
2593 #define CDQUOTE 4 /* double quote */
2594 #define CENDQUOTE 5 /* a terminating quote */
2595 #define CBQUOTE 6 /* backwards single quote */
2596 #define CVAR 7 /* a dollar sign */
2597 #define CENDVAR 8 /* a '}' character */
2598 #define CLP 9 /* a left paren in arithmetic */
2599 #define CRP 10 /* a right paren in arithmetic */
2600 #define CENDFILE 11 /* end of file */
2601 #define CCTL 12 /* like CWORD, except it must be escaped */
2602 #define CSPCL 13 /* these terminate a word */
2603 #define CIGN 14 /* character should be ignored */
2605 #if ENABLE_ASH_ALIAS
2612 /* number syntax index */
2613 #define BASESYNTAX 0 /* not in quotes */
2614 #define DQSYNTAX 1 /* in double quotes */
2615 #define SQSYNTAX 2 /* in single quotes */
2616 #define ARISYNTAX 3 /* in arithmetic */
2617 #define PSSYNTAX 4 /* prompt */
2619 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2620 # define USE_SIT_FUNCTION
2623 #if ENABLE_SH_MATH_SUPPORT
2624 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2626 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2628 static const uint16_t S_I_T[] = {
2629 #if ENABLE_ASH_ALIAS
2630 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2632 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2633 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2634 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2635 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2636 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2637 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2638 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2639 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2640 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2641 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2642 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2643 #ifndef USE_SIT_FUNCTION
2644 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2645 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2646 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2650 /* Constants below must match table above */
2652 #if ENABLE_ASH_ALIAS
2653 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2655 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2656 CNL_CNL_CNL_CNL , /* 2 */
2657 CWORD_CCTL_CCTL_CWORD , /* 3 */
2658 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2659 CVAR_CVAR_CWORD_CVAR , /* 5 */
2660 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2661 CSPCL_CWORD_CWORD_CLP , /* 7 */
2662 CSPCL_CWORD_CWORD_CRP , /* 8 */
2663 CBACK_CBACK_CCTL_CBACK , /* 9 */
2664 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2665 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2666 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2667 CWORD_CWORD_CWORD_CWORD , /* 13 */
2668 CCTL_CCTL_CCTL_CCTL , /* 14 */
2671 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2672 * caller must ensure proper cast on it if c is *char_ptr!
2675 #ifdef USE_SIT_FUNCTION
2678 SIT(int c, int syntax)
2680 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2681 # if ENABLE_ASH_ALIAS
2682 static const uint8_t syntax_index_table[] ALIGN1 = {
2683 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2684 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2685 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2689 static const uint8_t syntax_index_table[] ALIGN1 = {
2690 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2691 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2692 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2699 if (c == PEOF) { /* 2^8+2 */
2702 # if ENABLE_ASH_ALIAS
2703 if (c == PEOA) { /* 2^8+1 */
2708 if ((unsigned char)c >= CTLESC
2709 && (unsigned char)c <= CTLQUOTEMARK
2713 s = strchrnul(spec_symbls, c);
2717 indx = syntax_index_table[s - spec_symbls];
2719 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2722 #else /* !USE_SIT_FUNCTION */
2724 static const uint8_t syntax_index_table[] = {
2725 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2726 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2736 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2737 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2759 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2760 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2761 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2762 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2763 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2764 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2765 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2766 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2767 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2768 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2769 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2770 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2771 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2772 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2773 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2774 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2775 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2785 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2786 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2787 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2788 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2789 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2790 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2791 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2818 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2819 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2820 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2823 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2851 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2852 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2853 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2854 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2856 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2857 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2858 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2859 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2860 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2861 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2862 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2863 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2982 # if ENABLE_ASH_ALIAS
2983 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2985 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2988 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> (syntax*4)) & 0xf)
2990 #endif /* !USE_SIT_FUNCTION */
2993 /* ============ Alias handling */
2995 #if ENABLE_ASH_ALIAS
2997 #define ALIASINUSE 1
3008 static struct alias **atab; // [ATABSIZE];
3009 #define INIT_G_alias() do { \
3010 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3014 static struct alias **
3015 __lookupalias(const char *name) {
3016 unsigned int hashval;
3023 ch = (unsigned char)*p;
3027 ch = (unsigned char)*++p;
3029 app = &atab[hashval % ATABSIZE];
3031 for (; *app; app = &(*app)->next) {
3032 if (strcmp(name, (*app)->name) == 0) {
3040 static struct alias *
3041 lookupalias(const char *name, int check)
3043 struct alias *ap = *__lookupalias(name);
3045 if (check && ap && (ap->flag & ALIASINUSE))
3050 static struct alias *
3051 freealias(struct alias *ap)
3055 if (ap->flag & ALIASINUSE) {
3056 ap->flag |= ALIASDEAD;
3068 setalias(const char *name, const char *val)
3070 struct alias *ap, **app;
3072 app = __lookupalias(name);
3076 if (!(ap->flag & ALIASINUSE)) {
3079 ap->val = ckstrdup(val);
3080 ap->flag &= ~ALIASDEAD;
3083 ap = ckzalloc(sizeof(struct alias));
3084 ap->name = ckstrdup(name);
3085 ap->val = ckstrdup(val);
3086 /*ap->flag = 0; - ckzalloc did it */
3087 /*ap->next = NULL;*/
3094 unalias(const char *name)
3098 app = __lookupalias(name);
3102 *app = freealias(*app);
3113 struct alias *ap, **app;
3117 for (i = 0; i < ATABSIZE; i++) {
3119 for (ap = *app; ap; ap = *app) {
3120 *app = freealias(*app);
3130 printalias(const struct alias *ap)
3132 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3136 * TODO - sort output
3138 static int FAST_FUNC
3139 aliascmd(int argc UNUSED_PARAM, char **argv)
3148 for (i = 0; i < ATABSIZE; i++) {
3149 for (ap = atab[i]; ap; ap = ap->next) {
3155 while ((n = *++argv) != NULL) {
3156 v = strchr(n+1, '=');
3157 if (v == NULL) { /* n+1: funny ksh stuff */
3158 ap = *__lookupalias(n);
3160 fprintf(stderr, "%s: %s not found\n", "alias", n);
3173 static int FAST_FUNC
3174 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3178 while ((i = nextopt("a")) != '\0') {
3184 for (i = 0; *argptr; argptr++) {
3185 if (unalias(*argptr)) {
3186 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3194 #endif /* ASH_ALIAS */
3197 /* ============ jobs.c */
3199 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3202 #define FORK_NOJOB 2
3204 /* mode flags for showjob(s) */
3205 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3206 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3207 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3210 * A job structure contains information about a job. A job is either a
3211 * single process or a set of processes contained in a pipeline. In the
3212 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3216 pid_t pid; /* process id */
3217 int status; /* last process status from wait() */
3218 char *cmd; /* text of command being run */
3222 struct procstat ps0; /* status of process */
3223 struct procstat *ps; /* status or processes when more than one */
3225 int stopstatus; /* status of a stopped job */
3228 nprocs: 16, /* number of processes */
3230 #define JOBRUNNING 0 /* at least one proc running */
3231 #define JOBSTOPPED 1 /* all procs are stopped */
3232 #define JOBDONE 2 /* all procs are completed */
3234 sigint: 1, /* job was killed by SIGINT */
3235 jobctl: 1, /* job running under job control */
3237 waited: 1, /* true if this entry has been waited for */
3238 used: 1, /* true if this entry is in used */
3239 changed: 1; /* true if status has changed */
3240 struct job *prev_job; /* previous job */
3243 static struct job *makejob(/*union node *,*/ int);
3244 static int forkshell(struct job *, union node *, int);
3245 static int waitforjob(struct job *);
3248 enum { doing_jobctl = 0 };
3249 #define setjobctl(on) do {} while (0)
3251 static smallint doing_jobctl; //references:8
3252 static void setjobctl(int);
3259 ignoresig(int signo)
3261 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3262 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3263 /* No, need to do it */
3264 signal(signo, SIG_IGN);
3266 sigmode[signo - 1] = S_HARD_IGN;
3270 * Signal handler. Only one usage site - in setsignal()
3275 gotsig[signo - 1] = 1;
3277 if (signo == SIGINT && !trap[SIGINT]) {
3278 if (!suppress_int) {
3280 raise_interrupt(); /* does not return */
3284 pending_sig = signo;
3289 * Set the signal handler for the specified signal. The routine figures
3290 * out what it should be set to.
3293 setsignal(int signo)
3296 char cur_act, new_act;
3297 struct sigaction act;
3301 if (t != NULL) { /* trap for this sig is set */
3303 if (t[0] == '\0') /* trap is "": ignore this sig */
3307 if (rootshell && new_act == S_DFL) {
3310 if (iflag || minusc || sflag == 0)
3319 * "In all cases, bash ignores SIGQUIT. Non-builtin
3320 * commands run by bash have signal handlers
3321 * set to the values inherited by the shell
3322 * from its parent". */
3338 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3339 //whereas we have to restore it to what shell got on entry
3340 //from the parent. See comment above
3342 t = &sigmode[signo - 1];
3345 /* current setting is not yet known */
3346 if (sigaction(signo, NULL, &act)) {
3347 /* pretend it worked; maybe we should give a warning,
3348 * but other shells don't. We don't alter sigmode,
3349 * so we retry every time.
3350 * btw, in Linux it never fails. --vda */
3353 if (act.sa_handler == SIG_IGN) {
3354 cur_act = S_HARD_IGN;
3356 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3358 cur_act = S_IGN; /* don't hard ignore these */
3362 if (cur_act == S_HARD_IGN || cur_act == new_act)
3365 act.sa_handler = SIG_DFL;
3368 act.sa_handler = onsig;
3369 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3370 sigfillset(&act.sa_mask); /* ditto */
3373 act.sa_handler = SIG_IGN;
3376 sigaction_set(signo, &act);
3381 /* mode flags for set_curjob */
3382 #define CUR_DELETE 2
3383 #define CUR_RUNNING 1
3384 #define CUR_STOPPED 0
3386 /* mode flags for dowait */
3387 #define DOWAIT_NONBLOCK WNOHANG
3388 #define DOWAIT_BLOCK 0
3391 /* pgrp of shell on invocation */
3392 static int initialpgrp; //references:2
3393 static int ttyfd = -1; //5
3396 static struct job *jobtab; //5
3398 static unsigned njobs; //4
3400 static struct job *curjob; //lots
3401 /* number of presumed living untracked jobs */
3402 static int jobless; //4
3405 set_curjob(struct job *jp, unsigned mode)
3408 struct job **jpp, **curp;
3410 /* first remove from list */
3411 jpp = curp = &curjob;
3416 jpp = &jp1->prev_job;
3418 *jpp = jp1->prev_job;
3420 /* Then re-insert in correct position */
3428 /* job being deleted */
3431 /* newly created job or backgrounded job,
3432 put after all stopped jobs. */
3436 if (!jp1 || jp1->state != JOBSTOPPED)
3439 jpp = &jp1->prev_job;
3445 /* newly stopped job - becomes curjob */
3446 jp->prev_job = *jpp;
3454 jobno(const struct job *jp)
3456 return jp - jobtab + 1;
3461 * Convert a job name to a job structure.
3464 #define getjob(name, getctl) getjob(name)
3467 getjob(const char *name, int getctl)
3471 const char *err_msg = "%s: no such job";
3475 char *(*match)(const char *, const char *);
3490 if (c == '+' || c == '%') {
3492 err_msg = "No current job";
3498 err_msg = "No previous job";
3509 jp = jobtab + num - 1;
3524 if (match(jp->ps[0].cmd, p)) {
3528 err_msg = "%s: ambiguous";
3538 err_msg = "job %s not created under job control";
3539 if (getctl && jp->jobctl == 0)
3544 ash_msg_and_raise_error(err_msg, name);
3548 * Mark a job structure as unused.
3551 freejob(struct job *jp)
3553 struct procstat *ps;
3557 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3558 if (ps->cmd != nullstr)
3561 if (jp->ps != &jp->ps0)
3564 set_curjob(jp, CUR_DELETE);
3570 xtcsetpgrp(int fd, pid_t pgrp)
3572 if (tcsetpgrp(fd, pgrp))
3573 ash_msg_and_raise_error("can't set tty process group (%m)");
3577 * Turn job control on and off.
3579 * Note: This code assumes that the third arg to ioctl is a character
3580 * pointer, which is true on Berkeley systems but not System V. Since
3581 * System V doesn't have job control yet, this isn't a problem now.
3583 * Called with interrupts off.
3591 if (on == doing_jobctl || rootshell == 0)
3595 ofd = fd = open(_PATH_TTY, O_RDWR);
3597 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3598 * That sometimes helps to acquire controlling tty.
3599 * Obviously, a workaround for bugs when someone
3600 * failed to provide a controlling tty to bash! :) */
3606 fd = fcntl(fd, F_DUPFD, 10);
3611 /* fd is a tty at this point */
3612 close_on_exec_on(fd);
3613 do { /* while we are in the background */
3614 pgrp = tcgetpgrp(fd);
3617 ash_msg("can't access tty; job control turned off");
3621 if (pgrp == getpgrp())
3632 xtcsetpgrp(fd, pgrp);
3634 /* turning job control off */
3637 /* was xtcsetpgrp, but this can make exiting ash
3638 * loop forever if pty is already deleted */
3639 tcsetpgrp(fd, pgrp);
3653 static int FAST_FUNC
3654 killcmd(int argc, char **argv)
3657 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3659 if (argv[i][0] == '%') {
3660 struct job *jp = getjob(argv[i], 0);
3661 unsigned pid = jp->ps[0].pid;
3662 /* Enough space for ' -NNN<nul>' */
3663 argv[i] = alloca(sizeof(int)*3 + 3);
3664 /* kill_main has matching code to expect
3665 * leading space. Needed to not confuse
3666 * negative pids with "kill -SIGNAL_NO" syntax */
3667 sprintf(argv[i], " -%u", pid);
3669 } while (argv[++i]);
3671 return kill_main(argc, argv);
3675 showpipe(struct job *jp, FILE *out)
3677 struct procstat *sp;
3678 struct procstat *spend;
3680 spend = jp->ps + jp->nprocs;
3681 for (sp = jp->ps + 1; sp < spend; sp++)
3682 fprintf(out, " | %s", sp->cmd);
3683 outcslow('\n', out);
3684 flush_stdout_stderr();
3689 restartjob(struct job *jp, int mode)
3691 struct procstat *ps;
3697 if (jp->state == JOBDONE)
3699 jp->state = JOBRUNNING;
3701 if (mode == FORK_FG)
3702 xtcsetpgrp(ttyfd, pgid);
3703 killpg(pgid, SIGCONT);
3707 if (WIFSTOPPED(ps->status)) {
3713 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3718 static int FAST_FUNC
3719 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3726 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3731 jp = getjob(*argv, 1);
3732 if (mode == FORK_BG) {
3733 set_curjob(jp, CUR_RUNNING);
3734 fprintf(out, "[%d] ", jobno(jp));
3736 outstr(jp->ps->cmd, out);
3738 retval = restartjob(jp, mode);
3739 } while (*argv && *++argv);
3745 sprint_status(char *s, int status, int sigonly)
3751 if (!WIFEXITED(status)) {
3753 if (WIFSTOPPED(status))
3754 st = WSTOPSIG(status);
3757 st = WTERMSIG(status);
3759 if (st == SIGINT || st == SIGPIPE)
3762 if (WIFSTOPPED(status))
3767 col = fmtstr(s, 32, strsignal(st));
3768 if (WCOREDUMP(status)) {
3769 col += fmtstr(s + col, 16, " (core dumped)");
3771 } else if (!sigonly) {
3772 st = WEXITSTATUS(status);
3774 col = fmtstr(s, 16, "Done(%d)", st);
3776 col = fmtstr(s, 16, "Done");
3783 dowait(int wait_flags, struct job *job)
3788 struct job *thisjob;
3791 TRACE(("dowait(0x%x) called\n", wait_flags));
3793 /* Do a wait system call. If job control is compiled in, we accept
3794 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3795 * NB: _not_ safe_waitpid, we need to detect EINTR */
3796 pid = waitpid(-1, &status,
3797 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3798 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3799 pid, status, errno, strerror(errno)));
3805 for (jp = curjob; jp; jp = jp->prev_job) {
3806 struct procstat *sp;
3807 struct procstat *spend;
3808 if (jp->state == JOBDONE)
3811 spend = jp->ps + jp->nprocs;
3814 if (sp->pid == pid) {
3815 TRACE(("Job %d: changing status of proc %d "
3816 "from 0x%x to 0x%x\n",
3817 jobno(jp), pid, sp->status, status));
3818 sp->status = status;
3821 if (sp->status == -1)
3824 if (state == JOBRUNNING)
3826 if (WIFSTOPPED(sp->status)) {
3827 jp->stopstatus = sp->status;
3831 } while (++sp < spend);
3836 if (!WIFSTOPPED(status))
3842 if (state != JOBRUNNING) {
3843 thisjob->changed = 1;
3845 if (thisjob->state != state) {
3846 TRACE(("Job %d: changing state from %d to %d\n",
3847 jobno(thisjob), thisjob->state, state));
3848 thisjob->state = state;
3850 if (state == JOBSTOPPED) {
3851 set_curjob(thisjob, CUR_STOPPED);
3860 if (thisjob && thisjob == job) {
3864 len = sprint_status(s, status, 1);
3875 blocking_wait_with_raise_on_sig(struct job *job)
3877 pid_t pid = dowait(DOWAIT_BLOCK, job);
3878 if (pid <= 0 && pending_sig)
3879 raise_exception(EXSIG);
3885 showjob(FILE *out, struct job *jp, int mode)
3887 struct procstat *ps;
3888 struct procstat *psend;
3895 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3896 /* just output process (group) id of pipeline */
3897 fprintf(out, "%d\n", ps->pid);
3901 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3906 else if (curjob && jp == curjob->prev_job)
3909 if (mode & SHOW_PIDS)
3910 col += fmtstr(s + col, 16, "%d ", ps->pid);
3912 psend = ps + jp->nprocs;
3914 if (jp->state == JOBRUNNING) {
3915 strcpy(s + col, "Running");
3916 col += sizeof("Running") - 1;
3918 int status = psend[-1].status;
3919 if (jp->state == JOBSTOPPED)
3920 status = jp->stopstatus;
3921 col += sprint_status(s + col, status, 0);
3923 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3925 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3926 * or prints several "PID | <cmdN>" lines,
3927 * depending on SHOW_PIDS bit.
3928 * We do not print status of individual processes
3929 * between PID and <cmdN>. bash does it, but not very well:
3930 * first line shows overall job status, not process status,
3931 * making it impossible to know 1st process status.
3935 /* for each process */
3938 if (mode & SHOW_PIDS)
3939 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
3941 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3944 fprintf(out, "%s", ps->cmd);
3948 outcslow('\n', out);
3952 if (jp->state == JOBDONE) {
3953 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3959 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3960 * statuses have changed since the last call to showjobs.
3963 showjobs(FILE *out, int mode)
3967 TRACE(("showjobs(0x%x) called\n", mode));
3969 /* Handle all finished jobs */
3970 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3973 for (jp = curjob; jp; jp = jp->prev_job) {
3974 if (!(mode & SHOW_CHANGED) || jp->changed) {
3975 showjob(out, jp, mode);
3980 static int FAST_FUNC
3981 jobscmd(int argc UNUSED_PARAM, char **argv)
3986 while ((m = nextopt("lp")) != '\0') {
3990 mode |= SHOW_ONLY_PGID;
3996 showjob(stdout, getjob(*argv, 0), mode);
3999 showjobs(stdout, mode);
4006 getstatus(struct job *job)
4011 status = job->ps[job->nprocs - 1].status;
4012 retval = WEXITSTATUS(status);
4013 if (!WIFEXITED(status)) {
4015 retval = WSTOPSIG(status);
4016 if (!WIFSTOPPED(status))
4019 /* XXX: limits number of signals */
4020 retval = WTERMSIG(status);
4022 if (retval == SIGINT)
4028 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4029 jobno(job), job->nprocs, status, retval));
4033 static int FAST_FUNC
4034 waitcmd(int argc UNUSED_PARAM, char **argv)
4041 raise_exception(EXSIG);
4048 /* wait for all jobs */
4052 if (!jp) /* no running procs */
4054 if (jp->state == JOBRUNNING)
4060 * "When bash is waiting for an asynchronous command via
4061 * the wait builtin, the reception of a signal for which a trap
4062 * has been set will cause the wait builtin to return immediately
4063 * with an exit status greater than 128, immediately after which
4064 * the trap is executed."
4065 * Do we do it that way? */
4066 blocking_wait_with_raise_on_sig(NULL);
4072 if (**argv != '%') {
4073 pid_t pid = number(*argv);
4078 if (job->ps[job->nprocs - 1].pid == pid)
4080 job = job->prev_job;
4083 job = getjob(*argv, 0);
4084 /* loop until process terminated or stopped */
4085 while (job->state == JOBRUNNING)
4086 blocking_wait_with_raise_on_sig(NULL);
4088 retval = getstatus(job);
4101 struct job *jp, *jq;
4103 len = njobs * sizeof(*jp);
4105 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4107 offset = (char *)jp - (char *)jq;
4109 /* Relocate pointers */
4112 jq = (struct job *)((char *)jq + l);
4116 #define joff(p) ((struct job *)((char *)(p) + l))
4117 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4118 if (joff(jp)->ps == &jq->ps0)
4119 jmove(joff(jp)->ps);
4120 if (joff(jp)->prev_job)
4121 jmove(joff(jp)->prev_job);
4131 jp = (struct job *)((char *)jp + len);
4135 } while (--jq >= jp);
4140 * Return a new job structure.
4141 * Called with interrupts off.
4144 makejob(/*union node *node,*/ int nprocs)
4149 for (i = njobs, jp = jobtab; ; jp++) {
4156 if (jp->state != JOBDONE || !jp->waited)
4165 memset(jp, 0, sizeof(*jp));
4167 /* jp->jobctl is a bitfield.
4168 * "jp->jobctl |= jobctl" likely to give awful code */
4172 jp->prev_job = curjob;
4177 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4179 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4186 * Return a string identifying a command (to be printed by the
4189 static char *cmdnextc;
4192 cmdputs(const char *s)
4194 static const char vstype[VSTYPE + 1][3] = {
4195 "", "}", "-", "+", "?", "=",
4196 "%", "%%", "#", "##"
4197 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4200 const char *p, *str;
4204 unsigned char subtype = 0;
4207 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4209 while ((c = *p++) != 0) {
4217 if ((subtype & VSTYPE) == VSLENGTH)
4221 if (!(subtype & VSQUOTE) == !(quoted & 1))
4227 str = "\"}" + !(quoted & 1);
4234 case CTLBACKQ+CTLQUOTE:
4237 #if ENABLE_SH_MATH_SUPPORT
4252 if ((subtype & VSTYPE) != VSNORMAL)
4254 str = vstype[subtype & VSTYPE];
4255 if (subtype & VSNUL)
4264 /* These can only happen inside quotes */
4277 while ((c = *str++) != '\0') {
4282 USTPUTC('"', nextc);
4288 /* cmdtxt() and cmdlist() call each other */
4289 static void cmdtxt(union node *n);
4292 cmdlist(union node *np, int sep)
4294 for (; np; np = np->narg.next) {
4298 if (sep && np->narg.next)
4304 cmdtxt(union node *n)
4307 struct nodelist *lp;
4318 lp = n->npipe.cmdlist;
4336 cmdtxt(n->nbinary.ch1);
4352 cmdtxt(n->nif.test);
4354 if (n->nif.elsepart) {
4355 cmdtxt(n->nif.ifpart);
4357 n = n->nif.elsepart;
4375 cmdtxt(n->nbinary.ch1);
4385 cmdputs(n->nfor.var);
4387 cmdlist(n->nfor.args, 1);
4392 cmdputs(n->narg.text);
4396 cmdlist(n->ncmd.args, 1);
4397 cmdlist(n->ncmd.redirect, 0);
4410 cmdputs(n->ncase.expr->narg.text);
4412 for (np = n->ncase.cases; np; np = np->nclist.next) {
4413 cmdtxt(np->nclist.pattern);
4415 cmdtxt(np->nclist.body);
4429 #if ENABLE_ASH_BASH_COMPAT
4444 cmdputs(utoa(n->nfile.fd));
4446 if (n->type == NTOFD || n->type == NFROMFD) {
4447 cmdputs(utoa(n->ndup.dupfd));
4456 commandtext(union node *n)
4460 STARTSTACKSTR(cmdnextc);
4462 name = stackblock();
4463 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4464 name, cmdnextc, cmdnextc));
4465 return ckstrdup(name);
4470 * Fork off a subshell. If we are doing job control, give the subshell its
4471 * own process group. Jp is a job structure that the job is to be added to.
4472 * N is the command that will be evaluated by the child. Both jp and n may
4473 * be NULL. The mode parameter can be one of the following:
4474 * FORK_FG - Fork off a foreground process.
4475 * FORK_BG - Fork off a background process.
4476 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4477 * process group even if job control is on.
4479 * When job control is turned off, background processes have their standard
4480 * input redirected to /dev/null (except for the second and later processes
4483 * Called with interrupts off.
4486 * Clear traps on a fork.
4493 for (tp = trap; tp < &trap[NSIG]; tp++) {
4494 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4496 if (trap_ptr == trap)
4498 /* else: it "belongs" to trap_ptr vector, don't free */
4500 if ((tp - trap) != 0)
4501 setsignal(tp - trap);
4507 /* Lives far away from here, needed for forkchild */
4508 static void closescript(void);
4510 /* Called after fork(), in child */
4511 static NOINLINE void
4512 forkchild(struct job *jp, union node *n, int mode)
4516 TRACE(("Child shell %d\n", getpid()));
4520 /* man bash: "Non-builtin commands run by bash have signal handlers
4521 * set to the values inherited by the shell from its parent".
4522 * Do we do it correctly? */
4526 if (mode == FORK_NOJOB /* is it `xxx` ? */
4527 && n && n->type == NCMD /* is it single cmd? */
4528 /* && n->ncmd.args->type == NARG - always true? */
4529 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4530 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4531 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4533 TRACE(("Trap hack\n"));
4534 /* Awful hack for `trap` or $(trap).
4536 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4537 * contains an example where "trap" is executed in a subshell:
4539 * save_traps=$(trap)
4541 * eval "$save_traps"
4543 * Standard does not say that "trap" in subshell shall print
4544 * parent shell's traps. It only says that its output
4545 * must have suitable form, but then, in the above example
4546 * (which is not supposed to be normative), it implies that.
4548 * bash (and probably other shell) does implement it
4549 * (traps are reset to defaults, but "trap" still shows them),
4550 * but as a result, "trap" logic is hopelessly messed up:
4553 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4554 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4555 * # true | trap <--- trap is in subshell - no output (ditto)
4556 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4557 * trap -- 'echo Ho' SIGWINCH
4558 * # echo `(trap)` <--- in subshell in subshell - output
4559 * trap -- 'echo Ho' SIGWINCH
4560 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4561 * trap -- 'echo Ho' SIGWINCH
4563 * The rules when to forget and when to not forget traps
4564 * get really complex and nonsensical.
4566 * Our solution: ONLY bare $(trap) or `trap` is special.
4568 /* Save trap handler strings for trap builtin to print */
4569 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4570 /* Fall through into clearing traps */
4574 /* do job control only in root shell */
4576 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4579 if (jp->nprocs == 0)
4582 pgrp = jp->ps[0].pid;
4583 /* this can fail because we are doing it in the parent also */
4585 if (mode == FORK_FG)
4586 xtcsetpgrp(ttyfd, pgrp);
4591 if (mode == FORK_BG) {
4592 /* man bash: "When job control is not in effect,
4593 * asynchronous commands ignore SIGINT and SIGQUIT" */
4596 if (jp->nprocs == 0) {
4598 if (open(bb_dev_null, O_RDONLY) != 0)
4599 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4603 if (iflag) { /* why if iflag only? */
4608 * "In all cases, bash ignores SIGQUIT. Non-builtin
4609 * commands run by bash have signal handlers
4610 * set to the values inherited by the shell
4612 * Take care of the second rule: */
4616 if (n && n->type == NCMD
4617 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4619 TRACE(("Job hack\n"));
4620 /* "jobs": we do not want to clear job list for it,
4621 * instead we remove only _its_ own_ job from job list.
4622 * This makes "jobs .... | cat" more useful.
4628 for (jp = curjob; jp; jp = jp->prev_job)
4633 /* Called after fork(), in parent */
4635 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4638 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4640 TRACE(("In parent shell: child = %d\n", pid));
4642 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4648 if (mode != FORK_NOJOB && jp->jobctl) {
4651 if (jp->nprocs == 0)
4654 pgrp = jp->ps[0].pid;
4655 /* This can fail because we are doing it in the child also */
4659 if (mode == FORK_BG) {
4660 backgndpid = pid; /* set $! */
4661 set_curjob(jp, CUR_RUNNING);
4664 struct procstat *ps = &jp->ps[jp->nprocs++];
4669 if (doing_jobctl && n)
4670 ps->cmd = commandtext(n);
4676 forkshell(struct job *jp, union node *n, int mode)
4680 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4683 TRACE(("Fork failed, errno=%d", errno));
4686 ash_msg_and_raise_error("can't fork");
4689 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4690 forkchild(jp, n, mode);
4692 forkparent(jp, n, mode, pid);
4698 * Wait for job to finish.
4700 * Under job control we have the problem that while a child process
4701 * is running interrupts generated by the user are sent to the child
4702 * but not to the shell. This means that an infinite loop started by
4703 * an interactive user may be hard to kill. With job control turned off,
4704 * an interactive user may place an interactive program inside a loop.
4705 * If the interactive program catches interrupts, the user doesn't want
4706 * these interrupts to also abort the loop. The approach we take here
4707 * is to have the shell ignore interrupt signals while waiting for a
4708 * foreground process to terminate, and then send itself an interrupt
4709 * signal if the child process was terminated by an interrupt signal.
4710 * Unfortunately, some programs want to do a bit of cleanup and then
4711 * exit on interrupt; unless these processes terminate themselves by
4712 * sending a signal to themselves (instead of calling exit) they will
4713 * confuse this approach.
4715 * Called with interrupts off.
4718 waitforjob(struct job *jp)
4722 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4725 while (jp->state == JOBRUNNING) {
4726 /* In non-interactive shells, we _can_ get
4727 * a keyboard signal here and be EINTRed,
4728 * but we just loop back, waiting for command to complete.
4731 * "If bash is waiting for a command to complete and receives
4732 * a signal for which a trap has been set, the trap
4733 * will not be executed until the command completes."
4735 * Reality is that even if trap is not set, bash
4736 * will not act on the signal until command completes.
4737 * Try this. sleep5intoff.c:
4738 * #include <signal.h>
4739 * #include <unistd.h>
4742 * sigemptyset(&set);
4743 * sigaddset(&set, SIGINT);
4744 * sigaddset(&set, SIGQUIT);
4745 * sigprocmask(SIG_BLOCK, &set, NULL);
4749 * $ bash -c './sleep5intoff; echo hi'
4750 * ^C^C^C^C <--- pressing ^C once a second
4752 * $ bash -c './sleep5intoff; echo hi'
4753 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4756 dowait(DOWAIT_BLOCK, jp);
4763 xtcsetpgrp(ttyfd, rootpid);
4765 * This is truly gross.
4766 * If we're doing job control, then we did a TIOCSPGRP which
4767 * caused us (the shell) to no longer be in the controlling
4768 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4769 * intuit from the subprocess exit status whether a SIGINT
4770 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4772 if (jp->sigint) /* TODO: do the same with all signals */
4773 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4775 if (jp->state == JOBDONE)
4782 * return 1 if there are stopped jobs, otherwise 0
4794 if (jp && jp->state == JOBSTOPPED) {
4795 out2str("You have stopped jobs.\n");
4804 /* ============ redir.c
4806 * Code for dealing with input/output redirection.
4809 #define EMPTY -2 /* marks an unused slot in redirtab */
4810 #define CLOSED -3 /* marks a slot of previously-closed fd */
4813 * Open a file in noclobber mode.
4814 * The code was copied from bash.
4817 noclobberopen(const char *fname)
4820 struct stat finfo, finfo2;
4823 * If the file exists and is a regular file, return an error
4826 r = stat(fname, &finfo);
4827 if (r == 0 && S_ISREG(finfo.st_mode)) {
4833 * If the file was not present (r != 0), make sure we open it
4834 * exclusively so that if it is created before we open it, our open
4835 * will fail. Make sure that we do not truncate an existing file.
4836 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4837 * file was not a regular file, we leave O_EXCL off.
4840 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4841 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4843 /* If the open failed, return the file descriptor right away. */
4848 * OK, the open succeeded, but the file may have been changed from a
4849 * non-regular file to a regular file between the stat and the open.
4850 * We are assuming that the O_EXCL open handles the case where FILENAME
4851 * did not exist and is symlinked to an existing file between the stat
4856 * If we can open it and fstat the file descriptor, and neither check
4857 * revealed that it was a regular file, and the file has not been
4858 * replaced, return the file descriptor.
4860 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4861 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4864 /* The file has been replaced. badness. */
4871 * Handle here documents. Normally we fork off a process to write the
4872 * data to a pipe. If the document is short, we can stuff the data in
4873 * the pipe without forking.
4875 /* openhere needs this forward reference */
4876 static void expandhere(union node *arg, int fd);
4878 openhere(union node *redir)
4884 ash_msg_and_raise_error("pipe call failed");
4885 if (redir->type == NHERE) {
4886 len = strlen(redir->nhere.doc->narg.text);
4887 if (len <= PIPE_BUF) {
4888 full_write(pip[1], redir->nhere.doc->narg.text, len);
4892 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4895 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4896 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4897 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4898 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4899 signal(SIGPIPE, SIG_DFL);
4900 if (redir->type == NHERE)
4901 full_write(pip[1], redir->nhere.doc->narg.text, len);
4903 expandhere(redir->nhere.doc, pip[1]);
4904 _exit(EXIT_SUCCESS);
4912 openredirect(union node *redir)
4917 switch (redir->nfile.type) {
4919 fname = redir->nfile.expfname;
4920 f = open(fname, O_RDONLY);
4925 fname = redir->nfile.expfname;
4926 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4931 #if ENABLE_ASH_BASH_COMPAT
4934 /* Take care of noclobber mode. */
4936 fname = redir->nfile.expfname;
4937 f = noclobberopen(fname);
4944 fname = redir->nfile.expfname;
4945 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4950 fname = redir->nfile.expfname;
4951 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4959 /* Fall through to eliminate warning. */
4960 /* Our single caller does this itself */
4967 f = openhere(redir);
4973 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4975 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4979 * Copy a file descriptor to be >= to. Returns -1
4980 * if the source file descriptor is closed, EMPTY if there are no unused
4981 * file descriptors left.
4983 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4984 * old code was doing close(to) prior to copyfd() to achieve the same */
4986 COPYFD_EXACT = (int)~(INT_MAX),
4987 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4990 copyfd(int from, int to)
4994 if (to & COPYFD_EXACT) {
4995 to &= ~COPYFD_EXACT;
4997 newfd = dup2(from, to);
4999 newfd = fcntl(from, F_DUPFD, to);
5002 if (errno == EMFILE)
5004 /* Happens when source fd is not open: try "echo >&99" */
5005 ash_msg_and_raise_error("%d: %m", from);
5010 /* Struct def and variable are moved down to the first usage site */
5015 struct redirtab *next;
5018 struct two_fd_t two_fd[];
5020 #define redirlist (G_var.redirlist)
5022 static int need_to_remember(struct redirtab *rp, int fd)
5026 if (!rp) /* remembering was not requested */
5029 for (i = 0; i < rp->pair_count; i++) {
5030 if (rp->two_fd[i].orig == fd) {
5031 /* already remembered */
5038 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5039 static int is_hidden_fd(struct redirtab *rp, int fd)
5042 struct parsefile *pf;
5055 fd |= COPYFD_RESTORE;
5056 for (i = 0; i < rp->pair_count; i++) {
5057 if (rp->two_fd[i].copy == fd) {
5065 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5066 * old file descriptors are stashed away so that the redirection can be
5067 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5068 * standard output, and the standard error if it becomes a duplicate of
5069 * stdout, is saved in memory.
5071 /* flags passed to redirect */
5072 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5073 #define REDIR_SAVEFD2 03 /* set preverrout */
5075 redirect(union node *redir, int flags)
5077 struct redirtab *sv;
5082 int copied_fd2 = -1;
5092 if (flags & REDIR_PUSH) {
5093 union node *tmp = redir;
5096 #if ENABLE_ASH_BASH_COMPAT
5097 if (redir->nfile.type == NTO2)
5100 tmp = tmp->nfile.next;
5102 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5103 sv->next = redirlist;
5104 sv->pair_count = sv_pos;
5106 sv->nullredirs = g_nullredirs - 1;
5108 while (sv_pos > 0) {
5110 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5115 fd = redir->nfile.fd;
5116 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5117 int right_fd = redir->ndup.dupfd;
5118 /* redirect from/to same file descriptor? */
5121 /* echo >&10 and 10 is a fd opened to the sh script? */
5122 if (is_hidden_fd(sv, right_fd)) {
5123 errno = EBADF; /* as if it is closed */
5124 ash_msg_and_raise_error("%d: %m", right_fd);
5128 newfd = openredirect(redir); /* always >= 0 */
5130 /* Descriptor wasn't open before redirect.
5131 * Mark it for close in the future */
5132 if (need_to_remember(sv, fd)) {
5133 goto remember_to_close;
5138 #if ENABLE_ASH_BASH_COMPAT
5141 if (need_to_remember(sv, fd)) {
5142 /* Copy old descriptor */
5143 i = fcntl(fd, F_DUPFD, 10);
5144 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5145 * are closed in popredir() in the child, preventing them from leaking
5146 * into child. (popredir() also cleans up the mess in case of failures)
5151 /* Strange error (e.g. "too many files" EMFILE?) */
5155 ash_msg_and_raise_error("%d: %m", fd);
5158 /* EBADF: it is not open - good, remember to close it */
5161 } else { /* fd is open, save its copy */
5162 /* "exec fd>&-" should not close fds
5163 * which point to script file(s).
5164 * Force them to be restored afterwards */
5165 if (is_hidden_fd(sv, fd))
5166 i |= COPYFD_RESTORE;
5170 sv->two_fd[sv_pos].orig = fd;
5171 sv->two_fd[sv_pos].copy = i;
5175 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5176 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5177 /* Don't want to trigger debugging */
5181 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5183 } else if (fd != newfd) { /* move newfd to fd */
5184 copyfd(newfd, fd | COPYFD_EXACT);
5185 #if ENABLE_ASH_BASH_COMPAT
5186 if (!(redir->nfile.type == NTO2 && fd == 2))
5190 #if ENABLE_ASH_BASH_COMPAT
5191 if (redir->nfile.type == NTO2 && fd == 1) {
5192 /* We already redirected it to fd 1, now copy it to 2 */
5198 } while ((redir = redir->nfile.next) != NULL);
5201 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5202 preverrout_fd = copied_fd2;
5206 * Undo the effects of the last redirection.
5209 popredir(int drop, int restore)
5211 struct redirtab *rp;
5214 if (--g_nullredirs >= 0)
5218 for (i = 0; i < rp->pair_count; i++) {
5219 int fd = rp->two_fd[i].orig;
5220 int copy = rp->two_fd[i].copy;
5221 if (copy == CLOSED) {
5226 if (copy != EMPTY) {
5227 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5228 copy &= ~COPYFD_RESTORE;
5230 copyfd(copy, fd | COPYFD_EXACT);
5232 close(copy & ~COPYFD_RESTORE);
5235 redirlist = rp->next;
5236 g_nullredirs = rp->nullredirs;
5242 * Undo all redirections. Called on error or interrupt.
5246 * Discard all saved file descriptors.
5249 clearredir(int drop)
5255 popredir(drop, /*restore:*/ 0);
5260 redirectsafe(union node *redir, int flags)
5263 volatile int saveint;
5264 struct jmploc *volatile savehandler = exception_handler;
5265 struct jmploc jmploc;
5268 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5269 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5271 exception_handler = &jmploc;
5272 redirect(redir, flags);
5274 exception_handler = savehandler;
5275 if (err && exception_type != EXERROR)
5276 longjmp(exception_handler->loc, 1);
5277 RESTORE_INT(saveint);
5282 /* ============ Routines to expand arguments to commands
5284 * We have to deal with backquotes, shell variables, and file metacharacters.
5287 #if ENABLE_SH_MATH_SUPPORT
5289 ash_arith(const char *s)
5291 arith_eval_hooks_t math_hooks;
5295 math_hooks.lookupvar = lookupvar;
5296 math_hooks.setvar = setvar;
5297 math_hooks.endofname = endofname;
5300 result = arith(s, &errcode, &math_hooks);
5303 ash_msg_and_raise_error("exponent less than 0");
5305 ash_msg_and_raise_error("divide by zero");
5307 ash_msg_and_raise_error("expression recursion loop detected");
5308 raise_error_syntax(s);
5319 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5320 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5321 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5322 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5323 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5324 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5325 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5326 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5327 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5331 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5332 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5333 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5334 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5335 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5338 * Structure specifying which parts of the string should be searched
5339 * for IFS characters.
5342 struct ifsregion *next; /* next region in list */
5343 int begoff; /* offset of start of region */
5344 int endoff; /* offset of end of region */
5345 int nulonly; /* search for nul bytes only */
5349 struct strlist *list;
5350 struct strlist **lastp;
5353 /* output of current string */
5354 static char *expdest;
5355 /* list of back quote expressions */
5356 static struct nodelist *argbackq;
5357 /* first struct in list of ifs regions */
5358 static struct ifsregion ifsfirst;
5359 /* last struct in list */
5360 static struct ifsregion *ifslastp;
5361 /* holds expanded arg list */
5362 static struct arglist exparg;
5372 expdest = makestrspace(32, expdest);
5373 len = fmtstr(expdest, 32, arith_t_fmt, num);
5374 STADJUST(len, expdest);
5379 esclen(const char *start, const char *p)
5383 while (p > start && (unsigned char)*--p == CTLESC) {
5390 * Remove any CTLESC characters from a string.
5393 rmescapes(char *str, int flag)
5395 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5399 unsigned protect_against_glob;
5402 p = strpbrk(str, qchars);
5408 if (flag & RMESCAPE_ALLOC) {
5409 size_t len = p - str;
5410 size_t fulllen = len + strlen(p) + 1;
5412 if (flag & RMESCAPE_GROW) {
5413 r = makestrspace(fulllen, expdest);
5414 } else if (flag & RMESCAPE_HEAP) {
5415 r = ckmalloc(fulllen);
5417 r = stalloc(fulllen);
5421 q = (char *)memcpy(q, str, len) + len;
5425 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5426 globbing = flag & RMESCAPE_GLOB;
5427 protect_against_glob = globbing;
5429 if ((unsigned char)*p == CTLQUOTEMARK) {
5430 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5431 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5432 // Note: both inquotes and protect_against_glob only affect whether
5433 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5434 inquotes = ~inquotes;
5436 protect_against_glob = globbing;
5440 /* naked back slash */
5441 protect_against_glob = 0;
5444 if ((unsigned char)*p == CTLESC) {
5446 if (protect_against_glob && inquotes && *p != '/') {
5450 protect_against_glob = globbing;
5455 if (flag & RMESCAPE_GROW) {
5457 STADJUST(q - r + 1, expdest);
5461 #define pmatch(a, b) !fnmatch((a), (b), 0)
5464 * Prepare a pattern for a expmeta (internal glob(3)) call.
5466 * Returns an stalloced string.
5469 preglob(const char *pattern, int quoted, int flag)
5471 flag |= RMESCAPE_GLOB;
5473 flag |= RMESCAPE_QUOTED;
5475 return rmescapes((char *)pattern, flag);
5479 * Put a string on the stack.
5482 memtodest(const char *p, size_t len, int syntax, int quotes)
5486 q = makestrspace(quotes ? len * 2 : len, q);
5489 unsigned char c = *p++;
5493 int n = SIT(c, syntax);
5494 if (n == CCTL || n == CBACK)
5504 strtodest(const char *p, int syntax, int quotes)
5506 memtodest(p, strlen(p), syntax, quotes);
5510 * Record the fact that we have to scan this region of the
5511 * string for IFS characters.
5514 recordregion(int start, int end, int nulonly)
5516 struct ifsregion *ifsp;
5518 if (ifslastp == NULL) {
5522 ifsp = ckzalloc(sizeof(*ifsp));
5523 /*ifsp->next = NULL; - ckzalloc did it */
5524 ifslastp->next = ifsp;
5528 ifslastp->begoff = start;
5529 ifslastp->endoff = end;
5530 ifslastp->nulonly = nulonly;
5534 removerecordregions(int endoff)
5536 if (ifslastp == NULL)
5539 if (ifsfirst.endoff > endoff) {
5540 while (ifsfirst.next != NULL) {
5541 struct ifsregion *ifsp;
5543 ifsp = ifsfirst.next->next;
5544 free(ifsfirst.next);
5545 ifsfirst.next = ifsp;
5548 if (ifsfirst.begoff > endoff)
5551 ifslastp = &ifsfirst;
5552 ifsfirst.endoff = endoff;
5557 ifslastp = &ifsfirst;
5558 while (ifslastp->next && ifslastp->next->begoff < endoff)
5559 ifslastp=ifslastp->next;
5560 while (ifslastp->next != NULL) {
5561 struct ifsregion *ifsp;
5563 ifsp = ifslastp->next->next;
5564 free(ifslastp->next);
5565 ifslastp->next = ifsp;
5568 if (ifslastp->endoff > endoff)
5569 ifslastp->endoff = endoff;
5573 exptilde(char *startp, char *p, int flags)
5579 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5584 while ((c = *++p) != '\0') {
5591 if (flags & EXP_VARTILDE)
5601 if (*name == '\0') {
5602 home = lookupvar(homestr);
5604 pw = getpwnam(name);
5609 if (!home || !*home)
5612 startloc = expdest - (char *)stackblock();
5613 strtodest(home, SQSYNTAX, quotes);
5614 recordregion(startloc, expdest - (char *)stackblock(), 0);
5622 * Execute a command inside back quotes. If it's a builtin command, we
5623 * want to save its output in a block obtained from malloc. Otherwise
5624 * we fork off a subprocess and get the output of the command via a pipe.
5625 * Should be called with interrupts off.
5627 struct backcmd { /* result of evalbackcmd */
5628 int fd; /* file descriptor to read from */
5629 int nleft; /* number of chars in buffer */
5630 char *buf; /* buffer */
5631 struct job *jp; /* job structure for command */
5634 /* These forward decls are needed to use "eval" code for backticks handling: */
5635 static uint8_t back_exitstatus; /* exit status of backquoted command */
5636 #define EV_EXIT 01 /* exit after evaluating tree */
5637 static void evaltree(union node *, int);
5639 static void FAST_FUNC
5640 evalbackcmd(union node *n, struct backcmd *result)
5651 saveherefd = herefd;
5659 ash_msg_and_raise_error("pipe call failed");
5660 jp = makejob(/*n,*/ 1);
5661 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5666 copyfd(pip[1], 1 | COPYFD_EXACT);
5670 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5674 result->fd = pip[0];
5677 herefd = saveherefd;
5679 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5680 result->fd, result->buf, result->nleft, result->jp));
5684 * Expand stuff in backwards quotes.
5687 expbackq(union node *cmd, int quoted, int quotes)
5695 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5696 struct stackmark smark;
5699 setstackmark(&smark);
5701 startloc = dest - (char *)stackblock();
5703 evalbackcmd(cmd, &in);
5704 popstackmark(&smark);
5711 memtodest(p, i, syntax, quotes);
5715 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5716 TRACE(("expbackq: read returns %d\n", i));
5725 back_exitstatus = waitforjob(in.jp);
5729 /* Eat all trailing newlines */
5731 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5736 recordregion(startloc, dest - (char *)stackblock(), 0);
5737 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5738 (dest - (char *)stackblock()) - startloc,
5739 (dest - (char *)stackblock()) - startloc,
5740 stackblock() + startloc));
5743 #if ENABLE_SH_MATH_SUPPORT
5745 * Expand arithmetic expression. Backup to start of expression,
5746 * evaluate, place result in (backed up) result, adjust string position.
5759 * This routine is slightly over-complicated for
5760 * efficiency. Next we scan backwards looking for the
5761 * start of arithmetic.
5763 start = stackblock();
5770 while ((unsigned char)*p != CTLARI) {
5774 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5779 esc = esclen(start, p);
5789 removerecordregions(begoff);
5796 rmescapes(p + 2, 0);
5798 len = cvtnum(ash_arith(p + 2));
5801 recordregion(begoff, begoff + len, 0);
5805 /* argstr needs it */
5806 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5809 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5810 * characters to allow for further processing. Otherwise treat
5811 * $@ like $* since no splitting will be performed.
5813 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5814 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5815 * for correct expansion of "B=$A" word.
5818 argstr(char *p, int flags, struct strlist *var_str_list)
5820 static const char spclchars[] ALIGN1 = {
5828 CTLBACKQ | CTLQUOTE,
5829 #if ENABLE_SH_MATH_SUPPORT
5834 const char *reject = spclchars;
5835 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5836 int breakall = flags & EXP_WORD;
5841 if (!(flags & EXP_VARTILDE)) {
5843 } else if (flags & EXP_VARTILDE2) {
5848 if (flags & EXP_TILDE) {
5851 flags &= ~EXP_TILDE;
5854 if (*q == CTLESC && (flags & EXP_QWORD))
5857 p = exptilde(p, q, flags);
5860 startloc = expdest - (char *)stackblock();
5864 length += strcspn(p + length, reject);
5868 #if ENABLE_SH_MATH_SUPPORT
5872 /* c == '=' || c == ':' || c == CTLENDARI */
5878 expdest = stack_nputstr(p, length, expdest);
5879 newloc = expdest - (char *)stackblock();
5880 if (breakall && !inquotes && newloc > startloc) {
5881 recordregion(startloc, newloc, 0);
5892 if (flags & EXP_VARTILDE2) {
5896 flags |= EXP_VARTILDE2;
5901 * sort of a hack - expand tildes in variable
5902 * assignments (after the first '=' and after ':'s).
5911 case CTLENDVAR: /* ??? */
5914 /* "$@" syntax adherence hack */
5916 && memcmp(p, dolatstr, 4) == 0
5917 && ( p[4] == CTLQUOTEMARK
5918 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5921 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5924 inquotes = !inquotes;
5937 p = evalvar(p, flags, var_str_list);
5941 case CTLBACKQ|CTLQUOTE:
5942 expbackq(argbackq->n, c, quotes);
5943 argbackq = argbackq->next;
5945 #if ENABLE_SH_MATH_SUPPORT
5958 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5961 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5962 // as part of a larger change when he added support for ${var/a/b}.
5963 // However, it broke # and % operators:
5967 //echo ${var#ab} abcdcd abcdcd
5968 //echo ${var##ab} abcdcd abcdcd
5969 //echo ${var#a*b} abcdcd ababcdcd (!)
5970 //echo ${var##a*b} cdcd cdcd
5971 //echo ${var#?} babcdcd ababcdcd (!)
5972 //echo ${var##?} babcdcd babcdcd
5973 //echo ${var#*} ababcdcd babcdcd (!)
5975 //echo ${var%cd} ababcd ababcd
5976 //echo ${var%%cd} ababcd abab (!)
5977 //echo ${var%c*d} ababcd ababcd
5978 //echo ${var%%c*d} abab ababcdcd (!)
5979 //echo ${var%?} ababcdc ababcdc
5980 //echo ${var%%?} ababcdc ababcdcd (!)
5981 //echo ${var%*} ababcdcd ababcdcd
5984 // Commenting it back out helped. Remove it completely if it really
5987 char *loc, *loc2; //, *full;
5993 int match; // = strlen(str);
5994 const char *s = loc2;
6001 match = pmatch(str, s); // this line was deleted
6003 // // chop off end if its '*'
6004 // full = strrchr(str, '*');
6005 // if (full && full != str)
6008 // // If str starts with '*' replace with s.
6009 // if ((*str == '*') && strlen(s) >= match) {
6010 // full = xstrdup(s);
6011 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6013 // full = xstrndup(str, match);
6014 // match = strncmp(s, full, strlen(full));
6018 if (match) // if (!match)
6020 if (quotes && (unsigned char)*loc == CTLESC)
6029 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6036 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6039 const char *s = loc2;
6044 match = pmatch(str, s);
6051 esc = esclen(startp, loc);
6062 static void varunset(const char *, const char *, const char *, int) NORETURN;
6064 varunset(const char *end, const char *var, const char *umsg, int varflags)
6070 msg = "parameter not set";
6072 if ((unsigned char)*end == CTLENDVAR) {
6073 if (varflags & VSNUL)
6079 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6082 #if ENABLE_ASH_BASH_COMPAT
6084 parse_sub_pattern(char *arg, int inquotes)
6086 char *idx, *repl = NULL;
6095 /* Only the first '/' seen is our separator */
6102 if (!inquotes && c == '\\' && arg[1] == '\\')
6103 arg++; /* skip both \\, not just first one */
6110 #endif /* ENABLE_ASH_BASH_COMPAT */
6113 subevalvar(char *p, char *str, int strloc, int subtype,
6114 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6116 struct nodelist *saveargbackq = argbackq;
6119 char *rmesc, *rmescend;
6120 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6121 IF_ASH_BASH_COMPAT(char null = '\0';)
6122 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6123 int saveherefd = herefd;
6124 int amount, workloc, resetloc;
6126 char *(*scan)(char*, char*, char*, char*, int, int);
6129 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6131 STPUTC('\0', expdest);
6132 herefd = saveherefd;
6133 argbackq = saveargbackq;
6134 startp = (char *)stackblock() + startloc;
6138 setvar(str, startp, 0);
6139 amount = startp - expdest;
6140 STADJUST(amount, expdest);
6143 #if ENABLE_ASH_BASH_COMPAT
6145 loc = str = stackblock() + strloc;
6146 /* Read POS in ${var:POS:LEN} */
6147 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6148 len = str - startp - 1;
6150 /* *loc != '\0', guaranteed by parser */
6154 /* Adjust the length by the number of escapes */
6155 for (ptr = startp; ptr < (str - 1); ptr++) {
6156 if ((unsigned char)*ptr == CTLESC) {
6164 if (*loc++ == ':') {
6168 /* Skip POS in ${var:POS:LEN} */
6170 while (*loc && *loc != ':') {
6172 * bash complains on: var=qwe; echo ${var:1a:123}
6174 ash_msg_and_raise_error(msg_illnum, str);
6178 if (*loc++ == ':') {
6182 if (pos >= orig_len) {
6186 if (len > (orig_len - pos))
6187 len = orig_len - pos;
6189 for (str = startp; pos; str++, pos--) {
6190 if (quotes && (unsigned char)*str == CTLESC)
6193 for (loc = startp; len; len--) {
6194 if (quotes && (unsigned char)*str == CTLESC)
6199 amount = loc - expdest;
6200 STADJUST(amount, expdest);
6205 varunset(p, str, startp, varflags);
6208 resetloc = expdest - (char *)stackblock();
6210 /* We'll comeback here if we grow the stack while handling
6211 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6212 * stack will need rebasing, and we'll need to remove our work
6215 IF_ASH_BASH_COMPAT(restart:)
6217 amount = expdest - ((char *)stackblock() + resetloc);
6218 STADJUST(-amount, expdest);
6219 startp = (char *)stackblock() + startloc;
6222 rmescend = (char *)stackblock() + strloc;
6224 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6225 if (rmesc != startp) {
6227 startp = (char *)stackblock() + startloc;
6231 str = (char *)stackblock() + strloc;
6232 preglob(str, varflags & VSQUOTE, 0);
6233 workloc = expdest - (char *)stackblock();
6235 #if ENABLE_ASH_BASH_COMPAT
6236 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6237 char *idx, *end, *restart_detect;
6240 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6245 /* If there's no pattern to match, return the expansion unmolested */
6253 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6255 /* No match, advance */
6256 restart_detect = stackblock();
6257 STPUTC(*idx, expdest);
6258 if (quotes && (unsigned char)*idx == CTLESC) {
6261 STPUTC(*idx, expdest);
6263 if (stackblock() != restart_detect)
6271 if (subtype == VSREPLACEALL) {
6273 if (quotes && (unsigned char)*idx == CTLESC)
6282 for (loc = repl; *loc; loc++) {
6283 restart_detect = stackblock();
6284 STPUTC(*loc, expdest);
6285 if (stackblock() != restart_detect)
6290 if (subtype == VSREPLACE) {
6292 restart_detect = stackblock();
6293 STPUTC(*idx, expdest);
6294 if (stackblock() != restart_detect)
6303 /* We've put the replaced text into a buffer at workloc, now
6304 * move it to the right place and adjust the stack.
6306 startp = stackblock() + startloc;
6307 STPUTC('\0', expdest);
6308 memmove(startp, stackblock() + workloc, len);
6309 startp[len++] = '\0';
6310 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6311 STADJUST(-amount, expdest);
6314 #endif /* ENABLE_ASH_BASH_COMPAT */
6316 subtype -= VSTRIMRIGHT;
6318 if (subtype < 0 || subtype > 7)
6321 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6322 zero = subtype >> 1;
6323 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6324 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6326 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6329 memmove(startp, loc, str - loc);
6330 loc = startp + (str - loc) - 1;
6333 amount = loc - expdest;
6334 STADJUST(amount, expdest);
6340 * Add the value of a specialized variable to the stack string.
6341 * name parameter (examples):
6342 * ash -c 'echo $1' name:'1='
6343 * ash -c 'echo $qwe' name:'qwe='
6344 * ash -c 'echo $$' name:'$='
6345 * ash -c 'echo ${$}' name:'$='
6346 * ash -c 'echo ${$##q}' name:'$=q'
6347 * ash -c 'echo ${#$}' name:'$='
6348 * note: examples with bad shell syntax:
6349 * ash -c 'echo ${#$1}' name:'$=1'
6350 * ash -c 'echo ${#1#}' name:'1=#'
6352 static NOINLINE ssize_t
6353 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6363 int quoted = varflags & VSQUOTE;
6364 int subtype = varflags & VSTYPE;
6365 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6367 if (quoted && (flags & EXP_FULL))
6368 sep = 1 << CHAR_BIT;
6370 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6379 num = shellparam.nparam;
6387 goto check_1char_name;
6389 expdest = makestrspace(NOPTS, expdest);
6390 for (i = NOPTS - 1; i >= 0; i--) {
6392 USTPUTC(optletters(i), expdest);
6398 /* handles cases similar to ${#$1} */
6399 if (name[2] != '\0')
6400 raise_error_syntax("bad substitution");
6408 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6409 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6415 while ((p = *ap++) != NULL) {
6418 partlen = strlen(p);
6421 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6422 memtodest(p, partlen, syntax, quotes);
6428 if (subtype == VSPLUS || subtype == VSLENGTH) {
6449 num = atoi(name); /* number(name) fails on ${N#str} etc */
6450 if (num < 0 || num > shellparam.nparam)
6452 p = num ? shellparam.p[num - 1] : arg0;
6455 /* NB: name has form "VAR=..." */
6457 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6458 * which should be considered before we check variables. */
6460 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6464 str = var_str_list->text;
6465 eq = strchr(str, '=');
6466 if (!eq) /* stop at first non-assignment */
6469 if (name_len == (unsigned)(eq - str)
6470 && strncmp(str, name, name_len) == 0) {
6472 /* goto value; - WRONG! */
6473 /* think "A=1 A=2 B=$A" */
6475 var_str_list = var_str_list->next;
6476 } while (var_str_list);
6480 p = lookupvar(name);
6486 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6487 memtodest(p, len, syntax, quotes);
6491 if (subtype == VSPLUS || subtype == VSLENGTH)
6492 STADJUST(-len, expdest);
6497 * Expand a variable, and return a pointer to the next character in the
6501 evalvar(char *p, int flags, struct strlist *var_str_list)
6512 varflags = (unsigned char) *p++;
6513 subtype = varflags & VSTYPE;
6514 quoted = varflags & VSQUOTE;
6516 easy = (!quoted || (*var == '@' && shellparam.nparam));
6517 startloc = expdest - (char *)stackblock();
6518 p = strchr(p, '=') + 1;
6521 varlen = varvalue(var, varflags, flags, var_str_list);
6522 if (varflags & VSNUL)
6525 if (subtype == VSPLUS) {
6526 varlen = -1 - varlen;
6530 if (subtype == VSMINUS) {
6534 p, flags | EXP_TILDE |
6535 (quoted ? EXP_QWORD : EXP_WORD),
6545 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6547 if (subevalvar(p, var, /* strloc: */ 0,
6548 subtype, startloc, varflags,
6554 * Remove any recorded regions beyond
6557 removerecordregions(startloc);
6567 if (varlen < 0 && uflag)
6568 varunset(p, var, 0, 0);
6570 if (subtype == VSLENGTH) {
6571 cvtnum(varlen > 0 ? varlen : 0);
6575 if (subtype == VSNORMAL) {
6586 case VSTRIMRIGHTMAX:
6587 #if ENABLE_ASH_BASH_COMPAT
6600 * Terminate the string and start recording the pattern
6603 STPUTC('\0', expdest);
6604 patloc = expdest - (char *)stackblock();
6605 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6607 //TODO: | EXP_REDIR too? All other such places do it too
6608 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6611 int amount = expdest - (
6612 (char *)stackblock() + patloc - 1
6614 STADJUST(-amount, expdest);
6616 /* Remove any recorded regions beyond start of variable */
6617 removerecordregions(startloc);
6619 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6623 if (subtype != VSNORMAL) { /* skip to end of alternative */
6626 unsigned char c = *p++;
6629 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6631 argbackq = argbackq->next;
6632 } else if (c == CTLVAR) {
6633 if ((*p++ & VSTYPE) != VSNORMAL)
6635 } else if (c == CTLENDVAR) {
6645 * Break the argument string into pieces based upon IFS and add the
6646 * strings to the argument list. The regions of the string to be
6647 * searched for IFS characters have been stored by recordregion.
6650 ifsbreakup(char *string, struct arglist *arglist)
6652 struct ifsregion *ifsp;
6657 const char *ifs, *realifs;
6662 if (ifslastp != NULL) {
6665 realifs = ifsset() ? ifsval() : defifs;
6668 p = string + ifsp->begoff;
6669 nulonly = ifsp->nulonly;
6670 ifs = nulonly ? nullstr : realifs;
6672 while (p < string + ifsp->endoff) {
6674 if ((unsigned char)*p == CTLESC)
6676 if (!strchr(ifs, *p)) {
6681 ifsspc = (strchr(defifs, *p) != NULL);
6682 /* Ignore IFS whitespace at start */
6683 if (q == start && ifsspc) {
6689 sp = stzalloc(sizeof(*sp));
6691 *arglist->lastp = sp;
6692 arglist->lastp = &sp->next;
6696 if (p >= string + ifsp->endoff) {
6700 if ((unsigned char)*p == CTLESC)
6702 if (strchr(ifs, *p) == NULL) {
6706 if (strchr(defifs, *p) == NULL) {
6721 } while (ifsp != NULL);
6730 sp = stzalloc(sizeof(*sp));
6732 *arglist->lastp = sp;
6733 arglist->lastp = &sp->next;
6739 struct ifsregion *p;
6744 struct ifsregion *ifsp;
6750 ifsfirst.next = NULL;
6755 * Add a file name to the list.
6758 addfname(const char *name)
6762 sp = stzalloc(sizeof(*sp));
6763 sp->text = ststrdup(name);
6765 exparg.lastp = &sp->next;
6768 static char *expdir;
6771 * Do metacharacter (i.e. *, ?, [...]) expansion.
6774 expmeta(char *enddir, char *name)
6789 for (p = name; *p; p++) {
6790 if (*p == '*' || *p == '?')
6792 else if (*p == '[') {
6799 if (*q == '/' || *q == '\0')
6806 } else if (*p == '\\')
6808 else if (*p == '/') {
6815 if (metaflag == 0) { /* we've reached the end of the file name */
6816 if (enddir != expdir)
6824 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6835 } while (p < start);
6837 if (enddir == expdir) {
6839 } else if (enddir == expdir + 1 && *expdir == '/') {
6848 if (enddir != expdir)
6850 if (*endname == 0) {
6862 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6863 if (dp->d_name[0] == '.' && !matchdot)
6865 if (pmatch(start, dp->d_name)) {
6867 strcpy(enddir, dp->d_name);
6870 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6873 expmeta(p, endname);
6882 static struct strlist *
6883 msort(struct strlist *list, int len)
6885 struct strlist *p, *q = NULL;
6886 struct strlist **lpp;
6894 for (n = half; --n >= 0;) {
6898 q->next = NULL; /* terminate first half of list */
6899 q = msort(list, half); /* sort first half of list */
6900 p = msort(p, len - half); /* sort second half */
6903 #if ENABLE_LOCALE_SUPPORT
6904 if (strcoll(p->text, q->text) < 0)
6906 if (strcmp(p->text, q->text) < 0)
6930 * Sort the results of file name expansion. It calculates the number of
6931 * strings to sort and then calls msort (short for merge sort) to do the
6934 static struct strlist *
6935 expsort(struct strlist *str)
6941 for (sp = str; sp; sp = sp->next)
6943 return msort(str, len);
6947 expandmeta(struct strlist *str /*, int flag*/)
6949 static const char metachars[] ALIGN1 = {
6952 /* TODO - EXP_REDIR */
6955 struct strlist **savelastp;
6961 if (!strpbrk(str->text, metachars))
6963 savelastp = exparg.lastp;
6966 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6968 int i = strlen(str->text);
6969 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6977 if (exparg.lastp == savelastp) {
6982 *exparg.lastp = str;
6983 rmescapes(str->text, 0);
6984 exparg.lastp = &str->next;
6986 *exparg.lastp = NULL;
6987 *savelastp = sp = expsort(*savelastp);
6988 while (sp->next != NULL)
6990 exparg.lastp = &sp->next;
6997 * Perform variable substitution and command substitution on an argument,
6998 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6999 * perform splitting and file name expansion. When arglist is NULL, perform
7000 * here document expansion.
7003 expandarg(union node *arg, struct arglist *arglist, int flag)
7008 argbackq = arg->narg.backquote;
7009 STARTSTACKSTR(expdest);
7010 ifsfirst.next = NULL;
7012 argstr(arg->narg.text, flag,
7013 /* var_str_list: */ arglist ? arglist->list : NULL);
7014 p = _STPUTC('\0', expdest);
7016 if (arglist == NULL) {
7017 return; /* here document expanded */
7019 p = grabstackstr(p);
7020 exparg.lastp = &exparg.list;
7024 if (flag & EXP_FULL) {
7025 ifsbreakup(p, &exparg);
7026 *exparg.lastp = NULL;
7027 exparg.lastp = &exparg.list;
7028 expandmeta(exparg.list /*, flag*/);
7030 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7032 sp = stzalloc(sizeof(*sp));
7035 exparg.lastp = &sp->next;
7039 *exparg.lastp = NULL;
7041 *arglist->lastp = exparg.list;
7042 arglist->lastp = exparg.lastp;
7047 * Expand shell variables and backquotes inside a here document.
7050 expandhere(union node *arg, int fd)
7053 expandarg(arg, (struct arglist *)NULL, 0);
7054 full_write(fd, stackblock(), expdest - (char *)stackblock());
7058 * Returns true if the pattern matches the string.
7061 patmatch(char *pattern, const char *string)
7063 return pmatch(preglob(pattern, 0, 0), string);
7067 * See if a pattern matches in a case statement.
7070 casematch(union node *pattern, char *val)
7072 struct stackmark smark;
7075 setstackmark(&smark);
7076 argbackq = pattern->narg.backquote;
7077 STARTSTACKSTR(expdest);
7079 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7080 /* var_str_list: */ NULL);
7081 STACKSTRNUL(expdest);
7082 result = patmatch(stackblock(), val);
7083 popstackmark(&smark);
7088 /* ============ find_command */
7092 int (*builtin)(int, char **) FAST_FUNC;
7093 /* unsigned flags; */
7095 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7096 /* "regular" builtins always take precedence over commands,
7097 * regardless of PATH=....%builtin... position */
7098 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7099 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7102 smallint cmdtype; /* CMDxxx */
7105 /* index >= 0 for commands without path (slashes) */
7106 /* (TODO: what exactly does the value mean? PATH position?) */
7107 /* index == -1 for commands with slashes */
7108 /* index == (-2 - applet_no) for NOFORK applets */
7109 const struct builtincmd *cmd;
7110 struct funcnode *func;
7113 /* values of cmdtype */
7114 #define CMDUNKNOWN -1 /* no entry in table for command */
7115 #define CMDNORMAL 0 /* command is an executable program */
7116 #define CMDFUNCTION 1 /* command is a shell function */
7117 #define CMDBUILTIN 2 /* command is a shell builtin */
7119 /* action to find_command() */
7120 #define DO_ERR 0x01 /* prints errors */
7121 #define DO_ABS 0x02 /* checks absolute paths */
7122 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7123 #define DO_ALTPATH 0x08 /* using alternate path */
7124 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7126 static void find_command(char *, struct cmdentry *, int, const char *);
7129 /* ============ Hashing commands */
7132 * When commands are first encountered, they are entered in a hash table.
7133 * This ensures that a full path search will not have to be done for them
7134 * on each invocation.
7136 * We should investigate converting to a linear search, even though that
7137 * would make the command name "hash" a misnomer.
7141 struct tblentry *next; /* next entry in hash chain */
7142 union param param; /* definition of builtin function */
7143 smallint cmdtype; /* CMDxxx */
7144 char rehash; /* if set, cd done since entry created */
7145 char cmdname[1]; /* name of command */
7148 static struct tblentry **cmdtable;
7149 #define INIT_G_cmdtable() do { \
7150 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7153 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7157 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7161 #if ENABLE_FEATURE_SH_STANDALONE
7162 if (applet_no >= 0) {
7163 if (APPLET_IS_NOEXEC(applet_no)) {
7166 run_applet_no_and_exit(applet_no, argv);
7168 /* re-exec ourselves with the new arguments */
7169 execve(bb_busybox_exec_path, argv, envp);
7170 /* If they called chroot or otherwise made the binary no longer
7171 * executable, fall through */
7178 execve(cmd, argv, envp);
7179 } while (errno == EINTR);
7181 execve(cmd, argv, envp);
7187 if (errno == ENOEXEC) {
7191 for (ap = argv; *ap; ap++)
7193 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7195 ap[0] = cmd = (char *)DEFAULT_SHELL;
7198 while ((*ap++ = *argv++) != NULL)
7207 * Exec a program. Never returns. If you change this routine, you may
7208 * have to change the find_command routine as well.
7210 static void shellexec(char **, const char *, int) NORETURN;
7212 shellexec(char **argv, const char *path, int idx)
7218 #if ENABLE_FEATURE_SH_STANDALONE
7222 clearredir(/*drop:*/ 1);
7223 envp = listvars(VEXPORT, VUNSET, 0);
7224 if (strchr(argv[0], '/') != NULL
7225 #if ENABLE_FEATURE_SH_STANDALONE
7226 || (applet_no = find_applet_by_name(argv[0])) >= 0
7229 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7233 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7234 if (--idx < 0 && pathopt == NULL) {
7235 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7236 if (errno != ENOENT && errno != ENOTDIR)
7243 /* Map to POSIX errors */
7255 exitstatus = exerrno;
7256 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7257 argv[0], e, suppress_int));
7258 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7263 printentry(struct tblentry *cmdp)
7269 idx = cmdp->param.index;
7272 name = path_advance(&path, cmdp->cmdname);
7274 } while (--idx >= 0);
7275 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7279 * Clear out command entries. The argument specifies the first entry in
7280 * PATH which has changed.
7283 clearcmdentry(int firstchange)
7285 struct tblentry **tblp;
7286 struct tblentry **pp;
7287 struct tblentry *cmdp;
7290 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7292 while ((cmdp = *pp) != NULL) {
7293 if ((cmdp->cmdtype == CMDNORMAL &&
7294 cmdp->param.index >= firstchange)
7295 || (cmdp->cmdtype == CMDBUILTIN &&
7296 builtinloc >= firstchange)
7309 * Locate a command in the command hash table. If "add" is nonzero,
7310 * add the command to the table if it is not already present. The
7311 * variable "lastcmdentry" is set to point to the address of the link
7312 * pointing to the entry, so that delete_cmd_entry can delete the
7315 * Interrupts must be off if called with add != 0.
7317 static struct tblentry **lastcmdentry;
7319 static struct tblentry *
7320 cmdlookup(const char *name, int add)
7322 unsigned int hashval;
7324 struct tblentry *cmdp;
7325 struct tblentry **pp;
7328 hashval = (unsigned char)*p << 4;
7330 hashval += (unsigned char)*p++;
7332 pp = &cmdtable[hashval % CMDTABLESIZE];
7333 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7334 if (strcmp(cmdp->cmdname, name) == 0)
7338 if (add && cmdp == NULL) {
7339 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7341 /* + 1 - already done because
7342 * tblentry::cmdname is char[1] */);
7343 /*cmdp->next = NULL; - ckzalloc did it */
7344 cmdp->cmdtype = CMDUNKNOWN;
7345 strcpy(cmdp->cmdname, name);
7352 * Delete the command entry returned on the last lookup.
7355 delete_cmd_entry(void)
7357 struct tblentry *cmdp;
7360 cmdp = *lastcmdentry;
7361 *lastcmdentry = cmdp->next;
7362 if (cmdp->cmdtype == CMDFUNCTION)
7363 freefunc(cmdp->param.func);
7369 * Add a new command entry, replacing any existing command entry for
7370 * the same name - except special builtins.
7373 addcmdentry(char *name, struct cmdentry *entry)
7375 struct tblentry *cmdp;
7377 cmdp = cmdlookup(name, 1);
7378 if (cmdp->cmdtype == CMDFUNCTION) {
7379 freefunc(cmdp->param.func);
7381 cmdp->cmdtype = entry->cmdtype;
7382 cmdp->param = entry->u;
7386 static int FAST_FUNC
7387 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7389 struct tblentry **pp;
7390 struct tblentry *cmdp;
7392 struct cmdentry entry;
7395 if (nextopt("r") != '\0') {
7400 if (*argptr == NULL) {
7401 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7402 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7403 if (cmdp->cmdtype == CMDNORMAL)
7411 while ((name = *argptr) != NULL) {
7412 cmdp = cmdlookup(name, 0);
7414 && (cmdp->cmdtype == CMDNORMAL
7415 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7419 find_command(name, &entry, DO_ERR, pathval());
7420 if (entry.cmdtype == CMDUNKNOWN)
7428 * Called when a cd is done. Marks all commands so the next time they
7429 * are executed they will be rehashed.
7434 struct tblentry **pp;
7435 struct tblentry *cmdp;
7437 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7438 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7439 if (cmdp->cmdtype == CMDNORMAL
7440 || (cmdp->cmdtype == CMDBUILTIN
7441 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7451 * Fix command hash table when PATH changed.
7452 * Called before PATH is changed. The argument is the new value of PATH;
7453 * pathval() still returns the old value at this point.
7454 * Called with interrupts off.
7456 static void FAST_FUNC
7457 changepath(const char *new)
7465 firstchange = 9999; /* assume no change */
7471 if ((*old == '\0' && *new == ':')
7472 || (*old == ':' && *new == '\0'))
7474 old = new; /* ignore subsequent differences */
7478 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7484 if (builtinloc < 0 && idx_bltin >= 0)
7485 builtinloc = idx_bltin; /* zap builtins */
7486 if (builtinloc >= 0 && idx_bltin < 0)
7488 clearcmdentry(firstchange);
7489 builtinloc = idx_bltin;
7504 #define TENDBQUOTE 12
7521 typedef smallint token_id_t;
7523 /* first char is indicating which tokens mark the end of a list */
7524 static const char *const tokname_array[] = {
7538 #define KWDOFFSET 13
7539 /* the following are keywords */
7561 static char buf[16];
7564 //if (tok < TSEMI) return tokname_array[tok] + 1;
7565 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7570 sprintf(buf + (tok >= TSEMI), "%s%c",
7571 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7575 /* Wrapper around strcmp for qsort/bsearch/... */
7577 pstrcmp(const void *a, const void *b)
7579 return strcmp((char*) a, (*(char**) b) + 1);
7582 static const char *const *
7583 findkwd(const char *s)
7585 return bsearch(s, tokname_array + KWDOFFSET,
7586 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7587 sizeof(tokname_array[0]), pstrcmp);
7591 * Locate and print what a word is...
7594 describe_command(char *command, int describe_command_verbose)
7596 struct cmdentry entry;
7597 struct tblentry *cmdp;
7598 #if ENABLE_ASH_ALIAS
7599 const struct alias *ap;
7601 const char *path = pathval();
7603 if (describe_command_verbose) {
7607 /* First look at the keywords */
7608 if (findkwd(command)) {
7609 out1str(describe_command_verbose ? " is a shell keyword" : command);
7613 #if ENABLE_ASH_ALIAS
7614 /* Then look at the aliases */
7615 ap = lookupalias(command, 0);
7617 if (!describe_command_verbose) {
7622 out1fmt(" is an alias for %s", ap->val);
7626 /* Then check if it is a tracked alias */
7627 cmdp = cmdlookup(command, 0);
7629 entry.cmdtype = cmdp->cmdtype;
7630 entry.u = cmdp->param;
7632 /* Finally use brute force */
7633 find_command(command, &entry, DO_ABS, path);
7636 switch (entry.cmdtype) {
7638 int j = entry.u.index;
7644 p = path_advance(&path, command);
7648 if (describe_command_verbose) {
7650 (cmdp ? " a tracked alias for" : nullstr), p
7659 if (describe_command_verbose) {
7660 out1str(" is a shell function");
7667 if (describe_command_verbose) {
7668 out1fmt(" is a %sshell builtin",
7669 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7670 "special " : nullstr
7678 if (describe_command_verbose) {
7679 out1str(": not found\n");
7684 outstr("\n", stdout);
7688 static int FAST_FUNC
7689 typecmd(int argc UNUSED_PARAM, char **argv)
7695 /* type -p ... ? (we don't bother checking for 'p') */
7696 if (argv[1] && argv[1][0] == '-') {
7701 err |= describe_command(argv[i++], verbose);
7706 #if ENABLE_ASH_CMDCMD
7707 static int FAST_FUNC
7708 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7716 while ((c = nextopt("pvV")) != '\0')
7718 verify |= VERIFY_VERBOSE;
7720 verify |= VERIFY_BRIEF;
7725 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7726 if (verify && (*argptr != NULL)) {
7727 return describe_command(*argptr, verify - VERIFY_BRIEF);
7735 /* ============ eval.c */
7737 static int funcblocksize; /* size of structures in function */
7738 static int funcstringsize; /* size of strings in node */
7739 static void *funcblock; /* block to allocate function from */
7740 static char *funcstring; /* block to allocate strings from */
7742 /* flags in argument to evaltree */
7743 #define EV_EXIT 01 /* exit after evaluating tree */
7744 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7745 #define EV_BACKCMD 04 /* command executing within back quotes */
7747 static const uint8_t nodesize[N_NUMBER] = {
7748 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7749 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7750 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7751 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7752 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7753 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7754 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7755 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7756 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7757 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7758 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7759 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7760 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7761 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7762 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7763 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7764 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7765 #if ENABLE_ASH_BASH_COMPAT
7766 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7768 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7769 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7770 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7771 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7772 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7773 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7774 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7775 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7776 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7779 static void calcsize(union node *n);
7782 sizenodelist(struct nodelist *lp)
7785 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7792 calcsize(union node *n)
7796 funcblocksize += nodesize[n->type];
7799 calcsize(n->ncmd.redirect);
7800 calcsize(n->ncmd.args);
7801 calcsize(n->ncmd.assign);
7804 sizenodelist(n->npipe.cmdlist);
7809 calcsize(n->nredir.redirect);
7810 calcsize(n->nredir.n);
7817 calcsize(n->nbinary.ch2);
7818 calcsize(n->nbinary.ch1);
7821 calcsize(n->nif.elsepart);
7822 calcsize(n->nif.ifpart);
7823 calcsize(n->nif.test);
7826 funcstringsize += strlen(n->nfor.var) + 1;
7827 calcsize(n->nfor.body);
7828 calcsize(n->nfor.args);
7831 calcsize(n->ncase.cases);
7832 calcsize(n->ncase.expr);
7835 calcsize(n->nclist.body);
7836 calcsize(n->nclist.pattern);
7837 calcsize(n->nclist.next);
7841 sizenodelist(n->narg.backquote);
7842 funcstringsize += strlen(n->narg.text) + 1;
7843 calcsize(n->narg.next);
7846 #if ENABLE_ASH_BASH_COMPAT
7853 calcsize(n->nfile.fname);
7854 calcsize(n->nfile.next);
7858 calcsize(n->ndup.vname);
7859 calcsize(n->ndup.next);
7863 calcsize(n->nhere.doc);
7864 calcsize(n->nhere.next);
7867 calcsize(n->nnot.com);
7873 nodeckstrdup(char *s)
7875 char *rtn = funcstring;
7877 strcpy(funcstring, s);
7878 funcstring += strlen(s) + 1;
7882 static union node *copynode(union node *);
7884 static struct nodelist *
7885 copynodelist(struct nodelist *lp)
7887 struct nodelist *start;
7888 struct nodelist **lpp;
7893 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7894 (*lpp)->n = copynode(lp->n);
7896 lpp = &(*lpp)->next;
7903 copynode(union node *n)
7910 funcblock = (char *) funcblock + nodesize[n->type];
7914 new->ncmd.redirect = copynode(n->ncmd.redirect);
7915 new->ncmd.args = copynode(n->ncmd.args);
7916 new->ncmd.assign = copynode(n->ncmd.assign);
7919 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7920 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7925 new->nredir.redirect = copynode(n->nredir.redirect);
7926 new->nredir.n = copynode(n->nredir.n);
7933 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7934 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7937 new->nif.elsepart = copynode(n->nif.elsepart);
7938 new->nif.ifpart = copynode(n->nif.ifpart);
7939 new->nif.test = copynode(n->nif.test);
7942 new->nfor.var = nodeckstrdup(n->nfor.var);
7943 new->nfor.body = copynode(n->nfor.body);
7944 new->nfor.args = copynode(n->nfor.args);
7947 new->ncase.cases = copynode(n->ncase.cases);
7948 new->ncase.expr = copynode(n->ncase.expr);
7951 new->nclist.body = copynode(n->nclist.body);
7952 new->nclist.pattern = copynode(n->nclist.pattern);
7953 new->nclist.next = copynode(n->nclist.next);
7957 new->narg.backquote = copynodelist(n->narg.backquote);
7958 new->narg.text = nodeckstrdup(n->narg.text);
7959 new->narg.next = copynode(n->narg.next);
7962 #if ENABLE_ASH_BASH_COMPAT
7969 new->nfile.fname = copynode(n->nfile.fname);
7970 new->nfile.fd = n->nfile.fd;
7971 new->nfile.next = copynode(n->nfile.next);
7975 new->ndup.vname = copynode(n->ndup.vname);
7976 new->ndup.dupfd = n->ndup.dupfd;
7977 new->ndup.fd = n->ndup.fd;
7978 new->ndup.next = copynode(n->ndup.next);
7982 new->nhere.doc = copynode(n->nhere.doc);
7983 new->nhere.fd = n->nhere.fd;
7984 new->nhere.next = copynode(n->nhere.next);
7987 new->nnot.com = copynode(n->nnot.com);
7990 new->type = n->type;
7995 * Make a copy of a parse tree.
7997 static struct funcnode *
7998 copyfunc(union node *n)
8003 funcblocksize = offsetof(struct funcnode, n);
8006 blocksize = funcblocksize;
8007 f = ckmalloc(blocksize + funcstringsize);
8008 funcblock = (char *) f + offsetof(struct funcnode, n);
8009 funcstring = (char *) f + blocksize;
8016 * Define a shell function.
8019 defun(char *name, union node *func)
8021 struct cmdentry entry;
8024 entry.cmdtype = CMDFUNCTION;
8025 entry.u.func = copyfunc(func);
8026 addcmdentry(name, &entry);
8030 /* Reasons for skipping commands (see comment on breakcmd routine) */
8031 #define SKIPBREAK (1 << 0)
8032 #define SKIPCONT (1 << 1)
8033 #define SKIPFUNC (1 << 2)
8034 #define SKIPFILE (1 << 3)
8035 #define SKIPEVAL (1 << 4)
8036 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8037 static int skipcount; /* number of levels to skip */
8038 static int funcnest; /* depth of function calls */
8039 static int loopnest; /* current loop nesting level */
8041 /* Forward decl way out to parsing code - dotrap needs it */
8042 static int evalstring(char *s, int mask);
8044 /* Called to execute a trap.
8045 * Single callsite - at the end of evaltree().
8046 * If we return non-zero, exaltree raises EXEXIT exception.
8048 * Perhaps we should avoid entering new trap handlers
8049 * while we are executing a trap handler. [is it a TODO?]
8058 savestatus = exitstatus;
8062 TRACE(("dotrap entered\n"));
8063 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8070 /* non-trapped SIGINT is handled separately by raise_interrupt,
8071 * don't upset it by resetting gotsig[SIGINT-1] */
8072 if (sig == SIGINT && !t)
8075 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8079 want_exexit = evalstring(t, SKIPEVAL);
8080 exitstatus = savestatus;
8082 TRACE(("dotrap returns %d\n", want_exexit));
8087 TRACE(("dotrap returns 0\n"));
8091 /* forward declarations - evaluation is fairly recursive business... */
8092 static void evalloop(union node *, int);
8093 static void evalfor(union node *, int);
8094 static void evalcase(union node *, int);
8095 static void evalsubshell(union node *, int);
8096 static void expredir(union node *);
8097 static void evalpipe(union node *, int);
8098 static void evalcommand(union node *, int);
8099 static int evalbltin(const struct builtincmd *, int, char **);
8100 static void prehash(union node *);
8103 * Evaluate a parse tree. The value is left in the global variable
8107 evaltree(union node *n, int flags)
8109 struct jmploc *volatile savehandler = exception_handler;
8110 struct jmploc jmploc;
8112 void (*evalfn)(union node *, int);
8116 SAVE_INT(int_level);
8119 TRACE(("evaltree(NULL) called\n"));
8122 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8124 exception_handler = &jmploc;
8126 int err = setjmp(jmploc.loc);
8128 /* if it was a signal, check for trap handlers */
8129 if (exception_type == EXSIG) {
8130 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8131 exception_type, err));
8134 /* continue on the way out */
8135 TRACE(("exception %d in evaltree, propagating err=%d\n",
8136 exception_type, err));
8137 exception_handler = savehandler;
8138 longjmp(exception_handler->loc, err);
8145 out1fmt("Node type = %d\n", n->type);
8150 evaltree(n->nnot.com, EV_TESTED);
8151 status = !exitstatus;
8154 expredir(n->nredir.redirect);
8155 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8157 evaltree(n->nredir.n, flags & EV_TESTED);
8158 status = exitstatus;
8160 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8163 evalfn = evalcommand;
8165 if (eflag && !(flags & EV_TESTED))
8177 evalfn = evalsubshell;
8190 #error NAND + 1 != NOR
8192 #if NOR + 1 != NSEMI
8193 #error NOR + 1 != NSEMI
8195 unsigned is_or = n->type - NAND;
8198 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8200 if (!exitstatus == is_or)
8213 evaltree(n->nif.test, EV_TESTED);
8216 if (exitstatus == 0) {
8220 if (n->nif.elsepart) {
8221 n = n->nif.elsepart;
8226 defun(n->narg.text, n->narg.next);
8230 exitstatus = status;
8235 exception_handler = savehandler;
8237 if (checkexit & exitstatus)
8238 evalskip |= SKIPEVAL;
8239 else if (pending_sig && dotrap())
8242 if (flags & EV_EXIT) {
8244 raise_exception(EXEXIT);
8247 RESTORE_INT(int_level);
8248 TRACE(("leaving evaltree (no interrupts)\n"));
8251 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8254 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8257 evalloop(union node *n, int flags)
8267 evaltree(n->nbinary.ch1, EV_TESTED);
8270 if (evalskip == SKIPCONT && --skipcount <= 0) {
8274 if (evalskip == SKIPBREAK && --skipcount <= 0)
8279 if (n->type != NWHILE)
8283 evaltree(n->nbinary.ch2, flags);
8284 status = exitstatus;
8289 exitstatus = status;
8293 evalfor(union node *n, int flags)
8295 struct arglist arglist;
8298 struct stackmark smark;
8300 setstackmark(&smark);
8301 arglist.list = NULL;
8302 arglist.lastp = &arglist.list;
8303 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8304 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8309 *arglist.lastp = NULL;
8314 for (sp = arglist.list; sp; sp = sp->next) {
8315 setvar(n->nfor.var, sp->text, 0);
8316 evaltree(n->nfor.body, flags);
8318 if (evalskip == SKIPCONT && --skipcount <= 0) {
8322 if (evalskip == SKIPBREAK && --skipcount <= 0)
8329 popstackmark(&smark);
8333 evalcase(union node *n, int flags)
8337 struct arglist arglist;
8338 struct stackmark smark;
8340 setstackmark(&smark);
8341 arglist.list = NULL;
8342 arglist.lastp = &arglist.list;
8343 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8345 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8346 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8347 if (casematch(patp, arglist.list->text)) {
8348 if (evalskip == 0) {
8349 evaltree(cp->nclist.body, flags);
8356 popstackmark(&smark);
8360 * Kick off a subshell to evaluate a tree.
8363 evalsubshell(union node *n, int flags)
8366 int backgnd = (n->type == NBACKGND);
8369 expredir(n->nredir.redirect);
8370 if (!backgnd && flags & EV_EXIT && !trap[0])
8373 jp = makejob(/*n,*/ 1);
8374 if (forkshell(jp, n, backgnd) == 0) {
8378 flags &=~ EV_TESTED;
8380 redirect(n->nredir.redirect, 0);
8381 evaltreenr(n->nredir.n, flags);
8386 status = waitforjob(jp);
8387 exitstatus = status;
8392 * Compute the names of the files in a redirection list.
8394 static void fixredir(union node *, const char *, int);
8396 expredir(union node *n)
8400 for (redir = n; redir; redir = redir->nfile.next) {
8404 fn.lastp = &fn.list;
8405 switch (redir->type) {
8409 #if ENABLE_ASH_BASH_COMPAT
8414 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8415 #if ENABLE_ASH_BASH_COMPAT
8418 redir->nfile.expfname = fn.list->text;
8421 case NTOFD: /* >& */
8422 if (redir->ndup.vname) {
8423 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8424 if (fn.list == NULL)
8425 ash_msg_and_raise_error("redir error");
8426 #if ENABLE_ASH_BASH_COMPAT
8427 //FIXME: we used expandarg with different args!
8428 if (!isdigit_str9(fn.list->text)) {
8429 /* >&file, not >&fd */
8430 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8431 ash_msg_and_raise_error("redir error");
8433 goto store_expfname;
8436 fixredir(redir, fn.list->text, 1);
8444 * Evaluate a pipeline. All the processes in the pipeline are children
8445 * of the process creating the pipeline. (This differs from some versions
8446 * of the shell, which make the last process in a pipeline the parent
8450 evalpipe(union node *n, int flags)
8453 struct nodelist *lp;
8458 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8460 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8464 jp = makejob(/*n,*/ pipelen);
8466 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8470 if (pipe(pip) < 0) {
8472 ash_msg_and_raise_error("pipe call failed");
8475 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8488 evaltreenr(lp->n, flags);
8494 /* Don't want to trigger debugging */
8498 if (n->npipe.pipe_backgnd == 0) {
8499 exitstatus = waitforjob(jp);
8500 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8506 * Controls whether the shell is interactive or not.
8509 setinteractive(int on)
8511 static smallint is_interactive;
8513 if (++on == is_interactive)
8515 is_interactive = on;
8519 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8520 if (is_interactive > 1) {
8521 /* Looks like they want an interactive shell */
8522 static smallint did_banner;
8525 /* note: ash and hush share this string */
8526 out1fmt("\n\n%s %s\n"
8527 "Enter 'help' for a list of built-in commands."
8530 "built-in shell (ash)"
8544 setinteractive(iflag);
8546 #if ENABLE_FEATURE_EDITING_VI
8548 line_input_state->flags |= VI_MODE;
8550 line_input_state->flags &= ~VI_MODE;
8552 viflag = 0; /* forcibly keep the option off */
8556 static struct localvar *localvars;
8559 * Called after a function returns.
8560 * Interrupts must be off.
8565 struct localvar *lvp;
8568 while ((lvp = localvars) != NULL) {
8569 localvars = lvp->next;
8571 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8572 if (vp == NULL) { /* $- saved */
8573 memcpy(optlist, lvp->text, sizeof(optlist));
8574 free((char*)lvp->text);
8576 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8580 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8581 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8582 free((char*)vp->text);
8583 vp->flags = lvp->flags;
8584 vp->text = lvp->text;
8591 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8593 volatile struct shparam saveparam;
8594 struct localvar *volatile savelocalvars;
8595 struct jmploc *volatile savehandler;
8596 struct jmploc jmploc;
8599 saveparam = shellparam;
8600 savelocalvars = localvars;
8601 e = setjmp(jmploc.loc);
8606 savehandler = exception_handler;
8607 exception_handler = &jmploc;
8609 shellparam.malloced = 0;
8613 shellparam.nparam = argc - 1;
8614 shellparam.p = argv + 1;
8615 #if ENABLE_ASH_GETOPTS
8616 shellparam.optind = 1;
8617 shellparam.optoff = -1;
8619 evaltree(&func->n, flags & EV_TESTED);
8625 localvars = savelocalvars;
8626 freeparam(&shellparam);
8627 shellparam = saveparam;
8628 exception_handler = savehandler;
8630 evalskip &= ~SKIPFUNC;
8634 #if ENABLE_ASH_CMDCMD
8636 parse_command_args(char **argv, const char **path)
8649 if (c == '-' && !*cp) {
8656 *path = bb_default_path;
8659 /* run 'typecmd' for other options */
8670 * Make a variable a local variable. When a variable is made local, it's
8671 * value and flags are saved in a localvar structure. The saved values
8672 * will be restored when the shell function returns. We handle the name
8673 * "-" as a special case.
8678 struct localvar *lvp;
8683 lvp = ckzalloc(sizeof(struct localvar));
8684 if (LONE_DASH(name)) {
8686 p = ckmalloc(sizeof(optlist));
8687 lvp->text = memcpy(p, optlist, sizeof(optlist));
8692 vpp = hashvar(name);
8693 vp = *findvar(vpp, name);
8694 eq = strchr(name, '=');
8697 setvareq(name, VSTRFIXED);
8699 setvar(name, NULL, VSTRFIXED);
8700 vp = *vpp; /* the new variable */
8701 lvp->flags = VUNSET;
8703 lvp->text = vp->text;
8704 lvp->flags = vp->flags;
8705 vp->flags |= VSTRFIXED|VTEXTFIXED;
8711 lvp->next = localvars;
8717 * The "local" command.
8719 static int FAST_FUNC
8720 localcmd(int argc UNUSED_PARAM, char **argv)
8725 while ((name = *argv++) != NULL) {
8731 static int FAST_FUNC
8732 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8737 static int FAST_FUNC
8738 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8743 static int FAST_FUNC
8744 execcmd(int argc UNUSED_PARAM, char **argv)
8747 iflag = 0; /* exit on error */
8750 shellexec(argv + 1, pathval(), 0);
8756 * The return command.
8758 static int FAST_FUNC
8759 returncmd(int argc UNUSED_PARAM, char **argv)
8762 * If called outside a function, do what ksh does;
8763 * skip the rest of the file.
8765 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8766 return argv[1] ? number(argv[1]) : exitstatus;
8769 /* Forward declarations for builtintab[] */
8770 static int breakcmd(int, char **) FAST_FUNC;
8771 static int dotcmd(int, char **) FAST_FUNC;
8772 static int evalcmd(int, char **) FAST_FUNC;
8773 static int exitcmd(int, char **) FAST_FUNC;
8774 static int exportcmd(int, char **) FAST_FUNC;
8775 #if ENABLE_ASH_GETOPTS
8776 static int getoptscmd(int, char **) FAST_FUNC;
8778 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8779 static int helpcmd(int, char **) FAST_FUNC;
8781 #if ENABLE_SH_MATH_SUPPORT
8782 static int letcmd(int, char **) FAST_FUNC;
8784 static int readcmd(int, char **) FAST_FUNC;
8785 static int setcmd(int, char **) FAST_FUNC;
8786 static int shiftcmd(int, char **) FAST_FUNC;
8787 static int timescmd(int, char **) FAST_FUNC;
8788 static int trapcmd(int, char **) FAST_FUNC;
8789 static int umaskcmd(int, char **) FAST_FUNC;
8790 static int unsetcmd(int, char **) FAST_FUNC;
8791 static int ulimitcmd(int, char **) FAST_FUNC;
8793 #define BUILTIN_NOSPEC "0"
8794 #define BUILTIN_SPECIAL "1"
8795 #define BUILTIN_REGULAR "2"
8796 #define BUILTIN_SPEC_REG "3"
8797 #define BUILTIN_ASSIGN "4"
8798 #define BUILTIN_SPEC_ASSG "5"
8799 #define BUILTIN_REG_ASSG "6"
8800 #define BUILTIN_SPEC_REG_ASSG "7"
8802 /* Stubs for calling non-FAST_FUNC's */
8803 #if ENABLE_ASH_BUILTIN_ECHO
8804 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8806 #if ENABLE_ASH_BUILTIN_PRINTF
8807 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8809 #if ENABLE_ASH_BUILTIN_TEST
8810 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8813 /* Keep these in proper order since it is searched via bsearch() */
8814 static const struct builtincmd builtintab[] = {
8815 { BUILTIN_SPEC_REG ".", dotcmd },
8816 { BUILTIN_SPEC_REG ":", truecmd },
8817 #if ENABLE_ASH_BUILTIN_TEST
8818 { BUILTIN_REGULAR "[", testcmd },
8819 #if ENABLE_ASH_BASH_COMPAT
8820 { BUILTIN_REGULAR "[[", testcmd },
8823 #if ENABLE_ASH_ALIAS
8824 { BUILTIN_REG_ASSG "alias", aliascmd },
8827 { BUILTIN_REGULAR "bg", fg_bgcmd },
8829 { BUILTIN_SPEC_REG "break", breakcmd },
8830 { BUILTIN_REGULAR "cd", cdcmd },
8831 { BUILTIN_NOSPEC "chdir", cdcmd },
8832 #if ENABLE_ASH_CMDCMD
8833 { BUILTIN_REGULAR "command", commandcmd },
8835 { BUILTIN_SPEC_REG "continue", breakcmd },
8836 #if ENABLE_ASH_BUILTIN_ECHO
8837 { BUILTIN_REGULAR "echo", echocmd },
8839 { BUILTIN_SPEC_REG "eval", evalcmd },
8840 { BUILTIN_SPEC_REG "exec", execcmd },
8841 { BUILTIN_SPEC_REG "exit", exitcmd },
8842 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8843 { BUILTIN_REGULAR "false", falsecmd },
8845 { BUILTIN_REGULAR "fg", fg_bgcmd },
8847 #if ENABLE_ASH_GETOPTS
8848 { BUILTIN_REGULAR "getopts", getoptscmd },
8850 { BUILTIN_NOSPEC "hash", hashcmd },
8851 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8852 { BUILTIN_NOSPEC "help", helpcmd },
8855 { BUILTIN_REGULAR "jobs", jobscmd },
8856 { BUILTIN_REGULAR "kill", killcmd },
8858 #if ENABLE_SH_MATH_SUPPORT
8859 { BUILTIN_NOSPEC "let", letcmd },
8861 { BUILTIN_ASSIGN "local", localcmd },
8862 #if ENABLE_ASH_BUILTIN_PRINTF
8863 { BUILTIN_REGULAR "printf", printfcmd },
8865 { BUILTIN_NOSPEC "pwd", pwdcmd },
8866 { BUILTIN_REGULAR "read", readcmd },
8867 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8868 { BUILTIN_SPEC_REG "return", returncmd },
8869 { BUILTIN_SPEC_REG "set", setcmd },
8870 { BUILTIN_SPEC_REG "shift", shiftcmd },
8871 { BUILTIN_SPEC_REG "source", dotcmd },
8872 #if ENABLE_ASH_BUILTIN_TEST
8873 { BUILTIN_REGULAR "test", testcmd },
8875 { BUILTIN_SPEC_REG "times", timescmd },
8876 { BUILTIN_SPEC_REG "trap", trapcmd },
8877 { BUILTIN_REGULAR "true", truecmd },
8878 { BUILTIN_NOSPEC "type", typecmd },
8879 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8880 { BUILTIN_REGULAR "umask", umaskcmd },
8881 #if ENABLE_ASH_ALIAS
8882 { BUILTIN_REGULAR "unalias", unaliascmd },
8884 { BUILTIN_SPEC_REG "unset", unsetcmd },
8885 { BUILTIN_REGULAR "wait", waitcmd },
8888 /* Should match the above table! */
8889 #define COMMANDCMD (builtintab + \
8891 1 * ENABLE_ASH_BUILTIN_TEST + \
8892 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8893 1 * ENABLE_ASH_ALIAS + \
8894 1 * ENABLE_ASH_JOB_CONTROL + \
8896 #define EXECCMD (builtintab + \
8898 1 * ENABLE_ASH_BUILTIN_TEST + \
8899 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8900 1 * ENABLE_ASH_ALIAS + \
8901 1 * ENABLE_ASH_JOB_CONTROL + \
8903 1 * ENABLE_ASH_CMDCMD + \
8905 ENABLE_ASH_BUILTIN_ECHO + \
8909 * Search the table of builtin commands.
8911 static struct builtincmd *
8912 find_builtin(const char *name)
8914 struct builtincmd *bp;
8917 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8924 * Execute a simple command.
8927 isassignment(const char *p)
8929 const char *q = endofname(p);
8934 static int FAST_FUNC
8935 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8937 /* Preserve exitstatus of a previous possible redirection
8938 * as POSIX mandates */
8939 return back_exitstatus;
8942 evalcommand(union node *cmd, int flags)
8944 static const struct builtincmd null_bltin = {
8945 "\0\0", bltincmd /* why three NULs? */
8947 struct stackmark smark;
8949 struct arglist arglist;
8950 struct arglist varlist;
8953 const struct strlist *sp;
8954 struct cmdentry cmdentry;
8961 struct builtincmd *bcmd;
8962 smallint cmd_is_exec;
8963 smallint pseudovarflag = 0;
8965 /* First expand the arguments. */
8966 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8967 setstackmark(&smark);
8968 back_exitstatus = 0;
8970 cmdentry.cmdtype = CMDBUILTIN;
8971 cmdentry.u.cmd = &null_bltin;
8972 varlist.lastp = &varlist.list;
8973 *varlist.lastp = NULL;
8974 arglist.lastp = &arglist.list;
8975 *arglist.lastp = NULL;
8978 if (cmd->ncmd.args) {
8979 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8980 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8983 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8984 struct strlist **spp;
8986 spp = arglist.lastp;
8987 if (pseudovarflag && isassignment(argp->narg.text))
8988 expandarg(argp, &arglist, EXP_VARTILDE);
8990 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8992 for (sp = *spp; sp; sp = sp->next)
8996 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8997 for (sp = arglist.list; sp; sp = sp->next) {
8998 TRACE(("evalcommand arg: %s\n", sp->text));
8999 *nargv++ = sp->text;
9004 if (iflag && funcnest == 0 && argc > 0)
9005 lastarg = nargv[-1];
9008 expredir(cmd->ncmd.redirect);
9009 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9012 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9013 struct strlist **spp;
9016 spp = varlist.lastp;
9017 expandarg(argp, &varlist, EXP_VARTILDE);
9020 * Modify the command lookup path, if a PATH= assignment
9024 if (varequal(p, path))
9028 /* Print the command if xflag is set. */
9031 const char *p = " %s";
9034 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9037 for (n = 0; n < 2; n++) {
9039 fdprintf(preverrout_fd, p, sp->text);
9047 safe_write(preverrout_fd, "\n", 1);
9053 /* Now locate the command. */
9055 const char *oldpath;
9056 int cmd_flag = DO_ERR;
9061 find_command(argv[0], &cmdentry, cmd_flag, path);
9062 if (cmdentry.cmdtype == CMDUNKNOWN) {
9063 flush_stdout_stderr();
9068 /* implement bltin and command here */
9069 if (cmdentry.cmdtype != CMDBUILTIN)
9072 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9073 if (cmdentry.u.cmd == EXECCMD)
9075 #if ENABLE_ASH_CMDCMD
9076 if (cmdentry.u.cmd == COMMANDCMD) {
9078 nargv = parse_command_args(argv, &path);
9081 argc -= nargv - argv;
9083 cmd_flag |= DO_NOFUNC;
9091 /* We have a redirection error. */
9093 raise_exception(EXERROR);
9095 exitstatus = status;
9099 /* Execute the command. */
9100 switch (cmdentry.cmdtype) {
9103 #if ENABLE_FEATURE_SH_NOFORK
9104 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9105 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9107 /* find_command() encodes applet_no as (-2 - applet_no) */
9108 int applet_no = (- cmdentry.u.index - 2);
9109 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9110 listsetvar(varlist.list, VEXPORT|VSTACK);
9111 /* run <applet>_main() */
9112 exitstatus = run_nofork_applet(applet_no, argv);
9117 /* Fork off a child process if necessary. */
9118 if (!(flags & EV_EXIT) || trap[0]) {
9120 jp = makejob(/*cmd,*/ 1);
9121 if (forkshell(jp, cmd, FORK_FG) != 0) {
9122 exitstatus = waitforjob(jp);
9124 TRACE(("forked child exited with %d\n", exitstatus));
9129 listsetvar(varlist.list, VEXPORT|VSTACK);
9130 shellexec(argv, path, cmdentry.u.index);
9134 cmdenviron = varlist.list;
9136 struct strlist *list = cmdenviron;
9138 if (spclbltin > 0 || argc == 0) {
9140 if (cmd_is_exec && argc > 1)
9143 listsetvar(list, i);
9145 /* Tight loop with builtins only:
9146 * "while kill -0 $child; do true; done"
9147 * will never exit even if $child died, unless we do this
9148 * to reap the zombie and make kill detect that it's gone: */
9149 dowait(DOWAIT_NONBLOCK, NULL);
9151 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9153 int i = exception_type;
9158 exit_status = 128 + SIGINT;
9160 exit_status = 128 + pending_sig;
9161 exitstatus = exit_status;
9162 if (i == EXINT || spclbltin > 0) {
9164 longjmp(exception_handler->loc, 1);
9171 listsetvar(varlist.list, 0);
9172 /* See above for the rationale */
9173 dowait(DOWAIT_NONBLOCK, NULL);
9174 if (evalfun(cmdentry.u.func, argc, argv, flags))
9180 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9182 /* dsl: I think this is intended to be used to support
9183 * '_' in 'vi' command mode during line editing...
9184 * However I implemented that within libedit itself.
9186 setvar("_", lastarg, 0);
9188 popstackmark(&smark);
9192 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9194 char *volatile savecmdname;
9195 struct jmploc *volatile savehandler;
9196 struct jmploc jmploc;
9199 savecmdname = commandname;
9200 i = setjmp(jmploc.loc);
9203 savehandler = exception_handler;
9204 exception_handler = &jmploc;
9205 commandname = argv[0];
9207 optptr = NULL; /* initialize nextopt */
9208 exitstatus = (*cmd->builtin)(argc, argv);
9209 flush_stdout_stderr();
9211 exitstatus |= ferror(stdout);
9213 commandname = savecmdname;
9214 exception_handler = savehandler;
9220 goodname(const char *p)
9222 return !*endofname(p);
9227 * Search for a command. This is called before we fork so that the
9228 * location of the command will be available in the parent as well as
9229 * the child. The check for "goodname" is an overly conservative
9230 * check that the name will not be subject to expansion.
9233 prehash(union node *n)
9235 struct cmdentry entry;
9237 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9238 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9242 /* ============ Builtin commands
9244 * Builtin commands whose functions are closely tied to evaluation
9245 * are implemented here.
9249 * Handle break and continue commands. Break, continue, and return are
9250 * all handled by setting the evalskip flag. The evaluation routines
9251 * above all check this flag, and if it is set they start skipping
9252 * commands rather than executing them. The variable skipcount is
9253 * the number of loops to break/continue, or the number of function
9254 * levels to return. (The latter is always 1.) It should probably
9255 * be an error to break out of more loops than exist, but it isn't
9256 * in the standard shell so we don't make it one here.
9258 static int FAST_FUNC
9259 breakcmd(int argc UNUSED_PARAM, char **argv)
9261 int n = argv[1] ? number(argv[1]) : 1;
9264 ash_msg_and_raise_error(msg_illnum, argv[1]);
9268 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9275 /* ============ input.c
9277 * This implements the input routines used by the parser.
9281 INPUT_PUSH_FILE = 1,
9282 INPUT_NOFILE_OK = 2,
9285 static smallint checkkwd;
9286 /* values of checkkwd variable */
9287 #define CHKALIAS 0x1
9292 * Push a string back onto the input at this current parsefile level.
9293 * We handle aliases this way.
9295 #if !ENABLE_ASH_ALIAS
9296 #define pushstring(s, ap) pushstring(s)
9299 pushstring(char *s, struct alias *ap)
9306 if (g_parsefile->strpush) {
9307 sp = ckzalloc(sizeof(*sp));
9308 sp->prev = g_parsefile->strpush;
9310 sp = &(g_parsefile->basestrpush);
9312 g_parsefile->strpush = sp;
9313 sp->prev_string = g_parsefile->next_to_pgetc;
9314 sp->prev_left_in_line = g_parsefile->left_in_line;
9315 #if ENABLE_ASH_ALIAS
9318 ap->flag |= ALIASINUSE;
9322 g_parsefile->next_to_pgetc = s;
9323 g_parsefile->left_in_line = len;
9330 struct strpush *sp = g_parsefile->strpush;
9333 #if ENABLE_ASH_ALIAS
9335 if (g_parsefile->next_to_pgetc[-1] == ' '
9336 || g_parsefile->next_to_pgetc[-1] == '\t'
9338 checkkwd |= CHKALIAS;
9340 if (sp->string != sp->ap->val) {
9343 sp->ap->flag &= ~ALIASINUSE;
9344 if (sp->ap->flag & ALIASDEAD) {
9345 unalias(sp->ap->name);
9349 g_parsefile->next_to_pgetc = sp->prev_string;
9350 g_parsefile->left_in_line = sp->prev_left_in_line;
9351 g_parsefile->strpush = sp->prev;
9352 if (sp != &(g_parsefile->basestrpush))
9357 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9358 //it peeks whether it is &>, and then pushes back both chars.
9359 //This function needs to save last *next_to_pgetc to buf[0]
9360 //to make two pungetc() reliable. Currently,
9361 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9366 char *buf = g_parsefile->buf;
9368 g_parsefile->next_to_pgetc = buf;
9369 #if ENABLE_FEATURE_EDITING
9371 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9372 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9374 #if ENABLE_FEATURE_TAB_COMPLETION
9375 line_input_state->path_lookup = pathval();
9377 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9379 /* Ctrl+C pressed */
9388 if (nr < 0 && errno == 0) {
9389 /* Ctrl+D pressed */
9394 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9398 /* nonblock_safe_read() handles this problem */
9400 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9401 int flags = fcntl(0, F_GETFL);
9402 if (flags >= 0 && (flags & O_NONBLOCK)) {
9403 flags &= ~O_NONBLOCK;
9404 if (fcntl(0, F_SETFL, flags) >= 0) {
9405 out2str("sh: turning off NDELAY mode\n");
9416 * Refill the input buffer and return the next input character:
9418 * 1) If a string was pushed back on the input, pop it;
9419 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9420 * or we are reading from a string so we can't refill the buffer,
9422 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9423 * 4) Process input up to the next newline, deleting nul characters.
9425 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9426 #define pgetc_debug(...) ((void)0)
9433 while (g_parsefile->strpush) {
9434 #if ENABLE_ASH_ALIAS
9435 if (g_parsefile->left_in_line == -1
9436 && g_parsefile->strpush->ap
9437 && g_parsefile->next_to_pgetc[-1] != ' '
9438 && g_parsefile->next_to_pgetc[-1] != '\t'
9440 pgetc_debug("preadbuffer PEOA");
9445 /* try "pgetc" now: */
9446 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9447 g_parsefile->left_in_line,
9448 g_parsefile->next_to_pgetc,
9449 g_parsefile->next_to_pgetc);
9450 if (--g_parsefile->left_in_line >= 0)
9451 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9453 /* on both branches above g_parsefile->left_in_line < 0.
9454 * "pgetc" needs refilling.
9457 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9458 * pungetc() may increment it a few times.
9459 * Assuming it won't increment it to less than -90.
9461 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9462 pgetc_debug("preadbuffer PEOF1");
9463 /* even in failure keep left_in_line and next_to_pgetc
9464 * in lock step, for correct multi-layer pungetc.
9465 * left_in_line was decremented before preadbuffer(),
9466 * must inc next_to_pgetc: */
9467 g_parsefile->next_to_pgetc++;
9471 more = g_parsefile->left_in_buffer;
9473 flush_stdout_stderr();
9477 /* don't try reading again */
9478 g_parsefile->left_in_line = -99;
9479 pgetc_debug("preadbuffer PEOF2");
9480 g_parsefile->next_to_pgetc++;
9485 /* Find out where's the end of line.
9486 * Set g_parsefile->left_in_line
9487 * and g_parsefile->left_in_buffer acordingly.
9488 * NUL chars are deleted.
9490 q = g_parsefile->next_to_pgetc;
9498 memmove(q, q + 1, more);
9502 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9508 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9509 if (g_parsefile->left_in_line < 0)
9514 g_parsefile->left_in_buffer = more;
9519 out2str(g_parsefile->next_to_pgetc);
9523 pgetc_debug("preadbuffer at %d:%p'%s'",
9524 g_parsefile->left_in_line,
9525 g_parsefile->next_to_pgetc,
9526 g_parsefile->next_to_pgetc);
9527 return (unsigned char)*g_parsefile->next_to_pgetc++;
9530 #define pgetc_as_macro() \
9531 (--g_parsefile->left_in_line >= 0 \
9532 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9539 pgetc_debug("pgetc_fast at %d:%p'%s'",
9540 g_parsefile->left_in_line,
9541 g_parsefile->next_to_pgetc,
9542 g_parsefile->next_to_pgetc);
9543 return pgetc_as_macro();
9546 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9547 #define pgetc_fast() pgetc()
9549 #define pgetc_fast() pgetc_as_macro()
9553 * Same as pgetc(), but ignores PEOA.
9555 #if ENABLE_ASH_ALIAS
9561 pgetc_debug("pgetc_fast at %d:%p'%s'",
9562 g_parsefile->left_in_line,
9563 g_parsefile->next_to_pgetc,
9564 g_parsefile->next_to_pgetc);
9566 } while (c == PEOA);
9570 #define pgetc2() pgetc()
9574 * Read a line from the script.
9577 pfgets(char *line, int len)
9583 while (--nleft > 0) {
9599 * Undo the last call to pgetc. Only one character may be pushed back.
9600 * PEOF may be pushed back.
9605 g_parsefile->left_in_line++;
9606 g_parsefile->next_to_pgetc--;
9607 pgetc_debug("pushed back to %d:%p'%s'",
9608 g_parsefile->left_in_line,
9609 g_parsefile->next_to_pgetc,
9610 g_parsefile->next_to_pgetc);
9614 * To handle the "." command, a stack of input files is used. Pushfile
9615 * adds a new entry to the stack and popfile restores the previous level.
9620 struct parsefile *pf;
9622 pf = ckzalloc(sizeof(*pf));
9623 pf->prev = g_parsefile;
9625 /*pf->strpush = NULL; - ckzalloc did it */
9626 /*pf->basestrpush.prev = NULL;*/
9633 struct parsefile *pf = g_parsefile;
9641 g_parsefile = pf->prev;
9647 * Return to top level.
9652 while (g_parsefile != &basepf)
9657 * Close the file(s) that the shell is reading commands from. Called
9658 * after a fork is done.
9664 if (g_parsefile->fd > 0) {
9665 close(g_parsefile->fd);
9666 g_parsefile->fd = 0;
9671 * Like setinputfile, but takes an open file descriptor. Call this with
9675 setinputfd(int fd, int push)
9677 close_on_exec_on(fd);
9680 g_parsefile->buf = NULL;
9682 g_parsefile->fd = fd;
9683 if (g_parsefile->buf == NULL)
9684 g_parsefile->buf = ckmalloc(IBUFSIZ);
9685 g_parsefile->left_in_buffer = 0;
9686 g_parsefile->left_in_line = 0;
9687 g_parsefile->linno = 1;
9691 * Set the input to take input from a file. If push is set, push the
9692 * old input onto the stack first.
9695 setinputfile(const char *fname, int flags)
9701 fd = open(fname, O_RDONLY);
9703 if (flags & INPUT_NOFILE_OK)
9705 ash_msg_and_raise_error("can't open '%s'", fname);
9708 fd2 = copyfd(fd, 10);
9711 ash_msg_and_raise_error("out of file descriptors");
9714 setinputfd(fd, flags & INPUT_PUSH_FILE);
9721 * Like setinputfile, but takes input from a string.
9724 setinputstring(char *string)
9728 g_parsefile->next_to_pgetc = string;
9729 g_parsefile->left_in_line = strlen(string);
9730 g_parsefile->buf = NULL;
9731 g_parsefile->linno = 1;
9736 /* ============ mail.c
9738 * Routines to check for mail.
9743 #define MAXMBOXES 10
9745 /* times of mailboxes */
9746 static time_t mailtime[MAXMBOXES];
9747 /* Set if MAIL or MAILPATH is changed. */
9748 static smallint mail_var_path_changed;
9751 * Print appropriate message(s) if mail has arrived.
9752 * If mail_var_path_changed is set,
9753 * then the value of MAIL has mail_var_path_changed,
9754 * so we just update the values.
9763 struct stackmark smark;
9766 setstackmark(&smark);
9767 mpath = mpathset() ? mpathval() : mailval();
9768 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9769 p = path_advance(&mpath, nullstr);
9774 for (q = p; *q; q++)
9780 q[-1] = '\0'; /* delete trailing '/' */
9781 if (stat(p, &statb) < 0) {
9785 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9788 pathopt ? pathopt : "you have mail"
9791 *mtp = statb.st_mtime;
9793 mail_var_path_changed = 0;
9794 popstackmark(&smark);
9797 static void FAST_FUNC
9798 changemail(const char *val UNUSED_PARAM)
9800 mail_var_path_changed = 1;
9803 #endif /* ASH_MAIL */
9806 /* ============ ??? */
9809 * Set the shell parameters.
9812 setparam(char **argv)
9818 for (nparam = 0; argv[nparam]; nparam++)
9820 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9822 *ap++ = ckstrdup(*argv++);
9825 freeparam(&shellparam);
9826 shellparam.malloced = 1;
9827 shellparam.nparam = nparam;
9828 shellparam.p = newparam;
9829 #if ENABLE_ASH_GETOPTS
9830 shellparam.optind = 1;
9831 shellparam.optoff = -1;
9836 * Process shell options. The global variable argptr contains a pointer
9837 * to the argument list; we advance it past the options.
9839 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9840 * For a non-interactive shell, an error condition encountered
9841 * by a special built-in ... shall cause the shell to write a diagnostic message
9842 * to standard error and exit as shown in the following table:
9843 * Error Special Built-In
9845 * Utility syntax error (option or operand error) Shall exit
9847 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9848 * we see that bash does not do that (set "finishes" with error code 1 instead,
9849 * and shell continues), and people rely on this behavior!
9851 * set -o barfoo 2>/dev/null
9854 * Oh well. Let's mimic that.
9857 plus_minus_o(char *name, int val)
9862 for (i = 0; i < NOPTS; i++) {
9863 if (strcmp(name, optnames(i)) == 0) {
9868 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9871 for (i = 0; i < NOPTS; i++) {
9873 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9875 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9881 setoption(int flag, int val)
9885 for (i = 0; i < NOPTS; i++) {
9886 if (optletters(i) == flag) {
9891 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9895 options(int cmdline)
9903 while ((p = *argptr) != NULL) {
9905 if (c != '-' && c != '+')
9908 val = 0; /* val = 0 if c == '+' */
9911 if (p[0] == '\0' || LONE_DASH(p)) {
9913 /* "-" means turn off -x and -v */
9916 /* "--" means reset params */
9917 else if (*argptr == NULL)
9920 break; /* "-" or "--" terminates options */
9923 /* first char was + or - */
9924 while ((c = *p++) != '\0') {
9925 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9926 if (c == 'c' && cmdline) {
9927 minusc = p; /* command is after shell args */
9928 } else if (c == 'o') {
9929 if (plus_minus_o(*argptr, val)) {
9930 /* it already printed err message */
9931 return 1; /* error */
9935 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9937 /* bash does not accept +-login, we also won't */
9938 } else if (cmdline && val && (c == '-')) { /* long options */
9939 if (strcmp(p, "login") == 0)
9951 * The shift builtin command.
9953 static int FAST_FUNC
9954 shiftcmd(int argc UNUSED_PARAM, char **argv)
9961 n = number(argv[1]);
9962 if (n > shellparam.nparam)
9963 n = 0; /* bash compat, was = shellparam.nparam; */
9965 shellparam.nparam -= n;
9966 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9967 if (shellparam.malloced)
9971 while ((*ap2++ = *ap1++) != NULL)
9973 #if ENABLE_ASH_GETOPTS
9974 shellparam.optind = 1;
9975 shellparam.optoff = -1;
9982 * POSIX requires that 'set' (but not export or readonly) output the
9983 * variables in lexicographic order - by the locale's collating order (sigh).
9984 * Maybe we could keep them in an ordered balanced binary tree
9985 * instead of hashed lists.
9986 * For now just roll 'em through qsort for printing...
9989 showvars(const char *sep_prefix, int on, int off)
9994 ep = listvars(on, off, &epend);
9995 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9997 sep = *sep_prefix ? " " : sep_prefix;
9999 for (; ep < epend; ep++) {
10003 p = strchrnul(*ep, '=');
10006 q = single_quote(++p);
10007 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10013 * The set command builtin.
10015 static int FAST_FUNC
10016 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10021 return showvars(nullstr, 0, VUNSET);
10024 if (!options(0)) { /* if no parse error... */
10027 if (*argptr != NULL) {
10035 #if ENABLE_ASH_RANDOM_SUPPORT
10036 static void FAST_FUNC
10037 change_random(const char *value)
10041 if (value == NULL) {
10042 /* "get", generate */
10043 t = next_random(&random_gen);
10044 /* set without recursion */
10045 setvar(vrandom.text, utoa(t), VNOFUNC);
10046 vrandom.flags &= ~VNOFUNC;
10049 t = strtoul(value, NULL, 10);
10050 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10055 #if ENABLE_ASH_GETOPTS
10057 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10066 if (*param_optind < 1)
10068 optnext = optfirst + *param_optind - 1;
10070 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10073 p = optnext[-1] + *optoff;
10074 if (p == NULL || *p == '\0') {
10075 /* Current word is done, advance */
10077 if (p == NULL || *p != '-' || *++p == '\0') {
10084 if (LONE_DASH(p)) /* check for "--" */
10089 for (q = optstr; *q != c;) {
10091 if (optstr[0] == ':') {
10094 err |= setvarsafe("OPTARG", s, 0);
10096 fprintf(stderr, "Illegal option -%c\n", c);
10097 unsetvar("OPTARG");
10107 if (*p == '\0' && (p = *optnext) == NULL) {
10108 if (optstr[0] == ':') {
10111 err |= setvarsafe("OPTARG", s, 0);
10114 fprintf(stderr, "No arg for -%c option\n", c);
10115 unsetvar("OPTARG");
10123 err |= setvarsafe("OPTARG", p, 0);
10126 err |= setvarsafe("OPTARG", nullstr, 0);
10128 *optoff = p ? p - *(optnext - 1) : -1;
10129 *param_optind = optnext - optfirst + 1;
10130 fmtstr(s, sizeof(s), "%d", *param_optind);
10131 err |= setvarsafe("OPTIND", s, VNOFUNC);
10134 err |= setvarsafe(optvar, s, 0);
10138 flush_stdout_stderr();
10139 raise_exception(EXERROR);
10145 * The getopts builtin. Shellparam.optnext points to the next argument
10146 * to be processed. Shellparam.optptr points to the next character to
10147 * be processed in the current argument. If shellparam.optnext is NULL,
10148 * then it's the first time getopts has been called.
10150 static int FAST_FUNC
10151 getoptscmd(int argc, char **argv)
10156 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10158 optbase = shellparam.p;
10159 if (shellparam.optind > shellparam.nparam + 1) {
10160 shellparam.optind = 1;
10161 shellparam.optoff = -1;
10164 optbase = &argv[3];
10165 if (shellparam.optind > argc - 2) {
10166 shellparam.optind = 1;
10167 shellparam.optoff = -1;
10171 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10172 &shellparam.optoff);
10174 #endif /* ASH_GETOPTS */
10177 /* ============ Shell parser */
10180 struct heredoc *next; /* next here document in list */
10181 union node *here; /* redirection node */
10182 char *eofmark; /* string indicating end of input */
10183 smallint striptabs; /* if set, strip leading tabs */
10186 static smallint tokpushback; /* last token pushed back */
10187 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10188 static smallint quoteflag; /* set if (part of) last token was quoted */
10189 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10190 static struct heredoc *heredoclist; /* list of here documents to read */
10191 static char *wordtext; /* text of last word returned by readtoken */
10192 static struct nodelist *backquotelist;
10193 static union node *redirnode;
10194 static struct heredoc *heredoc;
10197 * Called when an unexpected token is read during the parse. The argument
10198 * is the token that is expected, or -1 if more than one type of token can
10199 * occur at this point.
10201 static void raise_error_unexpected_syntax(int) NORETURN;
10203 raise_error_unexpected_syntax(int token)
10208 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10210 sprintf(msg + l, " (expecting %s)", tokname(token));
10211 raise_error_syntax(msg);
10215 #define EOFMARKLEN 79
10217 /* parsing is heavily cross-recursive, need these forward decls */
10218 static union node *andor(void);
10219 static union node *pipeline(void);
10220 static union node *parse_command(void);
10221 static void parseheredoc(void);
10222 static char peektoken(void);
10223 static int readtoken(void);
10225 static union node *
10228 union node *n1, *n2, *n3;
10231 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10232 if (nlflag == 2 && peektoken())
10238 if (tok == TBACKGND) {
10239 if (n2->type == NPIPE) {
10240 n2->npipe.pipe_backgnd = 1;
10242 if (n2->type != NREDIR) {
10243 n3 = stzalloc(sizeof(struct nredir));
10245 /*n3->nredir.redirect = NULL; - stzalloc did it */
10248 n2->type = NBACKGND;
10254 n3 = stzalloc(sizeof(struct nbinary));
10256 n3->nbinary.ch1 = n1;
10257 n3->nbinary.ch2 = n2;
10273 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10281 pungetc(); /* push back EOF on input */
10285 raise_error_unexpected_syntax(-1);
10292 static union node *
10295 union node *n1, *n2, *n3;
10303 } else if (t == TOR) {
10309 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10311 n3 = stzalloc(sizeof(struct nbinary));
10313 n3->nbinary.ch1 = n1;
10314 n3->nbinary.ch2 = n2;
10319 static union node *
10322 union node *n1, *n2, *pipenode;
10323 struct nodelist *lp, *prev;
10327 TRACE(("pipeline: entered\n"));
10328 if (readtoken() == TNOT) {
10330 checkkwd = CHKKWD | CHKALIAS;
10333 n1 = parse_command();
10334 if (readtoken() == TPIPE) {
10335 pipenode = stzalloc(sizeof(struct npipe));
10336 pipenode->type = NPIPE;
10337 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10338 lp = stzalloc(sizeof(struct nodelist));
10339 pipenode->npipe.cmdlist = lp;
10343 lp = stzalloc(sizeof(struct nodelist));
10344 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10345 lp->n = parse_command();
10347 } while (readtoken() == TPIPE);
10353 n2 = stzalloc(sizeof(struct nnot));
10361 static union node *
10366 n = stzalloc(sizeof(struct narg));
10368 /*n->narg.next = NULL; - stzalloc did it */
10369 n->narg.text = wordtext;
10370 n->narg.backquote = backquotelist;
10375 fixredir(union node *n, const char *text, int err)
10379 TRACE(("Fix redir %s %d\n", text, err));
10381 n->ndup.vname = NULL;
10383 fd = bb_strtou(text, NULL, 10);
10384 if (!errno && fd >= 0)
10385 n->ndup.dupfd = fd;
10386 else if (LONE_DASH(text))
10387 n->ndup.dupfd = -1;
10390 raise_error_syntax("bad fd number");
10391 n->ndup.vname = makename();
10396 * Returns true if the text contains nothing to expand (no dollar signs
10400 noexpand(const char *text)
10404 while ((c = *text++) != '\0') {
10405 if (c == CTLQUOTEMARK)
10409 else if (SIT(c, BASESYNTAX) == CCTL)
10418 union node *n = redirnode;
10420 if (readtoken() != TWORD)
10421 raise_error_unexpected_syntax(-1);
10422 if (n->type == NHERE) {
10423 struct heredoc *here = heredoc;
10427 if (quoteflag == 0)
10429 TRACE(("Here document %d\n", n->type));
10430 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10431 raise_error_syntax("illegal eof marker for << redirection");
10432 rmescapes(wordtext, 0);
10433 here->eofmark = wordtext;
10435 if (heredoclist == NULL)
10436 heredoclist = here;
10438 for (p = heredoclist; p->next; p = p->next)
10442 } else if (n->type == NTOFD || n->type == NFROMFD) {
10443 fixredir(n, wordtext, 0);
10445 n->nfile.fname = makename();
10449 static union node *
10452 union node *args, **app;
10453 union node *n = NULL;
10454 union node *vars, **vpp;
10455 union node **rpp, *redir;
10457 #if ENABLE_ASH_BASH_COMPAT
10458 smallint double_brackets_flag = 0;
10468 savecheckkwd = CHKALIAS;
10471 checkkwd = savecheckkwd;
10474 #if ENABLE_ASH_BASH_COMPAT
10475 case TAND: /* "&&" */
10476 case TOR: /* "||" */
10477 if (!double_brackets_flag) {
10481 wordtext = (char *) (t == TAND ? "-a" : "-o");
10484 n = stzalloc(sizeof(struct narg));
10486 /*n->narg.next = NULL; - stzalloc did it */
10487 n->narg.text = wordtext;
10488 #if ENABLE_ASH_BASH_COMPAT
10489 if (strcmp("[[", wordtext) == 0)
10490 double_brackets_flag = 1;
10491 else if (strcmp("]]", wordtext) == 0)
10492 double_brackets_flag = 0;
10494 n->narg.backquote = backquotelist;
10495 if (savecheckkwd && isassignment(wordtext)) {
10497 vpp = &n->narg.next;
10500 app = &n->narg.next;
10505 *rpp = n = redirnode;
10506 rpp = &n->nfile.next;
10507 parsefname(); /* read name of redirection file */
10510 if (args && app == &args->narg.next
10513 struct builtincmd *bcmd;
10516 /* We have a function */
10517 if (readtoken() != TRP)
10518 raise_error_unexpected_syntax(TRP);
10519 name = n->narg.text;
10520 if (!goodname(name)
10521 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10523 raise_error_syntax("bad function name");
10526 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10527 n->narg.next = parse_command();
10540 n = stzalloc(sizeof(struct ncmd));
10542 n->ncmd.args = args;
10543 n->ncmd.assign = vars;
10544 n->ncmd.redirect = redir;
10548 static union node *
10549 parse_command(void)
10551 union node *n1, *n2;
10552 union node *ap, **app;
10553 union node *cp, **cpp;
10554 union node *redir, **rpp;
10561 switch (readtoken()) {
10563 raise_error_unexpected_syntax(-1);
10566 n1 = stzalloc(sizeof(struct nif));
10568 n1->nif.test = list(0);
10569 if (readtoken() != TTHEN)
10570 raise_error_unexpected_syntax(TTHEN);
10571 n1->nif.ifpart = list(0);
10573 while (readtoken() == TELIF) {
10574 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10575 n2 = n2->nif.elsepart;
10577 n2->nif.test = list(0);
10578 if (readtoken() != TTHEN)
10579 raise_error_unexpected_syntax(TTHEN);
10580 n2->nif.ifpart = list(0);
10582 if (lasttoken == TELSE)
10583 n2->nif.elsepart = list(0);
10585 n2->nif.elsepart = NULL;
10593 n1 = stzalloc(sizeof(struct nbinary));
10594 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10595 n1->nbinary.ch1 = list(0);
10598 TRACE(("expecting DO got %s %s\n", tokname(got),
10599 got == TWORD ? wordtext : ""));
10600 raise_error_unexpected_syntax(TDO);
10602 n1->nbinary.ch2 = list(0);
10607 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10608 raise_error_syntax("bad for loop variable");
10609 n1 = stzalloc(sizeof(struct nfor));
10611 n1->nfor.var = wordtext;
10612 checkkwd = CHKKWD | CHKALIAS;
10613 if (readtoken() == TIN) {
10615 while (readtoken() == TWORD) {
10616 n2 = stzalloc(sizeof(struct narg));
10618 /*n2->narg.next = NULL; - stzalloc did it */
10619 n2->narg.text = wordtext;
10620 n2->narg.backquote = backquotelist;
10622 app = &n2->narg.next;
10625 n1->nfor.args = ap;
10626 if (lasttoken != TNL && lasttoken != TSEMI)
10627 raise_error_unexpected_syntax(-1);
10629 n2 = stzalloc(sizeof(struct narg));
10631 /*n2->narg.next = NULL; - stzalloc did it */
10632 n2->narg.text = (char *)dolatstr;
10633 /*n2->narg.backquote = NULL;*/
10634 n1->nfor.args = n2;
10636 * Newline or semicolon here is optional (but note
10637 * that the original Bourne shell only allowed NL).
10639 if (lasttoken != TNL && lasttoken != TSEMI)
10642 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10643 if (readtoken() != TDO)
10644 raise_error_unexpected_syntax(TDO);
10645 n1->nfor.body = list(0);
10649 n1 = stzalloc(sizeof(struct ncase));
10651 if (readtoken() != TWORD)
10652 raise_error_unexpected_syntax(TWORD);
10653 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10655 /*n2->narg.next = NULL; - stzalloc did it */
10656 n2->narg.text = wordtext;
10657 n2->narg.backquote = backquotelist;
10659 checkkwd = CHKKWD | CHKALIAS;
10660 } while (readtoken() == TNL);
10661 if (lasttoken != TIN)
10662 raise_error_unexpected_syntax(TIN);
10663 cpp = &n1->ncase.cases;
10665 checkkwd = CHKNL | CHKKWD;
10667 while (t != TESAC) {
10668 if (lasttoken == TLP)
10670 *cpp = cp = stzalloc(sizeof(struct nclist));
10672 app = &cp->nclist.pattern;
10674 *app = ap = stzalloc(sizeof(struct narg));
10676 /*ap->narg.next = NULL; - stzalloc did it */
10677 ap->narg.text = wordtext;
10678 ap->narg.backquote = backquotelist;
10679 if (readtoken() != TPIPE)
10681 app = &ap->narg.next;
10684 //ap->narg.next = NULL;
10685 if (lasttoken != TRP)
10686 raise_error_unexpected_syntax(TRP);
10687 cp->nclist.body = list(2);
10689 cpp = &cp->nclist.next;
10691 checkkwd = CHKNL | CHKKWD;
10695 raise_error_unexpected_syntax(TENDCASE);
10702 n1 = stzalloc(sizeof(struct nredir));
10703 n1->type = NSUBSHELL;
10704 n1->nredir.n = list(0);
10705 /*n1->nredir.redirect = NULL; - stzalloc did it */
10715 return simplecmd();
10718 if (readtoken() != t)
10719 raise_error_unexpected_syntax(t);
10722 /* Now check for redirection which may follow command */
10723 checkkwd = CHKKWD | CHKALIAS;
10725 while (readtoken() == TREDIR) {
10726 *rpp = n2 = redirnode;
10727 rpp = &n2->nfile.next;
10733 if (n1->type != NSUBSHELL) {
10734 n2 = stzalloc(sizeof(struct nredir));
10739 n1->nredir.redirect = redir;
10744 #if ENABLE_ASH_BASH_COMPAT
10745 static int decode_dollar_squote(void)
10747 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10753 p = strchr(C_escapes, c);
10758 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10762 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10764 } else if (c == 'x') { /* \xHH */
10768 } while (isxdigit(c) && --cnt);
10770 if (cnt == 3) { /* \x but next char is "bad" */
10774 } else { /* simple seq like \\ or \t */
10779 c = bb_process_escape_sequence((void*)&p);
10780 } else { /* unrecognized "\z": print both chars unless ' or " */
10781 if (c != '\'' && c != '"') {
10783 c |= 0x100; /* "please encode \, then me" */
10791 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10792 * is not NULL, read a here document. In the latter case, eofmark is the
10793 * word which marks the end of the document and striptabs is true if
10794 * leading tabs should be stripped from the document. The argument c
10795 * is the first character of the input token or document.
10797 * Because C does not have internal subroutines, I have simulated them
10798 * using goto's to implement the subroutine linkage. The following macros
10799 * will run code that appears at the end of readtoken1.
10801 #define CHECKEND() {goto checkend; checkend_return:;}
10802 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10803 #define PARSESUB() {goto parsesub; parsesub_return:;}
10804 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10805 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10806 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10808 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10810 /* NB: syntax parameter fits into smallint */
10811 /* c parameter is an unsigned char or PEOF or PEOA */
10814 char line[EOFMARKLEN + 1];
10815 struct nodelist *bqlist;
10819 smallint prevsyntax; /* syntax before arithmetic */
10820 #if ENABLE_ASH_EXPAND_PRMT
10821 smallint pssyntax; /* we are expanding a prompt string */
10823 int varnest; /* levels of variables expansion */
10824 int arinest; /* levels of arithmetic expansion */
10825 int parenlevel; /* levels of parens in arithmetic */
10826 int dqvarnest; /* levels of variables expansion within double quotes */
10828 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10831 /* Avoid longjmp clobbering */
10837 (void) &parenlevel;
10840 (void) &prevsyntax;
10843 startlinno = g_parsefile->linno;
10848 #if ENABLE_ASH_EXPAND_PRMT
10849 pssyntax = (syntax == PSSYNTAX);
10853 dblquote = (syntax == DQSYNTAX);
10859 STARTSTACKSTR(out);
10861 /* For each line, until end of word */
10863 CHECKEND(); /* set c to PEOF if at end of here document */
10864 for (;;) { /* until end of line or end of word */
10865 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10866 switch (SIT(c, syntax)) {
10867 case CNL: /* '\n' */
10868 if (syntax == BASESYNTAX)
10869 goto endword; /* exit outer loop */
10871 g_parsefile->linno++;
10875 goto loop; /* continue outer loop */
10880 if (eofmark == NULL || dblquote)
10881 USTPUTC(CTLESC, out);
10882 #if ENABLE_ASH_BASH_COMPAT
10883 if (c == '\\' && bash_dollar_squote) {
10884 c = decode_dollar_squote();
10886 USTPUTC('\\', out);
10887 c = (unsigned char)c;
10893 case CBACK: /* backslash */
10896 USTPUTC(CTLESC, out);
10897 USTPUTC('\\', out);
10899 } else if (c == '\n') {
10903 #if ENABLE_ASH_EXPAND_PRMT
10904 if (c == '$' && pssyntax) {
10905 USTPUTC(CTLESC, out);
10906 USTPUTC('\\', out);
10909 if (dblquote && c != '\\'
10910 && c != '`' && c != '$'
10911 && (c != '"' || eofmark != NULL)
10913 USTPUTC(CTLESC, out);
10914 USTPUTC('\\', out);
10916 if (SIT(c, SQSYNTAX) == CCTL)
10917 USTPUTC(CTLESC, out);
10925 if (eofmark == NULL) {
10926 USTPUTC(CTLQUOTEMARK, out);
10934 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10935 if (eofmark != NULL && arinest == 0
10940 if (dqvarnest == 0) {
10941 syntax = BASESYNTAX;
10948 case CVAR: /* '$' */
10949 PARSESUB(); /* parse substitution */
10951 case CENDVAR: /* '}' */
10954 if (dqvarnest > 0) {
10957 USTPUTC(CTLENDVAR, out);
10962 #if ENABLE_SH_MATH_SUPPORT
10963 case CLP: /* '(' in arithmetic */
10967 case CRP: /* ')' in arithmetic */
10968 if (parenlevel > 0) {
10972 if (pgetc() == ')') {
10973 if (--arinest == 0) {
10974 USTPUTC(CTLENDARI, out);
10975 syntax = prevsyntax;
10976 dblquote = (syntax == DQSYNTAX);
10981 * unbalanced parens
10982 * (don't 2nd guess - no error)
10990 case CBQUOTE: /* '`' */
10994 goto endword; /* exit outer loop */
10998 if (varnest == 0) {
10999 #if ENABLE_ASH_BASH_COMPAT
11001 if (pgetc() == '>')
11002 c = 0x100 + '>'; /* flag &> */
11006 goto endword; /* exit outer loop */
11008 #if ENABLE_ASH_ALIAS
11018 #if ENABLE_SH_MATH_SUPPORT
11019 if (syntax == ARISYNTAX)
11020 raise_error_syntax("missing '))'");
11022 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11023 raise_error_syntax("unterminated quoted string");
11024 if (varnest != 0) {
11025 startlinno = g_parsefile->linno;
11027 raise_error_syntax("missing '}'");
11029 USTPUTC('\0', out);
11030 len = out - (char *)stackblock();
11031 out = stackblock();
11032 if (eofmark == NULL) {
11033 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11036 if (isdigit_str9(out)) {
11037 PARSEREDIR(); /* passed as params: out, c */
11038 lasttoken = TREDIR;
11041 /* else: non-number X seen, interpret it
11042 * as "NNNX>file" = "NNNX >file" */
11046 quoteflag = quotef;
11047 backquotelist = bqlist;
11048 grabstackblock(len);
11052 /* end of readtoken routine */
11055 * Check to see whether we are at the end of the here document. When this
11056 * is called, c is set to the first character of the next input line. If
11057 * we are at the end of the here document, this routine sets the c to PEOF.
11061 #if ENABLE_ASH_ALIAS
11067 while (c == '\t') {
11071 if (c == *eofmark) {
11072 if (pfgets(line, sizeof(line)) != NULL) {
11076 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11078 if (*p == '\n' && *q == '\0') {
11080 g_parsefile->linno++;
11081 needprompt = doprompt;
11083 pushstring(line, NULL);
11088 goto checkend_return;
11092 * Parse a redirection operator. The variable "out" points to a string
11093 * specifying the fd to be redirected. The variable "c" contains the
11094 * first character of the redirection operator.
11097 /* out is already checked to be a valid number or "" */
11098 int fd = (*out == '\0' ? -1 : atoi(out));
11101 np = stzalloc(sizeof(struct nfile));
11106 np->type = NAPPEND;
11108 np->type = NCLOBBER;
11111 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11117 #if ENABLE_ASH_BASH_COMPAT
11118 else if (c == 0x100 + '>') { /* this flags &> redirection */
11120 pgetc(); /* this is '>', no need to check */
11124 else { /* c == '<' */
11125 /*np->nfile.fd = 0; - stzalloc did it */
11129 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11130 np = stzalloc(sizeof(struct nhere));
11131 /*np->nfile.fd = 0; - stzalloc did it */
11134 heredoc = stzalloc(sizeof(struct heredoc));
11135 heredoc->here = np;
11138 heredoc->striptabs = 1;
11140 /*heredoc->striptabs = 0; - stzalloc did it */
11146 np->type = NFROMFD;
11150 np->type = NFROMTO;
11162 goto parseredir_return;
11166 * Parse a substitution. At this point, we have read the dollar sign
11167 * and nothing else.
11170 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11171 * (assuming ascii char codes, as the original implementation did) */
11172 #define is_special(c) \
11173 (((unsigned)(c) - 33 < 32) \
11174 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11176 unsigned char subtype;
11180 static const char types[] ALIGN1 = "}-+?=";
11183 if (c > 255 /* PEOA or PEOF */
11184 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11186 #if ENABLE_ASH_BASH_COMPAT
11188 bash_dollar_squote = 1;
11193 } else if (c == '(') { /* $(command) or $((arith)) */
11194 if (pgetc() == '(') {
11195 #if ENABLE_SH_MATH_SUPPORT
11198 raise_error_syntax("you disabled math support for $((arith)) syntax");
11205 USTPUTC(CTLVAR, out);
11206 typeloc = out - (char *)stackblock();
11207 USTPUTC(VSNORMAL, out);
11208 subtype = VSNORMAL;
11216 subtype = VSLENGTH;
11220 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11224 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11225 } else if (isdigit(c)) {
11229 } while (isdigit(c));
11230 } else if (is_special(c)) {
11235 raise_error_syntax("bad substitution");
11237 if (c != '}' && subtype == VSLENGTH)
11242 if (subtype == 0) {
11246 #if ENABLE_ASH_BASH_COMPAT
11247 if (c == ':' || c == '$' || isdigit(c)) {
11249 subtype = VSSUBSTR;
11256 p = strchr(types, c);
11259 subtype = p - types + VSNORMAL;
11264 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11272 #if ENABLE_ASH_BASH_COMPAT
11274 subtype = VSREPLACE;
11277 subtype++; /* VSREPLACEALL */
11286 if (dblquote || arinest)
11288 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11289 if (subtype != VSNORMAL) {
11291 if (dblquote || arinest) {
11296 goto parsesub_return;
11300 * Called to parse command substitutions. Newstyle is set if the command
11301 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11302 * list of commands (passed by reference), and savelen is the number of
11303 * characters on the top of the stack which must be preserved.
11306 struct nodelist **nlpp;
11309 char *volatile str;
11310 struct jmploc jmploc;
11311 struct jmploc *volatile savehandler;
11313 smallint saveprompt = 0;
11316 (void) &saveprompt;
11318 savepbq = parsebackquote;
11319 if (setjmp(jmploc.loc)) {
11321 parsebackquote = 0;
11322 exception_handler = savehandler;
11323 longjmp(exception_handler->loc, 1);
11327 savelen = out - (char *)stackblock();
11329 str = ckmalloc(savelen);
11330 memcpy(str, stackblock(), savelen);
11332 savehandler = exception_handler;
11333 exception_handler = &jmploc;
11336 /* We must read until the closing backquote, giving special
11337 treatment to some slashes, and then push the string and
11338 reread it as input, interpreting it normally. */
11345 STARTSTACKSTR(pout);
11358 g_parsefile->linno++;
11362 * If eating a newline, avoid putting
11363 * the newline into the new character
11364 * stream (via the STPUTC after the
11369 if (pc != '\\' && pc != '`' && pc != '$'
11370 && (!dblquote || pc != '"')
11372 STPUTC('\\', pout);
11374 if (pc <= 255 /* not PEOA or PEOF */) {
11380 #if ENABLE_ASH_ALIAS
11383 startlinno = g_parsefile->linno;
11384 raise_error_syntax("EOF in backquote substitution");
11387 g_parsefile->linno++;
11388 needprompt = doprompt;
11397 STPUTC('\0', pout);
11398 psavelen = pout - (char *)stackblock();
11399 if (psavelen > 0) {
11400 pstr = grabstackstr(pout);
11401 setinputstring(pstr);
11406 nlpp = &(*nlpp)->next;
11407 *nlpp = stzalloc(sizeof(**nlpp));
11408 /* (*nlpp)->next = NULL; - stzalloc did it */
11409 parsebackquote = oldstyle;
11412 saveprompt = doprompt;
11419 doprompt = saveprompt;
11420 else if (readtoken() != TRP)
11421 raise_error_unexpected_syntax(TRP);
11426 * Start reading from old file again, ignoring any pushed back
11427 * tokens left from the backquote parsing
11432 while (stackblocksize() <= savelen)
11434 STARTSTACKSTR(out);
11436 memcpy(out, str, savelen);
11437 STADJUST(savelen, out);
11443 parsebackquote = savepbq;
11444 exception_handler = savehandler;
11445 if (arinest || dblquote)
11446 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11448 USTPUTC(CTLBACKQ, out);
11450 goto parsebackq_oldreturn;
11451 goto parsebackq_newreturn;
11454 #if ENABLE_SH_MATH_SUPPORT
11456 * Parse an arithmetic expansion (indicate start of one and set state)
11459 if (++arinest == 1) {
11460 prevsyntax = syntax;
11461 syntax = ARISYNTAX;
11462 USTPUTC(CTLARI, out);
11469 * we collapse embedded arithmetic expansion to
11470 * parenthesis, which should be equivalent
11474 goto parsearith_return;
11478 } /* end of readtoken */
11481 * Read the next input token.
11482 * If the token is a word, we set backquotelist to the list of cmds in
11483 * backquotes. We set quoteflag to true if any part of the word was
11485 * If the token is TREDIR, then we set redirnode to a structure containing
11487 * In all cases, the variable startlinno is set to the number of the line
11488 * on which the token starts.
11490 * [Change comment: here documents and internal procedures]
11491 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11492 * word parsing code into a separate routine. In this case, readtoken
11493 * doesn't need to have any internal procedures, but parseword does.
11494 * We could also make parseoperator in essence the main routine, and
11495 * have parseword (readtoken1?) handle both words and redirection.]
11497 #define NEW_xxreadtoken
11498 #ifdef NEW_xxreadtoken
11499 /* singles must be first! */
11500 static const char xxreadtoken_chars[7] ALIGN1 = {
11501 '\n', '(', ')', /* singles */
11502 '&', '|', ';', /* doubles */
11506 #define xxreadtoken_singles 3
11507 #define xxreadtoken_doubles 3
11509 static const char xxreadtoken_tokens[] ALIGN1 = {
11510 TNL, TLP, TRP, /* only single occurrence allowed */
11511 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11512 TEOF, /* corresponds to trailing nul */
11513 TAND, TOR, TENDCASE /* if double occurrence */
11528 startlinno = g_parsefile->linno;
11529 for (;;) { /* until token or start of word found */
11531 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11535 while ((c = pgetc()) != '\n' && c != PEOF)
11538 } else if (c == '\\') {
11539 if (pgetc() != '\n') {
11541 break; /* return readtoken1(...) */
11543 startlinno = ++g_parsefile->linno;
11549 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11552 g_parsefile->linno++;
11553 needprompt = doprompt;
11556 p = strchr(xxreadtoken_chars, c);
11558 break; /* return readtoken1(...) */
11560 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11562 if (cc == c) { /* double occurrence? */
11563 p += xxreadtoken_doubles + 1;
11566 #if ENABLE_ASH_BASH_COMPAT
11567 if (c == '&' && cc == '>') /* &> */
11568 break; /* return readtoken1(...) */
11573 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11578 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11580 #else /* old xxreadtoken */
11581 #define RETURN(token) return lasttoken = token
11594 startlinno = g_parsefile->linno;
11595 for (;;) { /* until token or start of word found */
11598 case ' ': case '\t':
11599 #if ENABLE_ASH_ALIAS
11604 while ((c = pgetc()) != '\n' && c != PEOF)
11609 if (pgetc() == '\n') {
11610 startlinno = ++g_parsefile->linno;
11618 g_parsefile->linno++;
11619 needprompt = doprompt;
11624 if (pgetc() == '&')
11629 if (pgetc() == '|')
11634 if (pgetc() == ';')
11647 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11650 #endif /* old xxreadtoken */
11657 smallint alreadyseen = tokpushback;
11660 #if ENABLE_ASH_ALIAS
11669 if (checkkwd & CHKNL) {
11676 if (t != TWORD || quoteflag) {
11681 * check for keywords
11683 if (checkkwd & CHKKWD) {
11684 const char *const *pp;
11686 pp = findkwd(wordtext);
11688 lasttoken = t = pp - tokname_array;
11689 TRACE(("keyword %s recognized\n", tokname(t)));
11694 if (checkkwd & CHKALIAS) {
11695 #if ENABLE_ASH_ALIAS
11697 ap = lookupalias(wordtext, 1);
11700 pushstring(ap->val, ap);
11710 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11712 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11724 return tokname_array[t][0];
11728 * Read and parse a command. Returns NODE_EOF on end of file.
11729 * (NULL is a valid parse tree indicating a blank line.)
11731 static union node *
11732 parsecmd(int interact)
11737 doprompt = interact;
11739 setprompt(doprompt);
11751 * Input any here documents.
11756 struct heredoc *here;
11759 here = heredoclist;
11760 heredoclist = NULL;
11766 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11767 here->eofmark, here->striptabs);
11768 n = stzalloc(sizeof(struct narg));
11769 n->narg.type = NARG;
11770 /*n->narg.next = NULL; - stzalloc did it */
11771 n->narg.text = wordtext;
11772 n->narg.backquote = backquotelist;
11773 here->here->nhere.doc = n;
11780 * called by editline -- any expansions to the prompt should be added here.
11782 #if ENABLE_ASH_EXPAND_PRMT
11783 static const char *
11784 expandstr(const char *ps)
11788 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11789 * and token processing _can_ alter it (delete NULs etc). */
11790 setinputstring((char *)ps);
11791 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11794 n.narg.type = NARG;
11795 n.narg.next = NULL;
11796 n.narg.text = wordtext;
11797 n.narg.backquote = backquotelist;
11799 expandarg(&n, NULL, 0);
11800 return stackblock();
11805 * Execute a command or commands contained in a string.
11808 evalstring(char *s, int mask)
11811 struct stackmark smark;
11815 setstackmark(&smark);
11818 while ((n = parsecmd(0)) != NODE_EOF) {
11820 popstackmark(&smark);
11833 * The eval command.
11835 static int FAST_FUNC
11836 evalcmd(int argc UNUSED_PARAM, char **argv)
11845 STARTSTACKSTR(concat);
11847 concat = stack_putstr(p, concat);
11851 STPUTC(' ', concat);
11853 STPUTC('\0', concat);
11854 p = grabstackstr(concat);
11856 evalstring(p, ~SKIPEVAL);
11863 * Read and execute commands. "Top" is nonzero for the top level command
11864 * loop; it turns on prompting if the shell is interactive.
11870 struct stackmark smark;
11874 TRACE(("cmdloop(%d) called\n", top));
11878 setstackmark(&smark);
11881 showjobs(stderr, SHOW_CHANGED);
11884 if (iflag && top) {
11886 #if ENABLE_ASH_MAIL
11890 n = parsecmd(inter);
11892 if (DEBUG > 2 && debug && (n != NODE_EOF))
11895 if (n == NODE_EOF) {
11896 if (!top || numeof >= 50)
11898 if (!stoppedjobs()) {
11901 out2str("\nUse \"exit\" to leave shell.\n");
11904 } else if (nflag == 0) {
11905 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11910 popstackmark(&smark);
11915 return skip & SKIPEVAL;
11922 * Take commands from a file. To be compatible we should do a path
11923 * search for the file, which is necessary to find sub-commands.
11926 find_dot_file(char *name)
11929 const char *path = pathval();
11932 /* don't try this for absolute or relative paths */
11933 if (strchr(name, '/'))
11936 /* IIRC standards do not say whether . is to be searched.
11937 * And it is even smaller this way, making it unconditional for now:
11939 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11944 while ((fullname = path_advance(&path, name)) != NULL) {
11946 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11948 * Don't bother freeing here, since it will
11949 * be freed by the caller.
11953 if (fullname != name)
11954 stunalloc(fullname);
11957 /* not found in the PATH */
11958 ash_msg_and_raise_error("%s: not found", name);
11962 static int FAST_FUNC
11963 dotcmd(int argc, char **argv)
11965 struct strlist *sp;
11966 volatile struct shparam saveparam;
11969 for (sp = cmdenviron; sp; sp = sp->next)
11970 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11972 if (argv[1]) { /* That's what SVR2 does */
11973 char *fullname = find_dot_file(argv[1]);
11976 if (argc) { /* argc > 0, argv[0] != NULL */
11977 saveparam = shellparam;
11978 shellparam.malloced = 0;
11979 shellparam.nparam = argc;
11980 shellparam.p = argv;
11983 setinputfile(fullname, INPUT_PUSH_FILE);
11984 commandname = fullname;
11989 freeparam(&shellparam);
11990 shellparam = saveparam;
11992 status = exitstatus;
11997 static int FAST_FUNC
11998 exitcmd(int argc UNUSED_PARAM, char **argv)
12003 exitstatus = number(argv[1]);
12004 raise_exception(EXEXIT);
12009 * Read a file containing shell functions.
12012 readcmdfile(char *name)
12014 setinputfile(name, INPUT_PUSH_FILE);
12020 /* ============ find_command inplementation */
12023 * Resolve a command name. If you change this routine, you may have to
12024 * change the shellexec routine as well.
12027 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12029 struct tblentry *cmdp;
12036 struct builtincmd *bcmd;
12038 /* If name contains a slash, don't use PATH or hash table */
12039 if (strchr(name, '/') != NULL) {
12040 entry->u.index = -1;
12041 if (act & DO_ABS) {
12042 while (stat(name, &statb) < 0) {
12044 if (errno == EINTR)
12047 entry->cmdtype = CMDUNKNOWN;
12051 entry->cmdtype = CMDNORMAL;
12055 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12057 updatetbl = (path == pathval());
12060 if (strstr(path, "%builtin") != NULL)
12061 act |= DO_ALTBLTIN;
12064 /* If name is in the table, check answer will be ok */
12065 cmdp = cmdlookup(name, 0);
12066 if (cmdp != NULL) {
12069 switch (cmdp->cmdtype) {
12087 } else if (cmdp->rehash == 0)
12088 /* if not invalidated by cd, we're done */
12092 /* If %builtin not in path, check for builtin next */
12093 bcmd = find_builtin(name);
12095 if (IS_BUILTIN_REGULAR(bcmd))
12096 goto builtin_success;
12097 if (act & DO_ALTPATH) {
12098 if (!(act & DO_ALTBLTIN))
12099 goto builtin_success;
12100 } else if (builtinloc <= 0) {
12101 goto builtin_success;
12105 #if ENABLE_FEATURE_SH_STANDALONE
12107 int applet_no = find_applet_by_name(name);
12108 if (applet_no >= 0) {
12109 entry->cmdtype = CMDNORMAL;
12110 entry->u.index = -2 - applet_no;
12116 /* We have to search path. */
12117 prev = -1; /* where to start */
12118 if (cmdp && cmdp->rehash) { /* doing a rehash */
12119 if (cmdp->cmdtype == CMDBUILTIN)
12122 prev = cmdp->param.index;
12128 while ((fullname = path_advance(&path, name)) != NULL) {
12129 stunalloc(fullname);
12130 /* NB: code below will still use fullname
12131 * despite it being "unallocated" */
12134 if (prefix(pathopt, "builtin")) {
12136 goto builtin_success;
12139 if ((act & DO_NOFUNC)
12140 || !prefix(pathopt, "func")
12141 ) { /* ignore unimplemented options */
12145 /* if rehash, don't redo absolute path names */
12146 if (fullname[0] == '/' && idx <= prev) {
12149 TRACE(("searchexec \"%s\": no change\n", name));
12152 while (stat(fullname, &statb) < 0) {
12154 if (errno == EINTR)
12157 if (errno != ENOENT && errno != ENOTDIR)
12161 e = EACCES; /* if we fail, this will be the error */
12162 if (!S_ISREG(statb.st_mode))
12164 if (pathopt) { /* this is a %func directory */
12165 stalloc(strlen(fullname) + 1);
12166 /* NB: stalloc will return space pointed by fullname
12167 * (because we don't have any intervening allocations
12168 * between stunalloc above and this stalloc) */
12169 readcmdfile(fullname);
12170 cmdp = cmdlookup(name, 0);
12171 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12172 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12173 stunalloc(fullname);
12176 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12178 entry->cmdtype = CMDNORMAL;
12179 entry->u.index = idx;
12183 cmdp = cmdlookup(name, 1);
12184 cmdp->cmdtype = CMDNORMAL;
12185 cmdp->param.index = idx;
12190 /* We failed. If there was an entry for this command, delete it */
12191 if (cmdp && updatetbl)
12192 delete_cmd_entry();
12194 ash_msg("%s: %s", name, errmsg(e, "not found"));
12195 entry->cmdtype = CMDUNKNOWN;
12200 entry->cmdtype = CMDBUILTIN;
12201 entry->u.cmd = bcmd;
12205 cmdp = cmdlookup(name, 1);
12206 cmdp->cmdtype = CMDBUILTIN;
12207 cmdp->param.cmd = bcmd;
12211 entry->cmdtype = cmdp->cmdtype;
12212 entry->u = cmdp->param;
12216 /* ============ trap.c */
12219 * The trap builtin.
12221 static int FAST_FUNC
12222 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12231 for (signo = 0; signo < NSIG; signo++) {
12232 char *tr = trap_ptr[signo];
12234 /* note: bash adds "SIG", but only if invoked
12235 * as "bash". If called as "sh", or if set -o posix,
12236 * then it prints short signal names.
12237 * We are printing short names: */
12238 out1fmt("trap -- %s %s\n",
12240 get_signame(signo));
12241 /* trap_ptr != trap only if we are in special-cased `trap` code.
12242 * In this case, we will exit very soon, no need to free(). */
12243 /* if (trap_ptr != trap && tp[0]) */
12248 if (trap_ptr != trap) {
12260 signo = get_signum(*ap);
12262 ash_msg_and_raise_error("%s: bad trap", *ap);
12265 if (LONE_DASH(action))
12268 action = ckstrdup(action);
12271 trap[signo] = action;
12281 /* ============ Builtins */
12283 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12285 * Lists available builtins
12287 static int FAST_FUNC
12288 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12294 "Built-in commands:\n"
12295 "------------------\n");
12296 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12297 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12298 builtintab[i].name + 1);
12304 #if ENABLE_FEATURE_SH_STANDALONE
12306 const char *a = applet_names;
12308 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12313 a += strlen(a) + 1;
12318 return EXIT_SUCCESS;
12320 #endif /* FEATURE_SH_EXTRA_QUIET */
12323 * The export and readonly commands.
12325 static int FAST_FUNC
12326 exportcmd(int argc UNUSED_PARAM, char **argv)
12332 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12334 if (nextopt("p") != 'p') {
12339 p = strchr(name, '=');
12343 vp = *findvar(hashvar(name), name);
12349 setvar(name, p, flag);
12350 } while ((name = *++aptr) != NULL);
12354 showvars(argv[0], flag, 0);
12359 * Delete a function if it exists.
12362 unsetfunc(const char *name)
12364 struct tblentry *cmdp;
12366 cmdp = cmdlookup(name, 0);
12367 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12368 delete_cmd_entry();
12372 * The unset builtin command. We unset the function before we unset the
12373 * variable to allow a function to be unset when there is a readonly variable
12374 * with the same name.
12376 static int FAST_FUNC
12377 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12384 while ((i = nextopt("vf")) != '\0') {
12388 for (ap = argptr; *ap; ap++) {
12404 #include <sys/times.h>
12406 static const unsigned char timescmd_str[] ALIGN1 = {
12407 ' ', offsetof(struct tms, tms_utime),
12408 '\n', offsetof(struct tms, tms_stime),
12409 ' ', offsetof(struct tms, tms_cutime),
12410 '\n', offsetof(struct tms, tms_cstime),
12414 static int FAST_FUNC
12415 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12417 long clk_tck, s, t;
12418 const unsigned char *p;
12421 clk_tck = sysconf(_SC_CLK_TCK);
12426 t = *(clock_t *)(((char *) &buf) + p[1]);
12428 out1fmt("%ldm%ld.%.3lds%c",
12430 ((t - s * clk_tck) * 1000) / clk_tck,
12432 } while (*(p += 2));
12437 #if ENABLE_SH_MATH_SUPPORT
12439 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12440 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12442 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12444 static int FAST_FUNC
12445 letcmd(int argc UNUSED_PARAM, char **argv)
12451 ash_msg_and_raise_error("expression expected");
12453 i = ash_arith(*argv);
12458 #endif /* SH_MATH_SUPPORT */
12461 /* ============ miscbltin.c
12463 * Miscellaneous builtins.
12468 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12469 typedef enum __rlimit_resource rlim_t;
12473 * The read builtin. Options:
12474 * -r Do not interpret '\' specially
12475 * -s Turn off echo (tty only)
12476 * -n NCHARS Read NCHARS max
12477 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12478 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12479 * -u FD Read from given FD instead of fd 0
12480 * This uses unbuffered input, which may be avoidable in some cases.
12481 * TODO: bash also has:
12482 * -a ARRAY Read into array[0],[1],etc
12483 * -d DELIM End on DELIM char, not newline
12484 * -e Use line editing (tty only)
12486 static int FAST_FUNC
12487 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12489 static const char *const arg_REPLY[] = { "REPLY", NULL };
12502 #if ENABLE_ASH_READ_NCHARS
12503 int nchars = 0; /* if != 0, -n is in effect */
12505 struct termios tty, old_tty;
12507 #if ENABLE_ASH_READ_TIMEOUT
12508 unsigned end_ms = 0;
12509 unsigned timeout = 0;
12514 while ((i = nextopt("p:u:r"
12515 IF_ASH_READ_TIMEOUT("t:")
12516 IF_ASH_READ_NCHARS("n:s")
12520 prompt = optionarg;
12522 #if ENABLE_ASH_READ_NCHARS
12524 nchars = bb_strtou(optionarg, NULL, 10);
12525 if (nchars < 0 || errno)
12526 ash_msg_and_raise_error("invalid count");
12527 /* nchars == 0: off (bash 3.2 does this too) */
12533 #if ENABLE_ASH_READ_TIMEOUT
12535 timeout = bb_strtou(optionarg, NULL, 10);
12536 if (errno || timeout > UINT_MAX / 2048)
12537 ash_msg_and_raise_error("invalid timeout");
12539 #if 0 /* even bash have no -t N.NNN support */
12540 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12542 /* EINVAL means number is ok, but not terminated by NUL */
12543 if (*p == '.' && errno == EINVAL) {
12547 ts.tv_usec = bb_strtou(p, &p2, 10);
12549 ash_msg_and_raise_error("invalid timeout");
12551 /* normalize to usec */
12553 ash_msg_and_raise_error("invalid timeout");
12554 while (scale++ < 6)
12557 } else if (ts.tv_sec < 0 || errno) {
12558 ash_msg_and_raise_error("invalid timeout");
12560 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12561 ash_msg_and_raise_error("invalid timeout");
12570 fd = bb_strtou(optionarg, NULL, 10);
12571 if (fd < 0 || errno)
12572 ash_msg_and_raise_error("invalid file descriptor");
12578 if (prompt && isatty(fd)) {
12583 ap = (char**)arg_REPLY;
12584 ifs = bltinlookup("IFS");
12587 #if ENABLE_ASH_READ_NCHARS
12588 tcgetattr(fd, &tty);
12590 if (nchars || silent) {
12592 tty.c_lflag &= ~ICANON;
12593 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12596 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12598 /* if tcgetattr failed, tcsetattr will fail too.
12599 * Ignoring, it's harmless. */
12600 tcsetattr(fd, TCSANOW, &tty);
12607 #if ENABLE_ASH_READ_TIMEOUT
12608 if (timeout) /* NB: ensuring end_ms is nonzero */
12609 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12613 const char *is_ifs;
12615 #if ENABLE_ASH_READ_TIMEOUT
12617 struct pollfd pfd[1];
12619 pfd[0].events = POLLIN;
12620 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12621 if ((int)timeout <= 0 /* already late? */
12622 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12623 ) { /* timed out! */
12624 #if ENABLE_ASH_READ_NCHARS
12625 tcsetattr(fd, TCSANOW, &old_tty);
12631 if (nonblock_safe_read(fd, &c, 1) != 1) {
12643 if (!rflag && c == '\\') {
12649 /* $IFS splitting */
12650 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12651 is_ifs = strchr(ifs, c);
12652 if (startword && is_ifs) {
12655 /* it is a non-space ifs char */
12657 if (startword == 1) /* first one? */
12658 continue; /* yes, it is not next word yet */
12661 if (ap[1] != NULL && is_ifs) {
12664 beg = stackblock();
12665 setvar(*ap, beg, 0);
12667 /* can we skip one non-space ifs char? (2: yes) */
12668 startword = isspace(c) ? 2 : 1;
12675 /* end of do {} while: */
12676 #if ENABLE_ASH_READ_NCHARS
12682 #if ENABLE_ASH_READ_NCHARS
12683 tcsetattr(fd, TCSANOW, &old_tty);
12687 /* Remove trailing space ifs chars */
12688 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12690 setvar(*ap, stackblock(), 0);
12691 while (*++ap != NULL)
12692 setvar(*ap, nullstr, 0);
12696 static int FAST_FUNC
12697 umaskcmd(int argc UNUSED_PARAM, char **argv)
12699 static const char permuser[3] ALIGN1 = "ugo";
12700 static const char permmode[3] ALIGN1 = "rwx";
12701 static const short permmask[] ALIGN2 = {
12702 S_IRUSR, S_IWUSR, S_IXUSR,
12703 S_IRGRP, S_IWGRP, S_IXGRP,
12704 S_IROTH, S_IWOTH, S_IXOTH
12707 /* TODO: use bb_parse_mode() instead */
12712 int symbolic_mode = 0;
12714 while (nextopt("S") != '\0') {
12725 if (symbolic_mode) {
12729 for (i = 0; i < 3; i++) {
12732 *p++ = permuser[i];
12734 for (j = 0; j < 3; j++) {
12735 if ((mask & permmask[3 * i + j]) == 0) {
12736 *p++ = permmode[j];
12744 out1fmt("%.4o\n", mask);
12747 if (isdigit((unsigned char) *ap)) {
12750 if (*ap >= '8' || *ap < '0')
12751 ash_msg_and_raise_error(msg_illnum, argv[1]);
12752 mask = (mask << 3) + (*ap - '0');
12753 } while (*++ap != '\0');
12756 mask = ~mask & 0777;
12757 if (!bb_parse_mode(ap, &mask)) {
12758 ash_msg_and_raise_error("illegal mode: %s", ap);
12760 umask(~mask & 0777);
12769 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12770 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12771 * ash by J.T. Conklin.
12776 uint8_t cmd; /* RLIMIT_xxx fit into it */
12777 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12781 static const struct limits limits_tbl[] = {
12783 { RLIMIT_CPU, 0, 't' },
12785 #ifdef RLIMIT_FSIZE
12786 { RLIMIT_FSIZE, 9, 'f' },
12789 { RLIMIT_DATA, 10, 'd' },
12791 #ifdef RLIMIT_STACK
12792 { RLIMIT_STACK, 10, 's' },
12795 { RLIMIT_CORE, 9, 'c' },
12798 { RLIMIT_RSS, 10, 'm' },
12800 #ifdef RLIMIT_MEMLOCK
12801 { RLIMIT_MEMLOCK, 10, 'l' },
12803 #ifdef RLIMIT_NPROC
12804 { RLIMIT_NPROC, 0, 'p' },
12806 #ifdef RLIMIT_NOFILE
12807 { RLIMIT_NOFILE, 0, 'n' },
12810 { RLIMIT_AS, 10, 'v' },
12812 #ifdef RLIMIT_LOCKS
12813 { RLIMIT_LOCKS, 0, 'w' },
12816 static const char limits_name[] =
12818 "time(seconds)" "\0"
12820 #ifdef RLIMIT_FSIZE
12821 "file(blocks)" "\0"
12826 #ifdef RLIMIT_STACK
12830 "coredump(blocks)" "\0"
12835 #ifdef RLIMIT_MEMLOCK
12836 "locked memory(kb)" "\0"
12838 #ifdef RLIMIT_NPROC
12841 #ifdef RLIMIT_NOFILE
12847 #ifdef RLIMIT_LOCKS
12852 enum limtype { SOFT = 0x1, HARD = 0x2 };
12855 printlim(enum limtype how, const struct rlimit *limit,
12856 const struct limits *l)
12860 val = limit->rlim_max;
12862 val = limit->rlim_cur;
12864 if (val == RLIM_INFINITY)
12865 out1fmt("unlimited\n");
12867 val >>= l->factor_shift;
12868 out1fmt("%lld\n", (long long) val);
12872 static int FAST_FUNC
12873 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12876 enum limtype how = SOFT | HARD;
12877 const struct limits *l;
12880 struct rlimit limit;
12883 while ((optc = nextopt("HSa"
12887 #ifdef RLIMIT_FSIZE
12893 #ifdef RLIMIT_STACK
12902 #ifdef RLIMIT_MEMLOCK
12905 #ifdef RLIMIT_NPROC
12908 #ifdef RLIMIT_NOFILE
12914 #ifdef RLIMIT_LOCKS
12932 for (l = limits_tbl; l->option != what; l++)
12935 set = *argptr ? 1 : 0;
12940 if (all || argptr[1])
12941 ash_msg_and_raise_error("too many arguments");
12942 if (strncmp(p, "unlimited\n", 9) == 0)
12943 val = RLIM_INFINITY;
12945 if (sizeof(val) == sizeof(int))
12946 val = bb_strtou(p, NULL, 10);
12947 else if (sizeof(val) == sizeof(long))
12948 val = bb_strtoul(p, NULL, 10);
12950 val = bb_strtoull(p, NULL, 10);
12952 ash_msg_and_raise_error("bad number");
12953 val <<= l->factor_shift;
12957 const char *lname = limits_name;
12958 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12959 getrlimit(l->cmd, &limit);
12960 out1fmt("%-20s ", lname);
12961 lname += strlen(lname) + 1;
12962 printlim(how, &limit, l);
12967 getrlimit(l->cmd, &limit);
12970 limit.rlim_max = val;
12972 limit.rlim_cur = val;
12973 if (setrlimit(l->cmd, &limit) < 0)
12974 ash_msg_and_raise_error("error setting limit (%m)");
12976 printlim(how, &limit, l);
12981 /* ============ main() and helpers */
12984 * Called to exit the shell.
12986 static void exitshell(void) NORETURN;
12994 status = exitstatus;
12995 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12996 if (setjmp(loc.loc)) {
12997 if (exception_type == EXEXIT)
12998 /* dash bug: it just does _exit(exitstatus) here
12999 * but we have to do setjobctl(0) first!
13000 * (bug is still not fixed in dash-0.5.3 - if you run dash
13001 * under Midnight Commander, on exit from dash MC is backgrounded) */
13002 status = exitstatus;
13005 exception_handler = &loc;
13012 flush_stdout_stderr();
13022 /* from input.c: */
13023 basepf.next_to_pgetc = basepf.buf = basebuf;
13026 signal(SIGCHLD, SIG_DFL);
13032 struct stat st1, st2;
13035 for (envp = environ; envp && *envp; envp++) {
13036 if (strchr(*envp, '=')) {
13037 setvareq(*envp, VEXPORT|VTEXTFIXED);
13041 setvar("PPID", utoa(getppid()), 0);
13043 p = lookupvar("PWD");
13045 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13046 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13053 * Process the shell command line arguments.
13056 procargs(char **argv)
13059 const char *xminusc;
13064 /* if (xargv[0]) - mmm, this is always true! */
13066 for (i = 0; i < NOPTS; i++)
13070 /* it already printed err message */
13071 raise_exception(EXERROR);
13075 if (*xargv == NULL) {
13077 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13080 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13084 for (i = 0; i < NOPTS; i++)
13085 if (optlist[i] == 2)
13090 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13095 } else if (!sflag) {
13096 setinputfile(*xargv, 0);
13099 commandname = arg0;
13102 shellparam.p = xargv;
13103 #if ENABLE_ASH_GETOPTS
13104 shellparam.optind = 1;
13105 shellparam.optoff = -1;
13107 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13109 shellparam.nparam++;
13116 * Read /etc/profile or .profile.
13119 read_profile(const char *name)
13123 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13132 * This routine is called when an error or an interrupt occurs in an
13133 * interactive shell and control is returned to the main command loop.
13141 /* from input.c: */
13142 g_parsefile->left_in_buffer = 0;
13143 g_parsefile->left_in_line = 0; /* clear input buffer */
13145 /* from parser.c: */
13148 /* from redir.c: */
13149 clearredir(/*drop:*/ 0);
13153 static short profile_buf[16384];
13154 extern int etext();
13158 * Main routine. We initialize things, parse the arguments, execute
13159 * profiles if we're a login shell, and then call cmdloop to execute
13160 * commands. The setjmp call sets up the location to jump to when an
13161 * exception occurs. When an exception occurs the variable "state"
13162 * is used to figure out how far we had gotten.
13164 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13165 int ash_main(int argc UNUSED_PARAM, char **argv)
13167 const char *shinit;
13168 volatile smallint state;
13169 struct jmploc jmploc;
13170 struct stackmark smark;
13172 /* Initialize global data */
13176 #if ENABLE_ASH_ALIAS
13182 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13185 #if ENABLE_FEATURE_EDITING
13186 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13189 if (setjmp(jmploc.loc)) {
13195 e = exception_type;
13199 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13202 outcslow('\n', stderr);
13204 popstackmark(&smark);
13205 FORCE_INT_ON; /* enable interrupts */
13214 exception_handler = &jmploc;
13217 TRACE(("Shell args: "));
13218 trace_puts_args(argv);
13220 rootpid = getpid();
13223 setstackmark(&smark);
13226 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13228 const char *hp = lookupvar("HISTFILE");
13231 hp = lookupvar("HOME");
13233 char *defhp = concat_path_file(hp, ".ash_history");
13234 setvar("HISTFILE", defhp, 0);
13240 if (/* argv[0] && */ argv[0][0] == '-')
13244 read_profile("/etc/profile");
13247 read_profile(".profile");
13253 getuid() == geteuid() && getgid() == getegid() &&
13257 shinit = lookupvar("ENV");
13258 if (shinit != NULL && *shinit != '\0') {
13259 read_profile(shinit);
13265 /* evalstring pushes parsefile stack.
13266 * Ensure we don't falsely claim that 0 (stdin)
13267 * is one of stacked source fds.
13268 * Testcase: ash -c 'exec 1>&0' must not complain. */
13270 g_parsefile->fd = -1;
13271 evalstring(minusc, 0);
13274 if (sflag || minusc == NULL) {
13275 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13277 const char *hp = lookupvar("HISTFILE");
13279 line_input_state->hist_file = hp;
13282 state4: /* XXX ??? - why isn't this before the "if" statement */
13290 extern void _mcleanup(void);
13300 * Copyright (c) 1989, 1991, 1993, 1994
13301 * The Regents of the University of California. All rights reserved.
13303 * This code is derived from software contributed to Berkeley by
13304 * Kenneth Almquist.
13306 * Redistribution and use in source and binary forms, with or without
13307 * modification, are permitted provided that the following conditions
13309 * 1. Redistributions of source code must retain the above copyright
13310 * notice, this list of conditions and the following disclaimer.
13311 * 2. Redistributions in binary form must reproduce the above copyright
13312 * notice, this list of conditions and the following disclaimer in the
13313 * documentation and/or other materials provided with the distribution.
13314 * 3. Neither the name of the University nor the names of its contributors
13315 * may be used to endorse or promote products derived from this software
13316 * without specific prior written permission.
13318 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13319 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13320 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13321 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13322 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13323 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13324 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13325 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13326 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13327 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF