1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
31 /* Tweak debug output verbosity here */
35 #define DEBUG_INTONOFF 0
39 #define JOBS ENABLE_ASH_JOB_CONTROL
43 #include <sys/times.h>
44 #include <sys/utsname.h> /* for setting $HOSTNAME */
46 #include "busybox.h" /* for applet_names */
48 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
49 /* Bionic at least up to version 24 has no glob() */
50 # undef ENABLE_ASH_INTERNAL_GLOB
51 # define ENABLE_ASH_INTERNAL_GLOB 1
54 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
55 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
56 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
57 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
58 # error glob() should unbackslash them and match. uClibc does not unbackslash,
59 # error fails to match dirname, subsequently not expanding <pattern> in it.
61 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
62 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
65 #if !ENABLE_ASH_INTERNAL_GLOB
70 #include "shell_common.h"
71 #if ENABLE_SH_MATH_SUPPORT
74 #if ENABLE_ASH_RANDOM_SUPPORT
77 # define CLEAR_RANDOM_T(rnd) ((void)0)
80 #include "NUM_APPLETS.h"
82 /* STANDALONE does not make sense, and won't compile */
83 # undef CONFIG_FEATURE_SH_STANDALONE
84 # undef ENABLE_FEATURE_SH_STANDALONE
85 # undef IF_FEATURE_SH_STANDALONE
86 # undef IF_NOT_FEATURE_SH_STANDALONE
87 # define ENABLE_FEATURE_SH_STANDALONE 0
88 # define IF_FEATURE_SH_STANDALONE(...)
89 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
93 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
97 # error "Do not even bother, ash will not run on NOMMU machine"
103 //config: depends on !NOMMU
105 //config: Tha 'ash' shell adds about 60k in the default configuration and is
106 //config: the most complete and most pedantically correct shell included with
107 //config: busybox. This shell is actually a derivative of the Debian 'dash'
108 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
109 //config: (written by Kenneth Almquist) from NetBSD.
111 //config:config ASH_OPTIMIZE_FOR_SIZE
112 //config: bool "Optimize for size instead of speed"
114 //config: depends on ASH
116 //config: Compile ash for reduced size at the price of speed.
118 //config:config ASH_INTERNAL_GLOB
119 //config: bool "Use internal glob() implementation"
121 //config: depends on ASH
123 //config: Do not use glob() function from libc, use internal implementation.
124 //config: Use this if you are getting "glob.h: No such file or directory"
125 //config: or similar build errors.
127 //config:config ASH_RANDOM_SUPPORT
128 //config: bool "Pseudorandom generator and $RANDOM variable"
130 //config: depends on ASH
132 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
133 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
134 //config: You can reset the generator by using a specified start value.
135 //config: After "unset RANDOM" the generator will switch off and this
136 //config: variable will no longer have special treatment.
138 //config:config ASH_EXPAND_PRMT
139 //config: bool "Expand prompt string"
141 //config: depends on ASH
143 //config: "PS#" may contain volatile content, such as backquote commands.
144 //config: This option recreates the prompt string from the environment
145 //config: variable each time it is displayed.
147 //config:config ASH_BASH_COMPAT
148 //config: bool "bash-compatible extensions"
150 //config: depends on ASH
152 //config: Enable bash-compatible extensions.
154 //config:config ASH_IDLE_TIMEOUT
155 //config: bool "Idle timeout variable"
157 //config: depends on ASH
159 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
161 //config:config ASH_JOB_CONTROL
162 //config: bool "Job control"
164 //config: depends on ASH
166 //config: Enable job control in the ash shell.
168 //config:config ASH_ALIAS
169 //config: bool "Alias support"
171 //config: depends on ASH
173 //config: Enable alias support in the ash shell.
175 //config:config ASH_GETOPTS
176 //config: bool "Builtin getopt to parse positional parameters"
178 //config: depends on ASH
180 //config: Enable support for getopts builtin in ash.
182 //config:config ASH_BUILTIN_ECHO
183 //config: bool "Builtin version of 'echo'"
185 //config: depends on ASH
187 //config: Enable support for echo builtin in ash.
189 //config:config ASH_BUILTIN_PRINTF
190 //config: bool "Builtin version of 'printf'"
192 //config: depends on ASH
194 //config: Enable support for printf builtin in ash.
196 //config:config ASH_BUILTIN_TEST
197 //config: bool "Builtin version of 'test'"
199 //config: depends on ASH
201 //config: Enable support for test builtin in ash.
203 //config:config ASH_HELP
204 //config: bool "help builtin"
206 //config: depends on ASH
208 //config: Enable help builtin in ash.
210 //config:config ASH_CMDCMD
211 //config: bool "'command' command to override shell builtins"
213 //config: depends on ASH
215 //config: Enable support for the ash 'command' builtin, which allows
216 //config: you to run the specified command with the specified arguments,
217 //config: even when there is an ash builtin command with the same name.
219 //config:config ASH_MAIL
220 //config: bool "Check for new mail on interactive shells"
222 //config: depends on ASH
224 //config: Enable "check for new mail" function in the ash shell.
227 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
228 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
229 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
231 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
232 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
235 /* ============ Hash table sizes. Configurable. */
239 #define CMDTABLESIZE 31 /* should be prime */
242 /* ============ Shell options */
244 static const char *const optletters_optnames[] = {
259 #if ENABLE_ASH_BASH_COMPAT
268 #define optletters(n) optletters_optnames[n][0]
269 #define optnames(n) (optletters_optnames[n] + 1)
271 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
274 /* ============ Misc data */
276 #define msg_illnum "Illegal number: %s"
279 * We enclose jmp_buf in a structure so that we can declare pointers to
280 * jump locations. The global variable handler contains the location to
281 * jump to when an exception occurs, and the global variable exception_type
282 * contains a code identifying the exception. To implement nested
283 * exception handlers, the user should save the value of handler on entry
284 * to an inner scope, set handler to point to a jmploc structure for the
285 * inner scope, and restore handler on exit from the scope.
291 struct globals_misc {
292 uint8_t exitstatus; /* exit status of last command */
293 uint8_t back_exitstatus;/* exit status of backquoted command */
294 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
295 int rootpid; /* pid of main shell */
296 /* shell level: 0 for the main shell, 1 for its children, and so on */
298 #define rootshell (!shlvl)
299 char *minusc; /* argument to -c option */
301 char *curdir; // = nullstr; /* current working directory */
302 char *physdir; // = nullstr; /* physical working directory */
304 char *arg0; /* value of $0 */
306 struct jmploc *exception_handler;
308 volatile int suppress_int; /* counter */
309 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
310 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
311 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
312 smallint exception_type; /* kind of exception (0..5) */
314 #define EXINT 0 /* SIGINT received */
315 #define EXERROR 1 /* a generic error */
316 #define EXEXIT 4 /* exit the shell */
319 char nullstr[1]; /* zero length string */
322 #define eflag optlist[0]
323 #define fflag optlist[1]
324 #define Iflag optlist[2]
325 #define iflag optlist[3]
326 #define mflag optlist[4]
327 #define nflag optlist[5]
328 #define sflag optlist[6]
329 #define xflag optlist[7]
330 #define vflag optlist[8]
331 #define Cflag optlist[9]
332 #define aflag optlist[10]
333 #define bflag optlist[11]
334 #define uflag optlist[12]
335 #define viflag optlist[13]
336 #if ENABLE_ASH_BASH_COMPAT
337 # define pipefail optlist[14]
342 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
343 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
346 /* trap handler commands */
348 * Sigmode records the current value of the signal handlers for the various
349 * modes. A value of zero means that the current handler is not known.
350 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
352 char sigmode[NSIG - 1];
353 #define S_DFL 1 /* default signal handling (SIG_DFL) */
354 #define S_CATCH 2 /* signal is caught */
355 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
356 #define S_HARD_IGN 4 /* signal is ignored permanently */
358 /* indicates specified signal received */
359 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
360 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
362 char **trap_ptr; /* used only by "trap hack" */
364 /* Rarely referenced stuff */
365 #if ENABLE_ASH_RANDOM_SUPPORT
368 pid_t backgndpid; /* pid of last background process */
370 extern struct globals_misc *const ash_ptr_to_globals_misc;
371 #define G_misc (*ash_ptr_to_globals_misc)
372 #define exitstatus (G_misc.exitstatus )
373 #define back_exitstatus (G_misc.back_exitstatus )
374 #define job_warning (G_misc.job_warning)
375 #define rootpid (G_misc.rootpid )
376 #define shlvl (G_misc.shlvl )
377 #define minusc (G_misc.minusc )
378 #define curdir (G_misc.curdir )
379 #define physdir (G_misc.physdir )
380 #define arg0 (G_misc.arg0 )
381 #define exception_handler (G_misc.exception_handler)
382 #define exception_type (G_misc.exception_type )
383 #define suppress_int (G_misc.suppress_int )
384 #define pending_int (G_misc.pending_int )
385 #define got_sigchld (G_misc.got_sigchld )
386 #define pending_sig (G_misc.pending_sig )
387 #define isloginsh (G_misc.isloginsh )
388 #define nullstr (G_misc.nullstr )
389 #define optlist (G_misc.optlist )
390 #define sigmode (G_misc.sigmode )
391 #define gotsig (G_misc.gotsig )
392 #define may_have_traps (G_misc.may_have_traps )
393 #define trap (G_misc.trap )
394 #define trap_ptr (G_misc.trap_ptr )
395 #define random_gen (G_misc.random_gen )
396 #define backgndpid (G_misc.backgndpid )
397 #define INIT_G_misc() do { \
398 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
406 /* ============ DEBUG */
408 static void trace_printf(const char *fmt, ...);
409 static void trace_vprintf(const char *fmt, va_list va);
410 # define TRACE(param) trace_printf param
411 # define TRACEV(param) trace_vprintf param
412 # define close(fd) do { \
414 if (close(dfd) < 0) \
415 bb_error_msg("bug on %d: closing %d(0x%x)", \
416 __LINE__, dfd, dfd); \
419 # define TRACE(param)
420 # define TRACEV(param)
424 /* ============ Utility functions */
425 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
426 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
429 isdigit_str9(const char *str)
431 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
432 while (--maxlen && isdigit(*str))
434 return (*str == '\0');
438 var_end(const char *var)
447 /* ============ Interrupts / exceptions */
449 static void exitshell(void) NORETURN;
452 * These macros allow the user to suspend the handling of interrupt signals
453 * over a period of time. This is similar to SIGHOLD or to sigblock, but
454 * much more efficient and portable. (But hacking the kernel is so much
455 * more fun than worrying about efficiency and portability. :-))
458 # define INT_OFF do { \
459 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
464 # define INT_OFF do { \
471 * Called to raise an exception. Since C doesn't include exceptions, we
472 * just do a longjmp to the exception handler. The type of exception is
473 * stored in the global variable "exception_type".
475 static void raise_exception(int) NORETURN;
477 raise_exception(int e)
480 if (exception_handler == NULL)
485 longjmp(exception_handler->loc, 1);
488 #define raise_exception(e) do { \
489 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
490 raise_exception(e); \
495 * Called when a SIGINT is received. (If the user specifies
496 * that SIGINT is to be trapped or ignored using the trap builtin, then
497 * this routine is not called.) Suppressint is nonzero when interrupts
498 * are held using the INT_OFF macro. (The test for iflag is just
499 * defensive programming.)
501 static void raise_interrupt(void) NORETURN;
503 raise_interrupt(void)
506 /* Signal is not automatically unmasked after it is raised,
507 * do it ourself - unmask all signals */
508 sigprocmask_allsigs(SIG_UNBLOCK);
509 /* pending_sig = 0; - now done in signal_handler() */
511 if (!(rootshell && iflag)) {
512 /* Kill ourself with SIGINT */
513 signal(SIGINT, SIG_DFL);
516 /* bash: ^C even on empty command line sets $? */
517 exitstatus = SIGINT + 128;
518 raise_exception(EXINT);
522 #define raise_interrupt() do { \
523 TRACE(("raising interrupt on line %d\n", __LINE__)); \
528 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
532 if (--suppress_int == 0 && pending_int) {
537 # define INT_ON do { \
538 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
542 # define INT_ON int_on()
544 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
552 #define FORCE_INT_ON force_int_on()
554 #define SAVE_INT(v) ((v) = suppress_int)
556 #define RESTORE_INT(v) do { \
558 suppress_int = (v); \
559 if (suppress_int == 0 && pending_int) \
564 /* ============ Stdout/stderr output */
567 outstr(const char *p, FILE *file)
575 flush_stdout_stderr(void)
582 /* Was called outcslow(c,FILE*), but c was always '\n' */
584 newline_and_flush(FILE *dest)
592 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
594 out1fmt(const char *fmt, ...)
601 r = vprintf(fmt, ap);
607 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
609 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
616 ret = vsnprintf(outbuf, length, fmt, ap);
623 out1str(const char *p)
629 out2str(const char *p)
632 flush_stdout_stderr();
636 /* ============ Parser structures */
638 /* control characters in argument strings */
639 #define CTL_FIRST CTLESC
640 #define CTLESC ((unsigned char)'\201') /* escape next character */
641 #define CTLVAR ((unsigned char)'\202') /* variable defn */
642 #define CTLENDVAR ((unsigned char)'\203')
643 #define CTLBACKQ ((unsigned char)'\204')
644 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
645 #define CTLENDARI ((unsigned char)'\207')
646 #define CTLQUOTEMARK ((unsigned char)'\210')
647 #define CTL_LAST CTLQUOTEMARK
649 /* variable substitution byte (follows CTLVAR) */
650 #define VSTYPE 0x0f /* type of variable substitution */
651 #define VSNUL 0x10 /* colon--treat the empty string as unset */
653 /* values of VSTYPE field */
654 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
655 #define VSMINUS 0x2 /* ${var-text} */
656 #define VSPLUS 0x3 /* ${var+text} */
657 #define VSQUESTION 0x4 /* ${var?message} */
658 #define VSASSIGN 0x5 /* ${var=text} */
659 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
660 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
661 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
662 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
663 #define VSLENGTH 0xa /* ${#var} */
664 #if ENABLE_ASH_BASH_COMPAT
665 #define VSSUBSTR 0xc /* ${var:position:length} */
666 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
667 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
670 static const char dolatstr[] ALIGN1 = {
671 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
673 #define DOLATSTRLEN 6
692 #if ENABLE_ASH_BASH_COMPAT
709 smallint type; /* Nxxxx */
712 union node *redirect;
717 smallint pipe_backgnd;
718 struct nodelist *cmdlist;
724 union node *redirect;
737 union node *elsepart;
764 struct nodelist *backquote;
767 /* nfile and ndup layout must match!
768 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
769 * that it is actually NTO2 (>&file), and change its type.
786 char *_unused_expfname;
805 struct nredir nredir;
806 struct nbinary nbinary;
810 struct nclist nclist;
819 * NODE_EOF is returned by parsecmd when it encounters an end of file.
820 * It must be distinct from NULL.
822 #define NODE_EOF ((union node *) -1L)
825 struct nodelist *next;
838 freefunc(struct funcnode *f)
840 if (f && --f->count < 0)
845 /* ============ Debugging output */
849 static FILE *tracefile;
852 trace_printf(const char *fmt, ...)
859 fprintf(tracefile, "%u ", (int) time(NULL));
861 fprintf(tracefile, "[%u] ", (int) getpid());
863 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
865 vfprintf(tracefile, fmt, va);
870 trace_vprintf(const char *fmt, va_list va)
874 vfprintf(tracefile, fmt, va);
875 fprintf(tracefile, "\n");
879 trace_puts(const char *s)
887 trace_puts_quoted(char *s)
894 putc('"', tracefile);
895 for (p = s; *p; p++) {
896 switch ((unsigned char)*p) {
897 case '\n': c = 'n'; goto backslash;
898 case '\t': c = 't'; goto backslash;
899 case '\r': c = 'r'; goto backslash;
900 case '\"': c = '\"'; goto backslash;
901 case '\\': c = '\\'; goto backslash;
902 case CTLESC: c = 'e'; goto backslash;
903 case CTLVAR: c = 'v'; goto backslash;
904 case CTLBACKQ: c = 'q'; goto backslash;
906 putc('\\', tracefile);
910 if (*p >= ' ' && *p <= '~')
913 putc('\\', tracefile);
914 putc((*p >> 6) & 03, tracefile);
915 putc((*p >> 3) & 07, tracefile);
916 putc(*p & 07, tracefile);
921 putc('"', tracefile);
925 trace_puts_args(char **ap)
932 trace_puts_quoted(*ap);
934 putc('\n', tracefile);
937 putc(' ', tracefile);
952 /* leave open because libedit might be using it */
955 strcpy(s, "./trace");
957 if (!freopen(s, "a", tracefile)) {
958 fprintf(stderr, "Can't re-open %s\n", s);
963 tracefile = fopen(s, "a");
964 if (tracefile == NULL) {
965 fprintf(stderr, "Can't open %s\n", s);
971 flags = fcntl(fileno(tracefile), F_GETFL);
973 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
975 setlinebuf(tracefile);
976 fputs("\nTracing started.\n", tracefile);
980 indent(int amount, char *pfx, FILE *fp)
984 for (i = 0; i < amount; i++) {
985 if (pfx && i == amount - 1)
991 /* little circular references here... */
992 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
995 sharg(union node *arg, FILE *fp)
998 struct nodelist *bqlist;
999 unsigned char subtype;
1001 if (arg->type != NARG) {
1002 out1fmt("<node type %d>\n", arg->type);
1005 bqlist = arg->narg.backquote;
1006 for (p = arg->narg.text; *p; p++) {
1007 switch ((unsigned char)*p) {
1016 if (subtype == VSLENGTH)
1024 if (subtype & VSNUL)
1027 switch (subtype & VSTYPE) {
1053 case VSTRIMRIGHTMAX:
1060 out1fmt("<subtype %d>", subtype);
1069 shtree(bqlist->n, -1, NULL, fp);
1080 shcmd(union node *cmd, FILE *fp)
1088 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1094 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1098 switch (np->nfile.type) {
1099 case NTO: s = ">>"+1; dftfd = 1; break;
1100 case NCLOBBER: s = ">|"; dftfd = 1; break;
1101 case NAPPEND: s = ">>"; dftfd = 1; break;
1102 #if ENABLE_ASH_BASH_COMPAT
1105 case NTOFD: s = ">&"; dftfd = 1; break;
1106 case NFROM: s = "<"; break;
1107 case NFROMFD: s = "<&"; break;
1108 case NFROMTO: s = "<>"; break;
1109 default: s = "*error*"; break;
1111 if (np->nfile.fd != dftfd)
1112 fprintf(fp, "%d", np->nfile.fd);
1114 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1115 fprintf(fp, "%d", np->ndup.dupfd);
1117 sharg(np->nfile.fname, fp);
1124 shtree(union node *n, int ind, char *pfx, FILE *fp)
1126 struct nodelist *lp;
1132 indent(ind, pfx, fp);
1134 if (n == NODE_EOF) {
1149 shtree(n->nbinary.ch1, ind, NULL, fp);
1152 shtree(n->nbinary.ch2, ind, NULL, fp);
1160 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1161 shtree(lp->n, 0, NULL, fp);
1165 if (n->npipe.pipe_backgnd)
1171 fprintf(fp, "<node type %d>", n->type);
1179 showtree(union node *n)
1181 trace_puts("showtree called\n");
1182 shtree(n, 1, NULL, stderr);
1188 /* ============ Parser data */
1191 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1194 struct strlist *next;
1201 struct strpush *prev; /* preceding string on stack */
1203 int prev_left_in_line;
1204 #if ENABLE_ASH_ALIAS
1205 struct alias *ap; /* if push was associated with an alias */
1207 char *string; /* remember the string since it may change */
1209 /* Remember last two characters for pungetc. */
1212 /* Number of outstanding calls to pungetc. */
1217 struct parsefile *prev; /* preceding file on stack */
1218 int linno; /* current line */
1219 int pf_fd; /* file descriptor (or -1 if string) */
1220 int left_in_line; /* number of chars left in this line */
1221 int left_in_buffer; /* number of chars left in this buffer past the line */
1222 char *next_to_pgetc; /* next char in buffer */
1223 char *buf; /* input buffer */
1224 struct strpush *strpush; /* for pushing strings at this level */
1225 struct strpush basestrpush; /* so pushing one is fast */
1227 /* Remember last two characters for pungetc. */
1230 /* Number of outstanding calls to pungetc. */
1234 static struct parsefile basepf; /* top level input file */
1235 static struct parsefile *g_parsefile = &basepf; /* current input file */
1236 static int startlinno; /* line # where last token started */
1237 static char *commandname; /* currently executing command */
1238 static struct strlist *cmdenviron; /* environment for builtin command */
1241 /* ============ Message printing */
1244 ash_vmsg(const char *msg, va_list ap)
1246 fprintf(stderr, "%s: ", arg0);
1248 if (strcmp(arg0, commandname))
1249 fprintf(stderr, "%s: ", commandname);
1250 if (!iflag || g_parsefile->pf_fd > 0)
1251 fprintf(stderr, "line %d: ", startlinno);
1253 vfprintf(stderr, msg, ap);
1254 newline_and_flush(stderr);
1258 * Exverror is called to raise the error exception. If the second argument
1259 * is not NULL then error prints an error message using printf style
1260 * formatting. It then raises the error exception.
1262 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1264 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1268 TRACE(("ash_vmsg_and_raise(%d):", cond));
1271 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1276 flush_stdout_stderr();
1277 raise_exception(cond);
1281 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1283 ash_msg_and_raise_error(const char *msg, ...)
1288 ash_vmsg_and_raise(EXERROR, msg, ap);
1293 static void raise_error_syntax(const char *) NORETURN;
1295 raise_error_syntax(const char *msg)
1297 ash_msg_and_raise_error("syntax error: %s", msg);
1301 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1303 ash_msg_and_raise(int cond, const char *msg, ...)
1308 ash_vmsg_and_raise(cond, msg, ap);
1314 * error/warning routines for external builtins
1317 ash_msg(const char *fmt, ...)
1327 * Return a string describing an error. The returned string may be a
1328 * pointer to a static buffer that will be overwritten on the next call.
1329 * Action describes the operation that got the error.
1332 errmsg(int e, const char *em)
1334 if (e == ENOENT || e == ENOTDIR) {
1341 /* ============ Memory allocation */
1344 /* I consider these wrappers nearly useless:
1345 * ok, they return you to nearest exception handler, but
1346 * how much memory do you leak in the process, making
1347 * memory starvation worse?
1350 ckrealloc(void * p, size_t nbytes)
1352 p = realloc(p, nbytes);
1354 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1359 ckmalloc(size_t nbytes)
1361 return ckrealloc(NULL, nbytes);
1365 ckzalloc(size_t nbytes)
1367 return memset(ckmalloc(nbytes), 0, nbytes);
1371 ckstrdup(const char *s)
1373 char *p = strdup(s);
1375 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1379 /* Using bbox equivalents. They exit if out of memory */
1380 # define ckrealloc xrealloc
1381 # define ckmalloc xmalloc
1382 # define ckzalloc xzalloc
1383 # define ckstrdup xstrdup
1387 * It appears that grabstackstr() will barf with such alignments
1388 * because stalloc() will return a string allocated in a new stackblock.
1390 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1392 /* Most machines require the value returned from malloc to be aligned
1393 * in some way. The following macro will get this right
1394 * on many machines. */
1395 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1396 /* Minimum size of a block */
1397 MINSIZE = SHELL_ALIGN(504),
1400 struct stack_block {
1401 struct stack_block *prev;
1402 char space[MINSIZE];
1406 struct stack_block *stackp;
1412 struct globals_memstack {
1413 struct stack_block *g_stackp; // = &stackbase;
1414 char *g_stacknxt; // = stackbase.space;
1415 char *sstrend; // = stackbase.space + MINSIZE;
1416 size_t g_stacknleft; // = MINSIZE;
1417 struct stack_block stackbase;
1419 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1420 #define G_memstack (*ash_ptr_to_globals_memstack)
1421 #define g_stackp (G_memstack.g_stackp )
1422 #define g_stacknxt (G_memstack.g_stacknxt )
1423 #define sstrend (G_memstack.sstrend )
1424 #define g_stacknleft (G_memstack.g_stacknleft)
1425 #define stackbase (G_memstack.stackbase )
1426 #define INIT_G_memstack() do { \
1427 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1429 g_stackp = &stackbase; \
1430 g_stacknxt = stackbase.space; \
1431 g_stacknleft = MINSIZE; \
1432 sstrend = stackbase.space + MINSIZE; \
1436 #define stackblock() ((void *)g_stacknxt)
1437 #define stackblocksize() g_stacknleft
1440 * Parse trees for commands are allocated in lifo order, so we use a stack
1441 * to make this more efficient, and also to avoid all sorts of exception
1442 * handling code to handle interrupts in the middle of a parse.
1444 * The size 504 was chosen because the Ultrix malloc handles that size
1448 stalloc(size_t nbytes)
1453 aligned = SHELL_ALIGN(nbytes);
1454 if (aligned > g_stacknleft) {
1457 struct stack_block *sp;
1459 blocksize = aligned;
1460 if (blocksize < MINSIZE)
1461 blocksize = MINSIZE;
1462 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1463 if (len < blocksize)
1464 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1467 sp->prev = g_stackp;
1468 g_stacknxt = sp->space;
1469 g_stacknleft = blocksize;
1470 sstrend = g_stacknxt + blocksize;
1475 g_stacknxt += aligned;
1476 g_stacknleft -= aligned;
1481 stzalloc(size_t nbytes)
1483 return memset(stalloc(nbytes), 0, nbytes);
1490 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1491 write(STDERR_FILENO, "stunalloc\n", 10);
1495 g_stacknleft += g_stacknxt - (char *)p;
1500 * Like strdup but works with the ash stack.
1503 sstrdup(const char *p)
1505 size_t len = strlen(p) + 1;
1506 return memcpy(stalloc(len), p, len);
1510 grabstackblock(size_t len)
1516 pushstackmark(struct stackmark *mark, size_t len)
1518 mark->stackp = g_stackp;
1519 mark->stacknxt = g_stacknxt;
1520 mark->stacknleft = g_stacknleft;
1521 grabstackblock(len);
1525 setstackmark(struct stackmark *mark)
1527 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1531 popstackmark(struct stackmark *mark)
1533 struct stack_block *sp;
1539 while (g_stackp != mark->stackp) {
1541 g_stackp = sp->prev;
1544 g_stacknxt = mark->stacknxt;
1545 g_stacknleft = mark->stacknleft;
1546 sstrend = mark->stacknxt + mark->stacknleft;
1551 * When the parser reads in a string, it wants to stick the string on the
1552 * stack and only adjust the stack pointer when it knows how big the
1553 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1554 * of space on top of the stack and stackblocklen returns the length of
1555 * this block. Growstackblock will grow this space by at least one byte,
1556 * possibly moving it (like realloc). Grabstackblock actually allocates the
1557 * part of the block that has been used.
1560 growstackblock(void)
1564 newlen = g_stacknleft * 2;
1565 if (newlen < g_stacknleft)
1566 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1570 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1571 struct stack_block *sp;
1572 struct stack_block *prevstackp;
1577 prevstackp = sp->prev;
1578 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1579 sp = ckrealloc(sp, grosslen);
1580 sp->prev = prevstackp;
1582 g_stacknxt = sp->space;
1583 g_stacknleft = newlen;
1584 sstrend = sp->space + newlen;
1587 char *oldspace = g_stacknxt;
1588 size_t oldlen = g_stacknleft;
1589 char *p = stalloc(newlen);
1591 /* free the space we just allocated */
1592 g_stacknxt = memcpy(p, oldspace, oldlen);
1593 g_stacknleft += newlen;
1598 * The following routines are somewhat easier to use than the above.
1599 * The user declares a variable of type STACKSTR, which may be declared
1600 * to be a register. The macro STARTSTACKSTR initializes things. Then
1601 * the user uses the macro STPUTC to add characters to the string. In
1602 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1603 * grown as necessary. When the user is done, she can just leave the
1604 * string there and refer to it using stackblock(). Or she can allocate
1605 * the space for it using grabstackstr(). If it is necessary to allow
1606 * someone else to use the stack temporarily and then continue to grow
1607 * the string, the user should use grabstack to allocate the space, and
1608 * then call ungrabstr(p) to return to the previous mode of operation.
1610 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1611 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1612 * is space for at least one character.
1617 size_t len = stackblocksize();
1619 return (char *)stackblock() + len;
1623 * Called from CHECKSTRSPACE.
1626 makestrspace(size_t newlen, char *p)
1628 size_t len = p - g_stacknxt;
1634 size = stackblocksize();
1636 if (nleft >= newlen)
1640 return (char *)stackblock() + len;
1644 stack_nputstr(const char *s, size_t n, char *p)
1646 p = makestrspace(n, p);
1647 p = (char *)memcpy(p, s, n) + n;
1652 stack_putstr(const char *s, char *p)
1654 return stack_nputstr(s, strlen(s), p);
1658 _STPUTC(int c, char *p)
1666 #define STARTSTACKSTR(p) ((p) = stackblock())
1667 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1668 #define CHECKSTRSPACE(n, p) do { \
1671 size_t m = sstrend - q; \
1673 (p) = makestrspace(l, q); \
1675 #define USTPUTC(c, p) (*(p)++ = (c))
1676 #define STACKSTRNUL(p) do { \
1677 if ((p) == sstrend) \
1678 (p) = growstackstr(); \
1681 #define STUNPUTC(p) (--(p))
1682 #define STTOPC(p) ((p)[-1])
1683 #define STADJUST(amount, p) ((p) += (amount))
1685 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1686 #define ungrabstackstr(s, p) stunalloc(s)
1687 #define stackstrend() ((void *)sstrend)
1690 /* ============ String helpers */
1693 * prefix -- see if pfx is a prefix of string.
1696 prefix(const char *string, const char *pfx)
1699 if (*pfx++ != *string++)
1702 return (char *) string;
1706 * Check for a valid number. This should be elsewhere.
1709 is_number(const char *p)
1714 } while (*++p != '\0');
1719 * Convert a string of digits to an integer, printing an error message on
1723 number(const char *s)
1726 ash_msg_and_raise_error(msg_illnum, s);
1731 * Produce a possibly single quoted string suitable as input to the shell.
1732 * The return string is allocated on the stack.
1735 single_quote(const char *s)
1745 len = strchrnul(s, '\'') - s;
1747 q = p = makestrspace(len + 3, p);
1750 q = (char *)memcpy(q, s, len) + len;
1759 do len++; while (*++s == '\'');
1761 q = p = makestrspace(len + 3, p);
1764 q = (char *)memcpy(q, s - len, len) + len;
1772 return stackblock();
1776 /* ============ nextopt */
1778 static char **argptr; /* argument list for builtin commands */
1779 static char *optionarg; /* set by nextopt (like getopt) */
1780 static char *optptr; /* used by nextopt */
1783 * XXX - should get rid of. Have all builtins use getopt(3).
1784 * The library getopt must have the BSD extension static variable
1785 * "optreset", otherwise it can't be used within the shell safely.
1787 * Standard option processing (a la getopt) for builtin routines.
1788 * The only argument that is passed to nextopt is the option string;
1789 * the other arguments are unnecessary. It returns the character,
1790 * or '\0' on end of input.
1793 nextopt(const char *optstring)
1800 if (p == NULL || *p == '\0') {
1801 /* We ate entire "-param", take next one */
1807 if (*++p == '\0') /* just "-" ? */
1810 if (LONE_DASH(p)) /* "--" ? */
1812 /* p => next "-param" */
1814 /* p => some option char in the middle of a "-param" */
1816 for (q = optstring; *q != c;) {
1818 ash_msg_and_raise_error("illegal option -%c", c);
1826 ash_msg_and_raise_error("no arg for -%c option", c);
1836 /* ============ Shell variables */
1839 * The parsefile structure pointed to by the global variable parsefile
1840 * contains information about the current file being read.
1843 int nparam; /* # of positional parameters (without $0) */
1844 #if ENABLE_ASH_GETOPTS
1845 int optind; /* next parameter to be processed by getopts */
1846 int optoff; /* used by getopts */
1848 unsigned char malloced; /* if parameter list dynamically allocated */
1849 char **p; /* parameter list */
1853 * Free the list of positional parameters.
1856 freeparam(volatile struct shparam *param)
1858 if (param->malloced) {
1860 ap = ap1 = param->p;
1867 #if ENABLE_ASH_GETOPTS
1868 static void FAST_FUNC getoptsreset(const char *value);
1872 struct var *next; /* next entry in hash list */
1873 int flags; /* flags are defined above */
1874 const char *var_text; /* name=value */
1875 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1876 /* the variable gets set/unset */
1880 struct localvar *next; /* next local variable in list */
1881 struct var *vp; /* the variable that was made local */
1882 int flags; /* saved flags */
1883 const char *text; /* saved text */
1887 #define VEXPORT 0x01 /* variable is exported */
1888 #define VREADONLY 0x02 /* variable cannot be modified */
1889 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1890 #define VTEXTFIXED 0x08 /* text is statically allocated */
1891 #define VSTACK 0x10 /* text is allocated on the stack */
1892 #define VUNSET 0x20 /* the variable is not set */
1893 #define VNOFUNC 0x40 /* don't call the callback function */
1894 #define VNOSET 0x80 /* do not set variable - just readonly test */
1895 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1896 #if ENABLE_ASH_RANDOM_SUPPORT
1897 # define VDYNAMIC 0x200 /* dynamic variable */
1903 /* Need to be before varinit_data[] */
1904 #if ENABLE_LOCALE_SUPPORT
1905 static void FAST_FUNC
1906 change_lc_all(const char *value)
1908 if (value && *value != '\0')
1909 setlocale(LC_ALL, value);
1911 static void FAST_FUNC
1912 change_lc_ctype(const char *value)
1914 if (value && *value != '\0')
1915 setlocale(LC_CTYPE, value);
1919 static void chkmail(void);
1920 static void changemail(const char *var_value) FAST_FUNC;
1922 # define chkmail() ((void)0)
1924 static void changepath(const char *) FAST_FUNC;
1925 #if ENABLE_ASH_RANDOM_SUPPORT
1926 static void change_random(const char *) FAST_FUNC;
1929 static const struct {
1931 const char *var_text;
1932 void (*var_func)(const char *) FAST_FUNC;
1933 } varinit_data[] = {
1935 * Note: VEXPORT would not work correctly here for NOFORK applets:
1936 * some environment strings may be constant.
1938 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1940 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1941 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1943 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1944 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1945 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1946 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1947 #if ENABLE_ASH_GETOPTS
1948 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1950 #if ENABLE_ASH_RANDOM_SUPPORT
1951 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1953 #if ENABLE_LOCALE_SUPPORT
1954 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1955 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1957 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1958 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1964 struct globals_var {
1965 struct shparam shellparam; /* $@ current positional parameters */
1966 struct redirtab *redirlist;
1967 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1968 struct var *vartab[VTABSIZE];
1969 struct var varinit[ARRAY_SIZE(varinit_data)];
1971 extern struct globals_var *const ash_ptr_to_globals_var;
1972 #define G_var (*ash_ptr_to_globals_var)
1973 #define shellparam (G_var.shellparam )
1974 //#define redirlist (G_var.redirlist )
1975 #define preverrout_fd (G_var.preverrout_fd)
1976 #define vartab (G_var.vartab )
1977 #define varinit (G_var.varinit )
1978 #define INIT_G_var() do { \
1980 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1982 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1983 varinit[i].flags = varinit_data[i].flags; \
1984 varinit[i].var_text = varinit_data[i].var_text; \
1985 varinit[i].var_func = varinit_data[i].var_func; \
1989 #define vifs varinit[0]
1991 # define vmail (&vifs)[1]
1992 # define vmpath (&vmail)[1]
1993 # define vpath (&vmpath)[1]
1995 # define vpath (&vifs)[1]
1997 #define vps1 (&vpath)[1]
1998 #define vps2 (&vps1)[1]
1999 #define vps4 (&vps2)[1]
2000 #if ENABLE_ASH_GETOPTS
2001 # define voptind (&vps4)[1]
2002 # if ENABLE_ASH_RANDOM_SUPPORT
2003 # define vrandom (&voptind)[1]
2006 # if ENABLE_ASH_RANDOM_SUPPORT
2007 # define vrandom (&vps4)[1]
2012 * The following macros access the values of the above variables.
2013 * They have to skip over the name. They return the null string
2014 * for unset variables.
2016 #define ifsval() (vifs.var_text + 4)
2017 #define ifsset() ((vifs.flags & VUNSET) == 0)
2019 # define mailval() (vmail.var_text + 5)
2020 # define mpathval() (vmpath.var_text + 9)
2021 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2023 #define pathval() (vpath.var_text + 5)
2024 #define ps1val() (vps1.var_text + 4)
2025 #define ps2val() (vps2.var_text + 4)
2026 #define ps4val() (vps4.var_text + 4)
2027 #if ENABLE_ASH_GETOPTS
2028 # define optindval() (voptind.var_text + 7)
2031 #if ENABLE_ASH_GETOPTS
2032 static void FAST_FUNC
2033 getoptsreset(const char *value)
2035 shellparam.optind = number(value) ?: 1;
2036 shellparam.optoff = -1;
2041 * Compares two strings up to the first = or '\0'. The first
2042 * string must be terminated by '='; the second may be terminated by
2043 * either '=' or '\0'.
2046 varcmp(const char *p, const char *q)
2050 while ((c = *p) == (d = *q)) {
2051 if (c == '\0' || c == '=')
2065 * Find the appropriate entry in the hash table from the name.
2067 static struct var **
2068 hashvar(const char *p)
2072 hashval = ((unsigned char) *p) << 4;
2073 while (*p && *p != '=')
2074 hashval += (unsigned char) *p++;
2075 return &vartab[hashval % VTABSIZE];
2079 vpcmp(const void *a, const void *b)
2081 return varcmp(*(const char **)a, *(const char **)b);
2085 * This routine initializes the builtin variables.
2095 * PS1 depends on uid
2097 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2098 vps1.var_text = "PS1=\\w \\$ ";
2101 vps1.var_text = "PS1=# ";
2104 end = vp + ARRAY_SIZE(varinit);
2106 vpp = hashvar(vp->var_text);
2109 } while (++vp < end);
2112 static struct var **
2113 findvar(struct var **vpp, const char *name)
2115 for (; *vpp; vpp = &(*vpp)->next) {
2116 if (varcmp((*vpp)->var_text, name) == 0) {
2124 * Find the value of a variable. Returns NULL if not set.
2126 static const char* FAST_FUNC
2127 lookupvar(const char *name)
2131 v = *findvar(hashvar(name), name);
2133 #if ENABLE_ASH_RANDOM_SUPPORT
2135 * Dynamic variables are implemented roughly the same way they are
2136 * in bash. Namely, they're "special" so long as they aren't unset.
2137 * As soon as they're unset, they're no longer dynamic, and dynamic
2138 * lookup will no longer happen at that point. -- PFM.
2140 if (v->flags & VDYNAMIC)
2143 if (!(v->flags & VUNSET))
2144 return var_end(v->var_text);
2150 reinit_unicode_for_ash(void)
2152 /* Unicode support should be activated even if LANG is set
2153 * _during_ shell execution, not only if it was set when
2154 * shell was started. Therefore, re-check LANG every time:
2156 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2157 || ENABLE_UNICODE_USING_LOCALE
2159 const char *s = lookupvar("LC_ALL");
2160 if (!s) s = lookupvar("LC_CTYPE");
2161 if (!s) s = lookupvar("LANG");
2167 * Search the environment of a builtin command.
2170 bltinlookup(const char *name)
2174 for (sp = cmdenviron; sp; sp = sp->next) {
2175 if (varcmp(sp->text, name) == 0)
2176 return var_end(sp->text);
2178 return lookupvar(name);
2182 * Same as setvar except that the variable and value are passed in
2183 * the first argument as name=value. Since the first argument will
2184 * be actually stored in the table, it should not be a string that
2186 * Called with interrupts off.
2189 setvareq(char *s, int flags)
2191 struct var *vp, **vpp;
2194 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2195 vp = *findvar(vpp, s);
2197 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2200 if (flags & VNOSAVE)
2204 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2210 if (vp->var_func && !(flags & VNOFUNC))
2211 vp->var_func(var_end(s));
2213 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2214 free((char*)vp->var_text);
2216 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2218 /* variable s is not found */
2221 vp = ckzalloc(sizeof(*vp));
2223 /*vp->func = NULL; - ckzalloc did it */
2226 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2233 * Set the value of a variable. The flags argument is ored with the
2234 * flags of the variable. If val is NULL, the variable is unset.
2237 setvar(const char *name, const char *val, int flags)
2245 q = endofname(name);
2246 p = strchrnul(q, '=');
2248 if (!namelen || p != q)
2249 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2254 vallen = strlen(val);
2258 nameeq = ckmalloc(namelen + vallen + 2);
2259 p = memcpy(nameeq, name, namelen) + namelen;
2262 p = memcpy(p, val, vallen) + vallen;
2265 setvareq(nameeq, flags | VNOSAVE);
2269 static void FAST_FUNC
2270 setvar0(const char *name, const char *val)
2272 setvar(name, val, 0);
2276 * Unset the specified variable.
2279 unsetvar(const char *s)
2285 vpp = findvar(hashvar(s), s);
2289 int flags = vp->flags;
2292 if (flags & VREADONLY)
2294 #if ENABLE_ASH_RANDOM_SUPPORT
2295 vp->flags &= ~VDYNAMIC;
2299 if ((flags & VSTRFIXED) == 0) {
2301 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2302 free((char*)vp->var_text);
2308 vp->flags &= ~VEXPORT;
2318 * Process a linked list of variable assignments.
2321 listsetvar(struct strlist *list_set_var, int flags)
2323 struct strlist *lp = list_set_var;
2329 setvareq(lp->text, flags);
2336 * Generate a list of variables satisfying the given conditions.
2339 listvars(int on, int off, char ***end)
2350 for (vp = *vpp; vp; vp = vp->next) {
2351 if ((vp->flags & mask) == on) {
2352 if (ep == stackstrend())
2353 ep = growstackstr();
2354 *ep++ = (char*)vp->var_text;
2357 } while (++vpp < vartab + VTABSIZE);
2358 if (ep == stackstrend())
2359 ep = growstackstr();
2363 return grabstackstr(ep);
2367 /* ============ Path search helper
2369 * The variable path (passed by reference) should be set to the start
2370 * of the path before the first call; path_advance will update
2371 * this value as it proceeds. Successive calls to path_advance will return
2372 * the possible path expansions in sequence. If an option (indicated by
2373 * a percent sign) appears in the path entry then the global variable
2374 * pathopt will be set to point to it; otherwise pathopt will be set to
2377 static const char *pathopt; /* set by path_advance */
2380 path_advance(const char **path, const char *name)
2390 for (p = start; *p && *p != ':' && *p != '%'; p++)
2392 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2393 while (stackblocksize() < len)
2397 memcpy(q, start, p - start);
2405 while (*p && *p != ':')
2412 return stalloc(len);
2416 /* ============ Prompt */
2418 static smallint doprompt; /* if set, prompt the user */
2419 static smallint needprompt; /* true if interactive and at start of line */
2421 #if ENABLE_FEATURE_EDITING
2422 static line_input_t *line_input_state;
2423 static const char *cmdedit_prompt;
2425 putprompt(const char *s)
2427 if (ENABLE_ASH_EXPAND_PRMT) {
2428 free((char*)cmdedit_prompt);
2429 cmdedit_prompt = ckstrdup(s);
2436 putprompt(const char *s)
2442 #if ENABLE_ASH_EXPAND_PRMT
2443 /* expandstr() needs parsing machinery, so it is far away ahead... */
2444 static const char *expandstr(const char *ps);
2446 #define expandstr(s) s
2450 setprompt_if(smallint do_set, int whichprompt)
2453 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2460 switch (whichprompt) {
2470 #if ENABLE_ASH_EXPAND_PRMT
2471 pushstackmark(&smark, stackblocksize());
2473 putprompt(expandstr(prompt));
2474 #if ENABLE_ASH_EXPAND_PRMT
2475 popstackmark(&smark);
2480 /* ============ The cd and pwd commands */
2482 #define CD_PHYSICAL 1
2492 while ((i = nextopt("LP")) != '\0') {
2494 flags ^= CD_PHYSICAL;
2503 * Update curdir (the name of the current directory) in response to a
2507 updatepwd(const char *dir)
2514 cdcomppath = sstrdup(dir);
2517 if (curdir == nullstr)
2519 new = stack_putstr(curdir, new);
2521 new = makestrspace(strlen(dir) + 2, new);
2522 lim = (char *)stackblock() + 1;
2526 if (new > lim && *lim == '/')
2531 if (dir[1] == '/' && dir[2] != '/') {
2537 p = strtok(cdcomppath, "/");
2541 if (p[1] == '.' && p[2] == '\0') {
2553 new = stack_putstr(p, new);
2556 p = strtok(NULL, "/");
2561 return stackblock();
2565 * Find out what the current directory is. If we already know the current
2566 * directory, this routine returns immediately.
2571 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2572 return dir ? dir : nullstr;
2576 setpwd(const char *val, int setold)
2580 oldcur = dir = curdir;
2583 setvar("OLDPWD", oldcur, VEXPORT);
2586 if (physdir != nullstr) {
2587 if (physdir != oldcur)
2591 if (oldcur == val || !val) {
2597 dir = ckstrdup(val);
2598 if (oldcur != dir && oldcur != nullstr) {
2603 setvar("PWD", dir, VEXPORT);
2606 static void hashcd(void);
2609 * Actually do the chdir. We also call hashcd to let other routines
2610 * know that the current directory has changed.
2613 docd(const char *dest, int flags)
2615 const char *dir = NULL;
2618 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2621 if (!(flags & CD_PHYSICAL)) {
2622 dir = updatepwd(dest);
2636 static int FAST_FUNC
2637 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2649 dest = bltinlookup("HOME");
2650 else if (LONE_DASH(dest)) {
2651 dest = bltinlookup("OLDPWD");
2673 path = bltinlookup("CDPATH");
2676 p = path_advance(&path, dest);
2677 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2681 if (!docd(p, flags))
2692 ash_msg_and_raise_error("can't cd to %s", dest);
2695 if (flags & CD_PRINT)
2696 out1fmt("%s\n", curdir);
2700 static int FAST_FUNC
2701 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2704 const char *dir = curdir;
2708 if (physdir == nullstr)
2712 out1fmt("%s\n", dir);
2717 /* ============ ... */
2720 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2722 /* Syntax classes */
2723 #define CWORD 0 /* character is nothing special */
2724 #define CNL 1 /* newline character */
2725 #define CBACK 2 /* a backslash character */
2726 #define CSQUOTE 3 /* single quote */
2727 #define CDQUOTE 4 /* double quote */
2728 #define CENDQUOTE 5 /* a terminating quote */
2729 #define CBQUOTE 6 /* backwards single quote */
2730 #define CVAR 7 /* a dollar sign */
2731 #define CENDVAR 8 /* a '}' character */
2732 #define CLP 9 /* a left paren in arithmetic */
2733 #define CRP 10 /* a right paren in arithmetic */
2734 #define CENDFILE 11 /* end of file */
2735 #define CCTL 12 /* like CWORD, except it must be escaped */
2736 #define CSPCL 13 /* these terminate a word */
2737 #define CIGN 14 /* character should be ignored */
2740 #if ENABLE_ASH_ALIAS
2744 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2746 #if ENABLE_SH_MATH_SUPPORT
2747 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2749 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2751 static const uint16_t S_I_T[] ALIGN2 = {
2752 #if ENABLE_ASH_ALIAS
2753 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2755 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2756 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2757 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2758 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2759 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2760 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2761 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2762 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2763 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2764 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2765 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2766 #if !USE_SIT_FUNCTION
2767 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2768 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2769 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2773 /* Constants below must match table above */
2775 #if ENABLE_ASH_ALIAS
2776 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2778 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2779 CNL_CNL_CNL_CNL , /* 2 */
2780 CWORD_CCTL_CCTL_CWORD , /* 3 */
2781 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2782 CVAR_CVAR_CWORD_CVAR , /* 5 */
2783 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2784 CSPCL_CWORD_CWORD_CLP , /* 7 */
2785 CSPCL_CWORD_CWORD_CRP , /* 8 */
2786 CBACK_CBACK_CCTL_CBACK , /* 9 */
2787 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2788 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2789 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2790 CWORD_CWORD_CWORD_CWORD , /* 13 */
2791 CCTL_CCTL_CCTL_CCTL , /* 14 */
2794 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2795 * caller must ensure proper cast on it if c is *char_ptr!
2797 /* Values for syntax param */
2798 #define BASESYNTAX 0 /* not in quotes */
2799 #define DQSYNTAX 1 /* in double quotes */
2800 #define SQSYNTAX 2 /* in single quotes */
2801 #define ARISYNTAX 3 /* in arithmetic */
2802 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2804 #if USE_SIT_FUNCTION
2807 SIT(int c, int syntax)
2809 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2810 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2812 * This causes '/' to be prepended with CTLESC in dquoted string,
2813 * making "./file"* treated incorrectly because we feed
2814 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2815 * The "homegrown" glob implementation is okay with that,
2816 * but glibc one isn't. With '/' always treated as CWORD,
2819 # if ENABLE_ASH_ALIAS
2820 static const uint8_t syntax_index_table[] ALIGN1 = {
2821 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2822 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2823 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2827 static const uint8_t syntax_index_table[] ALIGN1 = {
2828 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2829 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2830 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2839 # if ENABLE_ASH_ALIAS
2845 /* Cast is purely for paranoia here,
2846 * just in case someone passed signed char to us */
2847 if ((unsigned char)c >= CTL_FIRST
2848 && (unsigned char)c <= CTL_LAST
2852 s = strchrnul(spec_symbls, c);
2855 indx = syntax_index_table[s - spec_symbls];
2857 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2860 #else /* !USE_SIT_FUNCTION */
2862 static const uint8_t syntax_index_table[] ALIGN1 = {
2863 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2864 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2874 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2875 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2897 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2898 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2899 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2901 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2903 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2904 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2905 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2906 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2907 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2909 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2910 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2911 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2912 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2924 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2925 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2926 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2927 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2928 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2929 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2957 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2958 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2959 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2962 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2990 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2991 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2992 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2993 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2995 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2996 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2997 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2998 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2999 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3000 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3001 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3002 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3121 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3122 # if ENABLE_ASH_ALIAS
3123 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3128 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3129 #else /* debug version, caught one signed char bug */
3130 # define SIT(c, syntax) \
3132 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3133 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3134 if ((syntax) < 0 || (syntax) > (2 + ENABLE_SH_MATH_SUPPORT)) \
3135 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3136 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3140 #endif /* !USE_SIT_FUNCTION */
3143 /* ============ Alias handling */
3145 #if ENABLE_ASH_ALIAS
3147 #define ALIASINUSE 1
3158 static struct alias **atab; // [ATABSIZE];
3159 #define INIT_G_alias() do { \
3160 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3164 static struct alias **
3165 __lookupalias(const char *name)
3167 unsigned int hashval;
3174 ch = (unsigned char)*p;
3178 ch = (unsigned char)*++p;
3180 app = &atab[hashval % ATABSIZE];
3182 for (; *app; app = &(*app)->next) {
3183 if (strcmp(name, (*app)->name) == 0) {
3191 static struct alias *
3192 lookupalias(const char *name, int check)
3194 struct alias *ap = *__lookupalias(name);
3196 if (check && ap && (ap->flag & ALIASINUSE))
3201 static struct alias *
3202 freealias(struct alias *ap)
3206 if (ap->flag & ALIASINUSE) {
3207 ap->flag |= ALIASDEAD;
3219 setalias(const char *name, const char *val)
3221 struct alias *ap, **app;
3223 app = __lookupalias(name);
3227 if (!(ap->flag & ALIASINUSE)) {
3230 ap->val = ckstrdup(val);
3231 ap->flag &= ~ALIASDEAD;
3234 ap = ckzalloc(sizeof(struct alias));
3235 ap->name = ckstrdup(name);
3236 ap->val = ckstrdup(val);
3237 /*ap->flag = 0; - ckzalloc did it */
3238 /*ap->next = NULL;*/
3245 unalias(const char *name)
3249 app = __lookupalias(name);
3253 *app = freealias(*app);
3264 struct alias *ap, **app;
3268 for (i = 0; i < ATABSIZE; i++) {
3270 for (ap = *app; ap; ap = *app) {
3271 *app = freealias(*app);
3281 printalias(const struct alias *ap)
3283 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3287 * TODO - sort output
3289 static int FAST_FUNC
3290 aliascmd(int argc UNUSED_PARAM, char **argv)
3299 for (i = 0; i < ATABSIZE; i++) {
3300 for (ap = atab[i]; ap; ap = ap->next) {
3306 while ((n = *++argv) != NULL) {
3307 v = strchr(n+1, '=');
3308 if (v == NULL) { /* n+1: funny ksh stuff */
3309 ap = *__lookupalias(n);
3311 fprintf(stderr, "%s: %s not found\n", "alias", n);
3324 static int FAST_FUNC
3325 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3329 while ((i = nextopt("a")) != '\0') {
3335 for (i = 0; *argptr; argptr++) {
3336 if (unalias(*argptr)) {
3337 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3345 #endif /* ASH_ALIAS */
3348 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3351 #define FORK_NOJOB 2
3353 /* mode flags for showjob(s) */
3354 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3355 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3356 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3357 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3360 * A job structure contains information about a job. A job is either a
3361 * single process or a set of processes contained in a pipeline. In the
3362 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3366 pid_t ps_pid; /* process id */
3367 int ps_status; /* last process status from wait() */
3368 char *ps_cmd; /* text of command being run */
3372 struct procstat ps0; /* status of process */
3373 struct procstat *ps; /* status or processes when more than one */
3375 int stopstatus; /* status of a stopped job */
3378 nprocs: 16, /* number of processes */
3380 #define JOBRUNNING 0 /* at least one proc running */
3381 #define JOBSTOPPED 1 /* all procs are stopped */
3382 #define JOBDONE 2 /* all procs are completed */
3384 sigint: 1, /* job was killed by SIGINT */
3385 jobctl: 1, /* job running under job control */
3387 waited: 1, /* true if this entry has been waited for */
3388 used: 1, /* true if this entry is in used */
3389 changed: 1; /* true if status has changed */
3390 struct job *prev_job; /* previous job */
3393 static struct job *makejob(/*union node *,*/ int);
3394 static int forkshell(struct job *, union node *, int);
3395 static int waitforjob(struct job *);
3398 enum { doing_jobctl = 0 };
3399 #define setjobctl(on) do {} while (0)
3401 static smallint doing_jobctl; //references:8
3402 static void setjobctl(int);
3409 ignoresig(int signo)
3411 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3412 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3413 /* No, need to do it */
3414 signal(signo, SIG_IGN);
3416 sigmode[signo - 1] = S_HARD_IGN;
3420 * Only one usage site - in setsignal()
3423 signal_handler(int signo)
3425 if (signo == SIGCHLD) {
3431 gotsig[signo - 1] = 1;
3432 pending_sig = signo;
3434 if (signo == SIGINT && !trap[SIGINT]) {
3435 if (!suppress_int) {
3437 raise_interrupt(); /* does not return */
3444 * Set the signal handler for the specified signal. The routine figures
3445 * out what it should be set to.
3448 setsignal(int signo)
3451 char cur_act, new_act;
3452 struct sigaction act;
3456 if (t != NULL) { /* trap for this sig is set */
3458 if (t[0] == '\0') /* trap is "": ignore this sig */
3462 if (rootshell && new_act == S_DFL) {
3465 if (iflag || minusc || sflag == 0)
3474 * "In all cases, bash ignores SIGQUIT. Non-builtin
3475 * commands run by bash have signal handlers
3476 * set to the values inherited by the shell
3477 * from its parent". */
3493 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3494 //whereas we have to restore it to what shell got on entry
3495 //from the parent. See comment above
3497 if (signo == SIGCHLD)
3500 t = &sigmode[signo - 1];
3503 /* current setting is not yet known */
3504 if (sigaction(signo, NULL, &act)) {
3505 /* pretend it worked; maybe we should give a warning,
3506 * but other shells don't. We don't alter sigmode,
3507 * so we retry every time.
3508 * btw, in Linux it never fails. --vda */
3511 if (act.sa_handler == SIG_IGN) {
3512 cur_act = S_HARD_IGN;
3514 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3516 cur_act = S_IGN; /* don't hard ignore these */
3520 if (cur_act == S_HARD_IGN || cur_act == new_act)
3523 act.sa_handler = SIG_DFL;
3526 act.sa_handler = signal_handler;
3529 act.sa_handler = SIG_IGN;
3533 /* flags and mask matter only if !DFL and !IGN, but we do it
3534 * for all cases for more deterministic behavior:
3537 sigfillset(&act.sa_mask);
3539 sigaction_set(signo, &act);
3544 /* mode flags for set_curjob */
3545 #define CUR_DELETE 2
3546 #define CUR_RUNNING 1
3547 #define CUR_STOPPED 0
3550 /* pgrp of shell on invocation */
3551 static int initialpgrp; //references:2
3552 static int ttyfd = -1; //5
3555 static struct job *jobtab; //5
3557 static unsigned njobs; //4
3559 static struct job *curjob; //lots
3560 /* number of presumed living untracked jobs */
3561 static int jobless; //4
3564 set_curjob(struct job *jp, unsigned mode)
3567 struct job **jpp, **curp;
3569 /* first remove from list */
3570 jpp = curp = &curjob;
3575 jpp = &jp1->prev_job;
3577 *jpp = jp1->prev_job;
3579 /* Then re-insert in correct position */
3587 /* job being deleted */
3590 /* newly created job or backgrounded job,
3591 * put after all stopped jobs.
3596 if (!jp1 || jp1->state != JOBSTOPPED)
3599 jpp = &jp1->prev_job;
3605 /* newly stopped job - becomes curjob */
3606 jp->prev_job = *jpp;
3614 jobno(const struct job *jp)
3616 return jp - jobtab + 1;
3621 * Convert a job name to a job structure.
3624 #define getjob(name, getctl) getjob(name)
3627 getjob(const char *name, int getctl)
3631 const char *err_msg = "%s: no such job";
3635 char *(*match)(const char *, const char *);
3650 if (c == '+' || c == '%') {
3652 err_msg = "No current job";
3658 err_msg = "No previous job";
3668 if (num > 0 && num <= njobs) {
3669 jp = jobtab + num - 1;
3684 if (match(jp->ps[0].ps_cmd, p)) {
3688 err_msg = "%s: ambiguous";
3698 err_msg = "job %s not created under job control";
3699 if (getctl && jp->jobctl == 0)
3704 ash_msg_and_raise_error(err_msg, name);
3708 * Mark a job structure as unused.
3711 freejob(struct job *jp)
3713 struct procstat *ps;
3717 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3718 if (ps->ps_cmd != nullstr)
3721 if (jp->ps != &jp->ps0)
3724 set_curjob(jp, CUR_DELETE);
3730 xtcsetpgrp(int fd, pid_t pgrp)
3732 if (tcsetpgrp(fd, pgrp))
3733 ash_msg_and_raise_error("can't set tty process group (%m)");
3737 * Turn job control on and off.
3739 * Note: This code assumes that the third arg to ioctl is a character
3740 * pointer, which is true on Berkeley systems but not System V. Since
3741 * System V doesn't have job control yet, this isn't a problem now.
3743 * Called with interrupts off.
3751 if (on == doing_jobctl || rootshell == 0)
3755 ofd = fd = open(_PATH_TTY, O_RDWR);
3757 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3758 * That sometimes helps to acquire controlling tty.
3759 * Obviously, a workaround for bugs when someone
3760 * failed to provide a controlling tty to bash! :) */
3766 /* fd is a tty at this point */
3767 fd = fcntl(fd, F_DUPFD, 10);
3768 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3771 goto out; /* F_DUPFD failed */
3772 close_on_exec_on(fd);
3773 while (1) { /* while we are in the background */
3774 pgrp = tcgetpgrp(fd);
3777 ash_msg("can't access tty; job control turned off");
3781 if (pgrp == getpgrp())
3792 xtcsetpgrp(fd, pgrp);
3794 /* turning job control off */
3797 /* was xtcsetpgrp, but this can make exiting ash
3798 * loop forever if pty is already deleted */
3799 tcsetpgrp(fd, pgrp);
3813 static int FAST_FUNC
3814 killcmd(int argc, char **argv)
3816 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3819 if (argv[i][0] == '%') {
3821 * "kill %N" - job kill
3822 * Converting to pgrp / pid kill
3828 jp = getjob(argv[i], 0);
3830 * In jobs started under job control, we signal
3831 * entire process group by kill -PGRP_ID.
3832 * This happens, f.e., in interactive shell.
3834 * Otherwise, we signal each child via
3835 * kill PID1 PID2 PID3.
3837 * sh -c 'sleep 1|sleep 1 & kill %1'
3838 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3839 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3841 n = jp->nprocs; /* can't be 0 (I hope) */
3844 dst = alloca(n * sizeof(int)*4);
3846 for (j = 0; j < n; j++) {
3847 struct procstat *ps = &jp->ps[j];
3848 /* Skip non-running and not-stopped members
3849 * (i.e. dead members) of the job
3851 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3854 * kill_main has matching code to expect
3855 * leading space. Needed to not confuse
3856 * negative pids with "kill -SIGNAL_NO" syntax
3858 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3862 } while (argv[++i]);
3864 return kill_main(argc, argv);
3868 showpipe(struct job *jp /*, FILE *out*/)
3870 struct procstat *ps;
3871 struct procstat *psend;
3873 psend = jp->ps + jp->nprocs;
3874 for (ps = jp->ps + 1; ps < psend; ps++)
3875 printf(" | %s", ps->ps_cmd);
3876 newline_and_flush(stdout);
3877 flush_stdout_stderr();
3882 restartjob(struct job *jp, int mode)
3884 struct procstat *ps;
3890 if (jp->state == JOBDONE)
3892 jp->state = JOBRUNNING;
3893 pgid = jp->ps[0].ps_pid;
3894 if (mode == FORK_FG)
3895 xtcsetpgrp(ttyfd, pgid);
3896 killpg(pgid, SIGCONT);
3900 if (WIFSTOPPED(ps->ps_status)) {
3906 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3911 static int FAST_FUNC
3912 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3918 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3922 jp = getjob(*argv, 1);
3923 if (mode == FORK_BG) {
3924 set_curjob(jp, CUR_RUNNING);
3925 printf("[%d] ", jobno(jp));
3927 out1str(jp->ps[0].ps_cmd);
3928 showpipe(jp /*, stdout*/);
3929 retval = restartjob(jp, mode);
3930 } while (*argv && *++argv);
3936 sprint_status48(char *s, int status, int sigonly)
3942 if (!WIFEXITED(status)) {
3943 if (JOBS && WIFSTOPPED(status))
3944 st = WSTOPSIG(status);
3946 st = WTERMSIG(status);
3948 if (st == SIGINT || st == SIGPIPE)
3950 if (JOBS && WIFSTOPPED(status))
3954 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3955 col = fmtstr(s, 32, strsignal(st));
3956 if (WCOREDUMP(status)) {
3957 strcpy(s + col, " (core dumped)");
3958 col += sizeof(" (core dumped)")-1;
3960 } else if (!sigonly) {
3961 st = WEXITSTATUS(status);
3962 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3969 wait_block_or_sig(int *status)
3976 /* Poll all children for changes in their state */
3978 /* if job control is active, accept stopped processes too */
3979 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
3981 break; /* Error (e.g. EINTR, ECHILD) or pid */
3983 /* Children exist, but none are ready. Sleep until interesting signal */
3986 sigprocmask(SIG_SETMASK, &mask, &mask);
3987 while (!got_sigchld && !pending_sig)
3989 sigprocmask(SIG_SETMASK, &mask, NULL);
3990 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
3991 while (!got_sigchld && !pending_sig)
3995 /* If it was SIGCHLD, poll children again */
3996 } while (got_sigchld);
4001 #define DOWAIT_NONBLOCK 0
4002 #define DOWAIT_BLOCK 1
4003 #define DOWAIT_BLOCK_OR_SIG 2
4006 dowait(int block, struct job *job)
4011 struct job *thisjob = NULL;
4013 TRACE(("dowait(0x%x) called\n", block));
4015 /* It's wrong to call waitpid() outside of INT_OFF region:
4016 * signal can arrive just after syscall return and handler can
4017 * longjmp away, losing stop/exit notification processing.
4018 * Thus, for "jobs" builtin, and for waiting for a fg job,
4019 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4021 * However, for "wait" builtin it is wrong to simply call waitpid()
4022 * in INT_OFF region: "wait" needs to wait for any running job
4023 * to change state, but should exit on any trap too.
4024 * In INT_OFF region, a signal just before syscall entry can set
4025 * pending_sig variables, but we can't check them, and we would
4026 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4028 * Because of this, we run inside INT_OFF, but use a special routine
4029 * which combines waitpid() and sigsuspend().
4030 * This is the reason why we need to have a handler for SIGCHLD:
4031 * SIG_DFL handler does not wake sigsuspend().
4034 if (block == DOWAIT_BLOCK_OR_SIG) {
4035 pid = wait_block_or_sig(&status);
4038 if (block == DOWAIT_NONBLOCK)
4039 wait_flags = WNOHANG;
4040 /* if job control is active, accept stopped processes too */
4042 wait_flags |= WUNTRACED;
4043 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4044 pid = waitpid(-1, &status, wait_flags);
4046 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4047 pid, status, errno, strerror(errno)));
4052 for (jp = curjob; jp; jp = jp->prev_job) {
4054 struct procstat *ps;
4055 struct procstat *psend;
4056 if (jp->state == JOBDONE)
4060 psend = ps + jp->nprocs;
4062 if (ps->ps_pid == pid) {
4063 TRACE(("Job %d: changing status of proc %d "
4064 "from 0x%x to 0x%x\n",
4065 jobno(jp), pid, ps->ps_status, status));
4066 ps->ps_status = status;
4069 if (ps->ps_status == -1)
4070 jobstate = JOBRUNNING;
4072 if (jobstate == JOBRUNNING)
4074 if (WIFSTOPPED(ps->ps_status)) {
4075 jp->stopstatus = ps->ps_status;
4076 jobstate = JOBSTOPPED;
4079 } while (++ps < psend);
4083 /* Found the job where one of its processes changed its state.
4084 * Is there at least one live and running process in this job? */
4085 if (jobstate != JOBRUNNING) {
4086 /* No. All live processes in the job are stopped
4087 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4089 thisjob->changed = 1;
4090 if (thisjob->state != jobstate) {
4091 TRACE(("Job %d: changing state from %d to %d\n",
4092 jobno(thisjob), thisjob->state, jobstate));
4093 thisjob->state = jobstate;
4095 if (jobstate == JOBSTOPPED)
4096 set_curjob(thisjob, CUR_STOPPED);
4102 /* The process wasn't found in job list */
4103 if (JOBS && !WIFSTOPPED(status))
4108 if (thisjob && thisjob == job) {
4112 len = sprint_status48(s, status, 1);
4124 showjob(struct job *jp, int mode)
4126 struct procstat *ps;
4127 struct procstat *psend;
4130 char s[16 + 16 + 48];
4131 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4135 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4136 /* just output process (group) id of pipeline */
4137 fprintf(out, "%d\n", ps->ps_pid);
4141 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4146 else if (curjob && jp == curjob->prev_job)
4149 if (mode & SHOW_PIDS)
4150 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4152 psend = ps + jp->nprocs;
4154 if (jp->state == JOBRUNNING) {
4155 strcpy(s + col, "Running");
4156 col += sizeof("Running") - 1;
4158 int status = psend[-1].ps_status;
4159 if (jp->state == JOBSTOPPED)
4160 status = jp->stopstatus;
4161 col += sprint_status48(s + col, status, 0);
4163 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4165 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4166 * or prints several "PID | <cmdN>" lines,
4167 * depending on SHOW_PIDS bit.
4168 * We do not print status of individual processes
4169 * between PID and <cmdN>. bash does it, but not very well:
4170 * first line shows overall job status, not process status,
4171 * making it impossible to know 1st process status.
4175 /* for each process */
4178 if (mode & SHOW_PIDS)
4179 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4181 fprintf(out, "%s%*c%s%s",
4183 33 - col >= 0 ? 33 - col : 0, ' ',
4184 ps == jp->ps ? "" : "| ",
4187 } while (++ps != psend);
4188 newline_and_flush(out);
4192 if (jp->state == JOBDONE) {
4193 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4199 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4200 * statuses have changed since the last call to showjobs.
4207 TRACE(("showjobs(0x%x) called\n", mode));
4209 /* Handle all finished jobs */
4210 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4213 for (jp = curjob; jp; jp = jp->prev_job) {
4214 if (!(mode & SHOW_CHANGED) || jp->changed) {
4220 static int FAST_FUNC
4221 jobscmd(int argc UNUSED_PARAM, char **argv)
4226 while ((m = nextopt("lp")) != '\0') {
4230 mode |= SHOW_ONLY_PGID;
4236 showjob(getjob(*argv, 0), mode);
4246 /* Called only on finished or stopped jobs (no members are running) */
4248 getstatus(struct job *job)
4252 struct procstat *ps;
4254 /* Fetch last member's status */
4255 ps = job->ps + job->nprocs - 1;
4256 status = ps->ps_status;
4258 /* "set -o pipefail" mode: use last _nonzero_ status */
4259 while (status == 0 && --ps >= job->ps)
4260 status = ps->ps_status;
4263 retval = WEXITSTATUS(status);
4264 if (!WIFEXITED(status)) {
4266 retval = WSTOPSIG(status);
4267 if (!WIFSTOPPED(status))
4270 /* XXX: limits number of signals */
4271 retval = WTERMSIG(status);
4273 if (retval == SIGINT)
4279 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4280 jobno(job), job->nprocs, status, retval));
4284 static int FAST_FUNC
4285 waitcmd(int argc UNUSED_PARAM, char **argv)
4296 /* wait for all jobs */
4300 if (!jp) /* no running procs */
4302 if (jp->state == JOBRUNNING)
4308 * "When bash is waiting for an asynchronous command via
4309 * the wait builtin, the reception of a signal for which a trap
4310 * has been set will cause the wait builtin to return immediately
4311 * with an exit status greater than 128, immediately after which
4312 * the trap is executed."
4314 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4315 /* if child sends us a signal *and immediately exits*,
4316 * dowait() returns pid > 0. Check this case,
4317 * not "if (dowait() < 0)"!
4326 if (**argv != '%') {
4327 pid_t pid = number(*argv);
4332 if (job->ps[job->nprocs - 1].ps_pid == pid)
4334 job = job->prev_job;
4337 job = getjob(*argv, 0);
4339 /* loop until process terminated or stopped */
4340 while (job->state == JOBRUNNING) {
4341 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4346 retval = getstatus(job);
4353 retval = 128 + pending_sig;
4362 struct job *jp, *jq;
4364 len = njobs * sizeof(*jp);
4366 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4368 offset = (char *)jp - (char *)jq;
4370 /* Relocate pointers */
4373 jq = (struct job *)((char *)jq + l);
4377 #define joff(p) ((struct job *)((char *)(p) + l))
4378 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4379 if (joff(jp)->ps == &jq->ps0)
4380 jmove(joff(jp)->ps);
4381 if (joff(jp)->prev_job)
4382 jmove(joff(jp)->prev_job);
4392 jp = (struct job *)((char *)jp + len);
4396 } while (--jq >= jp);
4401 * Return a new job structure.
4402 * Called with interrupts off.
4405 makejob(/*union node *node,*/ int nprocs)
4410 for (i = njobs, jp = jobtab; ; jp++) {
4417 if (jp->state != JOBDONE || !jp->waited)
4426 memset(jp, 0, sizeof(*jp));
4428 /* jp->jobctl is a bitfield.
4429 * "jp->jobctl |= jobctl" likely to give awful code */
4433 jp->prev_job = curjob;
4438 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4440 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4447 * Return a string identifying a command (to be printed by the
4450 static char *cmdnextc;
4453 cmdputs(const char *s)
4455 static const char vstype[VSTYPE + 1][3] = {
4456 "", "}", "-", "+", "?", "=",
4457 "%", "%%", "#", "##"
4458 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4461 const char *p, *str;
4465 unsigned char subtype = 0;
4469 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4471 while ((c = *p++) != '\0') {
4479 if ((subtype & VSTYPE) == VSLENGTH)
4485 str = "\"}" + !(quoted & 1);
4492 #if ENABLE_SH_MATH_SUPPORT
4507 if ((subtype & VSTYPE) != VSNORMAL)
4509 str = vstype[subtype & VSTYPE];
4510 if (subtype & VSNUL)
4519 /* These can only happen inside quotes */
4532 while ((c = *str++) != '\0') {
4535 } /* while *p++ not NUL */
4538 USTPUTC('"', nextc);
4544 /* cmdtxt() and cmdlist() call each other */
4545 static void cmdtxt(union node *n);
4548 cmdlist(union node *np, int sep)
4550 for (; np; np = np->narg.next) {
4554 if (sep && np->narg.next)
4560 cmdtxt(union node *n)
4563 struct nodelist *lp;
4574 lp = n->npipe.cmdlist;
4592 cmdtxt(n->nbinary.ch1);
4608 cmdtxt(n->nif.test);
4610 if (n->nif.elsepart) {
4611 cmdtxt(n->nif.ifpart);
4613 n = n->nif.elsepart;
4631 cmdtxt(n->nbinary.ch1);
4641 cmdputs(n->nfor.var);
4643 cmdlist(n->nfor.args, 1);
4648 cmdputs(n->narg.text);
4652 cmdlist(n->ncmd.args, 1);
4653 cmdlist(n->ncmd.redirect, 0);
4666 cmdputs(n->ncase.expr->narg.text);
4668 for (np = n->ncase.cases; np; np = np->nclist.next) {
4669 cmdtxt(np->nclist.pattern);
4671 cmdtxt(np->nclist.body);
4685 #if ENABLE_ASH_BASH_COMPAT
4700 cmdputs(utoa(n->nfile.fd));
4702 if (n->type == NTOFD || n->type == NFROMFD) {
4703 cmdputs(utoa(n->ndup.dupfd));
4712 commandtext(union node *n)
4716 STARTSTACKSTR(cmdnextc);
4718 name = stackblock();
4719 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4720 return ckstrdup(name);
4725 * Fork off a subshell. If we are doing job control, give the subshell its
4726 * own process group. Jp is a job structure that the job is to be added to.
4727 * N is the command that will be evaluated by the child. Both jp and n may
4728 * be NULL. The mode parameter can be one of the following:
4729 * FORK_FG - Fork off a foreground process.
4730 * FORK_BG - Fork off a background process.
4731 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4732 * process group even if job control is on.
4734 * When job control is turned off, background processes have their standard
4735 * input redirected to /dev/null (except for the second and later processes
4738 * Called with interrupts off.
4741 * Clear traps on a fork.
4749 for (tp = trap; tp < &trap[NSIG]; tp++) {
4750 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4751 if (trap_ptr == trap)
4753 /* else: it "belongs" to trap_ptr vector, don't free */
4755 if ((tp - trap) != 0)
4756 setsignal(tp - trap);
4763 /* Lives far away from here, needed for forkchild */
4764 static void closescript(void);
4766 /* Called after fork(), in child */
4767 /* jp and n are NULL when called by openhere() for heredoc support */
4768 static NOINLINE void
4769 forkchild(struct job *jp, union node *n, int mode)
4773 TRACE(("Child shell %d\n", getpid()));
4777 /* man bash: "Non-builtin commands run by bash have signal handlers
4778 * set to the values inherited by the shell from its parent".
4779 * Do we do it correctly? */
4783 if (mode == FORK_NOJOB /* is it `xxx` ? */
4784 && n && n->type == NCMD /* is it single cmd? */
4785 /* && n->ncmd.args->type == NARG - always true? */
4786 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4787 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4788 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4790 TRACE(("Trap hack\n"));
4791 /* Awful hack for `trap` or $(trap).
4793 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4794 * contains an example where "trap" is executed in a subshell:
4796 * save_traps=$(trap)
4798 * eval "$save_traps"
4800 * Standard does not say that "trap" in subshell shall print
4801 * parent shell's traps. It only says that its output
4802 * must have suitable form, but then, in the above example
4803 * (which is not supposed to be normative), it implies that.
4805 * bash (and probably other shell) does implement it
4806 * (traps are reset to defaults, but "trap" still shows them),
4807 * but as a result, "trap" logic is hopelessly messed up:
4810 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4811 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4812 * # true | trap <--- trap is in subshell - no output (ditto)
4813 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4814 * trap -- 'echo Ho' SIGWINCH
4815 * # echo `(trap)` <--- in subshell in subshell - output
4816 * trap -- 'echo Ho' SIGWINCH
4817 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4818 * trap -- 'echo Ho' SIGWINCH
4820 * The rules when to forget and when to not forget traps
4821 * get really complex and nonsensical.
4823 * Our solution: ONLY bare $(trap) or `trap` is special.
4825 /* Save trap handler strings for trap builtin to print */
4826 trap_ptr = xmemdup(trap, sizeof(trap));
4827 /* Fall through into clearing traps */
4831 /* do job control only in root shell */
4833 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4836 if (jp->nprocs == 0)
4839 pgrp = jp->ps[0].ps_pid;
4840 /* this can fail because we are doing it in the parent also */
4842 if (mode == FORK_FG)
4843 xtcsetpgrp(ttyfd, pgrp);
4848 if (mode == FORK_BG) {
4849 /* man bash: "When job control is not in effect,
4850 * asynchronous commands ignore SIGINT and SIGQUIT" */
4853 if (jp->nprocs == 0) {
4855 if (open(bb_dev_null, O_RDONLY) != 0)
4856 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4860 if (iflag) { /* why if iflag only? */
4865 * "In all cases, bash ignores SIGQUIT. Non-builtin
4866 * commands run by bash have signal handlers
4867 * set to the values inherited by the shell
4869 * Take care of the second rule: */
4873 if (n && n->type == NCMD
4874 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4876 TRACE(("Job hack\n"));
4877 /* "jobs": we do not want to clear job list for it,
4878 * instead we remove only _its_ own_ job from job list.
4879 * This makes "jobs .... | cat" more useful.
4885 for (jp = curjob; jp; jp = jp->prev_job)
4890 /* Called after fork(), in parent */
4892 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4895 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4897 TRACE(("In parent shell: child = %d\n", pid));
4899 /* jp is NULL when called by openhere() for heredoc support */
4900 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4906 if (mode != FORK_NOJOB && jp->jobctl) {
4909 if (jp->nprocs == 0)
4912 pgrp = jp->ps[0].ps_pid;
4913 /* This can fail because we are doing it in the child also */
4917 if (mode == FORK_BG) {
4918 backgndpid = pid; /* set $! */
4919 set_curjob(jp, CUR_RUNNING);
4922 struct procstat *ps = &jp->ps[jp->nprocs++];
4925 ps->ps_cmd = nullstr;
4927 if (doing_jobctl && n)
4928 ps->ps_cmd = commandtext(n);
4933 /* jp and n are NULL when called by openhere() for heredoc support */
4935 forkshell(struct job *jp, union node *n, int mode)
4939 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4942 TRACE(("Fork failed, errno=%d", errno));
4945 ash_msg_and_raise_error("can't fork");
4948 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4949 forkchild(jp, n, mode);
4951 forkparent(jp, n, mode, pid);
4957 * Wait for job to finish.
4959 * Under job control we have the problem that while a child process
4960 * is running interrupts generated by the user are sent to the child
4961 * but not to the shell. This means that an infinite loop started by
4962 * an interactive user may be hard to kill. With job control turned off,
4963 * an interactive user may place an interactive program inside a loop.
4964 * If the interactive program catches interrupts, the user doesn't want
4965 * these interrupts to also abort the loop. The approach we take here
4966 * is to have the shell ignore interrupt signals while waiting for a
4967 * foreground process to terminate, and then send itself an interrupt
4968 * signal if the child process was terminated by an interrupt signal.
4969 * Unfortunately, some programs want to do a bit of cleanup and then
4970 * exit on interrupt; unless these processes terminate themselves by
4971 * sending a signal to themselves (instead of calling exit) they will
4972 * confuse this approach.
4974 * Called with interrupts off.
4977 waitforjob(struct job *jp)
4981 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4984 while (jp->state == JOBRUNNING) {
4985 /* In non-interactive shells, we _can_ get
4986 * a keyboard signal here and be EINTRed,
4987 * but we just loop back, waiting for command to complete.
4990 * "If bash is waiting for a command to complete and receives
4991 * a signal for which a trap has been set, the trap
4992 * will not be executed until the command completes."
4994 * Reality is that even if trap is not set, bash
4995 * will not act on the signal until command completes.
4996 * Try this. sleep5intoff.c:
4997 * #include <signal.h>
4998 * #include <unistd.h>
5001 * sigemptyset(&set);
5002 * sigaddset(&set, SIGINT);
5003 * sigaddset(&set, SIGQUIT);
5004 * sigprocmask(SIG_BLOCK, &set, NULL);
5008 * $ bash -c './sleep5intoff; echo hi'
5009 * ^C^C^C^C <--- pressing ^C once a second
5011 * $ bash -c './sleep5intoff; echo hi'
5012 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5015 dowait(DOWAIT_BLOCK, jp);
5022 xtcsetpgrp(ttyfd, rootpid);
5024 * This is truly gross.
5025 * If we're doing job control, then we did a TIOCSPGRP which
5026 * caused us (the shell) to no longer be in the controlling
5027 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5028 * intuit from the subprocess exit status whether a SIGINT
5029 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5031 if (jp->sigint) /* TODO: do the same with all signals */
5032 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5034 if (jp->state == JOBDONE)
5041 * return 1 if there are stopped jobs, otherwise 0
5053 if (jp && jp->state == JOBSTOPPED) {
5054 out2str("You have stopped jobs.\n");
5064 * Code for dealing with input/output redirection.
5069 #define EMPTY -2 /* marks an unused slot in redirtab */
5070 #define CLOSED -3 /* marks a slot of previously-closed fd */
5073 * Open a file in noclobber mode.
5074 * The code was copied from bash.
5077 noclobberopen(const char *fname)
5080 struct stat finfo, finfo2;
5083 * If the file exists and is a regular file, return an error
5086 r = stat(fname, &finfo);
5087 if (r == 0 && S_ISREG(finfo.st_mode)) {
5093 * If the file was not present (r != 0), make sure we open it
5094 * exclusively so that if it is created before we open it, our open
5095 * will fail. Make sure that we do not truncate an existing file.
5096 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5097 * file was not a regular file, we leave O_EXCL off.
5100 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5101 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5103 /* If the open failed, return the file descriptor right away. */
5108 * OK, the open succeeded, but the file may have been changed from a
5109 * non-regular file to a regular file between the stat and the open.
5110 * We are assuming that the O_EXCL open handles the case where FILENAME
5111 * did not exist and is symlinked to an existing file between the stat
5116 * If we can open it and fstat the file descriptor, and neither check
5117 * revealed that it was a regular file, and the file has not been
5118 * replaced, return the file descriptor.
5120 if (fstat(fd, &finfo2) == 0
5121 && !S_ISREG(finfo2.st_mode)
5122 && finfo.st_dev == finfo2.st_dev
5123 && finfo.st_ino == finfo2.st_ino
5128 /* The file has been replaced. badness. */
5135 * Handle here documents. Normally we fork off a process to write the
5136 * data to a pipe. If the document is short, we can stuff the data in
5137 * the pipe without forking.
5139 /* openhere needs this forward reference */
5140 static void expandhere(union node *arg, int fd);
5142 openhere(union node *redir)
5148 ash_msg_and_raise_error("pipe call failed");
5149 if (redir->type == NHERE) {
5150 len = strlen(redir->nhere.doc->narg.text);
5151 if (len <= PIPE_BUF) {
5152 full_write(pip[1], redir->nhere.doc->narg.text, len);
5156 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5159 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5160 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5161 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5162 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5163 signal(SIGPIPE, SIG_DFL);
5164 if (redir->type == NHERE)
5165 full_write(pip[1], redir->nhere.doc->narg.text, len);
5167 expandhere(redir->nhere.doc, pip[1]);
5168 _exit(EXIT_SUCCESS);
5176 openredirect(union node *redir)
5181 switch (redir->nfile.type) {
5182 /* Can't happen, our single caller does this itself */
5188 return openhere(redir);
5191 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5192 * allocated space. Do it only when we know it is safe.
5194 fname = redir->nfile.expfname;
5196 switch (redir->nfile.type) {
5202 f = open(fname, O_RDONLY);
5207 f = open(fname, O_RDWR|O_CREAT, 0666);
5212 #if ENABLE_ASH_BASH_COMPAT
5215 /* Take care of noclobber mode. */
5217 f = noclobberopen(fname);
5224 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5229 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5237 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5239 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5243 * Copy a file descriptor to be >= 10. Throws exception on error.
5251 newfd = fcntl(from, F_DUPFD, 10);
5252 err = newfd < 0 ? errno : 0;
5255 ash_msg_and_raise_error("%d: %m", from);
5257 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5263 dup2_or_raise(int from, int to)
5267 newfd = (from != to) ? dup2(from, to) : to;
5269 /* Happens when source fd is not open: try "echo >&99" */
5270 ash_msg_and_raise_error("%d: %m", from);
5275 /* Struct def and variable are moved down to the first usage site */
5280 struct redirtab *next;
5282 struct two_fd_t two_fd[];
5284 #define redirlist (G_var.redirlist)
5286 COPYFD_RESTORE = (int)~(INT_MAX),
5290 need_to_remember(struct redirtab *rp, int fd)
5294 if (!rp) /* remembering was not requested */
5297 for (i = 0; i < rp->pair_count; i++) {
5298 if (rp->two_fd[i].orig == fd) {
5299 /* already remembered */
5306 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5308 is_hidden_fd(struct redirtab *rp, int fd)
5311 struct parsefile *pf;
5315 /* Check open scripts' fds */
5318 /* We skip pf_fd == 0 case because of the following case:
5319 * $ ash # running ash interactively
5321 * and in script.sh: "exec 9>&0".
5322 * Even though top-level pf_fd _is_ 0,
5323 * it's still ok to use it: "read" builtin uses it,
5324 * why should we cripple "exec" builtin?
5326 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5334 /* Check saved fds of redirects */
5335 fd |= COPYFD_RESTORE;
5336 for (i = 0; i < rp->pair_count; i++) {
5337 if (rp->two_fd[i].copy == fd) {
5345 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5346 * old file descriptors are stashed away so that the redirection can be
5347 * undone by calling popredir.
5349 /* flags passed to redirect */
5350 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5351 #define REDIR_SAVEFD2 03 /* set preverrout */
5353 redirect(union node *redir, int flags)
5355 struct redirtab *sv;
5360 int copied_fd2 = -1;
5369 if (flags & REDIR_PUSH) {
5370 union node *tmp = redir;
5373 #if ENABLE_ASH_BASH_COMPAT
5374 if (tmp->nfile.type == NTO2)
5377 tmp = tmp->nfile.next;
5379 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5380 sv->next = redirlist;
5381 sv->pair_count = sv_pos;
5383 while (sv_pos > 0) {
5385 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5391 fd = redir->nfile.fd;
5392 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5393 right_fd = redir->ndup.dupfd;
5394 //bb_error_msg("doing %d > %d", fd, right_fd);
5395 /* redirect from/to same file descriptor? */
5398 /* "echo >&10" and 10 is a fd opened to a sh script? */
5399 if (is_hidden_fd(sv, right_fd)) {
5400 errno = EBADF; /* as if it is closed */
5401 ash_msg_and_raise_error("%d: %m", right_fd);
5405 newfd = openredirect(redir); /* always >= 0 */
5407 /* Descriptor wasn't open before redirect.
5408 * Mark it for close in the future */
5409 if (need_to_remember(sv, fd)) {
5410 goto remember_to_close;
5415 #if ENABLE_ASH_BASH_COMPAT
5418 if (need_to_remember(sv, fd)) {
5419 /* Copy old descriptor */
5420 /* Careful to not accidentally "save"
5421 * to the same fd as right side fd in N>&M */
5422 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5423 i = fcntl(fd, F_DUPFD, minfd);
5424 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5425 * are closed in popredir() in the child, preventing them from leaking
5426 * into child. (popredir() also cleans up the mess in case of failures)
5431 /* Strange error (e.g. "too many files" EMFILE?) */
5435 ash_msg_and_raise_error("%d: %m", fd);
5438 /* EBADF: it is not open - good, remember to close it */
5441 } else { /* fd is open, save its copy */
5442 /* "exec fd>&-" should not close fds
5443 * which point to script file(s).
5444 * Force them to be restored afterwards */
5445 if (is_hidden_fd(sv, fd))
5446 i |= COPYFD_RESTORE;
5450 sv->two_fd[sv_pos].orig = fd;
5451 sv->two_fd[sv_pos].copy = i;
5455 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5456 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5457 /* Don't want to trigger debugging */
5461 dup2_or_raise(redir->ndup.dupfd, fd);
5463 } else if (fd != newfd) { /* move newfd to fd */
5464 dup2_or_raise(newfd, fd);
5465 #if ENABLE_ASH_BASH_COMPAT
5466 if (!(redir->nfile.type == NTO2 && fd == 2))
5470 #if ENABLE_ASH_BASH_COMPAT
5471 if (redir->nfile.type == NTO2 && fd == 1) {
5472 /* We already redirected it to fd 1, now copy it to 2 */
5478 } while ((redir = redir->nfile.next) != NULL);
5481 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5482 preverrout_fd = copied_fd2;
5486 * Undo the effects of the last redirection.
5489 popredir(int drop, int restore)
5491 struct redirtab *rp;
5494 if (redirlist == NULL)
5498 for (i = 0; i < rp->pair_count; i++) {
5499 int fd = rp->two_fd[i].orig;
5500 int copy = rp->two_fd[i].copy;
5501 if (copy == CLOSED) {
5506 if (copy != EMPTY) {
5507 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5508 copy &= ~COPYFD_RESTORE;
5510 dup2_or_raise(copy, fd);
5512 close(copy & ~COPYFD_RESTORE);
5515 redirlist = rp->next;
5521 * Undo all redirections. Called on error or interrupt.
5525 redirectsafe(union node *redir, int flags)
5528 volatile int saveint;
5529 struct jmploc *volatile savehandler = exception_handler;
5530 struct jmploc jmploc;
5533 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5534 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5536 exception_handler = &jmploc;
5537 redirect(redir, flags);
5539 exception_handler = savehandler;
5540 if (err && exception_type != EXERROR)
5541 longjmp(exception_handler->loc, 1);
5542 RESTORE_INT(saveint);
5547 /* ============ Routines to expand arguments to commands
5549 * We have to deal with backquotes, shell variables, and file metacharacters.
5552 #if ENABLE_SH_MATH_SUPPORT
5554 ash_arith(const char *s)
5556 arith_state_t math_state;
5559 math_state.lookupvar = lookupvar;
5560 math_state.setvar = setvar0;
5561 //math_state.endofname = endofname;
5564 result = arith(&math_state, s);
5565 if (math_state.errmsg)
5566 ash_msg_and_raise_error(math_state.errmsg);
5576 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5577 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5578 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5579 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5580 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5581 * POSIX says for this case:
5582 * Pathname expansion shall not be performed on the word by a
5583 * non-interactive shell; an interactive shell may perform it, but shall
5584 * do so only when the expansion would result in one word.
5585 * Currently, our code complies to the above rule by never globbing
5586 * redirection filenames.
5587 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5588 * (this means that on a typical Linux distro, bash almost always
5589 * performs globbing, and thus diverges from what we do).
5591 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5592 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5593 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5594 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5595 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5599 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5600 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5601 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5602 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5603 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5605 /* Add CTLESC when necessary. */
5606 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5607 /* Do not skip NUL characters. */
5608 #define QUOTES_KEEPNUL EXP_TILDE
5611 * Structure specifying which parts of the string should be searched
5612 * for IFS characters.
5615 struct ifsregion *next; /* next region in list */
5616 int begoff; /* offset of start of region */
5617 int endoff; /* offset of end of region */
5618 int nulonly; /* search for nul bytes only */
5622 struct strlist *list;
5623 struct strlist **lastp;
5626 /* output of current string */
5627 static char *expdest;
5628 /* list of back quote expressions */
5629 static struct nodelist *argbackq;
5630 /* first struct in list of ifs regions */
5631 static struct ifsregion ifsfirst;
5632 /* last struct in list */
5633 static struct ifsregion *ifslastp;
5634 /* holds expanded arg list */
5635 static struct arglist exparg;
5640 #if !ENABLE_SH_MATH_SUPPORT
5641 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5642 typedef long arith_t;
5643 # define ARITH_FMT "%ld"
5650 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5651 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5652 STADJUST(len, expdest);
5657 * Break the argument string into pieces based upon IFS and add the
5658 * strings to the argument list. The regions of the string to be
5659 * searched for IFS characters have been stored by recordregion.
5662 ifsbreakup(char *string, struct arglist *arglist)
5664 struct ifsregion *ifsp;
5669 const char *ifs, *realifs;
5674 if (ifslastp != NULL) {
5677 realifs = ifsset() ? ifsval() : defifs;
5680 p = string + ifsp->begoff;
5681 nulonly = ifsp->nulonly;
5682 ifs = nulonly ? nullstr : realifs;
5684 while (p < string + ifsp->endoff) {
5686 if ((unsigned char)*p == CTLESC)
5688 if (!strchr(ifs, *p)) {
5693 ifsspc = (strchr(defifs, *p) != NULL);
5694 /* Ignore IFS whitespace at start */
5695 if (q == start && ifsspc) {
5701 sp = stzalloc(sizeof(*sp));
5703 *arglist->lastp = sp;
5704 arglist->lastp = &sp->next;
5708 if (p >= string + ifsp->endoff) {
5712 if ((unsigned char)*p == CTLESC)
5714 if (strchr(ifs, *p) == NULL) {
5718 if (strchr(defifs, *p) == NULL) {
5733 } while (ifsp != NULL);
5742 sp = stzalloc(sizeof(*sp));
5744 *arglist->lastp = sp;
5745 arglist->lastp = &sp->next;
5751 struct ifsregion *p = ifsfirst.next;
5758 struct ifsregion *ifsp;
5763 ifsfirst.next = NULL;
5770 esclen(const char *start, const char *p)
5774 while (p > start && (unsigned char)*--p == CTLESC) {
5781 * Remove any CTLESC characters from a string.
5784 rmescapes(char *str, int flag)
5786 static const char qchars[] ALIGN1 = {
5787 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5791 unsigned protect_against_glob;
5793 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5795 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5801 if (flag & RMESCAPE_ALLOC) {
5802 size_t len = p - str;
5803 size_t fulllen = len + strlen(p) + 1;
5805 if (flag & RMESCAPE_GROW) {
5806 int strloc = str - (char *)stackblock();
5807 r = makestrspace(fulllen, expdest);
5808 /* p and str may be invalidated by makestrspace */
5809 str = (char *)stackblock() + strloc;
5811 } else if (flag & RMESCAPE_HEAP) {
5812 r = ckmalloc(fulllen);
5814 r = stalloc(fulllen);
5818 q = (char *)memcpy(q, str, len) + len;
5823 globbing = flag & RMESCAPE_GLOB;
5824 protect_against_glob = globbing;
5826 if ((unsigned char)*p == CTLQUOTEMARK) {
5827 // Note: both inquotes and protect_against_glob only affect whether
5828 inquotes = ~inquotes;
5830 protect_against_glob = globbing;
5833 if ((unsigned char)*p == CTLESC) {
5837 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5839 if (protect_against_glob) {
5842 } else if (*p == '\\' && !inquotes) {
5843 /* naked back slash */
5844 protect_against_glob = 0;
5847 #if ENABLE_ASH_BASH_COMPAT
5848 else if (*p == '/' && slash) {
5849 /* stop handling globbing and mark location of slash */
5850 globbing = slash = 0;
5854 protect_against_glob = globbing;
5859 if (flag & RMESCAPE_GROW) {
5861 STADJUST(q - r + 1, expdest);
5865 #define pmatch(a, b) !fnmatch((a), (b), 0)
5868 * Prepare a pattern for a expmeta (internal glob(3)) call.
5870 * Returns an stalloced string.
5873 preglob(const char *pattern, int flag)
5875 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5879 * Put a string on the stack.
5882 memtodest(const char *p, size_t len, int syntax, int quotes)
5889 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5892 unsigned char c = *p++;
5894 if (quotes & QUOTES_ESC) {
5895 int n = SIT(c, syntax);
5897 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5904 } else if (!(quotes & QUOTES_KEEPNUL))
5913 strtodest(const char *p, int syntax, int quotes)
5915 size_t len = strlen(p);
5916 memtodest(p, len, syntax, quotes);
5921 * Record the fact that we have to scan this region of the
5922 * string for IFS characters.
5925 recordregion(int start, int end, int nulonly)
5927 struct ifsregion *ifsp;
5929 if (ifslastp == NULL) {
5933 ifsp = ckzalloc(sizeof(*ifsp));
5934 /*ifsp->next = NULL; - ckzalloc did it */
5935 ifslastp->next = ifsp;
5939 ifslastp->begoff = start;
5940 ifslastp->endoff = end;
5941 ifslastp->nulonly = nulonly;
5945 removerecordregions(int endoff)
5947 if (ifslastp == NULL)
5950 if (ifsfirst.endoff > endoff) {
5951 while (ifsfirst.next) {
5952 struct ifsregion *ifsp;
5954 ifsp = ifsfirst.next->next;
5955 free(ifsfirst.next);
5956 ifsfirst.next = ifsp;
5959 if (ifsfirst.begoff > endoff) {
5962 ifslastp = &ifsfirst;
5963 ifsfirst.endoff = endoff;
5968 ifslastp = &ifsfirst;
5969 while (ifslastp->next && ifslastp->next->begoff < endoff)
5970 ifslastp = ifslastp->next;
5971 while (ifslastp->next) {
5972 struct ifsregion *ifsp;
5974 ifsp = ifslastp->next->next;
5975 free(ifslastp->next);
5976 ifslastp->next = ifsp;
5979 if (ifslastp->endoff > endoff)
5980 ifslastp->endoff = endoff;
5984 exptilde(char *startp, char *p, int flags)
5990 int quotes = flags & QUOTES_ESC;
5994 while ((c = *++p) != '\0') {
6001 if (flags & EXP_VARTILDE)
6011 if (*name == '\0') {
6012 home = lookupvar("HOME");
6014 pw = getpwnam(name);
6019 if (!home || !*home)
6022 strtodest(home, SQSYNTAX, quotes);
6030 * Execute a command inside back quotes. If it's a builtin command, we
6031 * want to save its output in a block obtained from malloc. Otherwise
6032 * we fork off a subprocess and get the output of the command via a pipe.
6033 * Should be called with interrupts off.
6035 struct backcmd { /* result of evalbackcmd */
6036 int fd; /* file descriptor to read from */
6037 int nleft; /* number of chars in buffer */
6038 char *buf; /* buffer */
6039 struct job *jp; /* job structure for command */
6042 /* These forward decls are needed to use "eval" code for backticks handling: */
6043 #define EV_EXIT 01 /* exit after evaluating tree */
6044 static int evaltree(union node *, int);
6046 static void FAST_FUNC
6047 evalbackcmd(union node *n, struct backcmd *result)
6061 ash_msg_and_raise_error("pipe call failed");
6062 jp = makejob(/*n,*/ 1);
6063 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6069 dup2_or_raise(pip[1], 1);
6072 /* TODO: eflag clearing makes the following not abort:
6073 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6074 * which is what bash does (unless it is in POSIX mode).
6075 * dash deleted "eflag = 0" line in the commit
6076 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6077 * [EVAL] Don't clear eflag in evalbackcmd
6078 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6082 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6087 result->fd = pip[0];
6091 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6092 result->fd, result->buf, result->nleft, result->jp));
6096 * Expand stuff in backwards quotes.
6099 expbackq(union node *cmd, int flag)
6107 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6108 struct stackmark smark;
6111 startloc = expdest - (char *)stackblock();
6112 pushstackmark(&smark, startloc);
6113 evalbackcmd(cmd, &in);
6114 popstackmark(&smark);
6121 memtodest(p, i, syntax, flag & QUOTES_ESC);
6125 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6126 TRACE(("expbackq: read returns %d\n", i));
6135 back_exitstatus = waitforjob(in.jp);
6139 /* Eat all trailing newlines */
6141 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6145 if (!(flag & EXP_QUOTED))
6146 recordregion(startloc, dest - (char *)stackblock(), 0);
6147 TRACE(("evalbackq: size:%d:'%.*s'\n",
6148 (int)((dest - (char *)stackblock()) - startloc),
6149 (int)((dest - (char *)stackblock()) - startloc),
6150 stackblock() + startloc));
6153 #if ENABLE_SH_MATH_SUPPORT
6155 * Expand arithmetic expression. Backup to start of expression,
6156 * evaluate, place result in (backed up) result, adjust string position.
6168 * This routine is slightly over-complicated for
6169 * efficiency. Next we scan backwards looking for the
6170 * start of arithmetic.
6172 start = stackblock();
6179 while ((unsigned char)*p != CTLARI) {
6183 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6188 esc = esclen(start, p);
6198 removerecordregions(begoff);
6202 if (flag & QUOTES_ESC)
6203 rmescapes(p + 1, 0);
6205 len = cvtnum(ash_arith(p + 1));
6207 if (!(flag & EXP_QUOTED))
6208 recordregion(begoff, begoff + len, 0);
6212 /* argstr needs it */
6213 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6216 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6217 * characters to allow for further processing. Otherwise treat
6218 * $@ like $* since no splitting will be performed.
6220 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6221 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6222 * for correct expansion of "B=$A" word.
6225 argstr(char *p, int flags, struct strlist *var_str_list)
6227 static const char spclchars[] ALIGN1 = {
6235 #if ENABLE_SH_MATH_SUPPORT
6240 const char *reject = spclchars;
6241 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6246 if (!(flags & EXP_VARTILDE)) {
6248 } else if (flags & EXP_VARTILDE2) {
6253 if (flags & EXP_TILDE) {
6256 flags &= ~EXP_TILDE;
6260 p = exptilde(p, q, flags);
6263 startloc = expdest - (char *)stackblock();
6267 length += strcspn(p + length, reject);
6271 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6273 /* c == '=' || c == ':' || c == CTLENDARI */
6279 expdest = stack_nputstr(p, length, expdest);
6280 newloc = expdest - (char *)stackblock();
6281 if (breakall && !inquotes && newloc > startloc) {
6282 recordregion(startloc, newloc, 0);
6293 if (flags & EXP_VARTILDE2) {
6297 flags |= EXP_VARTILDE2;
6302 * sort of a hack - expand tildes in variable
6303 * assignments (after the first '=' and after ':'s).
6312 case CTLENDVAR: /* ??? */
6315 inquotes ^= EXP_QUOTED;
6316 /* "$@" syntax adherence hack */
6317 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6318 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6322 if (flags & QUOTES_ESC) {
6333 * Quoted parameter expansion pattern: remove quote
6334 * unless inside inner quotes or we have a literal
6337 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6338 EXP_QPAT && *p != '\\')
6343 TRACE(("argstr: evalvar('%s')\n", p));
6344 p = evalvar(p, flags | inquotes, var_str_list);
6345 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6348 expbackq(argbackq->n, flags | inquotes);
6349 argbackq = argbackq->next;
6351 #if ENABLE_SH_MATH_SUPPORT
6354 expari(flags | inquotes);
6363 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6364 char *pattern, int quotes, int zero)
6373 const char *s = loc2;
6380 match = pmatch(pattern, s);
6385 if (quotes && (unsigned char)*loc == CTLESC)
6394 scanright(char *startp, char *rmesc, char *rmescend,
6395 char *pattern, int quotes, int match_at_start)
6397 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6398 int try2optimize = match_at_start;
6404 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6405 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6406 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6408 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6409 * and on each iteration they go back two/one char until they reach the beginning.
6410 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6412 /* TODO: document in what other circumstances we are called. */
6414 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6417 const char *s = loc2;
6418 if (match_at_start) {
6422 match = pmatch(pattern, s);
6423 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6427 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6429 /* Maybe we can optimize this:
6430 * if pattern ends with unescaped *, we can avoid checking
6431 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6432 * it wont match truncated "raw_value_of_" strings too.
6434 unsigned plen = strlen(pattern);
6435 /* Does it end with "*"? */
6436 if (plen != 0 && pattern[--plen] == '*') {
6437 /* "xxxx*" is not escaped */
6438 /* "xxx\*" is escaped */
6439 /* "xx\\*" is not escaped */
6440 /* "x\\\*" is escaped */
6442 while (plen != 0 && pattern[--plen] == '\\')
6445 break; /* ends with unescaped "*" */
6453 esc = esclen(startp, loc);
6464 static void varunset(const char *, const char *, const char *, int) NORETURN;
6466 varunset(const char *end, const char *var, const char *umsg, int varflags)
6472 msg = "parameter not set";
6474 if ((unsigned char)*end == CTLENDVAR) {
6475 if (varflags & VSNUL)
6481 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6485 subevalvar(char *p, char *varname, int strloc, int subtype,
6486 int startloc, int varflags, int flag, struct strlist *var_str_list)
6488 struct nodelist *saveargbackq = argbackq;
6489 int quotes = flag & QUOTES_ESC;
6492 char *rmesc, *rmescend;
6494 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6495 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6496 int amount, resetloc;
6497 IF_ASH_BASH_COMPAT(int workloc;)
6499 char *(*scan)(char*, char*, char*, char*, int, int);
6501 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6502 // p, varname, strloc, subtype, startloc, varflags, quotes);
6504 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6505 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6507 STPUTC('\0', expdest);
6508 argbackq = saveargbackq;
6509 startp = (char *)stackblock() + startloc;
6513 setvar0(varname, startp);
6514 amount = startp - expdest;
6515 STADJUST(amount, expdest);
6519 varunset(p, varname, startp, varflags);
6522 #if ENABLE_ASH_BASH_COMPAT
6524 //TODO: support more general format ${v:EXPR:EXPR},
6525 // where EXPR follows $(()) rules
6526 loc = str = stackblock() + strloc;
6527 /* Read POS in ${var:POS:LEN} */
6528 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6529 len = str - startp - 1;
6531 /* *loc != '\0', guaranteed by parser */
6535 /* Adjust the length by the number of escapes */
6536 for (ptr = startp; ptr < (str - 1); ptr++) {
6537 if ((unsigned char)*ptr == CTLESC) {
6545 if (*loc++ == ':') {
6549 /* Skip POS in ${var:POS:LEN} */
6551 while (*loc && *loc != ':') {
6553 * bash complains on: var=qwe; echo ${var:1a:123}
6555 ash_msg_and_raise_error(msg_illnum, str);
6559 if (*loc++ == ':') {
6564 /* ${VAR:$((-n)):l} starts n chars from the end */
6565 pos = orig_len + pos;
6567 if ((unsigned)pos >= orig_len) {
6568 /* apart from obvious ${VAR:999999:l},
6569 * covers ${VAR:$((-9999999)):l} - result is ""
6575 if (len > (orig_len - pos))
6576 len = orig_len - pos;
6578 for (str = startp; pos; str++, pos--) {
6579 if (quotes && (unsigned char)*str == CTLESC)
6582 for (loc = startp; len; len--) {
6583 if (quotes && (unsigned char)*str == CTLESC)
6588 amount = loc - expdest;
6589 STADJUST(amount, expdest);
6594 resetloc = expdest - (char *)stackblock();
6596 /* We'll comeback here if we grow the stack while handling
6597 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6598 * stack will need rebasing, and we'll need to remove our work
6601 IF_ASH_BASH_COMPAT(restart:)
6603 amount = expdest - ((char *)stackblock() + resetloc);
6604 STADJUST(-amount, expdest);
6605 startp = (char *)stackblock() + startloc;
6608 rmescend = (char *)stackblock() + strloc;
6610 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6611 if (rmesc != startp) {
6613 startp = (char *)stackblock() + startloc;
6617 str = (char *)stackblock() + strloc;
6619 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6620 * The result is a_\_z_c (not a\_\_z_c)!
6622 * The search pattern and replace string treat backslashes differently!
6623 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6624 * and string. It's only used on the first call.
6626 preglob(str, IF_ASH_BASH_COMPAT(
6627 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6628 RMESCAPE_SLASH :) 0);
6630 #if ENABLE_ASH_BASH_COMPAT
6631 workloc = expdest - (char *)stackblock();
6632 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6636 repl = strchr(str, CTLESC);
6642 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6644 /* If there's no pattern to match, return the expansion unmolested */
6653 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6654 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6656 /* No match, advance */
6657 char *restart_detect = stackblock();
6659 STPUTC(*idx, expdest);
6660 if (quotes && (unsigned char)*idx == CTLESC) {
6663 STPUTC(*idx, expdest);
6665 if (stackblock() != restart_detect)
6670 /* continue; - prone to quadratic behavior, smarter code: */
6673 if (str[0] == '*') {
6674 /* Pattern is "*foo". If "*foo" does not match "long_string",
6675 * it would never match "ong_string" etc, no point in trying.
6682 if (subtype == VSREPLACEALL) {
6684 if (quotes && (unsigned char)*idx == CTLESC)
6693 //bb_error_msg("repl:'%s'", repl);
6694 for (loc = (char*)repl; *loc; loc++) {
6695 char *restart_detect = stackblock();
6696 if (quotes && *loc == '\\') {
6697 STPUTC(CTLESC, expdest);
6700 STPUTC(*loc, expdest);
6701 if (stackblock() != restart_detect)
6706 if (subtype == VSREPLACE) {
6707 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6709 char *restart_detect = stackblock();
6710 STPUTC(*idx, expdest);
6711 if (stackblock() != restart_detect)
6720 /* We've put the replaced text into a buffer at workloc, now
6721 * move it to the right place and adjust the stack.
6723 STPUTC('\0', expdest);
6724 startp = (char *)stackblock() + startloc;
6725 memmove(startp, (char *)stackblock() + workloc, len + 1);
6726 //bb_error_msg("startp:'%s'", startp);
6727 amount = expdest - (startp + len);
6728 STADJUST(-amount, expdest);
6731 #endif /* ENABLE_ASH_BASH_COMPAT */
6733 subtype -= VSTRIMRIGHT;
6735 if (subtype < 0 || subtype > 7)
6738 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6739 zero = subtype >> 1;
6740 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6741 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6743 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6746 memmove(startp, loc, str - loc);
6747 loc = startp + (str - loc) - 1;
6750 amount = loc - expdest;
6751 STADJUST(amount, expdest);
6757 * Add the value of a specialized variable to the stack string.
6758 * name parameter (examples):
6759 * ash -c 'echo $1' name:'1='
6760 * ash -c 'echo $qwe' name:'qwe='
6761 * ash -c 'echo $$' name:'$='
6762 * ash -c 'echo ${$}' name:'$='
6763 * ash -c 'echo ${$##q}' name:'$=q'
6764 * ash -c 'echo ${#$}' name:'$='
6765 * note: examples with bad shell syntax:
6766 * ash -c 'echo ${#$1}' name:'$=1'
6767 * ash -c 'echo ${#1#}' name:'1=#'
6769 static NOINLINE ssize_t
6770 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6777 int quoted = *quotedp;
6778 int subtype = varflags & VSTYPE;
6779 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6780 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6783 sep = (flags & EXP_FULL) << CHAR_BIT;
6784 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6794 num = shellparam.nparam;
6802 goto check_1char_name;
6804 expdest = makestrspace(NOPTS, expdest);
6805 for (i = NOPTS - 1; i >= 0; i--) {
6807 USTPUTC(optletters(i), expdest);
6813 /* handles cases similar to ${#$1} */
6814 if (name[2] != '\0')
6815 raise_error_syntax("bad substitution");
6828 sep |= ifsset() ? ifsval()[0] : ' ';
6835 while ((p = *ap++) != NULL) {
6836 len += strtodest(p, syntax, quotes);
6840 memtodest(&sepc, 1, syntax, quotes);
6855 num = atoi(name); /* number(name) fails on ${N#str} etc */
6856 if (num < 0 || num > shellparam.nparam)
6858 p = num ? shellparam.p[num - 1] : arg0;
6861 /* NB: name has form "VAR=..." */
6863 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6864 * which should be considered before we check variables. */
6866 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6870 str = var_str_list->text;
6871 eq = strchr(str, '=');
6872 if (!eq) /* stop at first non-assignment */
6875 if (name_len == (unsigned)(eq - str)
6876 && strncmp(str, name, name_len) == 0
6879 /* goto value; - WRONG! */
6880 /* think "A=1 A=2 B=$A" */
6882 var_str_list = var_str_list->next;
6883 } while (var_str_list);
6887 p = lookupvar(name);
6892 len = strtodest(p, syntax, quotes);
6893 #if ENABLE_UNICODE_SUPPORT
6894 if (subtype == VSLENGTH && len > 0) {
6895 reinit_unicode_for_ash();
6896 if (unicode_status == UNICODE_ON) {
6897 STADJUST(-len, expdest);
6899 len = unicode_strlen(p);
6907 STADJUST(-len, expdest);
6912 * Expand a variable, and return a pointer to the next character in the
6916 evalvar(char *p, int flag, struct strlist *var_str_list)
6927 varflags = (unsigned char) *p++;
6928 subtype = varflags & VSTYPE;
6931 raise_error_syntax("bad substitution");
6933 quoted = flag & EXP_QUOTED;
6935 easy = (!quoted || (*var == '@' && shellparam.nparam));
6936 startloc = expdest - (char *)stackblock();
6937 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6940 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6941 if (varflags & VSNUL)
6944 if (subtype == VSPLUS) {
6945 varlen = -1 - varlen;
6949 if (subtype == VSMINUS) {
6954 flag | EXP_TILDE | EXP_WORD,
6962 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6966 subevalvar(p, var, 0, subtype, startloc, varflags,
6967 flag & ~QUOTES_ESC, var_str_list);
6970 * Remove any recorded regions beyond
6973 removerecordregions(startloc);
6977 if (varlen < 0 && uflag)
6978 varunset(p, var, 0, 0);
6980 if (subtype == VSLENGTH) {
6981 cvtnum(varlen > 0 ? varlen : 0);
6985 if (subtype == VSNORMAL) {
6989 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6998 case VSTRIMRIGHTMAX:
6999 #if ENABLE_ASH_BASH_COMPAT
7012 * Terminate the string and start recording the pattern
7015 STPUTC('\0', expdest);
7016 patloc = expdest - (char *)stackblock();
7017 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7018 startloc, varflags, flag, var_str_list)) {
7019 int amount = expdest - (
7020 (char *)stackblock() + patloc - 1
7022 STADJUST(-amount, expdest);
7024 /* Remove any recorded regions beyond start of variable */
7025 removerecordregions(startloc);
7030 if (subtype != VSNORMAL) { /* skip to end of alternative */
7033 unsigned char c = *p++;
7036 else if (c == CTLBACKQ) {
7038 argbackq = argbackq->next;
7039 } else if (c == CTLVAR) {
7040 if ((*p++ & VSTYPE) != VSNORMAL)
7042 } else if (c == CTLENDVAR) {
7052 * Add a file name to the list.
7055 addfname(const char *name)
7059 sp = stzalloc(sizeof(*sp));
7060 sp->text = sstrdup(name);
7062 exparg.lastp = &sp->next;
7065 /* If we want to use glob() from libc... */
7066 #if !ENABLE_ASH_INTERNAL_GLOB
7068 /* Add the result of glob() to the list */
7070 addglob(const glob_t *pglob)
7072 char **p = pglob->gl_pathv;
7079 expandmeta(struct strlist *str /*, int flag*/)
7081 /* TODO - EXP_REDIR */
7091 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7106 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7107 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7108 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7110 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7111 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7112 // Which means you need to unescape the string, right? Not so fast:
7113 // if there _is_ a file named "file\?" (with backslash), it is returned
7114 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7115 // You DONT KNOW by looking at the result whether you need to unescape it.
7117 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7118 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7119 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7120 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7121 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7122 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7123 i = glob(p, 0, NULL, &pglob);
7124 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7129 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7130 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7131 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7143 *exparg.lastp = str;
7144 rmescapes(str->text, 0);
7145 exparg.lastp = &str->next;
7147 default: /* GLOB_NOSPACE */
7150 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7157 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7160 * Do metacharacter (i.e. *, ?, [...]) expansion.
7163 expmeta(char *expdir, char *enddir, char *name)
7179 for (p = name; esc = 0, *p; p += esc + 1) {
7180 if (*p == '*' || *p == '?')
7182 else if (*p == '[') {
7189 if (*q == '/' || *q == '\0')
7199 if (p[esc] == '/') {
7202 start = p + esc + 1;
7206 if (metaflag == 0) { /* we've reached the end of the file name */
7207 if (enddir != expdir)
7215 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7226 } while (p < start);
7228 if (enddir == expdir) {
7230 } else if (enddir == expdir + 1 && *expdir == '/') {
7239 if (enddir != expdir)
7241 if (*endname == 0) {
7254 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7255 if (dp->d_name[0] == '.' && !matchdot)
7257 if (pmatch(start, dp->d_name)) {
7259 strcpy(enddir, dp->d_name);
7262 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7265 expmeta(expdir, p, endname);
7271 endname[-esc - 1] = esc ? '\\' : '/';
7274 static struct strlist *
7275 msort(struct strlist *list, int len)
7277 struct strlist *p, *q = NULL;
7278 struct strlist **lpp;
7286 for (n = half; --n >= 0;) {
7290 q->next = NULL; /* terminate first half of list */
7291 q = msort(list, half); /* sort first half of list */
7292 p = msort(p, len - half); /* sort second half */
7295 #if ENABLE_LOCALE_SUPPORT
7296 if (strcoll(p->text, q->text) < 0)
7298 if (strcmp(p->text, q->text) < 0)
7322 * Sort the results of file name expansion. It calculates the number of
7323 * strings to sort and then calls msort (short for merge sort) to do the
7326 static struct strlist *
7327 expsort(struct strlist *str)
7333 for (sp = str; sp; sp = sp->next)
7335 return msort(str, len);
7339 expandmeta(struct strlist *str /*, int flag*/)
7341 static const char metachars[] ALIGN1 = {
7344 /* TODO - EXP_REDIR */
7348 struct strlist **savelastp;
7354 if (!strpbrk(str->text, metachars))
7356 savelastp = exparg.lastp;
7359 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7361 int i = strlen(str->text);
7362 //BUGGY estimation of how long expanded name can be
7363 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7365 expmeta(expdir, expdir, p);
7370 if (exparg.lastp == savelastp) {
7375 *exparg.lastp = str;
7376 rmescapes(str->text, 0);
7377 exparg.lastp = &str->next;
7379 *exparg.lastp = NULL;
7380 *savelastp = sp = expsort(*savelastp);
7381 while (sp->next != NULL)
7383 exparg.lastp = &sp->next;
7388 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7391 * Perform variable substitution and command substitution on an argument,
7392 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7393 * perform splitting and file name expansion. When arglist is NULL, perform
7394 * here document expansion.
7397 expandarg(union node *arg, struct arglist *arglist, int flag)
7402 argbackq = arg->narg.backquote;
7403 STARTSTACKSTR(expdest);
7404 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7405 argstr(arg->narg.text, flag,
7406 /* var_str_list: */ arglist ? arglist->list : NULL);
7407 p = _STPUTC('\0', expdest);
7409 if (arglist == NULL) {
7410 /* here document expanded */
7413 p = grabstackstr(p);
7414 TRACE(("expandarg: p:'%s'\n", p));
7415 exparg.lastp = &exparg.list;
7419 if (flag & EXP_FULL) {
7420 ifsbreakup(p, &exparg);
7421 *exparg.lastp = NULL;
7422 exparg.lastp = &exparg.list;
7423 expandmeta(exparg.list /*, flag*/);
7425 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7427 TRACE(("expandarg: rmescapes:'%s'\n", p));
7429 sp = stzalloc(sizeof(*sp));
7432 exparg.lastp = &sp->next;
7434 *exparg.lastp = NULL;
7436 *arglist->lastp = exparg.list;
7437 arglist->lastp = exparg.lastp;
7445 * Expand shell variables and backquotes inside a here document.
7448 expandhere(union node *arg, int fd)
7450 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7451 full_write(fd, stackblock(), expdest - (char *)stackblock());
7455 * Returns true if the pattern matches the string.
7458 patmatch(char *pattern, const char *string)
7460 return pmatch(preglob(pattern, 0), string);
7464 * See if a pattern matches in a case statement.
7467 casematch(union node *pattern, char *val)
7469 struct stackmark smark;
7472 setstackmark(&smark);
7473 argbackq = pattern->narg.backquote;
7474 STARTSTACKSTR(expdest);
7475 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7476 /* var_str_list: */ NULL);
7477 STACKSTRNUL(expdest);
7479 result = patmatch(stackblock(), val);
7480 popstackmark(&smark);
7485 /* ============ find_command */
7489 int (*builtin)(int, char **) FAST_FUNC;
7490 /* unsigned flags; */
7492 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7493 /* "regular" builtins always take precedence over commands,
7494 * regardless of PATH=....%builtin... position */
7495 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7496 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7499 smallint cmdtype; /* CMDxxx */
7502 /* index >= 0 for commands without path (slashes) */
7503 /* (TODO: what exactly does the value mean? PATH position?) */
7504 /* index == -1 for commands with slashes */
7505 /* index == (-2 - applet_no) for NOFORK applets */
7506 const struct builtincmd *cmd;
7507 struct funcnode *func;
7510 /* values of cmdtype */
7511 #define CMDUNKNOWN -1 /* no entry in table for command */
7512 #define CMDNORMAL 0 /* command is an executable program */
7513 #define CMDFUNCTION 1 /* command is a shell function */
7514 #define CMDBUILTIN 2 /* command is a shell builtin */
7516 /* action to find_command() */
7517 #define DO_ERR 0x01 /* prints errors */
7518 #define DO_ABS 0x02 /* checks absolute paths */
7519 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7520 #define DO_ALTPATH 0x08 /* using alternate path */
7521 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7523 static void find_command(char *, struct cmdentry *, int, const char *);
7526 /* ============ Hashing commands */
7529 * When commands are first encountered, they are entered in a hash table.
7530 * This ensures that a full path search will not have to be done for them
7531 * on each invocation.
7533 * We should investigate converting to a linear search, even though that
7534 * would make the command name "hash" a misnomer.
7538 struct tblentry *next; /* next entry in hash chain */
7539 union param param; /* definition of builtin function */
7540 smallint cmdtype; /* CMDxxx */
7541 char rehash; /* if set, cd done since entry created */
7542 char cmdname[1]; /* name of command */
7545 static struct tblentry **cmdtable;
7546 #define INIT_G_cmdtable() do { \
7547 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7550 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7554 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7556 #if ENABLE_FEATURE_SH_STANDALONE
7557 if (applet_no >= 0) {
7558 if (APPLET_IS_NOEXEC(applet_no)) {
7562 run_applet_no_and_exit(applet_no, argv);
7564 /* re-exec ourselves with the new arguments */
7565 execve(bb_busybox_exec_path, argv, envp);
7566 /* If they called chroot or otherwise made the binary no longer
7567 * executable, fall through */
7574 execve(cmd, argv, envp);
7575 } while (errno == EINTR);
7577 execve(cmd, argv, envp);
7579 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7580 /* Run "cmd" as a shell script:
7581 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7582 * "If the execve() function fails with ENOEXEC, the shell
7583 * shall execute a command equivalent to having a shell invoked
7584 * with the command name as its first operand,
7585 * with any remaining arguments passed to the new shell"
7587 * That is, do not use $SHELL, user's shell, or /bin/sh;
7588 * just call ourselves.
7590 * Note that bash reads ~80 chars of the file, and if it sees
7591 * a zero byte before it sees newline, it doesn't try to
7592 * interpret it, but fails with "cannot execute binary file"
7593 * message and exit code 126. For one, this prevents attempts
7594 * to interpret foreign ELF binaries as shell scripts.
7597 cmd = (char*) bb_busybox_exec_path;
7598 /* NB: this is only possible because all callers of shellexec()
7599 * ensure that the argv[-1] slot exists!
7602 argv[0] = (char*) "ash";
7608 * Exec a program. Never returns. If you change this routine, you may
7609 * have to change the find_command routine as well.
7610 * argv[-1] must exist and be writable! See tryexec() for why.
7612 static void shellexec(char **, const char *, int) NORETURN;
7614 shellexec(char **argv, const char *path, int idx)
7620 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7622 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7623 if (strchr(argv[0], '/') != NULL
7624 #if ENABLE_FEATURE_SH_STANDALONE
7625 || (applet_no = find_applet_by_name(argv[0])) >= 0
7628 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7629 if (applet_no >= 0) {
7630 /* We tried execing ourself, but it didn't work.
7631 * Maybe /proc/self/exe doesn't exist?
7640 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7641 if (--idx < 0 && pathopt == NULL) {
7642 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7643 if (errno != ENOENT && errno != ENOTDIR)
7650 /* Map to POSIX errors */
7662 exitstatus = exerrno;
7663 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7664 argv[0], e, suppress_int));
7665 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7670 printentry(struct tblentry *cmdp)
7676 idx = cmdp->param.index;
7679 name = path_advance(&path, cmdp->cmdname);
7681 } while (--idx >= 0);
7682 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7686 * Clear out command entries. The argument specifies the first entry in
7687 * PATH which has changed.
7690 clearcmdentry(int firstchange)
7692 struct tblentry **tblp;
7693 struct tblentry **pp;
7694 struct tblentry *cmdp;
7697 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7699 while ((cmdp = *pp) != NULL) {
7700 if ((cmdp->cmdtype == CMDNORMAL &&
7701 cmdp->param.index >= firstchange)
7702 || (cmdp->cmdtype == CMDBUILTIN &&
7703 builtinloc >= firstchange)
7716 * Locate a command in the command hash table. If "add" is nonzero,
7717 * add the command to the table if it is not already present. The
7718 * variable "lastcmdentry" is set to point to the address of the link
7719 * pointing to the entry, so that delete_cmd_entry can delete the
7722 * Interrupts must be off if called with add != 0.
7724 static struct tblentry **lastcmdentry;
7726 static struct tblentry *
7727 cmdlookup(const char *name, int add)
7729 unsigned int hashval;
7731 struct tblentry *cmdp;
7732 struct tblentry **pp;
7735 hashval = (unsigned char)*p << 4;
7737 hashval += (unsigned char)*p++;
7739 pp = &cmdtable[hashval % CMDTABLESIZE];
7740 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7741 if (strcmp(cmdp->cmdname, name) == 0)
7745 if (add && cmdp == NULL) {
7746 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7748 /* + 1 - already done because
7749 * tblentry::cmdname is char[1] */);
7750 /*cmdp->next = NULL; - ckzalloc did it */
7751 cmdp->cmdtype = CMDUNKNOWN;
7752 strcpy(cmdp->cmdname, name);
7759 * Delete the command entry returned on the last lookup.
7762 delete_cmd_entry(void)
7764 struct tblentry *cmdp;
7767 cmdp = *lastcmdentry;
7768 *lastcmdentry = cmdp->next;
7769 if (cmdp->cmdtype == CMDFUNCTION)
7770 freefunc(cmdp->param.func);
7776 * Add a new command entry, replacing any existing command entry for
7777 * the same name - except special builtins.
7780 addcmdentry(char *name, struct cmdentry *entry)
7782 struct tblentry *cmdp;
7784 cmdp = cmdlookup(name, 1);
7785 if (cmdp->cmdtype == CMDFUNCTION) {
7786 freefunc(cmdp->param.func);
7788 cmdp->cmdtype = entry->cmdtype;
7789 cmdp->param = entry->u;
7793 static int FAST_FUNC
7794 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7796 struct tblentry **pp;
7797 struct tblentry *cmdp;
7799 struct cmdentry entry;
7802 if (nextopt("r") != '\0') {
7807 if (*argptr == NULL) {
7808 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7809 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7810 if (cmdp->cmdtype == CMDNORMAL)
7818 while ((name = *argptr) != NULL) {
7819 cmdp = cmdlookup(name, 0);
7821 && (cmdp->cmdtype == CMDNORMAL
7822 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7826 find_command(name, &entry, DO_ERR, pathval());
7827 if (entry.cmdtype == CMDUNKNOWN)
7835 * Called when a cd is done. Marks all commands so the next time they
7836 * are executed they will be rehashed.
7841 struct tblentry **pp;
7842 struct tblentry *cmdp;
7844 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7845 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7846 if (cmdp->cmdtype == CMDNORMAL
7847 || (cmdp->cmdtype == CMDBUILTIN
7848 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7858 * Fix command hash table when PATH changed.
7859 * Called before PATH is changed. The argument is the new value of PATH;
7860 * pathval() still returns the old value at this point.
7861 * Called with interrupts off.
7863 static void FAST_FUNC
7864 changepath(const char *new)
7872 firstchange = 9999; /* assume no change */
7878 if ((*old == '\0' && *new == ':')
7879 || (*old == ':' && *new == '\0')
7883 old = new; /* ignore subsequent differences */
7887 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7894 if (builtinloc < 0 && idx_bltin >= 0)
7895 builtinloc = idx_bltin; /* zap builtins */
7896 if (builtinloc >= 0 && idx_bltin < 0)
7898 clearcmdentry(firstchange);
7899 builtinloc = idx_bltin;
7924 #if ENABLE_ASH_BASH_COMPAT
7935 typedef smallint token_id_t;
7937 /* Nth bit indicates if token marks the end of a list */
7940 /* 0 */ | (1u << TEOF)
7941 /* 1 */ | (0u << TNL)
7942 /* 2 */ | (0u << TREDIR)
7943 /* 3 */ | (0u << TWORD)
7944 /* 4 */ | (0u << TSEMI)
7945 /* 5 */ | (0u << TBACKGND)
7946 /* 6 */ | (0u << TAND)
7947 /* 7 */ | (0u << TOR)
7948 /* 8 */ | (0u << TPIPE)
7949 /* 9 */ | (0u << TLP)
7950 /* 10 */ | (1u << TRP)
7951 /* 11 */ | (1u << TENDCASE)
7952 /* 12 */ | (1u << TENDBQUOTE)
7953 /* 13 */ | (0u << TNOT)
7954 /* 14 */ | (0u << TCASE)
7955 /* 15 */ | (1u << TDO)
7956 /* 16 */ | (1u << TDONE)
7957 /* 17 */ | (1u << TELIF)
7958 /* 18 */ | (1u << TELSE)
7959 /* 19 */ | (1u << TESAC)
7960 /* 20 */ | (1u << TFI)
7961 /* 21 */ | (0u << TFOR)
7962 #if ENABLE_ASH_BASH_COMPAT
7963 /* 22 */ | (0u << TFUNCTION)
7965 /* 23 */ | (0u << TIF)
7966 /* 24 */ | (0u << TIN)
7967 /* 25 */ | (1u << TTHEN)
7968 /* 26 */ | (0u << TUNTIL)
7969 /* 27 */ | (0u << TWHILE)
7970 /* 28 */ | (0u << TBEGIN)
7971 /* 29 */ | (1u << TEND)
7972 , /* thus far 29 bits used */
7975 static const char *const tokname_array[] = {
7989 #define KWDOFFSET 13
7990 /* the following are keywords */
8000 #if ENABLE_ASH_BASH_COMPAT
8012 /* Wrapper around strcmp for qsort/bsearch/... */
8014 pstrcmp(const void *a, const void *b)
8016 return strcmp((char*)a, *(char**)b);
8019 static const char *const *
8020 findkwd(const char *s)
8022 return bsearch(s, tokname_array + KWDOFFSET,
8023 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8024 sizeof(tokname_array[0]), pstrcmp);
8028 * Locate and print what a word is...
8031 describe_command(char *command, const char *path, int describe_command_verbose)
8033 struct cmdentry entry;
8034 struct tblentry *cmdp;
8035 #if ENABLE_ASH_ALIAS
8036 const struct alias *ap;
8039 path = path ? path : pathval();
8041 if (describe_command_verbose) {
8045 /* First look at the keywords */
8046 if (findkwd(command)) {
8047 out1str(describe_command_verbose ? " is a shell keyword" : command);
8051 #if ENABLE_ASH_ALIAS
8052 /* Then look at the aliases */
8053 ap = lookupalias(command, 0);
8055 if (!describe_command_verbose) {
8060 out1fmt(" is an alias for %s", ap->val);
8064 /* Then check if it is a tracked alias */
8065 cmdp = cmdlookup(command, 0);
8067 entry.cmdtype = cmdp->cmdtype;
8068 entry.u = cmdp->param;
8070 /* Finally use brute force */
8071 find_command(command, &entry, DO_ABS, path);
8074 switch (entry.cmdtype) {
8076 int j = entry.u.index;
8082 p = path_advance(&path, command);
8086 if (describe_command_verbose) {
8088 (cmdp ? " a tracked alias for" : nullstr), p
8097 if (describe_command_verbose) {
8098 out1str(" is a shell function");
8105 if (describe_command_verbose) {
8106 out1fmt(" is a %sshell builtin",
8107 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8108 "special " : nullstr
8116 if (describe_command_verbose) {
8117 out1str(": not found\n");
8126 static int FAST_FUNC
8127 typecmd(int argc UNUSED_PARAM, char **argv)
8133 /* type -p ... ? (we don't bother checking for 'p') */
8134 if (argv[1] && argv[1][0] == '-') {
8139 err |= describe_command(argv[i++], NULL, verbose);
8144 #if ENABLE_ASH_CMDCMD
8145 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8147 parse_command_args(char **argv, const char **path)
8160 if (c == '-' && !*cp) {
8168 *path = bb_default_path;
8171 /* run 'typecmd' for other options */
8180 static int FAST_FUNC
8181 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8189 const char *path = NULL;
8191 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8192 * never reaches this function.
8195 while ((c = nextopt("pvV")) != '\0')
8197 verify |= VERIFY_VERBOSE;
8199 /*verify |= VERIFY_BRIEF*/;
8205 path = bb_default_path;
8207 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8209 if (/*verify && */ cmd)
8210 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8217 /*static int funcblocksize; // size of structures in function */
8218 /*static int funcstringsize; // size of strings in node */
8219 static void *funcblock; /* block to allocate function from */
8220 static char *funcstring_end; /* end of block to allocate strings from */
8222 /* flags in argument to evaltree */
8223 #define EV_EXIT 01 /* exit after evaluating tree */
8224 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8226 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8227 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8228 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8229 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8230 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8231 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8232 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8233 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8234 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8235 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8236 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8237 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8238 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8239 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8240 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8241 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8242 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8243 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8244 #if ENABLE_ASH_BASH_COMPAT
8245 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8247 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8248 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8249 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8250 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8251 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8252 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8253 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8254 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8255 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8258 static int calcsize(int funcblocksize, union node *n);
8261 sizenodelist(int funcblocksize, struct nodelist *lp)
8264 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8265 funcblocksize = calcsize(funcblocksize, lp->n);
8268 return funcblocksize;
8272 calcsize(int funcblocksize, union node *n)
8275 return funcblocksize;
8276 funcblocksize += nodesize[n->type];
8279 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8280 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8281 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8284 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8289 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8290 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8297 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8298 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8301 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8302 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8303 funcblocksize = calcsize(funcblocksize, n->nif.test);
8306 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8307 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8308 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8311 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8312 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8315 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8316 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8317 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8321 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8322 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8323 funcblocksize = calcsize(funcblocksize, n->narg.next);
8326 #if ENABLE_ASH_BASH_COMPAT
8333 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8334 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8338 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8339 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8343 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8344 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8347 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8350 return funcblocksize;
8354 nodeckstrdup(char *s)
8356 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8357 return strcpy(funcstring_end, s);
8360 static union node *copynode(union node *);
8362 static struct nodelist *
8363 copynodelist(struct nodelist *lp)
8365 struct nodelist *start;
8366 struct nodelist **lpp;
8371 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8372 (*lpp)->n = copynode(lp->n);
8374 lpp = &(*lpp)->next;
8381 copynode(union node *n)
8388 funcblock = (char *) funcblock + nodesize[n->type];
8392 new->ncmd.redirect = copynode(n->ncmd.redirect);
8393 new->ncmd.args = copynode(n->ncmd.args);
8394 new->ncmd.assign = copynode(n->ncmd.assign);
8397 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8398 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8403 new->nredir.redirect = copynode(n->nredir.redirect);
8404 new->nredir.n = copynode(n->nredir.n);
8411 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8412 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8415 new->nif.elsepart = copynode(n->nif.elsepart);
8416 new->nif.ifpart = copynode(n->nif.ifpart);
8417 new->nif.test = copynode(n->nif.test);
8420 new->nfor.var = nodeckstrdup(n->nfor.var);
8421 new->nfor.body = copynode(n->nfor.body);
8422 new->nfor.args = copynode(n->nfor.args);
8425 new->ncase.cases = copynode(n->ncase.cases);
8426 new->ncase.expr = copynode(n->ncase.expr);
8429 new->nclist.body = copynode(n->nclist.body);
8430 new->nclist.pattern = copynode(n->nclist.pattern);
8431 new->nclist.next = copynode(n->nclist.next);
8435 new->narg.backquote = copynodelist(n->narg.backquote);
8436 new->narg.text = nodeckstrdup(n->narg.text);
8437 new->narg.next = copynode(n->narg.next);
8440 #if ENABLE_ASH_BASH_COMPAT
8447 new->nfile.fname = copynode(n->nfile.fname);
8448 new->nfile.fd = n->nfile.fd;
8449 new->nfile.next = copynode(n->nfile.next);
8453 new->ndup.vname = copynode(n->ndup.vname);
8454 new->ndup.dupfd = n->ndup.dupfd;
8455 new->ndup.fd = n->ndup.fd;
8456 new->ndup.next = copynode(n->ndup.next);
8460 new->nhere.doc = copynode(n->nhere.doc);
8461 new->nhere.fd = n->nhere.fd;
8462 new->nhere.next = copynode(n->nhere.next);
8465 new->nnot.com = copynode(n->nnot.com);
8468 new->type = n->type;
8473 * Make a copy of a parse tree.
8475 static struct funcnode *
8476 copyfunc(union node *n)
8481 /*funcstringsize = 0;*/
8482 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8483 f = ckzalloc(blocksize /* + funcstringsize */);
8484 funcblock = (char *) f + offsetof(struct funcnode, n);
8485 funcstring_end = (char *) f + blocksize;
8487 /* f->count = 0; - ckzalloc did it */
8492 * Define a shell function.
8495 defun(union node *func)
8497 struct cmdentry entry;
8500 entry.cmdtype = CMDFUNCTION;
8501 entry.u.func = copyfunc(func);
8502 addcmdentry(func->narg.text, &entry);
8506 /* Reasons for skipping commands (see comment on breakcmd routine) */
8507 #define SKIPBREAK (1 << 0)
8508 #define SKIPCONT (1 << 1)
8509 #define SKIPFUNC (1 << 2)
8510 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8511 static int skipcount; /* number of levels to skip */
8512 static int funcnest; /* depth of function calls */
8513 static int loopnest; /* current loop nesting level */
8515 /* Forward decl way out to parsing code - dotrap needs it */
8516 static int evalstring(char *s, int flags);
8518 /* Called to execute a trap.
8519 * Single callsite - at the end of evaltree().
8520 * If we return non-zero, evaltree raises EXEXIT exception.
8522 * Perhaps we should avoid entering new trap handlers
8523 * while we are executing a trap handler. [is it a TODO?]
8530 uint8_t last_status;
8535 last_status = exitstatus;
8539 TRACE(("dotrap entered\n"));
8540 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8552 /* non-trapped SIGINT is handled separately by raise_interrupt,
8553 * don't upset it by resetting gotsig[SIGINT-1] */
8554 if (sig == SIGINT && !p)
8557 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8563 exitstatus = last_status;
8564 TRACE(("dotrap returns\n"));
8567 /* forward declarations - evaluation is fairly recursive business... */
8568 static int evalloop(union node *, int);
8569 static int evalfor(union node *, int);
8570 static int evalcase(union node *, int);
8571 static int evalsubshell(union node *, int);
8572 static void expredir(union node *);
8573 static int evalpipe(union node *, int);
8574 static int evalcommand(union node *, int);
8575 static int evalbltin(const struct builtincmd *, int, char **, int);
8576 static void prehash(union node *);
8579 * Evaluate a parse tree. The value is left in the global variable
8583 evaltree(union node *n, int flags)
8586 int (*evalfn)(union node *, int);
8590 TRACE(("evaltree(NULL) called\n"));
8593 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8600 out1fmt("Node type = %d\n", n->type);
8605 status = !evaltree(n->nnot.com, EV_TESTED);
8608 expredir(n->nredir.redirect);
8609 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8611 status = evaltree(n->nredir.n, flags & EV_TESTED);
8613 if (n->nredir.redirect)
8614 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8617 evalfn = evalcommand;
8619 if (eflag && !(flags & EV_TESTED))
8631 evalfn = evalsubshell;
8644 #error NAND + 1 != NOR
8646 #if NOR + 1 != NSEMI
8647 #error NOR + 1 != NSEMI
8649 unsigned is_or = n->type - NAND;
8652 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8654 if ((!status) == is_or || evalskip)
8660 status = evalfn(n, flags);
8664 status = evaltree(n->nif.test, EV_TESTED);
8671 if (n->nif.elsepart) {
8672 n = n->nif.elsepart;
8679 /* Not necessary. To test it:
8680 * "false; f() { qwerty; }; echo $?" should print 0.
8684 exitstatus = status;
8688 /* Order of checks below is important:
8689 * signal handlers trigger before exit caused by "set -e".
8693 if (checkexit & status)
8694 raise_exception(EXEXIT);
8695 if (flags & EV_EXIT)
8696 raise_exception(EXEXIT);
8698 TRACE(("leaving evaltree (no interrupts)\n"));
8702 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8705 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8710 int skip = evalskip;
8717 if (--skipcount <= 0) {
8728 evalloop(union node *n, int flags)
8739 i = evaltree(n->nbinary.ch1, EV_TESTED);
8741 if (skip == SKIPFUNC)
8745 if (n->type != NWHILE)
8749 status = evaltree(n->nbinary.ch2, flags);
8751 } while (!(skip & ~SKIPCONT));
8758 evalfor(union node *n, int flags)
8760 struct arglist arglist;
8763 struct stackmark smark;
8766 setstackmark(&smark);
8767 arglist.list = NULL;
8768 arglist.lastp = &arglist.list;
8769 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8770 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8772 *arglist.lastp = NULL;
8776 for (sp = arglist.list; sp; sp = sp->next) {
8777 setvar0(n->nfor.var, sp->text);
8778 status = evaltree(n->nfor.body, flags);
8779 if (skiploop() & ~SKIPCONT)
8783 popstackmark(&smark);
8789 evalcase(union node *n, int flags)
8793 struct arglist arglist;
8794 struct stackmark smark;
8797 setstackmark(&smark);
8798 arglist.list = NULL;
8799 arglist.lastp = &arglist.list;
8800 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8801 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8802 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8803 if (casematch(patp, arglist.list->text)) {
8804 /* Ensure body is non-empty as otherwise
8805 * EV_EXIT may prevent us from setting the
8808 if (evalskip == 0 && cp->nclist.body) {
8809 status = evaltree(cp->nclist.body, flags);
8816 popstackmark(&smark);
8822 * Kick off a subshell to evaluate a tree.
8825 evalsubshell(union node *n, int flags)
8828 int backgnd = (n->type == NBACKGND);
8831 expredir(n->nredir.redirect);
8832 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8835 jp = makejob(/*n,*/ 1);
8836 if (forkshell(jp, n, backgnd) == 0) {
8841 flags &= ~EV_TESTED;
8843 redirect(n->nredir.redirect, 0);
8844 evaltreenr(n->nredir.n, flags);
8850 status = waitforjob(jp);
8856 * Compute the names of the files in a redirection list.
8858 static void fixredir(union node *, const char *, int);
8860 expredir(union node *n)
8864 for (redir = n; redir; redir = redir->nfile.next) {
8868 fn.lastp = &fn.list;
8869 switch (redir->type) {
8873 #if ENABLE_ASH_BASH_COMPAT
8878 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8879 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8880 #if ENABLE_ASH_BASH_COMPAT
8884 // By the design of stack allocator, the loop of this kind:
8885 // while true; do while true; do break; done </dev/null; done
8886 // will look like a memory leak: ash plans to free expfname's
8887 // of "/dev/null" as soon as it finishes running the loop
8888 // (in this case, never).
8889 // This "fix" is wrong:
8890 if (redir->nfile.expfname)
8891 stunalloc(redir->nfile.expfname);
8892 // It results in corrupted state of stacked allocations.
8894 redir->nfile.expfname = fn.list->text;
8897 case NTOFD: /* >& */
8898 if (redir->ndup.vname) {
8899 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8900 if (fn.list == NULL)
8901 ash_msg_and_raise_error("redir error");
8902 #if ENABLE_ASH_BASH_COMPAT
8903 //FIXME: we used expandarg with different args!
8904 if (!isdigit_str9(fn.list->text)) {
8905 /* >&file, not >&fd */
8906 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8907 ash_msg_and_raise_error("redir error");
8909 goto store_expfname;
8912 fixredir(redir, fn.list->text, 1);
8920 * Evaluate a pipeline. All the processes in the pipeline are children
8921 * of the process creating the pipeline. (This differs from some versions
8922 * of the shell, which make the last process in a pipeline the parent
8926 evalpipe(union node *n, int flags)
8929 struct nodelist *lp;
8935 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8937 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8941 jp = makejob(/*n,*/ pipelen);
8943 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8947 if (pipe(pip) < 0) {
8949 ash_msg_and_raise_error("pipe call failed");
8952 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8966 evaltreenr(lp->n, flags);
8973 /* Don't want to trigger debugging */
8977 if (n->npipe.pipe_backgnd == 0) {
8978 status = waitforjob(jp);
8979 TRACE(("evalpipe: job done exit status %d\n", status));
8987 * Controls whether the shell is interactive or not.
8990 setinteractive(int on)
8992 static smallint is_interactive;
8994 if (++on == is_interactive)
8996 is_interactive = on;
9000 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9001 if (is_interactive > 1) {
9002 /* Looks like they want an interactive shell */
9003 static smallint did_banner;
9006 /* note: ash and hush share this string */
9007 out1fmt("\n\n%s %s\n"
9008 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9011 "built-in shell (ash)"
9025 setinteractive(iflag);
9027 #if ENABLE_FEATURE_EDITING_VI
9029 line_input_state->flags |= VI_MODE;
9031 line_input_state->flags &= ~VI_MODE;
9033 viflag = 0; /* forcibly keep the option off */
9037 static struct localvar *localvars;
9040 * Called after a function returns.
9041 * Interrupts must be off.
9046 struct localvar *lvp;
9049 while ((lvp = localvars) != NULL) {
9050 localvars = lvp->next;
9052 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9053 if (vp == NULL) { /* $- saved */
9054 memcpy(optlist, lvp->text, sizeof(optlist));
9055 free((char*)lvp->text);
9057 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9058 unsetvar(vp->var_text);
9061 vp->var_func(var_end(lvp->text));
9062 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9063 free((char*)vp->var_text);
9064 vp->flags = lvp->flags;
9065 vp->var_text = lvp->text;
9072 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9074 volatile struct shparam saveparam;
9075 struct localvar *volatile savelocalvars;
9076 struct jmploc *volatile savehandler;
9077 struct jmploc jmploc;
9080 saveparam = shellparam;
9081 savelocalvars = localvars;
9082 savehandler = exception_handler;
9083 e = setjmp(jmploc.loc);
9088 exception_handler = &jmploc;
9090 shellparam.malloced = 0;
9094 shellparam.nparam = argc - 1;
9095 shellparam.p = argv + 1;
9096 #if ENABLE_ASH_GETOPTS
9097 shellparam.optind = 1;
9098 shellparam.optoff = -1;
9100 evaltree(func->n.narg.next, flags & EV_TESTED);
9106 localvars = savelocalvars;
9107 freeparam(&shellparam);
9108 shellparam = saveparam;
9109 exception_handler = savehandler;
9111 evalskip &= ~SKIPFUNC;
9116 * Make a variable a local variable. When a variable is made local, it's
9117 * value and flags are saved in a localvar structure. The saved values
9118 * will be restored when the shell function returns. We handle the name
9119 * "-" as a special case: it makes changes to "set +-options" local
9120 * (options will be restored on return from the function).
9125 struct localvar *lvp;
9128 char *eq = strchr(name, '=');
9131 /* Cater for duplicate "local". Examples:
9132 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9133 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9137 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9141 * it's a duplicate "local VAR" declaration, do nothing
9148 lvp = ckzalloc(sizeof(*lvp));
9149 if (LONE_DASH(name)) {
9151 p = ckmalloc(sizeof(optlist));
9152 lvp->text = memcpy(p, optlist, sizeof(optlist));
9155 vpp = hashvar(name);
9156 vp = *findvar(vpp, name);
9158 /* variable did not exist yet */
9160 setvareq(name, VSTRFIXED);
9162 setvar(name, NULL, VSTRFIXED);
9163 vp = *vpp; /* the new variable */
9164 lvp->flags = VUNSET;
9166 lvp->text = vp->var_text;
9167 lvp->flags = vp->flags;
9168 /* make sure neither "struct var" nor string gets freed
9169 * during (un)setting:
9171 vp->flags |= VSTRFIXED|VTEXTFIXED;
9175 /* "local VAR" unsets VAR: */
9176 setvar0(name, NULL);
9180 lvp->next = localvars;
9187 * The "local" command.
9189 static int FAST_FUNC
9190 localcmd(int argc UNUSED_PARAM, char **argv)
9195 ash_msg_and_raise_error("not in a function");
9198 while ((name = *argv++) != NULL) {
9204 static int FAST_FUNC
9205 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9210 static int FAST_FUNC
9211 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9216 static int FAST_FUNC
9217 execcmd(int argc UNUSED_PARAM, char **argv)
9220 iflag = 0; /* exit on error */
9223 /* We should set up signals for "exec CMD"
9224 * the same way as for "CMD" without "exec".
9225 * But optschanged->setinteractive->setsignal
9226 * still thought we are a root shell. Therefore, for example,
9227 * SIGQUIT is still set to IGN. Fix it:
9231 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9232 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9233 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9235 shellexec(argv + 1, pathval(), 0);
9242 * The return command.
9244 static int FAST_FUNC
9245 returncmd(int argc UNUSED_PARAM, char **argv)
9248 * If called outside a function, do what ksh does;
9249 * skip the rest of the file.
9251 evalskip = SKIPFUNC;
9252 return argv[1] ? number(argv[1]) : exitstatus;
9255 /* Forward declarations for builtintab[] */
9256 static int breakcmd(int, char **) FAST_FUNC;
9257 static int dotcmd(int, char **) FAST_FUNC;
9258 static int evalcmd(int, char **, int) FAST_FUNC;
9259 static int exitcmd(int, char **) FAST_FUNC;
9260 static int exportcmd(int, char **) FAST_FUNC;
9261 #if ENABLE_ASH_GETOPTS
9262 static int getoptscmd(int, char **) FAST_FUNC;
9265 static int helpcmd(int, char **) FAST_FUNC;
9268 static int historycmd(int, char **) FAST_FUNC;
9270 #if ENABLE_SH_MATH_SUPPORT
9271 static int letcmd(int, char **) FAST_FUNC;
9273 static int readcmd(int, char **) FAST_FUNC;
9274 static int setcmd(int, char **) FAST_FUNC;
9275 static int shiftcmd(int, char **) FAST_FUNC;
9276 static int timescmd(int, char **) FAST_FUNC;
9277 static int trapcmd(int, char **) FAST_FUNC;
9278 static int umaskcmd(int, char **) FAST_FUNC;
9279 static int unsetcmd(int, char **) FAST_FUNC;
9280 static int ulimitcmd(int, char **) FAST_FUNC;
9282 #define BUILTIN_NOSPEC "0"
9283 #define BUILTIN_SPECIAL "1"
9284 #define BUILTIN_REGULAR "2"
9285 #define BUILTIN_SPEC_REG "3"
9286 #define BUILTIN_ASSIGN "4"
9287 #define BUILTIN_SPEC_ASSG "5"
9288 #define BUILTIN_REG_ASSG "6"
9289 #define BUILTIN_SPEC_REG_ASSG "7"
9291 /* Stubs for calling non-FAST_FUNC's */
9292 #if ENABLE_ASH_BUILTIN_ECHO
9293 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9295 #if ENABLE_ASH_BUILTIN_PRINTF
9296 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9298 #if ENABLE_ASH_BUILTIN_TEST
9299 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9302 /* Keep these in proper order since it is searched via bsearch() */
9303 static const struct builtincmd builtintab[] = {
9304 { BUILTIN_SPEC_REG "." , dotcmd },
9305 { BUILTIN_SPEC_REG ":" , truecmd },
9306 #if ENABLE_ASH_BUILTIN_TEST
9307 { BUILTIN_REGULAR "[" , testcmd },
9308 # if ENABLE_ASH_BASH_COMPAT
9309 { BUILTIN_REGULAR "[[" , testcmd },
9312 #if ENABLE_ASH_ALIAS
9313 { BUILTIN_REG_ASSG "alias" , aliascmd },
9316 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9318 { BUILTIN_SPEC_REG "break" , breakcmd },
9319 { BUILTIN_REGULAR "cd" , cdcmd },
9320 { BUILTIN_NOSPEC "chdir" , cdcmd },
9321 #if ENABLE_ASH_CMDCMD
9322 { BUILTIN_REGULAR "command" , commandcmd },
9324 { BUILTIN_SPEC_REG "continue", breakcmd },
9325 #if ENABLE_ASH_BUILTIN_ECHO
9326 { BUILTIN_REGULAR "echo" , echocmd },
9328 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9329 { BUILTIN_SPEC_REG "exec" , execcmd },
9330 { BUILTIN_SPEC_REG "exit" , exitcmd },
9331 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9332 { BUILTIN_REGULAR "false" , falsecmd },
9334 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9336 #if ENABLE_ASH_GETOPTS
9337 { BUILTIN_REGULAR "getopts" , getoptscmd },
9339 { BUILTIN_NOSPEC "hash" , hashcmd },
9341 { BUILTIN_NOSPEC "help" , helpcmd },
9344 { BUILTIN_NOSPEC "history" , historycmd },
9347 { BUILTIN_REGULAR "jobs" , jobscmd },
9348 { BUILTIN_REGULAR "kill" , killcmd },
9350 #if ENABLE_SH_MATH_SUPPORT
9351 { BUILTIN_NOSPEC "let" , letcmd },
9353 { BUILTIN_ASSIGN "local" , localcmd },
9354 #if ENABLE_ASH_BUILTIN_PRINTF
9355 { BUILTIN_REGULAR "printf" , printfcmd },
9357 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9358 { BUILTIN_REGULAR "read" , readcmd },
9359 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9360 { BUILTIN_SPEC_REG "return" , returncmd },
9361 { BUILTIN_SPEC_REG "set" , setcmd },
9362 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9363 #if ENABLE_ASH_BASH_COMPAT
9364 { BUILTIN_SPEC_REG "source" , dotcmd },
9366 #if ENABLE_ASH_BUILTIN_TEST
9367 { BUILTIN_REGULAR "test" , testcmd },
9369 { BUILTIN_SPEC_REG "times" , timescmd },
9370 { BUILTIN_SPEC_REG "trap" , trapcmd },
9371 { BUILTIN_REGULAR "true" , truecmd },
9372 { BUILTIN_NOSPEC "type" , typecmd },
9373 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9374 { BUILTIN_REGULAR "umask" , umaskcmd },
9375 #if ENABLE_ASH_ALIAS
9376 { BUILTIN_REGULAR "unalias" , unaliascmd },
9378 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9379 { BUILTIN_REGULAR "wait" , waitcmd },
9382 /* Should match the above table! */
9383 #define COMMANDCMD (builtintab + \
9385 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9386 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9387 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9388 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9389 /* break cd cddir */ 3)
9390 #define EVALCMD (COMMANDCMD + \
9391 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9392 /* continue */ 1 + \
9393 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9395 #define EXECCMD (EVALCMD + \
9399 * Search the table of builtin commands.
9402 pstrcmp1(const void *a, const void *b)
9404 return strcmp((char*)a, *(char**)b + 1);
9406 static struct builtincmd *
9407 find_builtin(const char *name)
9409 struct builtincmd *bp;
9412 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9419 * Execute a simple command.
9422 isassignment(const char *p)
9424 const char *q = endofname(p);
9429 static int FAST_FUNC
9430 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9432 /* Preserve exitstatus of a previous possible redirection
9433 * as POSIX mandates */
9434 return back_exitstatus;
9437 evalcommand(union node *cmd, int flags)
9439 static const struct builtincmd null_bltin = {
9440 "\0\0", bltincmd /* why three NULs? */
9442 struct stackmark smark;
9444 struct arglist arglist;
9445 struct arglist varlist;
9448 const struct strlist *sp;
9449 struct cmdentry cmdentry;
9456 struct builtincmd *bcmd;
9457 smallint cmd_is_exec;
9458 smallint pseudovarflag = 0;
9460 /* First expand the arguments. */
9461 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9462 setstackmark(&smark);
9463 back_exitstatus = 0;
9465 cmdentry.cmdtype = CMDBUILTIN;
9466 cmdentry.u.cmd = &null_bltin;
9467 varlist.lastp = &varlist.list;
9468 *varlist.lastp = NULL;
9469 arglist.lastp = &arglist.list;
9470 *arglist.lastp = NULL;
9473 if (cmd->ncmd.args) {
9474 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9475 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9478 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9479 struct strlist **spp;
9481 spp = arglist.lastp;
9482 if (pseudovarflag && isassignment(argp->narg.text))
9483 expandarg(argp, &arglist, EXP_VARTILDE);
9485 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9487 for (sp = *spp; sp; sp = sp->next)
9491 /* Reserve one extra spot at the front for shellexec. */
9492 nargv = stalloc(sizeof(char *) * (argc + 2));
9494 for (sp = arglist.list; sp; sp = sp->next) {
9495 TRACE(("evalcommand arg: %s\n", sp->text));
9496 *nargv++ = sp->text;
9501 if (iflag && funcnest == 0 && argc > 0)
9502 lastarg = nargv[-1];
9505 expredir(cmd->ncmd.redirect);
9506 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9508 path = vpath.var_text;
9509 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9510 struct strlist **spp;
9513 spp = varlist.lastp;
9514 expandarg(argp, &varlist, EXP_VARTILDE);
9517 * Modify the command lookup path, if a PATH= assignment
9521 if (varcmp(p, path) == 0)
9525 /* Print the command if xflag is set. */
9528 const char *p = " %s" + 1;
9530 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9532 for (n = 0; n < 2; n++) {
9534 fdprintf(preverrout_fd, p, sp->text);
9540 safe_write(preverrout_fd, "\n", 1);
9546 /* Now locate the command. */
9548 int cmd_flag = DO_ERR;
9549 #if ENABLE_ASH_CMDCMD
9550 const char *oldpath = path + 5;
9554 find_command(argv[0], &cmdentry, cmd_flag, path);
9555 if (cmdentry.cmdtype == CMDUNKNOWN) {
9556 flush_stdout_stderr();
9561 /* implement bltin and command here */
9562 if (cmdentry.cmdtype != CMDBUILTIN)
9565 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9566 if (cmdentry.u.cmd == EXECCMD)
9568 #if ENABLE_ASH_CMDCMD
9569 if (cmdentry.u.cmd == COMMANDCMD) {
9571 nargv = parse_command_args(argv, &path);
9574 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9575 * nargv => "PROG". path is updated if -p.
9577 argc -= nargv - argv;
9579 cmd_flag |= DO_NOFUNC;
9587 /* We have a redirection error. */
9589 raise_exception(EXERROR);
9591 exitstatus = status;
9595 /* Execute the command. */
9596 switch (cmdentry.cmdtype) {
9599 #if ENABLE_FEATURE_SH_NOFORK
9600 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9601 * around run_nofork_applet() call.
9602 * (2) Should this check also be done in forkshell()?
9603 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9605 /* find_command() encodes applet_no as (-2 - applet_no) */
9606 int applet_no = (- cmdentry.u.index - 2);
9607 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9608 listsetvar(varlist.list, VEXPORT|VSTACK);
9609 /* run <applet>_main() */
9610 status = run_nofork_applet(applet_no, argv);
9614 /* Can we avoid forking off? For example, very last command
9615 * in a script or a subshell does not need forking,
9616 * we can just exec it.
9618 if (!(flags & EV_EXIT) || may_have_traps) {
9619 /* No, forking off a child is necessary */
9621 jp = makejob(/*cmd,*/ 1);
9622 if (forkshell(jp, cmd, FORK_FG) != 0) {
9624 status = waitforjob(jp);
9626 TRACE(("forked child exited with %d\n", status));
9631 /* fall through to exec'ing external program */
9633 listsetvar(varlist.list, VEXPORT|VSTACK);
9634 shellexec(argv, path, cmdentry.u.index);
9638 cmdenviron = varlist.list;
9640 struct strlist *list = cmdenviron;
9642 if (spclbltin > 0 || argc == 0) {
9644 if (cmd_is_exec && argc > 1)
9647 listsetvar(list, i);
9649 /* Tight loop with builtins only:
9650 * "while kill -0 $child; do true; done"
9651 * will never exit even if $child died, unless we do this
9652 * to reap the zombie and make kill detect that it's gone: */
9653 dowait(DOWAIT_NONBLOCK, NULL);
9655 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9656 if (exception_type == EXERROR && spclbltin <= 0) {
9661 longjmp(exception_handler->loc, 1);
9666 listsetvar(varlist.list, 0);
9667 /* See above for the rationale */
9668 dowait(DOWAIT_NONBLOCK, NULL);
9669 if (evalfun(cmdentry.u.func, argc, argv, flags))
9672 status = exitstatus;
9677 if (cmd->ncmd.redirect)
9678 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9680 /* dsl: I think this is intended to be used to support
9681 * '_' in 'vi' command mode during line editing...
9682 * However I implemented that within libedit itself.
9684 setvar0("_", lastarg);
9686 popstackmark(&smark);
9692 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9694 char *volatile savecmdname;
9695 struct jmploc *volatile savehandler;
9696 struct jmploc jmploc;
9700 savecmdname = commandname;
9701 savehandler = exception_handler;
9702 i = setjmp(jmploc.loc);
9705 exception_handler = &jmploc;
9706 commandname = argv[0];
9708 optptr = NULL; /* initialize nextopt */
9710 status = evalcmd(argc, argv, flags);
9712 status = (*cmd->builtin)(argc, argv);
9713 flush_stdout_stderr();
9714 status |= ferror(stdout);
9715 exitstatus = status;
9718 commandname = savecmdname;
9719 exception_handler = savehandler;
9725 goodname(const char *p)
9727 return endofname(p)[0] == '\0';
9732 * Search for a command. This is called before we fork so that the
9733 * location of the command will be available in the parent as well as
9734 * the child. The check for "goodname" is an overly conservative
9735 * check that the name will not be subject to expansion.
9738 prehash(union node *n)
9740 struct cmdentry entry;
9742 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9743 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9747 /* ============ Builtin commands
9749 * Builtin commands whose functions are closely tied to evaluation
9750 * are implemented here.
9754 * Handle break and continue commands. Break, continue, and return are
9755 * all handled by setting the evalskip flag. The evaluation routines
9756 * above all check this flag, and if it is set they start skipping
9757 * commands rather than executing them. The variable skipcount is
9758 * the number of loops to break/continue, or the number of function
9759 * levels to return. (The latter is always 1.) It should probably
9760 * be an error to break out of more loops than exist, but it isn't
9761 * in the standard shell so we don't make it one here.
9763 static int FAST_FUNC
9764 breakcmd(int argc UNUSED_PARAM, char **argv)
9766 int n = argv[1] ? number(argv[1]) : 1;
9769 ash_msg_and_raise_error(msg_illnum, argv[1]);
9773 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9781 * This implements the input routines used by the parser.
9785 INPUT_PUSH_FILE = 1,
9786 INPUT_NOFILE_OK = 2,
9789 static smallint checkkwd;
9790 /* values of checkkwd variable */
9791 #define CHKALIAS 0x1
9796 * Push a string back onto the input at this current parsefile level.
9797 * We handle aliases this way.
9799 #if !ENABLE_ASH_ALIAS
9800 #define pushstring(s, ap) pushstring(s)
9803 pushstring(char *s, struct alias *ap)
9810 if (g_parsefile->strpush) {
9811 sp = ckzalloc(sizeof(*sp));
9812 sp->prev = g_parsefile->strpush;
9814 sp = &(g_parsefile->basestrpush);
9816 g_parsefile->strpush = sp;
9817 sp->prev_string = g_parsefile->next_to_pgetc;
9818 sp->prev_left_in_line = g_parsefile->left_in_line;
9819 sp->unget = g_parsefile->unget;
9820 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9821 #if ENABLE_ASH_ALIAS
9824 ap->flag |= ALIASINUSE;
9828 g_parsefile->next_to_pgetc = s;
9829 g_parsefile->left_in_line = len;
9830 g_parsefile->unget = 0;
9837 struct strpush *sp = g_parsefile->strpush;
9840 #if ENABLE_ASH_ALIAS
9842 if (g_parsefile->next_to_pgetc[-1] == ' '
9843 || g_parsefile->next_to_pgetc[-1] == '\t'
9845 checkkwd |= CHKALIAS;
9847 if (sp->string != sp->ap->val) {
9850 sp->ap->flag &= ~ALIASINUSE;
9851 if (sp->ap->flag & ALIASDEAD) {
9852 unalias(sp->ap->name);
9856 g_parsefile->next_to_pgetc = sp->prev_string;
9857 g_parsefile->left_in_line = sp->prev_left_in_line;
9858 g_parsefile->unget = sp->unget;
9859 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9860 g_parsefile->strpush = sp->prev;
9861 if (sp != &(g_parsefile->basestrpush))
9870 char *buf = g_parsefile->buf;
9872 g_parsefile->next_to_pgetc = buf;
9873 #if ENABLE_FEATURE_EDITING
9875 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9876 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9879 # if ENABLE_ASH_IDLE_TIMEOUT
9881 const char *tmout_var = lookupvar("TMOUT");
9883 timeout = atoi(tmout_var) * 1000;
9889 # if ENABLE_FEATURE_TAB_COMPLETION
9890 line_input_state->path_lookup = pathval();
9892 reinit_unicode_for_ash();
9893 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9895 /* ^C pressed, "convert" to SIGINT */
9896 write(STDOUT_FILENO, "^C", 2);
9903 exitstatus = 128 + SIGINT;
9909 /* Ctrl+D pressed */
9912 # if ENABLE_ASH_IDLE_TIMEOUT
9913 else if (errno == EAGAIN && timeout > 0) {
9914 puts("\007timed out waiting for input: auto-logout");
9921 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9924 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9926 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9927 int flags = fcntl(0, F_GETFL);
9928 if (flags >= 0 && (flags & O_NONBLOCK)) {
9929 flags &= ~O_NONBLOCK;
9930 if (fcntl(0, F_SETFL, flags) >= 0) {
9931 out2str("sh: turning off NDELAY mode\n");
9942 * Refill the input buffer and return the next input character:
9944 * 1) If a string was pushed back on the input, pop it;
9945 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9946 * or we are reading from a string so we can't refill the buffer,
9948 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9949 * 4) Process input up to the next newline, deleting nul characters.
9951 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9952 #define pgetc_debug(...) ((void)0)
9953 static int pgetc(void);
9960 if (g_parsefile->strpush) {
9961 #if ENABLE_ASH_ALIAS
9962 if (g_parsefile->left_in_line == -1
9963 && g_parsefile->strpush->ap
9964 && g_parsefile->next_to_pgetc[-1] != ' '
9965 && g_parsefile->next_to_pgetc[-1] != '\t'
9967 pgetc_debug("preadbuffer PEOA");
9974 /* on both branches above g_parsefile->left_in_line < 0.
9975 * "pgetc" needs refilling.
9978 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9979 * pungetc() may increment it a few times.
9980 * Assuming it won't increment it to less than -90.
9982 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9983 pgetc_debug("preadbuffer PEOF1");
9984 /* even in failure keep left_in_line and next_to_pgetc
9985 * in lock step, for correct multi-layer pungetc.
9986 * left_in_line was decremented before preadbuffer(),
9987 * must inc next_to_pgetc: */
9988 g_parsefile->next_to_pgetc++;
9992 more = g_parsefile->left_in_buffer;
9994 flush_stdout_stderr();
9998 /* don't try reading again */
9999 g_parsefile->left_in_line = -99;
10000 pgetc_debug("preadbuffer PEOF2");
10001 g_parsefile->next_to_pgetc++;
10006 /* Find out where's the end of line.
10007 * Set g_parsefile->left_in_line
10008 * and g_parsefile->left_in_buffer acordingly.
10009 * NUL chars are deleted.
10011 q = g_parsefile->next_to_pgetc;
10019 memmove(q, q + 1, more);
10023 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10029 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10030 if (g_parsefile->left_in_line < 0)
10035 g_parsefile->left_in_buffer = more;
10040 out2str(g_parsefile->next_to_pgetc);
10044 pgetc_debug("preadbuffer at %d:%p'%s'",
10045 g_parsefile->left_in_line,
10046 g_parsefile->next_to_pgetc,
10047 g_parsefile->next_to_pgetc);
10048 return (unsigned char)*g_parsefile->next_to_pgetc++;
10054 g_parsefile->linno++;
10055 setprompt_if(doprompt, 2);
10060 g_parsefile->linno++;
10061 needprompt = doprompt;
10069 pgetc_debug("pgetc at %d:%p'%s'",
10070 g_parsefile->left_in_line,
10071 g_parsefile->next_to_pgetc,
10072 g_parsefile->next_to_pgetc);
10073 if (g_parsefile->unget)
10074 return g_parsefile->lastc[--g_parsefile->unget];
10076 if (--g_parsefile->left_in_line >= 0)
10077 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10081 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10082 g_parsefile->lastc[0] = c;
10087 #if ENABLE_ASH_ALIAS
10089 pgetc_without_PEOA(void)
10093 pgetc_debug("pgetc at %d:%p'%s'",
10094 g_parsefile->left_in_line,
10095 g_parsefile->next_to_pgetc,
10096 g_parsefile->next_to_pgetc);
10098 } while (c == PEOA);
10102 # define pgetc_without_PEOA() pgetc()
10106 * Read a line from the script.
10109 pfgets(char *line, int len)
10115 while (--nleft > 0) {
10116 c = pgetc_without_PEOA();
10131 * Undo a call to pgetc. Only two characters may be pushed back.
10132 * PEOF may be pushed back.
10137 g_parsefile->unget++;
10140 /* This one eats backslash+newline */
10146 while ((c = pgetc()) == '\\') {
10147 if (pgetc() != '\n') {
10159 * To handle the "." command, a stack of input files is used. Pushfile
10160 * adds a new entry to the stack and popfile restores the previous level.
10165 struct parsefile *pf;
10167 pf = ckzalloc(sizeof(*pf));
10168 pf->prev = g_parsefile;
10170 /*pf->strpush = NULL; - ckzalloc did it */
10171 /*pf->basestrpush.prev = NULL;*/
10179 struct parsefile *pf = g_parsefile;
10185 if (pf->pf_fd >= 0)
10188 while (pf->strpush)
10190 g_parsefile = pf->prev;
10196 * Return to top level.
10201 while (g_parsefile != &basepf)
10206 * Close the file(s) that the shell is reading commands from. Called
10207 * after a fork is done.
10213 if (g_parsefile->pf_fd > 0) {
10214 close(g_parsefile->pf_fd);
10215 g_parsefile->pf_fd = 0;
10220 * Like setinputfile, but takes an open file descriptor. Call this with
10224 setinputfd(int fd, int push)
10228 g_parsefile->buf = NULL;
10230 g_parsefile->pf_fd = fd;
10231 if (g_parsefile->buf == NULL)
10232 g_parsefile->buf = ckmalloc(IBUFSIZ);
10233 g_parsefile->left_in_buffer = 0;
10234 g_parsefile->left_in_line = 0;
10235 g_parsefile->linno = 1;
10239 * Set the input to take input from a file. If push is set, push the
10240 * old input onto the stack first.
10243 setinputfile(const char *fname, int flags)
10248 fd = open(fname, O_RDONLY);
10250 if (flags & INPUT_NOFILE_OK)
10253 ash_msg_and_raise_error("can't open '%s'", fname);
10258 close_on_exec_on(fd);
10259 setinputfd(fd, flags & INPUT_PUSH_FILE);
10266 * Like setinputfile, but takes input from a string.
10269 setinputstring(char *string)
10273 g_parsefile->next_to_pgetc = string;
10274 g_parsefile->left_in_line = strlen(string);
10275 g_parsefile->buf = NULL;
10276 g_parsefile->linno = 1;
10282 * Routines to check for mail.
10285 #if ENABLE_ASH_MAIL
10287 /* Hash of mtimes of mailboxes */
10288 static unsigned mailtime_hash;
10289 /* Set if MAIL or MAILPATH is changed. */
10290 static smallint mail_var_path_changed;
10293 * Print appropriate message(s) if mail has arrived.
10294 * If mail_var_path_changed is set,
10295 * then the value of MAIL has mail_var_path_changed,
10296 * so we just update the values.
10305 struct stackmark smark;
10308 setstackmark(&smark);
10309 mpath = mpathset() ? mpathval() : mailval();
10312 p = path_advance(&mpath, nullstr);
10317 for (q = p; *q; q++)
10323 q[-1] = '\0'; /* delete trailing '/' */
10324 if (stat(p, &statb) < 0) {
10327 /* Very simplistic "hash": just a sum of all mtimes */
10328 new_hash += (unsigned)statb.st_mtime;
10330 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10331 if (mailtime_hash != 0)
10332 out2str("you have mail\n");
10333 mailtime_hash = new_hash;
10335 mail_var_path_changed = 0;
10336 popstackmark(&smark);
10339 static void FAST_FUNC
10340 changemail(const char *val UNUSED_PARAM)
10342 mail_var_path_changed = 1;
10345 #endif /* ASH_MAIL */
10348 /* ============ ??? */
10351 * Set the shell parameters.
10354 setparam(char **argv)
10360 for (nparam = 0; argv[nparam]; nparam++)
10362 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10364 *ap++ = ckstrdup(*argv++);
10367 freeparam(&shellparam);
10368 shellparam.malloced = 1;
10369 shellparam.nparam = nparam;
10370 shellparam.p = newparam;
10371 #if ENABLE_ASH_GETOPTS
10372 shellparam.optind = 1;
10373 shellparam.optoff = -1;
10378 * Process shell options. The global variable argptr contains a pointer
10379 * to the argument list; we advance it past the options.
10381 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10382 * For a non-interactive shell, an error condition encountered
10383 * by a special built-in ... shall cause the shell to write a diagnostic message
10384 * to standard error and exit as shown in the following table:
10385 * Error Special Built-In
10387 * Utility syntax error (option or operand error) Shall exit
10389 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10390 * we see that bash does not do that (set "finishes" with error code 1 instead,
10391 * and shell continues), and people rely on this behavior!
10393 * set -o barfoo 2>/dev/null
10396 * Oh well. Let's mimic that.
10399 plus_minus_o(char *name, int val)
10404 for (i = 0; i < NOPTS; i++) {
10405 if (strcmp(name, optnames(i)) == 0) {
10410 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10413 for (i = 0; i < NOPTS; i++) {
10415 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10417 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10423 setoption(int flag, int val)
10427 for (i = 0; i < NOPTS; i++) {
10428 if (optletters(i) == flag) {
10433 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10437 options(int cmdline)
10445 while ((p = *argptr) != NULL) {
10447 if (c != '-' && c != '+')
10450 val = 0; /* val = 0 if c == '+' */
10453 if (p[0] == '\0' || LONE_DASH(p)) {
10455 /* "-" means turn off -x and -v */
10458 /* "--" means reset params */
10459 else if (*argptr == NULL)
10462 break; /* "-" or "--" terminates options */
10465 /* first char was + or - */
10466 while ((c = *p++) != '\0') {
10467 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10468 if (c == 'c' && cmdline) {
10469 minusc = p; /* command is after shell args */
10470 } else if (c == 'o') {
10471 if (plus_minus_o(*argptr, val)) {
10472 /* it already printed err message */
10473 return 1; /* error */
10477 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10479 /* bash does not accept +-login, we also won't */
10480 } else if (cmdline && val && (c == '-')) { /* long options */
10481 if (strcmp(p, "login") == 0)
10493 * The shift builtin command.
10495 static int FAST_FUNC
10496 shiftcmd(int argc UNUSED_PARAM, char **argv)
10503 n = number(argv[1]);
10504 if (n > shellparam.nparam)
10505 n = 0; /* bash compat, was = shellparam.nparam; */
10507 shellparam.nparam -= n;
10508 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10509 if (shellparam.malloced)
10512 ap2 = shellparam.p;
10513 while ((*ap2++ = *ap1++) != NULL)
10515 #if ENABLE_ASH_GETOPTS
10516 shellparam.optind = 1;
10517 shellparam.optoff = -1;
10524 * POSIX requires that 'set' (but not export or readonly) output the
10525 * variables in lexicographic order - by the locale's collating order (sigh).
10526 * Maybe we could keep them in an ordered balanced binary tree
10527 * instead of hashed lists.
10528 * For now just roll 'em through qsort for printing...
10531 showvars(const char *sep_prefix, int on, int off)
10534 char **ep, **epend;
10536 ep = listvars(on, off, &epend);
10537 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10539 sep = *sep_prefix ? " " : sep_prefix;
10541 for (; ep < epend; ep++) {
10545 p = strchrnul(*ep, '=');
10548 q = single_quote(++p);
10549 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10555 * The set command builtin.
10557 static int FAST_FUNC
10558 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10563 return showvars(nullstr, 0, VUNSET);
10566 retval = options(/*cmdline:*/ 0);
10567 if (retval == 0) { /* if no parse error... */
10569 if (*argptr != NULL) {
10577 #if ENABLE_ASH_RANDOM_SUPPORT
10578 static void FAST_FUNC
10579 change_random(const char *value)
10583 if (value == NULL) {
10584 /* "get", generate */
10585 t = next_random(&random_gen);
10586 /* set without recursion */
10587 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10588 vrandom.flags &= ~VNOFUNC;
10591 t = strtoul(value, NULL, 10);
10592 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10597 #if ENABLE_ASH_GETOPTS
10599 getopts(char *optstr, char *optvar, char **optfirst)
10606 int ind = shellparam.optind;
10607 int off = shellparam.optoff;
10611 shellparam.optind = -1;
10612 optnext = optfirst + ind - 1;
10614 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10617 p = optnext[-1] + off;
10618 if (p == NULL || *p == '\0') {
10619 /* Current word is done, advance */
10621 if (p == NULL || *p != '-' || *++p == '\0') {
10628 if (LONE_DASH(p)) /* check for "--" */
10633 for (q = optstr; *q != c;) {
10635 if (optstr[0] == ':') {
10637 /*sbuf[1] = '\0'; - already is */
10638 setvar0("OPTARG", sbuf);
10640 fprintf(stderr, "Illegal option -%c\n", c);
10641 unsetvar("OPTARG");
10651 if (*p == '\0' && (p = *optnext) == NULL) {
10652 if (optstr[0] == ':') {
10654 /*sbuf[1] = '\0'; - already is */
10655 setvar0("OPTARG", sbuf);
10658 fprintf(stderr, "No arg for -%c option\n", c);
10659 unsetvar("OPTARG");
10667 setvar0("OPTARG", p);
10670 setvar0("OPTARG", nullstr);
10672 ind = optnext - optfirst + 1;
10673 setvar("OPTIND", itoa(ind), VNOFUNC);
10675 /*sbuf[1] = '\0'; - already is */
10676 setvar0(optvar, sbuf);
10678 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10679 shellparam.optind = ind;
10685 * The getopts builtin. Shellparam.optnext points to the next argument
10686 * to be processed. Shellparam.optptr points to the next character to
10687 * be processed in the current argument. If shellparam.optnext is NULL,
10688 * then it's the first time getopts has been called.
10690 static int FAST_FUNC
10691 getoptscmd(int argc, char **argv)
10696 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10698 optbase = shellparam.p;
10699 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10700 shellparam.optind = 1;
10701 shellparam.optoff = -1;
10704 optbase = &argv[3];
10705 if ((unsigned)shellparam.optind > argc - 2) {
10706 shellparam.optind = 1;
10707 shellparam.optoff = -1;
10711 return getopts(argv[1], argv[2], optbase);
10713 #endif /* ASH_GETOPTS */
10716 /* ============ Shell parser */
10719 struct heredoc *next; /* next here document in list */
10720 union node *here; /* redirection node */
10721 char *eofmark; /* string indicating end of input */
10722 smallint striptabs; /* if set, strip leading tabs */
10725 static smallint tokpushback; /* last token pushed back */
10726 static smallint quoteflag; /* set if (part of) last token was quoted */
10727 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10728 static struct heredoc *heredoclist; /* list of here documents to read */
10729 static char *wordtext; /* text of last word returned by readtoken */
10730 static struct nodelist *backquotelist;
10731 static union node *redirnode;
10732 static struct heredoc *heredoc;
10734 static const char *
10735 tokname(char *buf, int tok)
10738 return tokname_array[tok];
10739 sprintf(buf, "\"%s\"", tokname_array[tok]);
10743 /* raise_error_unexpected_syntax:
10744 * Called when an unexpected token is read during the parse. The argument
10745 * is the token that is expected, or -1 if more than one type of token can
10746 * occur at this point.
10748 static void raise_error_unexpected_syntax(int) NORETURN;
10750 raise_error_unexpected_syntax(int token)
10756 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10758 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10759 raise_error_syntax(msg);
10763 #define EOFMARKLEN 79
10765 /* parsing is heavily cross-recursive, need these forward decls */
10766 static union node *andor(void);
10767 static union node *pipeline(void);
10768 static union node *parse_command(void);
10769 static void parseheredoc(void);
10770 static int peektoken(void);
10771 static int readtoken(void);
10773 static union node *
10776 union node *n1, *n2, *n3;
10781 switch (peektoken()) {
10789 if (!n1 && (nlflag & 1))
10795 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10796 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10802 if (tok == TBACKGND) {
10803 if (n2->type == NPIPE) {
10804 n2->npipe.pipe_backgnd = 1;
10806 if (n2->type != NREDIR) {
10807 n3 = stzalloc(sizeof(struct nredir));
10809 /*n3->nredir.redirect = NULL; - stzalloc did it */
10812 n2->type = NBACKGND;
10818 n3 = stzalloc(sizeof(struct nbinary));
10820 n3->nbinary.ch1 = n1;
10821 n3->nbinary.ch2 = n2;
10834 raise_error_unexpected_syntax(-1);
10841 static union node *
10844 union node *n1, *n2, *n3;
10852 } else if (t == TOR) {
10858 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10860 n3 = stzalloc(sizeof(struct nbinary));
10862 n3->nbinary.ch1 = n1;
10863 n3->nbinary.ch2 = n2;
10868 static union node *
10871 union node *n1, *n2, *pipenode;
10872 struct nodelist *lp, *prev;
10876 TRACE(("pipeline: entered\n"));
10877 if (readtoken() == TNOT) {
10879 checkkwd = CHKKWD | CHKALIAS;
10882 n1 = parse_command();
10883 if (readtoken() == TPIPE) {
10884 pipenode = stzalloc(sizeof(struct npipe));
10885 pipenode->type = NPIPE;
10886 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10887 lp = stzalloc(sizeof(struct nodelist));
10888 pipenode->npipe.cmdlist = lp;
10892 lp = stzalloc(sizeof(struct nodelist));
10893 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10894 lp->n = parse_command();
10896 } while (readtoken() == TPIPE);
10902 n2 = stzalloc(sizeof(struct nnot));
10910 static union node *
10915 n = stzalloc(sizeof(struct narg));
10917 /*n->narg.next = NULL; - stzalloc did it */
10918 n->narg.text = wordtext;
10919 n->narg.backquote = backquotelist;
10924 fixredir(union node *n, const char *text, int err)
10928 TRACE(("Fix redir %s %d\n", text, err));
10930 n->ndup.vname = NULL;
10932 fd = bb_strtou(text, NULL, 10);
10933 if (!errno && fd >= 0)
10934 n->ndup.dupfd = fd;
10935 else if (LONE_DASH(text))
10936 n->ndup.dupfd = -1;
10939 raise_error_syntax("bad fd number");
10940 n->ndup.vname = makename();
10945 * Returns true if the text contains nothing to expand (no dollar signs
10949 noexpand(const char *text)
10953 while ((c = *text++) != '\0') {
10954 if (c == CTLQUOTEMARK)
10958 else if (SIT(c, BASESYNTAX) == CCTL)
10967 union node *n = redirnode;
10969 if (readtoken() != TWORD)
10970 raise_error_unexpected_syntax(-1);
10971 if (n->type == NHERE) {
10972 struct heredoc *here = heredoc;
10976 if (quoteflag == 0)
10978 TRACE(("Here document %d\n", n->type));
10979 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10980 raise_error_syntax("illegal eof marker for << redirection");
10981 rmescapes(wordtext, 0);
10982 here->eofmark = wordtext;
10984 if (heredoclist == NULL)
10985 heredoclist = here;
10987 for (p = heredoclist; p->next; p = p->next)
10991 } else if (n->type == NTOFD || n->type == NFROMFD) {
10992 fixredir(n, wordtext, 0);
10994 n->nfile.fname = makename();
10998 static union node *
11001 union node *args, **app;
11002 union node *n = NULL;
11003 union node *vars, **vpp;
11004 union node **rpp, *redir;
11006 #if ENABLE_ASH_BASH_COMPAT
11007 smallint double_brackets_flag = 0;
11008 smallint function_flag = 0;
11018 savecheckkwd = CHKALIAS;
11021 checkkwd = savecheckkwd;
11024 #if ENABLE_ASH_BASH_COMPAT
11026 if (peektoken() != TWORD)
11027 raise_error_unexpected_syntax(TWORD);
11030 case TAND: /* "&&" */
11031 case TOR: /* "||" */
11032 if (!double_brackets_flag) {
11036 wordtext = (char *) (t == TAND ? "-a" : "-o");
11039 n = stzalloc(sizeof(struct narg));
11041 /*n->narg.next = NULL; - stzalloc did it */
11042 n->narg.text = wordtext;
11043 #if ENABLE_ASH_BASH_COMPAT
11044 if (strcmp("[[", wordtext) == 0)
11045 double_brackets_flag = 1;
11046 else if (strcmp("]]", wordtext) == 0)
11047 double_brackets_flag = 0;
11049 n->narg.backquote = backquotelist;
11050 if (savecheckkwd && isassignment(wordtext)) {
11052 vpp = &n->narg.next;
11055 app = &n->narg.next;
11058 #if ENABLE_ASH_BASH_COMPAT
11059 if (function_flag) {
11060 checkkwd = CHKNL | CHKKWD;
11061 switch (peektoken()) {
11073 if (strcmp("[[", wordtext) == 0)
11077 raise_error_unexpected_syntax(-1);
11083 *rpp = n = redirnode;
11084 rpp = &n->nfile.next;
11085 parsefname(); /* read name of redirection file */
11088 IF_ASH_BASH_COMPAT(do_func:)
11089 if (args && app == &args->narg.next
11092 struct builtincmd *bcmd;
11095 /* We have a function */
11096 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11097 raise_error_unexpected_syntax(TRP);
11098 name = n->narg.text;
11099 if (!goodname(name)
11100 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11102 raise_error_syntax("bad function name");
11105 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11106 n->narg.next = parse_command();
11109 IF_ASH_BASH_COMPAT(function_flag = 0;)
11120 n = stzalloc(sizeof(struct ncmd));
11122 n->ncmd.args = args;
11123 n->ncmd.assign = vars;
11124 n->ncmd.redirect = redir;
11128 static union node *
11129 parse_command(void)
11131 union node *n1, *n2;
11132 union node *ap, **app;
11133 union node *cp, **cpp;
11134 union node *redir, **rpp;
11141 switch (readtoken()) {
11143 raise_error_unexpected_syntax(-1);
11146 n1 = stzalloc(sizeof(struct nif));
11148 n1->nif.test = list(0);
11149 if (readtoken() != TTHEN)
11150 raise_error_unexpected_syntax(TTHEN);
11151 n1->nif.ifpart = list(0);
11153 while (readtoken() == TELIF) {
11154 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11155 n2 = n2->nif.elsepart;
11157 n2->nif.test = list(0);
11158 if (readtoken() != TTHEN)
11159 raise_error_unexpected_syntax(TTHEN);
11160 n2->nif.ifpart = list(0);
11162 if (lasttoken == TELSE)
11163 n2->nif.elsepart = list(0);
11165 n2->nif.elsepart = NULL;
11173 n1 = stzalloc(sizeof(struct nbinary));
11174 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11175 n1->nbinary.ch1 = list(0);
11178 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11179 got == TWORD ? wordtext : ""));
11180 raise_error_unexpected_syntax(TDO);
11182 n1->nbinary.ch2 = list(0);
11187 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11188 raise_error_syntax("bad for loop variable");
11189 n1 = stzalloc(sizeof(struct nfor));
11191 n1->nfor.var = wordtext;
11192 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11193 if (readtoken() == TIN) {
11195 while (readtoken() == TWORD) {
11196 n2 = stzalloc(sizeof(struct narg));
11198 /*n2->narg.next = NULL; - stzalloc did it */
11199 n2->narg.text = wordtext;
11200 n2->narg.backquote = backquotelist;
11202 app = &n2->narg.next;
11205 n1->nfor.args = ap;
11206 if (lasttoken != TNL && lasttoken != TSEMI)
11207 raise_error_unexpected_syntax(-1);
11209 n2 = stzalloc(sizeof(struct narg));
11211 /*n2->narg.next = NULL; - stzalloc did it */
11212 n2->narg.text = (char *)dolatstr;
11213 /*n2->narg.backquote = NULL;*/
11214 n1->nfor.args = n2;
11216 * Newline or semicolon here is optional (but note
11217 * that the original Bourne shell only allowed NL).
11219 if (lasttoken != TSEMI)
11222 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11223 if (readtoken() != TDO)
11224 raise_error_unexpected_syntax(TDO);
11225 n1->nfor.body = list(0);
11229 n1 = stzalloc(sizeof(struct ncase));
11231 if (readtoken() != TWORD)
11232 raise_error_unexpected_syntax(TWORD);
11233 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11235 /*n2->narg.next = NULL; - stzalloc did it */
11236 n2->narg.text = wordtext;
11237 n2->narg.backquote = backquotelist;
11238 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11239 if (readtoken() != TIN)
11240 raise_error_unexpected_syntax(TIN);
11241 cpp = &n1->ncase.cases;
11243 checkkwd = CHKNL | CHKKWD;
11245 while (t != TESAC) {
11246 if (lasttoken == TLP)
11248 *cpp = cp = stzalloc(sizeof(struct nclist));
11250 app = &cp->nclist.pattern;
11252 *app = ap = stzalloc(sizeof(struct narg));
11254 /*ap->narg.next = NULL; - stzalloc did it */
11255 ap->narg.text = wordtext;
11256 ap->narg.backquote = backquotelist;
11257 if (readtoken() != TPIPE)
11259 app = &ap->narg.next;
11262 //ap->narg.next = NULL;
11263 if (lasttoken != TRP)
11264 raise_error_unexpected_syntax(TRP);
11265 cp->nclist.body = list(2);
11267 cpp = &cp->nclist.next;
11269 checkkwd = CHKNL | CHKKWD;
11273 raise_error_unexpected_syntax(TENDCASE);
11280 n1 = stzalloc(sizeof(struct nredir));
11281 n1->type = NSUBSHELL;
11282 n1->nredir.n = list(0);
11283 /*n1->nredir.redirect = NULL; - stzalloc did it */
11290 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11294 return simplecmd();
11297 if (readtoken() != t)
11298 raise_error_unexpected_syntax(t);
11301 /* Now check for redirection which may follow command */
11302 checkkwd = CHKKWD | CHKALIAS;
11304 while (readtoken() == TREDIR) {
11305 *rpp = n2 = redirnode;
11306 rpp = &n2->nfile.next;
11312 if (n1->type != NSUBSHELL) {
11313 n2 = stzalloc(sizeof(struct nredir));
11318 n1->nredir.redirect = redir;
11323 #if ENABLE_ASH_BASH_COMPAT
11325 decode_dollar_squote(void)
11327 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11333 p = strchr(C_escapes, c);
11338 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11342 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11344 } else if (c == 'x') { /* \xHH */
11348 } while (isxdigit(c) && --cnt);
11350 if (cnt == 3) { /* \x but next char is "bad" */
11354 } else { /* simple seq like \\ or \t */
11359 c = bb_process_escape_sequence((void*)&p);
11360 } else { /* unrecognized "\z": print both chars unless ' or " */
11361 if (c != '\'' && c != '"') {
11363 c |= 0x100; /* "please encode \, then me" */
11371 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11372 * is not NULL, read a here document. In the latter case, eofmark is the
11373 * word which marks the end of the document and striptabs is true if
11374 * leading tabs should be stripped from the document. The argument c
11375 * is the first character of the input token or document.
11377 * Because C does not have internal subroutines, I have simulated them
11378 * using goto's to implement the subroutine linkage. The following macros
11379 * will run code that appears at the end of readtoken1.
11381 #define CHECKEND() {goto checkend; checkend_return:;}
11382 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11383 #define PARSESUB() {goto parsesub; parsesub_return:;}
11384 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11385 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11386 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11388 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11390 /* NB: syntax parameter fits into smallint */
11391 /* c parameter is an unsigned char or PEOF or PEOA */
11394 char line[EOFMARKLEN + 1];
11395 struct nodelist *bqlist;
11399 IF_SH_MATH_SUPPORT(smallint prevsyntax;) /* syntax before arithmetic */
11400 #if ENABLE_ASH_EXPAND_PRMT
11401 smallint pssyntax; /* we are expanding a prompt string */
11403 int varnest; /* levels of variables expansion */
11404 IF_SH_MATH_SUPPORT(int arinest;) /* levels of arithmetic expansion */
11405 IF_SH_MATH_SUPPORT(int parenlevel;) /* levels of parens in arithmetic */
11406 int dqvarnest; /* levels of variables expansion within double quotes */
11408 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11410 startlinno = g_parsefile->linno;
11413 IF_SH_MATH_SUPPORT(prevsyntax = 0;)
11414 #if ENABLE_ASH_EXPAND_PRMT
11415 pssyntax = (syntax == PSSYNTAX);
11419 dblquote = (syntax == DQSYNTAX);
11421 IF_SH_MATH_SUPPORT(arinest = 0;)
11422 IF_SH_MATH_SUPPORT(parenlevel = 0;)
11425 STARTSTACKSTR(out);
11427 /* For each line, until end of word */
11428 CHECKEND(); /* set c to PEOF if at end of here document */
11429 for (;;) { /* until end of line or end of word */
11430 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11431 switch (SIT(c, syntax)) {
11432 case CNL: /* '\n' */
11433 if (syntax == BASESYNTAX)
11434 goto endword; /* exit outer loop */
11438 goto loop; /* continue outer loop */
11443 #if ENABLE_ASH_BASH_COMPAT
11444 if (c == '\\' && bash_dollar_squote) {
11445 c = decode_dollar_squote();
11447 /* skip $'\000', $'\x00' (like bash) */
11451 /* Unknown escape. Encode as '\z' */
11452 c = (unsigned char)c;
11453 if (eofmark == NULL || dblquote)
11454 USTPUTC(CTLESC, out);
11455 USTPUTC('\\', out);
11459 if (eofmark == NULL || dblquote)
11460 USTPUTC(CTLESC, out);
11463 case CBACK: /* backslash */
11464 c = pgetc_without_PEOA();
11466 USTPUTC(CTLESC, out);
11467 USTPUTC('\\', out);
11469 } else if (c == '\n') {
11472 #if ENABLE_ASH_EXPAND_PRMT
11473 if (c == '$' && pssyntax) {
11474 USTPUTC(CTLESC, out);
11475 USTPUTC('\\', out);
11478 /* Backslash is retained if we are in "str" and next char isn't special */
11483 && (c != '"' || eofmark != NULL)
11485 USTPUTC('\\', out);
11487 USTPUTC(CTLESC, out);
11495 if (eofmark == NULL) {
11496 USTPUTC(CTLQUOTEMARK, out);
11504 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11505 if (eofmark != NULL && varnest == 0) {
11508 if (dqvarnest == 0) {
11509 syntax = BASESYNTAX;
11516 case CVAR: /* '$' */
11517 PARSESUB(); /* parse substitution */
11519 case CENDVAR: /* '}' */
11522 if (dqvarnest > 0) {
11529 #if ENABLE_SH_MATH_SUPPORT
11530 case CLP: /* '(' in arithmetic */
11534 case CRP: /* ')' in arithmetic */
11535 if (parenlevel > 0) {
11538 if (pgetc_eatbnl() == ')') {
11540 if (--arinest == 0) {
11541 syntax = prevsyntax;
11545 * unbalanced parens
11546 * (don't 2nd guess - no error)
11554 case CBQUOTE: /* '`' */
11558 goto endword; /* exit outer loop */
11562 if (varnest == 0) {
11563 #if ENABLE_ASH_BASH_COMPAT
11565 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11566 if (pgetc() == '>')
11567 c = 0x100 + '>'; /* flag &> */
11571 goto endword; /* exit outer loop */
11573 IF_ASH_ALIAS(if (c != PEOA))
11580 #if ENABLE_SH_MATH_SUPPORT
11581 if (syntax == ARISYNTAX)
11582 raise_error_syntax("missing '))'");
11584 if (syntax != BASESYNTAX && eofmark == NULL)
11585 raise_error_syntax("unterminated quoted string");
11586 if (varnest != 0) {
11587 startlinno = g_parsefile->linno;
11589 raise_error_syntax("missing '}'");
11591 USTPUTC('\0', out);
11592 len = out - (char *)stackblock();
11593 out = stackblock();
11594 if (eofmark == NULL) {
11595 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11598 if (isdigit_str9(out)) {
11599 PARSEREDIR(); /* passed as params: out, c */
11600 lasttoken = TREDIR;
11603 /* else: non-number X seen, interpret it
11604 * as "NNNX>file" = "NNNX >file" */
11608 quoteflag = quotef;
11609 backquotelist = bqlist;
11610 grabstackblock(len);
11614 /* end of readtoken routine */
11617 * Check to see whether we are at the end of the here document. When this
11618 * is called, c is set to the first character of the next input line. If
11619 * we are at the end of the here document, this routine sets the c to PEOF.
11623 #if ENABLE_ASH_ALIAS
11625 c = pgetc_without_PEOA();
11628 while (c == '\t') {
11629 c = pgetc_without_PEOA();
11632 if (c == *eofmark) {
11633 if (pfgets(line, sizeof(line)) != NULL) {
11638 for (q = eofmark + 1;; p++, q++) {
11642 if (!*q || cc != *q)
11649 pushstring(line, NULL);
11654 goto checkend_return;
11658 * Parse a redirection operator. The variable "out" points to a string
11659 * specifying the fd to be redirected. The variable "c" contains the
11660 * first character of the redirection operator.
11663 /* out is already checked to be a valid number or "" */
11664 int fd = (*out == '\0' ? -1 : atoi(out));
11667 np = stzalloc(sizeof(struct nfile));
11672 np->type = NAPPEND;
11674 np->type = NCLOBBER;
11677 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11683 #if ENABLE_ASH_BASH_COMPAT
11684 else if (c == 0x100 + '>') { /* this flags &> redirection */
11686 pgetc(); /* this is '>', no need to check */
11690 else { /* c == '<' */
11691 /*np->nfile.fd = 0; - stzalloc did it */
11695 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11696 np = stzalloc(sizeof(struct nhere));
11697 /*np->nfile.fd = 0; - stzalloc did it */
11700 heredoc = stzalloc(sizeof(struct heredoc));
11701 heredoc->here = np;
11704 heredoc->striptabs = 1;
11706 /*heredoc->striptabs = 0; - stzalloc did it */
11712 np->type = NFROMFD;
11716 np->type = NFROMTO;
11728 goto parseredir_return;
11732 * Parse a substitution. At this point, we have read the dollar sign
11733 * and nothing else.
11736 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11737 * (assuming ascii char codes, as the original implementation did) */
11738 #define is_special(c) \
11739 (((unsigned)(c) - 33 < 32) \
11740 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11742 unsigned char subtype;
11745 c = pgetc_eatbnl();
11746 if (c > 255 /* PEOA or PEOF */
11747 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11749 #if ENABLE_ASH_BASH_COMPAT
11750 if (syntax != DQSYNTAX && c == '\'')
11751 bash_dollar_squote = 1;
11756 } else if (c == '(') {
11757 /* $(command) or $((arith)) */
11758 if (pgetc_eatbnl() == '(') {
11759 #if ENABLE_SH_MATH_SUPPORT
11762 raise_error_syntax("you disabled math support for $((arith)) syntax");
11769 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11770 USTPUTC(CTLVAR, out);
11771 typeloc = out - (char *)stackblock();
11773 subtype = VSNORMAL;
11775 c = pgetc_eatbnl();
11780 /* $[{[#]]NAME[}] */
11783 c = pgetc_eatbnl();
11784 } while (is_in_name(c));
11785 } else if (isdigit(c)) {
11786 /* $[{[#]]NUM[}] */
11789 c = pgetc_eatbnl();
11790 } while (isdigit(c));
11791 } else if (is_special(c)) {
11792 /* $[{[#]]<specialchar>[}] */
11795 c = pgetc_eatbnl();
11796 if (!subtype && cc == '#') {
11797 subtype = VSLENGTH;
11798 if (c == '_' || isalnum(c))
11801 c = pgetc_eatbnl();
11802 if (cc == '}' || c != '}') {
11813 if (c != '}' && subtype == VSLENGTH) {
11814 /* ${#VAR didn't end with } */
11818 if (subtype == 0) {
11819 static const char types[] ALIGN1 = "}-+?=";
11820 /* ${VAR...} but not $VAR or ${#VAR} */
11821 /* c == first char after VAR */
11824 c = pgetc_eatbnl();
11825 #if ENABLE_ASH_BASH_COMPAT
11826 /* This check is only needed to not misinterpret
11827 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11830 if (!strchr(types, c)) {
11831 subtype = VSSUBSTR;
11833 break; /* "goto badsub" is bigger (!) */
11839 const char *p = strchr(types, c);
11842 subtype |= p - types + VSNORMAL;
11848 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11849 c = pgetc_eatbnl();
11855 #if ENABLE_ASH_BASH_COMPAT
11857 /* ${v/[/]pattern/repl} */
11858 //TODO: encode pattern and repl separately.
11859 // Currently ${v/$var_with_slash/repl} is horribly broken
11860 subtype = VSREPLACE;
11861 c = pgetc_eatbnl();
11864 subtype++; /* VSREPLACEALL */
11872 ((unsigned char *)stackblock())[typeloc] = subtype;
11873 if (subtype != VSNORMAL) {
11880 goto parsesub_return;
11884 * Called to parse command substitutions. Newstyle is set if the command
11885 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11886 * list of commands (passed by reference), and savelen is the number of
11887 * characters on the top of the stack which must be preserved.
11890 struct nodelist **nlpp;
11894 smallint saveprompt = 0;
11897 savelen = out - (char *)stackblock();
11900 * FIXME: this can allocate very large block on stack and SEGV.
11902 * echo "..<100kbytes>..`true` $(true) `true` ..."
11903 * allocates 100kb for every command subst. With about
11904 * a hundred command substitutions stack overflows.
11905 * With larger prepended string, SEGV happens sooner.
11907 str = alloca(savelen);
11908 memcpy(str, stackblock(), savelen);
11912 /* We must read until the closing backquote, giving special
11913 * treatment to some slashes, and then push the string and
11914 * reread it as input, interpreting it normally.
11920 STARTSTACKSTR(pout);
11924 setprompt_if(needprompt, 2);
11935 * If eating a newline, avoid putting
11936 * the newline into the new character
11937 * stream (via the STPUTC after the
11942 if (pc != '\\' && pc != '`' && pc != '$'
11943 && (!dblquote || pc != '"')
11945 STPUTC('\\', pout);
11947 if (pc <= 255 /* not PEOA or PEOF */) {
11953 IF_ASH_ALIAS(case PEOA:)
11954 startlinno = g_parsefile->linno;
11955 raise_error_syntax("EOF in backquote substitution");
11967 STPUTC('\0', pout);
11968 psavelen = pout - (char *)stackblock();
11969 if (psavelen > 0) {
11970 pstr = grabstackstr(pout);
11971 setinputstring(pstr);
11976 nlpp = &(*nlpp)->next;
11977 *nlpp = stzalloc(sizeof(**nlpp));
11978 /* (*nlpp)->next = NULL; - stzalloc did it */
11981 saveprompt = doprompt;
11988 doprompt = saveprompt;
11989 else if (readtoken() != TRP)
11990 raise_error_unexpected_syntax(TRP);
11995 * Start reading from old file again, ignoring any pushed back
11996 * tokens left from the backquote parsing
12001 while (stackblocksize() <= savelen)
12003 STARTSTACKSTR(out);
12005 memcpy(out, str, savelen);
12006 STADJUST(savelen, out);
12008 USTPUTC(CTLBACKQ, out);
12010 goto parsebackq_oldreturn;
12011 goto parsebackq_newreturn;
12014 #if ENABLE_SH_MATH_SUPPORT
12016 * Parse an arithmetic expansion (indicate start of one and set state)
12019 if (++arinest == 1) {
12020 prevsyntax = syntax;
12021 syntax = ARISYNTAX;
12023 USTPUTC(CTLARI, out);
12024 goto parsearith_return;
12027 } /* end of readtoken */
12030 * Read the next input token.
12031 * If the token is a word, we set backquotelist to the list of cmds in
12032 * backquotes. We set quoteflag to true if any part of the word was
12034 * If the token is TREDIR, then we set redirnode to a structure containing
12036 * In all cases, the variable startlinno is set to the number of the line
12037 * on which the token starts.
12039 * [Change comment: here documents and internal procedures]
12040 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12041 * word parsing code into a separate routine. In this case, readtoken
12042 * doesn't need to have any internal procedures, but parseword does.
12043 * We could also make parseoperator in essence the main routine, and
12044 * have parseword (readtoken1?) handle both words and redirection.]
12046 #define NEW_xxreadtoken
12047 #ifdef NEW_xxreadtoken
12048 /* singles must be first! */
12049 static const char xxreadtoken_chars[7] ALIGN1 = {
12050 '\n', '(', ')', /* singles */
12051 '&', '|', ';', /* doubles */
12055 #define xxreadtoken_singles 3
12056 #define xxreadtoken_doubles 3
12058 static const char xxreadtoken_tokens[] ALIGN1 = {
12059 TNL, TLP, TRP, /* only single occurrence allowed */
12060 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12061 TEOF, /* corresponds to trailing nul */
12062 TAND, TOR, TENDCASE /* if double occurrence */
12074 setprompt_if(needprompt, 2);
12075 startlinno = g_parsefile->linno;
12076 for (;;) { /* until token or start of word found */
12078 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12082 while ((c = pgetc()) != '\n' && c != PEOF)
12085 } else if (c == '\\') {
12086 if (pgetc() != '\n') {
12088 break; /* return readtoken1(...) */
12094 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12100 p = strchr(xxreadtoken_chars, c);
12102 break; /* return readtoken1(...) */
12104 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12106 if (cc == c) { /* double occurrence? */
12107 p += xxreadtoken_doubles + 1;
12110 #if ENABLE_ASH_BASH_COMPAT
12111 if (c == '&' && cc == '>') /* &> */
12112 break; /* return readtoken1(...) */
12117 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12122 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12124 #else /* old xxreadtoken */
12125 #define RETURN(token) return lasttoken = token
12135 setprompt_if(needprompt, 2);
12136 startlinno = g_parsefile->linno;
12137 for (;;) { /* until token or start of word found */
12140 case ' ': case '\t':
12141 IF_ASH_ALIAS(case PEOA:)
12144 while ((c = pgetc()) != '\n' && c != PEOF)
12149 if (pgetc() == '\n') {
12161 if (pgetc() == '&')
12166 if (pgetc() == '|')
12171 if (pgetc() == ';')
12184 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12187 #endif /* old xxreadtoken */
12193 int kwd = checkkwd;
12195 smallint alreadyseen = tokpushback;
12198 #if ENABLE_ASH_ALIAS
12214 if (t != TWORD || quoteflag) {
12219 * check for keywords
12221 if (kwd & CHKKWD) {
12222 const char *const *pp;
12224 pp = findkwd(wordtext);
12226 lasttoken = t = pp - tokname_array;
12227 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12232 if (checkkwd & CHKALIAS) {
12233 #if ENABLE_ASH_ALIAS
12235 ap = lookupalias(wordtext, 1);
12238 pushstring(ap->val, ap);
12248 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12250 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12266 * Read and parse a command. Returns NODE_EOF on end of file.
12267 * (NULL is a valid parse tree indicating a blank line.)
12269 static union node *
12270 parsecmd(int interact)
12275 doprompt = interact;
12276 setprompt_if(doprompt, doprompt);
12282 * Input any here documents.
12287 struct heredoc *here;
12290 here = heredoclist;
12291 heredoclist = NULL;
12294 setprompt_if(needprompt, 2);
12295 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12296 here->eofmark, here->striptabs);
12297 n = stzalloc(sizeof(struct narg));
12298 n->narg.type = NARG;
12299 /*n->narg.next = NULL; - stzalloc did it */
12300 n->narg.text = wordtext;
12301 n->narg.backquote = backquotelist;
12302 here->here->nhere.doc = n;
12309 * called by editline -- any expansions to the prompt should be added here.
12311 #if ENABLE_ASH_EXPAND_PRMT
12312 static const char *
12313 expandstr(const char *ps)
12318 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12319 * and token processing _can_ alter it (delete NULs etc). */
12320 setinputstring((char *)ps);
12322 saveprompt = doprompt;
12324 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12325 doprompt = saveprompt;
12329 n.narg.type = NARG;
12330 n.narg.next = NULL;
12331 n.narg.text = wordtext;
12332 n.narg.backquote = backquotelist;
12334 expandarg(&n, NULL, EXP_QUOTED);
12335 return stackblock();
12340 * Execute a command or commands contained in a string.
12343 evalstring(char *s, int flags)
12345 struct jmploc *volatile savehandler;
12346 struct jmploc jmploc;
12350 struct stackmark smark;
12355 setstackmark(&smark);
12358 /* On exception inside execution loop, we must popfile().
12359 * Try interactively:
12361 * command eval "a=b" # throws "is read only" error
12362 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12363 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12365 savehandler = exception_handler;
12366 ex = setjmp(jmploc.loc);
12369 exception_handler = &jmploc;
12371 while ((n = parsecmd(0)) != NODE_EOF) {
12374 i = evaltree(n, flags);
12377 popstackmark(&smark);
12382 popstackmark(&smark);
12386 exception_handler = savehandler;
12388 longjmp(exception_handler->loc, ex);
12394 * The eval command.
12396 static int FAST_FUNC
12397 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12406 STARTSTACKSTR(concat);
12408 concat = stack_putstr(p, concat);
12412 STPUTC(' ', concat);
12414 STPUTC('\0', concat);
12415 p = grabstackstr(concat);
12417 return evalstring(p, flags & EV_TESTED);
12423 * Read and execute commands.
12424 * "Top" is nonzero for the top level command loop;
12425 * it turns on prompting if the shell is interactive.
12431 struct stackmark smark;
12436 TRACE(("cmdloop(%d) called\n", top));
12440 setstackmark(&smark);
12443 showjobs(SHOW_CHANGED|SHOW_STDERR);
12446 if (iflag && top) {
12450 n = parsecmd(inter);
12452 if (DEBUG > 2 && debug && (n != NODE_EOF))
12455 if (n == NODE_EOF) {
12456 if (!top || numeof >= 50)
12458 if (!stoppedjobs()) {
12461 out2str("\nUse \"exit\" to leave shell.\n");
12464 } else if (nflag == 0) {
12467 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12470 i = evaltree(n, 0);
12474 popstackmark(&smark);
12478 evalskip &= ~SKIPFUNC;
12486 * Take commands from a file. To be compatible we should do a path
12487 * search for the file, which is necessary to find sub-commands.
12490 find_dot_file(char *name)
12493 const char *path = pathval();
12496 /* don't try this for absolute or relative paths */
12497 if (strchr(name, '/'))
12500 /* IIRC standards do not say whether . is to be searched.
12501 * And it is even smaller this way, making it unconditional for now:
12503 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12508 while ((fullname = path_advance(&path, name)) != NULL) {
12510 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12512 * Don't bother freeing here, since it will
12513 * be freed by the caller.
12517 if (fullname != name)
12518 stunalloc(fullname);
12521 /* not found in the PATH */
12522 ash_msg_and_raise_error("%s: not found", name);
12526 static int FAST_FUNC
12527 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12529 /* "false; . empty_file; echo $?" should print 0, not 1: */
12533 struct strlist *sp;
12534 volatile struct shparam saveparam;
12536 for (sp = cmdenviron; sp; sp = sp->next)
12537 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12539 nextopt(nullstr); /* handle possible "--" */
12543 /* bash says: "bash: .: filename argument required" */
12544 return 2; /* bash compat */
12547 /* This aborts if file isn't found, which is POSIXly correct.
12548 * bash returns exitcode 1 instead.
12550 fullname = find_dot_file(argv[0]);
12552 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12554 saveparam = shellparam;
12555 shellparam.malloced = 0;
12559 shellparam.nparam = argc;
12560 shellparam.p = argv;
12563 /* This aborts if file can't be opened, which is POSIXly correct.
12564 * bash returns exitcode 1 instead.
12566 setinputfile(fullname, INPUT_PUSH_FILE);
12567 commandname = fullname;
12568 status = cmdloop(0);
12572 freeparam(&shellparam);
12573 shellparam = saveparam;
12579 static int FAST_FUNC
12580 exitcmd(int argc UNUSED_PARAM, char **argv)
12585 exitstatus = number(argv[1]);
12586 raise_exception(EXEXIT);
12591 * Read a file containing shell functions.
12594 readcmdfile(char *name)
12596 setinputfile(name, INPUT_PUSH_FILE);
12602 /* ============ find_command inplementation */
12605 * Resolve a command name. If you change this routine, you may have to
12606 * change the shellexec routine as well.
12609 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12611 struct tblentry *cmdp;
12618 struct builtincmd *bcmd;
12620 /* If name contains a slash, don't use PATH or hash table */
12621 if (strchr(name, '/') != NULL) {
12622 entry->u.index = -1;
12623 if (act & DO_ABS) {
12624 while (stat(name, &statb) < 0) {
12626 if (errno == EINTR)
12629 entry->cmdtype = CMDUNKNOWN;
12633 entry->cmdtype = CMDNORMAL;
12637 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12639 updatetbl = (path == pathval());
12642 if (strstr(path, "%builtin") != NULL)
12643 act |= DO_ALTBLTIN;
12646 /* If name is in the table, check answer will be ok */
12647 cmdp = cmdlookup(name, 0);
12648 if (cmdp != NULL) {
12651 switch (cmdp->cmdtype) {
12669 } else if (cmdp->rehash == 0)
12670 /* if not invalidated by cd, we're done */
12674 /* If %builtin not in path, check for builtin next */
12675 bcmd = find_builtin(name);
12677 if (IS_BUILTIN_REGULAR(bcmd))
12678 goto builtin_success;
12679 if (act & DO_ALTPATH) {
12680 if (!(act & DO_ALTBLTIN))
12681 goto builtin_success;
12682 } else if (builtinloc <= 0) {
12683 goto builtin_success;
12687 #if ENABLE_FEATURE_SH_STANDALONE
12689 int applet_no = find_applet_by_name(name);
12690 if (applet_no >= 0) {
12691 entry->cmdtype = CMDNORMAL;
12692 entry->u.index = -2 - applet_no;
12698 /* We have to search path. */
12699 prev = -1; /* where to start */
12700 if (cmdp && cmdp->rehash) { /* doing a rehash */
12701 if (cmdp->cmdtype == CMDBUILTIN)
12704 prev = cmdp->param.index;
12710 while ((fullname = path_advance(&path, name)) != NULL) {
12711 stunalloc(fullname);
12712 /* NB: code below will still use fullname
12713 * despite it being "unallocated" */
12716 if (prefix(pathopt, "builtin")) {
12718 goto builtin_success;
12721 if ((act & DO_NOFUNC)
12722 || !prefix(pathopt, "func")
12723 ) { /* ignore unimplemented options */
12727 /* if rehash, don't redo absolute path names */
12728 if (fullname[0] == '/' && idx <= prev) {
12731 TRACE(("searchexec \"%s\": no change\n", name));
12734 while (stat(fullname, &statb) < 0) {
12736 if (errno == EINTR)
12739 if (errno != ENOENT && errno != ENOTDIR)
12743 e = EACCES; /* if we fail, this will be the error */
12744 if (!S_ISREG(statb.st_mode))
12746 if (pathopt) { /* this is a %func directory */
12747 stalloc(strlen(fullname) + 1);
12748 /* NB: stalloc will return space pointed by fullname
12749 * (because we don't have any intervening allocations
12750 * between stunalloc above and this stalloc) */
12751 readcmdfile(fullname);
12752 cmdp = cmdlookup(name, 0);
12753 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12754 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12755 stunalloc(fullname);
12758 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12760 entry->cmdtype = CMDNORMAL;
12761 entry->u.index = idx;
12765 cmdp = cmdlookup(name, 1);
12766 cmdp->cmdtype = CMDNORMAL;
12767 cmdp->param.index = idx;
12772 /* We failed. If there was an entry for this command, delete it */
12773 if (cmdp && updatetbl)
12774 delete_cmd_entry();
12776 ash_msg("%s: %s", name, errmsg(e, "not found"));
12777 entry->cmdtype = CMDUNKNOWN;
12782 entry->cmdtype = CMDBUILTIN;
12783 entry->u.cmd = bcmd;
12787 cmdp = cmdlookup(name, 1);
12788 cmdp->cmdtype = CMDBUILTIN;
12789 cmdp->param.cmd = bcmd;
12793 entry->cmdtype = cmdp->cmdtype;
12794 entry->u = cmdp->param;
12799 * The trap builtin.
12801 static int FAST_FUNC
12802 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12806 int signo, exitcode;
12811 for (signo = 0; signo < NSIG; signo++) {
12812 char *tr = trap_ptr[signo];
12814 /* note: bash adds "SIG", but only if invoked
12815 * as "bash". If called as "sh", or if set -o posix,
12816 * then it prints short signal names.
12817 * We are printing short names: */
12818 out1fmt("trap -- %s %s\n",
12820 get_signame(signo));
12821 /* trap_ptr != trap only if we are in special-cased `trap` code.
12822 * In this case, we will exit very soon, no need to free(). */
12823 /* if (trap_ptr != trap && tp[0]) */
12828 if (trap_ptr != trap) {
12841 signo = get_signum(*ap);
12843 /* Mimic bash message exactly */
12844 ash_msg("%s: invalid signal specification", *ap);
12850 if (LONE_DASH(action))
12853 if (action[0]) /* not NULL and not "" and not "-" */
12854 may_have_traps = 1;
12855 action = ckstrdup(action);
12859 trap[signo] = action;
12870 /* ============ Builtins */
12872 #if ENABLE_ASH_HELP
12873 static int FAST_FUNC
12874 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12880 "Built-in commands:\n"
12881 "------------------\n");
12882 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12883 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12884 builtintab[i].name + 1);
12890 # if ENABLE_FEATURE_SH_STANDALONE
12892 const char *a = applet_names;
12894 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12899 while (*a++ != '\0')
12904 newline_and_flush(stdout);
12905 return EXIT_SUCCESS;
12910 static int FAST_FUNC
12911 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12913 show_history(line_input_state);
12914 return EXIT_SUCCESS;
12919 * The export and readonly commands.
12921 static int FAST_FUNC
12922 exportcmd(int argc UNUSED_PARAM, char **argv)
12932 /* "readonly" in bash accepts, but ignores -n.
12933 * We do the same: it saves a conditional in nextopt's param.
12936 while ((opt = nextopt("np")) != '\0') {
12938 flag_off = VEXPORT;
12941 if (argv[0][0] == 'r') {
12943 flag_off = 0; /* readonly ignores -n */
12945 flag_off = ~flag_off;
12947 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12953 p = strchr(name, '=');
12957 vp = *findvar(hashvar(name), name);
12959 vp->flags = ((vp->flags | flag) & flag_off);
12963 setvar(name, p, (flag & flag_off));
12964 } while ((name = *++aptr) != NULL);
12969 /* No arguments. Show the list of exported or readonly vars.
12972 showvars(argv[0], flag, 0);
12977 * Delete a function if it exists.
12980 unsetfunc(const char *name)
12982 struct tblentry *cmdp;
12984 cmdp = cmdlookup(name, 0);
12985 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12986 delete_cmd_entry();
12990 * The unset builtin command. We unset the function before we unset the
12991 * variable to allow a function to be unset when there is a readonly variable
12992 * with the same name.
12994 static int FAST_FUNC
12995 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13002 while ((i = nextopt("vf")) != 0) {
13006 for (ap = argptr; *ap; ap++) {
13019 static const unsigned char timescmd_str[] ALIGN1 = {
13020 ' ', offsetof(struct tms, tms_utime),
13021 '\n', offsetof(struct tms, tms_stime),
13022 ' ', offsetof(struct tms, tms_cutime),
13023 '\n', offsetof(struct tms, tms_cstime),
13026 static int FAST_FUNC
13027 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13029 unsigned long clk_tck, s, t;
13030 const unsigned char *p;
13033 clk_tck = bb_clk_tck();
13038 t = *(clock_t *)(((char *) &buf) + p[1]);
13041 out1fmt("%lum%lu.%03lus%c",
13043 (t * 1000) / clk_tck,
13051 #if ENABLE_SH_MATH_SUPPORT
13053 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13054 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13056 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13058 static int FAST_FUNC
13059 letcmd(int argc UNUSED_PARAM, char **argv)
13065 ash_msg_and_raise_error("expression expected");
13067 i = ash_arith(*argv);
13075 * The read builtin. Options:
13076 * -r Do not interpret '\' specially
13077 * -s Turn off echo (tty only)
13078 * -n NCHARS Read NCHARS max
13079 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13080 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13081 * -u FD Read from given FD instead of fd 0
13082 * This uses unbuffered input, which may be avoidable in some cases.
13083 * TODO: bash also has:
13084 * -a ARRAY Read into array[0],[1],etc
13085 * -d DELIM End on DELIM char, not newline
13086 * -e Use line editing (tty only)
13088 static int FAST_FUNC
13089 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13091 char *opt_n = NULL;
13092 char *opt_p = NULL;
13093 char *opt_t = NULL;
13094 char *opt_u = NULL;
13095 int read_flags = 0;
13099 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13108 read_flags |= BUILTIN_READ_SILENT;
13114 read_flags |= BUILTIN_READ_RAW;
13124 /* "read -s" needs to save/restore termios, can't allow ^C
13125 * to jump out of it.
13128 r = shell_builtin_read(setvar0,
13130 bltinlookup("IFS"), /* can be NULL */
13139 if ((uintptr_t)r > 1)
13140 ash_msg_and_raise_error(r);
13142 return (uintptr_t)r;
13145 static int FAST_FUNC
13146 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13148 static const char permuser[3] ALIGN1 = "ogu";
13151 int symbolic_mode = 0;
13153 while (nextopt("S") != '\0') {
13162 if (*argptr == NULL) {
13163 if (symbolic_mode) {
13164 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13171 *p++ = permuser[i];
13173 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13174 if (!(mask & 0400)) *p++ = 'r';
13175 if (!(mask & 0200)) *p++ = 'w';
13176 if (!(mask & 0100)) *p++ = 'x';
13184 out1fmt("%04o\n", mask);
13187 char *modestr = *argptr;
13188 /* numeric umasks are taken as-is */
13189 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13190 if (!isdigit(modestr[0]))
13192 mask = bb_parse_mode(modestr, mask);
13193 if ((unsigned)mask > 0777) {
13194 ash_msg_and_raise_error("illegal mode: %s", modestr);
13196 if (!isdigit(modestr[0]))
13203 static int FAST_FUNC
13204 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13206 return shell_builtin_ulimit(argv);
13209 /* ============ main() and helpers */
13212 * Called to exit the shell.
13221 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13222 save_history(line_input_state);
13224 status = exitstatus;
13225 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13226 if (setjmp(loc.loc)) {
13227 if (exception_type == EXEXIT)
13228 status = exitstatus;
13231 exception_handler = &loc;
13237 /*free(p); - we'll exit soon */
13240 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13241 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13244 flush_stdout_stderr();
13252 /* we will never free this */
13253 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13255 sigmode[SIGCHLD - 1] = S_DFL;
13256 setsignal(SIGCHLD);
13258 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13259 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13261 signal(SIGHUP, SIG_DFL);
13266 struct stat st1, st2;
13269 for (envp = environ; envp && *envp; envp++) {
13270 p = endofname(*envp);
13271 if (p != *envp && *p == '=') {
13272 setvareq(*envp, VEXPORT|VTEXTFIXED);
13276 setvareq((char*)defoptindvar, VTEXTFIXED);
13278 setvar0("PPID", utoa(getppid()));
13279 #if ENABLE_ASH_BASH_COMPAT
13280 p = lookupvar("SHLVL");
13281 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13282 if (!lookupvar("HOSTNAME")) {
13283 struct utsname uts;
13285 setvar0("HOSTNAME", uts.nodename);
13288 p = lookupvar("PWD");
13290 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13291 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13301 //usage:#define ash_trivial_usage
13302 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13303 //usage:#define ash_full_usage "\n\n"
13304 //usage: "Unix shell interpreter"
13306 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13307 //usage:# define sh_trivial_usage ash_trivial_usage
13308 //usage:# define sh_full_usage ash_full_usage
13310 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13311 //usage:# define bash_trivial_usage ash_trivial_usage
13312 //usage:# define bash_full_usage ash_full_usage
13316 * Process the shell command line arguments.
13319 procargs(char **argv)
13322 const char *xminusc;
13327 /* if (xargv[0]) - mmm, this is always true! */
13329 for (i = 0; i < NOPTS; i++)
13332 if (options(/*cmdline:*/ 1)) {
13333 /* it already printed err message */
13334 raise_exception(EXERROR);
13338 if (*xargv == NULL) {
13340 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13343 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13347 for (i = 0; i < NOPTS; i++)
13348 if (optlist[i] == 2)
13353 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13358 } else if (!sflag) {
13359 setinputfile(*xargv, 0);
13362 commandname = arg0;
13365 shellparam.p = xargv;
13366 #if ENABLE_ASH_GETOPTS
13367 shellparam.optind = 1;
13368 shellparam.optoff = -1;
13370 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13372 shellparam.nparam++;
13379 * Read /etc/profile, ~/.profile, $ENV.
13382 read_profile(const char *name)
13384 name = expandstr(name);
13385 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13392 * This routine is called when an error or an interrupt occurs in an
13393 * interactive shell and control is returned to the main command loop.
13394 * (In dash, this function is auto-generated by build machinery).
13403 /* from expand.c: */
13406 /* from input.c: */
13407 g_parsefile->left_in_buffer = 0;
13408 g_parsefile->left_in_line = 0; /* clear input buffer */
13411 /* from redir.c: */
13413 popredir(/*drop:*/ 0, /*restore:*/ 0);
13417 static short profile_buf[16384];
13418 extern int etext();
13422 * Main routine. We initialize things, parse the arguments, execute
13423 * profiles if we're a login shell, and then call cmdloop to execute
13424 * commands. The setjmp call sets up the location to jump to when an
13425 * exception occurs. When an exception occurs the variable "state"
13426 * is used to figure out how far we had gotten.
13428 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13429 int ash_main(int argc UNUSED_PARAM, char **argv)
13431 volatile smallint state;
13432 struct jmploc jmploc;
13433 struct stackmark smark;
13435 /* Initialize global data */
13439 #if ENABLE_ASH_ALIAS
13445 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13448 #if ENABLE_FEATURE_EDITING
13449 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13452 if (setjmp(jmploc.loc)) {
13458 e = exception_type;
13460 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13464 newline_and_flush(stderr);
13467 popstackmark(&smark);
13468 FORCE_INT_ON; /* enable interrupts */
13477 exception_handler = &jmploc;
13478 rootpid = getpid();
13481 setstackmark(&smark);
13484 TRACE(("Shell args: "));
13485 trace_puts_args(argv);
13488 if (argv[0] && argv[0][0] == '-')
13494 read_profile("/etc/profile");
13497 hp = lookupvar("HOME");
13499 read_profile("$HOME/.profile");
13505 getuid() == geteuid() && getgid() == getegid() &&
13509 const char *shinit = lookupvar("ENV");
13510 if (shinit != NULL && *shinit != '\0')
13511 read_profile(shinit);
13513 popstackmark(&smark);
13517 /* evalstring pushes parsefile stack.
13518 * Ensure we don't falsely claim that 0 (stdin)
13519 * is one of stacked source fds.
13520 * Testcase: ash -c 'exec 1>&0' must not complain. */
13521 // if (!sflag) g_parsefile->pf_fd = -1;
13522 // ^^ not necessary since now we special-case fd 0
13523 // in is_hidden_fd() to not be considered "hidden fd"
13524 evalstring(minusc, 0);
13527 if (sflag || minusc == NULL) {
13528 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13530 const char *hp = lookupvar("HISTFILE");
13532 hp = lookupvar("HOME");
13534 hp = concat_path_file(hp, ".ash_history");
13535 setvar0("HISTFILE", hp);
13537 hp = lookupvar("HISTFILE");
13541 line_input_state->hist_file = hp;
13542 # if ENABLE_FEATURE_SH_HISTFILESIZE
13543 hp = lookupvar("HISTFILESIZE");
13544 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13548 state4: /* XXX ??? - why isn't this before the "if" statement */
13556 extern void _mcleanup(void);
13560 TRACE(("End of main reached\n"));
13567 * Copyright (c) 1989, 1991, 1993, 1994
13568 * The Regents of the University of California. All rights reserved.
13570 * This code is derived from software contributed to Berkeley by
13571 * Kenneth Almquist.
13573 * Redistribution and use in source and binary forms, with or without
13574 * modification, are permitted provided that the following conditions
13576 * 1. Redistributions of source code must retain the above copyright
13577 * notice, this list of conditions and the following disclaimer.
13578 * 2. Redistributions in binary form must reproduce the above copyright
13579 * notice, this list of conditions and the following disclaimer in the
13580 * documentation and/or other materials provided with the distribution.
13581 * 3. Neither the name of the University nor the names of its contributors
13582 * may be used to endorse or promote products derived from this software
13583 * without specific prior written permission.
13585 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13586 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13587 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13588 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13589 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13590 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13591 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13592 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13593 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13594 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF