ash: [REDIR] Move null redirect checks into caller
[oweals/busybox.git] / shell / ash.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * ash shell port for busybox
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Original BSD copyright notice is retained at the end of this file.
9  *
10  * Copyright (c) 1989, 1991, 1993, 1994
11  *      The Regents of the University of California.  All rights reserved.
12  *
13  * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14  * was re-ported from NetBSD and debianized.
15  *
16  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
17  */
18
19 /*
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.
25  *
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.
29  */
30 #define DEBUG 0
31 /* Tweak debug output verbosity here */
32 #define DEBUG_TIME 0
33 #define DEBUG_PID 1
34 #define DEBUG_SIG 1
35
36 #define PROFILE 0
37
38 #define JOBS ENABLE_ASH_JOB_CONTROL
39
40 #include <setjmp.h>
41 #include <fnmatch.h>
42 #include <sys/times.h>
43 #include <sys/utsname.h> /* for setting $HOSTNAME */
44
45 #include "busybox.h" /* for applet_names */
46
47 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
48 /* Bionic at least up to version 24 has no glob() */
49 # undef  ENABLE_ASH_INTERNAL_GLOB
50 # define ENABLE_ASH_INTERNAL_GLOB 1
51 #endif
52
53 #if !ENABLE_ASH_INTERNAL_GLOB
54 # include <glob.h>
55 #endif
56
57 #include "unicode.h"
58 #include "shell_common.h"
59 #if ENABLE_SH_MATH_SUPPORT
60 # include "math.h"
61 #endif
62 #if ENABLE_ASH_RANDOM_SUPPORT
63 # include "random.h"
64 #else
65 # define CLEAR_RANDOM_T(rnd) ((void)0)
66 #endif
67
68 #include "NUM_APPLETS.h"
69 #if NUM_APPLETS == 1
70 /* STANDALONE does not make sense, and won't compile */
71 # undef CONFIG_FEATURE_SH_STANDALONE
72 # undef ENABLE_FEATURE_SH_STANDALONE
73 # undef IF_FEATURE_SH_STANDALONE
74 # undef IF_NOT_FEATURE_SH_STANDALONE
75 # define ENABLE_FEATURE_SH_STANDALONE 0
76 # define IF_FEATURE_SH_STANDALONE(...)
77 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
78 #endif
79
80 #ifndef PIPE_BUF
81 # define PIPE_BUF 4096           /* amount of buffering in a pipe */
82 #endif
83
84 #if !BB_MMU
85 # error "Do not even bother, ash will not run on NOMMU machine"
86 #endif
87
88 //config:config ASH
89 //config:       bool "ash"
90 //config:       default y
91 //config:       depends on !NOMMU
92 //config:       help
93 //config:         Tha 'ash' shell adds about 60k in the default configuration and is
94 //config:         the most complete and most pedantically correct shell included with
95 //config:         busybox. This shell is actually a derivative of the Debian 'dash'
96 //config:         shell (by Herbert Xu), which was created by porting the 'ash' shell
97 //config:         (written by Kenneth Almquist) from NetBSD.
98 //config:
99 //config:config ASH_OPTIMIZE_FOR_SIZE
100 //config:       bool "Optimize for size instead of speed"
101 //config:       default y
102 //config:       depends on ASH
103 //config:       help
104 //config:         Compile ash for reduced size at the price of speed.
105 //config:
106 //config:config ASH_INTERNAL_GLOB
107 //config:       bool "Use internal glob() implementation"
108 //config:       default n
109 //config:       depends on ASH
110 //config:       help
111 //config:         Do not use glob() function from libc, use internal implementation.
112 //config:         Use this if you are getting "glob.h: No such file or directory"
113 //config:         or similar build errors.
114 //config:
115 //config:config ASH_RANDOM_SUPPORT
116 //config:       bool "Pseudorandom generator and $RANDOM variable"
117 //config:       default y
118 //config:       depends on ASH
119 //config:       help
120 //config:         Enable pseudorandom generator and dynamic variable "$RANDOM".
121 //config:         Each read of "$RANDOM" will generate a new pseudorandom value.
122 //config:         You can reset the generator by using a specified start value.
123 //config:         After "unset RANDOM" the generator will switch off and this
124 //config:         variable will no longer have special treatment.
125 //config:
126 //config:config ASH_EXPAND_PRMT
127 //config:       bool "Expand prompt string"
128 //config:       default y
129 //config:       depends on ASH
130 //config:       help
131 //config:         "PS#" may contain volatile content, such as backquote commands.
132 //config:         This option recreates the prompt string from the environment
133 //config:         variable each time it is displayed.
134 //config:
135 //config:config ASH_BASH_COMPAT
136 //config:       bool "bash-compatible extensions"
137 //config:       default y
138 //config:       depends on ASH
139 //config:       help
140 //config:         Enable bash-compatible extensions.
141 //config:
142 //config:config ASH_IDLE_TIMEOUT
143 //config:       bool "Idle timeout variable"
144 //config:       default n
145 //config:       depends on ASH
146 //config:       help
147 //config:         Enables bash-like auto-logout after $TMOUT seconds of idle time.
148 //config:
149 //config:config ASH_JOB_CONTROL
150 //config:       bool "Job control"
151 //config:       default y
152 //config:       depends on ASH
153 //config:       help
154 //config:         Enable job control in the ash shell.
155 //config:
156 //config:config ASH_ALIAS
157 //config:       bool "Alias support"
158 //config:       default y
159 //config:       depends on ASH
160 //config:       help
161 //config:         Enable alias support in the ash shell.
162 //config:
163 //config:config ASH_GETOPTS
164 //config:       bool "Builtin getopt to parse positional parameters"
165 //config:       default y
166 //config:       depends on ASH
167 //config:       help
168 //config:         Enable support for getopts builtin in ash.
169 //config:
170 //config:config ASH_BUILTIN_ECHO
171 //config:       bool "Builtin version of 'echo'"
172 //config:       default y
173 //config:       depends on ASH
174 //config:       help
175 //config:         Enable support for echo builtin in ash.
176 //config:
177 //config:config ASH_BUILTIN_PRINTF
178 //config:       bool "Builtin version of 'printf'"
179 //config:       default y
180 //config:       depends on ASH
181 //config:       help
182 //config:         Enable support for printf builtin in ash.
183 //config:
184 //config:config ASH_BUILTIN_TEST
185 //config:       bool "Builtin version of 'test'"
186 //config:       default y
187 //config:       depends on ASH
188 //config:       help
189 //config:         Enable support for test builtin in ash.
190 //config:
191 //config:config ASH_HELP
192 //config:       bool "help builtin"
193 //config:       default y
194 //config:       depends on ASH
195 //config:       help
196 //config:         Enable help builtin in ash.
197 //config:
198 //config:config ASH_CMDCMD
199 //config:       bool "'command' command to override shell builtins"
200 //config:       default y
201 //config:       depends on ASH
202 //config:       help
203 //config:         Enable support for the ash 'command' builtin, which allows
204 //config:         you to run the specified command with the specified arguments,
205 //config:         even when there is an ash builtin command with the same name.
206 //config:
207 //config:config ASH_MAIL
208 //config:       bool "Check for new mail on interactive shells"
209 //config:       default n
210 //config:       depends on ASH
211 //config:       help
212 //config:         Enable "check for new mail" function in the ash shell.
213 //config:
214
215 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
216 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
217 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
218
219 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
220 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
221
222
223 /* ============ Hash table sizes. Configurable. */
224
225 #define VTABSIZE 39
226 #define ATABSIZE 39
227 #define CMDTABLESIZE 31         /* should be prime */
228
229
230 /* ============ Shell options */
231
232 static const char *const optletters_optnames[] = {
233         "e"   "errexit",
234         "f"   "noglob",
235         "I"   "ignoreeof",
236         "i"   "interactive",
237         "m"   "monitor",
238         "n"   "noexec",
239         "s"   "stdin",
240         "x"   "xtrace",
241         "v"   "verbose",
242         "C"   "noclobber",
243         "a"   "allexport",
244         "b"   "notify",
245         "u"   "nounset",
246         "\0"  "vi"
247 #if ENABLE_ASH_BASH_COMPAT
248         ,"\0"  "pipefail"
249 #endif
250 #if DEBUG
251         ,"\0"  "nolog"
252         ,"\0"  "debug"
253 #endif
254 };
255
256 #define optletters(n)  optletters_optnames[n][0]
257 #define optnames(n)   (optletters_optnames[n] + 1)
258
259 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
260
261
262 /* ============ Misc data */
263
264 #define msg_illnum "Illegal number: %s"
265
266 /*
267  * We enclose jmp_buf in a structure so that we can declare pointers to
268  * jump locations.  The global variable handler contains the location to
269  * jump to when an exception occurs, and the global variable exception_type
270  * contains a code identifying the exception.  To implement nested
271  * exception handlers, the user should save the value of handler on entry
272  * to an inner scope, set handler to point to a jmploc structure for the
273  * inner scope, and restore handler on exit from the scope.
274  */
275 struct jmploc {
276         jmp_buf loc;
277 };
278
279 struct globals_misc {
280         uint8_t exitstatus;     /* exit status of last command */
281         uint8_t back_exitstatus;/* exit status of backquoted command */
282         smallint job_warning;   /* user was warned about stopped jobs (can be 2, 1 or 0). */
283         int rootpid;            /* pid of main shell */
284         /* shell level: 0 for the main shell, 1 for its children, and so on */
285         int shlvl;
286 #define rootshell (!shlvl)
287         char *minusc;  /* argument to -c option */
288
289         char *curdir; // = nullstr;     /* current working directory */
290         char *physdir; // = nullstr;    /* physical working directory */
291
292         char *arg0; /* value of $0 */
293
294         struct jmploc *exception_handler;
295
296         volatile int suppress_int; /* counter */
297         volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
298         /* last pending signal */
299         volatile /*sig_atomic_t*/ smallint pending_sig;
300         smallint exception_type; /* kind of exception (0..5) */
301         /* exceptions */
302 #define EXINT 0         /* SIGINT received */
303 #define EXERROR 1       /* a generic error */
304 #define EXEXIT 4        /* exit the shell */
305 #define EXSIG 5         /* trapped signal in wait(1) */
306
307         smallint isloginsh;
308         char nullstr[1];        /* zero length string */
309
310         char optlist[NOPTS];
311 #define eflag optlist[0]
312 #define fflag optlist[1]
313 #define Iflag optlist[2]
314 #define iflag optlist[3]
315 #define mflag optlist[4]
316 #define nflag optlist[5]
317 #define sflag optlist[6]
318 #define xflag optlist[7]
319 #define vflag optlist[8]
320 #define Cflag optlist[9]
321 #define aflag optlist[10]
322 #define bflag optlist[11]
323 #define uflag optlist[12]
324 #define viflag optlist[13]
325 #if ENABLE_ASH_BASH_COMPAT
326 # define pipefail optlist[14]
327 #else
328 # define pipefail 0
329 #endif
330 #if DEBUG
331 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
332 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
333 #endif
334
335         /* trap handler commands */
336         /*
337          * Sigmode records the current value of the signal handlers for the various
338          * modes.  A value of zero means that the current handler is not known.
339          * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
340          */
341         char sigmode[NSIG - 1];
342 #define S_DFL      1            /* default signal handling (SIG_DFL) */
343 #define S_CATCH    2            /* signal is caught */
344 #define S_IGN      3            /* signal is ignored (SIG_IGN) */
345 #define S_HARD_IGN 4            /* signal is ignored permanently */
346
347         /* indicates specified signal received */
348         uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
349         uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
350         char *trap[NSIG];
351         char **trap_ptr;        /* used only by "trap hack" */
352
353         /* Rarely referenced stuff */
354 #if ENABLE_ASH_RANDOM_SUPPORT
355         random_t random_gen;
356 #endif
357         pid_t backgndpid;        /* pid of last background process */
358 };
359 extern struct globals_misc *const ash_ptr_to_globals_misc;
360 #define G_misc (*ash_ptr_to_globals_misc)
361 #define exitstatus        (G_misc.exitstatus )
362 #define back_exitstatus   (G_misc.back_exitstatus )
363 #define job_warning       (G_misc.job_warning)
364 #define rootpid     (G_misc.rootpid    )
365 #define shlvl       (G_misc.shlvl      )
366 #define minusc      (G_misc.minusc     )
367 #define curdir      (G_misc.curdir     )
368 #define physdir     (G_misc.physdir    )
369 #define arg0        (G_misc.arg0       )
370 #define exception_handler (G_misc.exception_handler)
371 #define exception_type    (G_misc.exception_type   )
372 #define suppress_int      (G_misc.suppress_int     )
373 #define pending_int       (G_misc.pending_int      )
374 #define pending_sig       (G_misc.pending_sig      )
375 #define isloginsh   (G_misc.isloginsh  )
376 #define nullstr     (G_misc.nullstr    )
377 #define optlist     (G_misc.optlist    )
378 #define sigmode     (G_misc.sigmode    )
379 #define gotsig      (G_misc.gotsig     )
380 #define may_have_traps    (G_misc.may_have_traps   )
381 #define trap        (G_misc.trap       )
382 #define trap_ptr    (G_misc.trap_ptr   )
383 #define random_gen  (G_misc.random_gen )
384 #define backgndpid  (G_misc.backgndpid )
385 #define INIT_G_misc() do { \
386         (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
387         barrier(); \
388         curdir = nullstr; \
389         physdir = nullstr; \
390         trap_ptr = trap; \
391 } while (0)
392
393
394 /* ============ DEBUG */
395 #if DEBUG
396 static void trace_printf(const char *fmt, ...);
397 static void trace_vprintf(const char *fmt, va_list va);
398 # define TRACE(param)    trace_printf param
399 # define TRACEV(param)   trace_vprintf param
400 # define close(fd) do { \
401         int dfd = (fd); \
402         if (close(dfd) < 0) \
403                 bb_error_msg("bug on %d: closing %d(0x%x)", \
404                         __LINE__, dfd, dfd); \
405 } while (0)
406 #else
407 # define TRACE(param)
408 # define TRACEV(param)
409 #endif
410
411
412 /* ============ Utility functions */
413 #define is_name(c)      ((c) == '_' || isalpha((unsigned char)(c)))
414 #define is_in_name(c)   ((c) == '_' || isalnum((unsigned char)(c)))
415
416 static int
417 isdigit_str9(const char *str)
418 {
419         int maxlen = 9 + 1; /* max 9 digits: 999999999 */
420         while (--maxlen && isdigit(*str))
421                 str++;
422         return (*str == '\0');
423 }
424
425 static const char *
426 var_end(const char *var)
427 {
428         while (*var)
429                 if (*var++ == '=')
430                         break;
431         return var;
432 }
433
434
435 /* ============ Interrupts / exceptions */
436
437 static void exitshell(void) NORETURN;
438
439 /*
440  * These macros allow the user to suspend the handling of interrupt signals
441  * over a period of time.  This is similar to SIGHOLD or to sigblock, but
442  * much more efficient and portable.  (But hacking the kernel is so much
443  * more fun than worrying about efficiency and portability. :-))
444  */
445 #define INT_OFF do { \
446         suppress_int++; \
447         barrier(); \
448 } while (0)
449
450 /*
451  * Called to raise an exception.  Since C doesn't include exceptions, we
452  * just do a longjmp to the exception handler.  The type of exception is
453  * stored in the global variable "exception_type".
454  */
455 static void raise_exception(int) NORETURN;
456 static void
457 raise_exception(int e)
458 {
459 #if DEBUG
460         if (exception_handler == NULL)
461                 abort();
462 #endif
463         INT_OFF;
464         exception_type = e;
465         longjmp(exception_handler->loc, 1);
466 }
467 #if DEBUG
468 #define raise_exception(e) do { \
469         TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
470         raise_exception(e); \
471 } while (0)
472 #endif
473
474 /*
475  * Called when a SIGINT is received.  (If the user specifies
476  * that SIGINT is to be trapped or ignored using the trap builtin, then
477  * this routine is not called.)  Suppressint is nonzero when interrupts
478  * are held using the INT_OFF macro.  (The test for iflag is just
479  * defensive programming.)
480  */
481 static void raise_interrupt(void) NORETURN;
482 static void
483 raise_interrupt(void)
484 {
485         int ex_type;
486
487         pending_int = 0;
488         /* Signal is not automatically unmasked after it is raised,
489          * do it ourself - unmask all signals */
490         sigprocmask_allsigs(SIG_UNBLOCK);
491         /* pending_sig = 0; - now done in signal_handler() */
492
493         ex_type = EXSIG;
494         if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
495                 if (!(rootshell && iflag)) {
496                         /* Kill ourself with SIGINT */
497                         signal(SIGINT, SIG_DFL);
498                         raise(SIGINT);
499                 }
500                 ex_type = EXINT;
501         }
502         /* bash: ^C even on empty command line sets $? */
503         exitstatus = SIGINT + 128;
504         raise_exception(ex_type);
505         /* NOTREACHED */
506 }
507 #if DEBUG
508 #define raise_interrupt() do { \
509         TRACE(("raising interrupt on line %d\n", __LINE__)); \
510         raise_interrupt(); \
511 } while (0)
512 #endif
513
514 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
515 int_on(void)
516 {
517         barrier();
518         if (--suppress_int == 0 && pending_int) {
519                 raise_interrupt();
520         }
521 }
522 #define INT_ON int_on()
523 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
524 force_int_on(void)
525 {
526         barrier();
527         suppress_int = 0;
528         if (pending_int)
529                 raise_interrupt();
530 }
531 #define FORCE_INT_ON force_int_on()
532
533 #define SAVE_INT(v) ((v) = suppress_int)
534
535 #define RESTORE_INT(v) do { \
536         barrier(); \
537         suppress_int = (v); \
538         if (suppress_int == 0 && pending_int) \
539                 raise_interrupt(); \
540 } while (0)
541
542
543 /* ============ Stdout/stderr output */
544
545 static void
546 outstr(const char *p, FILE *file)
547 {
548         INT_OFF;
549         fputs(p, file);
550         INT_ON;
551 }
552
553 static void
554 flush_stdout_stderr(void)
555 {
556         INT_OFF;
557         fflush_all();
558         INT_ON;
559 }
560
561 /* Was called outcslow(c,FILE*), but c was always '\n' */
562 static void
563 newline_and_flush(FILE *dest)
564 {
565         INT_OFF;
566         putc('\n', dest);
567         fflush(dest);
568         INT_ON;
569 }
570
571 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
572 static int
573 out1fmt(const char *fmt, ...)
574 {
575         va_list ap;
576         int r;
577
578         INT_OFF;
579         va_start(ap, fmt);
580         r = vprintf(fmt, ap);
581         va_end(ap);
582         INT_ON;
583         return r;
584 }
585
586 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
587 static int
588 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
589 {
590         va_list ap;
591         int ret;
592
593         va_start(ap, fmt);
594         INT_OFF;
595         ret = vsnprintf(outbuf, length, fmt, ap);
596         va_end(ap);
597         INT_ON;
598         return ret;
599 }
600
601 static void
602 out1str(const char *p)
603 {
604         outstr(p, stdout);
605 }
606
607 static void
608 out2str(const char *p)
609 {
610         outstr(p, stderr);
611         flush_stdout_stderr();
612 }
613
614
615 /* ============ Parser structures */
616
617 /* control characters in argument strings */
618 #define CTL_FIRST CTLESC
619 #define CTLESC       ((unsigned char)'\201')    /* escape next character */
620 #define CTLVAR       ((unsigned char)'\202')    /* variable defn */
621 #define CTLENDVAR    ((unsigned char)'\203')
622 #define CTLBACKQ     ((unsigned char)'\204')
623 #define CTLARI       ((unsigned char)'\206')    /* arithmetic expression */
624 #define CTLENDARI    ((unsigned char)'\207')
625 #define CTLQUOTEMARK ((unsigned char)'\210')
626 #define CTL_LAST CTLQUOTEMARK
627
628 /* variable substitution byte (follows CTLVAR) */
629 #define VSTYPE  0x0f            /* type of variable substitution */
630 #define VSNUL   0x10            /* colon--treat the empty string as unset */
631
632 /* values of VSTYPE field */
633 #define VSNORMAL        0x1     /* normal variable:  $var or ${var} */
634 #define VSMINUS         0x2     /* ${var-text} */
635 #define VSPLUS          0x3     /* ${var+text} */
636 #define VSQUESTION      0x4     /* ${var?message} */
637 #define VSASSIGN        0x5     /* ${var=text} */
638 #define VSTRIMRIGHT     0x6     /* ${var%pattern} */
639 #define VSTRIMRIGHTMAX  0x7     /* ${var%%pattern} */
640 #define VSTRIMLEFT      0x8     /* ${var#pattern} */
641 #define VSTRIMLEFTMAX   0x9     /* ${var##pattern} */
642 #define VSLENGTH        0xa     /* ${#var} */
643 #if ENABLE_ASH_BASH_COMPAT
644 #define VSSUBSTR        0xc     /* ${var:position:length} */
645 #define VSREPLACE       0xd     /* ${var/pattern/replacement} */
646 #define VSREPLACEALL    0xe     /* ${var//pattern/replacement} */
647 #endif
648
649 static const char dolatstr[] ALIGN1 = {
650         CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
651 };
652 #define DOLATSTRLEN 6
653
654 #define NCMD      0
655 #define NPIPE     1
656 #define NREDIR    2
657 #define NBACKGND  3
658 #define NSUBSHELL 4
659 #define NAND      5
660 #define NOR       6
661 #define NSEMI     7
662 #define NIF       8
663 #define NWHILE    9
664 #define NUNTIL   10
665 #define NFOR     11
666 #define NCASE    12
667 #define NCLIST   13
668 #define NDEFUN   14
669 #define NARG     15
670 #define NTO      16
671 #if ENABLE_ASH_BASH_COMPAT
672 #define NTO2     17
673 #endif
674 #define NCLOBBER 18
675 #define NFROM    19
676 #define NFROMTO  20
677 #define NAPPEND  21
678 #define NTOFD    22
679 #define NFROMFD  23
680 #define NHERE    24
681 #define NXHERE   25
682 #define NNOT     26
683 #define N_NUMBER 27
684
685 union node;
686
687 struct ncmd {
688         smallint type; /* Nxxxx */
689         union node *assign;
690         union node *args;
691         union node *redirect;
692 };
693
694 struct npipe {
695         smallint type;
696         smallint pipe_backgnd;
697         struct nodelist *cmdlist;
698 };
699
700 struct nredir {
701         smallint type;
702         union node *n;
703         union node *redirect;
704 };
705
706 struct nbinary {
707         smallint type;
708         union node *ch1;
709         union node *ch2;
710 };
711
712 struct nif {
713         smallint type;
714         union node *test;
715         union node *ifpart;
716         union node *elsepart;
717 };
718
719 struct nfor {
720         smallint type;
721         union node *args;
722         union node *body;
723         char *var;
724 };
725
726 struct ncase {
727         smallint type;
728         union node *expr;
729         union node *cases;
730 };
731
732 struct nclist {
733         smallint type;
734         union node *next;
735         union node *pattern;
736         union node *body;
737 };
738
739 struct narg {
740         smallint type;
741         union node *next;
742         char *text;
743         struct nodelist *backquote;
744 };
745
746 /* nfile and ndup layout must match!
747  * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
748  * that it is actually NTO2 (>&file), and change its type.
749  */
750 struct nfile {
751         smallint type;
752         union node *next;
753         int fd;
754         int _unused_dupfd;
755         union node *fname;
756         char *expfname;
757 };
758
759 struct ndup {
760         smallint type;
761         union node *next;
762         int fd;
763         int dupfd;
764         union node *vname;
765         char *_unused_expfname;
766 };
767
768 struct nhere {
769         smallint type;
770         union node *next;
771         int fd;
772         union node *doc;
773 };
774
775 struct nnot {
776         smallint type;
777         union node *com;
778 };
779
780 union node {
781         smallint type;
782         struct ncmd ncmd;
783         struct npipe npipe;
784         struct nredir nredir;
785         struct nbinary nbinary;
786         struct nif nif;
787         struct nfor nfor;
788         struct ncase ncase;
789         struct nclist nclist;
790         struct narg narg;
791         struct nfile nfile;
792         struct ndup ndup;
793         struct nhere nhere;
794         struct nnot nnot;
795 };
796
797 /*
798  * NODE_EOF is returned by parsecmd when it encounters an end of file.
799  * It must be distinct from NULL.
800  */
801 #define NODE_EOF ((union node *) -1L)
802
803 struct nodelist {
804         struct nodelist *next;
805         union node *n;
806 };
807
808 struct funcnode {
809         int count;
810         union node n;
811 };
812
813 /*
814  * Free a parse tree.
815  */
816 static void
817 freefunc(struct funcnode *f)
818 {
819         if (f && --f->count < 0)
820                 free(f);
821 }
822
823
824 /* ============ Debugging output */
825
826 #if DEBUG
827
828 static FILE *tracefile;
829
830 static void
831 trace_printf(const char *fmt, ...)
832 {
833         va_list va;
834
835         if (debug != 1)
836                 return;
837         if (DEBUG_TIME)
838                 fprintf(tracefile, "%u ", (int) time(NULL));
839         if (DEBUG_PID)
840                 fprintf(tracefile, "[%u] ", (int) getpid());
841         if (DEBUG_SIG)
842                 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
843         va_start(va, fmt);
844         vfprintf(tracefile, fmt, va);
845         va_end(va);
846 }
847
848 static void
849 trace_vprintf(const char *fmt, va_list va)
850 {
851         if (debug != 1)
852                 return;
853         if (DEBUG_TIME)
854                 fprintf(tracefile, "%u ", (int) time(NULL));
855         if (DEBUG_PID)
856                 fprintf(tracefile, "[%u] ", (int) getpid());
857         if (DEBUG_SIG)
858                 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
859         vfprintf(tracefile, fmt, va);
860 }
861
862 static void
863 trace_puts(const char *s)
864 {
865         if (debug != 1)
866                 return;
867         fputs(s, tracefile);
868 }
869
870 static void
871 trace_puts_quoted(char *s)
872 {
873         char *p;
874         char c;
875
876         if (debug != 1)
877                 return;
878         putc('"', tracefile);
879         for (p = s; *p; p++) {
880                 switch ((unsigned char)*p) {
881                 case '\n': c = 'n'; goto backslash;
882                 case '\t': c = 't'; goto backslash;
883                 case '\r': c = 'r'; goto backslash;
884                 case '\"': c = '\"'; goto backslash;
885                 case '\\': c = '\\'; goto backslash;
886                 case CTLESC: c = 'e'; goto backslash;
887                 case CTLVAR: c = 'v'; goto backslash;
888                 case CTLBACKQ: c = 'q'; goto backslash;
889  backslash:
890                         putc('\\', tracefile);
891                         putc(c, tracefile);
892                         break;
893                 default:
894                         if (*p >= ' ' && *p <= '~')
895                                 putc(*p, tracefile);
896                         else {
897                                 putc('\\', tracefile);
898                                 putc((*p >> 6) & 03, tracefile);
899                                 putc((*p >> 3) & 07, tracefile);
900                                 putc(*p & 07, tracefile);
901                         }
902                         break;
903                 }
904         }
905         putc('"', tracefile);
906 }
907
908 static void
909 trace_puts_args(char **ap)
910 {
911         if (debug != 1)
912                 return;
913         if (!*ap)
914                 return;
915         while (1) {
916                 trace_puts_quoted(*ap);
917                 if (!*++ap) {
918                         putc('\n', tracefile);
919                         break;
920                 }
921                 putc(' ', tracefile);
922         }
923 }
924
925 static void
926 opentrace(void)
927 {
928         char s[100];
929 #ifdef O_APPEND
930         int flags;
931 #endif
932
933         if (debug != 1) {
934                 if (tracefile)
935                         fflush(tracefile);
936                 /* leave open because libedit might be using it */
937                 return;
938         }
939         strcpy(s, "./trace");
940         if (tracefile) {
941                 if (!freopen(s, "a", tracefile)) {
942                         fprintf(stderr, "Can't re-open %s\n", s);
943                         debug = 0;
944                         return;
945                 }
946         } else {
947                 tracefile = fopen(s, "a");
948                 if (tracefile == NULL) {
949                         fprintf(stderr, "Can't open %s\n", s);
950                         debug = 0;
951                         return;
952                 }
953         }
954 #ifdef O_APPEND
955         flags = fcntl(fileno(tracefile), F_GETFL);
956         if (flags >= 0)
957                 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
958 #endif
959         setlinebuf(tracefile);
960         fputs("\nTracing started.\n", tracefile);
961 }
962
963 static void
964 indent(int amount, char *pfx, FILE *fp)
965 {
966         int i;
967
968         for (i = 0; i < amount; i++) {
969                 if (pfx && i == amount - 1)
970                         fputs(pfx, fp);
971                 putc('\t', fp);
972         }
973 }
974
975 /* little circular references here... */
976 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
977
978 static void
979 sharg(union node *arg, FILE *fp)
980 {
981         char *p;
982         struct nodelist *bqlist;
983         unsigned char subtype;
984
985         if (arg->type != NARG) {
986                 out1fmt("<node type %d>\n", arg->type);
987                 abort();
988         }
989         bqlist = arg->narg.backquote;
990         for (p = arg->narg.text; *p; p++) {
991                 switch ((unsigned char)*p) {
992                 case CTLESC:
993                         p++;
994                         putc(*p, fp);
995                         break;
996                 case CTLVAR:
997                         putc('$', fp);
998                         putc('{', fp);
999                         subtype = *++p;
1000                         if (subtype == VSLENGTH)
1001                                 putc('#', fp);
1002
1003                         while (*p != '=') {
1004                                 putc(*p, fp);
1005                                 p++;
1006                         }
1007
1008                         if (subtype & VSNUL)
1009                                 putc(':', fp);
1010
1011                         switch (subtype & VSTYPE) {
1012                         case VSNORMAL:
1013                                 putc('}', fp);
1014                                 break;
1015                         case VSMINUS:
1016                                 putc('-', fp);
1017                                 break;
1018                         case VSPLUS:
1019                                 putc('+', fp);
1020                                 break;
1021                         case VSQUESTION:
1022                                 putc('?', fp);
1023                                 break;
1024                         case VSASSIGN:
1025                                 putc('=', fp);
1026                                 break;
1027                         case VSTRIMLEFT:
1028                                 putc('#', fp);
1029                                 break;
1030                         case VSTRIMLEFTMAX:
1031                                 putc('#', fp);
1032                                 putc('#', fp);
1033                                 break;
1034                         case VSTRIMRIGHT:
1035                                 putc('%', fp);
1036                                 break;
1037                         case VSTRIMRIGHTMAX:
1038                                 putc('%', fp);
1039                                 putc('%', fp);
1040                                 break;
1041                         case VSLENGTH:
1042                                 break;
1043                         default:
1044                                 out1fmt("<subtype %d>", subtype);
1045                         }
1046                         break;
1047                 case CTLENDVAR:
1048                         putc('}', fp);
1049                         break;
1050                 case CTLBACKQ:
1051                         putc('$', fp);
1052                         putc('(', fp);
1053                         shtree(bqlist->n, -1, NULL, fp);
1054                         putc(')', fp);
1055                         break;
1056                 default:
1057                         putc(*p, fp);
1058                         break;
1059                 }
1060         }
1061 }
1062
1063 static void
1064 shcmd(union node *cmd, FILE *fp)
1065 {
1066         union node *np;
1067         int first;
1068         const char *s;
1069         int dftfd;
1070
1071         first = 1;
1072         for (np = cmd->ncmd.args; np; np = np->narg.next) {
1073                 if (!first)
1074                         putc(' ', fp);
1075                 sharg(np, fp);
1076                 first = 0;
1077         }
1078         for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1079                 if (!first)
1080                         putc(' ', fp);
1081                 dftfd = 0;
1082                 switch (np->nfile.type) {
1083                 case NTO:      s = ">>"+1; dftfd = 1; break;
1084                 case NCLOBBER: s = ">|"; dftfd = 1; break;
1085                 case NAPPEND:  s = ">>"; dftfd = 1; break;
1086 #if ENABLE_ASH_BASH_COMPAT
1087                 case NTO2:
1088 #endif
1089                 case NTOFD:    s = ">&"; dftfd = 1; break;
1090                 case NFROM:    s = "<"; break;
1091                 case NFROMFD:  s = "<&"; break;
1092                 case NFROMTO:  s = "<>"; break;
1093                 default:       s = "*error*"; break;
1094                 }
1095                 if (np->nfile.fd != dftfd)
1096                         fprintf(fp, "%d", np->nfile.fd);
1097                 fputs(s, fp);
1098                 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1099                         fprintf(fp, "%d", np->ndup.dupfd);
1100                 } else {
1101                         sharg(np->nfile.fname, fp);
1102                 }
1103                 first = 0;
1104         }
1105 }
1106
1107 static void
1108 shtree(union node *n, int ind, char *pfx, FILE *fp)
1109 {
1110         struct nodelist *lp;
1111         const char *s;
1112
1113         if (n == NULL)
1114                 return;
1115
1116         indent(ind, pfx, fp);
1117
1118         if (n == NODE_EOF) {
1119                 fputs("<EOF>", fp);
1120                 return;
1121         }
1122
1123         switch (n->type) {
1124         case NSEMI:
1125                 s = "; ";
1126                 goto binop;
1127         case NAND:
1128                 s = " && ";
1129                 goto binop;
1130         case NOR:
1131                 s = " || ";
1132  binop:
1133                 shtree(n->nbinary.ch1, ind, NULL, fp);
1134                 /* if (ind < 0) */
1135                         fputs(s, fp);
1136                 shtree(n->nbinary.ch2, ind, NULL, fp);
1137                 break;
1138         case NCMD:
1139                 shcmd(n, fp);
1140                 if (ind >= 0)
1141                         putc('\n', fp);
1142                 break;
1143         case NPIPE:
1144                 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1145                         shtree(lp->n, 0, NULL, fp);
1146                         if (lp->next)
1147                                 fputs(" | ", fp);
1148                 }
1149                 if (n->npipe.pipe_backgnd)
1150                         fputs(" &", fp);
1151                 if (ind >= 0)
1152                         putc('\n', fp);
1153                 break;
1154         default:
1155                 fprintf(fp, "<node type %d>", n->type);
1156                 if (ind >= 0)
1157                         putc('\n', fp);
1158                 break;
1159         }
1160 }
1161
1162 static void
1163 showtree(union node *n)
1164 {
1165         trace_puts("showtree called\n");
1166         shtree(n, 1, NULL, stderr);
1167 }
1168
1169 #endif /* DEBUG */
1170
1171
1172 /* ============ Parser data */
1173
1174 /*
1175  * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1176  */
1177 struct strlist {
1178         struct strlist *next;
1179         char *text;
1180 };
1181
1182 struct alias;
1183
1184 struct strpush {
1185         struct strpush *prev;   /* preceding string on stack */
1186         char *prev_string;
1187         int prev_left_in_line;
1188 #if ENABLE_ASH_ALIAS
1189         struct alias *ap;       /* if push was associated with an alias */
1190 #endif
1191         char *string;           /* remember the string since it may change */
1192
1193         /* Remember last two characters for pungetc. */
1194         int lastc[2];
1195
1196         /* Number of outstanding calls to pungetc. */
1197         int unget;
1198 };
1199
1200 struct parsefile {
1201         struct parsefile *prev; /* preceding file on stack */
1202         int linno;              /* current line */
1203         int pf_fd;              /* file descriptor (or -1 if string) */
1204         int left_in_line;       /* number of chars left in this line */
1205         int left_in_buffer;     /* number of chars left in this buffer past the line */
1206         char *next_to_pgetc;    /* next char in buffer */
1207         char *buf;              /* input buffer */
1208         struct strpush *strpush; /* for pushing strings at this level */
1209         struct strpush basestrpush; /* so pushing one is fast */
1210
1211         /* Remember last two characters for pungetc. */
1212         int lastc[2];
1213
1214         /* Number of outstanding calls to pungetc. */
1215         int unget;
1216 };
1217
1218 static struct parsefile basepf;        /* top level input file */
1219 static struct parsefile *g_parsefile = &basepf;  /* current input file */
1220 static int startlinno;                 /* line # where last token started */
1221 static char *commandname;              /* currently executing command */
1222 static struct strlist *cmdenviron;     /* environment for builtin command */
1223
1224
1225 /* ============ Message printing */
1226
1227 static void
1228 ash_vmsg(const char *msg, va_list ap)
1229 {
1230         fprintf(stderr, "%s: ", arg0);
1231         if (commandname) {
1232                 if (strcmp(arg0, commandname))
1233                         fprintf(stderr, "%s: ", commandname);
1234                 if (!iflag || g_parsefile->pf_fd > 0)
1235                         fprintf(stderr, "line %d: ", startlinno);
1236         }
1237         vfprintf(stderr, msg, ap);
1238         newline_and_flush(stderr);
1239 }
1240
1241 /*
1242  * Exverror is called to raise the error exception.  If the second argument
1243  * is not NULL then error prints an error message using printf style
1244  * formatting.  It then raises the error exception.
1245  */
1246 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1247 static void
1248 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1249 {
1250 #if DEBUG
1251         if (msg) {
1252                 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1253                 TRACEV((msg, ap));
1254                 TRACE(("\") pid=%d\n", getpid()));
1255         } else
1256                 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1257         if (msg)
1258 #endif
1259                 ash_vmsg(msg, ap);
1260
1261         flush_stdout_stderr();
1262         raise_exception(cond);
1263         /* NOTREACHED */
1264 }
1265
1266 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1267 static void
1268 ash_msg_and_raise_error(const char *msg, ...)
1269 {
1270         va_list ap;
1271
1272         va_start(ap, msg);
1273         ash_vmsg_and_raise(EXERROR, msg, ap);
1274         /* NOTREACHED */
1275         va_end(ap);
1276 }
1277
1278 static void raise_error_syntax(const char *) NORETURN;
1279 static void
1280 raise_error_syntax(const char *msg)
1281 {
1282         ash_msg_and_raise_error("syntax error: %s", msg);
1283         /* NOTREACHED */
1284 }
1285
1286 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1287 static void
1288 ash_msg_and_raise(int cond, const char *msg, ...)
1289 {
1290         va_list ap;
1291
1292         va_start(ap, msg);
1293         ash_vmsg_and_raise(cond, msg, ap);
1294         /* NOTREACHED */
1295         va_end(ap);
1296 }
1297
1298 /*
1299  * error/warning routines for external builtins
1300  */
1301 static void
1302 ash_msg(const char *fmt, ...)
1303 {
1304         va_list ap;
1305
1306         va_start(ap, fmt);
1307         ash_vmsg(fmt, ap);
1308         va_end(ap);
1309 }
1310
1311 /*
1312  * Return a string describing an error.  The returned string may be a
1313  * pointer to a static buffer that will be overwritten on the next call.
1314  * Action describes the operation that got the error.
1315  */
1316 static const char *
1317 errmsg(int e, const char *em)
1318 {
1319         if (e == ENOENT || e == ENOTDIR) {
1320                 return em;
1321         }
1322         return strerror(e);
1323 }
1324
1325
1326 /* ============ Memory allocation */
1327
1328 #if 0
1329 /* I consider these wrappers nearly useless:
1330  * ok, they return you to nearest exception handler, but
1331  * how much memory do you leak in the process, making
1332  * memory starvation worse?
1333  */
1334 static void *
1335 ckrealloc(void * p, size_t nbytes)
1336 {
1337         p = realloc(p, nbytes);
1338         if (!p)
1339                 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1340         return p;
1341 }
1342
1343 static void *
1344 ckmalloc(size_t nbytes)
1345 {
1346         return ckrealloc(NULL, nbytes);
1347 }
1348
1349 static void *
1350 ckzalloc(size_t nbytes)
1351 {
1352         return memset(ckmalloc(nbytes), 0, nbytes);
1353 }
1354
1355 static char *
1356 ckstrdup(const char *s)
1357 {
1358         char *p = strdup(s);
1359         if (!p)
1360                 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1361         return p;
1362 }
1363 #else
1364 /* Using bbox equivalents. They exit if out of memory */
1365 # define ckrealloc xrealloc
1366 # define ckmalloc  xmalloc
1367 # define ckzalloc  xzalloc
1368 # define ckstrdup  xstrdup
1369 #endif
1370
1371 /*
1372  * It appears that grabstackstr() will barf with such alignments
1373  * because stalloc() will return a string allocated in a new stackblock.
1374  */
1375 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1376 enum {
1377         /* Most machines require the value returned from malloc to be aligned
1378          * in some way.  The following macro will get this right
1379          * on many machines.  */
1380         SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1381         /* Minimum size of a block */
1382         MINSIZE = SHELL_ALIGN(504),
1383 };
1384
1385 struct stack_block {
1386         struct stack_block *prev;
1387         char space[MINSIZE];
1388 };
1389
1390 struct stackmark {
1391         struct stack_block *stackp;
1392         char *stacknxt;
1393         size_t stacknleft;
1394 };
1395
1396
1397 struct globals_memstack {
1398         struct stack_block *g_stackp; // = &stackbase;
1399         char *g_stacknxt; // = stackbase.space;
1400         char *sstrend; // = stackbase.space + MINSIZE;
1401         size_t g_stacknleft; // = MINSIZE;
1402         struct stack_block stackbase;
1403 };
1404 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1405 #define G_memstack (*ash_ptr_to_globals_memstack)
1406 #define g_stackp     (G_memstack.g_stackp    )
1407 #define g_stacknxt   (G_memstack.g_stacknxt  )
1408 #define sstrend      (G_memstack.sstrend     )
1409 #define g_stacknleft (G_memstack.g_stacknleft)
1410 #define stackbase    (G_memstack.stackbase   )
1411 #define INIT_G_memstack() do { \
1412         (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1413         barrier(); \
1414         g_stackp = &stackbase; \
1415         g_stacknxt = stackbase.space; \
1416         g_stacknleft = MINSIZE; \
1417         sstrend = stackbase.space + MINSIZE; \
1418 } while (0)
1419
1420
1421 #define stackblock()     ((void *)g_stacknxt)
1422 #define stackblocksize() g_stacknleft
1423
1424 /*
1425  * Parse trees for commands are allocated in lifo order, so we use a stack
1426  * to make this more efficient, and also to avoid all sorts of exception
1427  * handling code to handle interrupts in the middle of a parse.
1428  *
1429  * The size 504 was chosen because the Ultrix malloc handles that size
1430  * well.
1431  */
1432 static void *
1433 stalloc(size_t nbytes)
1434 {
1435         char *p;
1436         size_t aligned;
1437
1438         aligned = SHELL_ALIGN(nbytes);
1439         if (aligned > g_stacknleft) {
1440                 size_t len;
1441                 size_t blocksize;
1442                 struct stack_block *sp;
1443
1444                 blocksize = aligned;
1445                 if (blocksize < MINSIZE)
1446                         blocksize = MINSIZE;
1447                 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1448                 if (len < blocksize)
1449                         ash_msg_and_raise_error(bb_msg_memory_exhausted);
1450                 INT_OFF;
1451                 sp = ckmalloc(len);
1452                 sp->prev = g_stackp;
1453                 g_stacknxt = sp->space;
1454                 g_stacknleft = blocksize;
1455                 sstrend = g_stacknxt + blocksize;
1456                 g_stackp = sp;
1457                 INT_ON;
1458         }
1459         p = g_stacknxt;
1460         g_stacknxt += aligned;
1461         g_stacknleft -= aligned;
1462         return p;
1463 }
1464
1465 static void *
1466 stzalloc(size_t nbytes)
1467 {
1468         return memset(stalloc(nbytes), 0, nbytes);
1469 }
1470
1471 static void
1472 stunalloc(void *p)
1473 {
1474 #if DEBUG
1475         if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1476                 write(STDERR_FILENO, "stunalloc\n", 10);
1477                 abort();
1478         }
1479 #endif
1480         g_stacknleft += g_stacknxt - (char *)p;
1481         g_stacknxt = p;
1482 }
1483
1484 /*
1485  * Like strdup but works with the ash stack.
1486  */
1487 static char *
1488 sstrdup(const char *p)
1489 {
1490         size_t len = strlen(p) + 1;
1491         return memcpy(stalloc(len), p, len);
1492 }
1493
1494 static void
1495 grabstackblock(size_t len)
1496 {
1497         len = SHELL_ALIGN(len);
1498         g_stacknxt += len;
1499         g_stacknleft -= len;
1500 }
1501
1502 static void
1503 pushstackmark(struct stackmark *mark, size_t len)
1504 {
1505         mark->stackp = g_stackp;
1506         mark->stacknxt = g_stacknxt;
1507         mark->stacknleft = g_stacknleft;
1508         grabstackblock(len);
1509 }
1510
1511 static void
1512 setstackmark(struct stackmark *mark)
1513 {
1514         pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1515 }
1516
1517 static void
1518 popstackmark(struct stackmark *mark)
1519 {
1520         struct stack_block *sp;
1521
1522         if (!mark->stackp)
1523                 return;
1524
1525         INT_OFF;
1526         while (g_stackp != mark->stackp) {
1527                 sp = g_stackp;
1528                 g_stackp = sp->prev;
1529                 free(sp);
1530         }
1531         g_stacknxt = mark->stacknxt;
1532         g_stacknleft = mark->stacknleft;
1533         sstrend = mark->stacknxt + mark->stacknleft;
1534         INT_ON;
1535 }
1536
1537 /*
1538  * When the parser reads in a string, it wants to stick the string on the
1539  * stack and only adjust the stack pointer when it knows how big the
1540  * string is.  Stackblock (defined in stack.h) returns a pointer to a block
1541  * of space on top of the stack and stackblocklen returns the length of
1542  * this block.  Growstackblock will grow this space by at least one byte,
1543  * possibly moving it (like realloc).  Grabstackblock actually allocates the
1544  * part of the block that has been used.
1545  */
1546 static void
1547 growstackblock(void)
1548 {
1549         size_t newlen;
1550
1551         newlen = g_stacknleft * 2;
1552         if (newlen < g_stacknleft)
1553                 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1554         if (newlen < 128)
1555                 newlen += 128;
1556
1557         if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1558                 struct stack_block *sp;
1559                 struct stack_block *prevstackp;
1560                 size_t grosslen;
1561
1562                 INT_OFF;
1563                 sp = g_stackp;
1564                 prevstackp = sp->prev;
1565                 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1566                 sp = ckrealloc(sp, grosslen);
1567                 sp->prev = prevstackp;
1568                 g_stackp = sp;
1569                 g_stacknxt = sp->space;
1570                 g_stacknleft = newlen;
1571                 sstrend = sp->space + newlen;
1572                 INT_ON;
1573         } else {
1574                 char *oldspace = g_stacknxt;
1575                 size_t oldlen = g_stacknleft;
1576                 char *p = stalloc(newlen);
1577
1578                 /* free the space we just allocated */
1579                 g_stacknxt = memcpy(p, oldspace, oldlen);
1580                 g_stacknleft += newlen;
1581         }
1582 }
1583
1584 /*
1585  * The following routines are somewhat easier to use than the above.
1586  * The user declares a variable of type STACKSTR, which may be declared
1587  * to be a register.  The macro STARTSTACKSTR initializes things.  Then
1588  * the user uses the macro STPUTC to add characters to the string.  In
1589  * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1590  * grown as necessary.  When the user is done, she can just leave the
1591  * string there and refer to it using stackblock().  Or she can allocate
1592  * the space for it using grabstackstr().  If it is necessary to allow
1593  * someone else to use the stack temporarily and then continue to grow
1594  * the string, the user should use grabstack to allocate the space, and
1595  * then call ungrabstr(p) to return to the previous mode of operation.
1596  *
1597  * USTPUTC is like STPUTC except that it doesn't check for overflow.
1598  * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1599  * is space for at least one character.
1600  */
1601 static void *
1602 growstackstr(void)
1603 {
1604         size_t len = stackblocksize();
1605         growstackblock();
1606         return (char *)stackblock() + len;
1607 }
1608
1609 /*
1610  * Called from CHECKSTRSPACE.
1611  */
1612 static char *
1613 makestrspace(size_t newlen, char *p)
1614 {
1615         size_t len = p - g_stacknxt;
1616         size_t size;
1617
1618         for (;;) {
1619                 size_t nleft;
1620
1621                 size = stackblocksize();
1622                 nleft = size - len;
1623                 if (nleft >= newlen)
1624                         break;
1625                 growstackblock();
1626         }
1627         return (char *)stackblock() + len;
1628 }
1629
1630 static char *
1631 stack_nputstr(const char *s, size_t n, char *p)
1632 {
1633         p = makestrspace(n, p);
1634         p = (char *)memcpy(p, s, n) + n;
1635         return p;
1636 }
1637
1638 static char *
1639 stack_putstr(const char *s, char *p)
1640 {
1641         return stack_nputstr(s, strlen(s), p);
1642 }
1643
1644 static char *
1645 _STPUTC(int c, char *p)
1646 {
1647         if (p == sstrend)
1648                 p = growstackstr();
1649         *p++ = c;
1650         return p;
1651 }
1652
1653 #define STARTSTACKSTR(p)        ((p) = stackblock())
1654 #define STPUTC(c, p)            ((p) = _STPUTC((c), (p)))
1655 #define CHECKSTRSPACE(n, p) do { \
1656         char *q = (p); \
1657         size_t l = (n); \
1658         size_t m = sstrend - q; \
1659         if (l > m) \
1660                 (p) = makestrspace(l, q); \
1661 } while (0)
1662 #define USTPUTC(c, p)           (*(p)++ = (c))
1663 #define STACKSTRNUL(p) do { \
1664         if ((p) == sstrend) \
1665                 (p) = growstackstr(); \
1666         *(p) = '\0'; \
1667 } while (0)
1668 #define STUNPUTC(p)             (--(p))
1669 #define STTOPC(p)               ((p)[-1])
1670 #define STADJUST(amount, p)     ((p) += (amount))
1671
1672 #define grabstackstr(p)         stalloc((char *)(p) - (char *)stackblock())
1673 #define ungrabstackstr(s, p)    stunalloc(s)
1674 #define stackstrend()           ((void *)sstrend)
1675
1676
1677 /* ============ String helpers */
1678
1679 /*
1680  * prefix -- see if pfx is a prefix of string.
1681  */
1682 static char *
1683 prefix(const char *string, const char *pfx)
1684 {
1685         while (*pfx) {
1686                 if (*pfx++ != *string++)
1687                         return NULL;
1688         }
1689         return (char *) string;
1690 }
1691
1692 /*
1693  * Check for a valid number.  This should be elsewhere.
1694  */
1695 static int
1696 is_number(const char *p)
1697 {
1698         do {
1699                 if (!isdigit(*p))
1700                         return 0;
1701         } while (*++p != '\0');
1702         return 1;
1703 }
1704
1705 /*
1706  * Convert a string of digits to an integer, printing an error message on
1707  * failure.
1708  */
1709 static int
1710 number(const char *s)
1711 {
1712         if (!is_number(s))
1713                 ash_msg_and_raise_error(msg_illnum, s);
1714         return atoi(s);
1715 }
1716
1717 /*
1718  * Produce a possibly single quoted string suitable as input to the shell.
1719  * The return string is allocated on the stack.
1720  */
1721 static char *
1722 single_quote(const char *s)
1723 {
1724         char *p;
1725
1726         STARTSTACKSTR(p);
1727
1728         do {
1729                 char *q;
1730                 size_t len;
1731
1732                 len = strchrnul(s, '\'') - s;
1733
1734                 q = p = makestrspace(len + 3, p);
1735
1736                 *q++ = '\'';
1737                 q = (char *)memcpy(q, s, len) + len;
1738                 *q++ = '\'';
1739                 s += len;
1740
1741                 STADJUST(q - p, p);
1742
1743                 if (*s != '\'')
1744                         break;
1745                 len = 0;
1746                 do len++; while (*++s == '\'');
1747
1748                 q = p = makestrspace(len + 3, p);
1749
1750                 *q++ = '"';
1751                 q = (char *)memcpy(q, s - len, len) + len;
1752                 *q++ = '"';
1753
1754                 STADJUST(q - p, p);
1755         } while (*s);
1756
1757         USTPUTC('\0', p);
1758
1759         return stackblock();
1760 }
1761
1762
1763 /* ============ nextopt */
1764
1765 static char **argptr;                  /* argument list for builtin commands */
1766 static char *optionarg;                /* set by nextopt (like getopt) */
1767 static char *optptr;                   /* used by nextopt */
1768
1769 /*
1770  * XXX - should get rid of. Have all builtins use getopt(3).
1771  * The library getopt must have the BSD extension static variable
1772  * "optreset", otherwise it can't be used within the shell safely.
1773  *
1774  * Standard option processing (a la getopt) for builtin routines.
1775  * The only argument that is passed to nextopt is the option string;
1776  * the other arguments are unnecessary. It returns the character,
1777  * or '\0' on end of input.
1778  */
1779 static int
1780 nextopt(const char *optstring)
1781 {
1782         char *p;
1783         const char *q;
1784         char c;
1785
1786         p = optptr;
1787         if (p == NULL || *p == '\0') {
1788                 /* We ate entire "-param", take next one */
1789                 p = *argptr;
1790                 if (p == NULL)
1791                         return '\0';
1792                 if (*p != '-')
1793                         return '\0';
1794                 if (*++p == '\0') /* just "-" ? */
1795                         return '\0';
1796                 argptr++;
1797                 if (LONE_DASH(p)) /* "--" ? */
1798                         return '\0';
1799                 /* p => next "-param" */
1800         }
1801         /* p => some option char in the middle of a "-param" */
1802         c = *p++;
1803         for (q = optstring; *q != c;) {
1804                 if (*q == '\0')
1805                         ash_msg_and_raise_error("illegal option -%c", c);
1806                 if (*++q == ':')
1807                         q++;
1808         }
1809         if (*++q == ':') {
1810                 if (*p == '\0') {
1811                         p = *argptr++;
1812                         if (p == NULL)
1813                                 ash_msg_and_raise_error("no arg for -%c option", c);
1814                 }
1815                 optionarg = p;
1816                 p = NULL;
1817         }
1818         optptr = p;
1819         return c;
1820 }
1821
1822
1823 /* ============ Shell variables */
1824
1825 /*
1826  * The parsefile structure pointed to by the global variable parsefile
1827  * contains information about the current file being read.
1828  */
1829 struct shparam {
1830         int nparam;             /* # of positional parameters (without $0) */
1831 #if ENABLE_ASH_GETOPTS
1832         int optind;             /* next parameter to be processed by getopts */
1833         int optoff;             /* used by getopts */
1834 #endif
1835         unsigned char malloced; /* if parameter list dynamically allocated */
1836         char **p;               /* parameter list */
1837 };
1838
1839 /*
1840  * Free the list of positional parameters.
1841  */
1842 static void
1843 freeparam(volatile struct shparam *param)
1844 {
1845         if (param->malloced) {
1846                 char **ap, **ap1;
1847                 ap = ap1 = param->p;
1848                 while (*ap)
1849                         free(*ap++);
1850                 free(ap1);
1851         }
1852 }
1853
1854 #if ENABLE_ASH_GETOPTS
1855 static void FAST_FUNC getoptsreset(const char *value);
1856 #endif
1857
1858 struct var {
1859         struct var *next;               /* next entry in hash list */
1860         int flags;                      /* flags are defined above */
1861         const char *var_text;           /* name=value */
1862         void (*var_func)(const char *) FAST_FUNC; /* function to be called when  */
1863                                         /* the variable gets set/unset */
1864 };
1865
1866 struct localvar {
1867         struct localvar *next;          /* next local variable in list */
1868         struct var *vp;                 /* the variable that was made local */
1869         int flags;                      /* saved flags */
1870         const char *text;               /* saved text */
1871 };
1872
1873 /* flags */
1874 #define VEXPORT         0x01    /* variable is exported */
1875 #define VREADONLY       0x02    /* variable cannot be modified */
1876 #define VSTRFIXED       0x04    /* variable struct is statically allocated */
1877 #define VTEXTFIXED      0x08    /* text is statically allocated */
1878 #define VSTACK          0x10    /* text is allocated on the stack */
1879 #define VUNSET          0x20    /* the variable is not set */
1880 #define VNOFUNC         0x40    /* don't call the callback function */
1881 #define VNOSET          0x80    /* do not set variable - just readonly test */
1882 #define VNOSAVE         0x100   /* when text is on the heap before setvareq */
1883 #if ENABLE_ASH_RANDOM_SUPPORT
1884 # define VDYNAMIC       0x200   /* dynamic variable */
1885 #else
1886 # define VDYNAMIC       0
1887 #endif
1888
1889
1890 /* Need to be before varinit_data[] */
1891 #if ENABLE_LOCALE_SUPPORT
1892 static void FAST_FUNC
1893 change_lc_all(const char *value)
1894 {
1895         if (value && *value != '\0')
1896                 setlocale(LC_ALL, value);
1897 }
1898 static void FAST_FUNC
1899 change_lc_ctype(const char *value)
1900 {
1901         if (value && *value != '\0')
1902                 setlocale(LC_CTYPE, value);
1903 }
1904 #endif
1905 #if ENABLE_ASH_MAIL
1906 static void chkmail(void);
1907 static void changemail(const char *var_value) FAST_FUNC;
1908 #else
1909 # define chkmail()  ((void)0)
1910 #endif
1911 static void changepath(const char *) FAST_FUNC;
1912 #if ENABLE_ASH_RANDOM_SUPPORT
1913 static void change_random(const char *) FAST_FUNC;
1914 #endif
1915
1916 static const struct {
1917         int flags;
1918         const char *var_text;
1919         void (*var_func)(const char *) FAST_FUNC;
1920 } varinit_data[] = {
1921         /*
1922          * Note: VEXPORT would not work correctly here for NOFORK applets:
1923          * some environment strings may be constant.
1924          */
1925         { VSTRFIXED|VTEXTFIXED       , defifsvar   , NULL            },
1926 #if ENABLE_ASH_MAIL
1927         { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL"      , changemail      },
1928         { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH"  , changemail      },
1929 #endif
1930         { VSTRFIXED|VTEXTFIXED       , bb_PATH_root_path, changepath },
1931         { VSTRFIXED|VTEXTFIXED       , "PS1=$ "    , NULL            },
1932         { VSTRFIXED|VTEXTFIXED       , "PS2=> "    , NULL            },
1933         { VSTRFIXED|VTEXTFIXED       , "PS4=+ "    , NULL            },
1934 #if ENABLE_ASH_GETOPTS
1935         { VSTRFIXED|VTEXTFIXED       , defoptindvar, getoptsreset    },
1936 #endif
1937 #if ENABLE_ASH_RANDOM_SUPPORT
1938         { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1939 #endif
1940 #if ENABLE_LOCALE_SUPPORT
1941         { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL"    , change_lc_all   },
1942         { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE"  , change_lc_ctype },
1943 #endif
1944 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1945         { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE"  , NULL            },
1946 #endif
1947 };
1948
1949 struct redirtab;
1950
1951 struct globals_var {
1952         struct shparam shellparam;      /* $@ current positional parameters */
1953         struct redirtab *redirlist;
1954         int preverrout_fd;   /* save fd2 before print debug if xflag is set. */
1955         struct var *vartab[VTABSIZE];
1956         struct var varinit[ARRAY_SIZE(varinit_data)];
1957 };
1958 extern struct globals_var *const ash_ptr_to_globals_var;
1959 #define G_var (*ash_ptr_to_globals_var)
1960 #define shellparam    (G_var.shellparam   )
1961 //#define redirlist     (G_var.redirlist    )
1962 #define preverrout_fd (G_var.preverrout_fd)
1963 #define vartab        (G_var.vartab       )
1964 #define varinit       (G_var.varinit      )
1965 #define INIT_G_var() do { \
1966         unsigned i; \
1967         (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1968         barrier(); \
1969         for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1970                 varinit[i].flags    = varinit_data[i].flags; \
1971                 varinit[i].var_text = varinit_data[i].var_text; \
1972                 varinit[i].var_func = varinit_data[i].var_func; \
1973         } \
1974 } while (0)
1975
1976 #define vifs      varinit[0]
1977 #if ENABLE_ASH_MAIL
1978 # define vmail    (&vifs)[1]
1979 # define vmpath   (&vmail)[1]
1980 # define vpath    (&vmpath)[1]
1981 #else
1982 # define vpath    (&vifs)[1]
1983 #endif
1984 #define vps1      (&vpath)[1]
1985 #define vps2      (&vps1)[1]
1986 #define vps4      (&vps2)[1]
1987 #if ENABLE_ASH_GETOPTS
1988 # define voptind  (&vps4)[1]
1989 # if ENABLE_ASH_RANDOM_SUPPORT
1990 #  define vrandom (&voptind)[1]
1991 # endif
1992 #else
1993 # if ENABLE_ASH_RANDOM_SUPPORT
1994 #  define vrandom (&vps4)[1]
1995 # endif
1996 #endif
1997
1998 /*
1999  * The following macros access the values of the above variables.
2000  * They have to skip over the name.  They return the null string
2001  * for unset variables.
2002  */
2003 #define ifsval()        (vifs.var_text + 4)
2004 #define ifsset()        ((vifs.flags & VUNSET) == 0)
2005 #if ENABLE_ASH_MAIL
2006 # define mailval()      (vmail.var_text + 5)
2007 # define mpathval()     (vmpath.var_text + 9)
2008 # define mpathset()     ((vmpath.flags & VUNSET) == 0)
2009 #endif
2010 #define pathval()       (vpath.var_text + 5)
2011 #define ps1val()        (vps1.var_text + 4)
2012 #define ps2val()        (vps2.var_text + 4)
2013 #define ps4val()        (vps4.var_text + 4)
2014 #if ENABLE_ASH_GETOPTS
2015 # define optindval()    (voptind.var_text + 7)
2016 #endif
2017
2018 #if ENABLE_ASH_GETOPTS
2019 static void FAST_FUNC
2020 getoptsreset(const char *value)
2021 {
2022         shellparam.optind = number(value);
2023         shellparam.optoff = -1;
2024 }
2025 #endif
2026
2027 /*
2028  * Compares two strings up to the first = or '\0'.  The first
2029  * string must be terminated by '='; the second may be terminated by
2030  * either '=' or '\0'.
2031  */
2032 static int
2033 varcmp(const char *p, const char *q)
2034 {
2035         int c, d;
2036
2037         while ((c = *p) == (d = *q)) {
2038                 if (c == '\0' || c == '=')
2039                         goto out;
2040                 p++;
2041                 q++;
2042         }
2043         if (c == '=')
2044                 c = '\0';
2045         if (d == '=')
2046                 d = '\0';
2047  out:
2048         return c - d;
2049 }
2050
2051 /*
2052  * Find the appropriate entry in the hash table from the name.
2053  */
2054 static struct var **
2055 hashvar(const char *p)
2056 {
2057         unsigned hashval;
2058
2059         hashval = ((unsigned char) *p) << 4;
2060         while (*p && *p != '=')
2061                 hashval += (unsigned char) *p++;
2062         return &vartab[hashval % VTABSIZE];
2063 }
2064
2065 static int
2066 vpcmp(const void *a, const void *b)
2067 {
2068         return varcmp(*(const char **)a, *(const char **)b);
2069 }
2070
2071 /*
2072  * This routine initializes the builtin variables.
2073  */
2074 static void
2075 initvar(void)
2076 {
2077         struct var *vp;
2078         struct var *end;
2079         struct var **vpp;
2080
2081         /*
2082          * PS1 depends on uid
2083          */
2084 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2085         vps1.var_text = "PS1=\\w \\$ ";
2086 #else
2087         if (!geteuid())
2088                 vps1.var_text = "PS1=# ";
2089 #endif
2090         vp = varinit;
2091         end = vp + ARRAY_SIZE(varinit);
2092         do {
2093                 vpp = hashvar(vp->var_text);
2094                 vp->next = *vpp;
2095                 *vpp = vp;
2096         } while (++vp < end);
2097 }
2098
2099 static struct var **
2100 findvar(struct var **vpp, const char *name)
2101 {
2102         for (; *vpp; vpp = &(*vpp)->next) {
2103                 if (varcmp((*vpp)->var_text, name) == 0) {
2104                         break;
2105                 }
2106         }
2107         return vpp;
2108 }
2109
2110 /*
2111  * Find the value of a variable.  Returns NULL if not set.
2112  */
2113 static const char* FAST_FUNC
2114 lookupvar(const char *name)
2115 {
2116         struct var *v;
2117
2118         v = *findvar(hashvar(name), name);
2119         if (v) {
2120 #if ENABLE_ASH_RANDOM_SUPPORT
2121         /*
2122          * Dynamic variables are implemented roughly the same way they are
2123          * in bash. Namely, they're "special" so long as they aren't unset.
2124          * As soon as they're unset, they're no longer dynamic, and dynamic
2125          * lookup will no longer happen at that point. -- PFM.
2126          */
2127                 if (v->flags & VDYNAMIC)
2128                         v->var_func(NULL);
2129 #endif
2130                 if (!(v->flags & VUNSET))
2131                         return var_end(v->var_text);
2132         }
2133         return NULL;
2134 }
2135
2136 static void
2137 reinit_unicode_for_ash(void)
2138 {
2139         /* Unicode support should be activated even if LANG is set
2140          * _during_ shell execution, not only if it was set when
2141          * shell was started. Therefore, re-check LANG every time:
2142          */
2143         if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2144          || ENABLE_UNICODE_USING_LOCALE
2145         ) {
2146                 const char *s = lookupvar("LC_ALL");
2147                 if (!s) s = lookupvar("LC_CTYPE");
2148                 if (!s) s = lookupvar("LANG");
2149                 reinit_unicode(s);
2150         }
2151 }
2152
2153 /*
2154  * Search the environment of a builtin command.
2155  */
2156 static const char *
2157 bltinlookup(const char *name)
2158 {
2159         struct strlist *sp;
2160
2161         for (sp = cmdenviron; sp; sp = sp->next) {
2162                 if (varcmp(sp->text, name) == 0)
2163                         return var_end(sp->text);
2164         }
2165         return lookupvar(name);
2166 }
2167
2168 /*
2169  * Same as setvar except that the variable and value are passed in
2170  * the first argument as name=value.  Since the first argument will
2171  * be actually stored in the table, it should not be a string that
2172  * will go away.
2173  * Called with interrupts off.
2174  */
2175 static void
2176 setvareq(char *s, int flags)
2177 {
2178         struct var *vp, **vpp;
2179
2180         vpp = hashvar(s);
2181         flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2182         vp = *findvar(vpp, s);
2183         if (vp) {
2184                 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2185                         const char *n;
2186
2187                         if (flags & VNOSAVE)
2188                                 free(s);
2189                         n = vp->var_text;
2190                         ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2191                 }
2192
2193                 if (flags & VNOSET)
2194                         return;
2195
2196                 if (vp->var_func && !(flags & VNOFUNC))
2197                         vp->var_func(var_end(s));
2198
2199                 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2200                         free((char*)vp->var_text);
2201
2202                 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2203         } else {
2204                 /* variable s is not found */
2205                 if (flags & VNOSET)
2206                         return;
2207                 vp = ckzalloc(sizeof(*vp));
2208                 vp->next = *vpp;
2209                 /*vp->func = NULL; - ckzalloc did it */
2210                 *vpp = vp;
2211         }
2212         if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2213                 s = ckstrdup(s);
2214         vp->var_text = s;
2215         vp->flags = flags;
2216 }
2217
2218 /*
2219  * Set the value of a variable.  The flags argument is ored with the
2220  * flags of the variable.  If val is NULL, the variable is unset.
2221  */
2222 static void
2223 setvar(const char *name, const char *val, int flags)
2224 {
2225         const char *q;
2226         char *p;
2227         char *nameeq;
2228         size_t namelen;
2229         size_t vallen;
2230
2231         q = endofname(name);
2232         p = strchrnul(q, '=');
2233         namelen = p - name;
2234         if (!namelen || p != q)
2235                 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2236         vallen = 0;
2237         if (val == NULL) {
2238                 flags |= VUNSET;
2239         } else {
2240                 vallen = strlen(val);
2241         }
2242
2243         INT_OFF;
2244         nameeq = ckmalloc(namelen + vallen + 2);
2245         p = memcpy(nameeq, name, namelen) + namelen;
2246         if (val) {
2247                 *p++ = '=';
2248                 p = memcpy(p, val, vallen) + vallen;
2249         }
2250         *p = '\0';
2251         setvareq(nameeq, flags | VNOSAVE);
2252         INT_ON;
2253 }
2254
2255 static void FAST_FUNC
2256 setvar0(const char *name, const char *val)
2257 {
2258         setvar(name, val, 0);
2259 }
2260
2261 #if ENABLE_ASH_GETOPTS
2262 /*
2263  * Safe version of setvar, returns 1 on success 0 on failure.
2264  */
2265 static int
2266 setvarsafe(const char *name, const char *val, int flags)
2267 {
2268         int err;
2269         volatile int saveint;
2270         struct jmploc *volatile savehandler = exception_handler;
2271         struct jmploc jmploc;
2272
2273         SAVE_INT(saveint);
2274         if (setjmp(jmploc.loc))
2275                 err = 1;
2276         else {
2277                 exception_handler = &jmploc;
2278                 setvar(name, val, flags);
2279                 err = 0;
2280         }
2281         exception_handler = savehandler;
2282         RESTORE_INT(saveint);
2283         return err;
2284 }
2285 #endif
2286
2287 /*
2288  * Unset the specified variable.
2289  */
2290 static int
2291 unsetvar(const char *s)
2292 {
2293         struct var **vpp;
2294         struct var *vp;
2295         int retval;
2296
2297         vpp = findvar(hashvar(s), s);
2298         vp = *vpp;
2299         retval = 2;
2300         if (vp) {
2301                 int flags = vp->flags;
2302
2303                 retval = 1;
2304                 if (flags & VREADONLY)
2305                         goto out;
2306 #if ENABLE_ASH_RANDOM_SUPPORT
2307                 vp->flags &= ~VDYNAMIC;
2308 #endif
2309                 if (flags & VUNSET)
2310                         goto ok;
2311                 if ((flags & VSTRFIXED) == 0) {
2312                         INT_OFF;
2313                         if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2314                                 free((char*)vp->var_text);
2315                         *vpp = vp->next;
2316                         free(vp);
2317                         INT_ON;
2318                 } else {
2319                         setvar0(s, NULL);
2320                         vp->flags &= ~VEXPORT;
2321                 }
2322  ok:
2323                 retval = 0;
2324         }
2325  out:
2326         return retval;
2327 }
2328
2329 /*
2330  * Process a linked list of variable assignments.
2331  */
2332 static void
2333 listsetvar(struct strlist *list_set_var, int flags)
2334 {
2335         struct strlist *lp = list_set_var;
2336
2337         if (!lp)
2338                 return;
2339         INT_OFF;
2340         do {
2341                 setvareq(lp->text, flags);
2342                 lp = lp->next;
2343         } while (lp);
2344         INT_ON;
2345 }
2346
2347 /*
2348  * Generate a list of variables satisfying the given conditions.
2349  */
2350 static char **
2351 listvars(int on, int off, char ***end)
2352 {
2353         struct var **vpp;
2354         struct var *vp;
2355         char **ep;
2356         int mask;
2357
2358         STARTSTACKSTR(ep);
2359         vpp = vartab;
2360         mask = on | off;
2361         do {
2362                 for (vp = *vpp; vp; vp = vp->next) {
2363                         if ((vp->flags & mask) == on) {
2364                                 if (ep == stackstrend())
2365                                         ep = growstackstr();
2366                                 *ep++ = (char*)vp->var_text;
2367                         }
2368                 }
2369         } while (++vpp < vartab + VTABSIZE);
2370         if (ep == stackstrend())
2371                 ep = growstackstr();
2372         if (end)
2373                 *end = ep;
2374         *ep++ = NULL;
2375         return grabstackstr(ep);
2376 }
2377
2378
2379 /* ============ Path search helper
2380  *
2381  * The variable path (passed by reference) should be set to the start
2382  * of the path before the first call; path_advance will update
2383  * this value as it proceeds.  Successive calls to path_advance will return
2384  * the possible path expansions in sequence.  If an option (indicated by
2385  * a percent sign) appears in the path entry then the global variable
2386  * pathopt will be set to point to it; otherwise pathopt will be set to
2387  * NULL.
2388  */
2389 static const char *pathopt;     /* set by path_advance */
2390
2391 static char *
2392 path_advance(const char **path, const char *name)
2393 {
2394         const char *p;
2395         char *q;
2396         const char *start;
2397         size_t len;
2398
2399         if (*path == NULL)
2400                 return NULL;
2401         start = *path;
2402         for (p = start; *p && *p != ':' && *p != '%'; p++)
2403                 continue;
2404         len = p - start + strlen(name) + 2;     /* "2" is for '/' and '\0' */
2405         while (stackblocksize() < len)
2406                 growstackblock();
2407         q = stackblock();
2408         if (p != start) {
2409                 memcpy(q, start, p - start);
2410                 q += p - start;
2411                 *q++ = '/';
2412         }
2413         strcpy(q, name);
2414         pathopt = NULL;
2415         if (*p == '%') {
2416                 pathopt = ++p;
2417                 while (*p && *p != ':')
2418                         p++;
2419         }
2420         if (*p == ':')
2421                 *path = p + 1;
2422         else
2423                 *path = NULL;
2424         return stalloc(len);
2425 }
2426
2427
2428 /* ============ Prompt */
2429
2430 static smallint doprompt;                   /* if set, prompt the user */
2431 static smallint needprompt;                 /* true if interactive and at start of line */
2432
2433 #if ENABLE_FEATURE_EDITING
2434 static line_input_t *line_input_state;
2435 static const char *cmdedit_prompt;
2436 static void
2437 putprompt(const char *s)
2438 {
2439         if (ENABLE_ASH_EXPAND_PRMT) {
2440                 free((char*)cmdedit_prompt);
2441                 cmdedit_prompt = ckstrdup(s);
2442                 return;
2443         }
2444         cmdedit_prompt = s;
2445 }
2446 #else
2447 static void
2448 putprompt(const char *s)
2449 {
2450         out2str(s);
2451 }
2452 #endif
2453
2454 #if ENABLE_ASH_EXPAND_PRMT
2455 /* expandstr() needs parsing machinery, so it is far away ahead... */
2456 static const char *expandstr(const char *ps);
2457 #else
2458 #define expandstr(s) s
2459 #endif
2460
2461 static void
2462 setprompt_if(smallint do_set, int whichprompt)
2463 {
2464         const char *prompt;
2465         IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2466
2467         if (!do_set)
2468                 return;
2469
2470         needprompt = 0;
2471
2472         switch (whichprompt) {
2473         case 1:
2474                 prompt = ps1val();
2475                 break;
2476         case 2:
2477                 prompt = ps2val();
2478                 break;
2479         default:                        /* 0 */
2480                 prompt = nullstr;
2481         }
2482 #if ENABLE_ASH_EXPAND_PRMT
2483         pushstackmark(&smark, stackblocksize());
2484 #endif
2485         putprompt(expandstr(prompt));
2486 #if ENABLE_ASH_EXPAND_PRMT
2487         popstackmark(&smark);
2488 #endif
2489 }
2490
2491
2492 /* ============ The cd and pwd commands */
2493
2494 #define CD_PHYSICAL 1
2495 #define CD_PRINT 2
2496
2497 static int
2498 cdopt(void)
2499 {
2500         int flags = 0;
2501         int i, j;
2502
2503         j = 'L';
2504         while ((i = nextopt("LP")) != '\0') {
2505                 if (i != j) {
2506                         flags ^= CD_PHYSICAL;
2507                         j = i;
2508                 }
2509         }
2510
2511         return flags;
2512 }
2513
2514 /*
2515  * Update curdir (the name of the current directory) in response to a
2516  * cd command.
2517  */
2518 static const char *
2519 updatepwd(const char *dir)
2520 {
2521         char *new;
2522         char *p;
2523         char *cdcomppath;
2524         const char *lim;
2525
2526         cdcomppath = sstrdup(dir);
2527         STARTSTACKSTR(new);
2528         if (*dir != '/') {
2529                 if (curdir == nullstr)
2530                         return 0;
2531                 new = stack_putstr(curdir, new);
2532         }
2533         new = makestrspace(strlen(dir) + 2, new);
2534         lim = (char *)stackblock() + 1;
2535         if (*dir != '/') {
2536                 if (new[-1] != '/')
2537                         USTPUTC('/', new);
2538                 if (new > lim && *lim == '/')
2539                         lim++;
2540         } else {
2541                 USTPUTC('/', new);
2542                 cdcomppath++;
2543                 if (dir[1] == '/' && dir[2] != '/') {
2544                         USTPUTC('/', new);
2545                         cdcomppath++;
2546                         lim++;
2547                 }
2548         }
2549         p = strtok(cdcomppath, "/");
2550         while (p) {
2551                 switch (*p) {
2552                 case '.':
2553                         if (p[1] == '.' && p[2] == '\0') {
2554                                 while (new > lim) {
2555                                         STUNPUTC(new);
2556                                         if (new[-1] == '/')
2557                                                 break;
2558                                 }
2559                                 break;
2560                         }
2561                         if (p[1] == '\0')
2562                                 break;
2563                         /* fall through */
2564                 default:
2565                         new = stack_putstr(p, new);
2566                         USTPUTC('/', new);
2567                 }
2568                 p = strtok(NULL, "/");
2569         }
2570         if (new > lim)
2571                 STUNPUTC(new);
2572         *new = 0;
2573         return stackblock();
2574 }
2575
2576 /*
2577  * Find out what the current directory is. If we already know the current
2578  * directory, this routine returns immediately.
2579  */
2580 static char *
2581 getpwd(void)
2582 {
2583         char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2584         return dir ? dir : nullstr;
2585 }
2586
2587 static void
2588 setpwd(const char *val, int setold)
2589 {
2590         char *oldcur, *dir;
2591
2592         oldcur = dir = curdir;
2593
2594         if (setold) {
2595                 setvar("OLDPWD", oldcur, VEXPORT);
2596         }
2597         INT_OFF;
2598         if (physdir != nullstr) {
2599                 if (physdir != oldcur)
2600                         free(physdir);
2601                 physdir = nullstr;
2602         }
2603         if (oldcur == val || !val) {
2604                 char *s = getpwd();
2605                 physdir = s;
2606                 if (!val)
2607                         dir = s;
2608         } else
2609                 dir = ckstrdup(val);
2610         if (oldcur != dir && oldcur != nullstr) {
2611                 free(oldcur);
2612         }
2613         curdir = dir;
2614         INT_ON;
2615         setvar("PWD", dir, VEXPORT);
2616 }
2617
2618 static void hashcd(void);
2619
2620 /*
2621  * Actually do the chdir.  We also call hashcd to let the routines in exec.c
2622  * know that the current directory has changed.
2623  */
2624 static int
2625 docd(const char *dest, int flags)
2626 {
2627         const char *dir = NULL;
2628         int err;
2629
2630         TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2631
2632         INT_OFF;
2633         if (!(flags & CD_PHYSICAL)) {
2634                 dir = updatepwd(dest);
2635                 if (dir)
2636                         dest = dir;
2637         }
2638         err = chdir(dest);
2639         if (err)
2640                 goto out;
2641         setpwd(dir, 1);
2642         hashcd();
2643  out:
2644         INT_ON;
2645         return err;
2646 }
2647
2648 static int FAST_FUNC
2649 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2650 {
2651         const char *dest;
2652         const char *path;
2653         const char *p;
2654         char c;
2655         struct stat statb;
2656         int flags;
2657
2658         flags = cdopt();
2659         dest = *argptr;
2660         if (!dest)
2661                 dest = bltinlookup("HOME");
2662         else if (LONE_DASH(dest)) {
2663                 dest = bltinlookup("OLDPWD");
2664                 flags |= CD_PRINT;
2665         }
2666         if (!dest)
2667                 dest = nullstr;
2668         if (*dest == '/')
2669                 goto step7;
2670         if (*dest == '.') {
2671                 c = dest[1];
2672  dotdot:
2673                 switch (c) {
2674                 case '\0':
2675                 case '/':
2676                         goto step6;
2677                 case '.':
2678                         c = dest[2];
2679                         if (c != '.')
2680                                 goto dotdot;
2681                 }
2682         }
2683         if (!*dest)
2684                 dest = ".";
2685         path = bltinlookup("CDPATH");
2686         if (!path) {
2687  step6:
2688  step7:
2689                 p = dest;
2690                 goto docd;
2691         }
2692         do {
2693                 c = *path;
2694                 p = path_advance(&path, dest);
2695                 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2696                         if (c && c != ':')
2697                                 flags |= CD_PRINT;
2698  docd:
2699                         if (!docd(p, flags))
2700                                 goto out;
2701                         break;
2702                 }
2703         } while (path);
2704         ash_msg_and_raise_error("can't cd to %s", dest);
2705         /* NOTREACHED */
2706  out:
2707         if (flags & CD_PRINT)
2708                 out1fmt("%s\n", curdir);
2709         return 0;
2710 }
2711
2712 static int FAST_FUNC
2713 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2714 {
2715         int flags;
2716         const char *dir = curdir;
2717
2718         flags = cdopt();
2719         if (flags) {
2720                 if (physdir == nullstr)
2721                         setpwd(dir, 0);
2722                 dir = physdir;
2723         }
2724         out1fmt("%s\n", dir);
2725         return 0;
2726 }
2727
2728
2729 /* ============ ... */
2730
2731
2732 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2733
2734 /* Syntax classes */
2735 #define CWORD     0             /* character is nothing special */
2736 #define CNL       1             /* newline character */
2737 #define CBACK     2             /* a backslash character */
2738 #define CSQUOTE   3             /* single quote */
2739 #define CDQUOTE   4             /* double quote */
2740 #define CENDQUOTE 5             /* a terminating quote */
2741 #define CBQUOTE   6             /* backwards single quote */
2742 #define CVAR      7             /* a dollar sign */
2743 #define CENDVAR   8             /* a '}' character */
2744 #define CLP       9             /* a left paren in arithmetic */
2745 #define CRP      10             /* a right paren in arithmetic */
2746 #define CENDFILE 11             /* end of file */
2747 #define CCTL     12             /* like CWORD, except it must be escaped */
2748 #define CSPCL    13             /* these terminate a word */
2749 #define CIGN     14             /* character should be ignored */
2750
2751 #define PEOF     256
2752 #if ENABLE_ASH_ALIAS
2753 # define PEOA    257
2754 #endif
2755
2756 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2757
2758 #if ENABLE_SH_MATH_SUPPORT
2759 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2760 #else
2761 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2762 #endif
2763 static const uint16_t S_I_T[] ALIGN2 = {
2764 #if ENABLE_ASH_ALIAS
2765         SIT_ITEM(CSPCL   , CIGN     , CIGN , CIGN   ),    /* 0, PEOA */
2766 #endif
2767         SIT_ITEM(CSPCL   , CWORD    , CWORD, CWORD  ),    /* 1, ' ' */
2768         SIT_ITEM(CNL     , CNL      , CNL  , CNL    ),    /* 2, \n */
2769         SIT_ITEM(CWORD   , CCTL     , CCTL , CWORD  ),    /* 3, !*-/:=?[]~ */
2770         SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD  ),    /* 4, '"' */
2771         SIT_ITEM(CVAR    , CVAR     , CWORD, CVAR   ),    /* 5, $ */
2772         SIT_ITEM(CSQUOTE , CWORD    , CENDQUOTE, CWORD),  /* 6, "'" */
2773         SIT_ITEM(CSPCL   , CWORD    , CWORD, CLP    ),    /* 7, ( */
2774         SIT_ITEM(CSPCL   , CWORD    , CWORD, CRP    ),    /* 8, ) */
2775         SIT_ITEM(CBACK   , CBACK    , CCTL , CBACK  ),    /* 9, \ */
2776         SIT_ITEM(CBQUOTE , CBQUOTE  , CWORD, CBQUOTE),    /* 10, ` */
2777         SIT_ITEM(CENDVAR , CENDVAR  , CWORD, CENDVAR),    /* 11, } */
2778 #if !USE_SIT_FUNCTION
2779         SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2780         SIT_ITEM(CWORD   , CWORD    , CWORD, CWORD  ),    /* 13, 0-9A-Za-z */
2781         SIT_ITEM(CCTL    , CCTL     , CCTL , CCTL   )     /* 14, CTLESC ... */
2782 #endif
2783 #undef SIT_ITEM
2784 };
2785 /* Constants below must match table above */
2786 enum {
2787 #if ENABLE_ASH_ALIAS
2788         CSPCL_CIGN_CIGN_CIGN               , /*  0 */
2789 #endif
2790         CSPCL_CWORD_CWORD_CWORD            , /*  1 */
2791         CNL_CNL_CNL_CNL                    , /*  2 */
2792         CWORD_CCTL_CCTL_CWORD              , /*  3 */
2793         CDQUOTE_CENDQUOTE_CWORD_CWORD      , /*  4 */
2794         CVAR_CVAR_CWORD_CVAR               , /*  5 */
2795         CSQUOTE_CWORD_CENDQUOTE_CWORD      , /*  6 */
2796         CSPCL_CWORD_CWORD_CLP              , /*  7 */
2797         CSPCL_CWORD_CWORD_CRP              , /*  8 */
2798         CBACK_CBACK_CCTL_CBACK             , /*  9 */
2799         CBQUOTE_CBQUOTE_CWORD_CBQUOTE      , /* 10 */
2800         CENDVAR_CENDVAR_CWORD_CENDVAR      , /* 11 */
2801         CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2802         CWORD_CWORD_CWORD_CWORD            , /* 13 */
2803         CCTL_CCTL_CCTL_CCTL                , /* 14 */
2804 };
2805
2806 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2807  * caller must ensure proper cast on it if c is *char_ptr!
2808  */
2809 /* Values for syntax param */
2810 #define BASESYNTAX 0    /* not in quotes */
2811 #define DQSYNTAX   1    /* in double quotes */
2812 #define SQSYNTAX   2    /* in single quotes */
2813 #define ARISYNTAX  3    /* in arithmetic */
2814 #define PSSYNTAX   4    /* prompt. never passed to SIT() */
2815
2816 #if USE_SIT_FUNCTION
2817
2818 static int
2819 SIT(int c, int syntax)
2820 {
2821         /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2822         static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2823         /*
2824          * This causes '/' to be prepended with CTLESC in dquoted string,
2825          * making "./file"* treated incorrectly because we feed
2826          * ".\/file*" string to glob(), confusing it (see expandmeta func).
2827          * The "homegrown" glob implementation is okay with that,
2828          * but glibc one isn't. With '/' always treated as CWORD,
2829          * both work fine.
2830          */
2831 # if ENABLE_ASH_ALIAS
2832         static const uint8_t syntax_index_table[] ALIGN1 = {
2833                 1, 2, 1, 3, 4, 5, 1, 6,         /* "\t\n !\"$&'" */
2834                 7, 8, 3, 3,/*3,*/3, 1, 1,       /* "()*-/:;<" */
2835                 3, 1, 3, 3, 9, 3, 10, 1,        /* "=>?[\\]`|" */
2836                 11, 3                           /* "}~" */
2837         };
2838 # else
2839         static const uint8_t syntax_index_table[] ALIGN1 = {
2840                 0, 1, 0, 2, 3, 4, 0, 5,         /* "\t\n !\"$&'" */
2841                 6, 7, 2, 2,/*2,*/2, 0, 0,       /* "()*-/:;<" */
2842                 2, 0, 2, 2, 8, 2, 9, 0,         /* "=>?[\\]`|" */
2843                 10, 2                           /* "}~" */
2844         };
2845 # endif
2846         const char *s;
2847         int indx;
2848
2849         if (c == PEOF)
2850                 return CENDFILE;
2851 # if ENABLE_ASH_ALIAS
2852         if (c == PEOA)
2853                 indx = 0;
2854         else
2855 # endif
2856         {
2857                 /* Cast is purely for paranoia here,
2858                  * just in case someone passed signed char to us */
2859                 if ((unsigned char)c >= CTL_FIRST
2860                  && (unsigned char)c <= CTL_LAST
2861                 ) {
2862                         return CCTL;
2863                 }
2864                 s = strchrnul(spec_symbls, c);
2865                 if (*s == '\0')
2866                         return CWORD;
2867                 indx = syntax_index_table[s - spec_symbls];
2868         }
2869         return (S_I_T[indx] >> (syntax*4)) & 0xf;
2870 }
2871
2872 #else   /* !USE_SIT_FUNCTION */
2873
2874 static const uint8_t syntax_index_table[] ALIGN1 = {
2875         /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2876         /*   0      */ CWORD_CWORD_CWORD_CWORD,
2877         /*   1      */ CWORD_CWORD_CWORD_CWORD,
2878         /*   2      */ CWORD_CWORD_CWORD_CWORD,
2879         /*   3      */ CWORD_CWORD_CWORD_CWORD,
2880         /*   4      */ CWORD_CWORD_CWORD_CWORD,
2881         /*   5      */ CWORD_CWORD_CWORD_CWORD,
2882         /*   6      */ CWORD_CWORD_CWORD_CWORD,
2883         /*   7      */ CWORD_CWORD_CWORD_CWORD,
2884         /*   8      */ CWORD_CWORD_CWORD_CWORD,
2885         /*   9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2886         /*  10 "\n" */ CNL_CNL_CNL_CNL,
2887         /*  11      */ CWORD_CWORD_CWORD_CWORD,
2888         /*  12      */ CWORD_CWORD_CWORD_CWORD,
2889         /*  13      */ CWORD_CWORD_CWORD_CWORD,
2890         /*  14      */ CWORD_CWORD_CWORD_CWORD,
2891         /*  15      */ CWORD_CWORD_CWORD_CWORD,
2892         /*  16      */ CWORD_CWORD_CWORD_CWORD,
2893         /*  17      */ CWORD_CWORD_CWORD_CWORD,
2894         /*  18      */ CWORD_CWORD_CWORD_CWORD,
2895         /*  19      */ CWORD_CWORD_CWORD_CWORD,
2896         /*  20      */ CWORD_CWORD_CWORD_CWORD,
2897         /*  21      */ CWORD_CWORD_CWORD_CWORD,
2898         /*  22      */ CWORD_CWORD_CWORD_CWORD,
2899         /*  23      */ CWORD_CWORD_CWORD_CWORD,
2900         /*  24      */ CWORD_CWORD_CWORD_CWORD,
2901         /*  25      */ CWORD_CWORD_CWORD_CWORD,
2902         /*  26      */ CWORD_CWORD_CWORD_CWORD,
2903         /*  27      */ CWORD_CWORD_CWORD_CWORD,
2904         /*  28      */ CWORD_CWORD_CWORD_CWORD,
2905         /*  29      */ CWORD_CWORD_CWORD_CWORD,
2906         /*  30      */ CWORD_CWORD_CWORD_CWORD,
2907         /*  31      */ CWORD_CWORD_CWORD_CWORD,
2908         /*  32  " " */ CSPCL_CWORD_CWORD_CWORD,
2909         /*  33  "!" */ CWORD_CCTL_CCTL_CWORD,
2910         /*  34  """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2911         /*  35  "#" */ CWORD_CWORD_CWORD_CWORD,
2912         /*  36  "$" */ CVAR_CVAR_CWORD_CVAR,
2913         /*  37  "%" */ CWORD_CWORD_CWORD_CWORD,
2914         /*  38  "&" */ CSPCL_CWORD_CWORD_CWORD,
2915         /*  39  "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2916         /*  40  "(" */ CSPCL_CWORD_CWORD_CLP,
2917         /*  41  ")" */ CSPCL_CWORD_CWORD_CRP,
2918         /*  42  "*" */ CWORD_CCTL_CCTL_CWORD,
2919         /*  43  "+" */ CWORD_CWORD_CWORD_CWORD,
2920         /*  44  "," */ CWORD_CWORD_CWORD_CWORD,
2921         /*  45  "-" */ CWORD_CCTL_CCTL_CWORD,
2922         /*  46  "." */ CWORD_CWORD_CWORD_CWORD,
2923 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2924         /*  47  "/" */ CWORD_CWORD_CWORD_CWORD,
2925         /*  48  "0" */ CWORD_CWORD_CWORD_CWORD,
2926         /*  49  "1" */ CWORD_CWORD_CWORD_CWORD,
2927         /*  50  "2" */ CWORD_CWORD_CWORD_CWORD,
2928         /*  51  "3" */ CWORD_CWORD_CWORD_CWORD,
2929         /*  52  "4" */ CWORD_CWORD_CWORD_CWORD,
2930         /*  53  "5" */ CWORD_CWORD_CWORD_CWORD,
2931         /*  54  "6" */ CWORD_CWORD_CWORD_CWORD,
2932         /*  55  "7" */ CWORD_CWORD_CWORD_CWORD,
2933         /*  56  "8" */ CWORD_CWORD_CWORD_CWORD,
2934         /*  57  "9" */ CWORD_CWORD_CWORD_CWORD,
2935         /*  58  ":" */ CWORD_CCTL_CCTL_CWORD,
2936         /*  59  ";" */ CSPCL_CWORD_CWORD_CWORD,
2937         /*  60  "<" */ CSPCL_CWORD_CWORD_CWORD,
2938         /*  61  "=" */ CWORD_CCTL_CCTL_CWORD,
2939         /*  62  ">" */ CSPCL_CWORD_CWORD_CWORD,
2940         /*  63  "?" */ CWORD_CCTL_CCTL_CWORD,
2941         /*  64  "@" */ CWORD_CWORD_CWORD_CWORD,
2942         /*  65  "A" */ CWORD_CWORD_CWORD_CWORD,
2943         /*  66  "B" */ CWORD_CWORD_CWORD_CWORD,
2944         /*  67  "C" */ CWORD_CWORD_CWORD_CWORD,
2945         /*  68  "D" */ CWORD_CWORD_CWORD_CWORD,
2946         /*  69  "E" */ CWORD_CWORD_CWORD_CWORD,
2947         /*  70  "F" */ CWORD_CWORD_CWORD_CWORD,
2948         /*  71  "G" */ CWORD_CWORD_CWORD_CWORD,
2949         /*  72  "H" */ CWORD_CWORD_CWORD_CWORD,
2950         /*  73  "I" */ CWORD_CWORD_CWORD_CWORD,
2951         /*  74  "J" */ CWORD_CWORD_CWORD_CWORD,
2952         /*  75  "K" */ CWORD_CWORD_CWORD_CWORD,
2953         /*  76  "L" */ CWORD_CWORD_CWORD_CWORD,
2954         /*  77  "M" */ CWORD_CWORD_CWORD_CWORD,
2955         /*  78  "N" */ CWORD_CWORD_CWORD_CWORD,
2956         /*  79  "O" */ CWORD_CWORD_CWORD_CWORD,
2957         /*  80  "P" */ CWORD_CWORD_CWORD_CWORD,
2958         /*  81  "Q" */ CWORD_CWORD_CWORD_CWORD,
2959         /*  82  "R" */ CWORD_CWORD_CWORD_CWORD,
2960         /*  83  "S" */ CWORD_CWORD_CWORD_CWORD,
2961         /*  84  "T" */ CWORD_CWORD_CWORD_CWORD,
2962         /*  85  "U" */ CWORD_CWORD_CWORD_CWORD,
2963         /*  86  "V" */ CWORD_CWORD_CWORD_CWORD,
2964         /*  87  "W" */ CWORD_CWORD_CWORD_CWORD,
2965         /*  88  "X" */ CWORD_CWORD_CWORD_CWORD,
2966         /*  89  "Y" */ CWORD_CWORD_CWORD_CWORD,
2967         /*  90  "Z" */ CWORD_CWORD_CWORD_CWORD,
2968         /*  91  "[" */ CWORD_CCTL_CCTL_CWORD,
2969         /*  92  "\" */ CBACK_CBACK_CCTL_CBACK,
2970         /*  93  "]" */ CWORD_CCTL_CCTL_CWORD,
2971         /*  94  "^" */ CWORD_CWORD_CWORD_CWORD,
2972         /*  95  "_" */ CWORD_CWORD_CWORD_CWORD,
2973         /*  96  "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2974         /*  97  "a" */ CWORD_CWORD_CWORD_CWORD,
2975         /*  98  "b" */ CWORD_CWORD_CWORD_CWORD,
2976         /*  99  "c" */ CWORD_CWORD_CWORD_CWORD,
2977         /* 100  "d" */ CWORD_CWORD_CWORD_CWORD,
2978         /* 101  "e" */ CWORD_CWORD_CWORD_CWORD,
2979         /* 102  "f" */ CWORD_CWORD_CWORD_CWORD,
2980         /* 103  "g" */ CWORD_CWORD_CWORD_CWORD,
2981         /* 104  "h" */ CWORD_CWORD_CWORD_CWORD,
2982         /* 105  "i" */ CWORD_CWORD_CWORD_CWORD,
2983         /* 106  "j" */ CWORD_CWORD_CWORD_CWORD,
2984         /* 107  "k" */ CWORD_CWORD_CWORD_CWORD,
2985         /* 108  "l" */ CWORD_CWORD_CWORD_CWORD,
2986         /* 109  "m" */ CWORD_CWORD_CWORD_CWORD,
2987         /* 110  "n" */ CWORD_CWORD_CWORD_CWORD,
2988         /* 111  "o" */ CWORD_CWORD_CWORD_CWORD,
2989         /* 112  "p" */ CWORD_CWORD_CWORD_CWORD,
2990         /* 113  "q" */ CWORD_CWORD_CWORD_CWORD,
2991         /* 114  "r" */ CWORD_CWORD_CWORD_CWORD,
2992         /* 115  "s" */ CWORD_CWORD_CWORD_CWORD,
2993         /* 116  "t" */ CWORD_CWORD_CWORD_CWORD,
2994         /* 117  "u" */ CWORD_CWORD_CWORD_CWORD,
2995         /* 118  "v" */ CWORD_CWORD_CWORD_CWORD,
2996         /* 119  "w" */ CWORD_CWORD_CWORD_CWORD,
2997         /* 120  "x" */ CWORD_CWORD_CWORD_CWORD,
2998         /* 121  "y" */ CWORD_CWORD_CWORD_CWORD,
2999         /* 122  "z" */ CWORD_CWORD_CWORD_CWORD,
3000         /* 123  "{" */ CWORD_CWORD_CWORD_CWORD,
3001         /* 124  "|" */ CSPCL_CWORD_CWORD_CWORD,
3002         /* 125  "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3003         /* 126  "~" */ CWORD_CCTL_CCTL_CWORD,
3004         /* 127  del */ CWORD_CWORD_CWORD_CWORD,
3005         /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3006         /* 129 CTLESC       */ CCTL_CCTL_CCTL_CCTL,
3007         /* 130 CTLVAR       */ CCTL_CCTL_CCTL_CCTL,
3008         /* 131 CTLENDVAR    */ CCTL_CCTL_CCTL_CCTL,
3009         /* 132 CTLBACKQ     */ CCTL_CCTL_CCTL_CCTL,
3010         /* 133 CTLQUOTE     */ CCTL_CCTL_CCTL_CCTL,
3011         /* 134 CTLARI       */ CCTL_CCTL_CCTL_CCTL,
3012         /* 135 CTLENDARI    */ CCTL_CCTL_CCTL_CCTL,
3013         /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3014         /* 137      */ CWORD_CWORD_CWORD_CWORD,
3015         /* 138      */ CWORD_CWORD_CWORD_CWORD,
3016         /* 139      */ CWORD_CWORD_CWORD_CWORD,
3017         /* 140      */ CWORD_CWORD_CWORD_CWORD,
3018         /* 141      */ CWORD_CWORD_CWORD_CWORD,
3019         /* 142      */ CWORD_CWORD_CWORD_CWORD,
3020         /* 143      */ CWORD_CWORD_CWORD_CWORD,
3021         /* 144      */ CWORD_CWORD_CWORD_CWORD,
3022         /* 145      */ CWORD_CWORD_CWORD_CWORD,
3023         /* 146      */ CWORD_CWORD_CWORD_CWORD,
3024         /* 147      */ CWORD_CWORD_CWORD_CWORD,
3025         /* 148      */ CWORD_CWORD_CWORD_CWORD,
3026         /* 149      */ CWORD_CWORD_CWORD_CWORD,
3027         /* 150      */ CWORD_CWORD_CWORD_CWORD,
3028         /* 151      */ CWORD_CWORD_CWORD_CWORD,
3029         /* 152      */ CWORD_CWORD_CWORD_CWORD,
3030         /* 153      */ CWORD_CWORD_CWORD_CWORD,
3031         /* 154      */ CWORD_CWORD_CWORD_CWORD,
3032         /* 155      */ CWORD_CWORD_CWORD_CWORD,
3033         /* 156      */ CWORD_CWORD_CWORD_CWORD,
3034         /* 157      */ CWORD_CWORD_CWORD_CWORD,
3035         /* 158      */ CWORD_CWORD_CWORD_CWORD,
3036         /* 159      */ CWORD_CWORD_CWORD_CWORD,
3037         /* 160      */ CWORD_CWORD_CWORD_CWORD,
3038         /* 161      */ CWORD_CWORD_CWORD_CWORD,
3039         /* 162      */ CWORD_CWORD_CWORD_CWORD,
3040         /* 163      */ CWORD_CWORD_CWORD_CWORD,
3041         /* 164      */ CWORD_CWORD_CWORD_CWORD,
3042         /* 165      */ CWORD_CWORD_CWORD_CWORD,
3043         /* 166      */ CWORD_CWORD_CWORD_CWORD,
3044         /* 167      */ CWORD_CWORD_CWORD_CWORD,
3045         /* 168      */ CWORD_CWORD_CWORD_CWORD,
3046         /* 169      */ CWORD_CWORD_CWORD_CWORD,
3047         /* 170      */ CWORD_CWORD_CWORD_CWORD,
3048         /* 171      */ CWORD_CWORD_CWORD_CWORD,
3049         /* 172      */ CWORD_CWORD_CWORD_CWORD,
3050         /* 173      */ CWORD_CWORD_CWORD_CWORD,
3051         /* 174      */ CWORD_CWORD_CWORD_CWORD,
3052         /* 175      */ CWORD_CWORD_CWORD_CWORD,
3053         /* 176      */ CWORD_CWORD_CWORD_CWORD,
3054         /* 177      */ CWORD_CWORD_CWORD_CWORD,
3055         /* 178      */ CWORD_CWORD_CWORD_CWORD,
3056         /* 179      */ CWORD_CWORD_CWORD_CWORD,
3057         /* 180      */ CWORD_CWORD_CWORD_CWORD,
3058         /* 181      */ CWORD_CWORD_CWORD_CWORD,
3059         /* 182      */ CWORD_CWORD_CWORD_CWORD,
3060         /* 183      */ CWORD_CWORD_CWORD_CWORD,
3061         /* 184      */ CWORD_CWORD_CWORD_CWORD,
3062         /* 185      */ CWORD_CWORD_CWORD_CWORD,
3063         /* 186      */ CWORD_CWORD_CWORD_CWORD,
3064         /* 187      */ CWORD_CWORD_CWORD_CWORD,
3065         /* 188      */ CWORD_CWORD_CWORD_CWORD,
3066         /* 189      */ CWORD_CWORD_CWORD_CWORD,
3067         /* 190      */ CWORD_CWORD_CWORD_CWORD,
3068         /* 191      */ CWORD_CWORD_CWORD_CWORD,
3069         /* 192      */ CWORD_CWORD_CWORD_CWORD,
3070         /* 193      */ CWORD_CWORD_CWORD_CWORD,
3071         /* 194      */ CWORD_CWORD_CWORD_CWORD,
3072         /* 195      */ CWORD_CWORD_CWORD_CWORD,
3073         /* 196      */ CWORD_CWORD_CWORD_CWORD,
3074         /* 197      */ CWORD_CWORD_CWORD_CWORD,
3075         /* 198      */ CWORD_CWORD_CWORD_CWORD,
3076         /* 199      */ CWORD_CWORD_CWORD_CWORD,
3077         /* 200      */ CWORD_CWORD_CWORD_CWORD,
3078         /* 201      */ CWORD_CWORD_CWORD_CWORD,
3079         /* 202      */ CWORD_CWORD_CWORD_CWORD,
3080         /* 203      */ CWORD_CWORD_CWORD_CWORD,
3081         /* 204      */ CWORD_CWORD_CWORD_CWORD,
3082         /* 205      */ CWORD_CWORD_CWORD_CWORD,
3083         /* 206      */ CWORD_CWORD_CWORD_CWORD,
3084         /* 207      */ CWORD_CWORD_CWORD_CWORD,
3085         /* 208      */ CWORD_CWORD_CWORD_CWORD,
3086         /* 209      */ CWORD_CWORD_CWORD_CWORD,
3087         /* 210      */ CWORD_CWORD_CWORD_CWORD,
3088         /* 211      */ CWORD_CWORD_CWORD_CWORD,
3089         /* 212      */ CWORD_CWORD_CWORD_CWORD,
3090         /* 213      */ CWORD_CWORD_CWORD_CWORD,
3091         /* 214      */ CWORD_CWORD_CWORD_CWORD,
3092         /* 215      */ CWORD_CWORD_CWORD_CWORD,
3093         /* 216      */ CWORD_CWORD_CWORD_CWORD,
3094         /* 217      */ CWORD_CWORD_CWORD_CWORD,
3095         /* 218      */ CWORD_CWORD_CWORD_CWORD,
3096         /* 219      */ CWORD_CWORD_CWORD_CWORD,
3097         /* 220      */ CWORD_CWORD_CWORD_CWORD,
3098         /* 221      */ CWORD_CWORD_CWORD_CWORD,
3099         /* 222      */ CWORD_CWORD_CWORD_CWORD,
3100         /* 223      */ CWORD_CWORD_CWORD_CWORD,
3101         /* 224      */ CWORD_CWORD_CWORD_CWORD,
3102         /* 225      */ CWORD_CWORD_CWORD_CWORD,
3103         /* 226      */ CWORD_CWORD_CWORD_CWORD,
3104         /* 227      */ CWORD_CWORD_CWORD_CWORD,
3105         /* 228      */ CWORD_CWORD_CWORD_CWORD,
3106         /* 229      */ CWORD_CWORD_CWORD_CWORD,
3107         /* 230      */ CWORD_CWORD_CWORD_CWORD,
3108         /* 231      */ CWORD_CWORD_CWORD_CWORD,
3109         /* 232      */ CWORD_CWORD_CWORD_CWORD,
3110         /* 233      */ CWORD_CWORD_CWORD_CWORD,
3111         /* 234      */ CWORD_CWORD_CWORD_CWORD,
3112         /* 235      */ CWORD_CWORD_CWORD_CWORD,
3113         /* 236      */ CWORD_CWORD_CWORD_CWORD,
3114         /* 237      */ CWORD_CWORD_CWORD_CWORD,
3115         /* 238      */ CWORD_CWORD_CWORD_CWORD,
3116         /* 239      */ CWORD_CWORD_CWORD_CWORD,
3117         /* 230      */ CWORD_CWORD_CWORD_CWORD,
3118         /* 241      */ CWORD_CWORD_CWORD_CWORD,
3119         /* 242      */ CWORD_CWORD_CWORD_CWORD,
3120         /* 243      */ CWORD_CWORD_CWORD_CWORD,
3121         /* 244      */ CWORD_CWORD_CWORD_CWORD,
3122         /* 245      */ CWORD_CWORD_CWORD_CWORD,
3123         /* 246      */ CWORD_CWORD_CWORD_CWORD,
3124         /* 247      */ CWORD_CWORD_CWORD_CWORD,
3125         /* 248      */ CWORD_CWORD_CWORD_CWORD,
3126         /* 249      */ CWORD_CWORD_CWORD_CWORD,
3127         /* 250      */ CWORD_CWORD_CWORD_CWORD,
3128         /* 251      */ CWORD_CWORD_CWORD_CWORD,
3129         /* 252      */ CWORD_CWORD_CWORD_CWORD,
3130         /* 253      */ CWORD_CWORD_CWORD_CWORD,
3131         /* 254      */ CWORD_CWORD_CWORD_CWORD,
3132         /* 255      */ CWORD_CWORD_CWORD_CWORD,
3133         /* PEOF */     CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3134 # if ENABLE_ASH_ALIAS
3135         /* PEOA */     CSPCL_CIGN_CIGN_CIGN,
3136 # endif
3137 };
3138
3139 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3140
3141 #endif  /* !USE_SIT_FUNCTION */
3142
3143
3144 /* ============ Alias handling */
3145
3146 #if ENABLE_ASH_ALIAS
3147
3148 #define ALIASINUSE 1
3149 #define ALIASDEAD  2
3150
3151 struct alias {
3152         struct alias *next;
3153         char *name;
3154         char *val;
3155         int flag;
3156 };
3157
3158
3159 static struct alias **atab; // [ATABSIZE];
3160 #define INIT_G_alias() do { \
3161         atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3162 } while (0)
3163
3164
3165 static struct alias **
3166 __lookupalias(const char *name)
3167 {
3168         unsigned int hashval;
3169         struct alias **app;
3170         const char *p;
3171         unsigned int ch;
3172
3173         p = name;
3174
3175         ch = (unsigned char)*p;
3176         hashval = ch << 4;
3177         while (ch) {
3178                 hashval += ch;
3179                 ch = (unsigned char)*++p;
3180         }
3181         app = &atab[hashval % ATABSIZE];
3182
3183         for (; *app; app = &(*app)->next) {
3184                 if (strcmp(name, (*app)->name) == 0) {
3185                         break;
3186                 }
3187         }
3188
3189         return app;
3190 }
3191
3192 static struct alias *
3193 lookupalias(const char *name, int check)
3194 {
3195         struct alias *ap = *__lookupalias(name);
3196
3197         if (check && ap && (ap->flag & ALIASINUSE))
3198                 return NULL;
3199         return ap;
3200 }
3201
3202 static struct alias *
3203 freealias(struct alias *ap)
3204 {
3205         struct alias *next;
3206
3207         if (ap->flag & ALIASINUSE) {
3208                 ap->flag |= ALIASDEAD;
3209                 return ap;
3210         }
3211
3212         next = ap->next;
3213         free(ap->name);
3214         free(ap->val);
3215         free(ap);
3216         return next;
3217 }
3218
3219 static void
3220 setalias(const char *name, const char *val)
3221 {
3222         struct alias *ap, **app;
3223
3224         app = __lookupalias(name);
3225         ap = *app;
3226         INT_OFF;
3227         if (ap) {
3228                 if (!(ap->flag & ALIASINUSE)) {
3229                         free(ap->val);
3230                 }
3231                 ap->val = ckstrdup(val);
3232                 ap->flag &= ~ALIASDEAD;
3233         } else {
3234                 /* not found */
3235                 ap = ckzalloc(sizeof(struct alias));
3236                 ap->name = ckstrdup(name);
3237                 ap->val = ckstrdup(val);
3238                 /*ap->flag = 0; - ckzalloc did it */
3239                 /*ap->next = NULL;*/
3240                 *app = ap;
3241         }
3242         INT_ON;
3243 }
3244
3245 static int
3246 unalias(const char *name)
3247 {
3248         struct alias **app;
3249
3250         app = __lookupalias(name);
3251
3252         if (*app) {
3253                 INT_OFF;
3254                 *app = freealias(*app);
3255                 INT_ON;
3256                 return 0;
3257         }
3258
3259         return 1;
3260 }
3261
3262 static void
3263 rmaliases(void)
3264 {
3265         struct alias *ap, **app;
3266         int i;
3267
3268         INT_OFF;
3269         for (i = 0; i < ATABSIZE; i++) {
3270                 app = &atab[i];
3271                 for (ap = *app; ap; ap = *app) {
3272                         *app = freealias(*app);
3273                         if (ap == *app) {
3274                                 app = &ap->next;
3275                         }
3276                 }
3277         }
3278         INT_ON;
3279 }
3280
3281 static void
3282 printalias(const struct alias *ap)
3283 {
3284         out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3285 }
3286
3287 /*
3288  * TODO - sort output
3289  */
3290 static int FAST_FUNC
3291 aliascmd(int argc UNUSED_PARAM, char **argv)
3292 {
3293         char *n, *v;
3294         int ret = 0;
3295         struct alias *ap;
3296
3297         if (!argv[1]) {
3298                 int i;
3299
3300                 for (i = 0; i < ATABSIZE; i++) {
3301                         for (ap = atab[i]; ap; ap = ap->next) {
3302                                 printalias(ap);
3303                         }
3304                 }
3305                 return 0;
3306         }
3307         while ((n = *++argv) != NULL) {
3308                 v = strchr(n+1, '=');
3309                 if (v == NULL) { /* n+1: funny ksh stuff */
3310                         ap = *__lookupalias(n);
3311                         if (ap == NULL) {
3312                                 fprintf(stderr, "%s: %s not found\n", "alias", n);
3313                                 ret = 1;
3314                         } else
3315                                 printalias(ap);
3316                 } else {
3317                         *v++ = '\0';
3318                         setalias(n, v);
3319                 }
3320         }
3321
3322         return ret;
3323 }
3324
3325 static int FAST_FUNC
3326 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3327 {
3328         int i;
3329
3330         while ((i = nextopt("a")) != '\0') {
3331                 if (i == 'a') {
3332                         rmaliases();
3333                         return 0;
3334                 }
3335         }
3336         for (i = 0; *argptr; argptr++) {
3337                 if (unalias(*argptr)) {
3338                         fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3339                         i = 1;
3340                 }
3341         }
3342
3343         return i;
3344 }
3345
3346 #endif /* ASH_ALIAS */
3347
3348
3349 /* Mode argument to forkshell.  Don't change FORK_FG or FORK_BG. */
3350 #define FORK_FG    0
3351 #define FORK_BG    1
3352 #define FORK_NOJOB 2
3353
3354 /* mode flags for showjob(s) */
3355 #define SHOW_ONLY_PGID  0x01    /* show only pgid (jobs -p) */
3356 #define SHOW_PIDS       0x02    /* show individual pids, not just one line per job */
3357 #define SHOW_CHANGED    0x04    /* only jobs whose state has changed */
3358 #define SHOW_STDERR     0x08    /* print to stderr (else stdout) */
3359
3360 /*
3361  * A job structure contains information about a job.  A job is either a
3362  * single process or a set of processes contained in a pipeline.  In the
3363  * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3364  * array of pids.
3365  */
3366 struct procstat {
3367         pid_t   ps_pid;         /* process id */
3368         int     ps_status;      /* last process status from wait() */
3369         char    *ps_cmd;        /* text of command being run */
3370 };
3371
3372 struct job {
3373         struct procstat ps0;    /* status of process */
3374         struct procstat *ps;    /* status or processes when more than one */
3375 #if JOBS
3376         int stopstatus;         /* status of a stopped job */
3377 #endif
3378         uint32_t
3379                 nprocs: 16,     /* number of processes */
3380                 state: 8,
3381 #define JOBRUNNING      0       /* at least one proc running */
3382 #define JOBSTOPPED      1       /* all procs are stopped */
3383 #define JOBDONE         2       /* all procs are completed */
3384 #if JOBS
3385                 sigint: 1,      /* job was killed by SIGINT */
3386                 jobctl: 1,      /* job running under job control */
3387 #endif
3388                 waited: 1,      /* true if this entry has been waited for */
3389                 used: 1,        /* true if this entry is in used */
3390                 changed: 1;     /* true if status has changed */
3391         struct job *prev_job;   /* previous job */
3392 };
3393
3394 static struct job *makejob(/*union node *,*/ int);
3395 static int forkshell(struct job *, union node *, int);
3396 static int waitforjob(struct job *);
3397
3398 #if !JOBS
3399 enum { doing_jobctl = 0 };
3400 #define setjobctl(on) do {} while (0)
3401 #else
3402 static smallint doing_jobctl; //references:8
3403 static void setjobctl(int);
3404 #endif
3405
3406 /*
3407  * Ignore a signal.
3408  */
3409 static void
3410 ignoresig(int signo)
3411 {
3412         /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3413         if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3414                 /* No, need to do it */
3415                 signal(signo, SIG_IGN);
3416         }
3417         sigmode[signo - 1] = S_HARD_IGN;
3418 }
3419
3420 /*
3421  * Only one usage site - in setsignal()
3422  */
3423 static void
3424 signal_handler(int signo)
3425 {
3426         gotsig[signo - 1] = 1;
3427
3428         if (signo == SIGINT && !trap[SIGINT]) {
3429                 if (!suppress_int) {
3430                         pending_sig = 0;
3431                         raise_interrupt(); /* does not return */
3432                 }
3433                 pending_int = 1;
3434         } else {
3435                 pending_sig = signo;
3436         }
3437 }
3438
3439 /*
3440  * Set the signal handler for the specified signal.  The routine figures
3441  * out what it should be set to.
3442  */
3443 static void
3444 setsignal(int signo)
3445 {
3446         char *t;
3447         char cur_act, new_act;
3448         struct sigaction act;
3449
3450         t = trap[signo];
3451         new_act = S_DFL;
3452         if (t != NULL) { /* trap for this sig is set */
3453                 new_act = S_CATCH;
3454                 if (t[0] == '\0') /* trap is "": ignore this sig */
3455                         new_act = S_IGN;
3456         }
3457
3458         if (rootshell && new_act == S_DFL) {
3459                 switch (signo) {
3460                 case SIGINT:
3461                         if (iflag || minusc || sflag == 0)
3462                                 new_act = S_CATCH;
3463                         break;
3464                 case SIGQUIT:
3465 #if DEBUG
3466                         if (debug)
3467                                 break;
3468 #endif
3469                         /* man bash:
3470                          * "In all cases, bash ignores SIGQUIT. Non-builtin
3471                          * commands run by bash have signal handlers
3472                          * set to the values inherited by the shell
3473                          * from its parent". */
3474                         new_act = S_IGN;
3475                         break;
3476                 case SIGTERM:
3477                         if (iflag)
3478                                 new_act = S_IGN;
3479                         break;
3480 #if JOBS
3481                 case SIGTSTP:
3482                 case SIGTTOU:
3483                         if (mflag)
3484                                 new_act = S_IGN;
3485                         break;
3486 #endif
3487                 }
3488         }
3489 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3490 //whereas we have to restore it to what shell got on entry
3491 //from the parent. See comment above
3492
3493         t = &sigmode[signo - 1];
3494         cur_act = *t;
3495         if (cur_act == 0) {
3496                 /* current setting is not yet known */
3497                 if (sigaction(signo, NULL, &act)) {
3498                         /* pretend it worked; maybe we should give a warning,
3499                          * but other shells don't. We don't alter sigmode,
3500                          * so we retry every time.
3501                          * btw, in Linux it never fails. --vda */
3502                         return;
3503                 }
3504                 if (act.sa_handler == SIG_IGN) {
3505                         cur_act = S_HARD_IGN;
3506                         if (mflag
3507                          && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3508                         ) {
3509                                 cur_act = S_IGN;   /* don't hard ignore these */
3510                         }
3511                 }
3512         }
3513         if (cur_act == S_HARD_IGN || cur_act == new_act)
3514                 return;
3515
3516         act.sa_handler = SIG_DFL;
3517         switch (new_act) {
3518         case S_CATCH:
3519                 act.sa_handler = signal_handler;
3520                 break;
3521         case S_IGN:
3522                 act.sa_handler = SIG_IGN;
3523                 break;
3524         }
3525
3526         /* flags and mask matter only if !DFL and !IGN, but we do it
3527          * for all cases for more deterministic behavior:
3528          */
3529         act.sa_flags = 0;
3530         sigfillset(&act.sa_mask);
3531
3532         sigaction_set(signo, &act);
3533
3534         *t = new_act;
3535 }
3536
3537 /* mode flags for set_curjob */
3538 #define CUR_DELETE 2
3539 #define CUR_RUNNING 1
3540 #define CUR_STOPPED 0
3541
3542 /* mode flags for dowait */
3543 #define DOWAIT_NONBLOCK WNOHANG
3544 #define DOWAIT_BLOCK    0
3545
3546 #if JOBS
3547 /* pgrp of shell on invocation */
3548 static int initialpgrp; //references:2
3549 static int ttyfd = -1; //5
3550 #endif
3551 /* array of jobs */
3552 static struct job *jobtab; //5
3553 /* size of array */
3554 static unsigned njobs; //4
3555 /* current job */
3556 static struct job *curjob; //lots
3557 /* number of presumed living untracked jobs */
3558 static int jobless; //4
3559
3560 static void
3561 set_curjob(struct job *jp, unsigned mode)
3562 {
3563         struct job *jp1;
3564         struct job **jpp, **curp;
3565
3566         /* first remove from list */
3567         jpp = curp = &curjob;
3568         while (1) {
3569                 jp1 = *jpp;
3570                 if (jp1 == jp)
3571                         break;
3572                 jpp = &jp1->prev_job;
3573         }
3574         *jpp = jp1->prev_job;
3575
3576         /* Then re-insert in correct position */
3577         jpp = curp;
3578         switch (mode) {
3579         default:
3580 #if DEBUG
3581                 abort();
3582 #endif
3583         case CUR_DELETE:
3584                 /* job being deleted */
3585                 break;
3586         case CUR_RUNNING:
3587                 /* newly created job or backgrounded job,
3588                  * put after all stopped jobs.
3589                  */
3590                 while (1) {
3591                         jp1 = *jpp;
3592 #if JOBS
3593                         if (!jp1 || jp1->state != JOBSTOPPED)
3594 #endif
3595                                 break;
3596                         jpp = &jp1->prev_job;
3597                 }
3598                 /* FALLTHROUGH */
3599 #if JOBS
3600         case CUR_STOPPED:
3601 #endif
3602                 /* newly stopped job - becomes curjob */
3603                 jp->prev_job = *jpp;
3604                 *jpp = jp;
3605                 break;
3606         }
3607 }
3608
3609 #if JOBS || DEBUG
3610 static int
3611 jobno(const struct job *jp)
3612 {
3613         return jp - jobtab + 1;
3614 }
3615 #endif
3616
3617 /*
3618  * Convert a job name to a job structure.
3619  */
3620 #if !JOBS
3621 #define getjob(name, getctl) getjob(name)
3622 #endif
3623 static struct job *
3624 getjob(const char *name, int getctl)
3625 {
3626         struct job *jp;
3627         struct job *found;
3628         const char *err_msg = "%s: no such job";
3629         unsigned num;
3630         int c;
3631         const char *p;
3632         char *(*match)(const char *, const char *);
3633
3634         jp = curjob;
3635         p = name;
3636         if (!p)
3637                 goto currentjob;
3638
3639         if (*p != '%')
3640                 goto err;
3641
3642         c = *++p;
3643         if (!c)
3644                 goto currentjob;
3645
3646         if (!p[1]) {
3647                 if (c == '+' || c == '%') {
3648  currentjob:
3649                         err_msg = "No current job";
3650                         goto check;
3651                 }
3652                 if (c == '-') {
3653                         if (jp)
3654                                 jp = jp->prev_job;
3655                         err_msg = "No previous job";
3656  check:
3657                         if (!jp)
3658                                 goto err;
3659                         goto gotit;
3660                 }
3661         }
3662
3663         if (is_number(p)) {
3664                 num = atoi(p);
3665                 if (num > 0 && num <= njobs) {
3666                         jp = jobtab + num - 1;
3667                         if (jp->used)
3668                                 goto gotit;
3669                         goto err;
3670                 }
3671         }
3672
3673         match = prefix;
3674         if (*p == '?') {
3675                 match = strstr;
3676                 p++;
3677         }
3678
3679         found = NULL;
3680         while (jp) {
3681                 if (match(jp->ps[0].ps_cmd, p)) {
3682                         if (found)
3683                                 goto err;
3684                         found = jp;
3685                         err_msg = "%s: ambiguous";
3686                 }
3687                 jp = jp->prev_job;
3688         }
3689         if (!found)
3690                 goto err;
3691         jp = found;
3692
3693  gotit:
3694 #if JOBS
3695         err_msg = "job %s not created under job control";
3696         if (getctl && jp->jobctl == 0)
3697                 goto err;
3698 #endif
3699         return jp;
3700  err:
3701         ash_msg_and_raise_error(err_msg, name);
3702 }
3703
3704 /*
3705  * Mark a job structure as unused.
3706  */
3707 static void
3708 freejob(struct job *jp)
3709 {
3710         struct procstat *ps;
3711         int i;
3712
3713         INT_OFF;
3714         for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3715                 if (ps->ps_cmd != nullstr)
3716                         free(ps->ps_cmd);
3717         }
3718         if (jp->ps != &jp->ps0)
3719                 free(jp->ps);
3720         jp->used = 0;
3721         set_curjob(jp, CUR_DELETE);
3722         INT_ON;
3723 }
3724
3725 #if JOBS
3726 static void
3727 xtcsetpgrp(int fd, pid_t pgrp)
3728 {
3729         if (tcsetpgrp(fd, pgrp))
3730                 ash_msg_and_raise_error("can't set tty process group (%m)");
3731 }
3732
3733 /*
3734  * Turn job control on and off.
3735  *
3736  * Note:  This code assumes that the third arg to ioctl is a character
3737  * pointer, which is true on Berkeley systems but not System V.  Since
3738  * System V doesn't have job control yet, this isn't a problem now.
3739  *
3740  * Called with interrupts off.
3741  */
3742 static void
3743 setjobctl(int on)
3744 {
3745         int fd;
3746         int pgrp;
3747
3748         if (on == doing_jobctl || rootshell == 0)
3749                 return;
3750         if (on) {
3751                 int ofd;
3752                 ofd = fd = open(_PATH_TTY, O_RDWR);
3753                 if (fd < 0) {
3754         /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3755          * That sometimes helps to acquire controlling tty.
3756          * Obviously, a workaround for bugs when someone
3757          * failed to provide a controlling tty to bash! :) */
3758                         fd = 2;
3759                         while (!isatty(fd))
3760                                 if (--fd < 0)
3761                                         goto out;
3762                 }
3763                 fd = fcntl(fd, F_DUPFD, 10);
3764                 if (ofd >= 0)
3765                         close(ofd);
3766                 if (fd < 0)
3767                         goto out;
3768                 /* fd is a tty at this point */
3769                 close_on_exec_on(fd);
3770                 while (1) { /* while we are in the background */
3771                         pgrp = tcgetpgrp(fd);
3772                         if (pgrp < 0) {
3773  out:
3774                                 ash_msg("can't access tty; job control turned off");
3775                                 mflag = on = 0;
3776                                 goto close;
3777                         }
3778                         if (pgrp == getpgrp())
3779                                 break;
3780                         killpg(0, SIGTTIN);
3781                 }
3782                 initialpgrp = pgrp;
3783
3784                 setsignal(SIGTSTP);
3785                 setsignal(SIGTTOU);
3786                 setsignal(SIGTTIN);
3787                 pgrp = rootpid;
3788                 setpgid(0, pgrp);
3789                 xtcsetpgrp(fd, pgrp);
3790         } else {
3791                 /* turning job control off */
3792                 fd = ttyfd;
3793                 pgrp = initialpgrp;
3794                 /* was xtcsetpgrp, but this can make exiting ash
3795                  * loop forever if pty is already deleted */
3796                 tcsetpgrp(fd, pgrp);
3797                 setpgid(0, pgrp);
3798                 setsignal(SIGTSTP);
3799                 setsignal(SIGTTOU);
3800                 setsignal(SIGTTIN);
3801  close:
3802                 if (fd >= 0)
3803                         close(fd);
3804                 fd = -1;
3805         }
3806         ttyfd = fd;
3807         doing_jobctl = on;
3808 }
3809
3810 static int FAST_FUNC
3811 killcmd(int argc, char **argv)
3812 {
3813         if (argv[1] && strcmp(argv[1], "-l") != 0) {
3814                 int i = 1;
3815                 do {
3816                         if (argv[i][0] == '%') {
3817                                 /*
3818                                  * "kill %N" - job kill
3819                                  * Converting to pgrp / pid kill
3820                                  */
3821                                 struct job *jp;
3822                                 char *dst;
3823                                 int j, n;
3824
3825                                 jp = getjob(argv[i], 0);
3826                                 /*
3827                                  * In jobs started under job control, we signal
3828                                  * entire process group by kill -PGRP_ID.
3829                                  * This happens, f.e., in interactive shell.
3830                                  *
3831                                  * Otherwise, we signal each child via
3832                                  * kill PID1 PID2 PID3.
3833                                  * Testcases:
3834                                  * sh -c 'sleep 1|sleep 1 & kill %1'
3835                                  * sh -c 'true|sleep 2 & sleep 1; kill %1'
3836                                  * sh -c 'true|sleep 1 & sleep 2; kill %1'
3837                                  */
3838                                 n = jp->nprocs; /* can't be 0 (I hope) */
3839                                 if (jp->jobctl)
3840                                         n = 1;
3841                                 dst = alloca(n * sizeof(int)*4);
3842                                 argv[i] = dst;
3843                                 for (j = 0; j < n; j++) {
3844                                         struct procstat *ps = &jp->ps[j];
3845                                         /* Skip non-running and not-stopped members
3846                                          * (i.e. dead members) of the job
3847                                          */
3848                                         if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3849                                                 continue;
3850                                         /*
3851                                          * kill_main has matching code to expect
3852                                          * leading space. Needed to not confuse
3853                                          * negative pids with "kill -SIGNAL_NO" syntax
3854                                          */
3855                                         dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3856                                 }
3857                                 *dst = '\0';
3858                         }
3859                 } while (argv[++i]);
3860         }
3861         return kill_main(argc, argv);
3862 }
3863
3864 static void
3865 showpipe(struct job *jp /*, FILE *out*/)
3866 {
3867         struct procstat *ps;
3868         struct procstat *psend;
3869
3870         psend = jp->ps + jp->nprocs;
3871         for (ps = jp->ps + 1; ps < psend; ps++)
3872                 printf(" | %s", ps->ps_cmd);
3873         newline_and_flush(stdout);
3874         flush_stdout_stderr();
3875 }
3876
3877
3878 static int
3879 restartjob(struct job *jp, int mode)
3880 {
3881         struct procstat *ps;
3882         int i;
3883         int status;
3884         pid_t pgid;
3885
3886         INT_OFF;
3887         if (jp->state == JOBDONE)
3888                 goto out;
3889         jp->state = JOBRUNNING;
3890         pgid = jp->ps[0].ps_pid;
3891         if (mode == FORK_FG)
3892                 xtcsetpgrp(ttyfd, pgid);
3893         killpg(pgid, SIGCONT);
3894         ps = jp->ps;
3895         i = jp->nprocs;
3896         do {
3897                 if (WIFSTOPPED(ps->ps_status)) {
3898                         ps->ps_status = -1;
3899                 }
3900                 ps++;
3901         } while (--i);
3902  out:
3903         status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3904         INT_ON;
3905         return status;
3906 }
3907
3908 static int FAST_FUNC
3909 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3910 {
3911         struct job *jp;
3912         int mode;
3913         int retval;
3914
3915         mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3916         nextopt(nullstr);
3917         argv = argptr;
3918         do {
3919                 jp = getjob(*argv, 1);
3920                 if (mode == FORK_BG) {
3921                         set_curjob(jp, CUR_RUNNING);
3922                         printf("[%d] ", jobno(jp));
3923                 }
3924                 out1str(jp->ps[0].ps_cmd);
3925                 showpipe(jp /*, stdout*/);
3926                 retval = restartjob(jp, mode);
3927         } while (*argv && *++argv);
3928         return retval;
3929 }
3930 #endif
3931
3932 static int
3933 sprint_status48(char *s, int status, int sigonly)
3934 {
3935         int col;
3936         int st;
3937
3938         col = 0;
3939         if (!WIFEXITED(status)) {
3940                 if (JOBS && WIFSTOPPED(status))
3941                         st = WSTOPSIG(status);
3942                 else
3943                         st = WTERMSIG(status);
3944                 if (sigonly) {
3945                         if (st == SIGINT || st == SIGPIPE)
3946                                 goto out;
3947                         if (JOBS && WIFSTOPPED(status))
3948                                 goto out;
3949                 }
3950                 st &= 0x7f;
3951 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3952                 col = fmtstr(s, 32, strsignal(st));
3953                 if (WCOREDUMP(status)) {
3954                         strcpy(s + col, " (core dumped)");
3955                         col += sizeof(" (core dumped)")-1;
3956                 }
3957         } else if (!sigonly) {
3958                 st = WEXITSTATUS(status);
3959                 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3960         }
3961  out:
3962         return col;
3963 }
3964
3965 static int
3966 dowait(int wait_flags, struct job *job)
3967 {
3968         int pid;
3969         int status;
3970         struct job *jp;
3971         struct job *thisjob;
3972
3973         TRACE(("dowait(0x%x) called\n", wait_flags));
3974
3975         /* Do a wait system call. If job control is compiled in, we accept
3976          * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3977          * NB: _not_ safe_waitpid, we need to detect EINTR */
3978         if (doing_jobctl)
3979                 wait_flags |= WUNTRACED;
3980         pid = waitpid(-1, &status, wait_flags);
3981         TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3982                                 pid, status, errno, strerror(errno)));
3983         if (pid <= 0)
3984                 return pid;
3985
3986         INT_OFF;
3987         thisjob = NULL;
3988         for (jp = curjob; jp; jp = jp->prev_job) {
3989                 int jobstate;
3990                 struct procstat *ps;
3991                 struct procstat *psend;
3992                 if (jp->state == JOBDONE)
3993                         continue;
3994                 jobstate = JOBDONE;
3995                 ps = jp->ps;
3996                 psend = ps + jp->nprocs;
3997                 do {
3998                         if (ps->ps_pid == pid) {
3999                                 TRACE(("Job %d: changing status of proc %d "
4000                                         "from 0x%x to 0x%x\n",
4001                                         jobno(jp), pid, ps->ps_status, status));
4002                                 ps->ps_status = status;
4003                                 thisjob = jp;
4004                         }
4005                         if (ps->ps_status == -1)
4006                                 jobstate = JOBRUNNING;
4007 #if JOBS
4008                         if (jobstate == JOBRUNNING)
4009                                 continue;
4010                         if (WIFSTOPPED(ps->ps_status)) {
4011                                 jp->stopstatus = ps->ps_status;
4012                                 jobstate = JOBSTOPPED;
4013                         }
4014 #endif
4015                 } while (++ps < psend);
4016                 if (!thisjob)
4017                         continue;
4018
4019                 /* Found the job where one of its processes changed its state.
4020                  * Is there at least one live and running process in this job? */
4021                 if (jobstate != JOBRUNNING) {
4022                         /* No. All live processes in the job are stopped
4023                          * (JOBSTOPPED) or there are no live processes (JOBDONE)
4024                          */
4025                         thisjob->changed = 1;
4026                         if (thisjob->state != jobstate) {
4027                                 TRACE(("Job %d: changing state from %d to %d\n",
4028                                         jobno(thisjob), thisjob->state, jobstate));
4029                                 thisjob->state = jobstate;
4030 #if JOBS
4031                                 if (jobstate == JOBSTOPPED)
4032                                         set_curjob(thisjob, CUR_STOPPED);
4033 #endif
4034                         }
4035                 }
4036                 goto out;
4037         }
4038         /* The process wasn't found in job list */
4039         if (JOBS && !WIFSTOPPED(status))
4040                 jobless--;
4041  out:
4042         INT_ON;
4043
4044         if (thisjob && thisjob == job) {
4045                 char s[48 + 1];
4046                 int len;
4047
4048                 len = sprint_status48(s, status, 1);
4049                 if (len) {
4050                         s[len] = '\n';
4051                         s[len + 1] = '\0';
4052                         out2str(s);
4053                 }
4054         }
4055         return pid;
4056 }
4057
4058 static int
4059 blocking_wait_with_raise_on_sig(void)
4060 {
4061         pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4062         if (pid <= 0 && pending_sig)
4063                 raise_exception(EXSIG);
4064         return pid;
4065 }
4066
4067 #if JOBS
4068 static void
4069 showjob(struct job *jp, int mode)
4070 {
4071         struct procstat *ps;
4072         struct procstat *psend;
4073         int col;
4074         int indent_col;
4075         char s[16 + 16 + 48];
4076         FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4077
4078         ps = jp->ps;
4079
4080         if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4081                 /* just output process (group) id of pipeline */
4082                 fprintf(out, "%d\n", ps->ps_pid);
4083                 return;
4084         }
4085
4086         col = fmtstr(s, 16, "[%d]   ", jobno(jp));
4087         indent_col = col;
4088
4089         if (jp == curjob)
4090                 s[col - 3] = '+';
4091         else if (curjob && jp == curjob->prev_job)
4092                 s[col - 3] = '-';
4093
4094         if (mode & SHOW_PIDS)
4095                 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4096
4097         psend = ps + jp->nprocs;
4098
4099         if (jp->state == JOBRUNNING) {
4100                 strcpy(s + col, "Running");
4101                 col += sizeof("Running") - 1;
4102         } else {
4103                 int status = psend[-1].ps_status;
4104                 if (jp->state == JOBSTOPPED)
4105                         status = jp->stopstatus;
4106                 col += sprint_status48(s + col, status, 0);
4107         }
4108         /* By now, "[JOBID]*  [maybe PID] STATUS" is printed */
4109
4110         /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4111          * or prints several "PID             | <cmdN>" lines,
4112          * depending on SHOW_PIDS bit.
4113          * We do not print status of individual processes
4114          * between PID and <cmdN>. bash does it, but not very well:
4115          * first line shows overall job status, not process status,
4116          * making it impossible to know 1st process status.
4117          */
4118         goto start;
4119         do {
4120                 /* for each process */
4121                 s[0] = '\0';
4122                 col = 33;
4123                 if (mode & SHOW_PIDS)
4124                         col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4125  start:
4126                 fprintf(out, "%s%*c%s%s",
4127                                 s,
4128                                 33 - col >= 0 ? 33 - col : 0, ' ',
4129                                 ps == jp->ps ? "" : "| ",
4130                                 ps->ps_cmd
4131                 );
4132         } while (++ps != psend);
4133         newline_and_flush(out);
4134
4135         jp->changed = 0;
4136
4137         if (jp->state == JOBDONE) {
4138                 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4139                 freejob(jp);
4140         }
4141 }
4142
4143 /*
4144  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
4145  * statuses have changed since the last call to showjobs.
4146  */
4147 static void
4148 showjobs(int mode)
4149 {
4150         struct job *jp;
4151
4152         TRACE(("showjobs(0x%x) called\n", mode));
4153
4154         /* Handle all finished jobs */
4155         while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4156                 continue;
4157
4158         for (jp = curjob; jp; jp = jp->prev_job) {
4159                 if (!(mode & SHOW_CHANGED) || jp->changed) {
4160                         showjob(jp, mode);
4161                 }
4162         }
4163 }
4164
4165 static int FAST_FUNC
4166 jobscmd(int argc UNUSED_PARAM, char **argv)
4167 {
4168         int mode, m;
4169
4170         mode = 0;
4171         while ((m = nextopt("lp")) != '\0') {
4172                 if (m == 'l')
4173                         mode |= SHOW_PIDS;
4174                 else
4175                         mode |= SHOW_ONLY_PGID;
4176         }
4177
4178         argv = argptr;
4179         if (*argv) {
4180                 do
4181                         showjob(getjob(*argv, 0), mode);
4182                 while (*++argv);
4183         } else {
4184                 showjobs(mode);
4185         }
4186
4187         return 0;
4188 }
4189 #endif /* JOBS */
4190
4191 /* Called only on finished or stopped jobs (no members are running) */
4192 static int
4193 getstatus(struct job *job)
4194 {
4195         int status;
4196         int retval;
4197         struct procstat *ps;
4198
4199         /* Fetch last member's status */
4200         ps = job->ps + job->nprocs - 1;
4201         status = ps->ps_status;
4202         if (pipefail) {
4203                 /* "set -o pipefail" mode: use last _nonzero_ status */
4204                 while (status == 0 && --ps >= job->ps)
4205                         status = ps->ps_status;
4206         }
4207
4208         retval = WEXITSTATUS(status);
4209         if (!WIFEXITED(status)) {
4210 #if JOBS
4211                 retval = WSTOPSIG(status);
4212                 if (!WIFSTOPPED(status))
4213 #endif
4214                 {
4215                         /* XXX: limits number of signals */
4216                         retval = WTERMSIG(status);
4217 #if JOBS
4218                         if (retval == SIGINT)
4219                                 job->sigint = 1;
4220 #endif
4221                 }
4222                 retval += 128;
4223         }
4224         TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4225                 jobno(job), job->nprocs, status, retval));
4226         return retval;
4227 }
4228
4229 static int FAST_FUNC
4230 waitcmd(int argc UNUSED_PARAM, char **argv)
4231 {
4232         struct job *job;
4233         int retval;
4234         struct job *jp;
4235
4236         if (pending_sig)
4237                 raise_exception(EXSIG);
4238
4239         nextopt(nullstr);
4240         retval = 0;
4241
4242         argv = argptr;
4243         if (!*argv) {
4244                 /* wait for all jobs */
4245                 for (;;) {
4246                         jp = curjob;
4247                         while (1) {
4248                                 if (!jp) /* no running procs */
4249                                         goto ret;
4250                                 if (jp->state == JOBRUNNING)
4251                                         break;
4252                                 jp->waited = 1;
4253                                 jp = jp->prev_job;
4254                         }
4255                         blocking_wait_with_raise_on_sig();
4256         /* man bash:
4257          * "When bash is waiting for an asynchronous command via
4258          * the wait builtin, the reception of a signal for which a trap
4259          * has been set will cause the wait builtin to return immediately
4260          * with an exit status greater than 128, immediately after which
4261          * the trap is executed."
4262          *
4263          * blocking_wait_with_raise_on_sig raises signal handlers
4264          * if it gets no pid (pid < 0). However,
4265          * if child sends us a signal *and immediately exits*,
4266          * blocking_wait_with_raise_on_sig gets pid > 0
4267          * and does not handle pending_sig. Check this case: */
4268                         if (pending_sig)
4269                                 raise_exception(EXSIG);
4270                 }
4271         }
4272
4273         retval = 127;
4274         do {
4275                 if (**argv != '%') {
4276                         pid_t pid = number(*argv);
4277                         job = curjob;
4278                         while (1) {
4279                                 if (!job)
4280                                         goto repeat;
4281                                 if (job->ps[job->nprocs - 1].ps_pid == pid)
4282                                         break;
4283                                 job = job->prev_job;
4284                         }
4285                 } else {
4286                         job = getjob(*argv, 0);
4287                 }
4288                 /* loop until process terminated or stopped */
4289                 while (job->state == JOBRUNNING)
4290                         blocking_wait_with_raise_on_sig();
4291                 job->waited = 1;
4292                 retval = getstatus(job);
4293  repeat: ;
4294         } while (*++argv);
4295
4296  ret:
4297         return retval;
4298 }
4299
4300 static struct job *
4301 growjobtab(void)
4302 {
4303         size_t len;
4304         ptrdiff_t offset;
4305         struct job *jp, *jq;
4306
4307         len = njobs * sizeof(*jp);
4308         jq = jobtab;
4309         jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4310
4311         offset = (char *)jp - (char *)jq;
4312         if (offset) {
4313                 /* Relocate pointers */
4314                 size_t l = len;
4315
4316                 jq = (struct job *)((char *)jq + l);
4317                 while (l) {
4318                         l -= sizeof(*jp);
4319                         jq--;
4320 #define joff(p) ((struct job *)((char *)(p) + l))
4321 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4322                         if (joff(jp)->ps == &jq->ps0)
4323                                 jmove(joff(jp)->ps);
4324                         if (joff(jp)->prev_job)
4325                                 jmove(joff(jp)->prev_job);
4326                 }
4327                 if (curjob)
4328                         jmove(curjob);
4329 #undef joff
4330 #undef jmove
4331         }
4332
4333         njobs += 4;
4334         jobtab = jp;
4335         jp = (struct job *)((char *)jp + len);
4336         jq = jp + 3;
4337         do {
4338                 jq->used = 0;
4339         } while (--jq >= jp);
4340         return jp;
4341 }
4342
4343 /*
4344  * Return a new job structure.
4345  * Called with interrupts off.
4346  */
4347 static struct job *
4348 makejob(/*union node *node,*/ int nprocs)
4349 {
4350         int i;
4351         struct job *jp;
4352
4353         for (i = njobs, jp = jobtab; ; jp++) {
4354                 if (--i < 0) {
4355                         jp = growjobtab();
4356                         break;
4357                 }
4358                 if (jp->used == 0)
4359                         break;
4360                 if (jp->state != JOBDONE || !jp->waited)
4361                         continue;
4362 #if JOBS
4363                 if (doing_jobctl)
4364                         continue;
4365 #endif
4366                 freejob(jp);
4367                 break;
4368         }
4369         memset(jp, 0, sizeof(*jp));
4370 #if JOBS
4371         /* jp->jobctl is a bitfield.
4372          * "jp->jobctl |= jobctl" likely to give awful code */
4373         if (doing_jobctl)
4374                 jp->jobctl = 1;
4375 #endif
4376         jp->prev_job = curjob;
4377         curjob = jp;
4378         jp->used = 1;
4379         jp->ps = &jp->ps0;
4380         if (nprocs > 1) {
4381                 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4382         }
4383         TRACE(("makejob(%d) returns %%%d\n", nprocs,
4384                                 jobno(jp)));
4385         return jp;
4386 }
4387
4388 #if JOBS
4389 /*
4390  * Return a string identifying a command (to be printed by the
4391  * jobs command).
4392  */
4393 static char *cmdnextc;
4394
4395 static void
4396 cmdputs(const char *s)
4397 {
4398         static const char vstype[VSTYPE + 1][3] = {
4399                 "", "}", "-", "+", "?", "=",
4400                 "%", "%%", "#", "##"
4401                 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4402         };
4403
4404         const char *p, *str;
4405         char cc[2];
4406         char *nextc;
4407         unsigned char c;
4408         unsigned char subtype = 0;
4409         int quoted = 0;
4410
4411         cc[1] = '\0';
4412         nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4413         p = s;
4414         while ((c = *p++) != '\0') {
4415                 str = NULL;
4416                 switch (c) {
4417                 case CTLESC:
4418                         c = *p++;
4419                         break;
4420                 case CTLVAR:
4421                         subtype = *p++;
4422                         if ((subtype & VSTYPE) == VSLENGTH)
4423                                 str = "${#";
4424                         else
4425                                 str = "${";
4426                         goto dostr;
4427                 case CTLENDVAR:
4428                         str = "\"}" + !(quoted & 1);
4429                         quoted >>= 1;
4430                         subtype = 0;
4431                         goto dostr;
4432                 case CTLBACKQ:
4433                         str = "$(...)";
4434                         goto dostr;
4435 #if ENABLE_SH_MATH_SUPPORT
4436                 case CTLARI:
4437                         str = "$((";
4438                         goto dostr;
4439                 case CTLENDARI:
4440                         str = "))";
4441                         goto dostr;
4442 #endif
4443                 case CTLQUOTEMARK:
4444                         quoted ^= 1;
4445                         c = '"';
4446                         break;
4447                 case '=':
4448                         if (subtype == 0)
4449                                 break;
4450                         if ((subtype & VSTYPE) != VSNORMAL)
4451                                 quoted <<= 1;
4452                         str = vstype[subtype & VSTYPE];
4453                         if (subtype & VSNUL)
4454                                 c = ':';
4455                         else
4456                                 goto checkstr;
4457                         break;
4458                 case '\'':
4459                 case '\\':
4460                 case '"':
4461                 case '$':
4462                         /* These can only happen inside quotes */
4463                         cc[0] = c;
4464                         str = cc;
4465                         c = '\\';
4466                         break;
4467                 default:
4468                         break;
4469                 }
4470                 USTPUTC(c, nextc);
4471  checkstr:
4472                 if (!str)
4473                         continue;
4474  dostr:
4475                 while ((c = *str++) != '\0') {
4476                         USTPUTC(c, nextc);
4477                 }
4478         } /* while *p++ not NUL */
4479
4480         if (quoted & 1) {
4481                 USTPUTC('"', nextc);
4482         }
4483         *nextc = 0;
4484         cmdnextc = nextc;
4485 }
4486
4487 /* cmdtxt() and cmdlist() call each other */
4488 static void cmdtxt(union node *n);
4489
4490 static void
4491 cmdlist(union node *np, int sep)
4492 {
4493         for (; np; np = np->narg.next) {
4494                 if (!sep)
4495                         cmdputs(" ");
4496                 cmdtxt(np);
4497                 if (sep && np->narg.next)
4498                         cmdputs(" ");
4499         }
4500 }
4501
4502 static void
4503 cmdtxt(union node *n)
4504 {
4505         union node *np;
4506         struct nodelist *lp;
4507         const char *p;
4508
4509         if (!n)
4510                 return;
4511         switch (n->type) {
4512         default:
4513 #if DEBUG
4514                 abort();
4515 #endif
4516         case NPIPE:
4517                 lp = n->npipe.cmdlist;
4518                 for (;;) {
4519                         cmdtxt(lp->n);
4520                         lp = lp->next;
4521                         if (!lp)
4522                                 break;
4523                         cmdputs(" | ");
4524                 }
4525                 break;
4526         case NSEMI:
4527                 p = "; ";
4528                 goto binop;
4529         case NAND:
4530                 p = " && ";
4531                 goto binop;
4532         case NOR:
4533                 p = " || ";
4534  binop:
4535                 cmdtxt(n->nbinary.ch1);
4536                 cmdputs(p);
4537                 n = n->nbinary.ch2;
4538                 goto donode;
4539         case NREDIR:
4540         case NBACKGND:
4541                 n = n->nredir.n;
4542                 goto donode;
4543         case NNOT:
4544                 cmdputs("!");
4545                 n = n->nnot.com;
4546  donode:
4547                 cmdtxt(n);
4548                 break;
4549         case NIF:
4550                 cmdputs("if ");
4551                 cmdtxt(n->nif.test);
4552                 cmdputs("; then ");
4553                 if (n->nif.elsepart) {
4554                         cmdtxt(n->nif.ifpart);
4555                         cmdputs("; else ");
4556                         n = n->nif.elsepart;
4557                 } else {
4558                         n = n->nif.ifpart;
4559                 }
4560                 p = "; fi";
4561                 goto dotail;
4562         case NSUBSHELL:
4563                 cmdputs("(");
4564                 n = n->nredir.n;
4565                 p = ")";
4566                 goto dotail;
4567         case NWHILE:
4568                 p = "while ";
4569                 goto until;
4570         case NUNTIL:
4571                 p = "until ";
4572  until:
4573                 cmdputs(p);
4574                 cmdtxt(n->nbinary.ch1);
4575                 n = n->nbinary.ch2;
4576                 p = "; done";
4577  dodo:
4578                 cmdputs("; do ");
4579  dotail:
4580                 cmdtxt(n);
4581                 goto dotail2;
4582         case NFOR:
4583                 cmdputs("for ");
4584                 cmdputs(n->nfor.var);
4585                 cmdputs(" in ");
4586                 cmdlist(n->nfor.args, 1);
4587                 n = n->nfor.body;
4588                 p = "; done";
4589                 goto dodo;
4590         case NDEFUN:
4591                 cmdputs(n->narg.text);
4592                 p = "() { ... }";
4593                 goto dotail2;
4594         case NCMD:
4595                 cmdlist(n->ncmd.args, 1);
4596                 cmdlist(n->ncmd.redirect, 0);
4597                 break;
4598         case NARG:
4599                 p = n->narg.text;
4600  dotail2:
4601                 cmdputs(p);
4602                 break;
4603         case NHERE:
4604         case NXHERE:
4605                 p = "<<...";
4606                 goto dotail2;
4607         case NCASE:
4608                 cmdputs("case ");
4609                 cmdputs(n->ncase.expr->narg.text);
4610                 cmdputs(" in ");
4611                 for (np = n->ncase.cases; np; np = np->nclist.next) {
4612                         cmdtxt(np->nclist.pattern);
4613                         cmdputs(") ");
4614                         cmdtxt(np->nclist.body);
4615                         cmdputs(";; ");
4616                 }
4617                 p = "esac";
4618                 goto dotail2;
4619         case NTO:
4620                 p = ">";
4621                 goto redir;
4622         case NCLOBBER:
4623                 p = ">|";
4624                 goto redir;
4625         case NAPPEND:
4626                 p = ">>";
4627                 goto redir;
4628 #if ENABLE_ASH_BASH_COMPAT
4629         case NTO2:
4630 #endif
4631         case NTOFD:
4632                 p = ">&";
4633                 goto redir;
4634         case NFROM:
4635                 p = "<";
4636                 goto redir;
4637         case NFROMFD:
4638                 p = "<&";
4639                 goto redir;
4640         case NFROMTO:
4641                 p = "<>";
4642  redir:
4643                 cmdputs(utoa(n->nfile.fd));
4644                 cmdputs(p);
4645                 if (n->type == NTOFD || n->type == NFROMFD) {
4646                         cmdputs(utoa(n->ndup.dupfd));
4647                         break;
4648                 }
4649                 n = n->nfile.fname;
4650                 goto donode;
4651         }
4652 }
4653
4654 static char *
4655 commandtext(union node *n)
4656 {
4657         char *name;
4658
4659         STARTSTACKSTR(cmdnextc);
4660         cmdtxt(n);
4661         name = stackblock();
4662         TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4663         return ckstrdup(name);
4664 }
4665 #endif /* JOBS */
4666
4667 /*
4668  * Fork off a subshell.  If we are doing job control, give the subshell its
4669  * own process group.  Jp is a job structure that the job is to be added to.
4670  * N is the command that will be evaluated by the child.  Both jp and n may
4671  * be NULL.  The mode parameter can be one of the following:
4672  *      FORK_FG - Fork off a foreground process.
4673  *      FORK_BG - Fork off a background process.
4674  *      FORK_NOJOB - Like FORK_FG, but don't give the process its own
4675  *                   process group even if job control is on.
4676  *
4677  * When job control is turned off, background processes have their standard
4678  * input redirected to /dev/null (except for the second and later processes
4679  * in a pipeline).
4680  *
4681  * Called with interrupts off.
4682  */
4683 /*
4684  * Clear traps on a fork.
4685  */
4686 static void
4687 clear_traps(void)
4688 {
4689         char **tp;
4690
4691         for (tp = trap; tp < &trap[NSIG]; tp++) {
4692                 if (*tp && **tp) {      /* trap not NULL or "" (SIG_IGN) */
4693                         INT_OFF;
4694                         if (trap_ptr == trap)
4695                                 free(*tp);
4696                         /* else: it "belongs" to trap_ptr vector, don't free */
4697                         *tp = NULL;
4698                         if ((tp - trap) != 0)
4699                                 setsignal(tp - trap);
4700                         INT_ON;
4701                 }
4702         }
4703         may_have_traps = 0;
4704 }
4705
4706 /* Lives far away from here, needed for forkchild */
4707 static void closescript(void);
4708
4709 /* Called after fork(), in child */
4710 static NOINLINE void
4711 forkchild(struct job *jp, union node *n, int mode)
4712 {
4713         int oldlvl;
4714
4715         TRACE(("Child shell %d\n", getpid()));
4716         oldlvl = shlvl;
4717         shlvl++;
4718
4719         /* man bash: "Non-builtin commands run by bash have signal handlers
4720          * set to the values inherited by the shell from its parent".
4721          * Do we do it correctly? */
4722
4723         closescript();
4724
4725         if (mode == FORK_NOJOB          /* is it `xxx` ? */
4726          && n && n->type == NCMD        /* is it single cmd? */
4727         /* && n->ncmd.args->type == NARG - always true? */
4728          && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4729          && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4730         /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4731         ) {
4732                 TRACE(("Trap hack\n"));
4733                 /* Awful hack for `trap` or $(trap).
4734                  *
4735                  * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4736                  * contains an example where "trap" is executed in a subshell:
4737                  *
4738                  * save_traps=$(trap)
4739                  * ...
4740                  * eval "$save_traps"
4741                  *
4742                  * Standard does not say that "trap" in subshell shall print
4743                  * parent shell's traps. It only says that its output
4744                  * must have suitable form, but then, in the above example
4745                  * (which is not supposed to be normative), it implies that.
4746                  *
4747                  * bash (and probably other shell) does implement it
4748                  * (traps are reset to defaults, but "trap" still shows them),
4749                  * but as a result, "trap" logic is hopelessly messed up:
4750                  *
4751                  * # trap
4752                  * trap -- 'echo Ho' SIGWINCH  <--- we have a handler
4753                  * # (trap)        <--- trap is in subshell - no output (correct, traps are reset)
4754                  * # true | trap   <--- trap is in subshell - no output (ditto)
4755                  * # echo `true | trap`    <--- in subshell - output (but traps are reset!)
4756                  * trap -- 'echo Ho' SIGWINCH
4757                  * # echo `(trap)`         <--- in subshell in subshell - output
4758                  * trap -- 'echo Ho' SIGWINCH
4759                  * # echo `true | (trap)`  <--- in subshell in subshell in subshell - output!
4760                  * trap -- 'echo Ho' SIGWINCH
4761                  *
4762                  * The rules when to forget and when to not forget traps
4763                  * get really complex and nonsensical.
4764                  *
4765                  * Our solution: ONLY bare $(trap) or `trap` is special.
4766                  */
4767                 /* Save trap handler strings for trap builtin to print */
4768                 trap_ptr = xmemdup(trap, sizeof(trap));
4769                 /* Fall through into clearing traps */
4770         }
4771         clear_traps();
4772 #if JOBS
4773         /* do job control only in root shell */
4774         doing_jobctl = 0;
4775         if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4776                 pid_t pgrp;
4777
4778                 if (jp->nprocs == 0)
4779                         pgrp = getpid();
4780                 else
4781                         pgrp = jp->ps[0].ps_pid;
4782                 /* this can fail because we are doing it in the parent also */
4783                 setpgid(0, pgrp);
4784                 if (mode == FORK_FG)
4785                         xtcsetpgrp(ttyfd, pgrp);
4786                 setsignal(SIGTSTP);
4787                 setsignal(SIGTTOU);
4788         } else
4789 #endif
4790         if (mode == FORK_BG) {
4791                 /* man bash: "When job control is not in effect,
4792                  * asynchronous commands ignore SIGINT and SIGQUIT" */
4793                 ignoresig(SIGINT);
4794                 ignoresig(SIGQUIT);
4795                 if (jp->nprocs == 0) {
4796                         close(0);
4797                         if (open(bb_dev_null, O_RDONLY) != 0)
4798                                 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4799                 }
4800         }
4801         if (oldlvl == 0) {
4802                 if (iflag) { /* why if iflag only? */
4803                         setsignal(SIGINT);
4804                         setsignal(SIGTERM);
4805                 }
4806                 /* man bash:
4807                  * "In all cases, bash ignores SIGQUIT. Non-builtin
4808                  * commands run by bash have signal handlers
4809                  * set to the values inherited by the shell
4810                  * from its parent".
4811                  * Take care of the second rule: */
4812                 setsignal(SIGQUIT);
4813         }
4814 #if JOBS
4815         if (n && n->type == NCMD
4816          && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4817         ) {
4818                 TRACE(("Job hack\n"));
4819                 /* "jobs": we do not want to clear job list for it,
4820                  * instead we remove only _its_ own_ job from job list.
4821                  * This makes "jobs .... | cat" more useful.
4822                  */
4823                 freejob(curjob);
4824                 return;
4825         }
4826 #endif
4827         for (jp = curjob; jp; jp = jp->prev_job)
4828                 freejob(jp);
4829         jobless = 0;
4830 }
4831
4832 /* Called after fork(), in parent */
4833 #if !JOBS
4834 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4835 #endif
4836 static void
4837 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4838 {
4839         TRACE(("In parent shell: child = %d\n", pid));
4840         if (!jp) {
4841                 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4842                         continue;
4843                 jobless++;
4844                 return;
4845         }
4846 #if JOBS
4847         if (mode != FORK_NOJOB && jp->jobctl) {
4848                 int pgrp;
4849
4850                 if (jp->nprocs == 0)
4851                         pgrp = pid;
4852                 else
4853                         pgrp = jp->ps[0].ps_pid;
4854                 /* This can fail because we are doing it in the child also */
4855                 setpgid(pid, pgrp);
4856         }
4857 #endif
4858         if (mode == FORK_BG) {
4859                 backgndpid = pid;               /* set $! */
4860                 set_curjob(jp, CUR_RUNNING);
4861         }
4862         if (jp) {
4863                 struct procstat *ps = &jp->ps[jp->nprocs++];
4864                 ps->ps_pid = pid;
4865                 ps->ps_status = -1;
4866                 ps->ps_cmd = nullstr;
4867 #if JOBS
4868                 if (doing_jobctl && n)
4869                         ps->ps_cmd = commandtext(n);
4870 #endif
4871         }
4872 }
4873
4874 static int
4875 forkshell(struct job *jp, union node *n, int mode)
4876 {
4877         int pid;
4878
4879         TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4880         pid = fork();
4881         if (pid < 0) {
4882                 TRACE(("Fork failed, errno=%d", errno));
4883                 if (jp)
4884                         freejob(jp);
4885                 ash_msg_and_raise_error("can't fork");
4886         }
4887         if (pid == 0) {
4888                 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4889                 forkchild(jp, n, mode);
4890         } else {
4891                 forkparent(jp, n, mode, pid);
4892         }
4893         return pid;
4894 }
4895
4896 /*
4897  * Wait for job to finish.
4898  *
4899  * Under job control we have the problem that while a child process
4900  * is running interrupts generated by the user are sent to the child
4901  * but not to the shell.  This means that an infinite loop started by
4902  * an interactive user may be hard to kill.  With job control turned off,
4903  * an interactive user may place an interactive program inside a loop.
4904  * If the interactive program catches interrupts, the user doesn't want
4905  * these interrupts to also abort the loop.  The approach we take here
4906  * is to have the shell ignore interrupt signals while waiting for a
4907  * foreground process to terminate, and then send itself an interrupt
4908  * signal if the child process was terminated by an interrupt signal.
4909  * Unfortunately, some programs want to do a bit of cleanup and then
4910  * exit on interrupt; unless these processes terminate themselves by
4911  * sending a signal to themselves (instead of calling exit) they will
4912  * confuse this approach.
4913  *
4914  * Called with interrupts off.
4915  */
4916 static int
4917 waitforjob(struct job *jp)
4918 {
4919         int st;
4920
4921         TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4922
4923         INT_OFF;
4924         while (jp->state == JOBRUNNING) {
4925                 /* In non-interactive shells, we _can_ get
4926                  * a keyboard signal here and be EINTRed,
4927                  * but we just loop back, waiting for command to complete.
4928                  *
4929                  * man bash:
4930                  * "If bash is waiting for a command to complete and receives
4931                  * a signal for which a trap has been set, the trap
4932                  * will not be executed until the command completes."
4933                  *
4934                  * Reality is that even if trap is not set, bash
4935                  * will not act on the signal until command completes.
4936                  * Try this. sleep5intoff.c:
4937                  * #include <signal.h>
4938                  * #include <unistd.h>
4939                  * int main() {
4940                  *         sigset_t set;
4941                  *         sigemptyset(&set);
4942                  *         sigaddset(&set, SIGINT);
4943                  *         sigaddset(&set, SIGQUIT);
4944                  *         sigprocmask(SIG_BLOCK, &set, NULL);
4945                  *         sleep(5);
4946                  *         return 0;
4947                  * }
4948                  * $ bash -c './sleep5intoff; echo hi'
4949                  * ^C^C^C^C <--- pressing ^C once a second
4950                  * $ _
4951                  * $ bash -c './sleep5intoff; echo hi'
4952                  * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4953                  * $ _
4954                  */
4955                 dowait(DOWAIT_BLOCK, jp);
4956         }
4957         INT_ON;
4958
4959         st = getstatus(jp);
4960 #if JOBS
4961         if (jp->jobctl) {
4962                 xtcsetpgrp(ttyfd, rootpid);
4963                 /*
4964                  * This is truly gross.
4965                  * If we're doing job control, then we did a TIOCSPGRP which
4966                  * caused us (the shell) to no longer be in the controlling
4967                  * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
4968                  * intuit from the subprocess exit status whether a SIGINT
4969                  * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
4970                  */
4971                 if (jp->sigint) /* TODO: do the same with all signals */
4972                         raise(SIGINT); /* ... by raise(jp->sig) instead? */
4973         }
4974         if (jp->state == JOBDONE)
4975 #endif
4976                 freejob(jp);
4977         return st;
4978 }
4979
4980 /*
4981  * return 1 if there are stopped jobs, otherwise 0
4982  */
4983 static int
4984 stoppedjobs(void)
4985 {
4986         struct job *jp;
4987         int retval;
4988
4989         retval = 0;
4990         if (job_warning)
4991                 goto out;
4992         jp = curjob;
4993         if (jp && jp->state == JOBSTOPPED) {
4994                 out2str("You have stopped jobs.\n");
4995                 job_warning = 2;
4996                 retval++;
4997         }
4998  out:
4999         return retval;
5000 }
5001
5002
5003 /* ============ redir.c
5004  *
5005  * Code for dealing with input/output redirection.
5006  */
5007
5008 #undef EMPTY
5009 #undef CLOSED
5010 #define EMPTY -2                /* marks an unused slot in redirtab */
5011 #define CLOSED -3               /* marks a slot of previously-closed fd */
5012
5013 /*
5014  * Open a file in noclobber mode.
5015  * The code was copied from bash.
5016  */
5017 static int
5018 noclobberopen(const char *fname)
5019 {
5020         int r, fd;
5021         struct stat finfo, finfo2;
5022
5023         /*
5024          * If the file exists and is a regular file, return an error
5025          * immediately.
5026          */
5027         r = stat(fname, &finfo);
5028         if (r == 0 && S_ISREG(finfo.st_mode)) {
5029                 errno = EEXIST;
5030                 return -1;
5031         }
5032
5033         /*
5034          * If the file was not present (r != 0), make sure we open it
5035          * exclusively so that if it is created before we open it, our open
5036          * will fail.  Make sure that we do not truncate an existing file.
5037          * Note that we don't turn on O_EXCL unless the stat failed -- if the
5038          * file was not a regular file, we leave O_EXCL off.
5039          */
5040         if (r != 0)
5041                 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5042         fd = open(fname, O_WRONLY|O_CREAT, 0666);
5043
5044         /* If the open failed, return the file descriptor right away. */
5045         if (fd < 0)
5046                 return fd;
5047
5048         /*
5049          * OK, the open succeeded, but the file may have been changed from a
5050          * non-regular file to a regular file between the stat and the open.
5051          * We are assuming that the O_EXCL open handles the case where FILENAME
5052          * did not exist and is symlinked to an existing file between the stat
5053          * and open.
5054          */
5055
5056         /*
5057          * If we can open it and fstat the file descriptor, and neither check
5058          * revealed that it was a regular file, and the file has not been
5059          * replaced, return the file descriptor.
5060          */
5061         if (fstat(fd, &finfo2) == 0
5062          && !S_ISREG(finfo2.st_mode)
5063          && finfo.st_dev == finfo2.st_dev
5064          && finfo.st_ino == finfo2.st_ino
5065         ) {
5066                 return fd;
5067         }
5068
5069         /* The file has been replaced.  badness. */
5070         close(fd);
5071         errno = EEXIST;
5072         return -1;
5073 }
5074
5075 /*
5076  * Handle here documents.  Normally we fork off a process to write the
5077  * data to a pipe.  If the document is short, we can stuff the data in
5078  * the pipe without forking.
5079  */
5080 /* openhere needs this forward reference */
5081 static void expandhere(union node *arg, int fd);
5082 static int
5083 openhere(union node *redir)
5084 {
5085         int pip[2];
5086         size_t len = 0;
5087
5088         if (pipe(pip) < 0)
5089                 ash_msg_and_raise_error("pipe call failed");
5090         if (redir->type == NHERE) {
5091                 len = strlen(redir->nhere.doc->narg.text);
5092                 if (len <= PIPE_BUF) {
5093                         full_write(pip[1], redir->nhere.doc->narg.text, len);
5094                         goto out;
5095                 }
5096         }
5097         if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5098                 /* child */
5099                 close(pip[0]);
5100                 ignoresig(SIGINT);  //signal(SIGINT, SIG_IGN);
5101                 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5102                 ignoresig(SIGHUP);  //signal(SIGHUP, SIG_IGN);
5103                 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5104                 signal(SIGPIPE, SIG_DFL);
5105                 if (redir->type == NHERE)
5106                         full_write(pip[1], redir->nhere.doc->narg.text, len);
5107                 else /* NXHERE */
5108                         expandhere(redir->nhere.doc, pip[1]);
5109                 _exit(EXIT_SUCCESS);
5110         }
5111  out:
5112         close(pip[1]);
5113         return pip[0];
5114 }
5115
5116 static int
5117 openredirect(union node *redir)
5118 {
5119         char *fname;
5120         int f;
5121
5122         switch (redir->nfile.type) {
5123 /* Can't happen, our single caller does this itself */
5124 //      case NTOFD:
5125 //      case NFROMFD:
5126 //              return -1;
5127         case NHERE:
5128         case NXHERE:
5129                 return openhere(redir);
5130         }
5131
5132         /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5133          * allocated space. Do it only when we know it is safe.
5134          */
5135         fname = redir->nfile.expfname;
5136
5137         switch (redir->nfile.type) {
5138         default:
5139 #if DEBUG
5140                 abort();
5141 #endif
5142         case NFROM:
5143                 f = open(fname, O_RDONLY);
5144                 if (f < 0)
5145                         goto eopen;
5146                 break;
5147         case NFROMTO:
5148                 f = open(fname, O_RDWR|O_CREAT, 0666);
5149                 if (f < 0)
5150                         goto ecreate;
5151                 break;
5152         case NTO:
5153 #if ENABLE_ASH_BASH_COMPAT
5154         case NTO2:
5155 #endif
5156                 /* Take care of noclobber mode. */
5157                 if (Cflag) {
5158                         f = noclobberopen(fname);
5159                         if (f < 0)
5160                                 goto ecreate;
5161                         break;
5162                 }
5163                 /* FALLTHROUGH */
5164         case NCLOBBER:
5165                 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5166                 if (f < 0)
5167                         goto ecreate;
5168                 break;
5169         case NAPPEND:
5170                 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5171                 if (f < 0)
5172                         goto ecreate;
5173                 break;
5174         }
5175
5176         return f;
5177  ecreate:
5178         ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5179  eopen:
5180         ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5181 }
5182
5183 /*
5184  * Copy a file descriptor to be >= to. Throws exception on error.
5185  */
5186 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5187  * old code was doing close(to) prior to copyfd() to achieve the same */
5188 enum {
5189         COPYFD_EXACT   = (int)~(INT_MAX),
5190         COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5191 };
5192 static int
5193 copyfd(int from, int to)
5194 {
5195         int newfd;
5196
5197         if (to & COPYFD_EXACT) {
5198                 to &= ~COPYFD_EXACT;
5199                 /*if (from != to)*/
5200                         newfd = dup2(from, to);
5201         } else {
5202                 newfd = fcntl(from, F_DUPFD, to);
5203         }
5204         if (newfd < 0) {
5205                 /* Happens when source fd is not open: try "echo >&99" */
5206                 ash_msg_and_raise_error("%d: %m", from);
5207         }
5208         return newfd;
5209 }
5210
5211 /* Struct def and variable are moved down to the first usage site */
5212 struct two_fd_t {
5213         int orig, copy;
5214 };
5215 struct redirtab {
5216         struct redirtab *next;
5217         int pair_count;
5218         struct two_fd_t two_fd[];
5219 };
5220 #define redirlist (G_var.redirlist)
5221
5222 static int
5223 need_to_remember(struct redirtab *rp, int fd)
5224 {
5225         int i;
5226
5227         if (!rp) /* remembering was not requested */
5228                 return 0;
5229
5230         for (i = 0; i < rp->pair_count; i++) {
5231                 if (rp->two_fd[i].orig == fd) {
5232                         /* already remembered */
5233                         return 0;
5234                 }
5235         }
5236         return 1;
5237 }
5238
5239 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5240 static int
5241 is_hidden_fd(struct redirtab *rp, int fd)
5242 {
5243         int i;
5244         struct parsefile *pf;
5245
5246         if (fd == -1)
5247                 return 0;
5248         /* Check open scripts' fds */
5249         pf = g_parsefile;
5250         while (pf) {
5251                 /* We skip pf_fd == 0 case because of the following case:
5252                  * $ ash  # running ash interactively
5253                  * $ . ./script.sh
5254                  * and in script.sh: "exec 9>&0".
5255                  * Even though top-level pf_fd _is_ 0,
5256                  * it's still ok to use it: "read" builtin uses it,
5257                  * why should we cripple "exec" builtin?
5258                  */
5259                 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5260                         return 1;
5261                 }
5262                 pf = pf->prev;
5263         }
5264
5265         if (!rp)
5266                 return 0;
5267         /* Check saved fds of redirects */
5268         fd |= COPYFD_RESTORE;
5269         for (i = 0; i < rp->pair_count; i++) {
5270                 if (rp->two_fd[i].copy == fd) {
5271                         return 1;
5272                 }
5273         }
5274         return 0;
5275 }
5276
5277 /*
5278  * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
5279  * old file descriptors are stashed away so that the redirection can be
5280  * undone by calling popredir.
5281  */
5282 /* flags passed to redirect */
5283 #define REDIR_PUSH    01        /* save previous values of file descriptors */
5284 #define REDIR_SAVEFD2 03        /* set preverrout */
5285 static void
5286 redirect(union node *redir, int flags)
5287 {
5288         struct redirtab *sv;
5289         int sv_pos;
5290         int i;
5291         int fd;
5292         int newfd;
5293         int copied_fd2 = -1;
5294
5295         if (!redir) {
5296                 return;
5297         }
5298
5299         sv = NULL;
5300         sv_pos = 0;
5301         INT_OFF;
5302         if (flags & REDIR_PUSH) {
5303                 union node *tmp = redir;
5304                 do {
5305                         sv_pos++;
5306 #if ENABLE_ASH_BASH_COMPAT
5307                         if (tmp->nfile.type == NTO2)
5308                                 sv_pos++;
5309 #endif
5310                         tmp = tmp->nfile.next;
5311                 } while (tmp);
5312                 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5313                 sv->next = redirlist;
5314                 sv->pair_count = sv_pos;
5315                 redirlist = sv;
5316                 while (sv_pos > 0) {
5317                         sv_pos--;
5318                         sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5319                 }
5320         }
5321
5322         do {
5323                 int right_fd = -1;
5324                 fd = redir->nfile.fd;
5325                 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5326                         right_fd = redir->ndup.dupfd;
5327                         //bb_error_msg("doing %d > %d", fd, right_fd);
5328                         /* redirect from/to same file descriptor? */
5329                         if (right_fd == fd)
5330                                 continue;
5331                         /* "echo >&10" and 10 is a fd opened to a sh script? */
5332                         if (is_hidden_fd(sv, right_fd)) {
5333                                 errno = EBADF; /* as if it is closed */
5334                                 ash_msg_and_raise_error("%d: %m", right_fd);
5335                         }
5336                         newfd = -1;
5337                 } else {
5338                         newfd = openredirect(redir); /* always >= 0 */
5339                         if (fd == newfd) {
5340                                 /* Descriptor wasn't open before redirect.
5341                                  * Mark it for close in the future */
5342                                 if (need_to_remember(sv, fd)) {
5343                                         goto remember_to_close;
5344                                 }
5345                                 continue;
5346                         }
5347                 }
5348 #if ENABLE_ASH_BASH_COMPAT
5349  redirect_more:
5350 #endif
5351                 if (need_to_remember(sv, fd)) {
5352                         /* Copy old descriptor */
5353                         /* Careful to not accidentally "save"
5354                          * to the same fd as right side fd in N>&M */
5355                         int minfd = right_fd < 10 ? 10 : right_fd + 1;
5356                         i = fcntl(fd, F_DUPFD, minfd);
5357 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5358  * are closed in popredir() in the child, preventing them from leaking
5359  * into child. (popredir() also cleans up the mess in case of failures)
5360  */
5361                         if (i == -1) {
5362                                 i = errno;
5363                                 if (i != EBADF) {
5364                                         /* Strange error (e.g. "too many files" EMFILE?) */
5365                                         if (newfd >= 0)
5366                                                 close(newfd);
5367                                         errno = i;
5368                                         ash_msg_and_raise_error("%d: %m", fd);
5369                                         /* NOTREACHED */
5370                                 }
5371                                 /* EBADF: it is not open - good, remember to close it */
5372  remember_to_close:
5373                                 i = CLOSED;
5374                         } else { /* fd is open, save its copy */
5375                                 /* "exec fd>&-" should not close fds
5376                                  * which point to script file(s).
5377                                  * Force them to be restored afterwards */
5378                                 if (is_hidden_fd(sv, fd))
5379                                         i |= COPYFD_RESTORE;
5380                         }
5381                         if (fd == 2)
5382                                 copied_fd2 = i;
5383                         sv->two_fd[sv_pos].orig = fd;
5384                         sv->two_fd[sv_pos].copy = i;
5385                         sv_pos++;
5386                 }
5387                 if (newfd < 0) {
5388                         /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5389                         if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5390                                 /* Don't want to trigger debugging */
5391                                 if (fd != -1)
5392                                         close(fd);
5393                         } else {
5394                                 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5395                         }
5396                 } else if (fd != newfd) { /* move newfd to fd */
5397                         copyfd(newfd, fd | COPYFD_EXACT);
5398 #if ENABLE_ASH_BASH_COMPAT
5399                         if (!(redir->nfile.type == NTO2 && fd == 2))
5400 #endif
5401                                 close(newfd);
5402                 }
5403 #if ENABLE_ASH_BASH_COMPAT
5404                 if (redir->nfile.type == NTO2 && fd == 1) {
5405                         /* We already redirected it to fd 1, now copy it to 2 */
5406                         newfd = 1;
5407                         fd = 2;
5408                         goto redirect_more;
5409                 }
5410 #endif
5411         } while ((redir = redir->nfile.next) != NULL);
5412
5413         INT_ON;
5414         if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5415                 preverrout_fd = copied_fd2;
5416 }
5417
5418 /*
5419  * Undo the effects of the last redirection.
5420  */
5421 static void
5422 popredir(int drop, int restore)
5423 {
5424         struct redirtab *rp;
5425         int i;
5426
5427         if (redirlist == NULL)
5428                 return;
5429         INT_OFF;
5430         rp = redirlist;
5431         for (i = 0; i < rp->pair_count; i++) {
5432                 int fd = rp->two_fd[i].orig;
5433                 int copy = rp->two_fd[i].copy;
5434                 if (copy == CLOSED) {
5435                         if (!drop)
5436                                 close(fd);
5437                         continue;
5438                 }
5439                 if (copy != EMPTY) {
5440                         if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5441                                 copy &= ~COPYFD_RESTORE;
5442                                 /*close(fd);*/
5443                                 copyfd(copy, fd | COPYFD_EXACT);
5444                         }
5445                         close(copy & ~COPYFD_RESTORE);
5446                 }
5447         }
5448         redirlist = rp->next;
5449         free(rp);
5450         INT_ON;
5451 }
5452
5453 /*
5454  * Undo all redirections.  Called on error or interrupt.
5455  */
5456
5457 /*
5458  * Discard all saved file descriptors.
5459  */
5460 static void
5461 clearredir(int drop)
5462 {
5463         while (redirlist)
5464                 popredir(drop, /*restore:*/ 0);
5465 }
5466
5467 static int
5468 redirectsafe(union node *redir, int flags)
5469 {
5470         int err;
5471         volatile int saveint;
5472         struct jmploc *volatile savehandler = exception_handler;
5473         struct jmploc jmploc;
5474
5475         SAVE_INT(saveint);
5476         /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5477         err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5478         if (!err) {
5479                 exception_handler = &jmploc;
5480                 redirect(redir, flags);
5481         }
5482         exception_handler = savehandler;
5483         if (err && exception_type != EXERROR)
5484                 longjmp(exception_handler->loc, 1);
5485         RESTORE_INT(saveint);
5486         return err;
5487 }
5488
5489
5490 /* ============ Routines to expand arguments to commands
5491  *
5492  * We have to deal with backquotes, shell variables, and file metacharacters.
5493  */
5494
5495 #if ENABLE_SH_MATH_SUPPORT
5496 static arith_t
5497 ash_arith(const char *s)
5498 {
5499         arith_state_t math_state;
5500         arith_t result;
5501
5502         math_state.lookupvar = lookupvar;
5503         math_state.setvar    = setvar0;
5504         //math_state.endofname = endofname;
5505
5506         INT_OFF;
5507         result = arith(&math_state, s);
5508         if (math_state.errmsg)
5509                 ash_msg_and_raise_error(math_state.errmsg);
5510         INT_ON;
5511
5512         return result;
5513 }
5514 #endif
5515
5516 /*
5517  * expandarg flags
5518  */
5519 #define EXP_FULL        0x1     /* perform word splitting & file globbing */
5520 #define EXP_TILDE       0x2     /* do normal tilde expansion */
5521 #define EXP_VARTILDE    0x4     /* expand tildes in an assignment */
5522 #define EXP_REDIR       0x8     /* file glob for a redirection (1 match only) */
5523 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5524  * POSIX says for this case:
5525  *  Pathname expansion shall not be performed on the word by a
5526  *  non-interactive shell; an interactive shell may perform it, but shall
5527  *  do so only when the expansion would result in one word.
5528  * Currently, our code complies to the above rule by never globbing
5529  * redirection filenames.
5530  * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5531  * (this means that on a typical Linux distro, bash almost always
5532  * performs globbing, and thus diverges from what we do).
5533  */
5534 #define EXP_CASE        0x10    /* keeps quotes around for CASE pattern */
5535 #define EXP_QPAT        0x20    /* pattern in quoted parameter expansion */
5536 #define EXP_VARTILDE2   0x40    /* expand tildes after colons only */
5537 #define EXP_WORD        0x80    /* expand word in parameter expansion */
5538 #define EXP_QUOTED      0x100   /* expand word in double quotes */
5539 /*
5540  * rmescape() flags
5541  */
5542 #define RMESCAPE_ALLOC  0x1     /* Allocate a new string */
5543 #define RMESCAPE_GLOB   0x2     /* Add backslashes for glob */
5544 #define RMESCAPE_GROW   0x8     /* Grow strings instead of stalloc */
5545 #define RMESCAPE_HEAP   0x10    /* Malloc strings instead of stalloc */
5546 #define RMESCAPE_SLASH  0x20    /* Stop globbing after slash */
5547
5548 /* Add CTLESC when necessary. */
5549 #define QUOTES_ESC     (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5550 /* Do not skip NUL characters. */
5551 #define QUOTES_KEEPNUL EXP_TILDE
5552
5553 /*
5554  * Structure specifying which parts of the string should be searched
5555  * for IFS characters.
5556  */
5557 struct ifsregion {
5558         struct ifsregion *next; /* next region in list */
5559         int begoff;             /* offset of start of region */
5560         int endoff;             /* offset of end of region */
5561         int nulonly;            /* search for nul bytes only */
5562 };
5563
5564 struct arglist {
5565         struct strlist *list;
5566         struct strlist **lastp;
5567 };
5568
5569 /* output of current string */
5570 static char *expdest;
5571 /* list of back quote expressions */
5572 static struct nodelist *argbackq;
5573 /* first struct in list of ifs regions */
5574 static struct ifsregion ifsfirst;
5575 /* last struct in list */
5576 static struct ifsregion *ifslastp;
5577 /* holds expanded arg list */
5578 static struct arglist exparg;
5579
5580 /*
5581  * Our own itoa().
5582  */
5583 #if !ENABLE_SH_MATH_SUPPORT
5584 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5585 typedef long arith_t;
5586 # define ARITH_FMT "%ld"
5587 #endif
5588 static int
5589 cvtnum(arith_t num)
5590 {
5591         int len;
5592
5593         expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5594         len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5595         STADJUST(len, expdest);
5596         return len;
5597 }
5598
5599 static size_t
5600 esclen(const char *start, const char *p)
5601 {
5602         size_t esc = 0;
5603
5604         while (p > start && (unsigned char)*--p == CTLESC) {
5605                 esc++;
5606         }
5607         return esc;
5608 }
5609
5610 /*
5611  * Remove any CTLESC characters from a string.
5612  */
5613 static char *
5614 rmescapes(char *str, int flag)
5615 {
5616         static const char qchars[] ALIGN1 = {
5617                 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5618
5619         char *p, *q, *r;
5620         unsigned inquotes;
5621         unsigned protect_against_glob;
5622         unsigned globbing;
5623         IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5624
5625         p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5626         if (!p)
5627                 return str;
5628
5629         q = p;
5630         r = str;
5631         if (flag & RMESCAPE_ALLOC) {
5632                 size_t len = p - str;
5633                 size_t fulllen = len + strlen(p) + 1;
5634
5635                 if (flag & RMESCAPE_GROW) {
5636                         int strloc = str - (char *)stackblock();
5637                         r = makestrspace(fulllen, expdest);
5638                         /* p and str may be invalidated by makestrspace */
5639                         str = (char *)stackblock() + strloc;
5640                         p = str + len;
5641                 } else if (flag & RMESCAPE_HEAP) {
5642                         r = ckmalloc(fulllen);
5643                 } else {
5644                         r = stalloc(fulllen);
5645                 }
5646                 q = r;
5647                 if (len > 0) {
5648                         q = (char *)memcpy(q, str, len) + len;
5649                 }
5650         }
5651
5652         inquotes = 0;
5653         globbing = flag & RMESCAPE_GLOB;
5654         protect_against_glob = globbing;
5655         while (*p) {
5656                 if ((unsigned char)*p == CTLQUOTEMARK) {
5657 // Note: both inquotes and protect_against_glob only affect whether
5658                         inquotes = ~inquotes;
5659                         p++;
5660                         protect_against_glob = globbing;
5661                         continue;
5662                 }
5663                 if ((unsigned char)*p == CTLESC) {
5664                         p++;
5665 #if DEBUG
5666                         if (*p == '\0')
5667                                 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5668 #endif
5669                         if (protect_against_glob) {
5670                                 *q++ = '\\';
5671                         }
5672                 } else if (*p == '\\' && !inquotes) {
5673                         /* naked back slash */
5674                         protect_against_glob = 0;
5675                         goto copy;
5676                 }
5677 #if ENABLE_ASH_BASH_COMPAT
5678                 else if (*p == '/' && slash) {
5679                         /* stop handling globbing and mark location of slash */
5680                         globbing = slash = 0;
5681                         *p = CTLESC;
5682                 }
5683 #endif
5684                 protect_against_glob = globbing;
5685  copy:
5686                 *q++ = *p++;
5687         }
5688         *q = '\0';
5689         if (flag & RMESCAPE_GROW) {
5690                 expdest = r;
5691                 STADJUST(q - r + 1, expdest);
5692         }
5693         return r;
5694 }
5695 #define pmatch(a, b) !fnmatch((a), (b), 0)
5696
5697 /*
5698  * Prepare a pattern for a expmeta (internal glob(3)) call.
5699  *
5700  * Returns an stalloced string.
5701  */
5702 static char *
5703 preglob(const char *pattern, int flag)
5704 {
5705         return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5706 }
5707
5708 /*
5709  * Put a string on the stack.
5710  */
5711 static void
5712 memtodest(const char *p, size_t len, int syntax, int quotes)
5713 {
5714         char *q;
5715
5716         if (!len)
5717                 return;
5718
5719         q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5720
5721         do {
5722                 unsigned char c = *p++;
5723                 if (c) {
5724                         int n = SIT(c, syntax);
5725                         if ((quotes & QUOTES_ESC)
5726                          && ((n == CCTL)
5727                             ||  (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5728                                 && n == CBACK)
5729                                 )
5730                         ) {
5731                                 USTPUTC(CTLESC, q);
5732                         }
5733                 } else if (!(quotes & QUOTES_KEEPNUL))
5734                         continue;
5735                 USTPUTC(c, q);
5736         } while (--len);
5737
5738         expdest = q;
5739 }
5740
5741 static size_t
5742 strtodest(const char *p, int syntax, int quotes)
5743 {
5744         size_t len = strlen(p);
5745         memtodest(p, len, syntax, quotes);
5746         return len;
5747 }
5748
5749 /*
5750  * Record the fact that we have to scan this region of the
5751  * string for IFS characters.
5752  */
5753 static void
5754 recordregion(int start, int end, int nulonly)
5755 {
5756         struct ifsregion *ifsp;
5757
5758         if (ifslastp == NULL) {
5759                 ifsp = &ifsfirst;
5760         } else {
5761                 INT_OFF;
5762                 ifsp = ckzalloc(sizeof(*ifsp));
5763                 /*ifsp->next = NULL; - ckzalloc did it */
5764                 ifslastp->next = ifsp;
5765                 INT_ON;
5766         }
5767         ifslastp = ifsp;
5768         ifslastp->begoff = start;
5769         ifslastp->endoff = end;
5770         ifslastp->nulonly = nulonly;
5771 }
5772
5773 static void
5774 removerecordregions(int endoff)
5775 {
5776         if (ifslastp == NULL)
5777                 return;
5778
5779         if (ifsfirst.endoff > endoff) {
5780                 while (ifsfirst.next) {
5781                         struct ifsregion *ifsp;
5782                         INT_OFF;
5783                         ifsp = ifsfirst.next->next;
5784                         free(ifsfirst.next);
5785                         ifsfirst.next = ifsp;
5786                         INT_ON;
5787                 }
5788                 if (ifsfirst.begoff > endoff) {
5789                         ifslastp = NULL;
5790                 } else {
5791                         ifslastp = &ifsfirst;
5792                         ifsfirst.endoff = endoff;
5793                 }
5794                 return;
5795         }
5796
5797         ifslastp = &ifsfirst;
5798         while (ifslastp->next && ifslastp->next->begoff < endoff)
5799                 ifslastp = ifslastp->next;
5800         while (ifslastp->next) {
5801                 struct ifsregion *ifsp;
5802                 INT_OFF;
5803                 ifsp = ifslastp->next->next;
5804                 free(ifslastp->next);
5805                 ifslastp->next = ifsp;
5806                 INT_ON;
5807         }
5808         if (ifslastp->endoff > endoff)
5809                 ifslastp->endoff = endoff;
5810 }
5811
5812 static char *
5813 exptilde(char *startp, char *p, int flags)
5814 {
5815         unsigned char c;
5816         char *name;
5817         struct passwd *pw;
5818         const char *home;
5819         int quotes = flags & QUOTES_ESC;
5820
5821         name = p + 1;
5822
5823         while ((c = *++p) != '\0') {
5824                 switch (c) {
5825                 case CTLESC:
5826                         return startp;
5827                 case CTLQUOTEMARK:
5828                         return startp;
5829                 case ':':
5830                         if (flags & EXP_VARTILDE)
5831                                 goto done;
5832                         break;
5833                 case '/':
5834                 case CTLENDVAR:
5835                         goto done;
5836                 }
5837         }
5838  done:
5839         *p = '\0';
5840         if (*name == '\0') {
5841                 home = lookupvar("HOME");
5842         } else {
5843                 pw = getpwnam(name);
5844                 if (pw == NULL)
5845                         goto lose;
5846                 home = pw->pw_dir;
5847         }
5848         if (!home || !*home)
5849                 goto lose;
5850         *p = c;
5851         strtodest(home, SQSYNTAX, quotes);
5852         return p;
5853  lose:
5854         *p = c;
5855         return startp;
5856 }
5857
5858 /*
5859  * Execute a command inside back quotes.  If it's a builtin command, we
5860  * want to save its output in a block obtained from malloc.  Otherwise
5861  * we fork off a subprocess and get the output of the command via a pipe.
5862  * Should be called with interrupts off.
5863  */
5864 struct backcmd {                /* result of evalbackcmd */
5865         int fd;                 /* file descriptor to read from */
5866         int nleft;              /* number of chars in buffer */
5867         char *buf;              /* buffer */
5868         struct job *jp;         /* job structure for command */
5869 };
5870
5871 /* These forward decls are needed to use "eval" code for backticks handling: */
5872 #define EV_EXIT 01              /* exit after evaluating tree */
5873 static int evaltree(union node *, int);
5874
5875 static void FAST_FUNC
5876 evalbackcmd(union node *n, struct backcmd *result)
5877 {
5878         int pip[2];
5879         struct job *jp;
5880
5881         result->fd = -1;
5882         result->buf = NULL;
5883         result->nleft = 0;
5884         result->jp = NULL;
5885         if (n == NULL) {
5886                 goto out;
5887         }
5888
5889         if (pipe(pip) < 0)
5890                 ash_msg_and_raise_error("pipe call failed");
5891         jp = makejob(/*n,*/ 1);
5892         if (forkshell(jp, n, FORK_NOJOB) == 0) {
5893                 FORCE_INT_ON;
5894                 close(pip[0]);
5895                 if (pip[1] != 1) {
5896                         /*close(1);*/
5897                         copyfd(pip[1], 1 | COPYFD_EXACT);
5898                         close(pip[1]);
5899                 }
5900 /* TODO: eflag clearing makes the following not abort:
5901  *  ash -c 'set -e; z=$(false;echo foo); echo $z'
5902  * which is what bash does (unless it is in POSIX mode).
5903  * dash deleted "eflag = 0" line in the commit
5904  *  Date: Mon, 28 Jun 2010 17:11:58 +1000
5905  *  [EVAL] Don't clear eflag in evalbackcmd
5906  * For now, preserve bash-like behavior, it seems to be somewhat more useful:
5907  */
5908                 eflag = 0;
5909                 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5910                 /* NOTREACHED */
5911         }
5912         close(pip[1]);
5913         result->fd = pip[0];
5914         result->jp = jp;
5915
5916  out:
5917         TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5918                 result->fd, result->buf, result->nleft, result->jp));
5919 }
5920
5921 /*
5922  * Expand stuff in backwards quotes.
5923  */
5924 static void
5925 expbackq(union node *cmd, int flag)
5926 {
5927         struct backcmd in;
5928         int i;
5929         char buf[128];
5930         char *p;
5931         char *dest;
5932         int startloc;
5933         int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5934         struct stackmark smark;
5935
5936         INT_OFF;
5937         startloc = expdest - (char *)stackblock();
5938         pushstackmark(&smark, startloc);
5939         evalbackcmd(cmd, &in);
5940         popstackmark(&smark);
5941
5942         p = in.buf;
5943         i = in.nleft;
5944         if (i == 0)
5945                 goto read;
5946         for (;;) {
5947                 memtodest(p, i, syntax, flag & QUOTES_ESC);
5948  read:
5949                 if (in.fd < 0)
5950                         break;
5951                 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5952                 TRACE(("expbackq: read returns %d\n", i));
5953                 if (i <= 0)
5954                         break;
5955                 p = buf;
5956         }
5957
5958         free(in.buf);
5959         if (in.fd >= 0) {
5960                 close(in.fd);
5961                 back_exitstatus = waitforjob(in.jp);
5962         }
5963         INT_ON;
5964
5965         /* Eat all trailing newlines */
5966         dest = expdest;
5967         for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5968                 STUNPUTC(dest);
5969         expdest = dest;
5970
5971         if (!(flag & EXP_QUOTED))
5972                 recordregion(startloc, dest - (char *)stackblock(), 0);
5973         TRACE(("evalbackq: size:%d:'%.*s'\n",
5974                 (int)((dest - (char *)stackblock()) - startloc),
5975                 (int)((dest - (char *)stackblock()) - startloc),
5976                 stackblock() + startloc));
5977 }
5978
5979 #if ENABLE_SH_MATH_SUPPORT
5980 /*
5981  * Expand arithmetic expression.  Backup to start of expression,
5982  * evaluate, place result in (backed up) result, adjust string position.
5983  */
5984 static void
5985 expari(int flag)
5986 {
5987         char *p, *start;
5988         int begoff;
5989         int len;
5990
5991         /* ifsfree(); */
5992
5993         /*
5994          * This routine is slightly over-complicated for
5995          * efficiency.  Next we scan backwards looking for the
5996          * start of arithmetic.
5997          */
5998         start = stackblock();
5999         p = expdest - 1;
6000         *p = '\0';
6001         p--;
6002         while (1) {
6003                 int esc;
6004
6005                 while ((unsigned char)*p != CTLARI) {
6006                         p--;
6007 #if DEBUG
6008                         if (p < start) {
6009                                 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6010                         }
6011 #endif
6012                 }
6013
6014                 esc = esclen(start, p);
6015                 if (!(esc % 2)) {
6016                         break;
6017                 }
6018
6019                 p -= esc + 1;
6020         }
6021
6022         begoff = p - start;
6023
6024         removerecordregions(begoff);
6025
6026         expdest = p;
6027
6028         if (flag & QUOTES_ESC)
6029                 rmescapes(p + 1, 0);
6030
6031         len = cvtnum(ash_arith(p + 1));
6032
6033         if (!(flag & EXP_QUOTED))
6034                 recordregion(begoff, begoff + len, 0);
6035 }
6036 #endif
6037
6038 /* argstr needs it */
6039 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6040
6041 /*
6042  * Perform variable and command substitution.  If EXP_FULL is set, output CTLESC
6043  * characters to allow for further processing.  Otherwise treat
6044  * $@ like $* since no splitting will be performed.
6045  *
6046  * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6047  * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6048  * for correct expansion of "B=$A" word.
6049  */
6050 static void
6051 argstr(char *p, int flags, struct strlist *var_str_list)
6052 {
6053         static const char spclchars[] ALIGN1 = {
6054                 '=',
6055                 ':',
6056                 CTLQUOTEMARK,
6057                 CTLENDVAR,
6058                 CTLESC,
6059                 CTLVAR,
6060                 CTLBACKQ,
6061 #if ENABLE_SH_MATH_SUPPORT
6062                 CTLENDARI,
6063 #endif
6064                 '\0'
6065         };
6066         const char *reject = spclchars;
6067         int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6068         int inquotes;
6069         size_t length;
6070         int startloc;
6071
6072         if (!(flags & EXP_VARTILDE)) {
6073                 reject += 2;
6074         } else if (flags & EXP_VARTILDE2) {
6075                 reject++;
6076         }
6077         inquotes = 0;
6078         length = 0;
6079         if (flags & EXP_TILDE) {
6080                 char *q;
6081
6082                 flags &= ~EXP_TILDE;
6083  tilde:
6084                 q = p;
6085                 if (*q == '~')
6086                         p = exptilde(p, q, flags);
6087         }
6088  start:
6089         startloc = expdest - (char *)stackblock();
6090         for (;;) {
6091                 unsigned char c;
6092
6093                 length += strcspn(p + length, reject);
6094                 c = p[length];
6095                 if (c) {
6096                         if (!(c & 0x80)
6097                         IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6098                         ) {
6099                                 /* c == '=' || c == ':' || c == CTLENDARI */
6100                                 length++;
6101                         }
6102                 }
6103                 if (length > 0) {
6104                         int newloc;
6105                         expdest = stack_nputstr(p, length, expdest);
6106                         newloc = expdest - (char *)stackblock();
6107                         if (breakall && !inquotes && newloc > startloc) {
6108                                 recordregion(startloc, newloc, 0);
6109                         }
6110                         startloc = newloc;
6111                 }
6112                 p += length + 1;
6113                 length = 0;
6114
6115                 switch (c) {
6116                 case '\0':
6117                         goto breakloop;
6118                 case '=':
6119                         if (flags & EXP_VARTILDE2) {
6120                                 p--;
6121                                 continue;
6122                         }
6123                         flags |= EXP_VARTILDE2;
6124                         reject++;
6125                         /* fall through */
6126                 case ':':
6127                         /*
6128                          * sort of a hack - expand tildes in variable
6129                          * assignments (after the first '=' and after ':'s).
6130                          */
6131                         if (*--p == '~') {
6132                                 goto tilde;
6133                         }
6134                         continue;
6135                 }
6136
6137                 switch (c) {
6138                 case CTLENDVAR: /* ??? */
6139                         goto breakloop;
6140                 case CTLQUOTEMARK:
6141                         inquotes ^= EXP_QUOTED;
6142                         /* "$@" syntax adherence hack */
6143                         if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6144                                 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6145                                 goto start;
6146                         }
6147  addquote:
6148                         if (flags & QUOTES_ESC) {
6149                                 p--;
6150                                 length++;
6151                                 startloc++;
6152                         }
6153                         break;
6154                 case CTLESC:
6155                         startloc++;
6156                         length++;
6157
6158                         /*
6159                          * Quoted parameter expansion pattern: remove quote
6160                          * unless inside inner quotes or we have a literal
6161                          * backslash.
6162                          */
6163                         if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6164                             EXP_QPAT && *p != '\\')
6165                                 break;
6166
6167                         goto addquote;
6168                 case CTLVAR:
6169                         TRACE(("argstr: evalvar('%s')\n", p));
6170                         p = evalvar(p, flags | inquotes, var_str_list);
6171                         TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6172                         goto start;
6173                 case CTLBACKQ:
6174                         expbackq(argbackq->n, flags | inquotes);
6175                         argbackq = argbackq->next;
6176                         goto start;
6177 #if ENABLE_SH_MATH_SUPPORT
6178                 case CTLENDARI:
6179                         p--;
6180                         expari(flags | inquotes);
6181                         goto start;
6182 #endif
6183                 }
6184         }
6185  breakloop: ;
6186 }
6187
6188 static char *
6189 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6190                 char *pattern, int quotes, int zero)
6191 {
6192         char *loc, *loc2;
6193         char c;
6194
6195         loc = startp;
6196         loc2 = rmesc;
6197         do {
6198                 int match;
6199                 const char *s = loc2;
6200
6201                 c = *loc2;
6202                 if (zero) {
6203                         *loc2 = '\0';
6204                         s = rmesc;
6205                 }
6206                 match = pmatch(pattern, s);
6207
6208                 *loc2 = c;
6209                 if (match)
6210                         return loc;
6211                 if (quotes && (unsigned char)*loc == CTLESC)
6212                         loc++;
6213                 loc++;
6214                 loc2++;
6215         } while (c);
6216         return NULL;
6217 }
6218
6219 static char *
6220 scanright(char *startp, char *rmesc, char *rmescend,
6221                 char *pattern, int quotes, int match_at_start)
6222 {
6223 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6224         int try2optimize = match_at_start;
6225 #endif
6226         int esc = 0;
6227         char *loc;
6228         char *loc2;
6229
6230         /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6231          * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6232          * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6233          * Logic:
6234          * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6235          * and on each iteration they go back two/one char until they reach the beginning.
6236          * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6237          */
6238         /* TODO: document in what other circumstances we are called. */
6239
6240         for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6241                 int match;
6242                 char c = *loc2;
6243                 const char *s = loc2;
6244                 if (match_at_start) {
6245                         *loc2 = '\0';
6246                         s = rmesc;
6247                 }
6248                 match = pmatch(pattern, s);
6249                 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6250                 *loc2 = c;
6251                 if (match)
6252                         return loc;
6253 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6254                 if (try2optimize) {
6255                         /* Maybe we can optimize this:
6256                          * if pattern ends with unescaped *, we can avoid checking
6257                          * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6258                          * it wont match truncated "raw_value_of_" strings too.
6259                          */
6260                         unsigned plen = strlen(pattern);
6261                         /* Does it end with "*"? */
6262                         if (plen != 0 && pattern[--plen] == '*') {
6263                                 /* "xxxx*" is not escaped */
6264                                 /* "xxx\*" is escaped */
6265                                 /* "xx\\*" is not escaped */
6266                                 /* "x\\\*" is escaped */
6267                                 int slashes = 0;
6268                                 while (plen != 0 && pattern[--plen] == '\\')
6269                                         slashes++;
6270                                 if (!(slashes & 1))
6271                                         break; /* ends with unescaped "*" */
6272                         }
6273                         try2optimize = 0;
6274                 }
6275 #endif
6276                 loc--;
6277                 if (quotes) {
6278                         if (--esc < 0) {
6279                                 esc = esclen(startp, loc);
6280                         }
6281                         if (esc % 2) {
6282                                 esc--;
6283                                 loc--;
6284                         }
6285                 }
6286         }
6287         return NULL;
6288 }
6289
6290 static void varunset(const char *, const char *, const char *, int) NORETURN;
6291 static void
6292 varunset(const char *end, const char *var, const char *umsg, int varflags)
6293 {
6294         const char *msg;
6295         const char *tail;
6296
6297         tail = nullstr;
6298         msg = "parameter not set";
6299         if (umsg) {
6300                 if ((unsigned char)*end == CTLENDVAR) {
6301                         if (varflags & VSNUL)
6302                                 tail = " or null";
6303                 } else {
6304                         msg = umsg;
6305                 }
6306         }
6307         ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6308 }
6309
6310 static const char *
6311 subevalvar(char *p, char *varname, int strloc, int subtype,
6312                 int startloc, int varflags, int flag, struct strlist *var_str_list)
6313 {
6314         struct nodelist *saveargbackq = argbackq;
6315         int quotes = flag & QUOTES_ESC;
6316         char *startp;
6317         char *loc;
6318         char *rmesc, *rmescend;
6319         char *str;
6320         IF_ASH_BASH_COMPAT(char *repl = NULL;)
6321         IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6322         int amount, resetloc;
6323         IF_ASH_BASH_COMPAT(int workloc;)
6324         int zero;
6325         char *(*scan)(char*, char*, char*, char*, int, int);
6326
6327         //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6328         //              p, varname, strloc, subtype, startloc, varflags, quotes);
6329
6330         argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6331                         (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6332                         var_str_list);
6333         STPUTC('\0', expdest);
6334         argbackq = saveargbackq;
6335         startp = (char *)stackblock() + startloc;
6336
6337         switch (subtype) {
6338         case VSASSIGN:
6339                 setvar0(varname, startp);
6340                 amount = startp - expdest;
6341                 STADJUST(amount, expdest);
6342                 return startp;
6343
6344         case VSQUESTION:
6345                 varunset(p, varname, startp, varflags);
6346                 /* NOTREACHED */
6347
6348 #if ENABLE_ASH_BASH_COMPAT
6349         case VSSUBSTR:
6350 //TODO: support more general format ${v:EXPR:EXPR},
6351 // where EXPR follows $(()) rules
6352                 loc = str = stackblock() + strloc;
6353                 /* Read POS in ${var:POS:LEN} */
6354                 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6355                 len = str - startp - 1;
6356
6357                 /* *loc != '\0', guaranteed by parser */
6358                 if (quotes) {
6359                         char *ptr;
6360
6361                         /* Adjust the length by the number of escapes */
6362                         for (ptr = startp; ptr < (str - 1); ptr++) {
6363                                 if ((unsigned char)*ptr == CTLESC) {
6364                                         len--;
6365                                         ptr++;
6366                                 }
6367                         }
6368                 }
6369                 orig_len = len;
6370
6371                 if (*loc++ == ':') {
6372                         /* ${var::LEN} */
6373                         len = number(loc);
6374                 } else {
6375                         /* Skip POS in ${var:POS:LEN} */
6376                         len = orig_len;
6377                         while (*loc && *loc != ':') {
6378                                 /* TODO?
6379                                  * bash complains on: var=qwe; echo ${var:1a:123}
6380                                 if (!isdigit(*loc))
6381                                         ash_msg_and_raise_error(msg_illnum, str);
6382                                  */
6383                                 loc++;
6384                         }
6385                         if (*loc++ == ':') {
6386                                 len = number(loc);
6387                         }
6388                 }
6389                 if (pos < 0) {
6390                         /* ${VAR:$((-n)):l} starts n chars from the end */
6391                         pos = orig_len + pos;
6392                 }
6393                 if ((unsigned)pos >= orig_len) {
6394                         /* apart from obvious ${VAR:999999:l},
6395                          * covers ${VAR:$((-9999999)):l} - result is ""
6396                          * (bash-compat)
6397                          */
6398                         pos = 0;
6399                         len = 0;
6400                 }
6401                 if (len > (orig_len - pos))
6402                         len = orig_len - pos;
6403
6404                 for (str = startp; pos; str++, pos--) {
6405                         if (quotes && (unsigned char)*str == CTLESC)
6406                                 str++;
6407                 }
6408                 for (loc = startp; len; len--) {
6409                         if (quotes && (unsigned char)*str == CTLESC)
6410                                 *loc++ = *str++;
6411                         *loc++ = *str++;
6412                 }
6413                 *loc = '\0';
6414                 amount = loc - expdest;
6415                 STADJUST(amount, expdest);
6416                 return loc;
6417 #endif
6418         }
6419
6420         resetloc = expdest - (char *)stackblock();
6421
6422         /* We'll comeback here if we grow the stack while handling
6423          * a VSREPLACE or VSREPLACEALL, since our pointers into the
6424          * stack will need rebasing, and we'll need to remove our work
6425          * areas each time
6426          */
6427  IF_ASH_BASH_COMPAT(restart:)
6428
6429         amount = expdest - ((char *)stackblock() + resetloc);
6430         STADJUST(-amount, expdest);
6431         startp = (char *)stackblock() + startloc;
6432
6433         rmesc = startp;
6434         rmescend = (char *)stackblock() + strloc;
6435         if (quotes) {
6436                 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6437                 if (rmesc != startp) {
6438                         rmescend = expdest;
6439                         startp = (char *)stackblock() + startloc;
6440                 }
6441         }
6442         rmescend--;
6443         str = (char *)stackblock() + strloc;
6444         /*
6445          * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6446          * The result is a_\_z_c (not a\_\_z_c)!
6447          *
6448          * The search pattern and replace string treat backslashes differently!
6449          * RMESCAPE_SLASH causes preglob to work differently on the pattern
6450          * and string.  It's only used on the first call.
6451          */
6452         preglob(str, IF_ASH_BASH_COMPAT(
6453                 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6454                         RMESCAPE_SLASH :) 0);
6455
6456 #if ENABLE_ASH_BASH_COMPAT
6457         workloc = expdest - (char *)stackblock();
6458         if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6459                 char *idx, *end;
6460
6461                 if (!repl) {
6462                         repl = strchr(str, CTLESC);
6463                         if (repl)
6464                                 *repl++ = '\0';
6465                         else
6466                                 repl = nullstr;
6467                 }
6468                 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6469
6470                 /* If there's no pattern to match, return the expansion unmolested */
6471                 if (str[0] == '\0')
6472                         return NULL;
6473
6474                 len = 0;
6475                 idx = startp;
6476                 end = str - 1;
6477                 while (idx < end) {
6478  try_to_match:
6479                         loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6480                         //bb_error_msg("scanright('%s'):'%s'", str, loc);
6481                         if (!loc) {
6482                                 /* No match, advance */
6483                                 char *restart_detect = stackblock();
6484  skip_matching:
6485                                 STPUTC(*idx, expdest);
6486                                 if (quotes && (unsigned char)*idx == CTLESC) {
6487                                         idx++;
6488                                         len++;
6489                                         STPUTC(*idx, expdest);
6490                                 }
6491                                 if (stackblock() != restart_detect)
6492                                         goto restart;
6493                                 idx++;
6494                                 len++;
6495                                 rmesc++;
6496                                 /* continue; - prone to quadratic behavior, smarter code: */
6497                                 if (idx >= end)
6498                                         break;
6499                                 if (str[0] == '*') {
6500                                         /* Pattern is "*foo". If "*foo" does not match "long_string",
6501                                          * it would never match "ong_string" etc, no point in trying.
6502                                          */
6503                                         goto skip_matching;
6504                                 }
6505                                 goto try_to_match;
6506                         }
6507
6508                         if (subtype == VSREPLACEALL) {
6509                                 while (idx < loc) {
6510                                         if (quotes && (unsigned char)*idx == CTLESC)
6511                                                 idx++;
6512                                         idx++;
6513                                         rmesc++;
6514                                 }
6515                         } else {
6516                                 idx = loc;
6517                         }
6518
6519                         //bb_error_msg("repl:'%s'", repl);
6520                         for (loc = (char*)repl; *loc; loc++) {
6521                                 char *restart_detect = stackblock();
6522                                 if (quotes && *loc == '\\') {
6523                                         STPUTC(CTLESC, expdest);
6524                                         len++;
6525                                 }
6526                                 STPUTC(*loc, expdest);
6527                                 if (stackblock() != restart_detect)
6528                                         goto restart;
6529                                 len++;
6530                         }
6531
6532                         if (subtype == VSREPLACE) {
6533                                 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6534                                 while (*idx) {
6535                                         char *restart_detect = stackblock();
6536                                         STPUTC(*idx, expdest);
6537                                         if (stackblock() != restart_detect)
6538                                                 goto restart;
6539                                         len++;
6540                                         idx++;
6541                                 }
6542                                 break;
6543                         }
6544                 }
6545
6546                 /* We've put the replaced text into a buffer at workloc, now
6547                  * move it to the right place and adjust the stack.
6548                  */
6549                 STPUTC('\0', expdest);
6550                 startp = (char *)stackblock() + startloc;
6551                 memmove(startp, (char *)stackblock() + workloc, len + 1);
6552                 //bb_error_msg("startp:'%s'", startp);
6553                 amount = expdest - (startp + len);
6554                 STADJUST(-amount, expdest);
6555                 return startp;
6556         }
6557 #endif /* ENABLE_ASH_BASH_COMPAT */
6558
6559         subtype -= VSTRIMRIGHT;
6560 #if DEBUG
6561         if (subtype < 0 || subtype > 7)
6562                 abort();
6563 #endif
6564         /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6565         zero = subtype >> 1;
6566         /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6567         scan = (subtype & 1) ^ zero ? scanleft : scanright;
6568
6569         loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6570         if (loc) {
6571                 if (zero) {
6572                         memmove(startp, loc, str - loc);
6573                         loc = startp + (str - loc) - 1;
6574                 }
6575                 *loc = '\0';
6576                 amount = loc - expdest;
6577                 STADJUST(amount, expdest);
6578         }
6579         return loc;
6580 }
6581
6582 /*
6583  * Add the value of a specialized variable to the stack string.
6584  * name parameter (examples):
6585  * ash -c 'echo $1'      name:'1='
6586  * ash -c 'echo $qwe'    name:'qwe='
6587  * ash -c 'echo $$'      name:'$='
6588  * ash -c 'echo ${$}'    name:'$='
6589  * ash -c 'echo ${$##q}' name:'$=q'
6590  * ash -c 'echo ${#$}'   name:'$='
6591  * note: examples with bad shell syntax:
6592  * ash -c 'echo ${#$1}'  name:'$=1'
6593  * ash -c 'echo ${#1#}'  name:'1=#'
6594  */
6595 static NOINLINE ssize_t
6596 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6597 {
6598         const char *p;
6599         int num;
6600         int i;
6601         ssize_t len = 0;
6602         int sep;
6603         int quoted = *quotedp;
6604         int subtype = varflags & VSTYPE;
6605         int discard = subtype == VSPLUS || subtype == VSLENGTH;
6606         int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6607         int syntax;
6608
6609         sep = (flags & EXP_FULL) << CHAR_BIT;
6610         syntax = quoted ? DQSYNTAX : BASESYNTAX;
6611
6612         switch (*name) {
6613         case '$':
6614                 num = rootpid;
6615                 goto numvar;
6616         case '?':
6617                 num = exitstatus;
6618                 goto numvar;
6619         case '#':
6620                 num = shellparam.nparam;
6621                 goto numvar;
6622         case '!':
6623                 num = backgndpid;
6624                 if (num == 0)
6625                         return -1;
6626  numvar:
6627                 len = cvtnum(num);
6628                 goto check_1char_name;
6629         case '-':
6630                 expdest = makestrspace(NOPTS, expdest);
6631                 for (i = NOPTS - 1; i >= 0; i--) {
6632                         if (optlist[i]) {
6633                                 USTPUTC(optletters(i), expdest);
6634                                 len++;
6635                         }
6636                 }
6637  check_1char_name:
6638 #if 0
6639                 /* handles cases similar to ${#$1} */
6640                 if (name[2] != '\0')
6641                         raise_error_syntax("bad substitution");
6642 #endif
6643                 break;
6644         case '@':
6645                 if (quoted && sep)
6646                         goto param;
6647                 /* fall through */
6648         case '*': {
6649                 char **ap;
6650                 char sepc;
6651
6652                 if (quoted)
6653                         sep = 0;
6654                 sep |= ifsset() ? ifsval()[0] : ' ';
6655  param:
6656                 sepc = sep;
6657                 *quotedp = !sepc;
6658                 ap = shellparam.p;
6659                 if (!ap)
6660                         return -1;
6661                 while ((p = *ap++) != NULL) {
6662                         len += strtodest(p, syntax, quotes);
6663
6664                         if (*ap && sep) {
6665                                 len++;
6666                                 memtodest(&sepc, 1, syntax, quotes);
6667                         }
6668                 }
6669                 break;
6670         } /* case '*' */
6671         case '0':
6672         case '1':
6673         case '2':
6674         case '3':
6675         case '4':
6676         case '5':
6677         case '6':
6678         case '7':
6679         case '8':
6680         case '9':
6681                 num = atoi(name); /* number(name) fails on ${N#str} etc */
6682                 if (num < 0 || num > shellparam.nparam)
6683                         return -1;
6684                 p = num ? shellparam.p[num - 1] : arg0;
6685                 goto value;
6686         default:
6687                 /* NB: name has form "VAR=..." */
6688
6689                 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6690                  * which should be considered before we check variables. */
6691                 if (var_str_list) {
6692                         unsigned name_len = (strchrnul(name, '=') - name) + 1;
6693                         p = NULL;
6694                         do {
6695                                 char *str, *eq;
6696                                 str = var_str_list->text;
6697                                 eq = strchr(str, '=');
6698                                 if (!eq) /* stop at first non-assignment */
6699                                         break;
6700                                 eq++;
6701                                 if (name_len == (unsigned)(eq - str)
6702                                  && strncmp(str, name, name_len) == 0
6703                                 ) {
6704                                         p = eq;
6705                                         /* goto value; - WRONG! */
6706                                         /* think "A=1 A=2 B=$A" */
6707                                 }
6708                                 var_str_list = var_str_list->next;
6709                         } while (var_str_list);
6710                         if (p)
6711                                 goto value;
6712                 }
6713                 p = lookupvar(name);
6714  value:
6715                 if (!p)
6716                         return -1;
6717
6718                 len = strtodest(p, syntax, quotes);
6719 #if ENABLE_UNICODE_SUPPORT
6720                 if (subtype == VSLENGTH && len > 0) {
6721                         reinit_unicode_for_ash();
6722                         if (unicode_status == UNICODE_ON) {
6723                                 STADJUST(-len, expdest);
6724                                 discard = 0;
6725                                 len = unicode_strlen(p);
6726                         }
6727                 }
6728 #endif
6729                 break;
6730         }
6731
6732         if (discard)
6733                 STADJUST(-len, expdest);
6734         return len;
6735 }
6736
6737 /*
6738  * Expand a variable, and return a pointer to the next character in the
6739  * input string.
6740  */
6741 static char *
6742 evalvar(char *p, int flag, struct strlist *var_str_list)
6743 {
6744         char varflags;
6745         char subtype;
6746         int quoted;
6747         char easy;
6748         char *var;
6749         int patloc;
6750         int startloc;
6751         ssize_t varlen;
6752
6753         varflags = (unsigned char) *p++;
6754         subtype = varflags & VSTYPE;
6755         quoted = flag & EXP_QUOTED;
6756         var = p;
6757         easy = (!quoted || (*var == '@' && shellparam.nparam));
6758         startloc = expdest - (char *)stackblock();
6759         p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6760
6761  again:
6762         varlen = varvalue(var, varflags, flag, var_str_list, &quoted);
6763         if (varflags & VSNUL)
6764                 varlen--;
6765
6766         if (subtype == VSPLUS) {
6767                 varlen = -1 - varlen;
6768                 goto vsplus;
6769         }
6770
6771         if (subtype == VSMINUS) {
6772  vsplus:
6773                 if (varlen < 0) {
6774                         argstr(
6775                                 p,
6776                                 flag | EXP_TILDE | EXP_WORD,
6777                                 var_str_list
6778                         );
6779                         goto end;
6780                 }
6781                 goto record;
6782         }
6783
6784         if (subtype == VSASSIGN || subtype == VSQUESTION) {
6785                 if (varlen >= 0)
6786                         goto record;
6787
6788                 subevalvar(p, var, 0, subtype, startloc, varflags,
6789                            flag & ~QUOTES_ESC, var_str_list);
6790                 varflags &= ~VSNUL;
6791                 /*
6792                  * Remove any recorded regions beyond
6793                  * start of variable
6794                  */
6795                 removerecordregions(startloc);
6796                 goto again;
6797         }
6798
6799         if (varlen < 0 && uflag)
6800                 varunset(p, var, 0, 0);
6801
6802         if (subtype == VSLENGTH) {
6803                 cvtnum(varlen > 0 ? varlen : 0);
6804                 goto record;
6805         }
6806
6807         if (subtype == VSNORMAL) {
6808  record:
6809                 if (!easy)
6810                         goto end;
6811                 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6812                 goto end;
6813         }
6814
6815 #if DEBUG
6816         switch (subtype) {
6817         case VSTRIMLEFT:
6818         case VSTRIMLEFTMAX:
6819         case VSTRIMRIGHT:
6820         case VSTRIMRIGHTMAX:
6821 #if ENABLE_ASH_BASH_COMPAT
6822         case VSSUBSTR:
6823         case VSREPLACE:
6824         case VSREPLACEALL:
6825 #endif
6826                 break;
6827         default:
6828                 abort();
6829         }
6830 #endif
6831
6832         if (varlen >= 0) {
6833                 /*
6834                  * Terminate the string and start recording the pattern
6835                  * right after it
6836                  */
6837                 STPUTC('\0', expdest);
6838                 patloc = expdest - (char *)stackblock();
6839                 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6840                                 startloc, varflags, flag, var_str_list)) {
6841                         int amount = expdest - (
6842                                 (char *)stackblock() + patloc - 1
6843                         );
6844                         STADJUST(-amount, expdest);
6845                 }
6846                 /* Remove any recorded regions beyond start of variable */
6847                 removerecordregions(startloc);
6848                 goto record;
6849         }
6850
6851  end:
6852         if (subtype != VSNORMAL) {      /* skip to end of alternative */
6853                 int nesting = 1;
6854                 for (;;) {
6855                         unsigned char c = *p++;
6856                         if (c == CTLESC)
6857                                 p++;
6858                         else if (c == CTLBACKQ) {
6859                                 if (varlen >= 0)
6860                                         argbackq = argbackq->next;
6861                         } else if (c == CTLVAR) {
6862                                 if ((*p++ & VSTYPE) != VSNORMAL)
6863                                         nesting++;
6864                         } else if (c == CTLENDVAR) {
6865                                 if (--nesting == 0)
6866                                         break;
6867                         }
6868                 }
6869         }
6870         return p;
6871 }
6872
6873 /*
6874  * Break the argument string into pieces based upon IFS and add the
6875  * strings to the argument list.  The regions of the string to be
6876  * searched for IFS characters have been stored by recordregion.
6877  */
6878 static void
6879 ifsbreakup(char *string, struct arglist *arglist)
6880 {
6881         struct ifsregion *ifsp;
6882         struct strlist *sp;
6883         char *start;
6884         char *p;
6885         char *q;
6886         const char *ifs, *realifs;
6887         int ifsspc;
6888         int nulonly;
6889
6890         start = string;
6891         if (ifslastp != NULL) {
6892                 ifsspc = 0;
6893                 nulonly = 0;
6894                 realifs = ifsset() ? ifsval() : defifs;
6895                 ifsp = &ifsfirst;
6896                 do {
6897                         p = string + ifsp->begoff;
6898                         nulonly = ifsp->nulonly;
6899                         ifs = nulonly ? nullstr : realifs;
6900                         ifsspc = 0;
6901                         while (p < string + ifsp->endoff) {
6902                                 q = p;
6903                                 if ((unsigned char)*p == CTLESC)
6904                                         p++;
6905                                 if (!strchr(ifs, *p)) {
6906                                         p++;
6907                                         continue;
6908                                 }
6909                                 if (!nulonly)
6910                                         ifsspc = (strchr(defifs, *p) != NULL);
6911                                 /* Ignore IFS whitespace at start */
6912                                 if (q == start && ifsspc) {
6913                                         p++;
6914                                         start = p;
6915                                         continue;
6916                                 }
6917                                 *q = '\0';
6918                                 sp = stzalloc(sizeof(*sp));
6919                                 sp->text = start;
6920                                 *arglist->lastp = sp;
6921                                 arglist->lastp = &sp->next;
6922                                 p++;
6923                                 if (!nulonly) {
6924                                         for (;;) {
6925                                                 if (p >= string + ifsp->endoff) {
6926                                                         break;
6927                                                 }
6928                                                 q = p;
6929                                                 if ((unsigned char)*p == CTLESC)
6930                                                         p++;
6931                                                 if (strchr(ifs, *p) == NULL) {
6932                                                         p = q;
6933                                                         break;
6934                                                 }
6935                                                 if (strchr(defifs, *p) == NULL) {
6936                                                         if (ifsspc) {
6937                                                                 p++;
6938                                                                 ifsspc = 0;
6939                                                         } else {
6940                                                                 p = q;
6941                                                                 break;
6942                                                         }
6943                                                 } else
6944                                                         p++;
6945                                         }
6946                                 }
6947                                 start = p;
6948                         } /* while */
6949                         ifsp = ifsp->next;
6950                 } while (ifsp != NULL);
6951                 if (nulonly)
6952                         goto add;
6953         }
6954
6955         if (!*start)
6956                 return;
6957
6958  add:
6959         sp = stzalloc(sizeof(*sp));
6960         sp->text = start;
6961         *arglist->lastp = sp;
6962         arglist->lastp = &sp->next;
6963 }
6964
6965 static void
6966 ifsfree(void)
6967 {
6968         struct ifsregion *p;
6969
6970         INT_OFF;
6971         p = ifsfirst.next;
6972         do {
6973                 struct ifsregion *ifsp;
6974                 ifsp = p->next;
6975                 free(p);
6976                 p = ifsp;
6977         } while (p);
6978         ifslastp = NULL;
6979         ifsfirst.next = NULL;
6980         INT_ON;
6981 }
6982
6983 /*
6984  * Add a file name to the list.
6985  */
6986 static void
6987 addfname(const char *name)
6988 {
6989         struct strlist *sp;
6990
6991         sp = stzalloc(sizeof(*sp));
6992         sp->text = sstrdup(name);
6993         *exparg.lastp = sp;
6994         exparg.lastp = &sp->next;
6995 }
6996
6997 /* If we want to use glob() from libc... */
6998 #if !ENABLE_ASH_INTERNAL_GLOB
6999
7000 /* Add the result of glob() to the list */
7001 static void
7002 addglob(const glob_t *pglob)
7003 {
7004         char **p = pglob->gl_pathv;
7005
7006         do {
7007                 addfname(*p);
7008         } while (*++p);
7009 }
7010 static void
7011 expandmeta(struct strlist *str /*, int flag*/)
7012 {
7013         /* TODO - EXP_REDIR */
7014
7015         while (str) {
7016                 char *p;
7017                 glob_t pglob;
7018                 int i;
7019
7020                 if (fflag)
7021                         goto nometa;
7022                 INT_OFF;
7023                 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7024 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7025 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7026 //
7027 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7028 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7029 // Which means you need to unescape the string, right? Not so fast:
7030 // if there _is_ a file named "file\?" (with backslash), it is returned
7031 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7032 // You DONT KNOW by looking at the result whether you need to unescape it.
7033 //
7034 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7035 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7036 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7037 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7038 //              i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7039 //              i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7040                 i = glob(p, 0, NULL, &pglob);
7041                 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7042                 if (p != str->text)
7043                         free(p);
7044                 switch (i) {
7045                 case 0:
7046 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7047                         /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7048                         if (!(pglob.gl_flags & GLOB_MAGCHAR))
7049                                 goto nometa2;
7050 #endif
7051                         addglob(&pglob);
7052                         globfree(&pglob);
7053                         INT_ON;
7054                         break;
7055                 case GLOB_NOMATCH:
7056  //nometa2:
7057                         globfree(&pglob);
7058                         INT_ON;
7059  nometa:
7060                         *exparg.lastp = str;
7061                         rmescapes(str->text, 0);
7062                         exparg.lastp = &str->next;
7063                         break;
7064                 default:        /* GLOB_NOSPACE */
7065                         globfree(&pglob);
7066                         INT_ON;
7067                         ash_msg_and_raise_error(bb_msg_memory_exhausted);
7068                 }
7069                 str = str->next;
7070         }
7071 }
7072
7073 #else
7074 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7075
7076 /*
7077  * Do metacharacter (i.e. *, ?, [...]) expansion.
7078  */
7079 static void
7080 expmeta(char *expdir, char *enddir, char *name)
7081 {
7082         char *p;
7083         const char *cp;
7084         char *start;
7085         char *endname;
7086         int metaflag;
7087         struct stat statb;
7088         DIR *dirp;
7089         struct dirent *dp;
7090         int atend;
7091         int matchdot;
7092         int esc;
7093
7094         metaflag = 0;
7095         start = name;
7096         for (p = name; esc = 0, *p; p += esc + 1) {
7097                 if (*p == '*' || *p == '?')
7098                         metaflag = 1;
7099                 else if (*p == '[') {
7100                         char *q = p + 1;
7101                         if (*q == '!')
7102                                 q++;
7103                         for (;;) {
7104                                 if (*q == '\\')
7105                                         q++;
7106                                 if (*q == '/' || *q == '\0')
7107                                         break;
7108                                 if (*++q == ']') {
7109                                         metaflag = 1;
7110                                         break;
7111                                 }
7112                         }
7113                 } else {
7114                         if (*p == '\\')
7115                                 esc++;
7116                         if (p[esc] == '/') {
7117                                 if (metaflag)
7118                                         break;
7119                                 start = p + esc + 1;
7120                         }
7121                 }
7122         }
7123         if (metaflag == 0) {    /* we've reached the end of the file name */
7124                 if (enddir != expdir)
7125                         metaflag++;
7126                 p = name;
7127                 do {
7128                         if (*p == '\\')
7129                                 p++;
7130                         *enddir++ = *p;
7131                 } while (*p++);
7132                 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7133                         addfname(expdir);
7134                 return;
7135         }
7136         endname = p;
7137         if (name < start) {
7138                 p = name;
7139                 do {
7140                         if (*p == '\\')
7141                                 p++;
7142                         *enddir++ = *p++;
7143                 } while (p < start);
7144         }
7145         if (enddir == expdir) {
7146                 cp = ".";
7147         } else if (enddir == expdir + 1 && *expdir == '/') {
7148                 cp = "/";
7149         } else {
7150                 cp = expdir;
7151                 enddir[-1] = '\0';
7152         }
7153         dirp = opendir(cp);
7154         if (dirp == NULL)
7155                 return;
7156         if (enddir != expdir)
7157                 enddir[-1] = '/';
7158         if (*endname == 0) {
7159                 atend = 1;
7160         } else {
7161                 atend = 0;
7162                 *endname = '\0';
7163                 endname += esc + 1;
7164         }
7165         matchdot = 0;
7166         p = start;
7167         if (*p == '\\')
7168                 p++;
7169         if (*p == '.')
7170                 matchdot++;
7171         while (!pending_int && (dp = readdir(dirp)) != NULL) {
7172                 if (dp->d_name[0] == '.' && !matchdot)
7173                         continue;
7174                 if (pmatch(start, dp->d_name)) {
7175                         if (atend) {
7176                                 strcpy(enddir, dp->d_name);
7177                                 addfname(expdir);
7178                         } else {
7179                                 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7180                                         continue;
7181                                 p[-1] = '/';
7182                                 expmeta(expdir, p, endname);
7183                         }
7184                 }
7185         }
7186         closedir(dirp);
7187         if (!atend)
7188                 endname[-esc - 1] = esc ? '\\' : '/';
7189 }
7190
7191 static struct strlist *
7192 msort(struct strlist *list, int len)
7193 {
7194         struct strlist *p, *q = NULL;
7195         struct strlist **lpp;
7196         int half;
7197         int n;
7198
7199         if (len <= 1)
7200                 return list;
7201         half = len >> 1;
7202         p = list;
7203         for (n = half; --n >= 0;) {
7204                 q = p;
7205                 p = p->next;
7206         }
7207         q->next = NULL;                 /* terminate first half of list */
7208         q = msort(list, half);          /* sort first half of list */
7209         p = msort(p, len - half);               /* sort second half */
7210         lpp = &list;
7211         for (;;) {
7212 #if ENABLE_LOCALE_SUPPORT
7213                 if (strcoll(p->text, q->text) < 0)
7214 #else
7215                 if (strcmp(p->text, q->text) < 0)
7216 #endif
7217                                                 {
7218                         *lpp = p;
7219                         lpp = &p->next;
7220                         p = *lpp;
7221                         if (p == NULL) {
7222                                 *lpp = q;
7223                                 break;
7224                         }
7225                 } else {
7226                         *lpp = q;
7227                         lpp = &q->next;
7228                         q = *lpp;
7229                         if (q == NULL) {
7230                                 *lpp = p;
7231                                 break;
7232                         }
7233                 }
7234         }
7235         return list;
7236 }
7237
7238 /*
7239  * Sort the results of file name expansion.  It calculates the number of
7240  * strings to sort and then calls msort (short for merge sort) to do the
7241  * work.
7242  */
7243 static struct strlist *
7244 expsort(struct strlist *str)
7245 {
7246         int len;
7247         struct strlist *sp;
7248
7249         len = 0;
7250         for (sp = str; sp; sp = sp->next)
7251                 len++;
7252         return msort(str, len);
7253 }
7254
7255 static void
7256 expandmeta(struct strlist *str /*, int flag*/)
7257 {
7258         static const char metachars[] ALIGN1 = {
7259                 '*', '?', '[', 0
7260         };
7261         /* TODO - EXP_REDIR */
7262
7263         while (str) {
7264                 char *expdir;
7265                 struct strlist **savelastp;
7266                 struct strlist *sp;
7267                 char *p;
7268
7269                 if (fflag)
7270                         goto nometa;
7271                 if (!strpbrk(str->text, metachars))
7272                         goto nometa;
7273                 savelastp = exparg.lastp;
7274
7275                 INT_OFF;
7276                 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7277                 {
7278                         int i = strlen(str->text);
7279 //BUGGY estimation of how long expanded name can be
7280                         expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7281                 }
7282                 expmeta(expdir, expdir, p);
7283                 free(expdir);
7284                 if (p != str->text)
7285                         free(p);
7286                 INT_ON;
7287                 if (exparg.lastp == savelastp) {
7288                         /*
7289                          * no matches
7290                          */
7291  nometa:
7292                         *exparg.lastp = str;
7293                         rmescapes(str->text, 0);
7294                         exparg.lastp = &str->next;
7295                 } else {
7296                         *exparg.lastp = NULL;
7297                         *savelastp = sp = expsort(*savelastp);
7298                         while (sp->next != NULL)
7299                                 sp = sp->next;
7300                         exparg.lastp = &sp->next;
7301                 }
7302                 str = str->next;
7303         }
7304 }
7305 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7306
7307 /*
7308  * Perform variable substitution and command substitution on an argument,
7309  * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
7310  * perform splitting and file name expansion.  When arglist is NULL, perform
7311  * here document expansion.
7312  */
7313 static void
7314 expandarg(union node *arg, struct arglist *arglist, int flag)
7315 {
7316         struct strlist *sp;
7317         char *p;
7318
7319         argbackq = arg->narg.backquote;
7320         STARTSTACKSTR(expdest);
7321         ifsfirst.next = NULL;
7322         ifslastp = NULL;
7323         TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7324         argstr(arg->narg.text, flag,
7325                         /* var_str_list: */ arglist ? arglist->list : NULL);
7326         p = _STPUTC('\0', expdest);
7327         expdest = p - 1;
7328         if (arglist == NULL) {
7329                 return;                 /* here document expanded */
7330         }
7331         p = grabstackstr(p);
7332         TRACE(("expandarg: p:'%s'\n", p));
7333         exparg.lastp = &exparg.list;
7334         /*
7335          * TODO - EXP_REDIR
7336          */
7337         if (flag & EXP_FULL) {
7338                 ifsbreakup(p, &exparg);
7339                 *exparg.lastp = NULL;
7340                 exparg.lastp = &exparg.list;
7341                 expandmeta(exparg.list /*, flag*/);
7342         } else {
7343                 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7344                         rmescapes(p, 0);
7345                         TRACE(("expandarg: rmescapes:'%s'\n", p));
7346                 }
7347                 sp = stzalloc(sizeof(*sp));
7348                 sp->text = p;
7349                 *exparg.lastp = sp;
7350                 exparg.lastp = &sp->next;
7351         }
7352         if (ifsfirst.next)
7353                 ifsfree();
7354         *exparg.lastp = NULL;
7355         if (exparg.list) {
7356                 *arglist->lastp = exparg.list;
7357                 arglist->lastp = exparg.lastp;
7358         }
7359 }
7360
7361 /*
7362  * Expand shell variables and backquotes inside a here document.
7363  */
7364 static void
7365 expandhere(union node *arg, int fd)
7366 {
7367         expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7368         full_write(fd, stackblock(), expdest - (char *)stackblock());
7369 }
7370
7371 /*
7372  * Returns true if the pattern matches the string.
7373  */
7374 static int
7375 patmatch(char *pattern, const char *string)
7376 {
7377         return pmatch(preglob(pattern, 0), string);
7378 }
7379
7380 /*
7381  * See if a pattern matches in a case statement.
7382  */
7383 static int
7384 casematch(union node *pattern, char *val)
7385 {
7386         struct stackmark smark;
7387         int result;
7388
7389         setstackmark(&smark);
7390         argbackq = pattern->narg.backquote;
7391         STARTSTACKSTR(expdest);
7392         ifslastp = NULL;
7393         argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7394                         /* var_str_list: */ NULL);
7395         STACKSTRNUL(expdest);
7396         result = patmatch(stackblock(), val);
7397         popstackmark(&smark);
7398         return result;
7399 }
7400
7401
7402 /* ============ find_command */
7403
7404 struct builtincmd {
7405         const char *name;
7406         int (*builtin)(int, char **) FAST_FUNC;
7407         /* unsigned flags; */
7408 };
7409 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7410 /* "regular" builtins always take precedence over commands,
7411  * regardless of PATH=....%builtin... position */
7412 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7413 #define IS_BUILTIN_ASSIGN(b)  ((b)->name[0] & 4)
7414
7415 struct cmdentry {
7416         smallint cmdtype;       /* CMDxxx */
7417         union param {
7418                 int index;
7419                 /* index >= 0 for commands without path (slashes) */
7420                 /* (TODO: what exactly does the value mean? PATH position?) */
7421                 /* index == -1 for commands with slashes */
7422                 /* index == (-2 - applet_no) for NOFORK applets */
7423                 const struct builtincmd *cmd;
7424                 struct funcnode *func;
7425         } u;
7426 };
7427 /* values of cmdtype */
7428 #define CMDUNKNOWN      -1      /* no entry in table for command */
7429 #define CMDNORMAL       0       /* command is an executable program */
7430 #define CMDFUNCTION     1       /* command is a shell function */
7431 #define CMDBUILTIN      2       /* command is a shell builtin */
7432
7433 /* action to find_command() */
7434 #define DO_ERR          0x01    /* prints errors */
7435 #define DO_ABS          0x02    /* checks absolute paths */
7436 #define DO_NOFUNC       0x04    /* don't return shell functions, for command */
7437 #define DO_ALTPATH      0x08    /* using alternate path */
7438 #define DO_ALTBLTIN     0x20    /* %builtin in alt. path */
7439
7440 static void find_command(char *, struct cmdentry *, int, const char *);
7441
7442
7443 /* ============ Hashing commands */
7444
7445 /*
7446  * When commands are first encountered, they are entered in a hash table.
7447  * This ensures that a full path search will not have to be done for them
7448  * on each invocation.
7449  *
7450  * We should investigate converting to a linear search, even though that
7451  * would make the command name "hash" a misnomer.
7452  */
7453
7454 struct tblentry {
7455         struct tblentry *next;  /* next entry in hash chain */
7456         union param param;      /* definition of builtin function */
7457         smallint cmdtype;       /* CMDxxx */
7458         char rehash;            /* if set, cd done since entry created */
7459         char cmdname[1];        /* name of command */
7460 };
7461
7462 static struct tblentry **cmdtable;
7463 #define INIT_G_cmdtable() do { \
7464         cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7465 } while (0)
7466
7467 static int builtinloc = -1;     /* index in path of %builtin, or -1 */
7468
7469
7470 static void
7471 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7472 {
7473 #if ENABLE_FEATURE_SH_STANDALONE
7474         if (applet_no >= 0) {
7475                 if (APPLET_IS_NOEXEC(applet_no)) {
7476                         clearenv();
7477                         while (*envp)
7478                                 putenv(*envp++);
7479                         run_applet_no_and_exit(applet_no, argv);
7480                 }
7481                 /* re-exec ourselves with the new arguments */
7482                 execve(bb_busybox_exec_path, argv, envp);
7483                 /* If they called chroot or otherwise made the binary no longer
7484                  * executable, fall through */
7485         }
7486 #endif
7487
7488  repeat:
7489 #ifdef SYSV
7490         do {
7491                 execve(cmd, argv, envp);
7492         } while (errno == EINTR);
7493 #else
7494         execve(cmd, argv, envp);
7495 #endif
7496         if (cmd == (char*) bb_busybox_exec_path) {
7497                 /* We already visited ENOEXEC branch below, don't do it again */
7498 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7499                 free(argv);
7500                 return;
7501         }
7502         if (errno == ENOEXEC) {
7503                 /* Run "cmd" as a shell script:
7504                  * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7505                  * "If the execve() function fails with ENOEXEC, the shell
7506                  * shall execute a command equivalent to having a shell invoked
7507                  * with the command name as its first operand,
7508                  * with any remaining arguments passed to the new shell"
7509                  *
7510                  * That is, do not use $SHELL, user's shell, or /bin/sh;
7511                  * just call ourselves.
7512                  *
7513                  * Note that bash reads ~80 chars of the file, and if it sees
7514                  * a zero byte before it sees newline, it doesn't try to
7515                  * interpret it, but fails with "cannot execute binary file"
7516                  * message and exit code 126. For one, this prevents attempts
7517                  * to interpret foreign ELF binaries as shell scripts.
7518                  */
7519                 char **ap;
7520                 char **new;
7521
7522                 for (ap = argv; *ap; ap++)
7523                         continue;
7524                 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7525                 new[0] = (char*) "ash";
7526                 new[1] = cmd;
7527                 ap = new + 2;
7528                 while ((*ap++ = *++argv) != NULL)
7529                         continue;
7530                 cmd = (char*) bb_busybox_exec_path;
7531                 argv = new;
7532                 goto repeat;
7533         }
7534 }
7535
7536 /*
7537  * Exec a program.  Never returns.  If you change this routine, you may
7538  * have to change the find_command routine as well.
7539  */
7540 static void shellexec(char **, const char *, int) NORETURN;
7541 static void
7542 shellexec(char **argv, const char *path, int idx)
7543 {
7544         char *cmdname;
7545         int e;
7546         char **envp;
7547         int exerrno;
7548         int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7549
7550         clearredir(/*drop:*/ 1);
7551         envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7552         if (strchr(argv[0], '/') != NULL
7553 #if ENABLE_FEATURE_SH_STANDALONE
7554          || (applet_no = find_applet_by_name(argv[0])) >= 0
7555 #endif
7556         ) {
7557                 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7558                 if (applet_no >= 0) {
7559                         /* We tried execing ourself, but it didn't work.
7560                          * Maybe /proc/self/exe doesn't exist?
7561                          * Try $PATH search.
7562                          */
7563                         goto try_PATH;
7564                 }
7565                 e = errno;
7566         } else {
7567  try_PATH:
7568                 e = ENOENT;
7569                 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7570                         if (--idx < 0 && pathopt == NULL) {
7571                                 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7572                                 if (errno != ENOENT && errno != ENOTDIR)
7573                                         e = errno;
7574                         }
7575                         stunalloc(cmdname);
7576                 }
7577         }
7578
7579         /* Map to POSIX errors */
7580         switch (e) {
7581         case EACCES:
7582                 exerrno = 126;
7583                 break;
7584         case ENOENT:
7585                 exerrno = 127;
7586                 break;
7587         default:
7588                 exerrno = 2;
7589                 break;
7590         }
7591         exitstatus = exerrno;
7592         TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7593                 argv[0], e, suppress_int));
7594         ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7595         /* NOTREACHED */
7596 }
7597
7598 static void
7599 printentry(struct tblentry *cmdp)
7600 {
7601         int idx;
7602         const char *path;
7603         char *name;
7604
7605         idx = cmdp->param.index;
7606         path = pathval();
7607         do {
7608                 name = path_advance(&path, cmdp->cmdname);
7609                 stunalloc(name);
7610         } while (--idx >= 0);
7611         out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7612 }
7613
7614 /*
7615  * Clear out command entries.  The argument specifies the first entry in
7616  * PATH which has changed.
7617  */
7618 static void
7619 clearcmdentry(int firstchange)
7620 {
7621         struct tblentry **tblp;
7622         struct tblentry **pp;
7623         struct tblentry *cmdp;
7624
7625         INT_OFF;
7626         for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7627                 pp = tblp;
7628                 while ((cmdp = *pp) != NULL) {
7629                         if ((cmdp->cmdtype == CMDNORMAL &&
7630                              cmdp->param.index >= firstchange)
7631                          || (cmdp->cmdtype == CMDBUILTIN &&
7632                              builtinloc >= firstchange)
7633                         ) {
7634                                 *pp = cmdp->next;
7635                                 free(cmdp);
7636                         } else {
7637                                 pp = &cmdp->next;
7638                         }
7639                 }
7640         }
7641         INT_ON;
7642 }
7643
7644 /*
7645  * Locate a command in the command hash table.  If "add" is nonzero,
7646  * add the command to the table if it is not already present.  The
7647  * variable "lastcmdentry" is set to point to the address of the link
7648  * pointing to the entry, so that delete_cmd_entry can delete the
7649  * entry.
7650  *
7651  * Interrupts must be off if called with add != 0.
7652  */
7653 static struct tblentry **lastcmdentry;
7654
7655 static struct tblentry *
7656 cmdlookup(const char *name, int add)
7657 {
7658         unsigned int hashval;
7659         const char *p;
7660         struct tblentry *cmdp;
7661         struct tblentry **pp;
7662
7663         p = name;
7664         hashval = (unsigned char)*p << 4;
7665         while (*p)
7666                 hashval += (unsigned char)*p++;
7667         hashval &= 0x7FFF;
7668         pp = &cmdtable[hashval % CMDTABLESIZE];
7669         for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7670                 if (strcmp(cmdp->cmdname, name) == 0)
7671                         break;
7672                 pp = &cmdp->next;
7673         }
7674         if (add && cmdp == NULL) {
7675                 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7676                                 + strlen(name)
7677                                 /* + 1 - already done because
7678                                  * tblentry::cmdname is char[1] */);
7679                 /*cmdp->next = NULL; - ckzalloc did it */
7680                 cmdp->cmdtype = CMDUNKNOWN;
7681                 strcpy(cmdp->cmdname, name);
7682         }
7683         lastcmdentry = pp;
7684         return cmdp;
7685 }
7686
7687 /*
7688  * Delete the command entry returned on the last lookup.
7689  */
7690 static void
7691 delete_cmd_entry(void)
7692 {
7693         struct tblentry *cmdp;
7694
7695         INT_OFF;
7696         cmdp = *lastcmdentry;
7697         *lastcmdentry = cmdp->next;
7698         if (cmdp->cmdtype == CMDFUNCTION)
7699                 freefunc(cmdp->param.func);
7700         free(cmdp);
7701         INT_ON;
7702 }
7703
7704 /*
7705  * Add a new command entry, replacing any existing command entry for
7706  * the same name - except special builtins.
7707  */
7708 static void
7709 addcmdentry(char *name, struct cmdentry *entry)
7710 {
7711         struct tblentry *cmdp;
7712
7713         cmdp = cmdlookup(name, 1);
7714         if (cmdp->cmdtype == CMDFUNCTION) {
7715                 freefunc(cmdp->param.func);
7716         }
7717         cmdp->cmdtype = entry->cmdtype;
7718         cmdp->param = entry->u;
7719         cmdp->rehash = 0;
7720 }
7721
7722 static int FAST_FUNC
7723 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7724 {
7725         struct tblentry **pp;
7726         struct tblentry *cmdp;
7727         int c;
7728         struct cmdentry entry;
7729         char *name;
7730
7731         if (nextopt("r") != '\0') {
7732                 clearcmdentry(0);
7733                 return 0;
7734         }
7735
7736         if (*argptr == NULL) {
7737                 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7738                         for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7739                                 if (cmdp->cmdtype == CMDNORMAL)
7740                                         printentry(cmdp);
7741                         }
7742                 }
7743                 return 0;
7744         }
7745
7746         c = 0;
7747         while ((name = *argptr) != NULL) {
7748                 cmdp = cmdlookup(name, 0);
7749                 if (cmdp != NULL
7750                  && (cmdp->cmdtype == CMDNORMAL
7751                      || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7752                 ) {
7753                         delete_cmd_entry();
7754                 }
7755                 find_command(name, &entry, DO_ERR, pathval());
7756                 if (entry.cmdtype == CMDUNKNOWN)
7757                         c = 1;
7758                 argptr++;
7759         }
7760         return c;
7761 }
7762
7763 /*
7764  * Called when a cd is done.  Marks all commands so the next time they
7765  * are executed they will be rehashed.
7766  */
7767 static void
7768 hashcd(void)
7769 {
7770         struct tblentry **pp;
7771         struct tblentry *cmdp;
7772
7773         for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7774                 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7775                         if (cmdp->cmdtype == CMDNORMAL
7776                          || (cmdp->cmdtype == CMDBUILTIN
7777                              && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7778                              && builtinloc > 0)
7779                         ) {
7780                                 cmdp->rehash = 1;
7781                         }
7782                 }
7783         }
7784 }
7785
7786 /*
7787  * Fix command hash table when PATH changed.
7788  * Called before PATH is changed.  The argument is the new value of PATH;
7789  * pathval() still returns the old value at this point.
7790  * Called with interrupts off.
7791  */
7792 static void FAST_FUNC
7793 changepath(const char *new)
7794 {
7795         const char *old;
7796         int firstchange;
7797         int idx;
7798         int idx_bltin;
7799
7800         old = pathval();
7801         firstchange = 9999;     /* assume no change */
7802         idx = 0;
7803         idx_bltin = -1;
7804         for (;;) {
7805                 if (*old != *new) {
7806                         firstchange = idx;
7807                         if ((*old == '\0' && *new == ':')
7808                          || (*old == ':' && *new == '\0')
7809                         ) {
7810                                 firstchange++;
7811                         }
7812                         old = new;      /* ignore subsequent differences */
7813                 }
7814                 if (*new == '\0')
7815                         break;
7816                 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7817                         idx_bltin = idx;
7818                 if (*new == ':')
7819                         idx++;
7820                 new++;
7821                 old++;
7822         }
7823         if (builtinloc < 0 && idx_bltin >= 0)
7824                 builtinloc = idx_bltin;             /* zap builtins */
7825         if (builtinloc >= 0 && idx_bltin < 0)
7826                 firstchange = 0;
7827         clearcmdentry(firstchange);
7828         builtinloc = idx_bltin;
7829 }
7830 enum {
7831         TEOF,
7832         TNL,
7833         TREDIR,
7834         TWORD,
7835         TSEMI,
7836         TBACKGND,
7837         TAND,
7838         TOR,
7839         TPIPE,
7840         TLP,
7841         TRP,
7842         TENDCASE,
7843         TENDBQUOTE,
7844         TNOT,
7845         TCASE,
7846         TDO,
7847         TDONE,
7848         TELIF,
7849         TELSE,
7850         TESAC,
7851         TFI,
7852         TFOR,
7853 #if ENABLE_ASH_BASH_COMPAT
7854         TFUNCTION,
7855 #endif
7856         TIF,
7857         TIN,
7858         TTHEN,
7859         TUNTIL,
7860         TWHILE,
7861         TBEGIN,
7862         TEND
7863 };
7864 typedef smallint token_id_t;
7865
7866 /* Nth bit indicates if token marks the end of a list */
7867 enum {
7868         tokendlist = 0
7869         /*  0 */ | (1u << TEOF)
7870         /*  1 */ | (0u << TNL)
7871         /*  2 */ | (0u << TREDIR)
7872         /*  3 */ | (0u << TWORD)
7873         /*  4 */ | (0u << TSEMI)
7874         /*  5 */ | (0u << TBACKGND)
7875         /*  6 */ | (0u << TAND)
7876         /*  7 */ | (0u << TOR)
7877         /*  8 */ | (0u << TPIPE)
7878         /*  9 */ | (0u << TLP)
7879         /* 10 */ | (1u << TRP)
7880         /* 11 */ | (1u << TENDCASE)
7881         /* 12 */ | (1u << TENDBQUOTE)
7882         /* 13 */ | (0u << TNOT)
7883         /* 14 */ | (0u << TCASE)
7884         /* 15 */ | (1u << TDO)
7885         /* 16 */ | (1u << TDONE)
7886         /* 17 */ | (1u << TELIF)
7887         /* 18 */ | (1u << TELSE)
7888         /* 19 */ | (1u << TESAC)
7889         /* 20 */ | (1u << TFI)
7890         /* 21 */ | (0u << TFOR)
7891 #if ENABLE_ASH_BASH_COMPAT
7892         /* 22 */ | (0u << TFUNCTION)
7893 #endif
7894         /* 23 */ | (0u << TIF)
7895         /* 24 */ | (0u << TIN)
7896         /* 25 */ | (1u << TTHEN)
7897         /* 26 */ | (0u << TUNTIL)
7898         /* 27 */ | (0u << TWHILE)
7899         /* 28 */ | (0u << TBEGIN)
7900         /* 29 */ | (1u << TEND)
7901         , /* thus far 29 bits used */
7902 };
7903
7904 static const char *const tokname_array[] = {
7905         "end of file",
7906         "newline",
7907         "redirection",
7908         "word",
7909         ";",
7910         "&",
7911         "&&",
7912         "||",
7913         "|",
7914         "(",
7915         ")",
7916         ";;",
7917         "`",
7918 #define KWDOFFSET 13
7919         /* the following are keywords */
7920         "!",
7921         "case",
7922         "do",
7923         "done",
7924         "elif",
7925         "else",
7926         "esac",
7927         "fi",
7928         "for",
7929 #if ENABLE_ASH_BASH_COMPAT
7930         "function",
7931 #endif
7932         "if",
7933         "in",
7934         "then",
7935         "until",
7936         "while",
7937         "{",
7938         "}",
7939 };
7940
7941 /* Wrapper around strcmp for qsort/bsearch/... */
7942 static int
7943 pstrcmp(const void *a, const void *b)
7944 {
7945         return strcmp((char*)a, *(char**)b);
7946 }
7947
7948 static const char *const *
7949 findkwd(const char *s)
7950 {
7951         return bsearch(s, tokname_array + KWDOFFSET,
7952                         ARRAY_SIZE(tokname_array) - KWDOFFSET,
7953                         sizeof(tokname_array[0]), pstrcmp);
7954 }
7955
7956 /*
7957  * Locate and print what a word is...
7958  */
7959 static int
7960 describe_command(char *command, const char *path, int describe_command_verbose)
7961 {
7962         struct cmdentry entry;
7963         struct tblentry *cmdp;
7964 #if ENABLE_ASH_ALIAS
7965         const struct alias *ap;
7966 #endif
7967
7968         path = path ? path : pathval();
7969
7970         if (describe_command_verbose) {
7971                 out1str(command);
7972         }
7973
7974         /* First look at the keywords */
7975         if (findkwd(command)) {
7976                 out1str(describe_command_verbose ? " is a shell keyword" : command);
7977                 goto out;
7978         }
7979
7980 #if ENABLE_ASH_ALIAS
7981         /* Then look at the aliases */
7982         ap = lookupalias(command, 0);
7983         if (ap != NULL) {
7984                 if (!describe_command_verbose) {
7985                         out1str("alias ");
7986                         printalias(ap);
7987                         return 0;
7988                 }
7989                 out1fmt(" is an alias for %s", ap->val);
7990                 goto out;
7991         }
7992 #endif
7993         /* Then check if it is a tracked alias */
7994         cmdp = cmdlookup(command, 0);
7995         if (cmdp != NULL) {
7996                 entry.cmdtype = cmdp->cmdtype;
7997                 entry.u = cmdp->param;
7998         } else {
7999                 /* Finally use brute force */
8000                 find_command(command, &entry, DO_ABS, path);
8001         }
8002
8003         switch (entry.cmdtype) {
8004         case CMDNORMAL: {
8005                 int j = entry.u.index;
8006                 char *p;
8007                 if (j < 0) {
8008                         p = command;
8009                 } else {
8010                         do {
8011                                 p = path_advance(&path, command);
8012                                 stunalloc(p);
8013                         } while (--j >= 0);
8014                 }
8015                 if (describe_command_verbose) {
8016                         out1fmt(" is%s %s",
8017                                 (cmdp ? " a tracked alias for" : nullstr), p
8018                         );
8019                 } else {
8020                         out1str(p);
8021                 }
8022                 break;
8023         }
8024
8025         case CMDFUNCTION:
8026                 if (describe_command_verbose) {
8027                         out1str(" is a shell function");
8028                 } else {
8029                         out1str(command);
8030                 }
8031                 break;
8032
8033         case CMDBUILTIN:
8034                 if (describe_command_verbose) {
8035                         out1fmt(" is a %sshell builtin",
8036                                 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8037                                         "special " : nullstr
8038                         );
8039                 } else {
8040                         out1str(command);
8041                 }
8042                 break;
8043
8044         default:
8045                 if (describe_command_verbose) {
8046                         out1str(": not found\n");
8047                 }
8048                 return 127;
8049         }
8050  out:
8051         out1str("\n");
8052         return 0;
8053 }
8054
8055 static int FAST_FUNC
8056 typecmd(int argc UNUSED_PARAM, char **argv)
8057 {
8058         int i = 1;
8059         int err = 0;
8060         int verbose = 1;
8061
8062         /* type -p ... ? (we don't bother checking for 'p') */
8063         if (argv[1] && argv[1][0] == '-') {
8064                 i++;
8065                 verbose = 0;
8066         }
8067         while (argv[i]) {
8068                 err |= describe_command(argv[i++], NULL, verbose);
8069         }
8070         return err;
8071 }
8072
8073 #if ENABLE_ASH_CMDCMD
8074 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8075 static char **
8076 parse_command_args(char **argv, const char **path)
8077 {
8078         char *cp, c;
8079
8080         for (;;) {
8081                 cp = *++argv;
8082                 if (!cp)
8083                         return NULL;
8084                 if (*cp++ != '-')
8085                         break;
8086                 c = *cp++;
8087                 if (!c)
8088                         break;
8089                 if (c == '-' && !*cp) {
8090                         if (!*++argv)
8091                                 return NULL;
8092                         break;
8093                 }
8094                 do {
8095                         switch (c) {
8096                         case 'p':
8097                                 *path = bb_default_path;
8098                                 break;
8099                         default:
8100                                 /* run 'typecmd' for other options */
8101                                 return NULL;
8102                         }
8103                         c = *cp++;
8104                 } while (c);
8105         }
8106         return argv;
8107 }
8108
8109 static int FAST_FUNC
8110 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8111 {
8112         char *cmd;
8113         int c;
8114         enum {
8115                 VERIFY_BRIEF = 1,
8116                 VERIFY_VERBOSE = 2,
8117         } verify = 0;
8118         const char *path = NULL;
8119
8120         /* "command [-p] PROG ARGS" (that is, without -V or -v)
8121          * never reaches this function.
8122          */
8123
8124         while ((c = nextopt("pvV")) != '\0')
8125                 if (c == 'V')
8126                         verify |= VERIFY_VERBOSE;
8127                 else if (c == 'v')
8128                         /*verify |= VERIFY_BRIEF*/;
8129 #if DEBUG
8130                 else if (c != 'p')
8131                         abort();
8132 #endif
8133                 else
8134                         path = bb_default_path;
8135
8136         /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8137         cmd = *argptr;
8138         if (/*verify && */ cmd)
8139                 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8140
8141         return 0;
8142 }
8143 #endif
8144
8145
8146 /*static int funcblocksize;     // size of structures in function */
8147 /*static int funcstringsize;    // size of strings in node */
8148 static void *funcblock;         /* block to allocate function from */
8149 static char *funcstring_end;    /* end of block to allocate strings from */
8150
8151 /* flags in argument to evaltree */
8152 #define EV_EXIT    01           /* exit after evaluating tree */
8153 #define EV_TESTED  02           /* exit status is checked; ignore -e flag */
8154
8155 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8156         [NCMD     ] = SHELL_ALIGN(sizeof(struct ncmd)),
8157         [NPIPE    ] = SHELL_ALIGN(sizeof(struct npipe)),
8158         [NREDIR   ] = SHELL_ALIGN(sizeof(struct nredir)),
8159         [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8160         [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8161         [NAND     ] = SHELL_ALIGN(sizeof(struct nbinary)),
8162         [NOR      ] = SHELL_ALIGN(sizeof(struct nbinary)),
8163         [NSEMI    ] = SHELL_ALIGN(sizeof(struct nbinary)),
8164         [NIF      ] = SHELL_ALIGN(sizeof(struct nif)),
8165         [NWHILE   ] = SHELL_ALIGN(sizeof(struct nbinary)),
8166         [NUNTIL   ] = SHELL_ALIGN(sizeof(struct nbinary)),
8167         [NFOR     ] = SHELL_ALIGN(sizeof(struct nfor)),
8168         [NCASE    ] = SHELL_ALIGN(sizeof(struct ncase)),
8169         [NCLIST   ] = SHELL_ALIGN(sizeof(struct nclist)),
8170         [NDEFUN   ] = SHELL_ALIGN(sizeof(struct narg)),
8171         [NARG     ] = SHELL_ALIGN(sizeof(struct narg)),
8172         [NTO      ] = SHELL_ALIGN(sizeof(struct nfile)),
8173 #if ENABLE_ASH_BASH_COMPAT
8174         [NTO2     ] = SHELL_ALIGN(sizeof(struct nfile)),
8175 #endif
8176         [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8177         [NFROM    ] = SHELL_ALIGN(sizeof(struct nfile)),
8178         [NFROMTO  ] = SHELL_ALIGN(sizeof(struct nfile)),
8179         [NAPPEND  ] = SHELL_ALIGN(sizeof(struct nfile)),
8180         [NTOFD    ] = SHELL_ALIGN(sizeof(struct ndup)),
8181         [NFROMFD  ] = SHELL_ALIGN(sizeof(struct ndup)),
8182         [NHERE    ] = SHELL_ALIGN(sizeof(struct nhere)),
8183         [NXHERE   ] = SHELL_ALIGN(sizeof(struct nhere)),
8184         [NNOT     ] = SHELL_ALIGN(sizeof(struct nnot)),
8185 };
8186
8187 static int calcsize(int funcblocksize, union node *n);
8188
8189 static int
8190 sizenodelist(int funcblocksize, struct nodelist *lp)
8191 {
8192         while (lp) {
8193                 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8194                 funcblocksize = calcsize(funcblocksize, lp->n);
8195                 lp = lp->next;
8196         }
8197         return funcblocksize;
8198 }
8199
8200 static int
8201 calcsize(int funcblocksize, union node *n)
8202 {
8203         if (n == NULL)
8204                 return funcblocksize;
8205         funcblocksize += nodesize[n->type];
8206         switch (n->type) {
8207         case NCMD:
8208                 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8209                 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8210                 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8211                 break;
8212         case NPIPE:
8213                 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8214                 break;
8215         case NREDIR:
8216         case NBACKGND:
8217         case NSUBSHELL:
8218                 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8219                 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8220                 break;
8221         case NAND:
8222         case NOR:
8223         case NSEMI:
8224         case NWHILE:
8225         case NUNTIL:
8226                 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8227                 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8228                 break;
8229         case NIF:
8230                 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8231                 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8232                 funcblocksize = calcsize(funcblocksize, n->nif.test);
8233                 break;
8234         case NFOR:
8235                 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8236                 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8237                 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8238                 break;
8239         case NCASE:
8240                 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8241                 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8242                 break;
8243         case NCLIST:
8244                 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8245                 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8246                 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8247                 break;
8248         case NDEFUN:
8249         case NARG:
8250                 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8251                 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8252                 funcblocksize = calcsize(funcblocksize, n->narg.next);
8253                 break;
8254         case NTO:
8255 #if ENABLE_ASH_BASH_COMPAT
8256         case NTO2:
8257 #endif
8258         case NCLOBBER:
8259         case NFROM:
8260         case NFROMTO:
8261         case NAPPEND:
8262                 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8263                 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8264                 break;
8265         case NTOFD:
8266         case NFROMFD:
8267                 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8268                 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8269         break;
8270         case NHERE:
8271         case NXHERE:
8272                 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8273                 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8274                 break;
8275         case NNOT:
8276                 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8277                 break;
8278         };
8279         return funcblocksize;
8280 }
8281
8282 static char *
8283 nodeckstrdup(char *s)
8284 {
8285         funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8286         return strcpy(funcstring_end, s);
8287 }
8288
8289 static union node *copynode(union node *);
8290
8291 static struct nodelist *
8292 copynodelist(struct nodelist *lp)
8293 {
8294         struct nodelist *start;
8295         struct nodelist **lpp;
8296
8297         lpp = &start;
8298         while (lp) {
8299                 *lpp = funcblock;
8300                 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8301                 (*lpp)->n = copynode(lp->n);
8302                 lp = lp->next;
8303                 lpp = &(*lpp)->next;
8304         }
8305         *lpp = NULL;
8306         return start;
8307 }
8308
8309 static union node *
8310 copynode(union node *n)
8311 {
8312         union node *new;
8313
8314         if (n == NULL)
8315                 return NULL;
8316         new = funcblock;
8317         funcblock = (char *) funcblock + nodesize[n->type];
8318
8319         switch (n->type) {
8320         case NCMD:
8321                 new->ncmd.redirect = copynode(n->ncmd.redirect);
8322                 new->ncmd.args = copynode(n->ncmd.args);
8323                 new->ncmd.assign = copynode(n->ncmd.assign);
8324                 break;
8325         case NPIPE:
8326                 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8327                 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8328                 break;
8329         case NREDIR:
8330         case NBACKGND:
8331         case NSUBSHELL:
8332                 new->nredir.redirect = copynode(n->nredir.redirect);
8333                 new->nredir.n = copynode(n->nredir.n);
8334                 break;
8335         case NAND:
8336         case NOR:
8337         case NSEMI:
8338         case NWHILE:
8339         case NUNTIL:
8340                 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8341                 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8342                 break;
8343         case NIF:
8344                 new->nif.elsepart = copynode(n->nif.elsepart);
8345                 new->nif.ifpart = copynode(n->nif.ifpart);
8346                 new->nif.test = copynode(n->nif.test);
8347                 break;
8348         case NFOR:
8349                 new->nfor.var = nodeckstrdup(n->nfor.var);
8350                 new->nfor.body = copynode(n->nfor.body);
8351                 new->nfor.args = copynode(n->nfor.args);
8352                 break;
8353         case NCASE:
8354                 new->ncase.cases = copynode(n->ncase.cases);
8355                 new->ncase.expr = copynode(n->ncase.expr);
8356                 break;
8357         case NCLIST:
8358                 new->nclist.body = copynode(n->nclist.body);
8359                 new->nclist.pattern = copynode(n->nclist.pattern);
8360                 new->nclist.next = copynode(n->nclist.next);
8361                 break;
8362         case NDEFUN:
8363         case NARG:
8364                 new->narg.backquote = copynodelist(n->narg.backquote);
8365                 new->narg.text = nodeckstrdup(n->narg.text);
8366                 new->narg.next = copynode(n->narg.next);
8367                 break;
8368         case NTO:
8369 #if ENABLE_ASH_BASH_COMPAT
8370         case NTO2:
8371 #endif
8372         case NCLOBBER:
8373         case NFROM:
8374         case NFROMTO:
8375         case NAPPEND:
8376                 new->nfile.fname = copynode(n->nfile.fname);
8377                 new->nfile.fd = n->nfile.fd;
8378                 new->nfile.next = copynode(n->nfile.next);
8379                 break;
8380         case NTOFD:
8381         case NFROMFD:
8382                 new->ndup.vname = copynode(n->ndup.vname);
8383                 new->ndup.dupfd = n->ndup.dupfd;
8384                 new->ndup.fd = n->ndup.fd;
8385                 new->ndup.next = copynode(n->ndup.next);
8386                 break;
8387         case NHERE:
8388         case NXHERE:
8389                 new->nhere.doc = copynode(n->nhere.doc);
8390                 new->nhere.fd = n->nhere.fd;
8391                 new->nhere.next = copynode(n->nhere.next);
8392                 break;
8393         case NNOT:
8394                 new->nnot.com = copynode(n->nnot.com);
8395                 break;
8396         };
8397         new->type = n->type;
8398         return new;
8399 }
8400
8401 /*
8402  * Make a copy of a parse tree.
8403  */
8404 static struct funcnode *
8405 copyfunc(union node *n)
8406 {
8407         struct funcnode *f;
8408         size_t blocksize;
8409
8410         /*funcstringsize = 0;*/
8411         blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8412         f = ckzalloc(blocksize /* + funcstringsize */);
8413         funcblock = (char *) f + offsetof(struct funcnode, n);
8414         funcstring_end = (char *) f + blocksize;
8415         copynode(n);
8416         /* f->count = 0; - ckzalloc did it */
8417         return f;
8418 }
8419
8420 /*
8421  * Define a shell function.
8422  */
8423 static void
8424 defun(union node *func)
8425 {
8426         struct cmdentry entry;
8427
8428         INT_OFF;
8429         entry.cmdtype = CMDFUNCTION;
8430         entry.u.func = copyfunc(func);
8431         addcmdentry(func->narg.text, &entry);
8432         INT_ON;
8433 }
8434
8435 /* Reasons for skipping commands (see comment on breakcmd routine) */
8436 #define SKIPBREAK      (1 << 0)
8437 #define SKIPCONT       (1 << 1)
8438 #define SKIPFUNC       (1 << 2)
8439 static smallint evalskip;       /* set to SKIPxxx if we are skipping commands */
8440 static int skipcount;           /* number of levels to skip */
8441 static int funcnest;            /* depth of function calls */
8442 static int loopnest;            /* current loop nesting level */
8443
8444 /* Forward decl way out to parsing code - dotrap needs it */
8445 static int evalstring(char *s, int flags);
8446
8447 /* Called to execute a trap.
8448  * Single callsite - at the end of evaltree().
8449  * If we return non-zero, evaltree raises EXEXIT exception.
8450  *
8451  * Perhaps we should avoid entering new trap handlers
8452  * while we are executing a trap handler. [is it a TODO?]
8453  */
8454 static void
8455 dotrap(void)
8456 {
8457         uint8_t *g;
8458         int sig;
8459         uint8_t last_status;
8460
8461         if (!pending_sig)
8462                 return;
8463
8464         last_status = exitstatus;
8465         pending_sig = 0;
8466         barrier();
8467
8468         TRACE(("dotrap entered\n"));
8469         for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8470                 char *p;
8471
8472                 if (!*g)
8473                         continue;
8474
8475                 if (evalskip) {
8476                         pending_sig = sig;
8477                         break;
8478                 }
8479
8480                 p = trap[sig];
8481                 /* non-trapped SIGINT is handled separately by raise_interrupt,
8482                  * don't upset it by resetting gotsig[SIGINT-1] */
8483                 if (sig == SIGINT && !p)
8484                         continue;
8485
8486                 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8487                 *g = 0;
8488                 if (!p)
8489                         continue;
8490                 evalstring(p, 0);
8491         }
8492         exitstatus = last_status;
8493         TRACE(("dotrap returns\n"));
8494 }
8495
8496 /* forward declarations - evaluation is fairly recursive business... */
8497 static int evalloop(union node *, int);
8498 static int evalfor(union node *, int);
8499 static int evalcase(union node *, int);
8500 static int evalsubshell(union node *, int);
8501 static void expredir(union node *);
8502 static int evalpipe(union node *, int);
8503 static int evalcommand(union node *, int);
8504 static int evalbltin(const struct builtincmd *, int, char **, int);
8505 static void prehash(union node *);
8506
8507 /*
8508  * Evaluate a parse tree.  The value is left in the global variable
8509  * exitstatus.
8510  */
8511 static int
8512 evaltree(union node *n, int flags)
8513 {
8514         struct jmploc *volatile savehandler = exception_handler;
8515         struct jmploc jmploc;
8516         int checkexit = 0;
8517         int (*evalfn)(union node *, int);
8518         int status = 0;
8519         int int_level;
8520
8521         SAVE_INT(int_level);
8522
8523         if (n == NULL) {
8524                 TRACE(("evaltree(NULL) called\n"));
8525                 goto out1;
8526         }
8527         TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8528
8529         dotrap();
8530
8531         exception_handler = &jmploc;
8532         {
8533                 int err = setjmp(jmploc.loc);
8534                 if (err) {
8535                         /* if it was a signal, check for trap handlers */
8536                         if (exception_type == EXSIG) {
8537                                 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8538                                                 exception_type, err));
8539                                 goto out;
8540                         }
8541                         /* continue on the way out */
8542                         TRACE(("exception %d in evaltree, propagating err=%d\n",
8543                                         exception_type, err));
8544                         exception_handler = savehandler;
8545                         longjmp(exception_handler->loc, err);
8546                 }
8547         }
8548
8549         switch (n->type) {
8550         default:
8551 #if DEBUG
8552                 out1fmt("Node type = %d\n", n->type);
8553                 fflush_all();
8554                 break;
8555 #endif
8556         case NNOT:
8557                 status = !evaltree(n->nnot.com, EV_TESTED);
8558                 goto setstatus;
8559         case NREDIR:
8560                 expredir(n->nredir.redirect);
8561                 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8562                 if (!status) {
8563                         status = evaltree(n->nredir.n, flags & EV_TESTED);
8564                 }
8565                 if (n->nredir.redirect)
8566                         popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8567                 goto setstatus;
8568         case NCMD:
8569                 evalfn = evalcommand;
8570  checkexit:
8571                 if (eflag && !(flags & EV_TESTED))
8572                         checkexit = ~0;
8573                 goto calleval;
8574         case NFOR:
8575                 evalfn = evalfor;
8576                 goto calleval;
8577         case NWHILE:
8578         case NUNTIL:
8579                 evalfn = evalloop;
8580                 goto calleval;
8581         case NSUBSHELL:
8582         case NBACKGND:
8583                 evalfn = evalsubshell;
8584                 goto checkexit;
8585         case NPIPE:
8586                 evalfn = evalpipe;
8587                 goto checkexit;
8588         case NCASE:
8589                 evalfn = evalcase;
8590                 goto calleval;
8591         case NAND:
8592         case NOR:
8593         case NSEMI: {
8594
8595 #if NAND + 1 != NOR
8596 #error NAND + 1 != NOR
8597 #endif
8598 #if NOR + 1 != NSEMI
8599 #error NOR + 1 != NSEMI
8600 #endif
8601                 unsigned is_or = n->type - NAND;
8602                 status = evaltree(
8603                         n->nbinary.ch1,
8604                         (flags | ((is_or >> 1) - 1)) & EV_TESTED
8605                 );
8606                 if ((!status) == is_or || evalskip)
8607                         break;
8608                 n = n->nbinary.ch2;
8609  evaln:
8610                 evalfn = evaltree;
8611  calleval:
8612                 status = evalfn(n, flags);
8613                 goto setstatus;
8614         }
8615         case NIF:
8616                 status = evaltree(n->nif.test, EV_TESTED);
8617                 if (evalskip)
8618                         break;
8619                 if (!status) {
8620                         n = n->nif.ifpart;
8621                         goto evaln;
8622                 }
8623                 if (n->nif.elsepart) {
8624                         n = n->nif.elsepart;
8625                         goto evaln;
8626                 }
8627                 status = 0;
8628                 goto setstatus;
8629         case NDEFUN:
8630                 defun(n);
8631                 /* Not necessary. To test it:
8632                  * "false; f() { qwerty; }; echo $?" should print 0.
8633                  */
8634                 /* status = 0; */
8635  setstatus:
8636                 exitstatus = status;
8637                 break;
8638         }
8639
8640  out:
8641         exception_handler = savehandler;
8642
8643  out1:
8644         /* Order of checks below is important:
8645          * signal handlers trigger before exit caused by "set -e".
8646          */
8647         dotrap();
8648
8649         if (checkexit & status)
8650                 raise_exception(EXEXIT);
8651         if (flags & EV_EXIT)
8652                 raise_exception(EXEXIT);
8653
8654         RESTORE_INT(int_level);
8655         TRACE(("leaving evaltree (no interrupts)\n"));
8656
8657         return exitstatus;
8658 }
8659
8660 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8661 static
8662 #endif
8663 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8664
8665 static int
8666 skiploop(void)
8667 {
8668         int skip = evalskip;
8669
8670         switch (skip) {
8671         case 0:
8672                 break;
8673         case SKIPBREAK:
8674         case SKIPCONT:
8675                 if (--skipcount <= 0) {
8676                         evalskip = 0;
8677                         break;
8678                 }
8679                 skip = SKIPBREAK;
8680                 break;
8681         }
8682         return skip;
8683 }
8684
8685 static int
8686 evalloop(union node *n, int flags)
8687 {
8688         int skip;
8689         int status;
8690
8691         loopnest++;
8692         status = 0;
8693         flags &= EV_TESTED;
8694         do {
8695                 int i;
8696
8697                 i = evaltree(n->nbinary.ch1, EV_TESTED);
8698                 skip = skiploop();
8699                 if (skip == SKIPFUNC)
8700                         status = i;
8701                 if (skip)
8702                         continue;
8703                 if (n->type != NWHILE)
8704                         i = !i;
8705                 if (i != 0)
8706                         break;
8707                 status = evaltree(n->nbinary.ch2, flags);
8708                 skip = skiploop();
8709         } while (!(skip & ~SKIPCONT));
8710         loopnest--;
8711
8712         return status;
8713 }
8714
8715 static int
8716 evalfor(union node *n, int flags)
8717 {
8718         struct arglist arglist;
8719         union node *argp;
8720         struct strlist *sp;
8721         struct stackmark smark;
8722         int status = 0;
8723
8724         setstackmark(&smark);
8725         arglist.list = NULL;
8726         arglist.lastp = &arglist.list;
8727         for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8728                 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8729         }
8730         *arglist.lastp = NULL;
8731
8732         loopnest++;
8733         flags &= EV_TESTED;
8734         for (sp = arglist.list; sp; sp = sp->next) {
8735                 setvar0(n->nfor.var, sp->text);
8736                 status = evaltree(n->nfor.body, flags);
8737                 if (skiploop() & ~SKIPCONT)
8738                         break;
8739         }
8740         loopnest--;
8741         popstackmark(&smark);
8742
8743         return status;
8744 }
8745
8746 static int
8747 evalcase(union node *n, int flags)
8748 {
8749         union node *cp;
8750         union node *patp;
8751         struct arglist arglist;
8752         struct stackmark smark;
8753         int status = 0;
8754
8755         setstackmark(&smark);
8756         arglist.list = NULL;
8757         arglist.lastp = &arglist.list;
8758         expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8759         for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8760                 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8761                         if (casematch(patp, arglist.list->text)) {
8762                                 /* Ensure body is non-empty as otherwise
8763                                  * EV_EXIT may prevent us from setting the
8764                                  * exit status.
8765                                  */
8766                                 if (evalskip == 0 && cp->nclist.body) {
8767                                         status = evaltree(cp->nclist.body, flags);
8768                                 }
8769                                 goto out;
8770                         }
8771                 }
8772         }
8773  out:
8774         popstackmark(&smark);
8775
8776         return status;
8777 }
8778
8779 /*
8780  * Kick off a subshell to evaluate a tree.
8781  */
8782 static int
8783 evalsubshell(union node *n, int flags)
8784 {
8785         struct job *jp;
8786         int backgnd = (n->type == NBACKGND);
8787         int status;
8788
8789         expredir(n->nredir.redirect);
8790         if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8791                 goto nofork;
8792         INT_OFF;
8793         jp = makejob(/*n,*/ 1);
8794         if (forkshell(jp, n, backgnd) == 0) {
8795                 /* child */
8796                 INT_ON;
8797                 flags |= EV_EXIT;
8798                 if (backgnd)
8799                         flags &= ~EV_TESTED;
8800  nofork:
8801                 redirect(n->nredir.redirect, 0);
8802                 evaltreenr(n->nredir.n, flags);
8803                 /* never returns */
8804         }
8805         status = 0;
8806         if (!backgnd)
8807                 status = waitforjob(jp);
8808         INT_ON;
8809         return status;
8810 }
8811
8812 /*
8813  * Compute the names of the files in a redirection list.
8814  */
8815 static void fixredir(union node *, const char *, int);
8816 static void
8817 expredir(union node *n)
8818 {
8819         union node *redir;
8820
8821         for (redir = n; redir; redir = redir->nfile.next) {
8822                 struct arglist fn;
8823
8824                 fn.list = NULL;
8825                 fn.lastp = &fn.list;
8826                 switch (redir->type) {
8827                 case NFROMTO:
8828                 case NFROM:
8829                 case NTO:
8830 #if ENABLE_ASH_BASH_COMPAT
8831                 case NTO2:
8832 #endif
8833                 case NCLOBBER:
8834                 case NAPPEND:
8835                         expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8836                         TRACE(("expredir expanded to '%s'\n", fn.list->text));
8837 #if ENABLE_ASH_BASH_COMPAT
8838  store_expfname:
8839 #endif
8840 #if 0
8841 // By the design of stack allocator, the loop of this kind:
8842 //      while true; do while true; do break; done </dev/null; done
8843 // will look like a memory leak: ash plans to free expfname's
8844 // of "/dev/null" as soon as it finishes running the loop
8845 // (in this case, never).
8846 // This "fix" is wrong:
8847                         if (redir->nfile.expfname)
8848                                 stunalloc(redir->nfile.expfname);
8849 // It results in corrupted state of stacked allocations.
8850 #endif
8851                         redir->nfile.expfname = fn.list->text;
8852                         break;
8853                 case NFROMFD:
8854                 case NTOFD: /* >& */
8855                         if (redir->ndup.vname) {
8856                                 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8857                                 if (fn.list == NULL)
8858                                         ash_msg_and_raise_error("redir error");
8859 #if ENABLE_ASH_BASH_COMPAT
8860 //FIXME: we used expandarg with different args!
8861                                 if (!isdigit_str9(fn.list->text)) {
8862                                         /* >&file, not >&fd */
8863                                         if (redir->nfile.fd != 1) /* 123>&file - BAD */
8864                                                 ash_msg_and_raise_error("redir error");
8865                                         redir->type = NTO2;
8866                                         goto store_expfname;
8867                                 }
8868 #endif
8869                                 fixredir(redir, fn.list->text, 1);
8870                         }
8871                         break;
8872                 }
8873         }
8874 }
8875
8876 /*
8877  * Evaluate a pipeline.  All the processes in the pipeline are children
8878  * of the process creating the pipeline.  (This differs from some versions
8879  * of the shell, which make the last process in a pipeline the parent
8880  * of all the rest.)
8881  */
8882 static int
8883 evalpipe(union node *n, int flags)
8884 {
8885         struct job *jp;
8886         struct nodelist *lp;
8887         int pipelen;
8888         int prevfd;
8889         int pip[2];
8890         int status = 0;
8891
8892         TRACE(("evalpipe(0x%lx) called\n", (long)n));
8893         pipelen = 0;
8894         for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8895                 pipelen++;
8896         flags |= EV_EXIT;
8897         INT_OFF;
8898         jp = makejob(/*n,*/ pipelen);
8899         prevfd = -1;
8900         for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8901                 prehash(lp->n);
8902                 pip[1] = -1;
8903                 if (lp->next) {
8904                         if (pipe(pip) < 0) {
8905                                 close(prevfd);
8906                                 ash_msg_and_raise_error("pipe call failed");
8907                         }
8908                 }
8909                 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8910                         INT_ON;
8911                         if (pip[1] >= 0) {
8912                                 close(pip[0]);
8913                         }
8914                         if (prevfd > 0) {
8915                                 dup2(prevfd, 0);
8916                                 close(prevfd);
8917                         }
8918                         if (pip[1] > 1) {
8919                                 dup2(pip[1], 1);
8920                                 close(pip[1]);
8921                         }
8922                         evaltreenr(lp->n, flags);
8923                         /* never returns */
8924                 }
8925                 if (prevfd >= 0)
8926                         close(prevfd);
8927                 prevfd = pip[0];
8928                 /* Don't want to trigger debugging */
8929                 if (pip[1] != -1)
8930                         close(pip[1]);
8931         }
8932         if (n->npipe.pipe_backgnd == 0) {
8933                 status = waitforjob(jp);
8934                 TRACE(("evalpipe:  job done exit status %d\n", status));
8935         }
8936         INT_ON;
8937
8938         return status;
8939 }
8940
8941 /*
8942  * Controls whether the shell is interactive or not.
8943  */
8944 static void
8945 setinteractive(int on)
8946 {
8947         static smallint is_interactive;
8948
8949         if (++on == is_interactive)
8950                 return;
8951         is_interactive = on;
8952         setsignal(SIGINT);
8953         setsignal(SIGQUIT);
8954         setsignal(SIGTERM);
8955 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8956         if (is_interactive > 1) {
8957                 /* Looks like they want an interactive shell */
8958                 static smallint did_banner;
8959
8960                 if (!did_banner) {
8961                         /* note: ash and hush share this string */
8962                         out1fmt("\n\n%s %s\n"
8963                                 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8964                                 "\n",
8965                                 bb_banner,
8966                                 "built-in shell (ash)"
8967                         );
8968                         did_banner = 1;
8969                 }
8970         }
8971 #endif
8972 }
8973
8974 static void
8975 optschanged(void)
8976 {
8977 #if DEBUG
8978         opentrace();
8979 #endif
8980         setinteractive(iflag);
8981         setjobctl(mflag);
8982 #if ENABLE_FEATURE_EDITING_VI
8983         if (viflag)
8984                 line_input_state->flags |= VI_MODE;
8985         else
8986                 line_input_state->flags &= ~VI_MODE;
8987 #else
8988         viflag = 0; /* forcibly keep the option off */
8989 #endif
8990 }
8991
8992 static struct localvar *localvars;
8993
8994 /*
8995  * Called after a function returns.
8996  * Interrupts must be off.
8997  */
8998 static void
8999 poplocalvars(void)
9000 {
9001         struct localvar *lvp;
9002         struct var *vp;
9003
9004         while ((lvp = localvars) != NULL) {
9005                 localvars = lvp->next;
9006                 vp = lvp->vp;
9007                 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9008                 if (vp == NULL) {       /* $- saved */
9009                         memcpy(optlist, lvp->text, sizeof(optlist));
9010                         free((char*)lvp->text);
9011                         optschanged();
9012                 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9013                         unsetvar(vp->var_text);
9014                 } else {
9015                         if (vp->var_func)
9016                                 vp->var_func(var_end(lvp->text));
9017                         if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9018                                 free((char*)vp->var_text);
9019                         vp->flags = lvp->flags;
9020                         vp->var_text = lvp->text;
9021                 }
9022                 free(lvp);
9023         }
9024 }
9025
9026 static int
9027 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9028 {
9029         volatile struct shparam saveparam;
9030         struct localvar *volatile savelocalvars;
9031         struct jmploc *volatile savehandler;
9032         struct jmploc jmploc;
9033         int e;
9034
9035         saveparam = shellparam;
9036         savelocalvars = localvars;
9037         savehandler = exception_handler;
9038         e = setjmp(jmploc.loc);
9039         if (e) {
9040                 goto funcdone;
9041         }
9042         INT_OFF;
9043         exception_handler = &jmploc;
9044         localvars = NULL;
9045         shellparam.malloced = 0;
9046         func->count++;
9047         funcnest++;
9048         INT_ON;
9049         shellparam.nparam = argc - 1;
9050         shellparam.p = argv + 1;
9051 #if ENABLE_ASH_GETOPTS
9052         shellparam.optind = 1;
9053         shellparam.optoff = -1;
9054 #endif
9055         evaltree(func->n.narg.next, flags & EV_TESTED);
9056  funcdone:
9057         INT_OFF;
9058         funcnest--;
9059         freefunc(func);
9060         poplocalvars();
9061         localvars = savelocalvars;
9062         freeparam(&shellparam);
9063         shellparam = saveparam;
9064         exception_handler = savehandler;
9065         INT_ON;
9066         evalskip &= ~SKIPFUNC;
9067         return e;
9068 }
9069
9070 /*
9071  * Make a variable a local variable.  When a variable is made local, it's
9072  * value and flags are saved in a localvar structure.  The saved values
9073  * will be restored when the shell function returns.  We handle the name
9074  * "-" as a special case: it makes changes to "set +-options" local
9075  * (options will be restored on return from the function).
9076  */
9077 static void
9078 mklocal(char *name)
9079 {
9080         struct localvar *lvp;
9081         struct var **vpp;
9082         struct var *vp;
9083         char *eq = strchr(name, '=');
9084
9085         INT_OFF;
9086         /* Cater for duplicate "local". Examples:
9087          * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9088          * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9089          */
9090         lvp = localvars;
9091         while (lvp) {
9092                 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9093                         if (eq)
9094                                 setvareq(name, 0);
9095                         /* else:
9096                          * it's a duplicate "local VAR" declaration, do nothing
9097                          */
9098                         return;
9099                 }
9100                 lvp = lvp->next;
9101         }
9102
9103         lvp = ckzalloc(sizeof(*lvp));
9104         if (LONE_DASH(name)) {
9105                 char *p;
9106                 p = ckmalloc(sizeof(optlist));
9107                 lvp->text = memcpy(p, optlist, sizeof(optlist));
9108                 vp = NULL;
9109         } else {
9110                 vpp = hashvar(name);
9111                 vp = *findvar(vpp, name);
9112                 if (vp == NULL) {
9113                         /* variable did not exist yet */
9114                         if (eq)
9115                                 setvareq(name, VSTRFIXED);
9116                         else
9117                                 setvar(name, NULL, VSTRFIXED);
9118                         vp = *vpp;      /* the new variable */
9119                         lvp->flags = VUNSET;
9120                 } else {
9121                         lvp->text = vp->var_text;
9122                         lvp->flags = vp->flags;
9123                         /* make sure neither "struct var" nor string gets freed
9124                          * during (un)setting:
9125                          */
9126                         vp->flags |= VSTRFIXED|VTEXTFIXED;
9127                         if (eq)
9128                                 setvareq(name, 0);
9129                         else
9130                                 /* "local VAR" unsets VAR: */
9131                                 setvar0(name, NULL);
9132                 }
9133         }
9134         lvp->vp = vp;
9135         lvp->next = localvars;
9136         localvars = lvp;
9137         INT_ON;
9138 }
9139
9140 /*
9141  * The "local" command.
9142  */
9143 static int FAST_FUNC
9144 localcmd(int argc UNUSED_PARAM, char **argv)
9145 {
9146         char *name;
9147
9148         if (!funcnest)
9149                 ash_msg_and_raise_error("not in a function");
9150
9151         argv = argptr;
9152         while ((name = *argv++) != NULL) {
9153                 mklocal(name);
9154         }
9155         return 0;
9156 }
9157
9158 static int FAST_FUNC
9159 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9160 {
9161         return 1;
9162 }
9163
9164 static int FAST_FUNC
9165 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9166 {
9167         return 0;
9168 }
9169
9170 static int FAST_FUNC
9171 execcmd(int argc UNUSED_PARAM, char **argv)
9172 {
9173         if (argv[1]) {
9174                 iflag = 0;              /* exit on error */
9175                 mflag = 0;
9176                 optschanged();
9177                 /* We should set up signals for "exec CMD"
9178                  * the same way as for "CMD" without "exec".
9179                  * But optschanged->setinteractive->setsignal
9180                  * still thought we are a root shell. Therefore, for example,
9181                  * SIGQUIT is still set to IGN. Fix it:
9182                  */
9183                 shlvl++;
9184                 setsignal(SIGQUIT);
9185                 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9186                 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9187                 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9188
9189                 shellexec(argv + 1, pathval(), 0);
9190                 /* NOTREACHED */
9191         }
9192         return 0;
9193 }
9194
9195 /*
9196  * The return command.
9197  */
9198 static int FAST_FUNC
9199 returncmd(int argc UNUSED_PARAM, char **argv)
9200 {
9201         /*
9202          * If called outside a function, do what ksh does;
9203          * skip the rest of the file.
9204          */
9205         evalskip = SKIPFUNC;
9206         return argv[1] ? number(argv[1]) : exitstatus;
9207 }
9208
9209 /* Forward declarations for builtintab[] */
9210 static int breakcmd(int, char **) FAST_FUNC;
9211 static int dotcmd(int, char **) FAST_FUNC;
9212 static int evalcmd(int, char **, int) FAST_FUNC;
9213 static int exitcmd(int, char **) FAST_FUNC;
9214 static int exportcmd(int, char **) FAST_FUNC;
9215 #if ENABLE_ASH_GETOPTS
9216 static int getoptscmd(int, char **) FAST_FUNC;
9217 #endif
9218 #if ENABLE_ASH_HELP
9219 static int helpcmd(int, char **) FAST_FUNC;
9220 #endif
9221 #if MAX_HISTORY
9222 static int historycmd(int, char **) FAST_FUNC;
9223 #endif
9224 #if ENABLE_SH_MATH_SUPPORT
9225 static int letcmd(int, char **) FAST_FUNC;
9226 #endif
9227 static int readcmd(int, char **) FAST_FUNC;
9228 static int setcmd(int, char **) FAST_FUNC;
9229 static int shiftcmd(int, char **) FAST_FUNC;
9230 static int timescmd(int, char **) FAST_FUNC;
9231 static int trapcmd(int, char **) FAST_FUNC;
9232 static int umaskcmd(int, char **) FAST_FUNC;
9233 static int unsetcmd(int, char **) FAST_FUNC;
9234 static int ulimitcmd(int, char **) FAST_FUNC;
9235
9236 #define BUILTIN_NOSPEC          "0"
9237 #define BUILTIN_SPECIAL         "1"
9238 #define BUILTIN_REGULAR         "2"
9239 #define BUILTIN_SPEC_REG        "3"
9240 #define BUILTIN_ASSIGN          "4"
9241 #define BUILTIN_SPEC_ASSG       "5"
9242 #define BUILTIN_REG_ASSG        "6"
9243 #define BUILTIN_SPEC_REG_ASSG   "7"
9244
9245 /* Stubs for calling non-FAST_FUNC's */
9246 #if ENABLE_ASH_BUILTIN_ECHO
9247 static int FAST_FUNC echocmd(int argc, char **argv)   { return echo_main(argc, argv); }
9248 #endif
9249 #if ENABLE_ASH_BUILTIN_PRINTF
9250 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9251 #endif
9252 #if ENABLE_ASH_BUILTIN_TEST
9253 static int FAST_FUNC testcmd(int argc, char **argv)   { return test_main(argc, argv); }
9254 #endif
9255
9256 /* Keep these in proper order since it is searched via bsearch() */
9257 static const struct builtincmd builtintab[] = {
9258         { BUILTIN_SPEC_REG      "."       , dotcmd     },
9259         { BUILTIN_SPEC_REG      ":"       , truecmd    },
9260 #if ENABLE_ASH_BUILTIN_TEST
9261         { BUILTIN_REGULAR       "["       , testcmd    },
9262 #if ENABLE_ASH_BASH_COMPAT
9263         { BUILTIN_REGULAR       "[["      , testcmd    },
9264 #endif
9265 #endif
9266 #if ENABLE_ASH_ALIAS
9267         { BUILTIN_REG_ASSG      "alias"   , aliascmd   },
9268 #endif
9269 #if JOBS
9270         { BUILTIN_REGULAR       "bg"      , fg_bgcmd   },
9271 #endif
9272         { BUILTIN_SPEC_REG      "break"   , breakcmd   },
9273         { BUILTIN_REGULAR       "cd"      , cdcmd      },
9274         { BUILTIN_NOSPEC        "chdir"   , cdcmd      },
9275 #if ENABLE_ASH_CMDCMD
9276         { BUILTIN_REGULAR       "command" , commandcmd },
9277 #endif
9278         { BUILTIN_SPEC_REG      "continue", breakcmd   },
9279 #if ENABLE_ASH_BUILTIN_ECHO
9280         { BUILTIN_REGULAR       "echo"    , echocmd    },
9281 #endif
9282         { BUILTIN_SPEC_REG      "eval"    , NULL       }, /*evalcmd() has a differing prototype*/
9283         { BUILTIN_SPEC_REG      "exec"    , execcmd    },
9284         { BUILTIN_SPEC_REG      "exit"    , exitcmd    },
9285         { BUILTIN_SPEC_REG_ASSG "export"  , exportcmd  },
9286         { BUILTIN_REGULAR       "false"   , falsecmd   },
9287 #if JOBS
9288         { BUILTIN_REGULAR       "fg"      , fg_bgcmd   },
9289 #endif
9290 #if ENABLE_ASH_GETOPTS
9291         { BUILTIN_REGULAR       "getopts" , getoptscmd },
9292 #endif
9293         { BUILTIN_NOSPEC        "hash"    , hashcmd    },
9294 #if ENABLE_ASH_HELP
9295         { BUILTIN_NOSPEC        "help"    , helpcmd    },
9296 #endif
9297 #if MAX_HISTORY
9298         { BUILTIN_NOSPEC        "history" , historycmd },
9299 #endif
9300 #if JOBS
9301         { BUILTIN_REGULAR       "jobs"    , jobscmd    },
9302         { BUILTIN_REGULAR       "kill"    , killcmd    },
9303 #endif
9304 #if ENABLE_SH_MATH_SUPPORT
9305         { BUILTIN_NOSPEC        "let"     , letcmd     },
9306 #endif
9307         { BUILTIN_ASSIGN        "local"   , localcmd   },
9308 #if ENABLE_ASH_BUILTIN_PRINTF
9309         { BUILTIN_REGULAR       "printf"  , printfcmd  },
9310 #endif
9311         { BUILTIN_NOSPEC        "pwd"     , pwdcmd     },
9312         { BUILTIN_REGULAR       "read"    , readcmd    },
9313         { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd  },
9314         { BUILTIN_SPEC_REG      "return"  , returncmd  },
9315         { BUILTIN_SPEC_REG      "set"     , setcmd     },
9316         { BUILTIN_SPEC_REG      "shift"   , shiftcmd   },
9317 #if ENABLE_ASH_BASH_COMPAT
9318         { BUILTIN_SPEC_REG      "source"  , dotcmd     },
9319 #endif
9320 #if ENABLE_ASH_BUILTIN_TEST
9321         { BUILTIN_REGULAR       "test"    , testcmd    },
9322 #endif
9323         { BUILTIN_SPEC_REG      "times"   , timescmd   },
9324         { BUILTIN_SPEC_REG      "trap"    , trapcmd    },
9325         { BUILTIN_REGULAR       "true"    , truecmd    },
9326         { BUILTIN_NOSPEC        "type"    , typecmd    },
9327         { BUILTIN_NOSPEC        "ulimit"  , ulimitcmd  },
9328         { BUILTIN_REGULAR       "umask"   , umaskcmd   },
9329 #if ENABLE_ASH_ALIAS
9330         { BUILTIN_REGULAR       "unalias" , unaliascmd },
9331 #endif
9332         { BUILTIN_SPEC_REG      "unset"   , unsetcmd   },
9333         { BUILTIN_REGULAR       "wait"    , waitcmd    },
9334 };
9335
9336 /* Should match the above table! */
9337 #define COMMANDCMD (builtintab + \
9338         /* . : */       2 + \
9339         /* [ */         1 * ENABLE_ASH_BUILTIN_TEST + \
9340         /* [[ */        1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9341         /* alias */     1 * ENABLE_ASH_ALIAS + \
9342         /* bg */        1 * ENABLE_ASH_JOB_CONTROL + \
9343         /* break cd cddir  */   3)
9344 #define EVALCMD (COMMANDCMD + \
9345         /* command */   1 * ENABLE_ASH_CMDCMD + \
9346         /* continue */  1 + \
9347         /* echo */      1 * ENABLE_ASH_BUILTIN_ECHO + \
9348         0)
9349 #define EXECCMD (EVALCMD + \
9350         /* eval */      1)
9351
9352 /*
9353  * Search the table of builtin commands.
9354  */
9355 static int
9356 pstrcmp1(const void *a, const void *b)
9357 {
9358         return strcmp((char*)a, *(char**)b + 1);
9359 }
9360 static struct builtincmd *
9361 find_builtin(const char *name)
9362 {
9363         struct builtincmd *bp;
9364
9365         bp = bsearch(
9366                 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9367                 pstrcmp1
9368         );
9369         return bp;
9370 }
9371
9372 /*
9373  * Execute a simple command.
9374  */
9375 static int
9376 isassignment(const char *p)
9377 {
9378         const char *q = endofname(p);
9379         if (p == q)
9380                 return 0;
9381         return *q == '=';
9382 }
9383 static int FAST_FUNC
9384 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9385 {
9386         /* Preserve exitstatus of a previous possible redirection
9387          * as POSIX mandates */
9388         return back_exitstatus;
9389 }
9390 static int
9391 evalcommand(union node *cmd, int flags)
9392 {
9393         static const struct builtincmd null_bltin = {
9394                 "\0\0", bltincmd /* why three NULs? */
9395         };
9396         struct stackmark smark;
9397         union node *argp;
9398         struct arglist arglist;
9399         struct arglist varlist;
9400         char **argv;
9401         int argc;
9402         const struct strlist *sp;
9403         struct cmdentry cmdentry;
9404         struct job *jp;
9405         char *lastarg;
9406         const char *path;
9407         int spclbltin;
9408         int status;
9409         char **nargv;
9410         struct builtincmd *bcmd;
9411         smallint cmd_is_exec;
9412         smallint pseudovarflag = 0;
9413
9414         /* First expand the arguments. */
9415         TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9416         setstackmark(&smark);
9417         back_exitstatus = 0;
9418
9419         cmdentry.cmdtype = CMDBUILTIN;
9420         cmdentry.u.cmd = &null_bltin;
9421         varlist.lastp = &varlist.list;
9422         *varlist.lastp = NULL;
9423         arglist.lastp = &arglist.list;
9424         *arglist.lastp = NULL;
9425
9426         argc = 0;
9427         if (cmd->ncmd.args) {
9428                 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9429                 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9430         }
9431
9432         for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9433                 struct strlist **spp;
9434
9435                 spp = arglist.lastp;
9436                 if (pseudovarflag && isassignment(argp->narg.text))
9437                         expandarg(argp, &arglist, EXP_VARTILDE);
9438                 else
9439                         expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9440
9441                 for (sp = *spp; sp; sp = sp->next)
9442                         argc++;
9443         }
9444
9445         argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9446         for (sp = arglist.list; sp; sp = sp->next) {
9447                 TRACE(("evalcommand arg: %s\n", sp->text));
9448                 *nargv++ = sp->text;
9449         }
9450         *nargv = NULL;
9451
9452         lastarg = NULL;
9453         if (iflag && funcnest == 0 && argc > 0)
9454                 lastarg = nargv[-1];
9455
9456         preverrout_fd = 2;
9457         expredir(cmd->ncmd.redirect);
9458         status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9459
9460         path = vpath.var_text;
9461         for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9462                 struct strlist **spp;
9463                 char *p;
9464
9465                 spp = varlist.lastp;
9466                 expandarg(argp, &varlist, EXP_VARTILDE);
9467
9468                 /*
9469                  * Modify the command lookup path, if a PATH= assignment
9470                  * is present
9471                  */
9472                 p = (*spp)->text;
9473                 if (varcmp(p, path) == 0)
9474                         path = p;
9475         }
9476
9477         /* Print the command if xflag is set. */
9478         if (xflag) {
9479                 int n;
9480                 const char *p = " %s" + 1;
9481
9482                 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9483                 sp = varlist.list;
9484                 for (n = 0; n < 2; n++) {
9485                         while (sp) {
9486                                 fdprintf(preverrout_fd, p, sp->text);
9487                                 sp = sp->next;
9488                                 p = " %s";
9489                         }
9490                         sp = arglist.list;
9491                 }
9492                 safe_write(preverrout_fd, "\n", 1);
9493         }
9494
9495         cmd_is_exec = 0;
9496         spclbltin = -1;
9497
9498         /* Now locate the command. */
9499         if (argc) {
9500                 int cmd_flag = DO_ERR;
9501 #if ENABLE_ASH_CMDCMD
9502                 const char *oldpath = path + 5;
9503 #endif
9504                 path += 5;
9505                 for (;;) {
9506                         find_command(argv[0], &cmdentry, cmd_flag, path);
9507                         if (cmdentry.cmdtype == CMDUNKNOWN) {
9508                                 flush_stdout_stderr();
9509                                 status = 127;
9510                                 goto bail;
9511                         }
9512
9513                         /* implement bltin and command here */
9514                         if (cmdentry.cmdtype != CMDBUILTIN)
9515                                 break;
9516                         if (spclbltin < 0)
9517                                 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9518                         if (cmdentry.u.cmd == EXECCMD)
9519                                 cmd_is_exec = 1;
9520 #if ENABLE_ASH_CMDCMD
9521                         if (cmdentry.u.cmd == COMMANDCMD) {
9522                                 path = oldpath;
9523                                 nargv = parse_command_args(argv, &path);
9524                                 if (!nargv)
9525                                         break;
9526                                 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9527                                  * nargv => "PROG". path is updated if -p.
9528                                  */
9529                                 argc -= nargv - argv;
9530                                 argv = nargv;
9531                                 cmd_flag |= DO_NOFUNC;
9532                         } else
9533 #endif
9534                                 break;
9535                 }
9536         }
9537
9538         if (status) {
9539                 /* We have a redirection error. */
9540                 if (spclbltin > 0)
9541                         raise_exception(EXERROR);
9542  bail:
9543                 exitstatus = status;
9544                 goto out;
9545         }
9546
9547         /* Execute the command. */
9548         switch (cmdentry.cmdtype) {
9549         default: {
9550
9551 #if ENABLE_FEATURE_SH_NOFORK
9552 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9553  *     around run_nofork_applet() call.
9554  * (2) Should this check also be done in forkshell()?
9555  *     (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9556  */
9557                 /* find_command() encodes applet_no as (-2 - applet_no) */
9558                 int applet_no = (- cmdentry.u.index - 2);
9559                 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9560                         listsetvar(varlist.list, VEXPORT|VSTACK);
9561                         /* run <applet>_main() */
9562                         status = run_nofork_applet(applet_no, argv);
9563                         break;
9564                 }
9565 #endif
9566                 /* Can we avoid forking off? For example, very last command
9567                  * in a script or a subshell does not need forking,
9568                  * we can just exec it.
9569                  */
9570                 if (!(flags & EV_EXIT) || may_have_traps) {
9571                         /* No, forking off a child is necessary */
9572                         INT_OFF;
9573                         jp = makejob(/*cmd,*/ 1);
9574                         if (forkshell(jp, cmd, FORK_FG) != 0) {
9575                                 /* parent */
9576                                 status = waitforjob(jp);
9577                                 INT_ON;
9578                                 TRACE(("forked child exited with %d\n", status));
9579                                 break;
9580                         }
9581                         /* child */
9582                         FORCE_INT_ON;
9583                         /* fall through to exec'ing external program */
9584                 }
9585                 listsetvar(varlist.list, VEXPORT|VSTACK);
9586                 shellexec(argv, path, cmdentry.u.index);
9587                 /* NOTREACHED */
9588         } /* default */
9589         case CMDBUILTIN:
9590                 cmdenviron = varlist.list;
9591                 if (cmdenviron) {
9592                         struct strlist *list = cmdenviron;
9593                         int i = VNOSET;
9594                         if (spclbltin > 0 || argc == 0) {
9595                                 i = 0;
9596                                 if (cmd_is_exec && argc > 1)
9597                                         i = VEXPORT;
9598                         }
9599                         listsetvar(list, i);
9600                 }
9601                 /* Tight loop with builtins only:
9602                  * "while kill -0 $child; do true; done"
9603                  * will never exit even if $child died, unless we do this
9604                  * to reap the zombie and make kill detect that it's gone: */
9605                 dowait(DOWAIT_NONBLOCK, NULL);
9606
9607                 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9608                         int exit_status;
9609                         int i = exception_type;
9610                         if (i == EXEXIT)
9611                                 goto raise;
9612                         exit_status = 2;
9613                         if (i == EXINT)
9614                                 exit_status = 128 + SIGINT;
9615                         if (i == EXSIG)
9616                                 exit_status = 128 + pending_sig;
9617                         exitstatus = exit_status;
9618                         if (i == EXINT || spclbltin > 0) {
9619  raise:
9620                                 longjmp(exception_handler->loc, 1);
9621                         }
9622                         FORCE_INT_ON;
9623                 }
9624                 goto readstatus;
9625
9626         case CMDFUNCTION:
9627                 listsetvar(varlist.list, 0);
9628                 /* See above for the rationale */
9629                 dowait(DOWAIT_NONBLOCK, NULL);
9630                 if (evalfun(cmdentry.u.func, argc, argv, flags))
9631                         goto raise;
9632  readstatus:
9633                 status = exitstatus;
9634                 break;
9635         } /* switch */
9636
9637  out:
9638         if (cmd->ncmd.redirect)
9639                 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9640         if (lastarg) {
9641                 /* dsl: I think this is intended to be used to support
9642                  * '_' in 'vi' command mode during line editing...
9643                  * However I implemented that within libedit itself.
9644                  */
9645                 setvar0("_", lastarg);
9646         }
9647         popstackmark(&smark);
9648
9649         return status;
9650 }
9651
9652 static int
9653 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9654 {
9655         char *volatile savecmdname;
9656         struct jmploc *volatile savehandler;
9657         struct jmploc jmploc;
9658         int status;
9659         int i;
9660
9661         savecmdname = commandname;
9662         savehandler = exception_handler;
9663         i = setjmp(jmploc.loc);
9664         if (i)
9665                 goto cmddone;
9666         exception_handler = &jmploc;
9667         commandname = argv[0];
9668         argptr = argv + 1;
9669         optptr = NULL;                  /* initialize nextopt */
9670         if (cmd == EVALCMD)
9671                 status = evalcmd(argc, argv, flags);
9672         else
9673                 status = (*cmd->builtin)(argc, argv);
9674         flush_stdout_stderr();
9675         status |= ferror(stdout);
9676         exitstatus = status;
9677  cmddone:
9678         clearerr(stdout);
9679         commandname = savecmdname;
9680         exception_handler = savehandler;
9681
9682         return i;
9683 }
9684
9685 static int
9686 goodname(const char *p)
9687 {
9688         return endofname(p)[0] == '\0';
9689 }
9690
9691
9692 /*
9693  * Search for a command.  This is called before we fork so that the
9694  * location of the command will be available in the parent as well as
9695  * the child.  The check for "goodname" is an overly conservative
9696  * check that the name will not be subject to expansion.
9697  */
9698 static void
9699 prehash(union node *n)
9700 {
9701         struct cmdentry entry;
9702
9703         if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9704                 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9705 }
9706
9707
9708 /* ============ Builtin commands
9709  *
9710  * Builtin commands whose functions are closely tied to evaluation
9711  * are implemented here.
9712  */
9713
9714 /*
9715  * Handle break and continue commands.  Break, continue, and return are
9716  * all handled by setting the evalskip flag.  The evaluation routines
9717  * above all check this flag, and if it is set they start skipping
9718  * commands rather than executing them.  The variable skipcount is
9719  * the number of loops to break/continue, or the number of function
9720  * levels to return.  (The latter is always 1.)  It should probably
9721  * be an error to break out of more loops than exist, but it isn't
9722  * in the standard shell so we don't make it one here.
9723  */
9724 static int FAST_FUNC
9725 breakcmd(int argc UNUSED_PARAM, char **argv)
9726 {
9727         int n = argv[1] ? number(argv[1]) : 1;
9728
9729         if (n <= 0)
9730                 ash_msg_and_raise_error(msg_illnum, argv[1]);
9731         if (n > loopnest)
9732                 n = loopnest;
9733         if (n > 0) {
9734                 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9735                 skipcount = n;
9736         }
9737         return 0;
9738 }
9739
9740
9741 /* ============ input.c
9742  *
9743  * This implements the input routines used by the parser.
9744  */
9745
9746 enum {
9747         INPUT_PUSH_FILE = 1,
9748         INPUT_NOFILE_OK = 2,
9749 };
9750
9751 static smallint checkkwd;
9752 /* values of checkkwd variable */
9753 #define CHKALIAS        0x1
9754 #define CHKKWD          0x2
9755 #define CHKNL           0x4
9756
9757 /*
9758  * Push a string back onto the input at this current parsefile level.
9759  * We handle aliases this way.
9760  */
9761 #if !ENABLE_ASH_ALIAS
9762 #define pushstring(s, ap) pushstring(s)
9763 #endif
9764 static void
9765 pushstring(char *s, struct alias *ap)
9766 {
9767         struct strpush *sp;
9768         int len;
9769
9770         len = strlen(s);
9771         INT_OFF;
9772         if (g_parsefile->strpush) {
9773                 sp = ckzalloc(sizeof(*sp));
9774                 sp->prev = g_parsefile->strpush;
9775         } else {
9776                 sp = &(g_parsefile->basestrpush);
9777         }
9778         g_parsefile->strpush = sp;
9779         sp->prev_string = g_parsefile->next_to_pgetc;
9780         sp->prev_left_in_line = g_parsefile->left_in_line;
9781         sp->unget = g_parsefile->unget;
9782         memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9783 #if ENABLE_ASH_ALIAS
9784         sp->ap = ap;
9785         if (ap) {
9786                 ap->flag |= ALIASINUSE;
9787                 sp->string = s;
9788         }
9789 #endif
9790         g_parsefile->next_to_pgetc = s;
9791         g_parsefile->left_in_line = len;
9792         g_parsefile->unget = 0;
9793         INT_ON;
9794 }
9795
9796 static void
9797 popstring(void)
9798 {
9799         struct strpush *sp = g_parsefile->strpush;
9800
9801         INT_OFF;
9802 #if ENABLE_ASH_ALIAS
9803         if (sp->ap) {
9804                 if (g_parsefile->next_to_pgetc[-1] == ' '
9805                  || g_parsefile->next_to_pgetc[-1] == '\t'
9806                 ) {
9807                         checkkwd |= CHKALIAS;
9808                 }
9809                 if (sp->string != sp->ap->val) {
9810                         free(sp->string);
9811                 }
9812                 sp->ap->flag &= ~ALIASINUSE;
9813                 if (sp->ap->flag & ALIASDEAD) {
9814                         unalias(sp->ap->name);
9815                 }
9816         }
9817 #endif
9818         g_parsefile->next_to_pgetc = sp->prev_string;
9819         g_parsefile->left_in_line = sp->prev_left_in_line;
9820         g_parsefile->unget = sp->unget;
9821         memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9822         g_parsefile->strpush = sp->prev;
9823         if (sp != &(g_parsefile->basestrpush))
9824                 free(sp);
9825         INT_ON;
9826 }
9827
9828 static int
9829 preadfd(void)
9830 {
9831         int nr;
9832         char *buf = g_parsefile->buf;
9833
9834         g_parsefile->next_to_pgetc = buf;
9835 #if ENABLE_FEATURE_EDITING
9836  retry:
9837         if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9838                 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9839         else {
9840                 int timeout = -1;
9841 # if ENABLE_ASH_IDLE_TIMEOUT
9842                 if (iflag) {
9843                         const char *tmout_var = lookupvar("TMOUT");
9844                         if (tmout_var) {
9845                                 timeout = atoi(tmout_var) * 1000;
9846                                 if (timeout <= 0)
9847                                         timeout = -1;
9848                         }
9849                 }
9850 # endif
9851 # if ENABLE_FEATURE_TAB_COMPLETION
9852                 line_input_state->path_lookup = pathval();
9853 # endif
9854                 reinit_unicode_for_ash();
9855                 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9856                 if (nr == 0) {
9857                         /* Ctrl+C pressed */
9858                         if (trap[SIGINT]) {
9859                                 buf[0] = '\n';
9860                                 buf[1] = '\0';
9861                                 raise(SIGINT);
9862                                 return 1;
9863                         }
9864                         goto retry;
9865                 }
9866                 if (nr < 0) {
9867                         if (errno == 0) {
9868                                 /* Ctrl+D pressed */
9869                                 nr = 0;
9870                         }
9871 # if ENABLE_ASH_IDLE_TIMEOUT
9872                         else if (errno == EAGAIN && timeout > 0) {
9873                                 puts("\007timed out waiting for input: auto-logout");
9874                                 exitshell();
9875                         }
9876 # endif
9877                 }
9878         }
9879 #else
9880         nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9881 #endif
9882
9883 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9884         if (nr < 0) {
9885                 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9886                         int flags = fcntl(0, F_GETFL);
9887                         if (flags >= 0 && (flags & O_NONBLOCK)) {
9888                                 flags &= ~O_NONBLOCK;
9889                                 if (fcntl(0, F_SETFL, flags) >= 0) {
9890                                         out2str("sh: turning off NDELAY mode\n");
9891                                         goto retry;
9892                                 }
9893                         }
9894                 }
9895         }
9896 #endif
9897         return nr;
9898 }
9899
9900 /*
9901  * Refill the input buffer and return the next input character:
9902  *
9903  * 1) If a string was pushed back on the input, pop it;
9904  * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9905  *    or we are reading from a string so we can't refill the buffer,
9906  *    return EOF.
9907  * 3) If there is more stuff in this buffer, use it else call read to fill it.
9908  * 4) Process input up to the next newline, deleting nul characters.
9909  */
9910 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9911 #define pgetc_debug(...) ((void)0)
9912 static int pgetc(void);
9913 static int
9914 preadbuffer(void)
9915 {
9916         char *q;
9917         int more;
9918
9919         if (g_parsefile->strpush) {
9920 #if ENABLE_ASH_ALIAS
9921                 if (g_parsefile->left_in_line == -1
9922                  && g_parsefile->strpush->ap
9923                  && g_parsefile->next_to_pgetc[-1] != ' '
9924                  && g_parsefile->next_to_pgetc[-1] != '\t'
9925                 ) {
9926                         pgetc_debug("preadbuffer PEOA");
9927                         return PEOA;
9928                 }
9929 #endif
9930                 popstring();
9931                 return pgetc();
9932         }
9933         /* on both branches above g_parsefile->left_in_line < 0.
9934          * "pgetc" needs refilling.
9935          */
9936
9937         /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9938          * pungetc() may increment it a few times.
9939          * Assuming it won't increment it to less than -90.
9940          */
9941         if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9942                 pgetc_debug("preadbuffer PEOF1");
9943                 /* even in failure keep left_in_line and next_to_pgetc
9944                  * in lock step, for correct multi-layer pungetc.
9945                  * left_in_line was decremented before preadbuffer(),
9946                  * must inc next_to_pgetc: */
9947                 g_parsefile->next_to_pgetc++;
9948                 return PEOF;
9949         }
9950
9951         more = g_parsefile->left_in_buffer;
9952         if (more <= 0) {
9953                 flush_stdout_stderr();
9954  again:
9955                 more = preadfd();
9956                 if (more <= 0) {
9957                         /* don't try reading again */
9958                         g_parsefile->left_in_line = -99;
9959                         pgetc_debug("preadbuffer PEOF2");
9960                         g_parsefile->next_to_pgetc++;
9961                         return PEOF;
9962                 }
9963         }
9964
9965         /* Find out where's the end of line.
9966          * Set g_parsefile->left_in_line
9967          * and g_parsefile->left_in_buffer acordingly.
9968          * NUL chars are deleted.
9969          */
9970         q = g_parsefile->next_to_pgetc;
9971         for (;;) {
9972                 char c;
9973
9974                 more--;
9975
9976                 c = *q;
9977                 if (c == '\0') {
9978                         memmove(q, q + 1, more);
9979                 } else {
9980                         q++;
9981                         if (c == '\n') {
9982                                 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9983                                 break;
9984                         }
9985                 }
9986
9987                 if (more <= 0) {
9988                         g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9989                         if (g_parsefile->left_in_line < 0)
9990                                 goto again;
9991                         break;
9992                 }
9993         }
9994         g_parsefile->left_in_buffer = more;
9995
9996         if (vflag) {
9997                 char save = *q;
9998                 *q = '\0';
9999                 out2str(g_parsefile->next_to_pgetc);
10000                 *q = save;
10001         }
10002
10003         pgetc_debug("preadbuffer at %d:%p'%s'",
10004                         g_parsefile->left_in_line,
10005                         g_parsefile->next_to_pgetc,
10006                         g_parsefile->next_to_pgetc);
10007         return (unsigned char)*g_parsefile->next_to_pgetc++;
10008 }
10009
10010 static void
10011 nlprompt(void)
10012 {
10013         g_parsefile->linno++;
10014         setprompt_if(doprompt, 2);
10015 }
10016 static void
10017 nlnoprompt(void)
10018 {
10019         g_parsefile->linno++;
10020         needprompt = doprompt;
10021 }
10022
10023 static int
10024 pgetc(void)
10025 {
10026         int c;
10027
10028         pgetc_debug("pgetc at %d:%p'%s'",
10029                         g_parsefile->left_in_line,
10030                         g_parsefile->next_to_pgetc,
10031                         g_parsefile->next_to_pgetc);
10032         if (g_parsefile->unget)
10033                 return g_parsefile->lastc[--g_parsefile->unget];
10034
10035         if (--g_parsefile->left_in_line >= 0)
10036                 c = (signed char)*g_parsefile->next_to_pgetc++;
10037         else
10038                 c = preadbuffer();
10039
10040         g_parsefile->lastc[1] = g_parsefile->lastc[0];
10041         g_parsefile->lastc[0] = c;
10042
10043         return c;
10044 }
10045
10046 #if ENABLE_ASH_ALIAS
10047 static int
10048 pgetc_without_PEOA(void)
10049 {
10050         int c;
10051         do {
10052                 pgetc_debug("pgetc at %d:%p'%s'",
10053                                 g_parsefile->left_in_line,
10054                                 g_parsefile->next_to_pgetc,
10055                                 g_parsefile->next_to_pgetc);
10056                 c = pgetc();
10057         } while (c == PEOA);
10058         return c;
10059 }
10060 #else
10061 # define pgetc_without_PEOA() pgetc()
10062 #endif
10063
10064 /*
10065  * Read a line from the script.
10066  */
10067 static char *
10068 pfgets(char *line, int len)
10069 {
10070         char *p = line;
10071         int nleft = len;
10072         int c;
10073
10074         while (--nleft > 0) {
10075                 c = pgetc_without_PEOA();
10076                 if (c == PEOF) {
10077                         if (p == line)
10078                                 return NULL;
10079                         break;
10080                 }
10081                 *p++ = c;
10082                 if (c == '\n')
10083                         break;
10084         }
10085         *p = '\0';
10086         return line;
10087 }
10088
10089 /*
10090  * Undo a call to pgetc.  Only two characters may be pushed back.
10091  * PEOF may be pushed back.
10092  */
10093 static void
10094 pungetc(void)
10095 {
10096         g_parsefile->unget++;
10097 }
10098
10099 /* This one eats backslash+newline */
10100 static int
10101 pgetc_eatbnl(void)
10102 {
10103         int c;
10104
10105         while ((c = pgetc()) == '\\') {
10106                 if (pgetc() != '\n') {
10107                         pungetc();
10108                         break;
10109                 }
10110
10111                 nlprompt();
10112         }
10113
10114         return c;
10115 }
10116
10117 /*
10118  * To handle the "." command, a stack of input files is used.  Pushfile
10119  * adds a new entry to the stack and popfile restores the previous level.
10120  */
10121 static void
10122 pushfile(void)
10123 {
10124         struct parsefile *pf;
10125
10126         pf = ckzalloc(sizeof(*pf));
10127         pf->prev = g_parsefile;
10128         pf->pf_fd = -1;
10129         /*pf->strpush = NULL; - ckzalloc did it */
10130         /*pf->basestrpush.prev = NULL;*/
10131         /*pf->unget = 0;*/
10132         g_parsefile = pf;
10133 }
10134
10135 static void
10136 popfile(void)
10137 {
10138         struct parsefile *pf = g_parsefile;
10139
10140         INT_OFF;
10141         if (pf->pf_fd >= 0)
10142                 close(pf->pf_fd);
10143         free(pf->buf);
10144         while (pf->strpush)
10145                 popstring();
10146         g_parsefile = pf->prev;
10147         free(pf);
10148         INT_ON;
10149 }
10150
10151 /*
10152  * Return to top level.
10153  */
10154 static void
10155 popallfiles(void)
10156 {
10157         while (g_parsefile != &basepf)
10158                 popfile();
10159 }
10160
10161 /*
10162  * Close the file(s) that the shell is reading commands from.  Called
10163  * after a fork is done.
10164  */
10165 static void
10166 closescript(void)
10167 {
10168         popallfiles();
10169         if (g_parsefile->pf_fd > 0) {
10170                 close(g_parsefile->pf_fd);
10171                 g_parsefile->pf_fd = 0;
10172         }
10173 }
10174
10175 /*
10176  * Like setinputfile, but takes an open file descriptor.  Call this with
10177  * interrupts off.
10178  */
10179 static void
10180 setinputfd(int fd, int push)
10181 {
10182         close_on_exec_on(fd);
10183         if (push) {
10184                 pushfile();
10185                 g_parsefile->buf = NULL;
10186         }
10187         g_parsefile->pf_fd = fd;
10188         if (g_parsefile->buf == NULL)
10189                 g_parsefile->buf = ckmalloc(IBUFSIZ);
10190         g_parsefile->left_in_buffer = 0;
10191         g_parsefile->left_in_line = 0;
10192         g_parsefile->linno = 1;
10193 }
10194
10195 /*
10196  * Set the input to take input from a file.  If push is set, push the
10197  * old input onto the stack first.
10198  */
10199 static int
10200 setinputfile(const char *fname, int flags)
10201 {
10202         int fd;
10203         int fd2;
10204
10205         INT_OFF;
10206         fd = open(fname, O_RDONLY);
10207         if (fd < 0) {
10208                 if (flags & INPUT_NOFILE_OK)
10209                         goto out;
10210                 exitstatus = 127;
10211                 ash_msg_and_raise_error("can't open '%s'", fname);
10212         }
10213         if (fd < 10) {
10214                 fd2 = copyfd(fd, 10);
10215                 close(fd);
10216                 fd = fd2;
10217         }
10218         setinputfd(fd, flags & INPUT_PUSH_FILE);
10219  out:
10220         INT_ON;
10221         return fd;
10222 }
10223
10224 /*
10225  * Like setinputfile, but takes input from a string.
10226  */
10227 static void
10228 setinputstring(char *string)
10229 {
10230         INT_OFF;
10231         pushfile();
10232         g_parsefile->next_to_pgetc = string;
10233         g_parsefile->left_in_line = strlen(string);
10234         g_parsefile->buf = NULL;
10235         g_parsefile->linno = 1;
10236         INT_ON;
10237 }
10238
10239
10240 /* ============ mail.c
10241  *
10242  * Routines to check for mail.
10243  */
10244
10245 #if ENABLE_ASH_MAIL
10246
10247 /* Hash of mtimes of mailboxes */
10248 static unsigned mailtime_hash;
10249 /* Set if MAIL or MAILPATH is changed. */
10250 static smallint mail_var_path_changed;
10251
10252 /*
10253  * Print appropriate message(s) if mail has arrived.
10254  * If mail_var_path_changed is set,
10255  * then the value of MAIL has mail_var_path_changed,
10256  * so we just update the values.
10257  */
10258 static void
10259 chkmail(void)
10260 {
10261         const char *mpath;
10262         char *p;
10263         char *q;
10264         unsigned new_hash;
10265         struct stackmark smark;
10266         struct stat statb;
10267
10268         setstackmark(&smark);
10269         mpath = mpathset() ? mpathval() : mailval();
10270         new_hash = 0;
10271         for (;;) {
10272                 p = path_advance(&mpath, nullstr);
10273                 if (p == NULL)
10274                         break;
10275                 if (*p == '\0')
10276                         continue;
10277                 for (q = p; *q; q++)
10278                         continue;
10279 #if DEBUG
10280                 if (q[-1] != '/')
10281                         abort();
10282 #endif
10283                 q[-1] = '\0';                   /* delete trailing '/' */
10284                 if (stat(p, &statb) < 0) {
10285                         continue;
10286                 }
10287                 /* Very simplistic "hash": just a sum of all mtimes */
10288                 new_hash += (unsigned)statb.st_mtime;
10289         }
10290         if (!mail_var_path_changed && mailtime_hash != new_hash) {
10291                 if (mailtime_hash != 0)
10292                         out2str("you have mail\n");
10293                 mailtime_hash = new_hash;
10294         }
10295         mail_var_path_changed = 0;
10296         popstackmark(&smark);
10297 }
10298
10299 static void FAST_FUNC
10300 changemail(const char *val UNUSED_PARAM)
10301 {
10302         mail_var_path_changed = 1;
10303 }
10304
10305 #endif /* ASH_MAIL */
10306
10307
10308 /* ============ ??? */
10309
10310 /*
10311  * Set the shell parameters.
10312  */
10313 static void
10314 setparam(char **argv)
10315 {
10316         char **newparam;
10317         char **ap;
10318         int nparam;
10319
10320         for (nparam = 0; argv[nparam]; nparam++)
10321                 continue;
10322         ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10323         while (*argv) {
10324                 *ap++ = ckstrdup(*argv++);
10325         }
10326         *ap = NULL;
10327         freeparam(&shellparam);
10328         shellparam.malloced = 1;
10329         shellparam.nparam = nparam;
10330         shellparam.p = newparam;
10331 #if ENABLE_ASH_GETOPTS
10332         shellparam.optind = 1;
10333         shellparam.optoff = -1;
10334 #endif
10335 }
10336
10337 /*
10338  * Process shell options.  The global variable argptr contains a pointer
10339  * to the argument list; we advance it past the options.
10340  *
10341  * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10342  * For a non-interactive shell, an error condition encountered
10343  * by a special built-in ... shall cause the shell to write a diagnostic message
10344  * to standard error and exit as shown in the following table:
10345  * Error                                           Special Built-In
10346  * ...
10347  * Utility syntax error (option or operand error)  Shall exit
10348  * ...
10349  * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10350  * we see that bash does not do that (set "finishes" with error code 1 instead,
10351  * and shell continues), and people rely on this behavior!
10352  * Testcase:
10353  * set -o barfoo 2>/dev/null
10354  * echo $?
10355  *
10356  * Oh well. Let's mimic that.
10357  */
10358 static int
10359 plus_minus_o(char *name, int val)
10360 {
10361         int i;
10362
10363         if (name) {
10364                 for (i = 0; i < NOPTS; i++) {
10365                         if (strcmp(name, optnames(i)) == 0) {
10366                                 optlist[i] = val;
10367                                 return 0;
10368                         }
10369                 }
10370                 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10371                 return 1;
10372         }
10373         for (i = 0; i < NOPTS; i++) {
10374                 if (val) {
10375                         out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10376                 } else {
10377                         out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10378                 }
10379         }
10380         return 0;
10381 }
10382 static void
10383 setoption(int flag, int val)
10384 {
10385         int i;
10386
10387         for (i = 0; i < NOPTS; i++) {
10388                 if (optletters(i) == flag) {
10389                         optlist[i] = val;
10390                         return;
10391                 }
10392         }
10393         ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10394         /* NOTREACHED */
10395 }
10396 static int
10397 options(int cmdline)
10398 {
10399         char *p;
10400         int val;
10401         int c;
10402
10403         if (cmdline)
10404                 minusc = NULL;
10405         while ((p = *argptr) != NULL) {
10406                 c = *p++;
10407                 if (c != '-' && c != '+')
10408                         break;
10409                 argptr++;
10410                 val = 0; /* val = 0 if c == '+' */
10411                 if (c == '-') {
10412                         val = 1;
10413                         if (p[0] == '\0' || LONE_DASH(p)) {
10414                                 if (!cmdline) {
10415                                         /* "-" means turn off -x and -v */
10416                                         if (p[0] == '\0')
10417                                                 xflag = vflag = 0;
10418                                         /* "--" means reset params */
10419                                         else if (*argptr == NULL)
10420                                                 setparam(argptr);
10421                                 }
10422                                 break;    /* "-" or "--" terminates options */
10423                         }
10424                 }
10425                 /* first char was + or - */
10426                 while ((c = *p++) != '\0') {
10427                         /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10428                         if (c == 'c' && cmdline) {
10429                                 minusc = p;     /* command is after shell args */
10430                         } else if (c == 'o') {
10431                                 if (plus_minus_o(*argptr, val)) {
10432                                         /* it already printed err message */
10433                                         return 1; /* error */
10434                                 }
10435                                 if (*argptr)
10436                                         argptr++;
10437                         } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10438                                 isloginsh = 1;
10439                         /* bash does not accept +-login, we also won't */
10440                         } else if (cmdline && val && (c == '-')) { /* long options */
10441                                 if (strcmp(p, "login") == 0)
10442                                         isloginsh = 1;
10443                                 break;
10444                         } else {
10445                                 setoption(c, val);
10446                         }
10447                 }
10448         }
10449         return 0;
10450 }
10451
10452 /*
10453  * The shift builtin command.
10454  */
10455 static int FAST_FUNC
10456 shiftcmd(int argc UNUSED_PARAM, char **argv)
10457 {
10458         int n;
10459         char **ap1, **ap2;
10460
10461         n = 1;
10462         if (argv[1])
10463                 n = number(argv[1]);
10464         if (n > shellparam.nparam)
10465                 n = 0; /* bash compat, was = shellparam.nparam; */
10466         INT_OFF;
10467         shellparam.nparam -= n;
10468         for (ap1 = shellparam.p; --n >= 0; ap1++) {
10469                 if (shellparam.malloced)
10470                         free(*ap1);
10471         }
10472         ap2 = shellparam.p;
10473         while ((*ap2++ = *ap1++) != NULL)
10474                 continue;
10475 #if ENABLE_ASH_GETOPTS
10476         shellparam.optind = 1;
10477         shellparam.optoff = -1;
10478 #endif
10479         INT_ON;
10480         return 0;
10481 }
10482
10483 /*
10484  * POSIX requires that 'set' (but not export or readonly) output the
10485  * variables in lexicographic order - by the locale's collating order (sigh).
10486  * Maybe we could keep them in an ordered balanced binary tree
10487  * instead of hashed lists.
10488  * For now just roll 'em through qsort for printing...
10489  */
10490 static int
10491 showvars(const char *sep_prefix, int on, int off)
10492 {
10493         const char *sep;
10494         char **ep, **epend;
10495
10496         ep = listvars(on, off, &epend);
10497         qsort(ep, epend - ep, sizeof(char *), vpcmp);
10498
10499         sep = *sep_prefix ? " " : sep_prefix;
10500
10501         for (; ep < epend; ep++) {
10502                 const char *p;
10503                 const char *q;
10504
10505                 p = strchrnul(*ep, '=');
10506                 q = nullstr;
10507                 if (*p)
10508                         q = single_quote(++p);
10509                 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10510         }
10511         return 0;
10512 }
10513
10514 /*
10515  * The set command builtin.
10516  */
10517 static int FAST_FUNC
10518 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10519 {
10520         int retval;
10521
10522         if (!argv[1])
10523                 return showvars(nullstr, 0, VUNSET);
10524
10525         INT_OFF;
10526         retval = options(/*cmdline:*/ 0);
10527         if (retval == 0) { /* if no parse error... */
10528                 optschanged();
10529                 if (*argptr != NULL) {
10530                         setparam(argptr);
10531                 }
10532         }
10533         INT_ON;
10534         return retval;
10535 }
10536
10537 #if ENABLE_ASH_RANDOM_SUPPORT
10538 static void FAST_FUNC
10539 change_random(const char *value)
10540 {
10541         uint32_t t;
10542
10543         if (value == NULL) {
10544                 /* "get", generate */
10545                 t = next_random(&random_gen);
10546                 /* set without recursion */
10547                 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10548                 vrandom.flags &= ~VNOFUNC;
10549         } else {
10550                 /* set/reset */
10551                 t = strtoul(value, NULL, 10);
10552                 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10553         }
10554 }
10555 #endif
10556
10557 #if ENABLE_ASH_GETOPTS
10558 static int
10559 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10560 {
10561         char *p, *q;
10562         char c = '?';
10563         int done = 0;
10564         int err = 0;
10565         char sbuf[2];
10566         char **optnext;
10567
10568         sbuf[1] = '\0';
10569
10570         if (*param_optind < 1)
10571                 return 1;
10572         optnext = optfirst + *param_optind - 1;
10573
10574         if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10575                 p = NULL;
10576         else
10577                 p = optnext[-1] + *optoff;
10578         if (p == NULL || *p == '\0') {
10579                 /* Current word is done, advance */
10580                 p = *optnext;
10581                 if (p == NULL || *p != '-' || *++p == '\0') {
10582  atend:
10583                         p = NULL;
10584                         done = 1;
10585                         goto out;
10586                 }
10587                 optnext++;
10588                 if (LONE_DASH(p))        /* check for "--" */
10589                         goto atend;
10590         }
10591
10592         c = *p++;
10593         for (q = optstr; *q != c;) {
10594                 if (*q == '\0') {
10595                         if (optstr[0] == ':') {
10596                                 sbuf[0] = c;
10597                                 /*sbuf[1] = '\0'; - already is */
10598                                 err |= setvarsafe("OPTARG", sbuf, 0);
10599                         } else {
10600                                 fprintf(stderr, "Illegal option -%c\n", c);
10601                                 unsetvar("OPTARG");
10602                         }
10603                         c = '?';
10604                         goto out;
10605                 }
10606                 if (*++q == ':')
10607                         q++;
10608         }
10609
10610         if (*++q == ':') {
10611                 if (*p == '\0' && (p = *optnext) == NULL) {
10612                         if (optstr[0] == ':') {
10613                                 sbuf[0] = c;
10614                                 /*sbuf[1] = '\0'; - already is */
10615                                 err |= setvarsafe("OPTARG", sbuf, 0);
10616                                 c = ':';
10617                         } else {
10618                                 fprintf(stderr, "No arg for -%c option\n", c);
10619                                 unsetvar("OPTARG");
10620                                 c = '?';
10621                         }
10622                         goto out;
10623                 }
10624
10625                 if (p == *optnext)
10626                         optnext++;
10627                 err |= setvarsafe("OPTARG", p, 0);
10628                 p = NULL;
10629         } else
10630                 err |= setvarsafe("OPTARG", nullstr, 0);
10631  out:
10632         *optoff = p ? p - *(optnext - 1) : -1;
10633         *param_optind = optnext - optfirst + 1;
10634         err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10635         sbuf[0] = c;
10636         /*sbuf[1] = '\0'; - already is */
10637         err |= setvarsafe(optvar, sbuf, 0);
10638         if (err) {
10639                 *param_optind = 1;
10640                 *optoff = -1;
10641                 flush_stdout_stderr();
10642                 raise_exception(EXERROR);
10643         }
10644         return done;
10645 }
10646
10647 /*
10648  * The getopts builtin.  Shellparam.optnext points to the next argument
10649  * to be processed.  Shellparam.optptr points to the next character to
10650  * be processed in the current argument.  If shellparam.optnext is NULL,
10651  * then it's the first time getopts has been called.
10652  */
10653 static int FAST_FUNC
10654 getoptscmd(int argc, char **argv)
10655 {
10656         char **optbase;
10657
10658         if (argc < 3)
10659                 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10660         if (argc == 3) {
10661                 optbase = shellparam.p;
10662                 if (shellparam.optind > shellparam.nparam + 1) {
10663                         shellparam.optind = 1;
10664                         shellparam.optoff = -1;
10665                 }
10666         } else {
10667                 optbase = &argv[3];
10668                 if (shellparam.optind > argc - 2) {
10669                         shellparam.optind = 1;
10670                         shellparam.optoff = -1;
10671                 }
10672         }
10673
10674         return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10675                         &shellparam.optoff);
10676 }
10677 #endif /* ASH_GETOPTS */
10678
10679
10680 /* ============ Shell parser */
10681
10682 struct heredoc {
10683         struct heredoc *next;   /* next here document in list */
10684         union node *here;       /* redirection node */
10685         char *eofmark;          /* string indicating end of input */
10686         smallint striptabs;     /* if set, strip leading tabs */
10687 };
10688
10689 static smallint tokpushback;           /* last token pushed back */
10690 static smallint quoteflag;             /* set if (part of) last token was quoted */
10691 static token_id_t lasttoken;           /* last token read (integer id Txxx) */
10692 static struct heredoc *heredoclist;    /* list of here documents to read */
10693 static char *wordtext;                 /* text of last word returned by readtoken */
10694 static struct nodelist *backquotelist;
10695 static union node *redirnode;
10696 static struct heredoc *heredoc;
10697
10698 static const char *
10699 tokname(char *buf, int tok)
10700 {
10701         if (tok < TSEMI)
10702                 return tokname_array[tok];
10703         sprintf(buf, "\"%s\"", tokname_array[tok]);
10704         return buf;
10705 }
10706
10707 /* raise_error_unexpected_syntax:
10708  * Called when an unexpected token is read during the parse.  The argument
10709  * is the token that is expected, or -1 if more than one type of token can
10710  * occur at this point.
10711  */
10712 static void raise_error_unexpected_syntax(int) NORETURN;
10713 static void
10714 raise_error_unexpected_syntax(int token)
10715 {
10716         char msg[64];
10717         char buf[16];
10718         int l;
10719
10720         l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10721         if (token >= 0)
10722                 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10723         raise_error_syntax(msg);
10724         /* NOTREACHED */
10725 }
10726
10727 #define EOFMARKLEN 79
10728
10729 /* parsing is heavily cross-recursive, need these forward decls */
10730 static union node *andor(void);
10731 static union node *pipeline(void);
10732 static union node *parse_command(void);
10733 static void parseheredoc(void);
10734 static int peektoken(void);
10735 static int readtoken(void);
10736
10737 static union node *
10738 list(int nlflag)
10739 {
10740         union node *n1, *n2, *n3;
10741         int tok;
10742
10743         n1 = NULL;
10744         for (;;) {
10745                 switch (peektoken()) {
10746                 case TNL:
10747                         if (!(nlflag & 1))
10748                                 break;
10749                         parseheredoc();
10750                         return n1;
10751
10752                 case TEOF:
10753                         if (!n1 && (nlflag & 1))
10754                                 n1 = NODE_EOF;
10755                         parseheredoc();
10756                         return n1;
10757                 }
10758
10759                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10760                 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10761                         return n1;
10762                 nlflag |= 2;
10763
10764                 n2 = andor();
10765                 tok = readtoken();
10766                 if (tok == TBACKGND) {
10767                         if (n2->type == NPIPE) {
10768                                 n2->npipe.pipe_backgnd = 1;
10769                         } else {
10770                                 if (n2->type != NREDIR) {
10771                                         n3 = stzalloc(sizeof(struct nredir));
10772                                         n3->nredir.n = n2;
10773                                         /*n3->nredir.redirect = NULL; - stzalloc did it */
10774                                         n2 = n3;
10775                                 }
10776                                 n2->type = NBACKGND;
10777                         }
10778                 }
10779                 if (n1 == NULL) {
10780                         n1 = n2;
10781                 } else {
10782                         n3 = stzalloc(sizeof(struct nbinary));
10783                         n3->type = NSEMI;
10784                         n3->nbinary.ch1 = n1;
10785                         n3->nbinary.ch2 = n2;
10786                         n1 = n3;
10787                 }
10788                 switch (tok) {
10789                 case TNL:
10790                 case TEOF:
10791                         tokpushback = 1;
10792                         /* fall through */
10793                 case TBACKGND:
10794                 case TSEMI:
10795                         break;
10796                 default:
10797                         if ((nlflag & 1))
10798                                 raise_error_unexpected_syntax(-1);
10799                         tokpushback = 1;
10800                         return n1;
10801                 }
10802         }
10803 }
10804
10805 static union node *
10806 andor(void)
10807 {
10808         union node *n1, *n2, *n3;
10809         int t;
10810
10811         n1 = pipeline();
10812         for (;;) {
10813                 t = readtoken();
10814                 if (t == TAND) {
10815                         t = NAND;
10816                 } else if (t == TOR) {
10817                         t = NOR;
10818                 } else {
10819                         tokpushback = 1;
10820                         return n1;
10821                 }
10822                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10823                 n2 = pipeline();
10824                 n3 = stzalloc(sizeof(struct nbinary));
10825                 n3->type = t;
10826                 n3->nbinary.ch1 = n1;
10827                 n3->nbinary.ch2 = n2;
10828                 n1 = n3;
10829         }
10830 }
10831
10832 static union node *
10833 pipeline(void)
10834 {
10835         union node *n1, *n2, *pipenode;
10836         struct nodelist *lp, *prev;
10837         int negate;
10838
10839         negate = 0;
10840         TRACE(("pipeline: entered\n"));
10841         if (readtoken() == TNOT) {
10842                 negate = !negate;
10843                 checkkwd = CHKKWD | CHKALIAS;
10844         } else
10845                 tokpushback = 1;
10846         n1 = parse_command();
10847         if (readtoken() == TPIPE) {
10848                 pipenode = stzalloc(sizeof(struct npipe));
10849                 pipenode->type = NPIPE;
10850                 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10851                 lp = stzalloc(sizeof(struct nodelist));
10852                 pipenode->npipe.cmdlist = lp;
10853                 lp->n = n1;
10854                 do {
10855                         prev = lp;
10856                         lp = stzalloc(sizeof(struct nodelist));
10857                         checkkwd = CHKNL | CHKKWD | CHKALIAS;
10858                         lp->n = parse_command();
10859                         prev->next = lp;
10860                 } while (readtoken() == TPIPE);
10861                 lp->next = NULL;
10862                 n1 = pipenode;
10863         }
10864         tokpushback = 1;
10865         if (negate) {
10866                 n2 = stzalloc(sizeof(struct nnot));
10867                 n2->type = NNOT;
10868                 n2->nnot.com = n1;
10869                 return n2;
10870         }
10871         return n1;
10872 }
10873
10874 static union node *
10875 makename(void)
10876 {
10877         union node *n;
10878
10879         n = stzalloc(sizeof(struct narg));
10880         n->type = NARG;
10881         /*n->narg.next = NULL; - stzalloc did it */
10882         n->narg.text = wordtext;
10883         n->narg.backquote = backquotelist;
10884         return n;
10885 }
10886
10887 static void
10888 fixredir(union node *n, const char *text, int err)
10889 {
10890         int fd;
10891
10892         TRACE(("Fix redir %s %d\n", text, err));
10893         if (!err)
10894                 n->ndup.vname = NULL;
10895
10896         fd = bb_strtou(text, NULL, 10);
10897         if (!errno && fd >= 0)
10898                 n->ndup.dupfd = fd;
10899         else if (LONE_DASH(text))
10900                 n->ndup.dupfd = -1;
10901         else {
10902                 if (err)
10903                         raise_error_syntax("bad fd number");
10904                 n->ndup.vname = makename();
10905         }
10906 }
10907
10908 /*
10909  * Returns true if the text contains nothing to expand (no dollar signs
10910  * or backquotes).
10911  */
10912 static int
10913 noexpand(const char *text)
10914 {
10915         unsigned char c;
10916
10917         while ((c = *text++) != '\0') {
10918                 if (c == CTLQUOTEMARK)
10919                         continue;
10920                 if (c == CTLESC)
10921                         text++;
10922                 else if (SIT(c, BASESYNTAX) == CCTL)
10923                         return 0;
10924         }
10925         return 1;
10926 }
10927
10928 static void
10929 parsefname(void)
10930 {
10931         union node *n = redirnode;
10932
10933         if (readtoken() != TWORD)
10934                 raise_error_unexpected_syntax(-1);
10935         if (n->type == NHERE) {
10936                 struct heredoc *here = heredoc;
10937                 struct heredoc *p;
10938                 int i;
10939
10940                 if (quoteflag == 0)
10941                         n->type = NXHERE;
10942                 TRACE(("Here document %d\n", n->type));
10943                 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10944                         raise_error_syntax("illegal eof marker for << redirection");
10945                 rmescapes(wordtext, 0);
10946                 here->eofmark = wordtext;
10947                 here->next = NULL;
10948                 if (heredoclist == NULL)
10949                         heredoclist = here;
10950                 else {
10951                         for (p = heredoclist; p->next; p = p->next)
10952                                 continue;
10953                         p->next = here;
10954                 }
10955         } else if (n->type == NTOFD || n->type == NFROMFD) {
10956                 fixredir(n, wordtext, 0);
10957         } else {
10958                 n->nfile.fname = makename();
10959         }
10960 }
10961
10962 static union node *
10963 simplecmd(void)
10964 {
10965         union node *args, **app;
10966         union node *n = NULL;
10967         union node *vars, **vpp;
10968         union node **rpp, *redir;
10969         int savecheckkwd;
10970 #if ENABLE_ASH_BASH_COMPAT
10971         smallint double_brackets_flag = 0;
10972         smallint function_flag = 0;
10973 #endif
10974
10975         args = NULL;
10976         app = &args;
10977         vars = NULL;
10978         vpp = &vars;
10979         redir = NULL;
10980         rpp = &redir;
10981
10982         savecheckkwd = CHKALIAS;
10983         for (;;) {
10984                 int t;
10985                 checkkwd = savecheckkwd;
10986                 t = readtoken();
10987                 switch (t) {
10988 #if ENABLE_ASH_BASH_COMPAT
10989                 case TFUNCTION:
10990                         if (peektoken() != TWORD)
10991                                 raise_error_unexpected_syntax(TWORD);
10992                         function_flag = 1;
10993                         break;
10994                 case TAND: /* "&&" */
10995                 case TOR: /* "||" */
10996                         if (!double_brackets_flag) {
10997                                 tokpushback = 1;
10998                                 goto out;
10999                         }
11000                         wordtext = (char *) (t == TAND ? "-a" : "-o");
11001 #endif
11002                 case TWORD:
11003                         n = stzalloc(sizeof(struct narg));
11004                         n->type = NARG;
11005                         /*n->narg.next = NULL; - stzalloc did it */
11006                         n->narg.text = wordtext;
11007 #if ENABLE_ASH_BASH_COMPAT
11008                         if (strcmp("[[", wordtext) == 0)
11009                                 double_brackets_flag = 1;
11010                         else if (strcmp("]]", wordtext) == 0)
11011                                 double_brackets_flag = 0;
11012 #endif
11013                         n->narg.backquote = backquotelist;
11014                         if (savecheckkwd && isassignment(wordtext)) {
11015                                 *vpp = n;
11016                                 vpp = &n->narg.next;
11017                         } else {
11018                                 *app = n;
11019                                 app = &n->narg.next;
11020                                 savecheckkwd = 0;
11021                         }
11022 #if ENABLE_ASH_BASH_COMPAT
11023                         if (function_flag) {
11024                                 checkkwd = CHKNL | CHKKWD;
11025                                 switch (peektoken()) {
11026                                 case TBEGIN:
11027                                 case TIF:
11028                                 case TCASE:
11029                                 case TUNTIL:
11030                                 case TWHILE:
11031                                 case TFOR:
11032                                         goto do_func;
11033                                 case TLP:
11034                                         function_flag = 0;
11035                                         break;
11036                                 case TWORD:
11037                                         if (strcmp("[[", wordtext) == 0)
11038                                                 goto do_func;
11039                                         /* fall through */
11040                                 default:
11041                                         raise_error_unexpected_syntax(-1);
11042                                 }
11043                         }
11044 #endif
11045                         break;
11046                 case TREDIR:
11047                         *rpp = n = redirnode;
11048                         rpp = &n->nfile.next;
11049                         parsefname();   /* read name of redirection file */
11050                         break;
11051                 case TLP:
11052  IF_ASH_BASH_COMPAT(do_func:)
11053                         if (args && app == &args->narg.next
11054                          && !vars && !redir
11055                         ) {
11056                                 struct builtincmd *bcmd;
11057                                 const char *name;
11058
11059                                 /* We have a function */
11060                                 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11061                                         raise_error_unexpected_syntax(TRP);
11062                                 name = n->narg.text;
11063                                 if (!goodname(name)
11064                                  || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11065                                 ) {
11066                                         raise_error_syntax("bad function name");
11067                                 }
11068                                 n->type = NDEFUN;
11069                                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11070                                 n->narg.next = parse_command();
11071                                 return n;
11072                         }
11073                         IF_ASH_BASH_COMPAT(function_flag = 0;)
11074                         /* fall through */
11075                 default:
11076                         tokpushback = 1;
11077                         goto out;
11078                 }
11079         }
11080  out:
11081         *app = NULL;
11082         *vpp = NULL;
11083         *rpp = NULL;
11084         n = stzalloc(sizeof(struct ncmd));
11085         n->type = NCMD;
11086         n->ncmd.args = args;
11087         n->ncmd.assign = vars;
11088         n->ncmd.redirect = redir;
11089         return n;
11090 }
11091
11092 static union node *
11093 parse_command(void)
11094 {
11095         union node *n1, *n2;
11096         union node *ap, **app;
11097         union node *cp, **cpp;
11098         union node *redir, **rpp;
11099         union node **rpp2;
11100         int t;
11101
11102         redir = NULL;
11103         rpp2 = &redir;
11104
11105         switch (readtoken()) {
11106         default:
11107                 raise_error_unexpected_syntax(-1);
11108                 /* NOTREACHED */
11109         case TIF:
11110                 n1 = stzalloc(sizeof(struct nif));
11111                 n1->type = NIF;
11112                 n1->nif.test = list(0);
11113                 if (readtoken() != TTHEN)
11114                         raise_error_unexpected_syntax(TTHEN);
11115                 n1->nif.ifpart = list(0);
11116                 n2 = n1;
11117                 while (readtoken() == TELIF) {
11118                         n2->nif.elsepart = stzalloc(sizeof(struct nif));
11119                         n2 = n2->nif.elsepart;
11120                         n2->type = NIF;
11121                         n2->nif.test = list(0);
11122                         if (readtoken() != TTHEN)
11123                                 raise_error_unexpected_syntax(TTHEN);
11124                         n2->nif.ifpart = list(0);
11125                 }
11126                 if (lasttoken == TELSE)
11127                         n2->nif.elsepart = list(0);
11128                 else {
11129                         n2->nif.elsepart = NULL;
11130                         tokpushback = 1;
11131                 }
11132                 t = TFI;
11133                 break;
11134         case TWHILE:
11135         case TUNTIL: {
11136                 int got;
11137                 n1 = stzalloc(sizeof(struct nbinary));
11138                 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11139                 n1->nbinary.ch1 = list(0);
11140                 got = readtoken();
11141                 if (got != TDO) {
11142                         TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11143                                         got == TWORD ? wordtext : ""));
11144                         raise_error_unexpected_syntax(TDO);
11145                 }
11146                 n1->nbinary.ch2 = list(0);
11147                 t = TDONE;
11148                 break;
11149         }
11150         case TFOR:
11151                 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11152                         raise_error_syntax("bad for loop variable");
11153                 n1 = stzalloc(sizeof(struct nfor));
11154                 n1->type = NFOR;
11155                 n1->nfor.var = wordtext;
11156                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11157                 if (readtoken() == TIN) {
11158                         app = &ap;
11159                         while (readtoken() == TWORD) {
11160                                 n2 = stzalloc(sizeof(struct narg));
11161                                 n2->type = NARG;
11162                                 /*n2->narg.next = NULL; - stzalloc did it */
11163                                 n2->narg.text = wordtext;
11164                                 n2->narg.backquote = backquotelist;
11165                                 *app = n2;
11166                                 app = &n2->narg.next;
11167                         }
11168                         *app = NULL;
11169                         n1->nfor.args = ap;
11170                         if (lasttoken != TNL && lasttoken != TSEMI)
11171                                 raise_error_unexpected_syntax(-1);
11172                 } else {
11173                         n2 = stzalloc(sizeof(struct narg));
11174                         n2->type = NARG;
11175                         /*n2->narg.next = NULL; - stzalloc did it */
11176                         n2->narg.text = (char *)dolatstr;
11177                         /*n2->narg.backquote = NULL;*/
11178                         n1->nfor.args = n2;
11179                         /*
11180                          * Newline or semicolon here is optional (but note
11181                          * that the original Bourne shell only allowed NL).
11182                          */
11183                         if (lasttoken != TSEMI)
11184                                 tokpushback = 1;
11185                 }
11186                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11187                 if (readtoken() != TDO)
11188                         raise_error_unexpected_syntax(TDO);
11189                 n1->nfor.body = list(0);
11190                 t = TDONE;
11191                 break;
11192         case TCASE:
11193                 n1 = stzalloc(sizeof(struct ncase));
11194                 n1->type = NCASE;
11195                 if (readtoken() != TWORD)
11196                         raise_error_unexpected_syntax(TWORD);
11197                 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11198                 n2->type = NARG;
11199                 /*n2->narg.next = NULL; - stzalloc did it */
11200                 n2->narg.text = wordtext;
11201                 n2->narg.backquote = backquotelist;
11202                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11203                 if (readtoken() != TIN)
11204                         raise_error_unexpected_syntax(TIN);
11205                 cpp = &n1->ncase.cases;
11206  next_case:
11207                 checkkwd = CHKNL | CHKKWD;
11208                 t = readtoken();
11209                 while (t != TESAC) {
11210                         if (lasttoken == TLP)
11211                                 readtoken();
11212                         *cpp = cp = stzalloc(sizeof(struct nclist));
11213                         cp->type = NCLIST;
11214                         app = &cp->nclist.pattern;
11215                         for (;;) {
11216                                 *app = ap = stzalloc(sizeof(struct narg));
11217                                 ap->type = NARG;
11218                                 /*ap->narg.next = NULL; - stzalloc did it */
11219                                 ap->narg.text = wordtext;
11220                                 ap->narg.backquote = backquotelist;
11221                                 if (readtoken() != TPIPE)
11222                                         break;
11223                                 app = &ap->narg.next;
11224                                 readtoken();
11225                         }
11226                         //ap->narg.next = NULL;
11227                         if (lasttoken != TRP)
11228                                 raise_error_unexpected_syntax(TRP);
11229                         cp->nclist.body = list(2);
11230
11231                         cpp = &cp->nclist.next;
11232
11233                         checkkwd = CHKNL | CHKKWD;
11234                         t = readtoken();
11235                         if (t != TESAC) {
11236                                 if (t != TENDCASE)
11237                                         raise_error_unexpected_syntax(TENDCASE);
11238                                 goto next_case;
11239                         }
11240                 }
11241                 *cpp = NULL;
11242                 goto redir;
11243         case TLP:
11244                 n1 = stzalloc(sizeof(struct nredir));
11245                 n1->type = NSUBSHELL;
11246                 n1->nredir.n = list(0);
11247                 /*n1->nredir.redirect = NULL; - stzalloc did it */
11248                 t = TRP;
11249                 break;
11250         case TBEGIN:
11251                 n1 = list(0);
11252                 t = TEND;
11253                 break;
11254         IF_ASH_BASH_COMPAT(case TFUNCTION:)
11255         case TWORD:
11256         case TREDIR:
11257                 tokpushback = 1;
11258                 return simplecmd();
11259         }
11260
11261         if (readtoken() != t)
11262                 raise_error_unexpected_syntax(t);
11263
11264  redir:
11265         /* Now check for redirection which may follow command */
11266         checkkwd = CHKKWD | CHKALIAS;
11267         rpp = rpp2;
11268         while (readtoken() == TREDIR) {
11269                 *rpp = n2 = redirnode;
11270                 rpp = &n2->nfile.next;
11271                 parsefname();
11272         }
11273         tokpushback = 1;
11274         *rpp = NULL;
11275         if (redir) {
11276                 if (n1->type != NSUBSHELL) {
11277                         n2 = stzalloc(sizeof(struct nredir));
11278                         n2->type = NREDIR;
11279                         n2->nredir.n = n1;
11280                         n1 = n2;
11281                 }
11282                 n1->nredir.redirect = redir;
11283         }
11284         return n1;
11285 }
11286
11287 #if ENABLE_ASH_BASH_COMPAT
11288 static int
11289 decode_dollar_squote(void)
11290 {
11291         static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11292         int c, cnt;
11293         char *p;
11294         char buf[4];
11295
11296         c = pgetc();
11297         p = strchr(C_escapes, c);
11298         if (p) {
11299                 buf[0] = c;
11300                 p = buf;
11301                 cnt = 3;
11302                 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11303                         do {
11304                                 c = pgetc();
11305                                 *++p = c;
11306                         } while ((unsigned char)(c - '0') <= 7 && --cnt);
11307                         pungetc();
11308                 } else if (c == 'x') { /* \xHH */
11309                         do {
11310                                 c = pgetc();
11311                                 *++p = c;
11312                         } while (isxdigit(c) && --cnt);
11313                         pungetc();
11314                         if (cnt == 3) { /* \x but next char is "bad" */
11315                                 c = 'x';
11316                                 goto unrecognized;
11317                         }
11318                 } else { /* simple seq like \\ or \t */
11319                         p++;
11320                 }
11321                 *p = '\0';
11322                 p = buf;
11323                 c = bb_process_escape_sequence((void*)&p);
11324         } else { /* unrecognized "\z": print both chars unless ' or " */
11325                 if (c != '\'' && c != '"') {
11326  unrecognized:
11327                         c |= 0x100; /* "please encode \, then me" */
11328                 }
11329         }
11330         return c;
11331 }
11332 #endif
11333
11334 /*
11335  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
11336  * is not NULL, read a here document.  In the latter case, eofmark is the
11337  * word which marks the end of the document and striptabs is true if
11338  * leading tabs should be stripped from the document.  The argument c
11339  * is the first character of the input token or document.
11340  *
11341  * Because C does not have internal subroutines, I have simulated them
11342  * using goto's to implement the subroutine linkage.  The following macros
11343  * will run code that appears at the end of readtoken1.
11344  */
11345 #define CHECKEND()      {goto checkend; checkend_return:;}
11346 #define PARSEREDIR()    {goto parseredir; parseredir_return:;}
11347 #define PARSESUB()      {goto parsesub; parsesub_return:;}
11348 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11349 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11350 #define PARSEARITH()    {goto parsearith; parsearith_return:;}
11351 static int
11352 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11353 {
11354         /* NB: syntax parameter fits into smallint */
11355         /* c parameter is an unsigned char or PEOF or PEOA */
11356         char *out;
11357         size_t len;
11358         char line[EOFMARKLEN + 1];
11359         struct nodelist *bqlist;
11360         smallint quotef;
11361         smallint dblquote;
11362         smallint oldstyle;
11363         smallint prevsyntax; /* syntax before arithmetic */
11364 #if ENABLE_ASH_EXPAND_PRMT
11365         smallint pssyntax;   /* we are expanding a prompt string */
11366 #endif
11367         int varnest;         /* levels of variables expansion */
11368         int arinest;         /* levels of arithmetic expansion */
11369         int parenlevel;      /* levels of parens in arithmetic */
11370         int dqvarnest;       /* levels of variables expansion within double quotes */
11371
11372         IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11373
11374         startlinno = g_parsefile->linno;
11375         bqlist = NULL;
11376         quotef = 0;
11377         prevsyntax = 0;
11378 #if ENABLE_ASH_EXPAND_PRMT
11379         pssyntax = (syntax == PSSYNTAX);
11380         if (pssyntax)
11381                 syntax = DQSYNTAX;
11382 #endif
11383         dblquote = (syntax == DQSYNTAX);
11384         varnest = 0;
11385         arinest = 0;
11386         parenlevel = 0;
11387         dqvarnest = 0;
11388
11389         STARTSTACKSTR(out);
11390  loop:
11391         /* For each line, until end of word */
11392         CHECKEND();     /* set c to PEOF if at end of here document */
11393         for (;;) {      /* until end of line or end of word */
11394                 CHECKSTRSPACE(4, out);  /* permit 4 calls to USTPUTC */
11395                 switch (SIT(c, syntax)) {
11396                 case CNL:       /* '\n' */
11397                         if (syntax == BASESYNTAX)
11398                                 goto endword;   /* exit outer loop */
11399                         USTPUTC(c, out);
11400                         nlprompt();
11401                         c = pgetc();
11402                         goto loop;              /* continue outer loop */
11403                 case CWORD:
11404                         USTPUTC(c, out);
11405                         break;
11406                 case CCTL:
11407 #if ENABLE_ASH_BASH_COMPAT
11408                         if (c == '\\' && bash_dollar_squote) {
11409                                 c = decode_dollar_squote();
11410                                 if (c == '\0') {
11411                                         /* skip $'\000', $'\x00' (like bash) */
11412                                         break;
11413                                 }
11414                                 if (c & 0x100) {
11415                                         /* Unknown escape. Encode as '\z' */
11416                                         c = (unsigned char)c;
11417                                         if (eofmark == NULL || dblquote)
11418                                                 USTPUTC(CTLESC, out);
11419                                         USTPUTC('\\', out);
11420                                 }
11421                         }
11422 #endif
11423                         if (eofmark == NULL || dblquote)
11424                                 USTPUTC(CTLESC, out);
11425                         USTPUTC(c, out);
11426                         break;
11427                 case CBACK:     /* backslash */
11428                         c = pgetc_without_PEOA();
11429                         if (c == PEOF) {
11430                                 USTPUTC(CTLESC, out);
11431                                 USTPUTC('\\', out);
11432                                 pungetc();
11433                         } else if (c == '\n') {
11434                                 nlprompt();
11435                         } else {
11436 #if ENABLE_ASH_EXPAND_PRMT
11437                                 if (c == '$' && pssyntax) {
11438                                         USTPUTC(CTLESC, out);
11439                                         USTPUTC('\\', out);
11440                                 }
11441 #endif
11442                                 /* Backslash is retained if we are in "str" and next char isn't special */
11443                                 if (dblquote
11444                                  && c != '\\'
11445                                  && c != '`'
11446                                  && c != '$'
11447                                  && (c != '"' || eofmark != NULL)
11448                                 ) {
11449                                         USTPUTC('\\', out);
11450                                 }
11451                                 USTPUTC(CTLESC, out);
11452                                 USTPUTC(c, out);
11453                                 quotef = 1;
11454                         }
11455                         break;
11456                 case CSQUOTE:
11457                         syntax = SQSYNTAX;
11458  quotemark:
11459                         if (eofmark == NULL) {
11460                                 USTPUTC(CTLQUOTEMARK, out);
11461                         }
11462                         break;
11463                 case CDQUOTE:
11464                         syntax = DQSYNTAX;
11465                         dblquote = 1;
11466                         goto quotemark;
11467                 case CENDQUOTE:
11468                         IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11469                         if (eofmark != NULL && varnest == 0) {
11470                                 USTPUTC(c, out);
11471                         } else {
11472                                 if (dqvarnest == 0) {
11473                                         syntax = BASESYNTAX;
11474                                         dblquote = 0;
11475                                 }
11476                                 quotef = 1;
11477                                 goto quotemark;
11478                         }
11479                         break;
11480                 case CVAR:      /* '$' */
11481                         PARSESUB();             /* parse substitution */
11482                         break;
11483                 case CENDVAR:   /* '}' */
11484                         if (varnest > 0) {
11485                                 varnest--;
11486                                 if (dqvarnest > 0) {
11487                                         dqvarnest--;
11488                                 }
11489                                 c = CTLENDVAR;
11490                         }
11491                         USTPUTC(c, out);
11492                         break;
11493 #if ENABLE_SH_MATH_SUPPORT
11494                 case CLP:       /* '(' in arithmetic */
11495                         parenlevel++;
11496                         USTPUTC(c, out);
11497                         break;
11498                 case CRP:       /* ')' in arithmetic */
11499                         if (parenlevel > 0) {
11500                                 parenlevel--;
11501                         } else {
11502                                 if (pgetc_eatbnl() == ')') {
11503                                         c = CTLENDARI;
11504                                         if (--arinest == 0) {
11505                                                 syntax = prevsyntax;
11506                                         }
11507                                 } else {
11508                                         /*
11509                                          * unbalanced parens
11510                                          * (don't 2nd guess - no error)
11511                                          */
11512                                         pungetc();
11513                                 }
11514                         }
11515                         USTPUTC(c, out);
11516                         break;
11517 #endif
11518                 case CBQUOTE:   /* '`' */
11519                         PARSEBACKQOLD();
11520                         break;
11521                 case CENDFILE:
11522                         goto endword;           /* exit outer loop */
11523                 case CIGN:
11524                         break;
11525                 default:
11526                         if (varnest == 0) {
11527 #if ENABLE_ASH_BASH_COMPAT
11528                                 if (c == '&') {
11529 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11530                                         if (pgetc() == '>')
11531                                                 c = 0x100 + '>'; /* flag &> */
11532                                         pungetc();
11533                                 }
11534 #endif
11535                                 goto endword;   /* exit outer loop */
11536                         }
11537                         IF_ASH_ALIAS(if (c != PEOA))
11538                                 USTPUTC(c, out);
11539                 }
11540                 c = pgetc();
11541         } /* for (;;) */
11542  endword:
11543
11544 #if ENABLE_SH_MATH_SUPPORT
11545         if (syntax == ARISYNTAX)
11546                 raise_error_syntax("missing '))'");
11547 #endif
11548         if (syntax != BASESYNTAX && eofmark == NULL)
11549                 raise_error_syntax("unterminated quoted string");
11550         if (varnest != 0) {
11551                 startlinno = g_parsefile->linno;
11552                 /* { */
11553                 raise_error_syntax("missing '}'");
11554         }
11555         USTPUTC('\0', out);
11556         len = out - (char *)stackblock();
11557         out = stackblock();
11558         if (eofmark == NULL) {
11559                 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11560                  && quotef == 0
11561                 ) {
11562                         if (isdigit_str9(out)) {
11563                                 PARSEREDIR(); /* passed as params: out, c */
11564                                 lasttoken = TREDIR;
11565                                 return lasttoken;
11566                         }
11567                         /* else: non-number X seen, interpret it
11568                          * as "NNNX>file" = "NNNX >file" */
11569                 }
11570                 pungetc();
11571         }
11572         quoteflag = quotef;
11573         backquotelist = bqlist;
11574         grabstackblock(len);
11575         wordtext = out;
11576         lasttoken = TWORD;
11577         return lasttoken;
11578 /* end of readtoken routine */
11579
11580 /*
11581  * Check to see whether we are at the end of the here document.  When this
11582  * is called, c is set to the first character of the next input line.  If
11583  * we are at the end of the here document, this routine sets the c to PEOF.
11584  */
11585 checkend: {
11586         if (eofmark) {
11587 #if ENABLE_ASH_ALIAS
11588                 if (c == PEOA)
11589                         c = pgetc_without_PEOA();
11590 #endif
11591                 if (striptabs) {
11592                         while (c == '\t') {
11593                                 c = pgetc_without_PEOA();
11594                         }
11595                 }
11596                 if (c == *eofmark) {
11597                         if (pfgets(line, sizeof(line)) != NULL) {
11598                                 char *p, *q;
11599
11600                                 p = line;
11601                                 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11602                                         continue;
11603                                 if (*p == '\n' && *q == '\0') {
11604                                         c = PEOF;
11605                                         nlnoprompt();
11606                                 } else {
11607                                         pushstring(line, NULL);
11608                                 }
11609                         }
11610                 }
11611         }
11612         goto checkend_return;
11613 }
11614
11615 /*
11616  * Parse a redirection operator.  The variable "out" points to a string
11617  * specifying the fd to be redirected.  The variable "c" contains the
11618  * first character of the redirection operator.
11619  */
11620 parseredir: {
11621         /* out is already checked to be a valid number or "" */
11622         int fd = (*out == '\0' ? -1 : atoi(out));
11623         union node *np;
11624
11625         np = stzalloc(sizeof(struct nfile));
11626         if (c == '>') {
11627                 np->nfile.fd = 1;
11628                 c = pgetc();
11629                 if (c == '>')
11630                         np->type = NAPPEND;
11631                 else if (c == '|')
11632                         np->type = NCLOBBER;
11633                 else if (c == '&')
11634                         np->type = NTOFD;
11635                         /* it also can be NTO2 (>&file), but we can't figure it out yet */
11636                 else {
11637                         np->type = NTO;
11638                         pungetc();
11639                 }
11640         }
11641 #if ENABLE_ASH_BASH_COMPAT
11642         else if (c == 0x100 + '>') { /* this flags &> redirection */
11643                 np->nfile.fd = 1;
11644                 pgetc(); /* this is '>', no need to check */
11645                 np->type = NTO2;
11646         }
11647 #endif
11648         else { /* c == '<' */
11649                 /*np->nfile.fd = 0; - stzalloc did it */
11650                 c = pgetc();
11651                 switch (c) {
11652                 case '<':
11653                         if (sizeof(struct nfile) != sizeof(struct nhere)) {
11654                                 np = stzalloc(sizeof(struct nhere));
11655                                 /*np->nfile.fd = 0; - stzalloc did it */
11656                         }
11657                         np->type = NHERE;
11658                         heredoc = stzalloc(sizeof(struct heredoc));
11659                         heredoc->here = np;
11660                         c = pgetc();
11661                         if (c == '-') {
11662                                 heredoc->striptabs = 1;
11663                         } else {
11664                                 /*heredoc->striptabs = 0; - stzalloc did it */
11665                                 pungetc();
11666                         }
11667                         break;
11668
11669                 case '&':
11670                         np->type = NFROMFD;
11671                         break;
11672
11673                 case '>':
11674                         np->type = NFROMTO;
11675                         break;
11676
11677                 default:
11678                         np->type = NFROM;
11679                         pungetc();
11680                         break;
11681                 }
11682         }
11683         if (fd >= 0)
11684                 np->nfile.fd = fd;
11685         redirnode = np;
11686         goto parseredir_return;
11687 }
11688
11689 /*
11690  * Parse a substitution.  At this point, we have read the dollar sign
11691  * and nothing else.
11692  */
11693
11694 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11695  * (assuming ascii char codes, as the original implementation did) */
11696 #define is_special(c) \
11697         (((unsigned)(c) - 33 < 32) \
11698                         && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11699 parsesub: {
11700         unsigned char subtype;
11701         int typeloc;
11702         int flags;
11703
11704         c = pgetc_eatbnl();
11705         if (c > 255 /* PEOA or PEOF */
11706          || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11707         ) {
11708 #if ENABLE_ASH_BASH_COMPAT
11709                 if (syntax != DQSYNTAX && c == '\'')
11710                         bash_dollar_squote = 1;
11711                 else
11712 #endif
11713                         USTPUTC('$', out);
11714                 pungetc();
11715         } else if (c == '(') {
11716                 /* $(command) or $((arith)) */
11717                 if (pgetc_eatbnl() == '(') {
11718 #if ENABLE_SH_MATH_SUPPORT
11719                         PARSEARITH();
11720 #else
11721                         raise_error_syntax("you disabled math support for $((arith)) syntax");
11722 #endif
11723                 } else {
11724                         pungetc();
11725                         PARSEBACKQNEW();
11726                 }
11727         } else {
11728                 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11729                 USTPUTC(CTLVAR, out);
11730                 typeloc = out - (char *)stackblock();
11731                 USTPUTC(VSNORMAL, out);
11732                 subtype = VSNORMAL;
11733                 if (c == '{') {
11734                         c = pgetc_eatbnl();
11735                         if (c == '#') {
11736                                 c = pgetc_eatbnl();
11737                                 if (c == '}')
11738                                         c = '#'; /* ${#} - same as $# */
11739                                 else
11740                                         subtype = VSLENGTH; /* ${#VAR} */
11741                         } else {
11742                                 subtype = 0;
11743                         }
11744                 }
11745                 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11746                         /* $[{[#]]NAME[}] */
11747                         do {
11748                                 STPUTC(c, out);
11749                                 c = pgetc_eatbnl();
11750                         } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11751                 } else if (isdigit(c)) {
11752                         /* $[{[#]]NUM[}] */
11753                         do {
11754                                 STPUTC(c, out);
11755                                 c = pgetc_eatbnl();
11756                         } while (isdigit(c));
11757                 } else if (is_special(c)) {
11758                         /* $[{[#]]<specialchar>[}] */
11759                         USTPUTC(c, out);
11760                         c = pgetc_eatbnl();
11761                 } else {
11762  badsub:
11763                         raise_error_syntax("bad substitution");
11764                 }
11765                 if (c != '}' && subtype == VSLENGTH) {
11766                         /* ${#VAR didn't end with } */
11767                         goto badsub;
11768                 }
11769
11770                 STPUTC('=', out);
11771                 flags = 0;
11772                 if (subtype == 0) {
11773                         static const char types[] ALIGN1 = "}-+?=";
11774                         /* ${VAR...} but not $VAR or ${#VAR} */
11775                         /* c == first char after VAR */
11776                         switch (c) {
11777                         case ':':
11778                                 c = pgetc_eatbnl();
11779 #if ENABLE_ASH_BASH_COMPAT
11780                                 /* This check is only needed to not misinterpret
11781                                  * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11782                                  * constructs.
11783                                  */
11784                                 if (!strchr(types, c)) {
11785                                         subtype = VSSUBSTR;
11786                                         pungetc();
11787                                         break; /* "goto do_pungetc" is bigger (!) */
11788                                 }
11789 #endif
11790                                 flags = VSNUL;
11791                                 /*FALLTHROUGH*/
11792                         default: {
11793                                 const char *p = strchr(types, c);
11794                                 if (p == NULL)
11795                                         goto badsub;
11796                                 subtype = p - types + VSNORMAL;
11797                                 break;
11798                         }
11799                         case '%':
11800                         case '#': {
11801                                 int cc = c;
11802                                 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11803                                 c = pgetc_eatbnl();
11804                                 if (c != cc)
11805                                         goto do_pungetc;
11806                                 subtype++;
11807                                 break;
11808                         }
11809 #if ENABLE_ASH_BASH_COMPAT
11810                         case '/':
11811                                 /* ${v/[/]pattern/repl} */
11812 //TODO: encode pattern and repl separately.
11813 // Currently ${v/$var_with_slash/repl} is horribly broken
11814                                 subtype = VSREPLACE;
11815                                 c = pgetc_eatbnl();
11816                                 if (c != '/')
11817                                         goto do_pungetc;
11818                                 subtype++; /* VSREPLACEALL */
11819                                 break;
11820 #endif
11821                         }
11822                 } else {
11823  do_pungetc:
11824                         pungetc();
11825                 }
11826                 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11827                 if (subtype != VSNORMAL) {
11828                         varnest++;
11829                         if (dblquote) {
11830                                 dqvarnest++;
11831                         }
11832                 }
11833         }
11834         goto parsesub_return;
11835 }
11836
11837 /*
11838  * Called to parse command substitutions.  Newstyle is set if the command
11839  * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11840  * list of commands (passed by reference), and savelen is the number of
11841  * characters on the top of the stack which must be preserved.
11842  */
11843 parsebackq: {
11844         struct nodelist **nlpp;
11845         union node *n;
11846         char *str;
11847         size_t savelen;
11848         smallint saveprompt = 0;
11849
11850         str = NULL;
11851         savelen = out - (char *)stackblock();
11852         if (savelen > 0) {
11853                 /*
11854                  * FIXME: this can allocate very large block on stack and SEGV.
11855                  * Example:
11856                  * echo "..<100kbytes>..`true` $(true) `true` ..."
11857                  * allocates 100kb for every command subst. With about
11858                  * a hundred command substitutions stack overflows.
11859                  * With larger prepended string, SEGV happens sooner.
11860                  */
11861                 str = alloca(savelen);
11862                 memcpy(str, stackblock(), savelen);
11863         }
11864
11865         if (oldstyle) {
11866                 /* We must read until the closing backquote, giving special
11867                  * treatment to some slashes, and then push the string and
11868                  * reread it as input, interpreting it normally.
11869                  */
11870                 char *pout;
11871                 size_t psavelen;
11872                 char *pstr;
11873
11874                 STARTSTACKSTR(pout);
11875                 for (;;) {
11876                         int pc;
11877
11878                         setprompt_if(needprompt, 2);
11879                         pc = pgetc();
11880                         switch (pc) {
11881                         case '`':
11882                                 goto done;
11883
11884                         case '\\':
11885                                 pc = pgetc();
11886                                 if (pc == '\n') {
11887                                         nlprompt();
11888                                         /*
11889                                          * If eating a newline, avoid putting
11890                                          * the newline into the new character
11891                                          * stream (via the STPUTC after the
11892                                          * switch).
11893                                          */
11894                                         continue;
11895                                 }
11896                                 if (pc != '\\' && pc != '`' && pc != '$'
11897                                  && (!dblquote || pc != '"')
11898                                 ) {
11899                                         STPUTC('\\', pout);
11900                                 }
11901                                 if (pc <= 255 /* not PEOA or PEOF */) {
11902                                         break;
11903                                 }
11904                                 /* fall through */
11905
11906                         case PEOF:
11907                         IF_ASH_ALIAS(case PEOA:)
11908                                 startlinno = g_parsefile->linno;
11909                                 raise_error_syntax("EOF in backquote substitution");
11910
11911                         case '\n':
11912                                 nlnoprompt();
11913                                 break;
11914
11915                         default:
11916                                 break;
11917                         }
11918                         STPUTC(pc, pout);
11919                 }
11920  done:
11921                 STPUTC('\0', pout);
11922                 psavelen = pout - (char *)stackblock();
11923                 if (psavelen > 0) {
11924                         pstr = grabstackstr(pout);
11925                         setinputstring(pstr);
11926                 }
11927         }
11928         nlpp = &bqlist;
11929         while (*nlpp)
11930                 nlpp = &(*nlpp)->next;
11931         *nlpp = stzalloc(sizeof(**nlpp));
11932         /* (*nlpp)->next = NULL; - stzalloc did it */
11933
11934         if (oldstyle) {
11935                 saveprompt = doprompt;
11936                 doprompt = 0;
11937         }
11938
11939         n = list(2);
11940
11941         if (oldstyle)
11942                 doprompt = saveprompt;
11943         else if (readtoken() != TRP)
11944                 raise_error_unexpected_syntax(TRP);
11945
11946         (*nlpp)->n = n;
11947         if (oldstyle) {
11948                 /*
11949                  * Start reading from old file again, ignoring any pushed back
11950                  * tokens left from the backquote parsing
11951                  */
11952                 popfile();
11953                 tokpushback = 0;
11954         }
11955         while (stackblocksize() <= savelen)
11956                 growstackblock();
11957         STARTSTACKSTR(out);
11958         if (str) {
11959                 memcpy(out, str, savelen);
11960                 STADJUST(savelen, out);
11961         }
11962         USTPUTC(CTLBACKQ, out);
11963         if (oldstyle)
11964                 goto parsebackq_oldreturn;
11965         goto parsebackq_newreturn;
11966 }
11967
11968 #if ENABLE_SH_MATH_SUPPORT
11969 /*
11970  * Parse an arithmetic expansion (indicate start of one and set state)
11971  */
11972 parsearith: {
11973         if (++arinest == 1) {
11974                 prevsyntax = syntax;
11975                 syntax = ARISYNTAX;
11976         }
11977         USTPUTC(CTLARI, out);
11978         goto parsearith_return;
11979 }
11980 #endif
11981 } /* end of readtoken */
11982
11983 /*
11984  * Read the next input token.
11985  * If the token is a word, we set backquotelist to the list of cmds in
11986  *      backquotes.  We set quoteflag to true if any part of the word was
11987  *      quoted.
11988  * If the token is TREDIR, then we set redirnode to a structure containing
11989  *      the redirection.
11990  * In all cases, the variable startlinno is set to the number of the line
11991  *      on which the token starts.
11992  *
11993  * [Change comment:  here documents and internal procedures]
11994  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
11995  *  word parsing code into a separate routine.  In this case, readtoken
11996  *  doesn't need to have any internal procedures, but parseword does.
11997  *  We could also make parseoperator in essence the main routine, and
11998  *  have parseword (readtoken1?) handle both words and redirection.]
11999  */
12000 #define NEW_xxreadtoken
12001 #ifdef NEW_xxreadtoken
12002 /* singles must be first! */
12003 static const char xxreadtoken_chars[7] ALIGN1 = {
12004         '\n', '(', ')', /* singles */
12005         '&', '|', ';',  /* doubles */
12006         0
12007 };
12008
12009 #define xxreadtoken_singles 3
12010 #define xxreadtoken_doubles 3
12011
12012 static const char xxreadtoken_tokens[] ALIGN1 = {
12013         TNL, TLP, TRP,          /* only single occurrence allowed */
12014         TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12015         TEOF,                   /* corresponds to trailing nul */
12016         TAND, TOR, TENDCASE     /* if double occurrence */
12017 };
12018
12019 static int
12020 xxreadtoken(void)
12021 {
12022         int c;
12023
12024         if (tokpushback) {
12025                 tokpushback = 0;
12026                 return lasttoken;
12027         }
12028         setprompt_if(needprompt, 2);
12029         startlinno = g_parsefile->linno;
12030         for (;;) {                      /* until token or start of word found */
12031                 c = pgetc();
12032                 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12033                         continue;
12034
12035                 if (c == '#') {
12036                         while ((c = pgetc()) != '\n' && c != PEOF)
12037                                 continue;
12038                         pungetc();
12039                 } else if (c == '\\') {
12040                         if (pgetc() != '\n') {
12041                                 pungetc();
12042                                 break; /* return readtoken1(...) */
12043                         }
12044                         nlprompt();
12045                 } else {
12046                         const char *p;
12047
12048                         p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12049                         if (c != PEOF) {
12050                                 if (c == '\n') {
12051                                         nlnoprompt();
12052                                 }
12053
12054                                 p = strchr(xxreadtoken_chars, c);
12055                                 if (p == NULL)
12056                                         break; /* return readtoken1(...) */
12057
12058                                 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12059                                         int cc = pgetc();
12060                                         if (cc == c) {    /* double occurrence? */
12061                                                 p += xxreadtoken_doubles + 1;
12062                                         } else {
12063                                                 pungetc();
12064 #if ENABLE_ASH_BASH_COMPAT
12065                                                 if (c == '&' && cc == '>') /* &> */
12066                                                         break; /* return readtoken1(...) */
12067 #endif
12068                                         }
12069                                 }
12070                         }
12071                         lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12072                         return lasttoken;
12073                 }
12074         } /* for (;;) */
12075
12076         return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12077 }
12078 #else /* old xxreadtoken */
12079 #define RETURN(token)   return lasttoken = token
12080 static int
12081 xxreadtoken(void)
12082 {
12083         int c;
12084
12085         if (tokpushback) {
12086                 tokpushback = 0;
12087                 return lasttoken;
12088         }
12089         setprompt_if(needprompt, 2);
12090         startlinno = g_parsefile->linno;
12091         for (;;) {      /* until token or start of word found */
12092                 c = pgetc();
12093                 switch (c) {
12094                 case ' ': case '\t':
12095                 IF_ASH_ALIAS(case PEOA:)
12096                         continue;
12097                 case '#':
12098                         while ((c = pgetc()) != '\n' && c != PEOF)
12099                                 continue;
12100                         pungetc();
12101                         continue;
12102                 case '\\':
12103                         if (pgetc() == '\n') {
12104                                 nlprompt();
12105                                 continue;
12106                         }
12107                         pungetc();
12108                         goto breakloop;
12109                 case '\n':
12110                         nlnoprompt();
12111                         RETURN(TNL);
12112                 case PEOF:
12113                         RETURN(TEOF);
12114                 case '&':
12115                         if (pgetc() == '&')
12116                                 RETURN(TAND);
12117                         pungetc();
12118                         RETURN(TBACKGND);
12119                 case '|':
12120                         if (pgetc() == '|')
12121                                 RETURN(TOR);
12122                         pungetc();
12123                         RETURN(TPIPE);
12124                 case ';':
12125                         if (pgetc() == ';')
12126                                 RETURN(TENDCASE);
12127                         pungetc();
12128                         RETURN(TSEMI);
12129                 case '(':
12130                         RETURN(TLP);
12131                 case ')':
12132                         RETURN(TRP);
12133                 default:
12134                         goto breakloop;
12135                 }
12136         }
12137  breakloop:
12138         return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12139 #undef RETURN
12140 }
12141 #endif /* old xxreadtoken */
12142
12143 static int
12144 readtoken(void)
12145 {
12146         int t;
12147         int kwd = checkkwd;
12148 #if DEBUG
12149         smallint alreadyseen = tokpushback;
12150 #endif
12151
12152 #if ENABLE_ASH_ALIAS
12153  top:
12154 #endif
12155
12156         t = xxreadtoken();
12157
12158         /*
12159          * eat newlines
12160          */
12161         if (kwd & CHKNL) {
12162                 while (t == TNL) {
12163                         parseheredoc();
12164                         t = xxreadtoken();
12165                 }
12166         }
12167
12168         if (t != TWORD || quoteflag) {
12169                 goto out;
12170         }
12171
12172         /*
12173          * check for keywords
12174          */
12175         if (kwd & CHKKWD) {
12176                 const char *const *pp;
12177
12178                 pp = findkwd(wordtext);
12179                 if (pp) {
12180                         lasttoken = t = pp - tokname_array;
12181                         TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12182                         goto out;
12183                 }
12184         }
12185
12186         if (checkkwd & CHKALIAS) {
12187 #if ENABLE_ASH_ALIAS
12188                 struct alias *ap;
12189                 ap = lookupalias(wordtext, 1);
12190                 if (ap != NULL) {
12191                         if (*ap->val) {
12192                                 pushstring(ap->val, ap);
12193                         }
12194                         goto top;
12195                 }
12196 #endif
12197         }
12198  out:
12199         checkkwd = 0;
12200 #if DEBUG
12201         if (!alreadyseen)
12202                 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12203         else
12204                 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12205 #endif
12206         return t;
12207 }
12208
12209 static int
12210 peektoken(void)
12211 {
12212         int t;
12213
12214         t = readtoken();
12215         tokpushback = 1;
12216         return t;
12217 }
12218
12219 /*
12220  * Read and parse a command.  Returns NODE_EOF on end of file.
12221  * (NULL is a valid parse tree indicating a blank line.)
12222  */
12223 static union node *
12224 parsecmd(int interact)
12225 {
12226         tokpushback = 0;
12227         checkkwd = 0;
12228         heredoclist = 0;
12229         doprompt = interact;
12230         setprompt_if(doprompt, doprompt);
12231         needprompt = 0;
12232         return list(1);
12233 }
12234
12235 /*
12236  * Input any here documents.
12237  */
12238 static void
12239 parseheredoc(void)
12240 {
12241         struct heredoc *here;
12242         union node *n;
12243
12244         here = heredoclist;
12245         heredoclist = NULL;
12246
12247         while (here) {
12248                 setprompt_if(needprompt, 2);
12249                 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12250                                 here->eofmark, here->striptabs);
12251                 n = stzalloc(sizeof(struct narg));
12252                 n->narg.type = NARG;
12253                 /*n->narg.next = NULL; - stzalloc did it */
12254                 n->narg.text = wordtext;
12255                 n->narg.backquote = backquotelist;
12256                 here->here->nhere.doc = n;
12257                 here = here->next;
12258         }
12259 }
12260
12261
12262 /*
12263  * called by editline -- any expansions to the prompt should be added here.
12264  */
12265 #if ENABLE_ASH_EXPAND_PRMT
12266 static const char *
12267 expandstr(const char *ps)
12268 {
12269         union node n;
12270         int saveprompt;
12271
12272         /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12273          * and token processing _can_ alter it (delete NULs etc). */
12274         setinputstring((char *)ps);
12275
12276         saveprompt = doprompt;
12277         doprompt = 0;
12278         readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12279         doprompt = saveprompt;
12280
12281         popfile();
12282
12283         n.narg.type = NARG;
12284         n.narg.next = NULL;
12285         n.narg.text = wordtext;
12286         n.narg.backquote = backquotelist;
12287
12288         expandarg(&n, NULL, EXP_QUOTED);
12289         return stackblock();
12290 }
12291 #endif
12292
12293 /*
12294  * Execute a command or commands contained in a string.
12295  */
12296 static int
12297 evalstring(char *s, int flags)
12298 {
12299         union node *n;
12300         struct stackmark smark;
12301         int status;
12302
12303         s = sstrdup(s);
12304         setinputstring(s);
12305         setstackmark(&smark);
12306
12307         status = 0;
12308         while ((n = parsecmd(0)) != NODE_EOF) {
12309                 int i;
12310
12311                 i = evaltree(n, flags);
12312                 if (n)
12313                         status = i;
12314                 popstackmark(&smark);
12315                 if (evalskip)
12316                         break;
12317         }
12318         popstackmark(&smark);
12319         popfile();
12320         stunalloc(s);
12321
12322         return status;
12323 }
12324
12325 /*
12326  * The eval command.
12327  */
12328 static int FAST_FUNC
12329 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12330 {
12331         char *p;
12332         char *concat;
12333
12334         if (argv[1]) {
12335                 p = argv[1];
12336                 argv += 2;
12337                 if (argv[0]) {
12338                         STARTSTACKSTR(concat);
12339                         for (;;) {
12340                                 concat = stack_putstr(p, concat);
12341                                 p = *argv++;
12342                                 if (p == NULL)
12343                                         break;
12344                                 STPUTC(' ', concat);
12345                         }
12346                         STPUTC('\0', concat);
12347                         p = grabstackstr(concat);
12348                 }
12349                 return evalstring(p, flags & EV_TESTED);
12350         }
12351         return 0;
12352 }
12353
12354 /*
12355  * Read and execute commands.
12356  * "Top" is nonzero for the top level command loop;
12357  * it turns on prompting if the shell is interactive.
12358  */
12359 static int
12360 cmdloop(int top)
12361 {
12362         union node *n;
12363         struct stackmark smark;
12364         int inter;
12365         int status = 0;
12366         int numeof = 0;
12367
12368         TRACE(("cmdloop(%d) called\n", top));
12369         for (;;) {
12370                 int skip;
12371
12372                 setstackmark(&smark);
12373 #if JOBS
12374                 if (doing_jobctl)
12375                         showjobs(SHOW_CHANGED|SHOW_STDERR);
12376 #endif
12377                 inter = 0;
12378                 if (iflag && top) {
12379                         inter++;
12380                         chkmail();
12381                 }
12382                 n = parsecmd(inter);
12383 #if DEBUG
12384                 if (DEBUG > 2 && debug && (n != NODE_EOF))
12385                         showtree(n);
12386 #endif
12387                 if (n == NODE_EOF) {
12388                         if (!top || numeof >= 50)
12389                                 break;
12390                         if (!stoppedjobs()) {
12391                                 if (!Iflag)
12392                                         break;
12393                                 out2str("\nUse \"exit\" to leave shell.\n");
12394                         }
12395                         numeof++;
12396                 } else if (nflag == 0) {
12397                         int i;
12398
12399                         /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12400                         job_warning >>= 1;
12401                         numeof = 0;
12402                         i = evaltree(n, 0);
12403                         if (n)
12404                                 status = i;
12405                 }
12406                 popstackmark(&smark);
12407                 skip = evalskip;
12408
12409                 if (skip) {
12410                         evalskip &= ~SKIPFUNC;
12411                         break;
12412                 }
12413         }
12414         return status;
12415 }
12416
12417 /*
12418  * Take commands from a file.  To be compatible we should do a path
12419  * search for the file, which is necessary to find sub-commands.
12420  */
12421 static char *
12422 find_dot_file(char *name)
12423 {
12424         char *fullname;
12425         const char *path = pathval();
12426         struct stat statb;
12427
12428         /* don't try this for absolute or relative paths */
12429         if (strchr(name, '/'))
12430                 return name;
12431
12432         /* IIRC standards do not say whether . is to be searched.
12433          * And it is even smaller this way, making it unconditional for now:
12434          */
12435         if (1) { /* ENABLE_ASH_BASH_COMPAT */
12436                 fullname = name;
12437                 goto try_cur_dir;
12438         }
12439
12440         while ((fullname = path_advance(&path, name)) != NULL) {
12441  try_cur_dir:
12442                 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12443                         /*
12444                          * Don't bother freeing here, since it will
12445                          * be freed by the caller.
12446                          */
12447                         return fullname;
12448                 }
12449                 if (fullname != name)
12450                         stunalloc(fullname);
12451         }
12452
12453         /* not found in the PATH */
12454         ash_msg_and_raise_error("%s: not found", name);
12455         /* NOTREACHED */
12456 }
12457
12458 static int FAST_FUNC
12459 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12460 {
12461         /* "false; . empty_file; echo $?" should print 0, not 1: */
12462         int status = 0;
12463         char *fullname;
12464         char **argv;
12465         struct strlist *sp;
12466         volatile struct shparam saveparam;
12467
12468         for (sp = cmdenviron; sp; sp = sp->next)
12469                 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12470
12471         nextopt(nullstr); /* handle possible "--" */
12472         argv = argptr;
12473
12474         if (!argv[0]) {
12475                 /* bash says: "bash: .: filename argument required" */
12476                 return 2; /* bash compat */
12477         }
12478
12479         /* This aborts if file isn't found, which is POSIXly correct.
12480          * bash returns exitcode 1 instead.
12481          */
12482         fullname = find_dot_file(argv[0]);
12483         argv++;
12484         if (argv[0]) { /* . FILE ARGS, ARGS exist */
12485                 int argc;
12486                 saveparam = shellparam;
12487                 shellparam.malloced = 0;
12488                 argc = 1;
12489                 while (argv[argc])
12490                         argc++;
12491                 shellparam.nparam = argc;
12492                 shellparam.p = argv;
12493         };
12494
12495         /* This aborts if file can't be opened, which is POSIXly correct.
12496          * bash returns exitcode 1 instead.
12497          */
12498         setinputfile(fullname, INPUT_PUSH_FILE);
12499         commandname = fullname;
12500         status = cmdloop(0);
12501         popfile();
12502
12503         if (argv[0]) {
12504                 freeparam(&shellparam);
12505                 shellparam = saveparam;
12506         };
12507
12508         return status;
12509 }
12510
12511 static int FAST_FUNC
12512 exitcmd(int argc UNUSED_PARAM, char **argv)
12513 {
12514         if (stoppedjobs())
12515                 return 0;
12516         if (argv[1])
12517                 exitstatus = number(argv[1]);
12518         raise_exception(EXEXIT);
12519         /* NOTREACHED */
12520 }
12521
12522 /*
12523  * Read a file containing shell functions.
12524  */
12525 static void
12526 readcmdfile(char *name)
12527 {
12528         setinputfile(name, INPUT_PUSH_FILE);
12529         cmdloop(0);
12530         popfile();
12531 }
12532
12533
12534 /* ============ find_command inplementation */
12535
12536 /*
12537  * Resolve a command name.  If you change this routine, you may have to
12538  * change the shellexec routine as well.
12539  */
12540 static void
12541 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12542 {
12543         struct tblentry *cmdp;
12544         int idx;
12545         int prev;
12546         char *fullname;
12547         struct stat statb;
12548         int e;
12549         int updatetbl;
12550         struct builtincmd *bcmd;
12551
12552         /* If name contains a slash, don't use PATH or hash table */
12553         if (strchr(name, '/') != NULL) {
12554                 entry->u.index = -1;
12555                 if (act & DO_ABS) {
12556                         while (stat(name, &statb) < 0) {
12557 #ifdef SYSV
12558                                 if (errno == EINTR)
12559                                         continue;
12560 #endif
12561                                 entry->cmdtype = CMDUNKNOWN;
12562                                 return;
12563                         }
12564                 }
12565                 entry->cmdtype = CMDNORMAL;
12566                 return;
12567         }
12568
12569 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12570
12571         updatetbl = (path == pathval());
12572         if (!updatetbl) {
12573                 act |= DO_ALTPATH;
12574                 if (strstr(path, "%builtin") != NULL)
12575                         act |= DO_ALTBLTIN;
12576         }
12577
12578         /* If name is in the table, check answer will be ok */
12579         cmdp = cmdlookup(name, 0);
12580         if (cmdp != NULL) {
12581                 int bit;
12582
12583                 switch (cmdp->cmdtype) {
12584                 default:
12585 #if DEBUG
12586                         abort();
12587 #endif
12588                 case CMDNORMAL:
12589                         bit = DO_ALTPATH;
12590                         break;
12591                 case CMDFUNCTION:
12592                         bit = DO_NOFUNC;
12593                         break;
12594                 case CMDBUILTIN:
12595                         bit = DO_ALTBLTIN;
12596                         break;
12597                 }
12598                 if (act & bit) {
12599                         updatetbl = 0;
12600                         cmdp = NULL;
12601                 } else if (cmdp->rehash == 0)
12602                         /* if not invalidated by cd, we're done */
12603                         goto success;
12604         }
12605
12606         /* If %builtin not in path, check for builtin next */
12607         bcmd = find_builtin(name);
12608         if (bcmd) {
12609                 if (IS_BUILTIN_REGULAR(bcmd))
12610                         goto builtin_success;
12611                 if (act & DO_ALTPATH) {
12612                         if (!(act & DO_ALTBLTIN))
12613                                 goto builtin_success;
12614                 } else if (builtinloc <= 0) {
12615                         goto builtin_success;
12616                 }
12617         }
12618
12619 #if ENABLE_FEATURE_SH_STANDALONE
12620         {
12621                 int applet_no = find_applet_by_name(name);
12622                 if (applet_no >= 0) {
12623                         entry->cmdtype = CMDNORMAL;
12624                         entry->u.index = -2 - applet_no;
12625                         return;
12626                 }
12627         }
12628 #endif
12629
12630         /* We have to search path. */
12631         prev = -1;              /* where to start */
12632         if (cmdp && cmdp->rehash) {     /* doing a rehash */
12633                 if (cmdp->cmdtype == CMDBUILTIN)
12634                         prev = builtinloc;
12635                 else
12636                         prev = cmdp->param.index;
12637         }
12638
12639         e = ENOENT;
12640         idx = -1;
12641  loop:
12642         while ((fullname = path_advance(&path, name)) != NULL) {
12643                 stunalloc(fullname);
12644                 /* NB: code below will still use fullname
12645                  * despite it being "unallocated" */
12646                 idx++;
12647                 if (pathopt) {
12648                         if (prefix(pathopt, "builtin")) {
12649                                 if (bcmd)
12650                                         goto builtin_success;
12651                                 continue;
12652                         }
12653                         if ((act & DO_NOFUNC)
12654                          || !prefix(pathopt, "func")
12655                         ) {     /* ignore unimplemented options */
12656                                 continue;
12657                         }
12658                 }
12659                 /* if rehash, don't redo absolute path names */
12660                 if (fullname[0] == '/' && idx <= prev) {
12661                         if (idx < prev)
12662                                 continue;
12663                         TRACE(("searchexec \"%s\": no change\n", name));
12664                         goto success;
12665                 }
12666                 while (stat(fullname, &statb) < 0) {
12667 #ifdef SYSV
12668                         if (errno == EINTR)
12669                                 continue;
12670 #endif
12671                         if (errno != ENOENT && errno != ENOTDIR)
12672                                 e = errno;
12673                         goto loop;
12674                 }
12675                 e = EACCES;     /* if we fail, this will be the error */
12676                 if (!S_ISREG(statb.st_mode))
12677                         continue;
12678                 if (pathopt) {          /* this is a %func directory */
12679                         stalloc(strlen(fullname) + 1);
12680                         /* NB: stalloc will return space pointed by fullname
12681                          * (because we don't have any intervening allocations
12682                          * between stunalloc above and this stalloc) */
12683                         readcmdfile(fullname);
12684                         cmdp = cmdlookup(name, 0);
12685                         if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12686                                 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12687                         stunalloc(fullname);
12688                         goto success;
12689                 }
12690                 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12691                 if (!updatetbl) {
12692                         entry->cmdtype = CMDNORMAL;
12693                         entry->u.index = idx;
12694                         return;
12695                 }
12696                 INT_OFF;
12697                 cmdp = cmdlookup(name, 1);
12698                 cmdp->cmdtype = CMDNORMAL;
12699                 cmdp->param.index = idx;
12700                 INT_ON;
12701                 goto success;
12702         }
12703
12704         /* We failed.  If there was an entry for this command, delete it */
12705         if (cmdp && updatetbl)
12706                 delete_cmd_entry();
12707         if (act & DO_ERR)
12708                 ash_msg("%s: %s", name, errmsg(e, "not found"));
12709         entry->cmdtype = CMDUNKNOWN;
12710         return;
12711
12712  builtin_success:
12713         if (!updatetbl) {
12714                 entry->cmdtype = CMDBUILTIN;
12715                 entry->u.cmd = bcmd;
12716                 return;
12717         }
12718         INT_OFF;
12719         cmdp = cmdlookup(name, 1);
12720         cmdp->cmdtype = CMDBUILTIN;
12721         cmdp->param.cmd = bcmd;
12722         INT_ON;
12723  success:
12724         cmdp->rehash = 0;
12725         entry->cmdtype = cmdp->cmdtype;
12726         entry->u = cmdp->param;
12727 }
12728
12729
12730 /*
12731  * The trap builtin.
12732  */
12733 static int FAST_FUNC
12734 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12735 {
12736         char *action;
12737         char **ap;
12738         int signo, exitcode;
12739
12740         nextopt(nullstr);
12741         ap = argptr;
12742         if (!*ap) {
12743                 for (signo = 0; signo < NSIG; signo++) {
12744                         char *tr = trap_ptr[signo];
12745                         if (tr) {
12746                                 /* note: bash adds "SIG", but only if invoked
12747                                  * as "bash". If called as "sh", or if set -o posix,
12748                                  * then it prints short signal names.
12749                                  * We are printing short names: */
12750                                 out1fmt("trap -- %s %s\n",
12751                                                 single_quote(tr),
12752                                                 get_signame(signo));
12753                 /* trap_ptr != trap only if we are in special-cased `trap` code.
12754                  * In this case, we will exit very soon, no need to free(). */
12755                                 /* if (trap_ptr != trap && tp[0]) */
12756                                 /*      free(tr); */
12757                         }
12758                 }
12759                 /*
12760                 if (trap_ptr != trap) {
12761                         free(trap_ptr);
12762                         trap_ptr = trap;
12763                 }
12764                 */
12765                 return 0;
12766         }
12767
12768         action = NULL;
12769         if (ap[1])
12770                 action = *ap++;
12771         exitcode = 0;
12772         while (*ap) {
12773                 signo = get_signum(*ap);
12774                 if (signo < 0) {
12775                         /* Mimic bash message exactly */
12776                         ash_msg("%s: invalid signal specification", *ap);
12777                         exitcode = 1;
12778                         goto next;
12779                 }
12780                 INT_OFF;
12781                 if (action) {
12782                         if (LONE_DASH(action))
12783                                 action = NULL;
12784                         else
12785                                 action = ckstrdup(action);
12786                 }
12787                 free(trap[signo]);
12788                 if (action)
12789                         may_have_traps = 1;
12790                 trap[signo] = action;
12791                 if (signo != 0)
12792                         setsignal(signo);
12793                 INT_ON;
12794  next:
12795                 ap++;
12796         }
12797         return exitcode;
12798 }
12799
12800
12801 /* ============ Builtins */
12802
12803 #if ENABLE_ASH_HELP
12804 static int FAST_FUNC
12805 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12806 {
12807         unsigned col;
12808         unsigned i;
12809
12810         out1fmt(
12811                 "Built-in commands:\n"
12812                 "------------------\n");
12813         for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12814                 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12815                                         builtintab[i].name + 1);
12816                 if (col > 60) {
12817                         out1fmt("\n");
12818                         col = 0;
12819                 }
12820         }
12821 # if ENABLE_FEATURE_SH_STANDALONE
12822         {
12823                 const char *a = applet_names;
12824                 while (*a) {
12825                         col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12826                         if (col > 60) {
12827                                 out1fmt("\n");
12828                                 col = 0;
12829                         }
12830                         while (*a++ != '\0')
12831                                 continue;
12832                 }
12833         }
12834 # endif
12835         newline_and_flush(stdout);
12836         return EXIT_SUCCESS;
12837 }
12838 #endif
12839
12840 #if MAX_HISTORY
12841 static int FAST_FUNC
12842 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12843 {
12844         show_history(line_input_state);
12845         return EXIT_SUCCESS;
12846 }
12847 #endif
12848
12849 /*
12850  * The export and readonly commands.
12851  */
12852 static int FAST_FUNC
12853 exportcmd(int argc UNUSED_PARAM, char **argv)
12854 {
12855         struct var *vp;
12856         char *name;
12857         const char *p;
12858         char **aptr;
12859         char opt;
12860         int flag;
12861         int flag_off;
12862
12863         /* "readonly" in bash accepts, but ignores -n.
12864          * We do the same: it saves a conditional in nextopt's param.
12865          */
12866         flag_off = 0;
12867         while ((opt = nextopt("np")) != '\0') {
12868                 if (opt == 'n')
12869                         flag_off = VEXPORT;
12870         }
12871         flag = VEXPORT;
12872         if (argv[0][0] == 'r') {
12873                 flag = VREADONLY;
12874                 flag_off = 0; /* readonly ignores -n */
12875         }
12876         flag_off = ~flag_off;
12877
12878         /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12879         {
12880                 aptr = argptr;
12881                 name = *aptr;
12882                 if (name) {
12883                         do {
12884                                 p = strchr(name, '=');
12885                                 if (p != NULL) {
12886                                         p++;
12887                                 } else {
12888                                         vp = *findvar(hashvar(name), name);
12889                                         if (vp) {
12890                                                 vp->flags = ((vp->flags | flag) & flag_off);
12891                                                 continue;
12892                                         }
12893                                 }
12894                                 setvar(name, p, (flag & flag_off));
12895                         } while ((name = *++aptr) != NULL);
12896                         return 0;
12897                 }
12898         }
12899
12900         /* No arguments. Show the list of exported or readonly vars.
12901          * -n is ignored.
12902          */
12903         showvars(argv[0], flag, 0);
12904         return 0;
12905 }
12906
12907 /*
12908  * Delete a function if it exists.
12909  */
12910 static void
12911 unsetfunc(const char *name)
12912 {
12913         struct tblentry *cmdp;
12914
12915         cmdp = cmdlookup(name, 0);
12916         if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12917                 delete_cmd_entry();
12918 }
12919
12920 /*
12921  * The unset builtin command.  We unset the function before we unset the
12922  * variable to allow a function to be unset when there is a readonly variable
12923  * with the same name.
12924  */
12925 static int FAST_FUNC
12926 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12927 {
12928         char **ap;
12929         int i;
12930         int flag = 0;
12931         int ret = 0;
12932
12933         while ((i = nextopt("vf")) != 0) {
12934                 flag = i;
12935         }
12936
12937         for (ap = argptr; *ap; ap++) {
12938                 if (flag != 'f') {
12939                         i = unsetvar(*ap);
12940                         ret |= i;
12941                         if (!(i & 2))
12942                                 continue;
12943                 }
12944                 if (flag != 'v')
12945                         unsetfunc(*ap);
12946         }
12947         return ret & 1;
12948 }
12949
12950 static const unsigned char timescmd_str[] ALIGN1 = {
12951         ' ',  offsetof(struct tms, tms_utime),
12952         '\n', offsetof(struct tms, tms_stime),
12953         ' ',  offsetof(struct tms, tms_cutime),
12954         '\n', offsetof(struct tms, tms_cstime),
12955         0
12956 };
12957 static int FAST_FUNC
12958 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12959 {
12960         unsigned long clk_tck, s, t;
12961         const unsigned char *p;
12962         struct tms buf;
12963
12964         clk_tck = bb_clk_tck();
12965         times(&buf);
12966
12967         p = timescmd_str;
12968         do {
12969                 t = *(clock_t *)(((char *) &buf) + p[1]);
12970                 s = t / clk_tck;
12971                 t = t % clk_tck;
12972                 out1fmt("%lum%lu.%03lus%c",
12973                         s / 60, s % 60,
12974                         (t * 1000) / clk_tck,
12975                         p[0]);
12976                 p += 2;
12977         } while (*p);
12978
12979         return 0;
12980 }
12981
12982 #if ENABLE_SH_MATH_SUPPORT
12983 /*
12984  * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12985  * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12986  *
12987  * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12988  */
12989 static int FAST_FUNC
12990 letcmd(int argc UNUSED_PARAM, char **argv)
12991 {
12992         arith_t i;
12993
12994         argv++;
12995         if (!*argv)
12996                 ash_msg_and_raise_error("expression expected");
12997         do {
12998                 i = ash_arith(*argv);
12999         } while (*++argv);
13000
13001         return !i;
13002 }
13003 #endif
13004
13005 /*
13006  * The read builtin. Options:
13007  *      -r              Do not interpret '\' specially
13008  *      -s              Turn off echo (tty only)
13009  *      -n NCHARS       Read NCHARS max
13010  *      -p PROMPT       Display PROMPT on stderr (if input is from tty)
13011  *      -t SECONDS      Timeout after SECONDS (tty or pipe only)
13012  *      -u FD           Read from given FD instead of fd 0
13013  * This uses unbuffered input, which may be avoidable in some cases.
13014  * TODO: bash also has:
13015  *      -a ARRAY        Read into array[0],[1],etc
13016  *      -d DELIM        End on DELIM char, not newline
13017  *      -e              Use line editing (tty only)
13018  */
13019 static int FAST_FUNC
13020 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13021 {
13022         char *opt_n = NULL;
13023         char *opt_p = NULL;
13024         char *opt_t = NULL;
13025         char *opt_u = NULL;
13026         int read_flags = 0;
13027         const char *r;
13028         int i;
13029
13030         while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13031                 switch (i) {
13032                 case 'p':
13033                         opt_p = optionarg;
13034                         break;
13035                 case 'n':
13036                         opt_n = optionarg;
13037                         break;
13038                 case 's':
13039                         read_flags |= BUILTIN_READ_SILENT;
13040                         break;
13041                 case 't':
13042                         opt_t = optionarg;
13043                         break;
13044                 case 'r':
13045                         read_flags |= BUILTIN_READ_RAW;
13046                         break;
13047                 case 'u':
13048                         opt_u = optionarg;
13049                         break;
13050                 default:
13051                         break;
13052                 }
13053         }
13054
13055         /* "read -s" needs to save/restore termios, can't allow ^C
13056          * to jump out of it.
13057          */
13058         INT_OFF;
13059         r = shell_builtin_read(setvar0,
13060                 argptr,
13061                 bltinlookup("IFS"), /* can be NULL */
13062                 read_flags,
13063                 opt_n,
13064                 opt_p,
13065                 opt_t,
13066                 opt_u
13067         );
13068         INT_ON;
13069
13070         if ((uintptr_t)r > 1)
13071                 ash_msg_and_raise_error(r);
13072
13073         return (uintptr_t)r;
13074 }
13075
13076 static int FAST_FUNC
13077 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13078 {
13079         static const char permuser[3] ALIGN1 = "ogu";
13080
13081         mode_t mask;
13082         int symbolic_mode = 0;
13083
13084         while (nextopt("S") != '\0') {
13085                 symbolic_mode = 1;
13086         }
13087
13088         INT_OFF;
13089         mask = umask(0);
13090         umask(mask);
13091         INT_ON;
13092
13093         if (*argptr == NULL) {
13094                 if (symbolic_mode) {
13095                         char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13096                         char *p = buf;
13097                         int i;
13098
13099                         i = 2;
13100                         for (;;) {
13101                                 *p++ = ',';
13102                                 *p++ = permuser[i];
13103                                 *p++ = '=';
13104                                 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13105                                 if (!(mask & 0400)) *p++ = 'r';
13106                                 if (!(mask & 0200)) *p++ = 'w';
13107                                 if (!(mask & 0100)) *p++ = 'x';
13108                                 mask <<= 3;
13109                                 if (--i < 0)
13110                                         break;
13111                         }
13112                         *p = '\0';
13113                         puts(buf + 1);
13114                 } else {
13115                         out1fmt("%04o\n", mask);
13116                 }
13117         } else {
13118                 char *modestr = *argptr;
13119                 /* numeric umasks are taken as-is */
13120                 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13121                 if (!isdigit(modestr[0]))
13122                         mask ^= 0777;
13123                 mask = bb_parse_mode(modestr, mask);
13124                 if ((unsigned)mask > 0777) {
13125                         ash_msg_and_raise_error("illegal mode: %s", modestr);
13126                 }
13127                 if (!isdigit(modestr[0]))
13128                         mask ^= 0777;
13129                 umask(mask);
13130         }
13131         return 0;
13132 }
13133
13134 static int FAST_FUNC
13135 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13136 {
13137         return shell_builtin_ulimit(argv);
13138 }
13139
13140 /* ============ main() and helpers */
13141
13142 /*
13143  * Called to exit the shell.
13144  */
13145 static void
13146 exitshell(void)
13147 {
13148         struct jmploc loc;
13149         char *p;
13150         int status;
13151
13152 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13153         save_history(line_input_state);
13154 #endif
13155         status = exitstatus;
13156         TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13157         if (setjmp(loc.loc)) {
13158                 if (exception_type == EXEXIT)
13159                         status = exitstatus;
13160                 goto out;
13161         }
13162         exception_handler = &loc;
13163         p = trap[0];
13164         if (p) {
13165                 trap[0] = NULL;
13166                 evalskip = 0;
13167                 evalstring(p, 0);
13168                 /*free(p); - we'll exit soon */
13169         }
13170  out:
13171         /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13172          * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13173          */
13174         setjobctl(0);
13175         flush_stdout_stderr();
13176         _exit(status);
13177         /* NOTREACHED */
13178 }
13179
13180 static void
13181 init(void)
13182 {
13183         /* we will never free this */
13184         basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13185
13186         signal(SIGCHLD, SIG_DFL);
13187         /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13188          * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13189          */
13190         signal(SIGHUP, SIG_DFL);
13191
13192         {
13193                 char **envp;
13194                 const char *p;
13195                 struct stat st1, st2;
13196
13197                 initvar();
13198                 for (envp = environ; envp && *envp; envp++) {
13199                         p = endofname(*envp);
13200                         if (p != *envp && *p == '=') {
13201                                 setvareq(*envp, VEXPORT|VTEXTFIXED);
13202                         }
13203                 }
13204
13205                 setvareq((char*)defoptindvar, VTEXTFIXED);
13206
13207                 setvar0("PPID", utoa(getppid()));
13208 #if ENABLE_ASH_BASH_COMPAT
13209                 p = lookupvar("SHLVL");
13210                 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13211                 if (!lookupvar("HOSTNAME")) {
13212                         struct utsname uts;
13213                         uname(&uts);
13214                         setvar0("HOSTNAME", uts.nodename);
13215                 }
13216 #endif
13217                 p = lookupvar("PWD");
13218                 if (p) {
13219                         if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13220                          || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13221                         ) {
13222                                 p = NULL;
13223                         }
13224                 }
13225                 setpwd(p, 0);
13226         }
13227 }
13228
13229
13230 //usage:#define ash_trivial_usage
13231 //usage:        "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13232 //usage:#define ash_full_usage "\n\n"
13233 //usage:        "Unix shell interpreter"
13234
13235 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13236 //usage:# define sh_trivial_usage ash_trivial_usage
13237 //usage:# define sh_full_usage    ash_full_usage
13238 //usage:#endif
13239 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13240 //usage:# define bash_trivial_usage ash_trivial_usage
13241 //usage:# define bash_full_usage    ash_full_usage
13242 //usage:#endif
13243
13244 /*
13245  * Process the shell command line arguments.
13246  */
13247 static void
13248 procargs(char **argv)
13249 {
13250         int i;
13251         const char *xminusc;
13252         char **xargv;
13253
13254         xargv = argv;
13255         arg0 = xargv[0];
13256         /* if (xargv[0]) - mmm, this is always true! */
13257                 xargv++;
13258         for (i = 0; i < NOPTS; i++)
13259                 optlist[i] = 2;
13260         argptr = xargv;
13261         if (options(/*cmdline:*/ 1)) {
13262                 /* it already printed err message */
13263                 raise_exception(EXERROR);
13264         }
13265         xargv = argptr;
13266         xminusc = minusc;
13267         if (*xargv == NULL) {
13268                 if (xminusc)
13269                         ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13270                 sflag = 1;
13271         }
13272         if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13273                 iflag = 1;
13274         if (mflag == 2)
13275                 mflag = iflag;
13276         for (i = 0; i < NOPTS; i++)
13277                 if (optlist[i] == 2)
13278                         optlist[i] = 0;
13279 #if DEBUG == 2
13280         debug = 1;
13281 #endif
13282         /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13283         if (xminusc) {
13284                 minusc = *xargv++;
13285                 if (*xargv)
13286                         goto setarg0;
13287         } else if (!sflag) {
13288                 setinputfile(*xargv, 0);
13289  setarg0:
13290                 arg0 = *xargv++;
13291                 commandname = arg0;
13292         }
13293
13294         shellparam.p = xargv;
13295 #if ENABLE_ASH_GETOPTS
13296         shellparam.optind = 1;
13297         shellparam.optoff = -1;
13298 #endif
13299         /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13300         while (*xargv) {
13301                 shellparam.nparam++;
13302                 xargv++;
13303         }
13304         optschanged();
13305 }
13306
13307 /*
13308  * Read /etc/profile or .profile.
13309  */
13310 static void
13311 read_profile(const char *name)
13312 {
13313         if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13314                 return;
13315         cmdloop(0);
13316         popfile();
13317 }
13318
13319 /*
13320  * This routine is called when an error or an interrupt occurs in an
13321  * interactive shell and control is returned to the main command loop.
13322  */
13323 static void
13324 reset(void)
13325 {
13326         /* from eval.c: */
13327         evalskip = 0;
13328         loopnest = 0;
13329         /* from input.c: */
13330         g_parsefile->left_in_buffer = 0;
13331         g_parsefile->left_in_line = 0;      /* clear input buffer */
13332         popallfiles();
13333         /* from parser.c: */
13334         tokpushback = 0;
13335         checkkwd = 0;
13336         /* from redir.c: */
13337         clearredir(/*drop:*/ 0);
13338 }
13339
13340 #if PROFILE
13341 static short profile_buf[16384];
13342 extern int etext();
13343 #endif
13344
13345 /*
13346  * Main routine.  We initialize things, parse the arguments, execute
13347  * profiles if we're a login shell, and then call cmdloop to execute
13348  * commands.  The setjmp call sets up the location to jump to when an
13349  * exception occurs.  When an exception occurs the variable "state"
13350  * is used to figure out how far we had gotten.
13351  */
13352 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13353 int ash_main(int argc UNUSED_PARAM, char **argv)
13354 {
13355         const char *shinit;
13356         volatile smallint state;
13357         struct jmploc jmploc;
13358         struct stackmark smark;
13359
13360         /* Initialize global data */
13361         INIT_G_misc();
13362         INIT_G_memstack();
13363         INIT_G_var();
13364 #if ENABLE_ASH_ALIAS
13365         INIT_G_alias();
13366 #endif
13367         INIT_G_cmdtable();
13368
13369 #if PROFILE
13370         monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13371 #endif
13372
13373 #if ENABLE_FEATURE_EDITING
13374         line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13375 #endif
13376         state = 0;
13377         if (setjmp(jmploc.loc)) {
13378                 smallint e;
13379                 smallint s;
13380
13381                 reset();
13382
13383                 e = exception_type;
13384                 s = state;
13385                 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13386                         exitshell();
13387                 }
13388                 if (e == EXINT) {
13389                         newline_and_flush(stderr);
13390                 }
13391
13392                 popstackmark(&smark);
13393                 FORCE_INT_ON; /* enable interrupts */
13394                 if (s == 1)
13395                         goto state1;
13396                 if (s == 2)
13397                         goto state2;
13398                 if (s == 3)
13399                         goto state3;
13400                 goto state4;
13401         }
13402         exception_handler = &jmploc;
13403 #if DEBUG
13404         opentrace();
13405         TRACE(("Shell args: "));
13406         trace_puts_args(argv);
13407 #endif
13408         rootpid = getpid();
13409
13410         init();
13411         setstackmark(&smark);
13412         procargs(argv);
13413
13414         if (argv[0] && argv[0][0] == '-')
13415                 isloginsh = 1;
13416         if (isloginsh) {
13417                 const char *hp;
13418
13419                 state = 1;
13420                 read_profile("/etc/profile");
13421  state1:
13422                 state = 2;
13423                 hp = lookupvar("HOME");
13424                 if (hp) {
13425                         hp = concat_path_file(hp, ".profile");
13426                         read_profile(hp);
13427                         free((char*)hp);
13428                 }
13429         }
13430  state2:
13431         state = 3;
13432         if (
13433 #ifndef linux
13434          getuid() == geteuid() && getgid() == getegid() &&
13435 #endif
13436          iflag
13437         ) {
13438                 shinit = lookupvar("ENV");
13439                 if (shinit != NULL && *shinit != '\0') {
13440                         read_profile(shinit);
13441                 }
13442         }
13443  state3:
13444         state = 4;
13445         if (minusc) {
13446                 /* evalstring pushes parsefile stack.
13447                  * Ensure we don't falsely claim that 0 (stdin)
13448                  * is one of stacked source fds.
13449                  * Testcase: ash -c 'exec 1>&0' must not complain. */
13450                 // if (!sflag) g_parsefile->pf_fd = -1;
13451                 // ^^ not necessary since now we special-case fd 0
13452                 // in is_hidden_fd() to not be considered "hidden fd"
13453                 evalstring(minusc, 0);
13454         }
13455
13456         if (sflag || minusc == NULL) {
13457 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13458                 if (iflag) {
13459                         const char *hp = lookupvar("HISTFILE");
13460                         if (!hp) {
13461                                 hp = lookupvar("HOME");
13462                                 if (hp) {
13463                                         hp = concat_path_file(hp, ".ash_history");
13464                                         setvar0("HISTFILE", hp);
13465                                         free((char*)hp);
13466                                         hp = lookupvar("HISTFILE");
13467                                 }
13468                         }
13469                         if (hp)
13470                                 line_input_state->hist_file = hp;
13471 # if ENABLE_FEATURE_SH_HISTFILESIZE
13472                         hp = lookupvar("HISTFILESIZE");
13473                         line_input_state->max_history = size_from_HISTFILESIZE(hp);
13474 # endif
13475                 }
13476 #endif
13477  state4: /* XXX ??? - why isn't this before the "if" statement */
13478                 cmdloop(1);
13479         }
13480 #if PROFILE
13481         monitor(0);
13482 #endif
13483 #ifdef GPROF
13484         {
13485                 extern void _mcleanup(void);
13486                 _mcleanup();
13487         }
13488 #endif
13489         TRACE(("End of main reached\n"));
13490         exitshell();
13491         /* NOTREACHED */
13492 }
13493
13494
13495 /*-
13496  * Copyright (c) 1989, 1991, 1993, 1994
13497  *      The Regents of the University of California.  All rights reserved.
13498  *
13499  * This code is derived from software contributed to Berkeley by
13500  * Kenneth Almquist.
13501  *
13502  * Redistribution and use in source and binary forms, with or without
13503  * modification, are permitted provided that the following conditions
13504  * are met:
13505  * 1. Redistributions of source code must retain the above copyright
13506  *    notice, this list of conditions and the following disclaimer.
13507  * 2. Redistributions in binary form must reproduce the above copyright
13508  *    notice, this list of conditions and the following disclaimer in the
13509  *    documentation and/or other materials provided with the distribution.
13510  * 3. Neither the name of the University nor the names of its contributors
13511  *    may be used to endorse or promote products derived from this software
13512  *    without specific prior written permission.
13513  *
13514  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13515  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13516  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13517  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13518  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13519  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13520  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13521  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13522  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13523  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13524  * SUCH DAMAGE.
13525  */