Magellan Linux

Contents of /trunk/mkinitrd-magellan/busybox/shell/ash.c

Parent Directory Parent Directory | Revision Log Revision Log


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