722d90d5793a3845b70b2d6e2becd98b641aa07f
[oweals/busybox.git] / shell / msh.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Minix shell port for busybox
4  *
5  * This version of the Minix shell was adapted for use in busybox
6  * by Erik Andersen <andersen@codepoet.org>
7  *
8  * - backtick expansion did not work properly
9  *   Jonas Holmberg <jonas.holmberg@axis.com>
10  *   Robert Schwebel <r.schwebel@pengutronix.de>
11  *   Erik Andersen <andersen@codepoet.org>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21  * General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26  *
27  * Original copyright notice is retained at the end of this file.
28  */
29
30 #include <ctype.h>
31 #include <dirent.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <limits.h>
35 #include <setjmp.h>
36 #include <signal.h>
37 #include <stddef.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <time.h>
42 #include <unistd.h>
43 #include <sys/stat.h>
44 #include <sys/times.h>
45 #include <sys/types.h>
46 #include <sys/wait.h>
47
48 #include "cmdedit.h"
49 #include "busybox.h"
50
51
52 /* -------- sh.h -------- */
53 /*
54  * shell
55  */
56
57 #define LINELIM 2100
58 #define NPUSH   8                               /* limit to input nesting */
59
60 #undef NOFILE
61 #define NOFILE  20                              /* Number of open files */
62 #define NUFILE  10                              /* Number of user-accessible files */
63 #define FDBASE  10                              /* First file usable by Shell */
64
65 /*
66  * values returned by wait
67  */
68 #define WAITSIG(s) ((s)&0177)
69 #define WAITVAL(s) (((s)>>8)&0377)
70 #define WAITCORE(s) (((s)&0200)!=0)
71
72 /*
73  * library and system definitions
74  */
75 typedef void xint;                              /* base type of jmp_buf, for not broken compilers */
76
77 /*
78  * shell components
79  */
80
81 #define QUOTE   0200
82
83 #define NOBLOCK ((struct op *)NULL)
84 #define NOWORD  ((char *)NULL)
85 #define NOWORDS ((char **)NULL)
86 #define NOPIPE  ((int *)NULL)
87
88 /*
89  * Description of a command or an operation on commands.
90  * Might eventually use a union.
91  */
92 struct op {
93         int type;                                       /* operation type, see below */
94         char **words;                           /* arguments to a command */
95         struct ioword **ioact;          /* IO actions (eg, < > >>) */
96         struct op *left;
97         struct op *right;
98         char *str;                                      /* identifier for case and for */
99 };
100
101 #define TCOM    1                               /* command */
102 #define TPAREN  2                               /* (c-list) */
103 #define TPIPE   3                               /* a | b */
104 #define TLIST   4                               /* a [&;] b */
105 #define TOR     5                                       /* || */
106 #define TAND    6                               /* && */
107 #define TFOR    7
108 #define TDO     8
109 #define TCASE   9
110 #define TIF     10
111 #define TWHILE  11
112 #define TUNTIL  12
113 #define TELIF   13
114 #define TPAT    14                              /* pattern in case */
115 #define TBRACE  15                              /* {c-list} */
116 #define TASYNC  16                              /* c & */
117
118 /*
119  * actions determining the environment of a process
120  */
121 #define BIT(i)  (1<<(i))
122 #define FEXEC   BIT(0)                  /* execute without forking */
123
124 /*
125  * flags to control evaluation of words
126  */
127 #define DOSUB   1                               /* interpret $, `, and quotes */
128 #define DOBLANK 2                               /* perform blank interpretation */
129 #define DOGLOB  4                               /* interpret [?* */
130 #define DOKEY   8                               /* move words with `=' to 2nd arg. list */
131 #define DOTRIM  16                              /* trim resulting string */
132
133 #define DOALL   (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
134
135 static char **dolv;
136 static int dolc;
137 static int exstat;
138 static char gflg;
139 static int interactive;                 /* Is this an interactive shell */
140 static int execflg;
141 static int multiline;                   /* \n changed to ; */
142 static struct op *outtree;              /* result from parser */
143
144 static xint *failpt;
145 static xint *errpt;
146 static struct brkcon *brklist;
147 static int isbreak;
148 static int newfile(char *s);
149 static char *findeq(char *cp);
150 static char *cclass(char *p, int sub);
151 static void initarea(void);
152 extern int msh_main(int argc, char **argv);
153
154
155 struct brkcon {
156         jmp_buf brkpt;
157         struct brkcon *nextlev;
158 };
159
160 /*
161  * redirection
162  */
163 struct ioword {
164         short io_unit;                          /* unit affected */
165         short io_flag;                          /* action (below) */
166         char *io_name;                          /* file name */
167 };
168
169 #define IOREAD  1                               /* < */
170 #define IOHERE  2                               /* << (here file) */
171 #define IOWRITE 4                               /* > */
172 #define IOCAT   8                               /* >> */
173 #define IOXHERE 16                              /* ${}, ` in << */
174 #define IODUP   32                              /* >&digit */
175 #define IOCLOSE 64                              /* >&- */
176
177 #define IODEFAULT (-1)                  /* token for default IO unit */
178
179 static struct wdblock *wdlist;
180 static struct wdblock *iolist;
181
182 /*
183  * parsing & execution environment
184  */
185 static struct env {
186         char *linep;
187         struct io *iobase;
188         struct io *iop;
189         xint *errpt;
190         int iofd;
191         struct env *oenv;
192 } e;
193
194 /*
195  * flags:
196  * -e: quit on error
197  * -k: look for name=value everywhere on command line
198  * -n: no execution
199  * -t: exit after reading and executing one command
200  * -v: echo as read
201  * -x: trace
202  * -u: unset variables net diagnostic
203  */
204 static char *flag;
205
206 static char *null;                              /* null value for variable */
207 static int intr;                                /* interrupt pending */
208
209 static char *trap[_NSIG + 1];
210 static char ourtrap[_NSIG + 1];
211 static int trapset;                             /* trap pending */
212
213 static int heedint;                             /* heed interrupt signals */
214
215 static int yynerrs;                             /* yacc */
216
217 static char line[LINELIM];
218 static char *elinep;
219
220 /*
221  * other functions
222  */
223 static int (*inbuilt(char *s)) (struct op *);
224
225
226 static char *rexecve(char *c, char **v, char **envp);
227 static char *space(int n);
228 static char *strsave(char *s, int a);
229 static char *evalstr(char *cp, int f);
230 static char *putn(int n);
231 static char *itoa(int n);
232 static char *unquote(char *as);
233 static struct var *lookup(char *n);
234 static int rlookup(char *n);
235 static struct wdblock *glob(char *cp, struct wdblock *wb);
236 static int my_getc(int ec);
237 static int subgetc(int ec, int quoted);
238 static char **makenv(void);
239 static char **eval(char **ap, int f);
240 static int setstatus(int s);
241 static int waitfor(int lastpid, int canintr);
242
243 static void onintr(int s);              /* SIGINT handler */
244
245 static int newenv(int f);
246 static void quitenv(void);
247 static void err(char *s);
248 static int anys(char *s1, char *s2);
249 static int any(int c, char *s);
250 static void next(int f);
251 static void setdash(void);
252 static void onecommand(void);
253 static void runtrap(int i);
254 static int gmatch(char *s, char *p);
255
256 /*
257  * error handling
258  */
259 static void leave(void);                /* abort shell (or fail in subshell) */
260 static void fail(void);                 /* fail but return to process next command */
261 static void warn(char *s);
262 static void sig(int i);                 /* default signal handler */
263
264
265
266 /* -------- area stuff -------- */
267
268 #define REGSIZE         sizeof(struct region)
269 #define GROWBY          256
270 //#define   SHRINKBY   64
271 #undef  SHRINKBY
272 #define FREE 32767
273 #define BUSY 0
274 #define ALIGN (sizeof(int)-1)
275
276
277 struct region {
278         struct region *next;
279         int area;
280 };
281
282
283
284 /* -------- grammar stuff -------- */
285 typedef union {
286         char *cp;
287         char **wp;
288         int i;
289         struct op *o;
290 } YYSTYPE;
291
292 #define WORD    256
293 #define LOGAND  257
294 #define LOGOR   258
295 #define BREAK   259
296 #define IF      260
297 #define THEN    261
298 #define ELSE    262
299 #define ELIF    263
300 #define FI      264
301 #define CASE    265
302 #define ESAC    266
303 #define FOR     267
304 #define WHILE   268
305 #define UNTIL   269
306 #define DO      270
307 #define DONE    271
308 #define IN      272
309 #define YYERRCODE 300
310
311 /* flags to yylex */
312 #define CONTIN  01                              /* skip new lines to complete command */
313
314 #define SYNTAXERR       zzerr()
315 static struct op *pipeline(int cf);
316 static struct op *andor(void);
317 static struct op *c_list(void);
318 static int synio(int cf);
319 static void musthave(int c, int cf);
320 static struct op *simple(void);
321 static struct op *nested(int type, int mark);
322 static struct op *command(int cf);
323 static struct op *dogroup(int onlydone);
324 static struct op *thenpart(void);
325 static struct op *elsepart(void);
326 static struct op *caselist(void);
327 static struct op *casepart(void);
328 static char **pattern(void);
329 static char **wordlist(void);
330 static struct op *list(struct op *t1, struct op *t2);
331 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
332 static struct op *newtp(void);
333 static struct op *namelist(struct op *t);
334 static char **copyw(void);
335 static void word(char *cp);
336 static struct ioword **copyio(void);
337 static struct ioword *io(int u, int f, char *cp);
338 static void zzerr(void);
339 static void yyerror(char *s);
340 static int yylex(int cf);
341 static int collect(int c, int c1);
342 static int dual(int c);
343 static void diag(int ec);
344 static char *tree(unsigned size);
345
346 /* -------- var.h -------- */
347
348 struct var {
349         char *value;
350         char *name;
351         struct var *next;
352         char status;
353 };
354
355 #define COPYV   1                               /* flag to setval, suggesting copy */
356 #define RONLY   01                              /* variable is read-only */
357 #define EXPORT  02                              /* variable is to be exported */
358 #define GETCELL 04                              /* name & value space was got with getcell */
359
360 static struct var *vlist;               /* dictionary */
361
362 static struct var *homedir;             /* home directory */
363 static struct var *prompt;              /* main prompt */
364 static struct var *cprompt;             /* continuation prompt */
365 static struct var *path;                /* search path for commands */
366 static struct var *shell;               /* shell to interpret command files */
367 static struct var *ifs;                 /* field separators */
368
369 static int yyparse(void);
370 static struct var *lookup(char *n);
371 static void setval(struct var *vp, char *val);
372 static void nameval(struct var *vp, char *val, char *name);
373 static void export(struct var *vp);
374 static void ronly(struct var *vp);
375 static int isassign(char *s);
376 static int checkname(char *cp);
377 static int assign(char *s, int cf);
378 static void putvlist(int f, int out);
379 static int eqname(char *n1, char *n2);
380
381 static int execute(struct op *t, int *pin, int *pout, int act);
382
383 /* -------- io.h -------- */
384 /* io buffer */
385 struct iobuf {
386         unsigned id;                            /* buffer id */
387         char buf[512];                          /* buffer */
388         char *bufp;                                     /* pointer into buffer */
389         char *ebufp;                            /* pointer to end of buffer */
390 };
391
392 /* possible arguments to an IO function */
393 struct ioarg {
394         char *aword;
395         char **awordlist;
396         int afile;                                      /* file descriptor */
397         unsigned afid;                          /* buffer id */
398         long afpos;                                     /* file position */
399         struct iobuf *afbuf;            /* buffer for this file */
400 };
401
402 //static struct ioarg ioargstack[NPUSH];
403 #define AFID_NOBUF      (~0)
404 #define AFID_ID         0
405
406 /* an input generator's state */
407 struct io {
408         int (*iofn) (struct ioarg *, struct io *);
409         struct ioarg *argp;
410         int peekc;
411         char prev;                                      /* previous character read by readc() */
412         char nlcount;                           /* for `'s */
413         char xchar;                                     /* for `'s */
414         char task;                                      /* reason for pushed IO */
415 };
416
417 //static    struct  io  iostack[NPUSH];
418 #define XOTHER  0                               /* none of the below */
419 #define XDOLL   1                               /* expanding ${} */
420 #define XGRAVE  2                               /* expanding `'s */
421 #define XIO     3                                       /* file IO */
422
423 /* in substitution */
424 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
425
426 /*
427  * input generators for IO structure
428  */
429 static int nlchar(struct ioarg *ap);
430 static int strchar(struct ioarg *ap);
431 static int qstrchar(struct ioarg *ap);
432 static int filechar(struct ioarg *ap);
433 static int herechar(struct ioarg *ap);
434 static int linechar(struct ioarg *ap);
435 static int gravechar(struct ioarg *ap, struct io *iop);
436 static int qgravechar(struct ioarg *ap, struct io *iop);
437 static int dolchar(struct ioarg *ap);
438 static int wdchar(struct ioarg *ap);
439 static void scraphere(void);
440 static void freehere(int area);
441 static void gethere(void);
442 static void markhere(char *s, struct ioword *iop);
443 static int herein(char *hname, int xdoll);
444 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
445
446 /*
447  * IO functions
448  */
449 static int eofc(void);
450 static int readc(void);
451 static void unget(int c);
452 static void ioecho(int c);
453 static void prs(char *s);
454 static void prn(unsigned u);
455 static void closef(int i);
456 static void closeall(void);
457
458 /*
459  * IO control
460  */
461 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
462 static int remap(int fd);
463 static int openpipe(int *pv);
464 static void closepipe(int *pv);
465 static struct io *setbase(struct io *ip);
466
467 static struct ioarg temparg;    /* temporary for PUSHIO */
468
469 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)),pushio(&temparg,(gen)))
470 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
471
472 /* -------- word.h -------- */
473
474 #define NSTART  16                              /* default number of words to allow for initially */
475
476 struct wdblock {
477         short w_bsize;
478         short w_nword;
479         /* bounds are arbitrary */
480         char *w_words[1];
481 };
482
483 static struct wdblock *addword(char *wd, struct wdblock *wb);
484 static struct wdblock *newword(int nw);
485 static char **getwords(struct wdblock *wb);
486
487 /* -------- area.h -------- */
488
489 /*
490  * storage allocation
491  */
492 static char *getcell(unsigned nbytes);
493 static void garbage(void);
494 static void setarea(char *cp, int a);
495 static int getarea(char *cp);
496 static void freearea(int a);
497 static void freecell(char *cp);
498 static int areanum;                             /* current allocation area */
499
500 #define NEW(type) (type *)getcell(sizeof(type))
501 #define DELETE(obj)     freecell((char *)obj)
502
503
504 /* -------- misc stuff -------- */
505
506 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp,
507                                         int *pforked);
508 static int iosetup(struct ioword *iop, int pipein, int pipeout);
509 static void echo(char **wp);
510 static struct op **find1case(struct op *t, char *w);
511 static struct op *findcase(struct op *t, char *w);
512 static void brkset(struct brkcon *bc);
513 static int dolabel(struct op *t);
514 static int dohelp(struct op *t);
515 static int dochdir(struct op *t);
516 static int doshift(struct op *t);
517 static int dologin(struct op *t);
518 static int doumask(struct op *t);
519 static int doexec(struct op *t);
520 static int dodot(struct op *t);
521 static int dowait(struct op *t);
522 static int doread(struct op *t);
523 static int doeval(struct op *t);
524 static int dotrap(struct op *t);
525 static int getsig(char *s);
526 static void setsig(int n, sighandler_t f);
527 static int getn(char *as);
528 static int dobreak(struct op *t);
529 static int docontinue(struct op *t);
530 static int brkcontin(char *cp, int val);
531 static int doexit(struct op *t);
532 static int doexport(struct op *t);
533 static int doreadonly(struct op *t);
534 static void rdexp(char **wp, void (*f) (struct var *), int key);
535 static void badid(char *s);
536 static int doset(struct op *t);
537 static void varput(char *s, int out);
538 static int dotimes(struct op *t);
539 static int expand(char *cp, struct wdblock **wbp, int f);
540 static char *blank(int f);
541 static int dollar(int quoted);
542 static int grave(int quoted);
543 static void globname(char *we, char *pp);
544 static char *generate(char *start1, char *end1, char *middle, char *end);
545 static int anyspcl(struct wdblock *wb);
546 static int xstrcmp(char *p1, char *p2);
547 static void glob0(char *a0, unsigned int a1, int a2,
548                                   int (*a3) (char *, char *));
549 static void glob1(char *base, char *lim);
550 static void glob2(char *i, char *j);
551 static void glob3(char *i, char *j, char *k);
552 static void readhere(char **name, char *s, int ec);
553 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
554 static int xxchar(struct ioarg *ap);
555
556 struct here {
557         char *h_tag;
558         int h_dosub;
559         struct ioword *h_iop;
560         struct here *h_next;
561 };
562
563 static char *signame[] = {
564         "Signal 0",
565         "Hangup",
566         (char *) NULL,                          /* interrupt */
567         "Quit",
568         "Illegal instruction",
569         "Trace/BPT trap",
570         "Abort",
571         "Bus error",
572         "Floating Point Exception",
573         "Killed",
574         "SIGUSR1",
575         "SIGSEGV",
576         "SIGUSR2",
577         (char *) NULL,                          /* broken pipe */
578         "Alarm clock",
579         "Terminated",
580 };
581
582 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
583
584 struct res {
585         char *r_name;
586         int r_val;
587 };
588 static struct res restab[] = {
589         {"for", FOR},
590         {"case", CASE},
591         {"esac", ESAC},
592         {"while", WHILE},
593         {"do", DO},
594         {"done", DONE},
595         {"if", IF},
596         {"in", IN},
597         {"then", THEN},
598         {"else", ELSE},
599         {"elif", ELIF},
600         {"until", UNTIL},
601         {"fi", FI},
602
603         {";;", BREAK},
604         {"||", LOGOR},
605         {"&&", LOGAND},
606         {"{", '{'},
607         {"}", '}'},
608         {0, 0},
609 };
610
611
612 struct builtincmd {
613         const char *name;
614         int (*builtinfunc) (struct op * t);
615 };
616 static const struct builtincmd builtincmds[] = {
617         {".", dodot},
618         {":", dolabel},
619         {"break", dobreak},
620         {"cd", dochdir},
621         {"continue", docontinue},
622         {"eval", doeval},
623         {"exec", doexec},
624         {"exit", doexit},
625         {"export", doexport},
626         {"help", dohelp},
627         {"login", dologin},
628         {"newgrp", dologin},
629         {"read", doread},
630         {"readonly", doreadonly},
631         {"set", doset},
632         {"shift", doshift},
633         {"times", dotimes},
634         {"trap", dotrap},
635         {"umask", doumask},
636         {"wait", dowait},
637         {0, 0}
638 };
639
640 /* Globals */
641 extern char **environ;                  /* environment pointer */
642 static char **dolv;
643 static int dolc;
644 static int exstat;
645 static char gflg;
646 static int interactive;                 /* Is this an interactive shell */
647 static int execflg;
648 static int multiline;                   /* \n changed to ; */
649 static struct op *outtree;              /* result from parser */
650 static xint *failpt;
651 static xint *errpt;
652 static struct brkcon *brklist;
653 static int isbreak;
654 static struct wdblock *wdlist;
655 static struct wdblock *iolist;
656 static char *trap[_NSIG + 1];
657 static char ourtrap[_NSIG + 1];
658 static int trapset;                             /* trap pending */
659 static int yynerrs;                             /* yacc */
660 static char line[LINELIM];
661 static struct var *vlist;               /* dictionary */
662 static struct var *homedir;             /* home directory */
663 static struct var *prompt;              /* main prompt */
664 static struct var *cprompt;             /* continuation prompt */
665 static struct var *path;                /* search path for commands */
666 static struct var *shell;               /* shell to interpret command files */
667 static struct var *ifs;                 /* field separators */
668 static struct ioarg ioargstack[NPUSH];
669 static struct io iostack[NPUSH];
670 static int areanum;                             /* current allocation area */
671 static int intr;
672 static int inparse;
673 static char flags['z' - 'a' + 1];
674 static char *flag = flags - 'a';
675 static char *elinep = line + sizeof(line) - 5;
676 static char *null = "";
677 static int heedint = 1;
678 static struct env e =
679         { line, iostack, iostack - 1, (xint *) NULL, FDBASE,
680 (struct env *) NULL };
681 static void (*qflag) (int) = SIG_IGN;
682 static int startl;
683 static int peeksym;
684 static int nlseen;
685 static int iounit = IODEFAULT;
686 static YYSTYPE yylval;
687 static struct iobuf sharedbuf = { AFID_NOBUF };
688 static struct iobuf mainbuf = { AFID_NOBUF };
689 static unsigned bufid = AFID_ID;        /* buffer id counter */
690 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 };
691 static struct here *inhere;             /* list of hear docs while parsing */
692 static struct here *acthere;    /* list of active here documents */
693 static struct region *areabot;  /* bottom of area */
694 static struct region *areatop;  /* top of area */
695 static struct region *areanxt;  /* starting point of scan */
696 static void *brktop;
697 static void *brkaddr;
698
699
700 #ifdef CONFIG_FEATURE_COMMAND_EDITING
701 static char *current_prompt;
702 #endif
703
704 /* -------- sh.c -------- */
705 /*
706  * shell
707  */
708
709
710 extern int msh_main(int argc, char **argv)
711 {
712         register int f;
713         register char *s;
714         int cflag;
715         char *name, **ap;
716         int (*iof) (struct ioarg *);
717
718         initarea();
719         if ((ap = environ) != NULL) {
720                 while (*ap)
721                         assign(*ap++, !COPYV);
722                 for (ap = environ; *ap;)
723                         export(lookup(*ap++));
724         }
725         closeall();
726         areanum = 1;
727
728         shell = lookup("SHELL");
729         if (shell->value == null)
730                 setval(shell, DEFAULT_SHELL);
731         export(shell);
732
733         homedir = lookup("HOME");
734         if (homedir->value == null)
735                 setval(homedir, "/");
736         export(homedir);
737
738         setval(lookup("$"), putn(getpid()));
739
740         path = lookup("PATH");
741         if (path->value == null) {
742                 if (geteuid() == 0)
743                         setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
744                 else
745                         setval(path, "/bin:/usr/bin");
746         }
747         export(path);
748
749         ifs = lookup("IFS");
750         if (ifs->value == null)
751                 setval(ifs, " \t\n");
752
753         prompt = lookup("PS1");
754 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
755         if (prompt->value == null)
756 #endif
757                 setval(prompt, "$ ");
758         if (geteuid() == 0) {
759                 setval(prompt, "# ");
760                 prompt->status &= ~EXPORT;
761         }
762         cprompt = lookup("PS2");
763 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
764         if (cprompt->value == null)
765 #endif
766                 setval(cprompt, "> ");
767
768         iof = filechar;
769         cflag = 0;
770         name = *argv++;
771         if (--argc >= 1) {
772                 if (argv[0][0] == '-' && argv[0][1] != '\0') {
773                         for (s = argv[0] + 1; *s; s++)
774                                 switch (*s) {
775                                 case 'c':
776                                         prompt->status &= ~EXPORT;
777                                         cprompt->status &= ~EXPORT;
778                                         setval(prompt, "");
779                                         setval(cprompt, "");
780                                         cflag = 1;
781                                         if (--argc > 0)
782                                                 PUSHIO(aword, *++argv, iof = nlchar);
783                                         break;
784
785                                 case 'q':
786                                         qflag = SIG_DFL;
787                                         break;
788
789                                 case 's':
790                                         /* standard input */
791                                         break;
792
793                                 case 't':
794                                         prompt->status &= ~EXPORT;
795                                         setval(prompt, "");
796                                         iof = linechar;
797                                         break;
798
799                                 case 'i':
800                                         interactive++;
801                                 default:
802                                         if (*s >= 'a' && *s <= 'z')
803                                                 flag[(int) *s]++;
804                                 }
805                 } else {
806                         argv--;
807                         argc++;
808                 }
809                 if (iof == filechar && --argc > 0) {
810                         setval(prompt, "");
811                         setval(cprompt, "");
812                         prompt->status &= ~EXPORT;
813                         cprompt->status &= ~EXPORT;
814                         if (newfile(name = *++argv))
815                                 exit(1);
816                 }
817         }
818         setdash();
819         if (e.iop < iostack) {
820                 PUSHIO(afile, 0, iof);
821                 if (isatty(0) && isatty(1) && !cflag) {
822                         interactive++;
823 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
824                         printf("\n\n" BB_BANNER " Built-in shell (msh)\n");
825                         printf("Enter 'help' for a list of built-in commands.\n\n");
826 #endif
827                 }
828         }
829         signal(SIGQUIT, qflag);
830         if (name && name[0] == '-') {
831                 interactive++;
832                 if ((f = open(".profile", 0)) >= 0)
833                         next(remap(f));
834                 if ((f = open("/etc/profile", 0)) >= 0)
835                         next(remap(f));
836         }
837         if (interactive)
838                 signal(SIGTERM, sig);
839         if (signal(SIGINT, SIG_IGN) != SIG_IGN)
840                 signal(SIGINT, onintr);
841         dolv = argv;
842         dolc = argc;
843         dolv[0] = name;
844         if (dolc > 1) {
845                 for (ap = ++argv; --argc > 0;) {
846                         if (assign(*ap = *argv++, !COPYV)) {
847                                 dolc--;                 /* keyword */
848                         } else {
849                                 ap++;
850                         }
851                 }
852         }
853         setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
854
855         for (;;) {
856                 if (interactive && e.iop <= iostack) {
857 #ifdef CONFIG_FEATURE_COMMAND_EDITING
858                         current_prompt = prompt->value;
859 #else
860                         prs(prompt->value);
861 #endif
862                 }
863                 onecommand();
864                 /* Ensure that getenv("PATH") stays current */
865                 setenv("PATH", path->value, 1);
866         }
867 }
868
869 static void setdash()
870 {
871         register char *cp;
872         register int c;
873         char m['z' - 'a' + 1];
874
875         cp = m;
876         for (c = 'a'; c <= 'z'; c++)
877                 if (flag[(int) c])
878                         *cp++ = c;
879         *cp = 0;
880         setval(lookup("-"), m);
881 }
882
883 static int newfile(s)
884 register char *s;
885 {
886         register int f;
887
888         if (strcmp(s, "-") != 0) {
889                 f = open(s, 0);
890                 if (f < 0) {
891                         prs(s);
892                         err(": cannot open");
893                         return (1);
894                 }
895         } else
896                 f = 0;
897         next(remap(f));
898         return (0);
899 }
900
901 static void onecommand()
902 {
903         register int i;
904         jmp_buf m1;
905
906         while (e.oenv)
907                 quitenv();
908         areanum = 1;
909         freehere(areanum);
910         freearea(areanum);
911         garbage();
912         wdlist = 0;
913         iolist = 0;
914         e.errpt = 0;
915         e.linep = line;
916         yynerrs = 0;
917         multiline = 0;
918         inparse = 1;
919         intr = 0;
920         execflg = 0;
921         setjmp(failpt = m1);            /* Bruce Evans' fix */
922         if (setjmp(failpt = m1) || yyparse() || intr) {
923                 while (e.oenv)
924                         quitenv();
925                 scraphere();
926                 if (!interactive && intr)
927                         leave();
928                 inparse = 0;
929                 intr = 0;
930                 return;
931         }
932         inparse = 0;
933         brklist = 0;
934         intr = 0;
935         execflg = 0;
936         if (!flag['n'])
937                 execute(outtree, NOPIPE, NOPIPE, 0);
938         if (!interactive && intr) {
939                 execflg = 0;
940                 leave();
941         }
942         if ((i = trapset) != 0) {
943                 trapset = 0;
944                 runtrap(i);
945         }
946 }
947
948 static void fail()
949 {
950         longjmp(failpt, 1);
951         /* NOTREACHED */
952 }
953
954 static void leave()
955 {
956         if (execflg)
957                 fail();
958         scraphere();
959         freehere(1);
960         runtrap(0);
961         exit(exstat);
962         /* NOTREACHED */
963 }
964
965 static void warn(s)
966 register char *s;
967 {
968         if (*s) {
969                 prs(s);
970                 exstat = -1;
971         }
972         prs("\n");
973         if (flag['e'])
974                 leave();
975 }
976
977 static void err(s)
978 char *s;
979 {
980         warn(s);
981         if (flag['n'])
982                 return;
983         if (!interactive)
984                 leave();
985         if (e.errpt)
986                 longjmp(e.errpt, 1);
987         closeall();
988         e.iop = e.iobase = iostack;
989 }
990
991 static int newenv(f)
992 int f;
993 {
994         register struct env *ep;
995
996         if (f) {
997                 quitenv();
998                 return (1);
999         }
1000         ep = (struct env *) space(sizeof(*ep));
1001         if (ep == NULL) {
1002                 while (e.oenv)
1003                         quitenv();
1004                 fail();
1005         }
1006         *ep = e;
1007         e.oenv = ep;
1008         e.errpt = errpt;
1009         return (0);
1010 }
1011
1012 static void quitenv()
1013 {
1014         register struct env *ep;
1015         register int fd;
1016
1017         if ((ep = e.oenv) != NULL) {
1018                 fd = e.iofd;
1019                 e = *ep;
1020                 /* should close `'d files */
1021                 DELETE(ep);
1022                 while (--fd >= e.iofd)
1023                         close(fd);
1024         }
1025 }
1026
1027 /*
1028  * Is any character from s1 in s2?
1029  */
1030 static int anys(s1, s2)
1031 register char *s1, *s2;
1032 {
1033         while (*s1)
1034                 if (any(*s1++, s2))
1035                         return (1);
1036         return (0);
1037 }
1038
1039 /*
1040  * Is character c in s?
1041  */
1042 static int any(c, s)
1043 register int c;
1044 register char *s;
1045 {
1046         while (*s)
1047                 if (*s++ == c)
1048                         return (1);
1049         return (0);
1050 }
1051
1052 static char *putn(n)
1053 register int n;
1054 {
1055         return (itoa(n));
1056 }
1057
1058 static char *itoa(n)
1059 register int n;
1060 {
1061         static char s[20];
1062
1063         snprintf(s, sizeof(s), "%u", n);
1064         return (s);
1065 }
1066
1067 static void next(int f)
1068 {
1069         PUSHIO(afile, f, filechar);
1070 }
1071
1072 static void onintr(s)
1073 int s;                                                  /* ANSI C requires a parameter */
1074 {
1075         signal(SIGINT, onintr);
1076         intr = 1;
1077         if (interactive) {
1078                 if (inparse) {
1079                         prs("\n");
1080                         fail();
1081                 }
1082         } else if (heedint) {
1083                 execflg = 0;
1084                 leave();
1085         }
1086 }
1087
1088 static char *space(n)
1089 int n;
1090 {
1091         register char *cp;
1092
1093         if ((cp = getcell(n)) == 0)
1094                 err("out of string space");
1095         return (cp);
1096 }
1097
1098 static char *strsave(s, a)
1099 register char *s;
1100 int a;
1101 {
1102         register char *cp, *xp;
1103
1104         if ((cp = space(strlen(s) + 1)) != NULL) {
1105                 setarea((char *) cp, a);
1106                 for (xp = cp; (*xp++ = *s++) != '\0';);
1107                 return (cp);
1108         }
1109         return ("");
1110 }
1111
1112 /*
1113  * trap handling
1114  */
1115 static void sig(i)
1116 register int i;
1117 {
1118         trapset = i;
1119         signal(i, sig);
1120 }
1121
1122 static void runtrap(i)
1123 int i;
1124 {
1125         char *trapstr;
1126
1127         if ((trapstr = trap[i]) == NULL)
1128                 return;
1129         if (i == 0)
1130                 trap[i] = 0;
1131         RUN(aword, trapstr, nlchar);
1132 }
1133
1134 /* -------- var.c -------- */
1135
1136 /*
1137  * Find the given name in the dictionary
1138  * and return its value.  If the name was
1139  * not previously there, enter it now and
1140  * return a null value.
1141  */
1142 static struct var *lookup(n)
1143 register char *n;
1144 {
1145         register struct var *vp;
1146         register char *cp;
1147         register int c;
1148         static struct var dummy;
1149
1150         if (isdigit(*n)) {
1151                 dummy.name = n;
1152                 for (c = 0; isdigit(*n) && c < 1000; n++)
1153                         c = c * 10 + *n - '0';
1154                 dummy.status = RONLY;
1155                 dummy.value = c <= dolc ? dolv[c] : null;
1156                 return (&dummy);
1157         }
1158         for (vp = vlist; vp; vp = vp->next)
1159                 if (eqname(vp->name, n))
1160                         return (vp);
1161         cp = findeq(n);
1162         vp = (struct var *) space(sizeof(*vp));
1163         if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1164                 dummy.name = dummy.value = "";
1165                 return (&dummy);
1166         }
1167         for (cp = vp->name; (*cp = *n++) && *cp != '='; cp++);
1168         if (*cp == 0)
1169                 *cp = '=';
1170         *++cp = 0;
1171         setarea((char *) vp, 0);
1172         setarea((char *) vp->name, 0);
1173         vp->value = null;
1174         vp->next = vlist;
1175         vp->status = GETCELL;
1176         vlist = vp;
1177         return (vp);
1178 }
1179
1180 /*
1181  * give variable at `vp' the value `val'.
1182  */
1183 static void setval(vp, val)
1184 struct var *vp;
1185 char *val;
1186 {
1187         nameval(vp, val, (char *) NULL);
1188 }
1189
1190 /*
1191  * if name is not NULL, it must be
1192  * a prefix of the space `val',
1193  * and end with `='.
1194  * this is all so that exporting
1195  * values is reasonably painless.
1196  */
1197 static void nameval(vp, val, name)
1198 register struct var *vp;
1199 char *val, *name;
1200 {
1201         register char *cp, *xp;
1202         char *nv;
1203         int fl;
1204
1205         if (vp->status & RONLY) {
1206                 for (xp = vp->name; *xp && *xp != '=';)
1207                         putc(*xp++, stderr);
1208                 err(" is read-only");
1209                 return;
1210         }
1211         fl = 0;
1212         if (name == NULL) {
1213                 xp = space(strlen(vp->name) + strlen(val) + 2);
1214                 if (xp == 0)
1215                         return;
1216                 /* make string:  name=value */
1217                 setarea((char *) xp, 0);
1218                 name = xp;
1219                 for (cp = vp->name; (*xp = *cp++) && *xp != '='; xp++);
1220                 if (*xp++ == 0)
1221                         xp[-1] = '=';
1222                 nv = xp;
1223                 for (cp = val; (*xp++ = *cp++) != '\0';);
1224                 val = nv;
1225                 fl = GETCELL;
1226         }
1227         if (vp->status & GETCELL)
1228                 freecell(vp->name);             /* form new string `name=value' */
1229         vp->name = name;
1230         vp->value = val;
1231         vp->status |= fl;
1232 }
1233
1234 static void export(vp)
1235 struct var *vp;
1236 {
1237         vp->status |= EXPORT;
1238 }
1239
1240 static void ronly(vp)
1241 struct var *vp;
1242 {
1243         if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1244                 vp->status |= RONLY;
1245 }
1246
1247 static int isassign(s)
1248 register char *s;
1249 {
1250         if (!isalpha((int) *s) && *s != '_')
1251                 return (0);
1252         for (; *s != '='; s++)
1253                 if (*s == 0 || (!isalnum(*s) && *s != '_'))
1254                         return (0);
1255         return (1);
1256 }
1257
1258 static int assign(s, cf)
1259 register char *s;
1260 int cf;
1261 {
1262         register char *cp;
1263         struct var *vp;
1264
1265         if (!isalpha(*s) && *s != '_')
1266                 return (0);
1267         for (cp = s; *cp != '='; cp++)
1268                 if (*cp == 0 || (!isalnum(*cp) && *cp != '_'))
1269                         return (0);
1270         vp = lookup(s);
1271         nameval(vp, ++cp, cf == COPYV ? (char *) NULL : s);
1272         if (cf != COPYV)
1273                 vp->status &= ~GETCELL;
1274         return (1);
1275 }
1276
1277 static int checkname(cp)
1278 register char *cp;
1279 {
1280         if (!isalpha(*cp++) && *(cp - 1) != '_')
1281                 return (0);
1282         while (*cp)
1283                 if (!isalnum(*cp++) && *(cp - 1) != '_')
1284                         return (0);
1285         return (1);
1286 }
1287
1288 static void putvlist(f, out)
1289 register int f, out;
1290 {
1291         register struct var *vp;
1292
1293         for (vp = vlist; vp; vp = vp->next)
1294                 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1295                         if (vp->status & EXPORT)
1296                                 write(out, "export ", 7);
1297                         if (vp->status & RONLY)
1298                                 write(out, "readonly ", 9);
1299                         write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1300                         write(out, "\n", 1);
1301                 }
1302 }
1303
1304 static int eqname(n1, n2)
1305 register char *n1, *n2;
1306 {
1307         for (; *n1 != '=' && *n1 != 0; n1++)
1308                 if (*n2++ != *n1)
1309                         return (0);
1310         return (*n2 == 0 || *n2 == '=');
1311 }
1312
1313 static char *findeq(cp)
1314 register char *cp;
1315 {
1316         while (*cp != '\0' && *cp != '=')
1317                 cp++;
1318         return (cp);
1319 }
1320
1321 /* -------- gmatch.c -------- */
1322 /*
1323  * int gmatch(string, pattern)
1324  * char *string, *pattern;
1325  *
1326  * Match a pattern as in sh(1).
1327  */
1328
1329 #define CMASK   0377
1330 #define QUOTE   0200
1331 #define QMASK   (CMASK&~QUOTE)
1332 #define NOT     '!'                                     /* might use ^ */
1333
1334 static int gmatch(s, p)
1335 register char *s, *p;
1336 {
1337         register int sc, pc;
1338
1339         if (s == NULL || p == NULL)
1340                 return (0);
1341         while ((pc = *p++ & CMASK) != '\0') {
1342                 sc = *s++ & QMASK;
1343                 switch (pc) {
1344                 case '[':
1345                         if ((p = cclass(p, sc)) == NULL)
1346                                 return (0);
1347                         break;
1348
1349                 case '?':
1350                         if (sc == 0)
1351                                 return (0);
1352                         break;
1353
1354                 case '*':
1355                         s--;
1356                         do {
1357                                 if (*p == '\0' || gmatch(s, p))
1358                                         return (1);
1359                         } while (*s++ != '\0');
1360                         return (0);
1361
1362                 default:
1363                         if (sc != (pc & ~QUOTE))
1364                                 return (0);
1365                 }
1366         }
1367         return (*s == 0);
1368 }
1369
1370 static char *cclass(p, sub)
1371 register char *p;
1372 register int sub;
1373 {
1374         register int c, d, not, found;
1375
1376         if ((not = *p == NOT) != 0)
1377                 p++;
1378         found = not;
1379         do {
1380                 if (*p == '\0')
1381                         return ((char *) NULL);
1382                 c = *p & CMASK;
1383                 if (p[1] == '-' && p[2] != ']') {
1384                         d = p[2] & CMASK;
1385                         p++;
1386                 } else
1387                         d = c;
1388                 if (c == sub || (c <= sub && sub <= d))
1389                         found = !not;
1390         } while (*++p != ']');
1391         return (found ? p + 1 : (char *) NULL);
1392 }
1393
1394
1395 /* -------- area.c -------- */
1396
1397 /*
1398  * All memory between (char *)areabot and (char *)(areatop+1) is
1399  * exclusively administered by the area management routines.
1400  * It is assumed that sbrk() and brk() manipulate the high end.
1401  */
1402
1403 #define sbrk(X) ({ void * __q = (void *)-1; if (brkaddr + (int)(X) < brktop) { __q = brkaddr; brkaddr+=(int)(X); } __q;})
1404
1405 static void initarea()
1406 {
1407         brkaddr = malloc(65000);
1408         brktop = brkaddr + 65000;
1409
1410         while ((int) sbrk(0) & ALIGN)
1411                 sbrk(1);
1412         areabot = (struct region *) sbrk(REGSIZE);
1413
1414         areabot->next = areabot;
1415         areabot->area = BUSY;
1416         areatop = areabot;
1417         areanxt = areabot;
1418 }
1419
1420 char *getcell(nbytes)
1421 unsigned nbytes;
1422 {
1423         register int nregio;
1424         register struct region *p, *q;
1425         register int i;
1426
1427         if (nbytes == 0) {
1428                 puts("getcell(0)");
1429                 abort();
1430         }
1431         /* silly and defeats the algorithm */
1432         /*
1433          * round upwards and add administration area
1434          */
1435         nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
1436         for (p = areanxt;;) {
1437                 if (p->area > areanum) {
1438                         /*
1439                          * merge free cells
1440                          */
1441                         while ((q = p->next)->area > areanum && q != areanxt)
1442                                 p->next = q->next;
1443                         /*
1444                          * exit loop if cell big enough
1445                          */
1446                         if (q >= p + nregio)
1447                                 goto found;
1448                 }
1449                 p = p->next;
1450                 if (p == areanxt)
1451                         break;
1452         }
1453         i = nregio >= GROWBY ? nregio : GROWBY;
1454         p = (struct region *) sbrk(i * REGSIZE);
1455         if (p == (struct region *) -1)
1456                 return ((char *) NULL);
1457         p--;
1458         if (p != areatop) {
1459                 puts("not contig");
1460                 abort();                                /* allocated areas are contiguous */
1461         }
1462         q = p + i;
1463         p->next = q;
1464         p->area = FREE;
1465         q->next = areabot;
1466         q->area = BUSY;
1467         areatop = q;
1468   found:
1469         /*
1470          * we found a FREE area big enough, pointed to by 'p', and up to 'q'
1471          */
1472         areanxt = p + nregio;
1473         if (areanxt < q) {
1474                 /*
1475                  * split into requested area and rest
1476                  */
1477                 if (areanxt + 1 > q) {
1478                         puts("OOM");
1479                         abort();                        /* insufficient space left for admin */
1480                 }
1481                 areanxt->next = q;
1482                 areanxt->area = FREE;
1483                 p->next = areanxt;
1484         }
1485         p->area = areanum;
1486         return ((char *) (p + 1));
1487 }
1488
1489 static void freecell(cp)
1490 char *cp;
1491 {
1492         register struct region *p;
1493
1494         if ((p = (struct region *) cp) != NULL) {
1495                 p--;
1496                 if (p < areanxt)
1497                         areanxt = p;
1498                 p->area = FREE;
1499         }
1500 }
1501
1502 static void freearea(a)
1503 register int a;
1504 {
1505         register struct region *p, *top;
1506
1507         top = areatop;
1508         for (p = areabot; p != top; p = p->next)
1509                 if (p->area >= a)
1510                         p->area = FREE;
1511 }
1512
1513 static void setarea(cp, a)
1514 char *cp;
1515 int a;
1516 {
1517         register struct region *p;
1518
1519         if ((p = (struct region *) cp) != NULL)
1520                 (p - 1)->area = a;
1521 }
1522
1523 int getarea(cp)
1524 char *cp;
1525 {
1526         return ((struct region *) cp - 1)->area;
1527 }
1528
1529 static void garbage()
1530 {
1531         register struct region *p, *q, *top;
1532
1533         top = areatop;
1534         for (p = areabot; p != top; p = p->next) {
1535                 if (p->area > areanum) {
1536                         while ((q = p->next)->area > areanum)
1537                                 p->next = q->next;
1538                         areanxt = p;
1539                 }
1540         }
1541 #ifdef SHRINKBY
1542         if (areatop >= q + SHRINKBY && q->area > areanum) {
1543                 brk((char *) (q + 1));
1544                 q->next = areabot;
1545                 q->area = BUSY;
1546                 areatop = q;
1547         }
1548 #endif
1549 }
1550
1551 /* -------- csyn.c -------- */
1552 /*
1553  * shell: syntax (C version)
1554  */
1555
1556
1557 int yyparse()
1558 {
1559         startl = 1;
1560         peeksym = 0;
1561         yynerrs = 0;
1562         outtree = c_list();
1563         musthave('\n', 0);
1564         return (yynerrs != 0);
1565 }
1566
1567 static struct op *pipeline(cf)
1568 int cf;
1569 {
1570         register struct op *t, *p;
1571         register int c;
1572
1573         t = command(cf);
1574         if (t != NULL) {
1575                 while ((c = yylex(0)) == '|') {
1576                         if ((p = command(CONTIN)) == NULL)
1577                                 SYNTAXERR;
1578                         if (t->type != TPAREN && t->type != TCOM) {
1579                                 /* shell statement */
1580                                 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1581                         }
1582                         t = block(TPIPE, t, p, NOWORDS);
1583                 }
1584                 peeksym = c;
1585         }
1586         return (t);
1587 }
1588
1589 static struct op *andor()
1590 {
1591         register struct op *t, *p;
1592         register int c;
1593
1594         t = pipeline(0);
1595         if (t != NULL) {
1596                 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1597                         if ((p = pipeline(CONTIN)) == NULL)
1598                                 SYNTAXERR;
1599                         t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1600                 }
1601                 peeksym = c;
1602         }
1603         return (t);
1604 }
1605
1606 static struct op *c_list()
1607 {
1608         register struct op *t, *p;
1609         register int c;
1610
1611         t = andor();
1612         if (t != NULL) {
1613                 if ((peeksym = yylex(0)) == '&')
1614                         t = block(TASYNC, t, NOBLOCK, NOWORDS);
1615                 while ((c = yylex(0)) == ';' || c == '&'
1616                            || (multiline && c == '\n')) {
1617                         if ((p = andor()) == NULL)
1618                                 return (t);
1619                         if ((peeksym = yylex(0)) == '&')
1620                                 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1621                         t = list(t, p);
1622                 }
1623                 peeksym = c;
1624         }
1625         return (t);
1626 }
1627
1628
1629 static int synio(cf)
1630 int cf;
1631 {
1632         register struct ioword *iop;
1633         register int i;
1634         register int c;
1635
1636         if ((c = yylex(cf)) != '<' && c != '>') {
1637                 peeksym = c;
1638                 return (0);
1639         }
1640         i = yylval.i;
1641         musthave(WORD, 0);
1642         iop = io(iounit, i, yylval.cp);
1643         iounit = IODEFAULT;
1644         if (i & IOHERE)
1645                 markhere(yylval.cp, iop);
1646         return (1);
1647 }
1648
1649 static void musthave(c, cf)
1650 int c, cf;
1651 {
1652         if ((peeksym = yylex(cf)) != c)
1653                 SYNTAXERR;
1654         peeksym = 0;
1655 }
1656
1657 static struct op *simple()
1658 {
1659         register struct op *t;
1660
1661         t = NULL;
1662         for (;;) {
1663                 switch (peeksym = yylex(0)) {
1664                 case '<':
1665                 case '>':
1666                         (void) synio(0);
1667                         break;
1668
1669                 case WORD:
1670                         if (t == NULL) {
1671                                 t = newtp();
1672                                 t->type = TCOM;
1673                         }
1674                         peeksym = 0;
1675                         word(yylval.cp);
1676                         break;
1677
1678                 default:
1679                         return (t);
1680                 }
1681         }
1682 }
1683
1684 static struct op *nested(type, mark)
1685 int type, mark;
1686 {
1687         register struct op *t;
1688
1689         multiline++;
1690         t = c_list();
1691         musthave(mark, 0);
1692         multiline--;
1693         return (block(type, t, NOBLOCK, NOWORDS));
1694 }
1695
1696 static struct op *command(cf)
1697 int cf;
1698 {
1699         register struct op *t;
1700         struct wdblock *iosave;
1701         register int c;
1702
1703         iosave = iolist;
1704         iolist = NULL;
1705         if (multiline)
1706                 cf |= CONTIN;
1707         while (synio(cf))
1708                 cf = 0;
1709         switch (c = yylex(cf)) {
1710         default:
1711                 peeksym = c;
1712                 if ((t = simple()) == NULL) {
1713                         if (iolist == NULL)
1714                                 return ((struct op *) NULL);
1715                         t = newtp();
1716                         t->type = TCOM;
1717                 }
1718                 break;
1719
1720         case '(':
1721                 t = nested(TPAREN, ')');
1722                 break;
1723
1724         case '{':
1725                 t = nested(TBRACE, '}');
1726                 break;
1727
1728         case FOR:
1729                 t = newtp();
1730                 t->type = TFOR;
1731                 musthave(WORD, 0);
1732                 startl = 1;
1733                 t->str = yylval.cp;
1734                 multiline++;
1735                 t->words = wordlist();
1736                 if ((c = yylex(0)) != '\n' && c != ';')
1737                         peeksym = c;
1738                 t->left = dogroup(0);
1739                 multiline--;
1740                 break;
1741
1742         case WHILE:
1743         case UNTIL:
1744                 multiline++;
1745                 t = newtp();
1746                 t->type = c == WHILE ? TWHILE : TUNTIL;
1747                 t->left = c_list();
1748                 t->right = dogroup(1);
1749                 t->words = NULL;
1750                 multiline--;
1751                 break;
1752
1753         case CASE:
1754                 t = newtp();
1755                 t->type = TCASE;
1756                 musthave(WORD, 0);
1757                 t->str = yylval.cp;
1758                 startl++;
1759                 multiline++;
1760                 musthave(IN, CONTIN);
1761                 startl++;
1762                 t->left = caselist();
1763                 musthave(ESAC, 0);
1764                 multiline--;
1765                 break;
1766
1767         case IF:
1768                 multiline++;
1769                 t = newtp();
1770                 t->type = TIF;
1771                 t->left = c_list();
1772                 t->right = thenpart();
1773                 musthave(FI, 0);
1774                 multiline--;
1775                 break;
1776         }
1777         while (synio(0));
1778         t = namelist(t);
1779         iolist = iosave;
1780         return (t);
1781 }
1782
1783 static struct op *dogroup(onlydone)
1784 int onlydone;
1785 {
1786         register int c;
1787         register struct op *mylist;
1788
1789         c = yylex(CONTIN);
1790         if (c == DONE && onlydone)
1791                 return ((struct op *) NULL);
1792         if (c != DO)
1793                 SYNTAXERR;
1794         mylist = c_list();
1795         musthave(DONE, 0);
1796         return (mylist);
1797 }
1798
1799 static struct op *thenpart()
1800 {
1801         register int c;
1802         register struct op *t;
1803
1804         if ((c = yylex(0)) != THEN) {
1805                 peeksym = c;
1806                 return ((struct op *) NULL);
1807         }
1808         t = newtp();
1809         t->type = 0;
1810         t->left = c_list();
1811         if (t->left == NULL)
1812                 SYNTAXERR;
1813         t->right = elsepart();
1814         return (t);
1815 }
1816
1817 static struct op *elsepart()
1818 {
1819         register int c;
1820         register struct op *t;
1821
1822         switch (c = yylex(0)) {
1823         case ELSE:
1824                 if ((t = c_list()) == NULL)
1825                         SYNTAXERR;
1826                 return (t);
1827
1828         case ELIF:
1829                 t = newtp();
1830                 t->type = TELIF;
1831                 t->left = c_list();
1832                 t->right = thenpart();
1833                 return (t);
1834
1835         default:
1836                 peeksym = c;
1837                 return ((struct op *) NULL);
1838         }
1839 }
1840
1841 static struct op *caselist()
1842 {
1843         register struct op *t;
1844
1845         t = NULL;
1846         while ((peeksym = yylex(CONTIN)) != ESAC)
1847                 t = list(t, casepart());
1848         return (t);
1849 }
1850
1851 static struct op *casepart()
1852 {
1853         register struct op *t;
1854
1855         t = newtp();
1856         t->type = TPAT;
1857         t->words = pattern();
1858         musthave(')', 0);
1859         t->left = c_list();
1860         if ((peeksym = yylex(CONTIN)) != ESAC)
1861                 musthave(BREAK, CONTIN);
1862         return (t);
1863 }
1864
1865 static char **pattern()
1866 {
1867         register int c, cf;
1868
1869         cf = CONTIN;
1870         do {
1871                 musthave(WORD, cf);
1872                 word(yylval.cp);
1873                 cf = 0;
1874         } while ((c = yylex(0)) == '|');
1875         peeksym = c;
1876         word(NOWORD);
1877         return (copyw());
1878 }
1879
1880 static char **wordlist()
1881 {
1882         register int c;
1883
1884         if ((c = yylex(0)) != IN) {
1885                 peeksym = c;
1886                 return ((char **) NULL);
1887         }
1888         startl = 0;
1889         while ((c = yylex(0)) == WORD)
1890                 word(yylval.cp);
1891         word(NOWORD);
1892         peeksym = c;
1893         return (copyw());
1894 }
1895
1896 /*
1897  * supporting functions
1898  */
1899 static struct op *list(t1, t2)
1900 register struct op *t1, *t2;
1901 {
1902         if (t1 == NULL)
1903                 return (t2);
1904         if (t2 == NULL)
1905                 return (t1);
1906         return (block(TLIST, t1, t2, NOWORDS));
1907 }
1908
1909 static struct op *block(type, t1, t2, wp)
1910 int type;
1911 struct op *t1, *t2;
1912 char **wp;
1913 {
1914         register struct op *t;
1915
1916         t = newtp();
1917         t->type = type;
1918         t->left = t1;
1919         t->right = t2;
1920         t->words = wp;
1921         return (t);
1922 }
1923
1924 static int rlookup(n)
1925 register char *n;
1926 {
1927         register struct res *rp;
1928
1929         for (rp = restab; rp->r_name; rp++)
1930                 if (strcmp(rp->r_name, n) == 0)
1931                         return (rp->r_val);
1932         return (0);
1933 }
1934
1935 static struct op *newtp()
1936 {
1937         register struct op *t;
1938
1939         t = (struct op *) tree(sizeof(*t));
1940         t->type = 0;
1941         t->words = NULL;
1942         t->ioact = NULL;
1943         t->left = NULL;
1944         t->right = NULL;
1945         t->str = NULL;
1946         return (t);
1947 }
1948
1949 static struct op *namelist(t)
1950 register struct op *t;
1951 {
1952         if (iolist) {
1953                 iolist = addword((char *) NULL, iolist);
1954                 t->ioact = copyio();
1955         } else
1956                 t->ioact = NULL;
1957         if (t->type != TCOM) {
1958                 if (t->type != TPAREN && t->ioact != NULL) {
1959                         t = block(TPAREN, t, NOBLOCK, NOWORDS);
1960                         t->ioact = t->left->ioact;
1961                         t->left->ioact = NULL;
1962                 }
1963                 return (t);
1964         }
1965         word(NOWORD);
1966         t->words = copyw();
1967         return (t);
1968 }
1969
1970 static char **copyw()
1971 {
1972         register char **wd;
1973
1974         wd = getwords(wdlist);
1975         wdlist = 0;
1976         return (wd);
1977 }
1978
1979 static void word(cp)
1980 char *cp;
1981 {
1982         wdlist = addword(cp, wdlist);
1983 }
1984
1985 static struct ioword **copyio()
1986 {
1987         register struct ioword **iop;
1988
1989         iop = (struct ioword **) getwords(iolist);
1990         iolist = 0;
1991         return (iop);
1992 }
1993
1994 static struct ioword *io(u, f, cp)
1995 int u;
1996 int f;
1997 char *cp;
1998 {
1999         register struct ioword *iop;
2000
2001         iop = (struct ioword *) tree(sizeof(*iop));
2002         iop->io_unit = u;
2003         iop->io_flag = f;
2004         iop->io_name = cp;
2005         iolist = addword((char *) iop, iolist);
2006         return (iop);
2007 }
2008
2009 static void zzerr()
2010 {
2011         yyerror("syntax error");
2012 }
2013
2014 static void yyerror(s)
2015 char *s;
2016 {
2017         yynerrs++;
2018         if (interactive && e.iop <= iostack) {
2019                 multiline = 0;
2020                 while (eofc() == 0 && yylex(0) != '\n');
2021         }
2022         err(s);
2023         fail();
2024 }
2025
2026 static int yylex(cf)
2027 int cf;
2028 {
2029         register int c, c1;
2030         int atstart;
2031
2032         if ((c = peeksym) > 0) {
2033                 peeksym = 0;
2034                 if (c == '\n')
2035                         startl = 1;
2036                 return (c);
2037         }
2038         nlseen = 0;
2039         e.linep = line;
2040         atstart = startl;
2041         startl = 0;
2042         yylval.i = 0;
2043
2044   loop:
2045         while ((c = my_getc(0)) == ' ' || c == '\t');
2046         switch (c) {
2047         default:
2048                 if (any(c, "0123456789")) {
2049                         unget(c1 = my_getc(0));
2050                         if (c1 == '<' || c1 == '>') {
2051                                 iounit = c - '0';
2052                                 goto loop;
2053                         }
2054                         *e.linep++ = c;
2055                         c = c1;
2056                 }
2057                 break;
2058
2059         case '#':
2060                 while ((c = my_getc(0)) != 0 && c != '\n');
2061                 unget(c);
2062                 goto loop;
2063
2064         case 0:
2065                 return (c);
2066
2067         case '$':
2068                 *e.linep++ = c;
2069                 if ((c = my_getc(0)) == '{') {
2070                         if ((c = collect(c, '}')) != '\0')
2071                                 return (c);
2072                         goto pack;
2073                 }
2074                 break;
2075
2076         case '`':
2077         case '\'':
2078         case '"':
2079                 if ((c = collect(c, c)) != '\0')
2080                         return (c);
2081                 goto pack;
2082
2083         case '|':
2084         case '&':
2085         case ';':
2086                 if ((c1 = dual(c)) != '\0') {
2087                         startl = 1;
2088                         return (c1);
2089                 }
2090                 startl = 1;
2091                 return (c);
2092         case '^':
2093                 startl = 1;
2094                 return ('|');
2095         case '>':
2096         case '<':
2097                 diag(c);
2098                 return (c);
2099
2100         case '\n':
2101                 nlseen++;
2102                 gethere();
2103                 startl = 1;
2104                 if (multiline || cf & CONTIN) {
2105                         if (interactive && e.iop <= iostack) {
2106 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2107                                 current_prompt = cprompt->value;
2108 #else
2109                                 prs(cprompt->value);
2110 #endif
2111                         }
2112                         if (cf & CONTIN)
2113                                 goto loop;
2114                 }
2115                 return (c);
2116
2117         case '(':
2118         case ')':
2119                 startl = 1;
2120                 return (c);
2121         }
2122
2123         unget(c);
2124
2125   pack:
2126         while ((c = my_getc(0)) != 0 && !any(c, "`$ '\"\t;&<>()|^\n"))
2127                 if (e.linep >= elinep)
2128                         err("word too long");
2129                 else
2130                         *e.linep++ = c;
2131         unget(c);
2132         if (any(c, "\"'`$"))
2133                 goto loop;
2134         *e.linep++ = '\0';
2135         if (atstart && (c = rlookup(line)) != 0) {
2136                 startl = 1;
2137                 return (c);
2138         }
2139         yylval.cp = strsave(line, areanum);
2140         return (WORD);
2141 }
2142
2143 static int collect(c, c1)
2144 register int c, c1;
2145 {
2146         char s[2];
2147
2148         *e.linep++ = c;
2149         while ((c = my_getc(c1)) != c1) {
2150                 if (c == 0) {
2151                         unget(c);
2152                         s[0] = c1;
2153                         s[1] = 0;
2154                         prs("no closing ");
2155                         yyerror(s);
2156                         return (YYERRCODE);
2157                 }
2158                 if (interactive && c == '\n' && e.iop <= iostack) {
2159 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2160                         current_prompt = cprompt->value;
2161 #else
2162                         prs(cprompt->value);
2163 #endif
2164                 }
2165                 *e.linep++ = c;
2166         }
2167         *e.linep++ = c;
2168         return (0);
2169 }
2170
2171 static int dual(c)
2172 register int c;
2173 {
2174         char s[3];
2175         register char *cp = s;
2176
2177         *cp++ = c;
2178         *cp++ = my_getc(0);
2179         *cp = 0;
2180         if ((c = rlookup(s)) == 0)
2181                 unget(*--cp);
2182         return (c);
2183 }
2184
2185 static void diag(ec)
2186 register int ec;
2187 {
2188         register int c;
2189
2190         c = my_getc(0);
2191         if (c == '>' || c == '<') {
2192                 if (c != ec)
2193                         zzerr();
2194                 yylval.i = ec == '>' ? IOWRITE | IOCAT : IOHERE;
2195                 c = my_getc(0);
2196         } else
2197                 yylval.i = ec == '>' ? IOWRITE : IOREAD;
2198         if (c != '&' || yylval.i == IOHERE)
2199                 unget(c);
2200         else
2201                 yylval.i |= IODUP;
2202 }
2203
2204 static char *tree(size)
2205 unsigned size;
2206 {
2207         register char *t;
2208
2209         if ((t = getcell(size)) == NULL) {
2210                 prs("command line too complicated\n");
2211                 fail();
2212                 /* NOTREACHED */
2213         }
2214         return (t);
2215 }
2216
2217 /* VARARGS1 */
2218 /* ARGSUSED */
2219
2220 /* -------- exec.c -------- */
2221
2222 /*
2223  * execute tree
2224  */
2225
2226
2227 static int execute(t, pin, pout, act)
2228 register struct op *t;
2229 int *pin, *pout;
2230 int act;
2231 {
2232         register struct op *t1;
2233         volatile int i, rv, a;
2234         char *cp, **wp, **wp2;
2235         struct var *vp;
2236         struct brkcon bc;
2237
2238 #if __GNUC__
2239         /* Avoid longjmp clobbering */
2240         (void) &wp;
2241 #endif
2242
2243
2244         if (t == NULL)
2245                 return (0);
2246         rv = 0;
2247         a = areanum++;
2248         wp = (wp2 = t->words) != NULL
2249                 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2250                 : NULL;
2251
2252         switch (t->type) {
2253         case TPAREN:
2254                 rv = execute(t->left, pin, pout, 0);
2255                 break;
2256
2257         case TCOM:
2258                 {
2259                         int child;
2260
2261                         rv = forkexec(t, pin, pout, act, wp, &child);
2262                         if (child) {
2263                                 exstat = rv;
2264                                 leave();
2265                         }
2266                 }
2267                 break;
2268
2269         case TPIPE:
2270                 {
2271                         int pv[2];
2272
2273                         if ((rv = openpipe(pv)) < 0)
2274                                 break;
2275                         pv[0] = remap(pv[0]);
2276                         pv[1] = remap(pv[1]);
2277                         (void) execute(t->left, pin, pv, 0);
2278                         rv = execute(t->right, pv, pout, 0);
2279                 }
2280                 break;
2281
2282         case TLIST:
2283                 (void) execute(t->left, pin, pout, 0);
2284                 rv = execute(t->right, pin, pout, 0);
2285                 break;
2286
2287         case TASYNC:
2288                 {
2289                         int hinteractive = interactive;
2290
2291                         i = vfork();
2292                         if (i != 0) {
2293                                 interactive = hinteractive;
2294                                 if (i != -1) {
2295                                         setval(lookup("!"), putn(i));
2296                                         if (pin != NULL)
2297                                                 closepipe(pin);
2298                                         if (interactive) {
2299                                                 prs(putn(i));
2300                                                 prs("\n");
2301                                         }
2302                                 } else
2303                                         rv = -1;
2304                                 setstatus(rv);
2305                         } else {
2306                                 signal(SIGINT, SIG_IGN);
2307                                 signal(SIGQUIT, SIG_IGN);
2308                                 if (interactive)
2309                                         signal(SIGTERM, SIG_DFL);
2310                                 interactive = 0;
2311                                 if (pin == NULL) {
2312                                         close(0);
2313                                         open("/dev/null", 0);
2314                                 }
2315                                 exit(execute(t->left, pin, pout, FEXEC));
2316                         }
2317                 }
2318                 break;
2319
2320         case TOR:
2321         case TAND:
2322                 rv = execute(t->left, pin, pout, 0);
2323                 if ((t1 = t->right) != NULL && (rv == 0) == (t->type == TAND))
2324                         rv = execute(t1, pin, pout, 0);
2325                 break;
2326
2327         case TFOR:
2328                 if (wp == NULL) {
2329                         wp = dolv + 1;
2330                         if ((i = dolc) < 0)
2331                                 i = 0;
2332                 } else {
2333                         i = -1;
2334                         while (*wp++ != NULL);
2335                 }
2336                 vp = lookup(t->str);
2337                 while (setjmp(bc.brkpt))
2338                         if (isbreak)
2339                                 goto broken;
2340                 brkset(&bc);
2341                 for (t1 = t->left; i-- && *wp != NULL;) {
2342                         setval(vp, *wp++);
2343                         rv = execute(t1, pin, pout, 0);
2344                 }
2345                 brklist = brklist->nextlev;
2346                 break;
2347
2348         case TWHILE:
2349         case TUNTIL:
2350                 while (setjmp(bc.brkpt))
2351                         if (isbreak)
2352                                 goto broken;
2353                 brkset(&bc);
2354                 t1 = t->left;
2355                 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2356                         rv = execute(t->right, pin, pout, 0);
2357                 brklist = brklist->nextlev;
2358                 break;
2359
2360         case TIF:
2361         case TELIF:
2362                 if (t->right != NULL) {
2363                         rv = !execute(t->left, pin, pout, 0) ?
2364                                 execute(t->right->left, pin, pout, 0) :
2365                                 execute(t->right->right, pin, pout, 0);
2366                 }
2367                 break;
2368
2369         case TCASE:
2370                 if ((cp = evalstr(t->str, DOSUB | DOTRIM)) == 0)
2371                         cp = "";
2372                 if ((t1 = findcase(t->left, cp)) != NULL)
2373                         rv = execute(t1, pin, pout, 0);
2374                 break;
2375
2376         case TBRACE:
2377 /*
2378                 if (iopp = t->ioact)
2379                         while (*iopp)
2380                                 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2381                                         rv = -1;
2382                                         break;
2383                                 }
2384 */
2385                 if (rv >= 0 && (t1 = t->left))
2386                         rv = execute(t1, pin, pout, 0);
2387                 break;
2388         }
2389
2390   broken:
2391         t->words = wp2;
2392         isbreak = 0;
2393         freehere(areanum);
2394         freearea(areanum);
2395         areanum = a;
2396         if (interactive && intr) {
2397                 closeall();
2398                 fail();
2399         }
2400         if ((i = trapset) != 0) {
2401                 trapset = 0;
2402                 runtrap(i);
2403         }
2404         return (rv);
2405 }
2406
2407 static int
2408 forkexec(register struct op *t, int *pin, int *pout, int act, char **wp,
2409                  int *pforked)
2410 {
2411         int i, rv;
2412         int (*shcom) (struct op *) = NULL;
2413         register int f;
2414         char *cp = NULL;
2415         struct ioword **iopp;
2416         int resetsig;
2417         char **owp;
2418
2419         int *hpin = pin;
2420         int *hpout = pout;
2421         int hforked;
2422         char *hwp;
2423         int hinteractive;
2424         int hintr;
2425         struct brkcon *hbrklist;
2426         int hexecflg;
2427
2428 #if __GNUC__
2429         /* Avoid longjmp clobbering */
2430         (void) &pin;
2431         (void) &pout;
2432         (void) &wp;
2433         (void) &shcom;
2434         (void) &cp;
2435         (void) &resetsig;
2436         (void) &owp;
2437 #endif
2438
2439         owp = wp;
2440         resetsig = 0;
2441         *pforked = 0;
2442         rv = -1;                                        /* system-detected error */
2443         if (t->type == TCOM) {
2444                 while ((cp = *wp++) != NULL);
2445                 cp = *wp;
2446
2447                 /* strip all initial assignments */
2448                 /* not correct wrt PATH=yyy command  etc */
2449                 if (flag['x'])
2450                         echo(cp ? wp : owp);
2451                 if (cp == NULL && t->ioact == NULL) {
2452                         while ((cp = *owp++) != NULL && assign(cp, COPYV));
2453                         return (setstatus(0));
2454                 } else if (cp != NULL)
2455                         shcom = inbuilt(cp);
2456         }
2457         t->words = wp;
2458         f = act;
2459         if (shcom == NULL && (f & FEXEC) == 0) {
2460
2461                 hpin = pin;
2462                 hpout = pout;
2463                 hforked = *pforked;
2464                 hwp = *wp;
2465                 hinteractive = interactive;
2466                 hintr = intr;
2467                 hbrklist = brklist;
2468                 hexecflg = execflg;
2469
2470                 i = vfork();
2471                 if (i != 0) {
2472                         /* who wrote this crappy non vfork safe shit? */
2473                         pin = hpin;
2474                         pout = hpout;
2475                         *pforked = hforked;
2476                         *wp = hwp;
2477                         interactive = hinteractive;
2478                         intr = hintr;
2479                         brklist = hbrklist;
2480                         execflg = hexecflg;
2481
2482                         *pforked = 0;
2483                         if (i == -1)
2484                                 return (rv);
2485                         if (pin != NULL)
2486                                 closepipe(pin);
2487                         return (pout == NULL ? setstatus(waitfor(i, 0)) : 0);
2488                 }
2489
2490                 if (interactive) {
2491                         signal(SIGINT, SIG_IGN);
2492                         signal(SIGQUIT, SIG_IGN);
2493                         resetsig = 1;
2494                 }
2495                 interactive = 0;
2496                 intr = 0;
2497                 (*pforked)++;
2498                 brklist = 0;
2499                 execflg = 0;
2500         }
2501         if (owp != NULL)
2502                 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2503                         if (shcom == NULL)
2504                                 export(lookup(cp));
2505 #ifdef COMPIPE
2506         if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2507                 err("piping to/from shell builtins not yet done");
2508                 return (-1);
2509         }
2510 #endif
2511         if (pin != NULL) {
2512                 dup2(pin[0], 0);
2513                 closepipe(pin);
2514         }
2515         if (pout != NULL) {
2516                 dup2(pout[1], 1);
2517                 closepipe(pout);
2518         }
2519         if ((iopp = t->ioact) != NULL) {
2520                 if (shcom != NULL && shcom != doexec) {
2521                         prs(cp);
2522                         err(": cannot redirect shell command");
2523                         return (-1);
2524                 }
2525                 while (*iopp)
2526                         if (iosetup(*iopp++, pin != NULL, pout != NULL))
2527                                 return (rv);
2528         }
2529         if (shcom)
2530                 return (setstatus((*shcom) (t)));
2531         /* should use FIOCEXCL */
2532         for (i = FDBASE; i < NOFILE; i++)
2533                 close(i);
2534         if (resetsig) {
2535                 signal(SIGINT, SIG_DFL);
2536                 signal(SIGQUIT, SIG_DFL);
2537         }
2538         if (t->type == TPAREN)
2539                 exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2540         if (wp[0] == NULL)
2541                 exit(0);
2542
2543         cp = rexecve(wp[0], wp, makenv());
2544         prs(wp[0]);
2545         prs(": ");
2546         warn(cp);
2547         if (!execflg)
2548                 trap[0] = NULL;
2549         leave();
2550         /* NOTREACHED */
2551         exit(1);
2552 }
2553
2554 /*
2555  * 0< 1> are ignored as required
2556  * within pipelines.
2557  */
2558 static int iosetup(iop, pipein, pipeout)
2559 register struct ioword *iop;
2560 int pipein, pipeout;
2561 {
2562         register int u = -1;
2563         char *cp = NULL, *msg;
2564
2565         if (iop->io_unit == IODEFAULT)  /* take default */
2566                 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2567         if (pipein && iop->io_unit == 0)
2568                 return (0);
2569         if (pipeout && iop->io_unit == 1)
2570                 return (0);
2571         msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2572         if ((iop->io_flag & IOHERE) == 0) {
2573                 cp = iop->io_name;
2574                 if ((cp = evalstr(cp, DOSUB | DOTRIM)) == NULL)
2575                         return (1);
2576         }
2577         if (iop->io_flag & IODUP) {
2578                 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2579                         prs(cp);
2580                         err(": illegal >& argument");
2581                         return (1);
2582                 }
2583                 if (*cp == '-')
2584                         iop->io_flag = IOCLOSE;
2585                 iop->io_flag &= ~(IOREAD | IOWRITE);
2586         }
2587         switch (iop->io_flag) {
2588         case IOREAD:
2589                 u = open(cp, 0);
2590                 break;
2591
2592         case IOHERE:
2593         case IOHERE | IOXHERE:
2594                 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2595                 cp = "here file";
2596                 break;
2597
2598         case IOWRITE | IOCAT:
2599                 if ((u = open(cp, 1)) >= 0) {
2600                         lseek(u, (long) 0, 2);
2601                         break;
2602                 }
2603         case IOWRITE:
2604                 u = creat(cp, 0666);
2605                 break;
2606
2607         case IODUP:
2608                 u = dup2(*cp - '0', iop->io_unit);
2609                 break;
2610
2611         case IOCLOSE:
2612                 close(iop->io_unit);
2613                 return (0);
2614         }
2615         if (u < 0) {
2616                 prs(cp);
2617                 prs(": cannot ");
2618                 warn(msg);
2619                 return (1);
2620         } else {
2621                 if (u != iop->io_unit) {
2622                         dup2(u, iop->io_unit);
2623                         close(u);
2624                 }
2625         }
2626         return (0);
2627 }
2628
2629 static void echo(wp)
2630 register char **wp;
2631 {
2632         register int i;
2633
2634         prs("+");
2635         for (i = 0; wp[i]; i++) {
2636                 if (i)
2637                         prs(" ");
2638                 prs(wp[i]);
2639         }
2640         prs("\n");
2641 }
2642
2643 static struct op **find1case(t, w)
2644 struct op *t;
2645 char *w;
2646 {
2647         register struct op *t1;
2648         struct op **tp;
2649         register char **wp, *cp;
2650
2651         if (t == NULL)
2652                 return ((struct op **) NULL);
2653         if (t->type == TLIST) {
2654                 if ((tp = find1case(t->left, w)) != NULL)
2655                         return (tp);
2656                 t1 = t->right;                  /* TPAT */
2657         } else
2658                 t1 = t;
2659         for (wp = t1->words; *wp;)
2660                 if ((cp = evalstr(*wp++, DOSUB)) && gmatch(w, cp))
2661                         return (&t1->left);
2662         return ((struct op **) NULL);
2663 }
2664
2665 static struct op *findcase(t, w)
2666 struct op *t;
2667 char *w;
2668 {
2669         register struct op **tp;
2670
2671         return ((tp = find1case(t, w)) != NULL ? *tp : (struct op *) NULL);
2672 }
2673
2674 /*
2675  * Enter a new loop level (marked for break/continue).
2676  */
2677 static void brkset(bc)
2678 struct brkcon *bc;
2679 {
2680         bc->nextlev = brklist;
2681         brklist = bc;
2682 }
2683
2684 /*
2685  * Wait for the last process created.
2686  * Print a message for each process found
2687  * that was killed by a signal.
2688  * Ignore interrupt signals while waiting
2689  * unless `canintr' is true.
2690  */
2691 static int waitfor(lastpid, canintr)
2692 register int lastpid;
2693 int canintr;
2694 {
2695         register int pid, rv;
2696         int s;
2697         int oheedint = heedint;
2698
2699         heedint = 0;
2700         rv = 0;
2701         do {
2702                 pid = wait(&s);
2703                 if (pid == -1) {
2704                         if (errno != EINTR || canintr)
2705                                 break;
2706                 } else {
2707                         if ((rv = WAITSIG(s)) != 0) {
2708                                 if (rv < NSIGNAL) {
2709                                         if (signame[rv] != NULL) {
2710                                                 if (pid != lastpid) {
2711                                                         prn(pid);
2712                                                         prs(": ");
2713                                                 }
2714                                                 prs(signame[rv]);
2715                                         }
2716                                 } else {
2717                                         if (pid != lastpid) {
2718                                                 prn(pid);
2719                                                 prs(": ");
2720                                         }
2721                                         prs("Signal ");
2722                                         prn(rv);
2723                                         prs(" ");
2724                                 }
2725                                 if (WAITCORE(s))
2726                                         prs(" - core dumped");
2727                                 if (rv >= NSIGNAL || signame[rv])
2728                                         prs("\n");
2729                                 rv = -1;
2730                         } else
2731                                 rv = WAITVAL(s);
2732                 }
2733         } while (pid != lastpid);
2734         heedint = oheedint;
2735         if (intr) {
2736                 if (interactive) {
2737                         if (canintr)
2738                                 intr = 0;
2739                 } else {
2740                         if (exstat == 0)
2741                                 exstat = rv;
2742                         onintr(0);
2743                 }
2744         }
2745         return (rv);
2746 }
2747
2748 static int setstatus(s)
2749 register int s;
2750 {
2751         exstat = s;
2752         setval(lookup("?"), putn(s));
2753         return (s);
2754 }
2755
2756 /*
2757  * PATH-searching interface to execve.
2758  * If getenv("PATH") were kept up-to-date,
2759  * execvp might be used.
2760  */
2761 static char *rexecve(c, v, envp)
2762 char *c, **v, **envp;
2763 {
2764         register int i;
2765         register char *sp, *tp;
2766         int eacces = 0, asis = 0;
2767
2768 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
2769         char *name = c;
2770
2771         optind = 1;
2772         if (find_applet_by_name(name)) {
2773                 /* We have to exec here since we vforked.  Running
2774                  * run_applet_by_name() won't work and bad things
2775                  * will happen. */
2776                 execve("/proc/self/exe", v, envp);
2777                 execve("busybox", v, envp);
2778         }
2779 #endif
2780
2781         sp = any('/', c) ? "" : path->value;
2782         asis = *sp == '\0';
2783         while (asis || *sp != '\0') {
2784                 asis = 0;
2785                 tp = e.linep;
2786                 for (; *sp != '\0'; tp++)
2787                         if ((*tp = *sp++) == ':') {
2788                                 asis = *sp == '\0';
2789                                 break;
2790                         }
2791                 if (tp != e.linep)
2792                         *tp++ = '/';
2793                 for (i = 0; (*tp++ = c[i++]) != '\0';);
2794
2795                 execve(e.linep, v, envp);
2796                 switch (errno) {
2797                 case ENOEXEC:
2798                         *v = e.linep;
2799                         tp = *--v;
2800                         *v = e.linep;
2801                         execve(DEFAULT_SHELL, v, envp);
2802                         *v = tp;
2803                         return ("no Shell");
2804
2805                 case ENOMEM:
2806                         return ((char *) bb_msg_memory_exhausted);
2807
2808                 case E2BIG:
2809                         return ("argument list too long");
2810
2811                 case EACCES:
2812                         eacces++;
2813                         break;
2814                 }
2815         }
2816         return (errno == ENOENT ? "not found" : "cannot execute");
2817 }
2818
2819 /*
2820  * Run the command produced by generator `f'
2821  * applied to stream `arg'.
2822  */
2823 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
2824 {
2825         struct op *otree;
2826         struct wdblock *swdlist;
2827         struct wdblock *siolist;
2828         jmp_buf ev, rt;
2829         xint *ofail;
2830         int rv;
2831
2832 #if __GNUC__
2833         /* Avoid longjmp clobbering */
2834         (void) &rv;
2835 #endif
2836
2837         areanum++;
2838         swdlist = wdlist;
2839         siolist = iolist;
2840         otree = outtree;
2841         ofail = failpt;
2842         rv = -1;
2843         if (newenv(setjmp(errpt = ev)) == 0) {
2844                 wdlist = 0;
2845                 iolist = 0;
2846                 pushio(argp, f);
2847                 e.iobase = e.iop;
2848                 yynerrs = 0;
2849                 if (setjmp(failpt = rt) == 0 && yyparse() == 0)
2850                         rv = execute(outtree, NOPIPE, NOPIPE, 0);
2851                 quitenv();
2852         }
2853         wdlist = swdlist;
2854         iolist = siolist;
2855         failpt = ofail;
2856         outtree = otree;
2857         freearea(areanum--);
2858         return (rv);
2859 }
2860
2861 /* -------- do.c -------- */
2862
2863 /*
2864  * built-in commands: doX
2865  */
2866
2867 static int dohelp(struct op *t)
2868 {
2869         int col;
2870         const struct builtincmd *x;
2871
2872         printf("\nBuilt-in commands:\n");
2873         printf("-------------------\n");
2874
2875         for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
2876                 if (!x->name)
2877                         continue;
2878                 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
2879                 if (col > 60) {
2880                         printf("\n");
2881                         col = 0;
2882                 }
2883         }
2884 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
2885         {
2886                 int i;
2887                 const struct BB_applet *applet;
2888                 extern const struct BB_applet applets[];
2889                 extern const size_t NUM_APPLETS;
2890
2891                 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
2892                         if (!applet->name)
2893                                 continue;
2894
2895                         col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
2896                         if (col > 60) {
2897                                 printf("\n");
2898                                 col = 0;
2899                         }
2900                 }
2901         }
2902 #endif
2903         printf("\n\n");
2904         return EXIT_SUCCESS;
2905 }
2906
2907
2908
2909 static int dolabel(struct op *t)
2910 {
2911         return (0);
2912 }
2913
2914 static int dochdir(t)
2915 register struct op *t;
2916 {
2917         register char *cp, *er;
2918
2919         if ((cp = t->words[1]) == NULL && (cp = homedir->value) == NULL)
2920                 er = ": no home directory";
2921         else if (chdir(cp) < 0)
2922                 er = ": bad directory";
2923         else
2924                 return (0);
2925         prs(cp != NULL ? cp : "cd");
2926         err(er);
2927         return (1);
2928 }
2929
2930 static int doshift(t)
2931 register struct op *t;
2932 {
2933         register int n;
2934
2935         n = t->words[1] ? getn(t->words[1]) : 1;
2936         if (dolc < n) {
2937                 err("nothing to shift");
2938                 return (1);
2939         }
2940         dolv[n] = dolv[0];
2941         dolv += n;
2942         dolc -= n;
2943         setval(lookup("#"), putn(dolc));
2944         return (0);
2945 }
2946
2947 /*
2948  * execute login and newgrp directly
2949  */
2950 static int dologin(t)
2951 struct op *t;
2952 {
2953         register char *cp;
2954
2955         if (interactive) {
2956                 signal(SIGINT, SIG_DFL);
2957                 signal(SIGQUIT, SIG_DFL);
2958         }
2959         cp = rexecve(t->words[0], t->words, makenv());
2960         prs(t->words[0]);
2961         prs(": ");
2962         err(cp);
2963         return (1);
2964 }
2965
2966 static int doumask(t)
2967 register struct op *t;
2968 {
2969         register int i, n;
2970         register char *cp;
2971
2972         if ((cp = t->words[1]) == NULL) {
2973                 i = umask(0);
2974                 umask(i);
2975                 for (n = 3 * 4; (n -= 3) >= 0;)
2976                         putc('0' + ((i >> n) & 07), stderr);
2977                 putc('\n', stderr);
2978         } else {
2979                 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
2980                         n = n * 8 + (*cp - '0');
2981                 umask(n);
2982         }
2983         return (0);
2984 }
2985
2986 static int doexec(t)
2987 register struct op *t;
2988 {
2989         register int i;
2990         jmp_buf ex;
2991         xint *ofail;
2992
2993         t->ioact = NULL;
2994         for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
2995         if (i == 0)
2996                 return (1);
2997         execflg = 1;
2998         ofail = failpt;
2999         if (setjmp(failpt = ex) == 0)
3000                 execute(t, NOPIPE, NOPIPE, FEXEC);
3001         failpt = ofail;
3002         execflg = 0;
3003         return (1);
3004 }
3005
3006 static int dodot(t)
3007 struct op *t;
3008 {
3009         register int i;
3010         register char *sp, *tp;
3011         char *cp;
3012
3013         if ((cp = t->words[1]) == NULL)
3014                 return (0);
3015         sp = any('/', cp) ? ":" : path->value;
3016         while (*sp) {
3017                 tp = e.linep;
3018                 while (*sp && (*tp = *sp++) != ':')
3019                         tp++;
3020                 if (tp != e.linep)
3021                         *tp++ = '/';
3022                 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3023                 if ((i = open(e.linep, 0)) >= 0) {
3024                         exstat = 0;
3025                         next(remap(i));
3026                         return (exstat);
3027                 }
3028         }
3029         prs(cp);
3030         err(": not found");
3031         return (-1);
3032 }
3033
3034 static int dowait(t)
3035 struct op *t;
3036 {
3037         register int i;
3038         register char *cp;
3039
3040         if ((cp = t->words[1]) != NULL) {
3041                 i = getn(cp);
3042                 if (i == 0)
3043                         return (0);
3044         } else
3045                 i = -1;
3046         setstatus(waitfor(i, 1));
3047         return (0);
3048 }
3049
3050 static int doread(t)
3051 struct op *t;
3052 {
3053         register char *cp, **wp;
3054         register int nb = 0;
3055         register int nl = 0;
3056
3057         if (t->words[1] == NULL) {
3058                 err("Usage: read name ...");
3059                 return (1);
3060         }
3061         for (wp = t->words + 1; *wp; wp++) {
3062                 for (cp = e.linep; !nl && cp < elinep - 1; cp++)
3063                         if ((nb = read(0, cp, sizeof(*cp))) != sizeof(*cp) ||
3064                                 (nl = (*cp == '\n')) || (wp[1] && any(*cp, ifs->value)))
3065                                 break;
3066                 *cp = 0;
3067                 if (nb <= 0)
3068                         break;
3069                 setval(lookup(*wp), e.linep);
3070         }
3071         return (nb <= 0);
3072 }
3073
3074 static int doeval(t)
3075 register struct op *t;
3076 {
3077         return (RUN(awordlist, t->words + 1, wdchar));
3078 }
3079
3080 static int dotrap(t)
3081 register struct op *t;
3082 {
3083         register int n, i;
3084         register int resetsig;
3085
3086         if (t->words[1] == NULL) {
3087                 for (i = 0; i <= _NSIG; i++)
3088                         if (trap[i]) {
3089                                 prn(i);
3090                                 prs(": ");
3091                                 prs(trap[i]);
3092                                 prs("\n");
3093                         }
3094                 return (0);
3095         }
3096         resetsig = isdigit(*t->words[1]);
3097         for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3098                 n = getsig(t->words[i]);
3099                 freecell(trap[n]);
3100                 trap[n] = 0;
3101                 if (!resetsig) {
3102                         if (*t->words[1] != '\0') {
3103                                 trap[n] = strsave(t->words[1], 0);
3104                                 setsig(n, sig);
3105                         } else
3106                                 setsig(n, SIG_IGN);
3107                 } else {
3108                         if (interactive)
3109                                 if (n == SIGINT)
3110                                         setsig(n, onintr);
3111                                 else
3112                                         setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3113                         else
3114                                 setsig(n, SIG_DFL);
3115                 }
3116         }
3117         return (0);
3118 }
3119
3120 static int getsig(s)
3121 char *s;
3122 {
3123         register int n;
3124
3125         if ((n = getn(s)) < 0 || n > _NSIG) {
3126                 err("trap: bad signal number");
3127                 n = 0;
3128         }
3129         return (n);
3130 }
3131
3132 static void setsig(register int n, sighandler_t f)
3133 {
3134         if (n == 0)
3135                 return;
3136         if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3137                 ourtrap[n] = 1;
3138                 signal(n, f);
3139         }
3140 }
3141
3142 static int getn(as)
3143 char *as;
3144 {
3145         register char *s;
3146         register int n, m;
3147
3148         s = as;
3149         m = 1;
3150         if (*s == '-') {
3151                 m = -1;
3152                 s++;
3153         }
3154         for (n = 0; isdigit(*s); s++)
3155                 n = (n * 10) + (*s - '0');
3156         if (*s) {
3157                 prs(as);
3158                 err(": bad number");
3159         }
3160         return (n * m);
3161 }
3162
3163 static int dobreak(t)
3164 struct op *t;
3165 {
3166         return (brkcontin(t->words[1], 1));
3167 }
3168
3169 static int docontinue(t)
3170 struct op *t;
3171 {
3172         return (brkcontin(t->words[1], 0));
3173 }
3174
3175 static int brkcontin(cp, val)
3176 register char *cp;
3177 int val;
3178 {
3179         register struct brkcon *bc;
3180         register int nl;
3181
3182         nl = cp == NULL ? 1 : getn(cp);
3183         if (nl <= 0)
3184                 nl = 999;
3185         do {
3186                 if ((bc = brklist) == NULL)
3187                         break;
3188                 brklist = bc->nextlev;
3189         } while (--nl);
3190         if (nl) {
3191                 err("bad break/continue level");
3192                 return (1);
3193         }
3194         isbreak = val;
3195         longjmp(bc->brkpt, 1);
3196         /* NOTREACHED */
3197 }
3198
3199 static int doexit(t)
3200 struct op *t;
3201 {
3202         register char *cp;
3203
3204         execflg = 0;
3205         if ((cp = t->words[1]) != NULL)
3206                 setstatus(getn(cp));
3207         leave();
3208         /* NOTREACHED */
3209         return (0);
3210 }
3211
3212 static int doexport(t)
3213 struct op *t;
3214 {
3215         rdexp(t->words + 1, export, EXPORT);
3216         return (0);
3217 }
3218
3219 static int doreadonly(t)
3220 struct op *t;
3221 {
3222         rdexp(t->words + 1, ronly, RONLY);
3223         return (0);
3224 }
3225
3226 static void rdexp(char **wp, void (*f) (struct var *), int key)
3227 {
3228         if (*wp != NULL) {
3229                 for (; *wp != NULL; wp++) {
3230                         if (isassign(*wp)) {
3231                                 char *cp;
3232
3233                                 assign(*wp, COPYV);
3234                                 for (cp = *wp; *cp != '='; cp++);
3235                                 *cp = '\0';
3236                         }
3237                         if (checkname(*wp))
3238                                 (*f) (lookup(*wp));
3239                         else
3240                                 badid(*wp);
3241                 }
3242         } else
3243                 putvlist(key, 1);
3244 }
3245
3246 static void badid(s)
3247 register char *s;
3248 {
3249         prs(s);
3250         err(": bad identifier");
3251 }
3252
3253 static int doset(t)
3254 register struct op *t;
3255 {
3256         register struct var *vp;
3257         register char *cp;
3258         register int n;
3259
3260         if ((cp = t->words[1]) == NULL) {
3261                 for (vp = vlist; vp; vp = vp->next)
3262                         varput(vp->name, 1);
3263                 return (0);
3264         }
3265         if (*cp == '-') {
3266                 /* bad: t->words++; */
3267                 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3268                 if (*++cp == 0)
3269                         flag['x'] = flag['v'] = 0;
3270                 else
3271                         for (; *cp; cp++)
3272                                 switch (*cp) {
3273                                 case 'e':
3274                                         if (!interactive)
3275                                                 flag['e']++;
3276                                         break;
3277
3278                                 default:
3279                                         if (*cp >= 'a' && *cp <= 'z')
3280                                                 flag[(int) *cp]++;
3281                                         break;
3282                                 }
3283                 setdash();
3284         }
3285         if (t->words[1]) {
3286                 t->words[0] = dolv[0];
3287                 for (n = 1; t->words[n]; n++)
3288                         setarea((char *) t->words[n], 0);
3289                 dolc = n - 1;
3290                 dolv = t->words;
3291                 setval(lookup("#"), putn(dolc));
3292                 setarea((char *) (dolv - 1), 0);
3293         }
3294         return (0);
3295 }
3296
3297 static void varput(s, out)
3298 register char *s;
3299 int out;
3300 {
3301         if (isalnum(*s) || *s == '_') {
3302                 write(out, s, strlen(s));
3303                 write(out, "\n", 1);
3304         }
3305 }
3306
3307
3308 /*
3309  * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3310  * This file contains code for the times builtin.
3311  */
3312 static int dotimes(struct op *t)
3313 {
3314         struct tms buf;
3315         long int clk_tck = sysconf(_SC_CLK_TCK);
3316
3317         times(&buf);
3318         printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3319                    (int) (buf.tms_utime / clk_tck / 60),
3320                    ((double) buf.tms_utime) / clk_tck,
3321                    (int) (buf.tms_stime / clk_tck / 60),
3322                    ((double) buf.tms_stime) / clk_tck,
3323                    (int) (buf.tms_cutime / clk_tck / 60),
3324                    ((double) buf.tms_cutime) / clk_tck,
3325                    (int) (buf.tms_cstime / clk_tck / 60),
3326                    ((double) buf.tms_cstime) / clk_tck);
3327         return 0;
3328 }
3329
3330
3331 static int (*inbuilt(char *s)) (struct op *) {
3332         const struct builtincmd *bp;
3333
3334         for (bp = builtincmds; bp->name != NULL; bp++)
3335                 if (strcmp(bp->name, s) == 0)
3336                         return (bp->builtinfunc);
3337
3338         return (NULL);
3339 }
3340
3341 /* -------- eval.c -------- */
3342
3343 /*
3344  * ${}
3345  * `command`
3346  * blank interpretation
3347  * quoting
3348  * glob
3349  */
3350
3351 static char **eval(char **ap, int f)
3352 {
3353         struct wdblock *wb;
3354         char **wp;
3355         char **wf;
3356         jmp_buf ev;
3357
3358 #if __GNUC__
3359         /* Avoid longjmp clobbering */
3360         (void) &wp;
3361         (void) &ap;
3362 #endif
3363         wp = NULL;
3364         wb = NULL;
3365         wf = NULL;
3366         if (newenv(setjmp(errpt = ev)) == 0) {
3367                 while (*ap && isassign(*ap))
3368                         expand(*ap++, &wb, f & ~DOGLOB);
3369                 if (flag['k']) {
3370                         for (wf = ap; *wf; wf++) {
3371                                 if (isassign(*wf))
3372                                         expand(*wf, &wb, f & ~DOGLOB);
3373                         }
3374                 }
3375                 for (wb = addword((char *) 0, wb); *ap; ap++) {
3376                         if (!flag['k'] || !isassign(*ap))
3377                                 expand(*ap, &wb, f & ~DOKEY);
3378                 }
3379                 wb = addword((char *) 0, wb);
3380                 wp = getwords(wb);
3381                 quitenv();
3382         } else
3383                 gflg = 1;
3384         return (gflg ? (char **) NULL : wp);
3385 }
3386
3387 /*
3388  * Make the exported environment from the exported
3389  * names in the dictionary. Keyword assignments
3390  * will already have been done.
3391  */
3392 static char **makenv()
3393 {
3394         register struct wdblock *wb;
3395         register struct var *vp;
3396
3397         wb = NULL;
3398         for (vp = vlist; vp; vp = vp->next)
3399                 if (vp->status & EXPORT)
3400                         wb = addword(vp->name, wb);
3401         wb = addword((char *) 0, wb);
3402         return (getwords(wb));
3403 }
3404
3405 static char *evalstr(cp, f)
3406 register char *cp;
3407 int f;
3408 {
3409         struct wdblock *wb;
3410
3411         wb = NULL;
3412         if (expand(cp, &wb, f)) {
3413                 if (wb == NULL || wb->w_nword == 0
3414                         || (cp = wb->w_words[0]) == NULL)
3415                         cp = "";
3416                 DELETE(wb);
3417         } else
3418                 cp = NULL;
3419         return (cp);
3420 }
3421
3422 static int expand(char *cp, register struct wdblock **wbp, int f)
3423 {
3424         jmp_buf ev;
3425
3426 #if __GNUC__
3427         /* Avoid longjmp clobbering */
3428         (void) &cp;
3429 #endif
3430         gflg = 0;
3431         if (cp == NULL)
3432                 return (0);
3433         if (!anys("$`'\"", cp) &&
3434                 !anys(ifs->value, cp) && ((f & DOGLOB) == 0 || !anys("[*?", cp))) {
3435                 cp = strsave(cp, areanum);
3436                 if (f & DOTRIM)
3437                         unquote(cp);
3438                 *wbp = addword(cp, *wbp);
3439                 return (1);
3440         }
3441         if (newenv(setjmp(errpt = ev)) == 0) {
3442                 PUSHIO(aword, cp, strchar);
3443                 e.iobase = e.iop;
3444                 while ((cp = blank(f)) && gflg == 0) {
3445                         e.linep = cp;
3446                         cp = strsave(cp, areanum);
3447                         if ((f & DOGLOB) == 0) {
3448                                 if (f & DOTRIM)
3449                                         unquote(cp);
3450                                 *wbp = addword(cp, *wbp);
3451                         } else
3452                                 *wbp = glob(cp, *wbp);
3453                 }
3454                 quitenv();
3455         } else
3456                 gflg = 1;
3457         return (gflg == 0);
3458 }
3459
3460 /*
3461  * Blank interpretation and quoting
3462  */
3463 static char *blank(f)
3464 int f;
3465 {
3466         register int c, c1;
3467         register char *sp;
3468         int scanequals, foundequals;
3469
3470         sp = e.linep;
3471         scanequals = f & DOKEY;
3472         foundequals = 0;
3473
3474   loop:
3475         switch (c = subgetc('"', foundequals)) {
3476         case 0:
3477                 if (sp == e.linep)
3478                         return (0);
3479                 *e.linep++ = 0;
3480                 return (sp);
3481
3482         default:
3483                 if (f & DOBLANK && any(c, ifs->value))
3484                         goto loop;
3485                 break;
3486
3487         case '"':
3488         case '\'':
3489                 scanequals = 0;
3490                 if (INSUB())
3491                         break;
3492                 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3493                         if (c == 0)
3494                                 break;
3495                         if (c == '\'' || !any(c, "$`\""))
3496                                 c |= QUOTE;
3497                         *e.linep++ = c;
3498                 }
3499                 c = 0;
3500         }
3501         unget(c);
3502         if (!isalpha(c) && c != '_')
3503                 scanequals = 0;
3504         for (;;) {
3505                 c = subgetc('"', foundequals);
3506                 if (c == 0 ||
3507                         f & (DOBLANK && any(c, ifs->value)) ||
3508                         (!INSUB() && any(c, "\"'"))) {
3509                         scanequals = 0;
3510                         unget(c);
3511                         if (any(c, "\"'"))
3512                                 goto loop;
3513                         break;
3514                 }
3515                 if (scanequals) {
3516                         if (c == '=') {
3517                                 foundequals = 1;
3518                                 scanequals = 0;
3519                         } else if (!isalnum(c) && c != '_')
3520                                 scanequals = 0;
3521                 }
3522                 *e.linep++ = c;
3523         }
3524         *e.linep++ = 0;
3525         return (sp);
3526 }
3527
3528 /*
3529  * Get characters, substituting for ` and $
3530  */
3531 static int subgetc(ec, quoted)
3532 register char ec;
3533 int quoted;
3534 {
3535         register char c;
3536
3537   again:
3538         c = my_getc(ec);
3539         if (!INSUB() && ec != '\'') {
3540                 if (c == '`') {
3541                         if (grave(quoted) == 0)
3542                                 return (0);
3543                         e.iop->task = XGRAVE;
3544                         goto again;
3545                 }
3546                 if (c == '$' && (c = dollar(quoted)) == 0) {
3547                         e.iop->task = XDOLL;
3548                         goto again;
3549                 }
3550         }
3551         return (c);
3552 }
3553
3554 /*
3555  * Prepare to generate the string returned by ${} substitution.
3556  */
3557 static int dollar(quoted)
3558 int quoted;
3559 {
3560         int otask;
3561         struct io *oiop;
3562         char *dolp;
3563         register char *s, c, *cp = NULL;
3564         struct var *vp;
3565
3566         c = readc();
3567         s = e.linep;
3568         if (c != '{') {
3569                 *e.linep++ = c;
3570                 if (isalpha(c) || c == '_') {
3571                         while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3572                                 if (e.linep < elinep)
3573                                         *e.linep++ = c;
3574                         unget(c);
3575                 }
3576                 c = 0;
3577         } else {
3578                 oiop = e.iop;
3579                 otask = e.iop->task;
3580                 e.iop->task = XOTHER;
3581                 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3582                         if (e.linep < elinep)
3583                                 *e.linep++ = c;
3584                 if (oiop == e.iop)
3585                         e.iop->task = otask;
3586                 if (c != '}') {
3587                         err("unclosed ${");
3588                         gflg++;
3589                         return (c);
3590                 }
3591         }
3592         if (e.linep >= elinep) {
3593                 err("string in ${} too long");
3594                 gflg++;
3595                 e.linep -= 10;
3596         }
3597         *e.linep = 0;
3598         if (*s)
3599                 for (cp = s + 1; *cp; cp++)
3600                         if (any(*cp, "=-+?")) {
3601                                 c = *cp;
3602                                 *cp++ = 0;
3603                                 break;
3604                         }
3605         if (s[1] == 0 && (*s == '*' || *s == '@')) {
3606                 if (dolc > 1) {
3607                         /* currently this does not distinguish $* and $@ */
3608                         /* should check dollar */
3609                         e.linep = s;
3610                         PUSHIO(awordlist, dolv + 1, dolchar);
3611                         return (0);
3612                 } else {                                /* trap the nasty ${=} */
3613                         s[0] = '1';
3614                         s[1] = 0;
3615                 }
3616         }
3617         vp = lookup(s);
3618         if ((dolp = vp->value) == null) {
3619                 switch (c) {
3620                 case '=':
3621                         if (isdigit(*s)) {
3622                                 err("cannot use ${...=...} with $n");
3623                                 gflg++;
3624                                 break;
3625                         }
3626                         setval(vp, cp);
3627                         dolp = vp->value;
3628                         break;
3629
3630                 case '-':
3631                         dolp = strsave(cp, areanum);
3632                         break;
3633
3634                 case '?':
3635                         if (*cp == 0) {
3636                                 prs("missing value for ");
3637                                 err(s);
3638                         } else
3639                                 err(cp);
3640                         gflg++;
3641                         break;
3642                 }
3643         } else if (c == '+')
3644                 dolp = strsave(cp, areanum);
3645         if (flag['u'] && dolp == null) {
3646                 prs("unset variable: ");
3647                 err(s);
3648                 gflg++;
3649         }
3650         e.linep = s;
3651         PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
3652         return (0);
3653 }
3654
3655 /*
3656  * Run the command in `...` and read its output.
3657  */
3658
3659 static int grave(quoted)
3660 int quoted;
3661 {
3662         char *cp;
3663         register int i;
3664         int j;
3665         int pf[2];
3666         static char child_cmd[LINELIM];
3667         char *src;
3668         char *dest;
3669         int count;
3670         int ignore;
3671         int ignore_once;
3672         char *argument_list[4];
3673
3674 #if __GNUC__
3675         /* Avoid longjmp clobbering */
3676         (void) &cp;
3677 #endif
3678
3679         for (cp = e.iop->argp->aword; *cp != '`'; cp++)
3680                 if (*cp == 0) {
3681                         err("no closing `");
3682                         return (0);
3683                 }
3684
3685         /* string copy with dollar expansion */
3686         src = e.iop->argp->aword;
3687         dest = child_cmd;
3688         count = 0;
3689         ignore = 0;
3690         ignore_once = 0;
3691         while ((*src != '`') && (count < LINELIM)) {
3692                 if (*src == '\'')
3693                         ignore = !ignore;
3694                 if (*src == '\\')
3695                         ignore_once = 1;
3696                 if (*src == '$' && !ignore && !ignore_once) {
3697                         struct var *vp;
3698                         char var_name[LINELIM];
3699                         char alt_value[LINELIM];
3700                         int var_index = 0;
3701                         int alt_index = 0;
3702                         char operator = 0;
3703                         int braces = 0;
3704                         char *value;
3705
3706                         src++;
3707                         if (*src == '{') {
3708                                 braces = 1;
3709                                 src++;
3710                         }
3711
3712                         var_name[var_index++] = *src++;
3713                         while (isalnum(*src))
3714                                 var_name[var_index++] = *src++;
3715                         var_name[var_index] = 0;
3716
3717                         if (braces) {
3718                                 switch (*src) {
3719                                 case '}':
3720                                         break;
3721                                 case '-':
3722                                 case '=':
3723                                 case '+':
3724                                 case '?':
3725                                         operator = * src;
3726                                         break;
3727                                 default:
3728                                         err("unclosed ${\n");
3729                                         return (0);
3730                                 }
3731                                 if (operator) {
3732                                         src++;
3733                                         while (*src && (*src != '}')) {
3734                                                 alt_value[alt_index++] = *src++;
3735                                         }
3736                                         alt_value[alt_index] = 0;
3737                                         if (*src != '}') {
3738                                                 err("unclosed ${\n");
3739                                                 return (0);
3740                                         }
3741                                 }
3742                                 src++;
3743                         }
3744
3745                         vp = lookup(var_name);
3746                         if (vp->value != null)
3747                                 value = (operator == '+') ? alt_value : vp->value;
3748                         else if (operator == '?') {
3749                                 err(alt_value);
3750                                 return (0);
3751                         } else if (alt_index && (operator != '+')) {
3752                                 value = alt_value;
3753                                 if (operator == '=')
3754                                         setval(vp, value);
3755                         } else
3756                                 continue;
3757
3758                         while (*value && (count < LINELIM)) {
3759                                 *dest++ = *value++;
3760                                 count++;
3761                         }
3762                 } else {
3763                         *dest++ = *src++;
3764                         count++;
3765                         ignore_once = 0;
3766                 }
3767         }
3768         *dest = '\0';
3769
3770         if (openpipe(pf) < 0)
3771                 return (0);
3772         while ((i = vfork()) == -1 && errno == EAGAIN);
3773         if (i < 0) {
3774                 closepipe(pf);
3775                 err((char *) bb_msg_memory_exhausted);
3776                 return (0);
3777         }
3778         if (i != 0) {
3779                 waitpid(i, NULL, 0);
3780                 e.iop->argp->aword = ++cp;
3781                 close(pf[1]);
3782                 PUSHIO(afile, remap(pf[0]),
3783                            (int (*)(struct ioarg *)) ((quoted) ? qgravechar :
3784                                                                                   gravechar));
3785                 return (1);
3786         }
3787         /* allow trapped signals */
3788         /* XXX - Maybe this signal stuff should go as well? */
3789         for (j = 0; j <= _NSIG; j++)
3790                 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
3791                         signal(j, SIG_DFL);
3792
3793         dup2(pf[1], 1);
3794         closepipe(pf);
3795
3796         argument_list[0] = (char *) DEFAULT_SHELL;
3797         argument_list[1] = "-c";
3798         argument_list[2] = child_cmd;
3799         argument_list[3] = 0;
3800
3801         prs(rexecve(argument_list[0], argument_list, makenv()));
3802         _exit(1);
3803 }
3804
3805
3806 static char *unquote(as)
3807 register char *as;
3808 {
3809         register char *s;
3810
3811         if ((s = as) != NULL)
3812                 while (*s)
3813                         *s++ &= ~QUOTE;
3814         return (as);
3815 }
3816
3817 /* -------- glob.c -------- */
3818
3819 /*
3820  * glob
3821  */
3822
3823 #define scopy(x) strsave((x), areanum)
3824 #define BLKSIZ  512
3825 #define NDENT   ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
3826
3827 static struct wdblock *cl, *nl;
3828 static char spcl[] = "[?*";
3829
3830 static struct wdblock *glob(cp, wb)
3831 char *cp;
3832 struct wdblock *wb;
3833 {
3834         register int i;
3835         register char *pp;
3836
3837         if (cp == 0)
3838                 return (wb);
3839         i = 0;
3840         for (pp = cp; *pp; pp++)
3841                 if (any(*pp, spcl))
3842                         i++;
3843                 else if (!any(*pp & ~QUOTE, spcl))
3844                         *pp &= ~QUOTE;
3845         if (i != 0) {
3846                 for (cl = addword(scopy(cp), (struct wdblock *) 0); anyspcl(cl);
3847                          cl = nl) {
3848                         nl = newword(cl->w_nword * 2);
3849                         for (i = 0; i < cl->w_nword; i++) {     /* for each argument */
3850                                 for (pp = cl->w_words[i]; *pp; pp++)
3851                                         if (any(*pp, spcl)) {
3852                                                 globname(cl->w_words[i], pp);
3853                                                 break;
3854                                         }
3855                                 if (*pp == '\0')
3856                                         nl = addword(scopy(cl->w_words[i]), nl);
3857                         }
3858                         for (i = 0; i < cl->w_nword; i++)
3859                                 DELETE(cl->w_words[i]);
3860                         DELETE(cl);
3861                 }
3862                 for (i = 0; i < cl->w_nword; i++)
3863                         unquote(cl->w_words[i]);
3864                 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
3865                 if (cl->w_nword) {
3866                         for (i = 0; i < cl->w_nword; i++)
3867                                 wb = addword(cl->w_words[i], wb);
3868                         DELETE(cl);
3869                         return (wb);
3870                 }
3871         }
3872         wb = addword(unquote(cp), wb);
3873         return (wb);
3874 }
3875
3876 static void globname(we, pp)
3877 char *we;
3878 register char *pp;
3879 {
3880         register char *np, *cp;
3881         char *name, *gp, *dp;
3882         int k;
3883         DIR *dirp;
3884         struct dirent *de;
3885         char dname[NAME_MAX + 1];
3886         struct stat dbuf;
3887
3888         for (np = we; np != pp; pp--)
3889                 if (pp[-1] == '/')
3890                         break;
3891         for (dp = cp = space((int) (pp - np) + 3); np < pp;)
3892                 *cp++ = *np++;
3893         *cp++ = '.';
3894         *cp = '\0';
3895         for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
3896                 *cp++ = *np++;
3897         *cp = '\0';
3898         dirp = opendir(dp);
3899         if (dirp == 0) {
3900                 DELETE(dp);
3901                 DELETE(gp);
3902                 return;
3903         }
3904         dname[NAME_MAX] = '\0';
3905         while ((de = readdir(dirp)) != NULL) {
3906                 /* XXX Hmmm... What this could be? (abial) */
3907                 /*
3908                    if (ent[j].d_ino == 0)
3909                    continue;
3910                  */
3911                 strncpy(dname, de->d_name, NAME_MAX);
3912                 if (dname[0] == '.')
3913                         if (*gp != '.')
3914                                 continue;
3915                 for (k = 0; k < NAME_MAX; k++)
3916                         if (any(dname[k], spcl))
3917                                 dname[k] |= QUOTE;
3918                 if (gmatch(dname, gp)) {
3919                         name = generate(we, pp, dname, np);
3920                         if (*np && !anys(np, spcl)) {
3921                                 if (stat(name, &dbuf)) {
3922                                         DELETE(name);
3923                                         continue;
3924                                 }
3925                         }
3926                         nl = addword(name, nl);
3927                 }
3928         }
3929         closedir(dirp);
3930         DELETE(dp);
3931         DELETE(gp);
3932 }
3933
3934 /*
3935  * generate a pathname as below.
3936  * start..end1 / middle end
3937  * the slashes come for free
3938  */
3939 static char *generate(start1, end1, middle, end)
3940 char *start1;
3941 register char *end1;
3942 char *middle, *end;
3943 {
3944         char *p;
3945         register char *op, *xp;
3946
3947         p = op =
3948                 space((int) (end1 - start1) + strlen(middle) + strlen(end) + 2);
3949         for (xp = start1; xp != end1;)
3950                 *op++ = *xp++;
3951         for (xp = middle; (*op++ = *xp++) != '\0';);
3952         op--;
3953         for (xp = end; (*op++ = *xp++) != '\0';);
3954         return (p);
3955 }
3956
3957 static int anyspcl(wb)
3958 register struct wdblock *wb;
3959 {
3960         register int i;
3961         register char **wd;
3962
3963         wd = wb->w_words;
3964         for (i = 0; i < wb->w_nword; i++)
3965                 if (anys(spcl, *wd++))
3966                         return (1);
3967         return (0);
3968 }
3969
3970 static int xstrcmp(p1, p2)
3971 char *p1, *p2;
3972 {
3973         return (strcmp(*(char **) p1, *(char **) p2));
3974 }
3975
3976 /* -------- word.c -------- */
3977
3978 static struct wdblock *newword(nw)
3979 register int nw;
3980 {
3981         register struct wdblock *wb;
3982
3983         wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
3984         wb->w_bsize = nw;
3985         wb->w_nword = 0;
3986         return (wb);
3987 }
3988
3989 static struct wdblock *addword(wd, wb)
3990 char *wd;
3991 register struct wdblock *wb;
3992 {
3993         register struct wdblock *wb2;
3994         register int nw;
3995
3996         if (wb == NULL)
3997                 wb = newword(NSTART);
3998         if ((nw = wb->w_nword) >= wb->w_bsize) {
3999                 wb2 = newword(nw * 2);
4000                 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4001                            nw * sizeof(char *));
4002                 wb2->w_nword = nw;
4003                 DELETE(wb);
4004                 wb = wb2;
4005         }
4006         wb->w_words[wb->w_nword++] = wd;
4007         return (wb);
4008 }
4009
4010 static
4011 char **getwords(wb)
4012 register struct wdblock *wb;
4013 {
4014         register char **wd;
4015         register int nb;
4016
4017         if (wb == NULL)
4018                 return ((char **) NULL);
4019         if (wb->w_nword == 0) {
4020                 DELETE(wb);
4021                 return ((char **) NULL);
4022         }
4023         wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4024         memcpy((char *) wd, (char *) wb->w_words, nb);
4025         DELETE(wb);                                     /* perhaps should done by caller */
4026         return (wd);
4027 }
4028
4029 int (*func) (char *, char *);
4030 int globv;
4031
4032 static void glob0(a0, a1, a2, a3)
4033 char *a0;
4034 unsigned a1;
4035 int a2;
4036 int (*a3) (char *, char *);
4037 {
4038         func = a3;
4039         globv = a2;
4040         glob1(a0, a0 + a1 * a2);
4041 }
4042
4043 static void glob1(base, lim)
4044 char *base, *lim;
4045 {
4046         register char *i, *j;
4047         int v2;
4048         char *lptr, *hptr;
4049         int c;
4050         unsigned n;
4051
4052
4053         v2 = globv;
4054
4055   top:
4056         if ((n = (int) (lim - base)) <= v2)
4057                 return;
4058         n = v2 * (n / (2 * v2));
4059         hptr = lptr = base + n;
4060         i = base;
4061         j = lim - v2;
4062         for (;;) {
4063                 if (i < lptr) {
4064                         if ((c = (*func) (i, lptr)) == 0) {
4065                                 glob2(i, lptr -= v2);
4066                                 continue;
4067                         }
4068                         if (c < 0) {
4069                                 i += v2;
4070                                 continue;
4071                         }
4072                 }
4073
4074           begin:
4075                 if (j > hptr) {
4076                         if ((c = (*func) (hptr, j)) == 0) {
4077                                 glob2(hptr += v2, j);
4078                                 goto begin;
4079                         }
4080                         if (c > 0) {
4081                                 if (i == lptr) {
4082                                         glob3(i, hptr += v2, j);
4083                                         i = lptr += v2;
4084                                         goto begin;
4085                                 }
4086                                 glob2(i, j);
4087                                 j -= v2;
4088                                 i += v2;
4089                                 continue;
4090                         }
4091                         j -= v2;
4092                         goto begin;
4093                 }
4094
4095
4096                 if (i == lptr) {
4097                         if (lptr - base >= lim - hptr) {
4098                                 glob1(hptr + v2, lim);
4099                                 lim = lptr;
4100                         } else {
4101                                 glob1(base, lptr);
4102                                 base = hptr + v2;
4103                         }
4104                         goto top;
4105                 }
4106
4107
4108                 glob3(j, lptr -= v2, i);
4109                 j = hptr -= v2;
4110         }
4111 }
4112
4113 static void glob2(i, j)
4114 char *i, *j;
4115 {
4116         register char *index1, *index2, c;
4117         int m;
4118
4119         m = globv;
4120         index1 = i;
4121         index2 = j;
4122         do {
4123                 c = *index1;
4124                 *index1++ = *index2;
4125                 *index2++ = c;
4126         } while (--m);
4127 }
4128
4129 static void glob3(i, j, k)
4130 char *i, *j, *k;
4131 {
4132         register char *index1, *index2, *index3;
4133         int c;
4134         int m;
4135
4136         m = globv;
4137         index1 = i;
4138         index2 = j;
4139         index3 = k;
4140         do {
4141                 c = *index1;
4142                 *index1++ = *index3;
4143                 *index3++ = *index2;
4144                 *index2++ = c;
4145         } while (--m);
4146 }
4147
4148 /* -------- io.c -------- */
4149
4150 /*
4151  * shell IO
4152  */
4153
4154 static int my_getc(int ec)
4155 {
4156         register int c;
4157
4158         if (e.linep > elinep) {
4159                 while ((c = readc()) != '\n' && c);
4160                 err("input line too long");
4161                 gflg++;
4162                 return (c);
4163         }
4164         c = readc();
4165         if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4166                 if (c == '\\') {
4167                         c = readc();
4168                         if (c == '\n' && ec != '\"')
4169                                 return (my_getc(ec));
4170                         c |= QUOTE;
4171                 }
4172         }
4173         return (c);
4174 }
4175
4176 static void unget(c)
4177 int c;
4178 {
4179         if (e.iop >= e.iobase)
4180                 e.iop->peekc = c;
4181 }
4182
4183 static int eofc()
4184 {
4185         return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4186 }
4187
4188 static int readc()
4189 {
4190         register int c;
4191
4192         for (; e.iop >= e.iobase; e.iop--)
4193                 if ((c = e.iop->peekc) != '\0') {
4194                         e.iop->peekc = 0;
4195                         return (c);
4196                 } else {
4197                         if (e.iop->prev != 0) {
4198                                 if ((c = (*e.iop->iofn) (e.iop->argp, e.iop)) != '\0') {
4199                                         if (c == -1) {
4200                                                 e.iop++;
4201                                                 continue;
4202                                         }
4203                                         if (e.iop == iostack)
4204                                                 ioecho(c);
4205                                         return (e.iop->prev = c);
4206                                 } else if (e.iop->task == XIO && e.iop->prev != '\n') {
4207                                         e.iop->prev = 0;
4208                                         if (e.iop == iostack)
4209                                                 ioecho('\n');
4210                                         return '\n';
4211                                 }
4212                         }
4213                         if (e.iop->task == XIO) {
4214                                 if (multiline)
4215                                         return e.iop->prev = 0;
4216                                 if (interactive && e.iop == iostack + 1) {
4217 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4218                                         current_prompt = prompt->value;
4219 #else
4220                                         prs(prompt->value);
4221 #endif
4222                                 }
4223                         }
4224                 }
4225         if (e.iop >= iostack)
4226                 return (0);
4227         leave();
4228         /* NOTREACHED */
4229         return (0);
4230 }
4231
4232 static void ioecho(c)
4233 char c;
4234 {
4235         if (flag['v'])
4236                 write(2, &c, sizeof c);
4237 }
4238
4239 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4240 {
4241         if (++e.iop >= &iostack[NPUSH]) {
4242                 e.iop--;
4243                 err("Shell input nested too deeply");
4244                 gflg++;
4245                 return;
4246         }
4247         e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn;
4248
4249         if (argp->afid != AFID_NOBUF)
4250                 e.iop->argp = argp;
4251         else {
4252                 e.iop->argp = ioargstack + (e.iop - iostack);
4253                 *e.iop->argp = *argp;
4254                 e.iop->argp->afbuf = e.iop == &iostack[0] ? &mainbuf : &sharedbuf;
4255                 if (isatty(e.iop->argp->afile) == 0 &&
4256                         (e.iop == &iostack[0] ||
4257                          lseek(e.iop->argp->afile, 0L, 1) != -1)) {
4258                         if (++bufid == AFID_NOBUF)
4259                                 bufid = AFID_ID;
4260                         e.iop->argp->afid = bufid;
4261                 }
4262         }
4263
4264         e.iop->prev = ~'\n';
4265         e.iop->peekc = 0;
4266         e.iop->xchar = 0;
4267         e.iop->nlcount = 0;
4268         if (fn == filechar || fn == linechar)
4269                 e.iop->task = XIO;
4270         else if (fn == (int (*)(struct ioarg *)) gravechar
4271                          || fn == (int (*)(struct ioarg *)) qgravechar)
4272                 e.iop->task = XGRAVE;
4273         else
4274                 e.iop->task = XOTHER;
4275 }
4276
4277 static struct io *setbase(ip)
4278 struct io *ip;
4279 {
4280         register struct io *xp;
4281
4282         xp = e.iobase;
4283         e.iobase = ip;
4284         return (xp);
4285 }
4286
4287 /*
4288  * Input generating functions
4289  */
4290
4291 /*
4292  * Produce the characters of a string, then a newline, then EOF.
4293  */
4294 static int nlchar(ap)
4295 register struct ioarg *ap;
4296 {
4297         register int c;
4298
4299         if (ap->aword == NULL)
4300                 return (0);
4301         if ((c = *ap->aword++) == 0) {
4302                 ap->aword = NULL;
4303                 return ('\n');
4304         }
4305         return (c);
4306 }
4307
4308 /*
4309  * Given a list of words, produce the characters
4310  * in them, with a space after each word.
4311  */
4312 static int wdchar(ap)
4313 register struct ioarg *ap;
4314 {
4315         register char c;
4316         register char **wl;
4317
4318         if ((wl = ap->awordlist) == NULL)
4319                 return (0);
4320         if (*wl != NULL) {
4321                 if ((c = *(*wl)++) != 0)
4322                         return (c & 0177);
4323                 ap->awordlist++;
4324                 return (' ');
4325         }
4326         ap->awordlist = NULL;
4327         return ('\n');
4328 }
4329
4330 /*
4331  * Return the characters of a list of words,
4332  * producing a space between them.
4333  */
4334 static int dolchar(ap)
4335 register struct ioarg *ap;
4336 {
4337         register char *wp;
4338
4339         if ((wp = *ap->awordlist++) != NULL) {
4340                 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4341                 return (-1);
4342         }
4343         return (0);
4344 }
4345
4346 static int xxchar(ap)
4347 register struct ioarg *ap;
4348 {
4349         register int c;
4350
4351         if (ap->aword == NULL)
4352                 return (0);
4353         if ((c = *ap->aword++) == '\0') {
4354                 ap->aword = NULL;
4355                 return (' ');
4356         }
4357         return (c);
4358 }
4359
4360 /*
4361  * Produce the characters from a single word (string).
4362  */
4363 static int strchar(ap)
4364 register struct ioarg *ap;
4365 {
4366         register int c;
4367
4368         if (ap->aword == NULL || (c = *ap->aword++) == 0)
4369                 return (0);
4370         return (c);
4371 }
4372
4373 /*
4374  * Produce quoted characters from a single word (string).
4375  */
4376 static int qstrchar(ap)
4377 register struct ioarg *ap;
4378 {
4379         register int c;
4380
4381         if (ap->aword == NULL || (c = *ap->aword++) == 0)
4382                 return (0);
4383         return (c | QUOTE);
4384 }
4385
4386 /*
4387  * Return the characters from a file.
4388  */
4389 static int filechar(ap)
4390 register struct ioarg *ap;
4391 {
4392         register int i;
4393         char c;
4394         struct iobuf *bp = ap->afbuf;
4395
4396         if (ap->afid != AFID_NOBUF) {
4397                 if ((i = ap->afid != bp->id) || bp->bufp == bp->ebufp) {
4398                         if (i)
4399                                 lseek(ap->afile, ap->afpos, 0);
4400                         i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4401                         if (i <= 0) {
4402                                 closef(ap->afile);
4403                                 return 0;
4404                         }
4405                         bp->id = ap->afid;
4406                         bp->ebufp = (bp->bufp = bp->buf) + i;
4407                 }
4408                 ap->afpos++;
4409                 return *bp->bufp++ & 0177;
4410         }
4411 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4412         if (interactive && isatty(ap->afile)) {
4413                 static char mycommand[BUFSIZ];
4414                 static int position = 0, size = 0;
4415
4416                 while (size == 0 || position >= size) {
4417                         cmdedit_read_input(current_prompt, mycommand);
4418                         size = strlen(mycommand);
4419                         position = 0;
4420                 }
4421                 c = mycommand[position];
4422                 position++;
4423                 return (c);
4424         } else
4425 #endif
4426         {
4427                 i = safe_read(ap->afile, &c, sizeof(c));
4428                 return (i == sizeof(c) ? c & 0177 : (closef(ap->afile), 0));
4429         }
4430 }
4431
4432 /*
4433  * Return the characters from a here temp file.
4434  */
4435 static int herechar(ap)
4436 register struct ioarg *ap;
4437 {
4438         char c;
4439
4440
4441         if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4442                 close(ap->afile);
4443                 c = 0;
4444         }
4445         return (c);
4446
4447 }
4448
4449 /*
4450  * Return the characters produced by a process (`...`).
4451  * Quote them if required, and remove any trailing newline characters.
4452  */
4453 static int gravechar(ap, iop)
4454 struct ioarg *ap;
4455 struct io *iop;
4456 {
4457         register int c;
4458
4459         if ((c = qgravechar(ap, iop) & ~QUOTE) == '\n')
4460                 c = ' ';
4461         return (c);
4462 }
4463
4464 static int qgravechar(ap, iop)
4465 register struct ioarg *ap;
4466 struct io *iop;
4467 {
4468         register int c;
4469
4470         if (iop->xchar) {
4471                 if (iop->nlcount) {
4472                         iop->nlcount--;
4473                         return ('\n' | QUOTE);
4474                 }
4475                 c = iop->xchar;
4476                 iop->xchar = 0;
4477         } else if ((c = filechar(ap)) == '\n') {
4478                 iop->nlcount = 1;
4479                 while ((c = filechar(ap)) == '\n')
4480                         iop->nlcount++;
4481                 iop->xchar = c;
4482                 if (c == 0)
4483                         return (c);
4484                 iop->nlcount--;
4485                 c = '\n';
4486         }
4487         return (c != 0 ? c | QUOTE : 0);
4488 }
4489
4490 /*
4491  * Return a single command (usually the first line) from a file.
4492  */
4493 static int linechar(ap)
4494 register struct ioarg *ap;
4495 {
4496         register int c;
4497
4498         if ((c = filechar(ap)) == '\n') {
4499                 if (!multiline) {
4500                         closef(ap->afile);
4501                         ap->afile = -1;         /* illegal value */
4502                 }
4503         }
4504         return (c);
4505 }
4506
4507 static void prs(s)
4508 register char *s;
4509 {
4510         if (*s)
4511                 write(2, s, strlen(s));
4512 }
4513
4514 static void prn(u)
4515 unsigned u;
4516 {
4517         prs(itoa(u));
4518 }
4519
4520 static void closef(i)
4521 register int i;
4522 {
4523         if (i > 2)
4524                 close(i);
4525 }
4526
4527 static void closeall()
4528 {
4529         register int u;
4530
4531         for (u = NUFILE; u < NOFILE;)
4532                 close(u++);
4533 }
4534
4535 /*
4536  * remap fd into Shell's fd space
4537  */
4538 static int remap(fd)
4539 register int fd;
4540 {
4541         register int i;
4542         int map[NOFILE];
4543
4544         if (fd < e.iofd) {
4545                 for (i = 0; i < NOFILE; i++)
4546                         map[i] = 0;
4547                 do {
4548                         map[fd] = 1;
4549                         fd = dup(fd);
4550                 } while (fd >= 0 && fd < e.iofd);
4551                 for (i = 0; i < NOFILE; i++)
4552                         if (map[i])
4553                                 close(i);
4554                 if (fd < 0)
4555                         err("too many files open in shell");
4556         }
4557         return (fd);
4558 }
4559
4560 static int openpipe(pv)
4561 register int *pv;
4562 {
4563         register int i;
4564
4565         if ((i = pipe(pv)) < 0)
4566                 err("can't create pipe - try again");
4567         return (i);
4568 }
4569
4570 static void closepipe(pv)
4571 register int *pv;
4572 {
4573         if (pv != NULL) {
4574                 close(*pv++);
4575                 close(*pv);
4576         }
4577 }
4578
4579 /* -------- here.c -------- */
4580
4581 /*
4582  * here documents
4583  */
4584
4585 static void markhere(s, iop)
4586 register char *s;
4587 struct ioword *iop;
4588 {
4589         register struct here *h, *lh;
4590
4591         h = (struct here *) space(sizeof(struct here));
4592         if (h == 0)
4593                 return;
4594         h->h_tag = evalstr(s, DOSUB);
4595         if (h->h_tag == 0)
4596                 return;
4597         h->h_iop = iop;
4598         iop->io_name = 0;
4599         h->h_next = NULL;
4600         if (inhere == 0)
4601                 inhere = h;
4602         else
4603                 for (lh = inhere; lh != NULL; lh = lh->h_next)
4604                         if (lh->h_next == 0) {
4605                                 lh->h_next = h;
4606                                 break;
4607                         }
4608         iop->io_flag |= IOHERE | IOXHERE;
4609         for (s = h->h_tag; *s; s++)
4610                 if (*s & QUOTE) {
4611                         iop->io_flag &= ~IOXHERE;
4612                         *s &= ~QUOTE;
4613                 }
4614         h->h_dosub = iop->io_flag & IOXHERE;
4615 }
4616
4617 static void gethere()
4618 {
4619         register struct here *h, *hp;
4620
4621         /* Scan here files first leaving inhere list in place */
4622         for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
4623                 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
4624
4625         /* Make inhere list active - keep list intact for scraphere */
4626         if (hp != NULL) {
4627                 hp->h_next = acthere;
4628                 acthere = inhere;
4629                 inhere = NULL;
4630         }
4631 }
4632
4633 static void readhere(name, s, ec)
4634 char **name;
4635 register char *s;
4636 int ec;
4637 {
4638         int tf;
4639         char tname[30] = ".msh_XXXXXX";
4640         register int c;
4641         jmp_buf ev;
4642         char myline[LINELIM + 1];
4643         char *thenext;
4644
4645         tf = mkstemp(tname);
4646         if (tf < 0)
4647                 return;
4648         *name = strsave(tname, areanum);
4649         if (newenv(setjmp(errpt = ev)) != 0)
4650                 unlink(tname);
4651         else {
4652                 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
4653                 e.iobase = e.iop;
4654                 for (;;) {
4655                         if (interactive && e.iop <= iostack) {
4656 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4657                                 current_prompt = cprompt->value;
4658 #else
4659                                 prs(cprompt->value);
4660 #endif
4661                         }
4662                         thenext = myline;
4663                         while ((c = my_getc(ec)) != '\n' && c) {
4664                                 if (ec == '\'')
4665                                         c &= ~QUOTE;
4666                                 if (thenext >= &myline[LINELIM]) {
4667                                         c = 0;
4668                                         break;
4669                                 }
4670                                 *thenext++ = c;
4671                         }
4672                         *thenext = 0;
4673                         if (strcmp(s, myline) == 0 || c == 0)
4674                                 break;
4675                         *thenext++ = '\n';
4676                         write(tf, myline, (int) (thenext - myline));
4677                 }
4678                 if (c == 0) {
4679                         prs("here document `");
4680                         prs(s);
4681                         err("' unclosed");
4682                 }
4683                 quitenv();
4684         }
4685         close(tf);
4686 }
4687
4688 /*
4689  * open here temp file.
4690  * if unquoted here, expand here temp file into second temp file.
4691  */
4692 static int herein(hname, xdoll)
4693 char *hname;
4694 int xdoll;
4695 {
4696         register int hf;
4697         int tf;
4698
4699 #if __GNUC__
4700         /* Avoid longjmp clobbering */
4701         (void) &tf;
4702 #endif
4703         if (hname == 0)
4704                 return (-1);
4705         hf = open(hname, 0);
4706         if (hf < 0)
4707                 return (-1);
4708         if (xdoll) {
4709                 char c;
4710                 char tname[30] = ".msh_XXXXXX";
4711                 jmp_buf ev;
4712
4713                 tf = mkstemp(tname);
4714                 if (tf < 0)
4715                         return (-1);
4716                 if (newenv(setjmp(errpt = ev)) == 0) {
4717                         PUSHIO(afile, hf, herechar);
4718                         setbase(e.iop);
4719                         while ((c = subgetc(0, 0)) != 0) {
4720                                 c &= ~QUOTE;
4721                                 write(tf, &c, sizeof c);
4722                         }
4723                         quitenv();
4724                 } else
4725                         unlink(tname);
4726                 close(tf);
4727                 tf = open(tname, 0);
4728                 unlink(tname);
4729                 return (tf);
4730         } else
4731                 return (hf);
4732 }
4733
4734 static void scraphere()
4735 {
4736         register struct here *h;
4737
4738         for (h = inhere; h != NULL; h = h->h_next) {
4739                 if (h->h_iop && h->h_iop->io_name)
4740                         unlink(h->h_iop->io_name);
4741         }
4742         inhere = NULL;
4743 }
4744
4745 /* unlink here temp files before a freearea(area) */
4746 static void freehere(area)
4747 int area;
4748 {
4749         register struct here *h, *hl;
4750
4751         hl = NULL;
4752         for (h = acthere; h != NULL; h = h->h_next)
4753                 if (getarea((char *) h) >= area) {
4754                         if (h->h_iop->io_name != NULL)
4755                                 unlink(h->h_iop->io_name);
4756                         if (hl == NULL)
4757                                 acthere = h->h_next;
4758                         else
4759                                 hl->h_next = h->h_next;
4760                 } else
4761                         hl = h;
4762 }
4763
4764
4765
4766 /*
4767  * Copyright (c) 1987,1997, Prentice Hall
4768  * All rights reserved.
4769  *
4770  * Redistribution and use of the MINIX operating system in source and
4771  * binary forms, with or without modification, are permitted provided
4772  * that the following conditions are met:
4773  *
4774  * Redistributions of source code must retain the above copyright
4775  * notice, this list of conditions and the following disclaimer.
4776  *
4777  * Redistributions in binary form must reproduce the above
4778  * copyright notice, this list of conditions and the following
4779  * disclaimer in the documentation and/or other materials provided
4780  * with the distribution.
4781  *
4782  * Neither the name of Prentice Hall nor the names of the software
4783  * authors or contributors may be used to endorse or promote
4784  * products derived from this software without specific prior
4785  * written permission.
4786  *
4787  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
4788  * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
4789  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
4790  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
4791  * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
4792  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
4793  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
4794  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
4795  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
4796  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
4797  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
4798  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4799  *
4800  */