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