1 /* vi: set sw=4 ts=4: */
3 * Minix shell port for busybox
5 * This version of the Minix shell was adapted for use in busybox
6 * by Erik Andersen <andersen@codepoet.org>
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>
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.
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.
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
27 * Original copyright notice is retained at the end of this file.
44 #include <sys/times.h>
45 #include <sys/types.h>
52 /* Conditional use of "register" keyword */
53 #define REGISTER register
56 /*#define MSHDEBUG 1*/
61 #define DBGPRINTF(x) if(mshdbg>0)printf x
62 #define DBGPRINTF0(x) if(mshdbg>0)printf x
63 #define DBGPRINTF1(x) if(mshdbg>1)printf x
64 #define DBGPRINTF2(x) if(mshdbg>2)printf x
65 #define DBGPRINTF3(x) if(mshdbg>3)printf x
66 #define DBGPRINTF4(x) if(mshdbg>4)printf x
67 #define DBGPRINTF5(x) if(mshdbg>5)printf x
68 #define DBGPRINTF6(x) if(mshdbg>6)printf x
69 #define DBGPRINTF7(x) if(mshdbg>7)printf x
70 #define DBGPRINTF8(x) if(mshdbg>8)printf x
71 #define DBGPRINTF9(x) if(mshdbg>9)printf x
75 #define RCPRINTF(x) if(mshdbg_rc)printf x
96 /* -------- sh.h -------- */
102 #define NPUSH 8 /* limit to input nesting */
105 #define NOFILE 20 /* Number of open files */
106 #define NUFILE 10 /* Number of user-accessible files */
107 #define FDBASE 10 /* First file usable by Shell */
110 * values returned by wait
112 #define WAITSIG(s) ((s)&0177)
113 #define WAITVAL(s) (((s)>>8)&0377)
114 #define WAITCORE(s) (((s)&0200)!=0)
117 * library and system definitions
119 typedef void xint; /* base type of jmp_buf, for not broken compilers */
127 #define NOBLOCK ((struct op *)NULL)
128 #define NOWORD ((char *)NULL)
129 #define NOWORDS ((char **)NULL)
130 #define NOPIPE ((int *)NULL)
133 * Description of a command or an operation on commands.
134 * Might eventually use a union.
137 int type; /* operation type, see below */
138 char **words; /* arguments to a command */
139 struct ioword **ioact; /* IO actions (eg, < > >>) */
142 char *str; /* identifier for case and for */
145 #define TCOM 1 /* command */
146 #define TPAREN 2 /* (c-list) */
147 #define TPIPE 3 /* a | b */
148 #define TLIST 4 /* a [&;] b */
149 #define TOR 5 /* || */
150 #define TAND 6 /* && */
158 #define TPAT 14 /* pattern in case */
159 #define TBRACE 15 /* {c-list} */
160 #define TASYNC 16 /* c & */
161 /* Added to support "." file expansion */
164 /* Strings for names to make debug easier */
166 static char *T_CMD_NAMES[] = {
189 * actions determining the environment of a process
191 #define BIT(i) (1<<(i))
192 #define FEXEC BIT(0) /* execute without forking */
194 #if 0 /* Original value */
195 #define AREASIZE (65000)
197 #define AREASIZE (90000)
201 * flags to control evaluation of words
203 #define DOSUB 1 /* interpret $, `, and quotes */
204 #define DOBLANK 2 /* perform blank interpretation */
205 #define DOGLOB 4 /* interpret [?* */
206 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
207 #define DOTRIM 16 /* trim resulting string */
209 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
213 static int newfile(char *s);
214 static char *findeq(char *cp);
215 static char *cclass(char *p, int sub);
216 static void initarea(void);
217 extern int msh_main(int argc, char **argv);
222 struct brkcon *nextlev;
230 short io_unit; /* unit affected */
231 short io_flag; /* action (below) */
232 char *io_name; /* file name */
235 #define IOREAD 1 /* < */
236 #define IOHERE 2 /* << (here file) */
237 #define IOWRITE 4 /* > */
238 #define IOCAT 8 /* >> */
239 #define IOXHERE 16 /* ${}, ` in << */
240 #define IODUP 32 /* >&digit */
241 #define IOCLOSE 64 /* >&- */
243 #define IODEFAULT (-1) /* token for default IO unit */
248 * parsing & execution environment
254 xint *errpt; /* void * */
262 * -k: look for name=value everywhere on command line
264 * -t: exit after reading and executing one command
267 * -u: unset variables net diagnostic
271 static char *null; /* null value for variable */
272 static int intr; /* interrupt pending */
274 static char *trap[_NSIG + 1];
275 static char ourtrap[_NSIG + 1];
276 static int trapset; /* trap pending */
278 static int heedint; /* heed interrupt signals */
280 static int yynerrs; /* yacc */
282 static char line[LINELIM];
289 static int (*inbuilt(char *s)) (struct op *);
291 static char *rexecve(char *c, char **v, char **envp);
292 static char *space(int n);
293 static char *strsave(char *s, int a);
294 static char *evalstr(char *cp, int f);
295 static char *putn(int n);
296 static char *itoa(int n);
297 static char *unquote(char *as);
298 static struct var *lookup(char *n);
299 static int rlookup(char *n);
300 static struct wdblock *glob(char *cp, struct wdblock *wb);
301 static int my_getc(int ec);
302 static int subgetc(int ec, int quoted);
303 static char **makenv(int all, struct wdblock *wb);
304 static char **eval(char **ap, int f);
305 static int setstatus(int s);
306 static int waitfor(int lastpid, int canintr);
308 static void onintr(int s); /* SIGINT handler */
310 static int newenv(int f);
311 static void quitenv(void);
312 static void err(char *s);
313 static int anys(char *s1, char *s2);
314 static int any(int c, char *s);
315 static void next(int f);
316 static void setdash(void);
317 static void onecommand(void);
318 static void runtrap(int i);
319 static int gmatch(char *s, char *p);
325 static void leave(void); /* abort shell (or fail in subshell) */
326 static void fail(void); /* fail but return to process next command */
327 static void warn(char *s);
328 static void sig(int i); /* default signal handler */
332 /* -------- area stuff -------- */
334 #define REGSIZE sizeof(struct region)
336 /* #define SHRINKBY (64) */
340 #define ALIGN (sizeof(int)-1)
350 /* -------- grammar stuff -------- */
375 /* Added for "." file expansion */
378 #define YYERRCODE 300
381 #define CONTIN 01 /* skip new lines to complete command */
383 #define SYNTAXERR zzerr()
385 static struct op *pipeline(int cf);
386 static struct op *andor(void);
387 static struct op *c_list(void);
388 static int synio(int cf);
389 static void musthave(int c, int cf);
390 static struct op *simple(void);
391 static struct op *nested(int type, int mark);
392 static struct op *command(int cf);
393 static struct op *dogroup(int onlydone);
394 static struct op *thenpart(void);
395 static struct op *elsepart(void);
396 static struct op *caselist(void);
397 static struct op *casepart(void);
398 static char **pattern(void);
399 static char **wordlist(void);
400 static struct op *list(struct op *t1, struct op *t2);
401 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
402 static struct op *newtp(void);
403 static struct op *namelist(struct op *t);
404 static char **copyw(void);
405 static void word(char *cp);
406 static struct ioword **copyio(void);
407 static struct ioword *io(int u, int f, char *cp);
408 static void zzerr(void);
409 static void yyerror(char *s);
410 static int yylex(int cf);
411 static int collect(int c, int c1);
412 static int dual(int c);
413 static void diag(int ec);
414 static char *tree(unsigned size);
416 /* -------- var.h -------- */
425 #define COPYV 1 /* flag to setval, suggesting copy */
426 #define RONLY 01 /* variable is read-only */
427 #define EXPORT 02 /* variable is to be exported */
428 #define GETCELL 04 /* name & value space was got with getcell */
430 static int yyparse(void);
431 static struct var *lookup(char *n);
432 static void setval(struct var *vp, char *val);
433 static void nameval(struct var *vp, char *val, char *name);
434 static void export(struct var *vp);
435 static void ronly(struct var *vp);
436 static int isassign(char *s);
437 static int checkname(char *cp);
438 static int assign(char *s, int cf);
439 static void putvlist(int f, int out);
440 static int eqname(char *n1, char *n2);
442 static int execute(struct op *t, int *pin, int *pout, int act);
445 /* -------- io.h -------- */
448 unsigned id; /* buffer id */
449 char buf[512]; /* buffer */
450 char *bufp; /* pointer into buffer */
451 char *ebufp; /* pointer to end of buffer */
454 /* possible arguments to an IO function */
458 int afile; /* file descriptor */
459 unsigned afid; /* buffer id */
460 long afpos; /* file position */
461 struct iobuf *afbuf; /* buffer for this file */
464 //static struct ioarg ioargstack[NPUSH];
465 #define AFID_NOBUF (~0)
468 /* an input generator's state */
470 int (*iofn) (struct ioarg *, struct io *);
473 char prev; /* previous character read by readc() */
474 char nlcount; /* for `'s */
475 char xchar; /* for `'s */
476 char task; /* reason for pushed IO */
479 //static struct io iostack[NPUSH];
480 #define XOTHER 0 /* none of the below */
481 #define XDOLL 1 /* expanding ${} */
482 #define XGRAVE 2 /* expanding `'s */
483 #define XIO 3 /* file IO */
485 /* in substitution */
486 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
490 * input generators for IO structure
492 static int nlchar(struct ioarg *ap);
493 static int strchar(struct ioarg *ap);
494 static int qstrchar(struct ioarg *ap);
495 static int filechar(struct ioarg *ap);
496 static int herechar(struct ioarg *ap);
497 static int linechar(struct ioarg *ap);
498 static int gravechar(struct ioarg *ap, struct io *iop);
499 static int qgravechar(struct ioarg *ap, struct io *iop);
500 static int dolchar(struct ioarg *ap);
501 static int wdchar(struct ioarg *ap);
502 static void scraphere(void);
503 static void freehere(int area);
504 static void gethere(void);
505 static void markhere(char *s, struct ioword *iop);
506 static int herein(char *hname, int xdoll);
507 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
513 static int eofc(void);
514 static int readc(void);
515 static void unget(int c);
516 static void ioecho(int c);
517 static void prs(const char *s);
518 static void prn(unsigned u);
519 static void closef(int i);
520 static void closeall(void);
526 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
527 static int remap(int fd);
528 static int openpipe(int *pv);
529 static void closepipe(int *pv);
530 static struct io *setbase(struct io *ip);
532 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)),pushio(&temparg,(gen)))
533 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
535 /* -------- word.h -------- */
537 #define NSTART 16 /* default number of words to allow for initially */
542 /* bounds are arbitrary */
546 static struct wdblock *addword(char *wd, struct wdblock *wb);
547 static struct wdblock *newword(int nw);
548 static char **getwords(struct wdblock *wb);
550 /* -------- area.h -------- */
555 static char *getcell(unsigned nbytes);
556 static void garbage(void);
557 static void setarea(char *cp, int a);
558 static int getarea(char *cp);
559 static void freearea(int a);
560 static void freecell(char *cp);
561 static int areanum; /* current allocation area */
563 #define NEW(type) (type *)getcell(sizeof(type))
564 #define DELETE(obj) freecell((char *)obj)
567 /* -------- misc stuff -------- */
569 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
570 static int iosetup(struct ioword *iop, int pipein, int pipeout);
571 static void echo(char **wp);
572 static struct op **find1case(struct op *t, char *w);
573 static struct op *findcase(struct op *t, char *w);
574 static void brkset(struct brkcon *bc);
575 static int dolabel(struct op *t);
576 static int dohelp(struct op *t);
577 static int dochdir(struct op *t);
578 static int doshift(struct op *t);
579 static int dologin(struct op *t);
580 static int doumask(struct op *t);
581 static int doexec(struct op *t);
582 static int dodot(struct op *t);
583 static int dowait(struct op *t);
584 static int doread(struct op *t);
585 static int doeval(struct op *t);
586 static int dotrap(struct op *t);
587 static int getsig(char *s);
588 static void setsig(int n, sighandler_t f);
589 static int getn(char *as);
590 static int dobreak(struct op *t);
591 static int docontinue(struct op *t);
592 static int brkcontin(char *cp, int val);
593 static int doexit(struct op *t);
594 static int doexport(struct op *t);
595 static int doreadonly(struct op *t);
596 static void rdexp(char **wp, void (*f) (struct var *), int key);
597 static void badid(char *s);
598 static int doset(struct op *t);
599 static void varput(char *s, int out);
600 static int dotimes(struct op *t);
601 static int expand(char *cp, struct wdblock **wbp, int f);
602 static char *blank(int f);
603 static int dollar(int quoted);
604 static int grave(int quoted);
605 static void globname(char *we, char *pp);
606 static char *generate(char *start1, char *end1, char *middle, char *end);
607 static int anyspcl(struct wdblock *wb);
608 static int xstrcmp(char *p1, char *p2);
609 static void glob0(char *a0, unsigned int a1, int a2,
610 int (*a3) (char *, char *));
611 static void glob1(char *base, char *lim);
612 static void glob2(char *i, char *j);
613 static void glob3(char *i, char *j, char *k);
614 static void readhere(char **name, char *s, int ec);
615 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
616 static int xxchar(struct ioarg *ap);
621 struct ioword *h_iop;
625 static const char * const signame[] = {
628 (char *) NULL, /* interrupt */
630 "Illegal instruction",
634 "Floating Point Exception",
639 (char *) NULL, /* broken pipe */
644 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
650 static const struct res restab[] = {
676 int (*builtinfunc) (struct op * t);
678 static const struct builtincmd builtincmds[] = {
683 {"continue", docontinue},
687 {"export", doexport},
692 {"readonly", doreadonly},
702 static struct op *scantree(struct op *);
703 static struct op *dowholefile(int, int);
706 extern char **environ; /* environment pointer */
712 static int interactive; /* Is this an interactive shell */
714 static int multiline; /* \n changed to ; */
715 static struct op *outtree; /* result from parser */
718 static struct brkcon *brklist;
720 static struct wdblock *wdlist;
721 static struct wdblock *iolist;
722 static char *trap[_NSIG + 1];
723 static char ourtrap[_NSIG + 1];
724 static int trapset; /* trap pending */
725 static int yynerrs; /* yacc */
726 static char line[LINELIM];
729 static struct var *mshdbg_var;
731 static struct var *vlist; /* dictionary */
732 static struct var *homedir; /* home directory */
733 static struct var *prompt; /* main prompt */
734 static struct var *cprompt; /* continuation prompt */
735 static struct var *path; /* search path for commands */
736 static struct var *shell; /* shell to interpret command files */
737 static struct var *ifs; /* field separators */
739 static int areanum; /* current allocation area */
742 static char flags['z' - 'a' + 1];
743 static char *flag = flags - 'a';
744 static char *null = "";
745 static int heedint = 1;
746 static void (*qflag) (int) = SIG_IGN;
750 static int iounit = IODEFAULT;
751 static YYSTYPE yylval;
752 static char *elinep = line + sizeof(line) - 5;
754 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
755 static struct ioarg ioargstack[NPUSH];
756 static struct io iostack[NPUSH];
757 static struct iobuf sharedbuf = { AFID_NOBUF };
758 static struct iobuf mainbuf = { AFID_NOBUF };
759 static unsigned bufid = AFID_ID; /* buffer id counter */
761 static struct here *inhere; /* list of hear docs while parsing */
762 static struct here *acthere; /* list of active here documents */
763 static struct region *areabot; /* bottom of area */
764 static struct region *areatop; /* top of area */
765 static struct region *areanxt; /* starting point of scan */
767 static void *brkaddr;
769 static struct env e = {
770 line, /* linep: char ptr */
771 iostack, /* iobase: struct io ptr */
772 iostack - 1, /* iop: struct io ptr */
773 (xint *) NULL, /* errpt: void ptr for errors? */
774 FDBASE, /* iofd: file desc */
775 (struct env *) NULL /* oenv: struct env ptr */
779 void print_t(struct op *t)
781 DBGPRINTF(("T: t=0x%x, type %s, words=0x%x, IOword=0x%x\n", t,
782 T_CMD_NAMES[t->type], t->words, t->ioact));
785 DBGPRINTF(("T: W1: %s", t->words[0]));
791 void print_tree(struct op *head)
794 DBGPRINTF(("PRINT_TREE: no tree\n"));
798 DBGPRINTF(("NODE: 0x%x, left 0x%x, right 0x%x\n", head, head->left,
802 print_tree(head->left);
805 print_tree(head->right);
809 #endif /* MSHDEBUG */
812 #ifdef CONFIG_FEATURE_COMMAND_EDITING
813 static char *current_prompt;
816 /* -------- sh.c -------- */
822 int msh_main(int argc, char **argv)
828 int (*iof) (struct ioarg *);
830 DBGPRINTF(("MSH_MAIN: argc %d, environ 0x%x\n", argc, environ));
833 if ((ap = environ) != NULL) {
835 assign(*ap++, !COPYV);
836 for (ap = environ; *ap;)
837 export(lookup(*ap++));
842 shell = lookup("SHELL");
843 if (shell->value == null)
844 setval(shell, (char *)DEFAULT_SHELL);
847 homedir = lookup("HOME");
848 if (homedir->value == null)
849 setval(homedir, "/");
852 setval(lookup("$"), putn(getpid()));
854 path = lookup("PATH");
855 if (path->value == null) {
857 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
859 setval(path, "/bin:/usr/bin");
864 if (ifs->value == null)
865 setval(ifs, " \t\n");
868 mshdbg_var = lookup("MSHDEBUG");
869 if (mshdbg_var->value == null)
870 setval(mshdbg_var, "0");
874 prompt = lookup("PS1");
875 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
876 if (prompt->value == null)
878 setval(prompt, "$ ");
879 if (geteuid() == 0) {
880 setval(prompt, "# ");
881 prompt->status &= ~EXPORT;
883 cprompt = lookup("PS2");
884 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
885 if (cprompt->value == null)
887 setval(cprompt, "> ");
893 if (argv[0][0] == '-' && argv[0][1] != '\0') {
894 for (s = argv[0] + 1; *s; s++)
897 prompt->status &= ~EXPORT;
898 cprompt->status &= ~EXPORT;
903 PUSHIO(aword, *++argv, iof = nlchar);
915 prompt->status &= ~EXPORT;
923 if (*s >= 'a' && *s <= 'z')
931 if (iof == filechar && --argc > 0) {
934 prompt->status &= ~EXPORT;
935 cprompt->status &= ~EXPORT;
937 /* Shell is non-interactive, activate printf-based debug */
939 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
943 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
945 if (newfile(name = *++argv))
946 exit(1); /* Exit on error */
952 /* This won't be true if PUSHIO has been called, say from newfile() above */
953 if (e.iop < iostack) {
954 PUSHIO(afile, 0, iof);
955 if (isatty(0) && isatty(1) && !cflag) {
957 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
959 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
961 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
963 printf("Enter 'help' for a list of built-in commands.\n\n");
968 signal(SIGQUIT, qflag);
969 if (name && name[0] == '-') {
971 if ((f = open(".profile", 0)) >= 0)
973 if ((f = open("/etc/profile", 0)) >= 0)
977 signal(SIGTERM, sig);
979 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
980 signal(SIGINT, onintr);
985 for (ap = ++argv; --argc > 0;) {
986 if (assign(*ap = *argv++, !COPYV)) {
987 dolc--; /* keyword */
993 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
995 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop 0x%x, iostack 0x%x\n", interactive, e.iop, iostack));
998 if (interactive && e.iop <= iostack) {
999 #ifdef CONFIG_FEATURE_COMMAND_EDITING
1000 current_prompt = prompt->value;
1006 /* Ensure that getenv("PATH") stays current */
1007 setenv("PATH", path->value, 1);
1010 DBGPRINTF(("MSH_MAIN: returning.\n"));
1013 static void setdash()
1017 char m['z' - 'a' + 1];
1020 for (c = 'a'; c <= 'z'; c++)
1024 setval(lookup("-"), m);
1027 static int newfile(s)
1032 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1034 if (strcmp(s, "-") != 0) {
1035 DBGPRINTF(("NEWFILE: s is %s\n", s));
1039 err(": cannot open");
1050 struct op *scantree(head)
1058 if (head->left != NULL) {
1059 dotnode = scantree(head->left);
1064 if (head->right != NULL) {
1065 dotnode = scantree(head->right);
1070 if (head->words == NULL)
1073 DBGPRINTF5(("SCANTREE: checking node 0x%x\n", head));
1075 if ((head->type != TDOT) && (strcmp(".", head->words[0]) == 0)) {
1076 DBGPRINTF5(("SCANTREE: dot found in node 0x%x\n", head));
1084 static void onecommand()
1089 DBGPRINTF(("ONECOMMAND: enter, outtree=0x%x\n", outtree));
1108 setjmp(failpt = m1); /* Bruce Evans' fix */
1109 if (setjmp(failpt = m1) || yyparse() || intr) {
1111 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1116 if (!interactive && intr)
1129 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=0x%x\n",
1131 execute(outtree, NOPIPE, NOPIPE, 0);
1134 if (!interactive && intr) {
1139 if ((i = trapset) != 0) {
1153 DBGPRINTF(("LEAVE: leave called!\n"));
1185 longjmp(e.errpt, 1);
1187 e.iop = e.iobase = iostack;
1190 static int newenv(f)
1193 REGISTER struct env *ep;
1195 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1202 ep = (struct env *) space(sizeof(*ep));
1215 static void quitenv()
1217 REGISTER struct env *ep;
1220 DBGPRINTF(("QUITENV: e.oenv=0x%x\n", e.oenv));
1222 if ((ep = e.oenv) != NULL) {
1225 /* should close `'d files */
1227 while (--fd >= e.iofd)
1233 * Is any character from s1 in s2?
1235 static int anys(s1, s2)
1236 REGISTER char *s1, *s2;
1245 * Is character c in s?
1247 static int any(c, s)
1257 static char *putn(n)
1263 static char *itoa(n)
1268 snprintf(s, sizeof(s), "%u", n);
1273 static void next(int f)
1275 PUSHIO(afile, f, filechar);
1278 static void onintr(s)
1279 int s; /* ANSI C requires a parameter */
1281 signal(SIGINT, onintr);
1288 } else if (heedint) {
1294 static char *space(n)
1299 if ((cp = getcell(n)) == 0)
1300 err("out of string space");
1304 static char *strsave(s, a)
1308 REGISTER char *cp, *xp;
1310 if ((cp = space(strlen(s) + 1)) != NULL) {
1311 setarea((char *) cp, a);
1312 for (xp = cp; (*xp++ = *s++) != '\0';);
1328 static void runtrap(i)
1333 if ((trapstr = trap[i]) == NULL)
1339 RUN(aword, trapstr, nlchar);
1342 /* -------- var.c -------- */
1345 * Find the given name in the dictionary
1346 * and return its value. If the name was
1347 * not previously there, enter it now and
1348 * return a null value.
1350 static struct var *lookup(n)
1353 REGISTER struct var *vp;
1356 static struct var dummy;
1360 for (c = 0; isdigit(*n) && c < 1000; n++)
1361 c = c * 10 + *n - '0';
1362 dummy.status = RONLY;
1363 dummy.value = c <= dolc ? dolv[c] : null;
1366 for (vp = vlist; vp; vp = vp->next)
1367 if (eqname(vp->name, n))
1370 vp = (struct var *) space(sizeof(*vp));
1371 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1372 dummy.name = dummy.value = "";
1375 for (cp = vp->name; (*cp = *n++) && *cp != '='; cp++);
1379 setarea((char *) vp, 0);
1380 setarea((char *) vp->name, 0);
1383 vp->status = GETCELL;
1389 * give variable at `vp' the value `val'.
1391 static void setval(vp, val)
1395 nameval(vp, val, (char *) NULL);
1399 * if name is not NULL, it must be
1400 * a prefix of the space `val',
1402 * this is all so that exporting
1403 * values is reasonably painless.
1405 static void nameval(vp, val, name)
1406 REGISTER struct var *vp;
1409 REGISTER char *cp, *xp;
1413 if (vp->status & RONLY) {
1414 for (xp = vp->name; *xp && *xp != '=';)
1415 putc(*xp++, stderr);
1416 err(" is read-only");
1421 xp = space(strlen(vp->name) + strlen(val) + 2);
1424 /* make string: name=value */
1425 setarea((char *) xp, 0);
1427 for (cp = vp->name; (*xp = *cp++) && *xp != '='; xp++);
1431 for (cp = val; (*xp++ = *cp++) != '\0';);
1435 if (vp->status & GETCELL)
1436 freecell(vp->name); /* form new string `name=value' */
1442 static void export(vp)
1445 vp->status |= EXPORT;
1448 static void ronly(vp)
1451 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1452 vp->status |= RONLY;
1455 static int isassign(s)
1458 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1460 if (!isalpha((int) *s) && *s != '_')
1462 for (; *s != '='; s++)
1463 if (*s == 0 || (!isalnum(*s) && *s != '_'))
1469 static int assign(s, cf)
1476 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1478 if (!isalpha(*s) && *s != '_')
1480 for (cp = s; *cp != '='; cp++)
1481 if (*cp == 0 || (!isalnum(*cp) && *cp != '_'))
1484 nameval(vp, ++cp, cf == COPYV ? (char *) NULL : s);
1486 vp->status &= ~GETCELL;
1490 static int checkname(cp)
1493 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1495 if (!isalpha(*cp++) && *(cp - 1) != '_')
1498 if (!isalnum(*cp++) && *(cp - 1) != '_')
1503 static void putvlist(f, out)
1504 REGISTER int f, out;
1506 REGISTER struct var *vp;
1508 for (vp = vlist; vp; vp = vp->next)
1509 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1510 if (vp->status & EXPORT)
1511 write(out, "export ", 7);
1512 if (vp->status & RONLY)
1513 write(out, "readonly ", 9);
1514 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1515 write(out, "\n", 1);
1519 static int eqname(n1, n2)
1520 REGISTER char *n1, *n2;
1522 for (; *n1 != '=' && *n1 != 0; n1++)
1525 return (*n2 == 0 || *n2 == '=');
1528 static char *findeq(cp)
1531 while (*cp != '\0' && *cp != '=')
1536 /* -------- gmatch.c -------- */
1538 * int gmatch(string, pattern)
1539 * char *string, *pattern;
1541 * Match a pattern as in sh(1).
1546 #define QMASK (CMASK&~QUOTE)
1547 #define NOT '!' /* might use ^ */
1549 static int gmatch(s, p)
1550 REGISTER char *s, *p;
1552 REGISTER int sc, pc;
1554 if (s == NULL || p == NULL)
1556 while ((pc = *p++ & CMASK) != '\0') {
1560 if ((p = cclass(p, sc)) == NULL)
1572 if (*p == '\0' || gmatch(s, p))
1574 } while (*s++ != '\0');
1578 if (sc != (pc & ~QUOTE))
1585 static char *cclass(p, sub)
1589 REGISTER int c, d, not, found;
1591 if ((not = *p == NOT) != 0)
1596 return ((char *) NULL);
1598 if (p[1] == '-' && p[2] != ']') {
1603 if (c == sub || (c <= sub && sub <= d))
1605 } while (*++p != ']');
1606 return (found ? p + 1 : (char *) NULL);
1610 /* -------- area.c -------- */
1613 * All memory between (char *)areabot and (char *)(areatop+1) is
1614 * exclusively administered by the area management routines.
1615 * It is assumed that sbrk() and brk() manipulate the high end.
1618 #define sbrk(X) ({ void * __q = (void *)-1; if (brkaddr + (int)(X) < brktop) { __q = brkaddr; brkaddr+=(int)(X); } __q;})
1620 static void initarea()
1622 brkaddr = malloc(AREASIZE);
1623 brktop = brkaddr + AREASIZE;
1625 while ((long) sbrk(0) & ALIGN)
1627 areabot = (struct region *) sbrk(REGSIZE);
1629 areabot->next = areabot;
1630 areabot->area = BUSY;
1635 char *getcell(nbytes)
1638 REGISTER int nregio;
1639 REGISTER struct region *p, *q;
1646 /* silly and defeats the algorithm */
1648 * round upwards and add administration area
1650 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
1651 for (p = areanxt;;) {
1652 if (p->area > areanum) {
1656 while ((q = p->next)->area > areanum && q != areanxt)
1659 * exit loop if cell big enough
1661 if (q >= p + nregio)
1668 i = nregio >= GROWBY ? nregio : GROWBY;
1669 p = (struct region *) sbrk(i * REGSIZE);
1670 if (p == (struct region *) -1)
1671 return ((char *) NULL);
1675 abort(); /* allocated areas are contiguous */
1685 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
1687 areanxt = p + nregio;
1690 * split into requested area and rest
1692 if (areanxt + 1 > q) {
1694 abort(); /* insufficient space left for admin */
1697 areanxt->area = FREE;
1701 return ((char *) (p + 1));
1704 static void freecell(cp)
1707 REGISTER struct region *p;
1709 if ((p = (struct region *) cp) != NULL) {
1717 static void freearea(a)
1720 REGISTER struct region *p, *top;
1723 for (p = areabot; p != top; p = p->next)
1728 static void setarea(cp, a)
1732 REGISTER struct region *p;
1734 if ((p = (struct region *) cp) != NULL)
1741 return ((struct region *) cp - 1)->area;
1744 static void garbage()
1746 REGISTER struct region *p, *q, *top;
1749 for (p = areabot; p != top; p = p->next) {
1750 if (p->area > areanum) {
1751 while ((q = p->next)->area > areanum)
1757 if (areatop >= q + SHRINKBY && q->area > areanum) {
1758 brk((char *) (q + 1));
1766 /* -------- csyn.c -------- */
1768 * shell: syntax (C version)
1773 DBGPRINTF7(("YYPARSE: enter...\n"));
1780 return (yynerrs != 0);
1783 static struct op *pipeline(cf)
1786 REGISTER struct op *t, *p;
1789 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1793 DBGPRINTF9(("PIPELINE: t=0x%x\n", t));
1796 while ((c = yylex(0)) == '|') {
1797 if ((p = command(CONTIN)) == NULL) {
1798 DBGPRINTF8(("PIPELINE: error!\n"));
1802 if (t->type != TPAREN && t->type != TCOM) {
1803 /* shell statement */
1804 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1807 t = block(TPIPE, t, p, NOWORDS);
1812 DBGPRINTF7(("PIPELINE: returning t=0x%x\n", t));
1816 static struct op *andor()
1818 REGISTER struct op *t, *p;
1821 DBGPRINTF7(("ANDOR: enter...\n"));
1825 DBGPRINTF9(("ANDOR: t=0x%x\n", t));
1828 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1829 if ((p = pipeline(CONTIN)) == NULL) {
1830 DBGPRINTF8(("ANDOR: error!\n"));
1834 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1840 DBGPRINTF7(("ANDOR: returning t=0x%x\n", t));
1844 static struct op *c_list()
1846 REGISTER struct op *t, *p;
1849 DBGPRINTF7(("C_LIST: enter...\n"));
1854 if ((peeksym = yylex(0)) == '&')
1855 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1857 while ((c = yylex(0)) == ';' || c == '&'
1858 || (multiline && c == '\n')) {
1860 if ((p = andor()) == NULL)
1863 if ((peeksym = yylex(0)) == '&')
1864 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1872 DBGPRINTF7(("C_LIST: returning t=0x%x\n", t));
1876 static int synio(cf)
1879 REGISTER struct ioword *iop;
1883 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1885 if ((c = yylex(cf)) != '<' && c != '>') {
1892 iop = io(iounit, i, yylval.cp);
1896 markhere(yylval.cp, iop);
1898 DBGPRINTF7(("SYNIO: returning 1\n"));
1902 static void musthave(c, cf)
1905 if ((peeksym = yylex(cf)) != c) {
1906 DBGPRINTF7(("MUSTHAVE: error!\n"));
1913 static struct op *simple()
1915 REGISTER struct op *t;
1919 switch (peeksym = yylex(0)) {
1940 static struct op *nested(type, mark)
1943 REGISTER struct op *t;
1945 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1951 return (block(type, t, NOBLOCK, NOWORDS));
1954 static struct op *command(cf)
1957 REGISTER struct op *t;
1958 struct wdblock *iosave;
1961 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1977 if ((t = simple()) == NULL) {
1979 return ((struct op *) NULL);
1986 t = nested(TPAREN, ')');
1990 t = nested(TBRACE, '}');
2000 t->words = wordlist();
2001 if ((c = yylex(0)) != '\n' && c != ';')
2003 t->left = dogroup(0);
2011 t->type = c == WHILE ? TWHILE : TUNTIL;
2013 t->right = dogroup(1);
2025 musthave(IN, CONTIN);
2028 t->left = caselist();
2039 t->right = thenpart();
2048 musthave(WORD, 0); /* gets name of file */
2049 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
2051 word(yylval.cp); /* add word to wdlist */
2052 word(NOWORD); /* terminate wdlist */
2053 t->words = copyw(); /* dup wdlist */
2063 DBGPRINTF(("COMMAND: returning 0x%x\n", t));
2068 static struct op *dowholefile(type, mark)
2072 REGISTER struct op *t;
2074 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
2079 t = block(type, t, NOBLOCK, NOWORDS);
2080 DBGPRINTF(("DOWHOLEFILE: return t=0x%x\n", t));
2084 static struct op *dogroup(onlydone)
2088 REGISTER struct op *mylist;
2091 if (c == DONE && onlydone)
2092 return ((struct op *) NULL);
2100 static struct op *thenpart()
2103 REGISTER struct op *t;
2105 if ((c = yylex(0)) != THEN) {
2107 return ((struct op *) NULL);
2112 if (t->left == NULL)
2114 t->right = elsepart();
2118 static struct op *elsepart()
2121 REGISTER struct op *t;
2123 switch (c = yylex(0)) {
2125 if ((t = c_list()) == NULL)
2133 t->right = thenpart();
2138 return ((struct op *) NULL);
2142 static struct op *caselist()
2144 REGISTER struct op *t;
2147 while ((peeksym = yylex(CONTIN)) != ESAC) {
2148 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
2149 t = list(t, casepart());
2152 DBGPRINTF(("CASELIST, returning t=0x%x\n", t));
2156 static struct op *casepart()
2158 REGISTER struct op *t;
2160 DBGPRINTF7(("CASEPART: enter...\n"));
2164 t->words = pattern();
2167 if ((peeksym = yylex(CONTIN)) != ESAC)
2168 musthave(BREAK, CONTIN);
2170 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=0x%x)\n", t));
2175 static char **pattern()
2184 } while ((c = yylex(0)) == '|');
2191 static char **wordlist()
2195 if ((c = yylex(0)) != IN) {
2197 return ((char **) NULL);
2200 while ((c = yylex(0)) == WORD)
2208 * supporting functions
2210 static struct op *list(t1, t2)
2211 REGISTER struct op *t1, *t2;
2213 DBGPRINTF7(("LIST: enter, t1=0x%x, t2=0x%x\n", t1, t2));
2220 return (block(TLIST, t1, t2, NOWORDS));
2223 static struct op *block(type, t1, t2, wp)
2228 REGISTER struct op *t;
2230 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2238 DBGPRINTF7(("BLOCK: inserted 0x%x between 0x%x and 0x%x\n", t, t1,
2244 /* See if given string is a shell multiline (FOR, IF, etc) */
2245 static int rlookup(n)
2248 REGISTER const struct res *rp;
2250 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2252 for (rp = restab; rp->r_name; rp++)
2253 if (strcmp(rp->r_name, n) == 0) {
2254 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2255 return (rp->r_val); /* Return numeric code for shell multiline */
2258 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2259 return (0); /* Not a shell multiline */
2262 static struct op *newtp()
2264 REGISTER struct op *t;
2266 t = (struct op *) tree(sizeof(*t));
2274 DBGPRINTF3(("NEWTP: allocated 0x%x\n", t));
2279 static struct op *namelist(t)
2280 REGISTER struct op *t;
2283 DBGPRINTF7(("NAMELIST: enter, t=0x%x, type %s, iolist=0x%x\n", t,
2284 T_CMD_NAMES[t->type], iolist));
2287 iolist = addword((char *) NULL, iolist);
2288 t->ioact = copyio();
2292 if (t->type != TCOM) {
2293 if (t->type != TPAREN && t->ioact != NULL) {
2294 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2295 t->ioact = t->left->ioact;
2296 t->left->ioact = NULL;
2308 static char **copyw()
2312 wd = getwords(wdlist);
2317 static void word(cp)
2320 wdlist = addword(cp, wdlist);
2323 static struct ioword **copyio()
2325 REGISTER struct ioword **iop;
2327 iop = (struct ioword **) getwords(iolist);
2332 static struct ioword *io(u, f, cp)
2337 REGISTER struct ioword *iop;
2339 iop = (struct ioword *) tree(sizeof(*iop));
2343 iolist = addword((char *) iop, iolist);
2349 yyerror("syntax error");
2352 static void yyerror(s)
2356 if (interactive && e.iop <= iostack) {
2358 while (eofc() == 0 && yylex(0) != '\n');
2364 static int yylex(cf)
2370 if ((c = peeksym) > 0) {
2385 line[LINELIM - 1] = '\0';
2388 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2393 if (any(c, "0123456789")) {
2394 unget(c1 = my_getc(0));
2395 if (c1 == '<' || c1 == '>') {
2404 case '#': /* Comment, skip to next newline or End-of-string */
2405 while ((c = my_getc(0)) != 0 && c != '\n');
2410 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2414 DBGPRINTF9(("YYLEX: found $\n"));
2416 if ((c = my_getc(0)) == '{') {
2417 if ((c = collect(c, '}')) != '\0')
2426 if ((c = collect(c, c)) != '\0')
2434 /* If more chars process them, else return NULL char */
2435 if ((c1 = dual(c)) != '\0')
2452 if (multiline || cf & CONTIN) {
2453 if (interactive && e.iop <= iostack) {
2454 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2455 current_prompt = cprompt->value;
2457 prs(cprompt->value);
2474 while ((c = my_getc(0)) != 0 && !any(c, "`$ '\"\t;&<>()|^\n")) {
2475 if (e.linep >= elinep)
2476 err("word too long");
2483 if (any(c, "\"'`$"))
2488 if (atstart && (c = rlookup(line)) != 0) {
2493 yylval.cp = strsave(line, areanum);
2498 static int collect(c, c1)
2503 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2506 while ((c = my_getc(c1)) != c1) {
2515 if (interactive && c == '\n' && e.iop <= iostack) {
2516 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2517 current_prompt = cprompt->value;
2519 prs(cprompt->value);
2527 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2532 /* "multiline commands" helper func */
2533 /* see if next 2 chars form a shell multiline */
2538 REGISTER char *cp = s;
2540 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2542 *cp++ = c; /* c is the given "peek" char */
2543 *cp++ = my_getc(0); /* get next char of input */
2544 *cp = 0; /* add EOS marker */
2546 c = rlookup(s); /* see if 2 chars form a shell multiline */
2548 unget(*--cp); /* String is not a shell multiline, put peek char back */
2550 return (c); /* String is multiline, return numeric multiline (restab) code */
2553 static void diag(ec)
2558 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2561 if (c == '>' || c == '<') {
2564 yylval.i = ec == '>' ? IOWRITE | IOCAT : IOHERE;
2567 yylval.i = ec == '>' ? IOWRITE : IOREAD;
2568 if (c != '&' || yylval.i == IOHERE)
2574 static char *tree(size)
2579 if ((t = getcell(size)) == NULL) {
2580 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2581 prs("command line too complicated\n");
2591 /* -------- exec.c -------- */
2598 static int execute(t, pin, pout, act)
2599 REGISTER struct op *t;
2603 REGISTER struct op *t1;
2604 volatile int i, rv, a;
2605 char *cp, **wp, **wp2;
2607 struct op *outtree_save;
2611 /* Avoid longjmp clobbering */
2616 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2620 DBGPRINTF(("EXECUTE: t=0x%x, t->type=%d (%s), t->words is %s\n", t,
2621 t->type, T_CMD_NAMES[t->type],
2622 ((t->words == NULL) ? "NULL" : t->words[0])));
2626 wp = (wp2 = t->words) != NULL
2627 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2630 /* Hard to know how many words there are, be careful of garbage pointer values */
2631 /* They are likely to cause "PCI bus fault" errors */
2633 DBGPRINTF(("EXECUTE: t->left=0x%x, t->right=0x%x, t->words[1] is %s\n",
2635 ((t->words[1] == NULL) ? "NULL" : t->words[1])));
2636 DBGPRINTF7(("EXECUTE: t->words[2] is %s, t->words[3] is %s\n",
2637 ((t->words[2] == NULL) ? "NULL" : t->words[2]),
2638 ((t->words[3] == NULL) ? "NULL" : t->words[3])));
2644 DBGPRINTF3(("EXECUTE: TDOT\n"));
2646 outtree_save = outtree;
2648 newfile(evalstr(t->words[0], DOALL));
2650 t->left = dowholefile(TLIST, 0);
2653 outtree = outtree_save;
2656 rv = execute(t->left, pin, pout, 0);
2658 rv = execute(t->right, pin, pout, 0);
2662 rv = execute(t->left, pin, pout, 0);
2667 rv = forkexec(t, pin, pout, act, wp);
2675 if ((rv = openpipe(pv)) < 0)
2677 pv[0] = remap(pv[0]);
2678 pv[1] = remap(pv[1]);
2679 (void) execute(t->left, pin, pv, 0);
2680 rv = execute(t->right, pv, pout, 0);
2685 (void) execute(t->left, pin, pout, 0);
2686 rv = execute(t->right, pin, pout, 0);
2691 int hinteractive = interactive;
2693 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2697 interactive = hinteractive;
2699 setval(lookup("!"), putn(i));
2710 signal(SIGINT, SIG_IGN);
2711 signal(SIGQUIT, SIG_IGN);
2713 signal(SIGTERM, SIG_DFL);
2717 open(bb_dev_null, 0);
2719 _exit(execute(t->left, pin, pout, FEXEC));
2726 rv = execute(t->left, pin, pout, 0);
2727 if ((t1 = t->right) != NULL && (rv == 0) == (t->type == TAND))
2728 rv = execute(t1, pin, pout, 0);
2738 while (*wp++ != NULL);
2740 vp = lookup(t->str);
2741 while (setjmp(bc.brkpt))
2745 for (t1 = t->left; i-- && *wp != NULL;) {
2747 rv = execute(t1, pin, pout, 0);
2749 brklist = brklist->nextlev;
2754 while (setjmp(bc.brkpt))
2759 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2760 rv = execute(t->right, pin, pout, 0);
2761 brklist = brklist->nextlev;
2766 if (t->right != NULL) {
2767 rv = !execute(t->left, pin, pout, 0) ?
2768 execute(t->right->left, pin, pout, 0) :
2769 execute(t->right->right, pin, pout, 0);
2774 if ((cp = evalstr(t->str, DOSUB | DOTRIM)) == 0)
2777 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2778 ((t->str == NULL) ? "NULL" : t->str),
2779 ((cp == NULL) ? "NULL" : cp)));
2781 if ((t1 = findcase(t->left, cp)) != NULL) {
2782 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=0x%x, t1=0x%x)...\n", t, t1));
2783 rv = execute(t1, pin, pout, 0);
2784 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=0x%x, t1=0x%x)...\n", t, t1));
2790 if (iopp = t->ioact)
2792 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2797 if (rv >= 0 && (t1 = t->left))
2798 rv = execute(t1, pin, pout, 0);
2809 if (interactive && intr) {
2814 if ((i = trapset) != 0) {
2819 DBGPRINTF(("EXECUTE: returning from t=0x%x, rv=%d\n", t, rv));
2824 forkexec(REGISTER struct op *t, int *pin, int *pout, int act, char **wp)
2828 int (*shcom) (struct op *) = NULL;
2831 struct ioword **iopp;
2841 struct brkcon *hbrklist;
2845 /* Avoid longjmp clobbering */
2855 DBGPRINTF(("FORKEXEC: t=0x%x, pin 0x%x, pout 0x%x, act %d\n", t, pin,
2857 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2858 ((t->words == NULL) ? "NULL" : t->words[0])));
2860 /* Hard to know how many words there are, be careful of garbage pointer values */
2861 /* They are likely to cause "PCI bus fault" errors */
2863 DBGPRINTF7(("FORKEXEC: t->words is %s, t->words[1] is %s\n",
2864 ((t->words == NULL) ? "NULL" : t->words[0]),
2865 ((t->words == NULL) ? "NULL" : t->words[1])));
2866 DBGPRINTF7(("FORKEXEC: wp is %s, wp[1] is %s\n",
2867 ((wp == NULL) ? "NULL" : wp[0]),
2868 ((wp[1] == NULL) ? "NULL" : wp[1])));
2869 DBGPRINTF7(("FORKEXEC: wp2 is %s, wp[3] is %s\n",
2870 ((wp[2] == NULL) ? "NULL" : wp[2]),
2871 ((wp[3] == NULL) ? "NULL" : wp[3])));
2877 rv = -1; /* system-detected error */
2878 if (t->type == TCOM) {
2879 while ((cp = *wp++) != NULL);
2882 /* strip all initial assignments */
2883 /* not correct wrt PATH=yyy command etc */
2885 DBGPRINTF9(("FORKEXEC: echo'ing, cp=0x%x, wp=0x%x, owp=0x%x\n",
2887 echo(cp ? wp : owp);
2890 DBGPRINTF9(("FORKEXEC: t->words is %s, t->words[1] is %s\n",
2891 ((t->words == NULL) ? "NULL" : t->words[0]),
2892 ((t->words == NULL) ? "NULL" : t->words[1])));
2893 DBGPRINTF9(("FORKEXEC: wp is %s, wp[1] is %s\n",
2894 ((wp == NULL) ? "NULL" : wp[0]),
2895 ((wp == NULL) ? "NULL" : wp[1])));
2898 if (cp == NULL && t->ioact == NULL) {
2899 while ((cp = *owp++) != NULL && assign(cp, COPYV));
2900 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2901 return (setstatus(0));
2902 } else if (cp != NULL) {
2903 shcom = inbuilt(cp);
2911 DBGPRINTF3(("FORKEXEC: t->words is %s, t->words[1] is %s\n",
2912 ((t->words == NULL) ? "NULL" : t->words[0]),
2913 ((t->words == NULL) ? "NULL" : t->words[1])));
2915 DBGPRINTF(("FORKEXEC: shcom 0x%x, f&FEXEC 0x%x, owp 0x%x\n", shcom,
2918 if (shcom == NULL && (f & FEXEC) == 0) {
2919 /* Save values in case the child process alters them */
2923 hinteractive = interactive;
2928 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2933 DBGPRINTF(("FORKEXEC: ERROR, unable to vfork()!\n"));
2938 if (newpid > 0) { /* Parent */
2940 /* Restore values */
2944 interactive = hinteractive;
2957 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2960 /* Must be the child process, pid should be 0 */
2961 DBGPRINTF(("FORKEXEC: child process, shcom=0x%x\n", shcom));
2964 signal(SIGINT, SIG_IGN);
2965 signal(SIGQUIT, SIG_IGN);
2977 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2982 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2983 err("piping to/from shell builtins not yet done");
2999 if ((iopp = t->ioact) != NULL) {
3000 if (shcom != NULL && shcom != doexec) {
3002 err(": cannot redirect shell command");
3008 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
3016 i = setstatus((*shcom) (t));
3019 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
3023 /* should use FIOCEXCL */
3024 for (i = FDBASE; i < NOFILE; i++)
3027 signal(SIGINT, SIG_DFL);
3028 signal(SIGQUIT, SIG_DFL);
3031 if (t->type == TPAREN)
3032 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
3036 cp = rexecve(wp[0], wp, makenv(0, NULL));
3043 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
3051 * 0< 1> are ignored as required
3054 static int iosetup(iop, pipein, pipeout)
3055 REGISTER struct ioword *iop;
3056 int pipein, pipeout;
3058 REGISTER int u = -1;
3059 char *cp = NULL, *msg;
3061 DBGPRINTF(("IOSETUP: iop 0x%x, pipein 0x%x, pipeout 0x%x\n", iop,
3064 if (iop->io_unit == IODEFAULT) /* take default */
3065 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
3067 if (pipein && iop->io_unit == 0)
3070 if (pipeout && iop->io_unit == 1)
3073 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
3074 if ((iop->io_flag & IOHERE) == 0) {
3076 if ((cp = evalstr(cp, DOSUB | DOTRIM)) == NULL)
3080 if (iop->io_flag & IODUP) {
3081 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
3083 err(": illegal >& argument");
3087 iop->io_flag = IOCLOSE;
3088 iop->io_flag &= ~(IOREAD | IOWRITE);
3090 switch (iop->io_flag) {
3096 case IOHERE | IOXHERE:
3097 u = herein(iop->io_name, iop->io_flag & IOXHERE);
3101 case IOWRITE | IOCAT:
3102 if ((u = open(cp, 1)) >= 0) {
3103 lseek(u, (long) 0, 2);
3107 u = creat(cp, 0666);
3111 u = dup2(*cp - '0', iop->io_unit);
3115 close(iop->io_unit);
3124 if (u != iop->io_unit) {
3125 dup2(u, iop->io_unit);
3132 static void echo(wp)
3138 for (i = 0; wp[i]; i++) {
3146 static struct op **find1case(t, w)
3150 REGISTER struct op *t1;
3152 REGISTER char **wp, *cp;
3156 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
3157 return ((struct op **) NULL);
3160 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
3161 T_CMD_NAMES[t->type]));
3163 if (t->type == TLIST) {
3164 if ((tp = find1case(t->left, w)) != NULL) {
3165 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=0x%x\n", tp));
3168 t1 = t->right; /* TPAT */
3172 for (wp = t1->words; *wp;)
3173 if ((cp = evalstr(*wp++, DOSUB)) && gmatch(w, cp)) {
3174 DBGPRINTF3(("FIND1CASE: returning &t1->left= 0x%x.\n",
3179 DBGPRINTF(("FIND1CASE: returning NULL\n"));
3180 return ((struct op **) NULL);
3183 static struct op *findcase(t, w)
3187 REGISTER struct op **tp;
3189 return ((tp = find1case(t, w)) != NULL ? *tp : (struct op *) NULL);
3193 * Enter a new loop level (marked for break/continue).
3195 static void brkset(bc)
3198 bc->nextlev = brklist;
3203 * Wait for the last process created.
3204 * Print a message for each process found
3205 * that was killed by a signal.
3206 * Ignore interrupt signals while waiting
3207 * unless `canintr' is true.
3209 static int waitfor(lastpid, canintr)
3210 REGISTER int lastpid;
3213 REGISTER int pid, rv;
3215 int oheedint = heedint;
3222 if (errno != EINTR || canintr)
3225 if ((rv = WAITSIG(s)) != 0) {
3227 if (signame[rv] != NULL) {
3228 if (pid != lastpid) {
3235 if (pid != lastpid) {
3244 prs(" - core dumped");
3245 if (rv >= NSIGNAL || signame[rv])
3251 } while (pid != lastpid);
3266 static int setstatus(s)
3270 setval(lookup("?"), putn(s));
3275 * PATH-searching interface to execve.
3276 * If getenv("PATH") were kept up-to-date,
3277 * execvp might be used.
3279 static char *rexecve(c, v, envp)
3280 char *c, **v, **envp;
3283 REGISTER char *sp, *tp;
3284 int eacces = 0, asis = 0;
3286 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3290 if (find_applet_by_name(name)) {
3291 /* We have to exec here since we vforked. Running
3292 * run_applet_by_name() won't work and bad things
3294 execve("/proc/self/exe", v, envp);
3295 execve("busybox", v, envp);
3299 DBGPRINTF(("REXECVE: c=0x%x, v=0x%x, envp=0x%x\n", c, v, envp));
3301 sp = any('/', c) ? "" : path->value;
3303 while (asis || *sp != '\0') {
3306 for (; *sp != '\0'; tp++)
3307 if ((*tp = *sp++) == ':') {
3313 for (i = 0; (*tp++ = c[i++]) != '\0';);
3315 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3317 execve(e.linep, v, envp);
3324 execve(DEFAULT_SHELL, v, envp);
3326 return ("no Shell");
3329 return ((char *) bb_msg_memory_exhausted);
3332 return ("argument list too long");
3339 return (errno == ENOENT ? "not found" : "cannot execute");
3343 * Run the command produced by generator `f'
3344 * applied to stream `arg'.
3346 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3349 struct wdblock *swdlist;
3350 struct wdblock *siolist;
3356 /* Avoid longjmp clobbering */
3360 DBGPRINTF(("RUN: enter, areanum %d, outtree 0x%x, failpt 0x%x\n",
3361 areanum, outtree, failpt));
3370 if (newenv(setjmp(errpt = ev)) == 0) {
3376 if (setjmp(failpt = rt) == 0 && yyparse() == 0)
3377 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3380 DBGPRINTF(("RUN: error from newenv()!\n"));
3387 freearea(areanum--);
3392 /* -------- do.c -------- */
3395 * built-in commands: doX
3398 static int dohelp(struct op *t)
3401 const struct builtincmd *x;
3403 printf("\nBuilt-in commands:\n");
3404 printf("-------------------\n");
3406 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3409 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3415 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3418 const struct BB_applet *applet;
3419 extern const struct BB_applet applets[];
3420 extern const size_t NUM_APPLETS;
3422 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3426 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3435 return EXIT_SUCCESS;
3440 static int dolabel(struct op *t)
3445 static int dochdir(t)
3446 REGISTER struct op *t;
3448 REGISTER char *cp, *er;
3450 if ((cp = t->words[1]) == NULL && (cp = homedir->value) == NULL)
3451 er = ": no home directory";
3452 else if (chdir(cp) < 0)
3453 er = ": bad directory";
3456 prs(cp != NULL ? cp : "cd");
3461 static int doshift(t)
3462 REGISTER struct op *t;
3466 n = t->words[1] ? getn(t->words[1]) : 1;
3468 err("nothing to shift");
3474 setval(lookup("#"), putn(dolc));
3479 * execute login and newgrp directly
3481 static int dologin(t)
3487 signal(SIGINT, SIG_DFL);
3488 signal(SIGQUIT, SIG_DFL);
3490 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3497 static int doumask(t)
3498 REGISTER struct op *t;
3503 if ((cp = t->words[1]) == NULL) {
3506 for (n = 3 * 4; (n -= 3) >= 0;)
3507 putc('0' + ((i >> n) & 07), stderr);
3510 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3511 n = n * 8 + (*cp - '0');
3517 static int doexec(t)
3518 REGISTER struct op *t;
3525 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3530 if (setjmp(failpt = ex) == 0)
3531 execute(t, NOPIPE, NOPIPE, FEXEC);
3541 REGISTER char *sp, *tp;
3545 DBGPRINTF(("DODOT: enter, t=0x%x, tleft 0x%x, tright 0x%x, e.linep is %s\n", t, t->left, t->right, ((e.linep == NULL) ? "NULL" : e.linep)));
3547 if ((cp = t->words[1]) == NULL) {
3548 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3551 DBGPRINTF(("DODOT: cp is %s\n", cp));
3554 sp = any('/', cp) ? ":" : path->value;
3556 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3557 ((sp == NULL) ? "NULL" : sp),
3558 ((e.linep == NULL) ? "NULL" : e.linep)));
3562 while (*sp && (*tp = *sp++) != ':')
3567 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3570 if ((i = open(e.linep, 0)) >= 0) {
3573 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3575 next(maltmp); /* Basically a PUSHIO */
3577 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3590 static int dowait(t)
3596 if ((cp = t->words[1]) != NULL) {
3602 setstatus(waitfor(i, 1));
3606 static int doread(t)
3609 REGISTER char *cp, **wp;
3610 REGISTER int nb = 0;
3611 REGISTER int nl = 0;
3613 if (t->words[1] == NULL) {
3614 err("Usage: read name ...");
3617 for (wp = t->words + 1; *wp; wp++) {
3618 for (cp = e.linep; !nl && cp < elinep - 1; cp++)
3619 if ((nb = read(0, cp, sizeof(*cp))) != sizeof(*cp) ||
3620 (nl = (*cp == '\n')) || (wp[1] && any(*cp, ifs->value)))
3625 setval(lookup(*wp), e.linep);
3630 static int doeval(t)
3631 REGISTER struct op *t;
3633 return (RUN(awordlist, t->words + 1, wdchar));
3636 static int dotrap(t)
3637 REGISTER struct op *t;
3640 REGISTER int resetsig;
3642 if (t->words[1] == NULL) {
3643 for (i = 0; i <= _NSIG; i++)
3652 resetsig = isdigit(*t->words[1]);
3653 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3654 n = getsig(t->words[i]);
3658 if (*t->words[1] != '\0') {
3659 trap[n] = strsave(t->words[1], 0);
3668 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3676 static int getsig(s)
3681 if ((n = getn(s)) < 0 || n > _NSIG) {
3682 err("trap: bad signal number");
3688 static void setsig(REGISTER int n, sighandler_t f)
3692 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3710 for (n = 0; isdigit(*s); s++)
3711 n = (n * 10) + (*s - '0');
3714 err(": bad number");
3719 static int dobreak(t)
3722 return (brkcontin(t->words[1], 1));
3725 static int docontinue(t)
3728 return (brkcontin(t->words[1], 0));
3731 static int brkcontin(cp, val)
3735 REGISTER struct brkcon *bc;
3738 nl = cp == NULL ? 1 : getn(cp);
3742 if ((bc = brklist) == NULL)
3744 brklist = bc->nextlev;
3747 err("bad break/continue level");
3751 longjmp(bc->brkpt, 1);
3755 static int doexit(t)
3761 if ((cp = t->words[1]) != NULL)
3762 setstatus(getn(cp));
3764 DBGPRINTF(("DOEXIT: calling leave(), t=0x%x\n", t));
3771 static int doexport(t)
3774 rdexp(t->words + 1, export, EXPORT);
3778 static int doreadonly(t)
3781 rdexp(t->words + 1, ronly, RONLY);
3785 static void rdexp(char **wp, void (*f) (struct var *), int key)
3787 DBGPRINTF6(("RDEXP: enter, wp=0x%x, func=0x%x, key=%d\n", wp, f, key));
3788 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3791 for (; *wp != NULL; wp++) {
3792 if (isassign(*wp)) {
3796 for (cp = *wp; *cp != '='; cp++);
3808 static void badid(s)
3812 err(": bad identifier");
3816 REGISTER struct op *t;
3818 REGISTER struct var *vp;
3822 if ((cp = t->words[1]) == NULL) {
3823 for (vp = vlist; vp; vp = vp->next)
3824 varput(vp->name, 1);
3828 /* bad: t->words++; */
3829 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3831 flag['x'] = flag['v'] = 0;
3841 if (*cp >= 'a' && *cp <= 'z')
3848 t->words[0] = dolv[0];
3849 for (n = 1; t->words[n]; n++)
3850 setarea((char *) t->words[n], 0);
3853 setval(lookup("#"), putn(dolc));
3854 setarea((char *) (dolv - 1), 0);
3859 static void varput(s, out)
3863 if (isalnum(*s) || *s == '_') {
3864 write(out, s, strlen(s));
3865 write(out, "\n", 1);
3871 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3872 * This file contains code for the times builtin.
3874 static int dotimes(struct op *t)
3877 long int clk_tck = sysconf(_SC_CLK_TCK);
3880 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3881 (int) (buf.tms_utime / clk_tck / 60),
3882 ((double) buf.tms_utime) / clk_tck,
3883 (int) (buf.tms_stime / clk_tck / 60),
3884 ((double) buf.tms_stime) / clk_tck,
3885 (int) (buf.tms_cutime / clk_tck / 60),
3886 ((double) buf.tms_cutime) / clk_tck,
3887 (int) (buf.tms_cstime / clk_tck / 60),
3888 ((double) buf.tms_cstime) / clk_tck);
3893 static int (*inbuilt(char *s)) (struct op *) {
3894 const struct builtincmd *bp;
3896 for (bp = builtincmds; bp->name != NULL; bp++)
3897 if (strcmp(bp->name, s) == 0)
3898 return (bp->builtinfunc);
3903 /* -------- eval.c -------- */
3908 * blank interpretation
3913 static char **eval(char **ap, int f)
3921 /* Avoid longjmp clobbering */
3926 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3931 if (newenv(setjmp(errpt = ev)) == 0) {
3932 while (*ap && isassign(*ap))
3933 expand(*ap++, &wb, f & ~DOGLOB);
3935 for (wf = ap; *wf; wf++) {
3937 expand(*wf, &wb, f & ~DOGLOB);
3940 for (wb = addword((char *) 0, wb); *ap; ap++) {
3941 if (!flag['k'] || !isassign(*ap))
3942 expand(*ap, &wb, f & ~DOKEY);
3944 wb = addword((char *) 0, wb);
3950 return (gflg ? (char **) NULL : wp);
3954 * Make the exported environment from the exported
3955 * names in the dictionary. Keyword assignments
3956 * will already have been done.
3958 static char **makenv(int all, struct wdblock *wb)
3960 REGISTER struct var *vp;
3962 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3964 for (vp = vlist; vp; vp = vp->next)
3965 if (all || vp->status & EXPORT)
3966 wb = addword(vp->name, wb);
3967 wb = addword((char *) 0, wb);
3968 return (getwords(wb));
3971 static char *evalstr(cp, f)
3977 DBGPRINTF6(("EVALSTR: enter, cp=0x%x, f=%d\n", cp, f));
3980 if (expand(cp, &wb, f)) {
3981 if (wb == NULL || wb->w_nword == 0
3982 || (cp = wb->w_words[0]) == NULL)
3990 static int expand(char *cp, REGISTER struct wdblock **wbp, int f)
3995 /* Avoid longjmp clobbering */
3999 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
4006 if (!anys("$`'\"", cp) &&
4007 !anys(ifs->value, cp) && ((f & DOGLOB) == 0 || !anys("[*?", cp))) {
4008 cp = strsave(cp, areanum);
4011 *wbp = addword(cp, *wbp);
4014 if (newenv(setjmp(errpt = ev)) == 0) {
4015 PUSHIO(aword, cp, strchar);
4017 while ((cp = blank(f)) && gflg == 0) {
4019 cp = strsave(cp, areanum);
4020 if ((f & DOGLOB) == 0) {
4023 *wbp = addword(cp, *wbp);
4025 *wbp = glob(cp, *wbp);
4034 * Blank interpretation and quoting
4036 static char *blank(f)
4041 int scanequals, foundequals;
4043 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
4046 scanequals = f & DOKEY;
4050 switch (c = subgetc('"', foundequals)) {
4058 if (f & DOBLANK && any(c, ifs->value))
4067 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
4070 if (c == '\'' || !any(c, "$`\""))
4077 if (!isalpha(c) && c != '_')
4080 c = subgetc('"', foundequals);
4082 f & (DOBLANK && any(c, ifs->value)) ||
4083 (!INSUB() && any(c, "\"'"))) {
4094 } else if (!isalnum(c) && c != '_')
4104 * Get characters, substituting for ` and $
4106 static int subgetc(ec, quoted)
4112 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
4116 if (!INSUB() && ec != '\'') {
4118 if (grave(quoted) == 0)
4120 e.iop->task = XGRAVE;
4123 if (c == '$' && (c = dollar(quoted)) == 0) {
4124 e.iop->task = XDOLL;
4132 * Prepare to generate the string returned by ${} substitution.
4134 static int dollar(quoted)
4140 REGISTER char *s, c, *cp = NULL;
4143 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
4149 if (isalpha(c) || c == '_') {
4150 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
4151 if (e.linep < elinep)
4158 otask = e.iop->task;
4160 e.iop->task = XOTHER;
4161 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
4162 if (e.linep < elinep)
4165 e.iop->task = otask;
4172 if (e.linep >= elinep) {
4173 err("string in ${} too long");
4179 for (cp = s + 1; *cp; cp++)
4180 if (any(*cp, "=-+?")) {
4185 if (s[1] == 0 && (*s == '*' || *s == '@')) {
4187 /* currently this does not distinguish $* and $@ */
4188 /* should check dollar */
4190 PUSHIO(awordlist, dolv + 1, dolchar);
4192 } else { /* trap the nasty ${=} */
4198 if ((dolp = vp->value) == null) {
4202 err("cannot use ${...=...} with $n");
4211 dolp = strsave(cp, areanum);
4216 prs("missing value for ");
4223 } else if (c == '+')
4224 dolp = strsave(cp, areanum);
4225 if (flag['u'] && dolp == null) {
4226 prs("unset variable: ");
4231 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4236 * Run the command in `...` and read its output.
4239 static int grave(quoted)
4246 static char child_cmd[LINELIM];
4252 char *argument_list[4];
4253 struct wdblock *wb = NULL;
4256 /* Avoid longjmp clobbering */
4260 for (cp = e.iop->argp->aword; *cp != '`'; cp++)
4262 err("no closing `");
4266 /* string copy with dollar expansion */
4267 src = e.iop->argp->aword;
4272 while ((*src != '`') && (count < LINELIM)) {
4277 if (*src == '$' && !ignore && !ignore_once) {
4279 char var_name[LINELIM];
4280 char alt_value[LINELIM];
4293 var_name[var_index++] = *src++;
4294 while (isalnum(*src) || *src=='_')
4295 var_name[var_index++] = *src++;
4296 var_name[var_index] = 0;
4309 err("unclosed ${\n");
4314 while (*src && (*src != '}')) {
4315 alt_value[alt_index++] = *src++;
4317 alt_value[alt_index] = 0;
4319 err("unclosed ${\n");
4326 if (isalpha(*var_name)) {
4327 /* let subshell handle it instead */
4329 char *namep = var_name;
4337 char *altp = alt_value;
4345 wb = addword(lookup(var_name)->name, wb);
4349 vp = lookup(var_name);
4350 if (vp->value != null)
4351 value = (operator == '+') ?
4352 alt_value : vp->value;
4353 else if (operator == '?') {
4356 } else if (alt_index && (operator != '+')) {
4358 if (operator == '=')
4363 while (*value && (count < LINELIM)) {
4376 if (openpipe(pf) < 0)
4379 while ((i = vfork()) == -1 && errno == EAGAIN);
4381 DBGPRINTF3(("GRAVE: i is %d\n", io));
4385 err((char *) bb_msg_memory_exhausted);
4389 waitpid(i, NULL, 0);
4390 e.iop->argp->aword = ++cp;
4392 PUSHIO(afile, remap(pf[0]),
4393 (int (*)(struct ioarg *)) ((quoted) ? qgravechar :
4397 /* allow trapped signals */
4398 /* XXX - Maybe this signal stuff should go as well? */
4399 for (j = 0; j <= _NSIG; j++)
4400 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4406 argument_list[0] = (char *) DEFAULT_SHELL;
4407 argument_list[1] = "-c";
4408 argument_list[2] = child_cmd;
4409 argument_list[3] = 0;
4411 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4412 prs(argument_list[0]);
4419 static char *unquote(as)
4424 if ((s = as) != NULL)
4430 /* -------- glob.c -------- */
4436 #define scopy(x) strsave((x), areanum)
4438 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4440 static struct wdblock *cl, *nl;
4441 static char spcl[] = "[?*";
4443 static struct wdblock *glob(cp, wb)
4453 for (pp = cp; *pp; pp++)
4456 else if (!any(*pp & ~QUOTE, spcl))
4459 for (cl = addword(scopy(cp), (struct wdblock *) 0); anyspcl(cl);
4461 nl = newword(cl->w_nword * 2);
4462 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4463 for (pp = cl->w_words[i]; *pp; pp++)
4464 if (any(*pp, spcl)) {
4465 globname(cl->w_words[i], pp);
4469 nl = addword(scopy(cl->w_words[i]), nl);
4471 for (i = 0; i < cl->w_nword; i++)
4472 DELETE(cl->w_words[i]);
4475 for (i = 0; i < cl->w_nword; i++)
4476 unquote(cl->w_words[i]);
4477 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4479 for (i = 0; i < cl->w_nword; i++)
4480 wb = addword(cl->w_words[i], wb);
4485 wb = addword(unquote(cp), wb);
4489 static void globname(we, pp)
4493 REGISTER char *np, *cp;
4494 char *name, *gp, *dp;
4498 char dname[NAME_MAX + 1];
4501 for (np = we; np != pp; pp--)
4504 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4508 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4517 dname[NAME_MAX] = '\0';
4518 while ((de = readdir(dirp)) != NULL) {
4519 /* XXX Hmmm... What this could be? (abial) */
4521 if (ent[j].d_ino == 0)
4524 strncpy(dname, de->d_name, NAME_MAX);
4525 if (dname[0] == '.')
4528 for (k = 0; k < NAME_MAX; k++)
4529 if (any(dname[k], spcl))
4531 if (gmatch(dname, gp)) {
4532 name = generate(we, pp, dname, np);
4533 if (*np && !anys(np, spcl)) {
4534 if (stat(name, &dbuf)) {
4539 nl = addword(name, nl);
4548 * generate a pathname as below.
4549 * start..end1 / middle end
4550 * the slashes come for free
4552 static char *generate(start1, end1, middle, end)
4554 REGISTER char *end1;
4558 REGISTER char *op, *xp;
4561 space((int) (end1 - start1) + strlen(middle) + strlen(end) + 2);
4562 for (xp = start1; xp != end1;)
4564 for (xp = middle; (*op++ = *xp++) != '\0';);
4566 for (xp = end; (*op++ = *xp++) != '\0';);
4570 static int anyspcl(wb)
4571 REGISTER struct wdblock *wb;
4577 for (i = 0; i < wb->w_nword; i++)
4578 if (anys(spcl, *wd++))
4583 static int xstrcmp(p1, p2)
4586 return (strcmp(*(char **) p1, *(char **) p2));
4589 /* -------- word.c -------- */
4591 static struct wdblock *newword(nw)
4594 REGISTER struct wdblock *wb;
4596 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4602 static struct wdblock *addword(wd, wb)
4604 REGISTER struct wdblock *wb;
4606 REGISTER struct wdblock *wb2;
4610 wb = newword(NSTART);
4611 if ((nw = wb->w_nword) >= wb->w_bsize) {
4612 wb2 = newword(nw * 2);
4613 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4614 nw * sizeof(char *));
4619 wb->w_words[wb->w_nword++] = wd;
4625 REGISTER struct wdblock *wb;
4631 return ((char **) NULL);
4632 if (wb->w_nword == 0) {
4634 return ((char **) NULL);
4636 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4637 memcpy((char *) wd, (char *) wb->w_words, nb);
4638 DELETE(wb); /* perhaps should done by caller */
4642 static int (*func) (char *, char *);
4645 static void glob0(a0, a1, a2, a3)
4649 int (*a3) (char *, char *);
4653 glob1(a0, a0 + a1 * a2);
4656 static void glob1(base, lim)
4659 REGISTER char *i, *j;
4669 if ((n = (int) (lim - base)) <= v2)
4671 n = v2 * (n / (2 * v2));
4672 hptr = lptr = base + n;
4677 if ((c = (*func) (i, lptr)) == 0) {
4678 glob2(i, lptr -= v2);
4689 if ((c = (*func) (hptr, j)) == 0) {
4690 glob2(hptr += v2, j);
4695 glob3(i, hptr += v2, j);
4710 if (lptr - base >= lim - hptr) {
4711 glob1(hptr + v2, lim);
4721 glob3(j, lptr -= v2, i);
4726 static void glob2(i, j)
4729 REGISTER char *index1, *index2, c;
4737 *index1++ = *index2;
4742 static void glob3(i, j, k)
4745 REGISTER char *index1, *index2, *index3;
4755 *index1++ = *index3;
4756 *index3++ = *index2;
4761 /* -------- io.c -------- */
4767 static int my_getc(int ec)
4771 if (e.linep > elinep) {
4772 while ((c = readc()) != '\n' && c);
4773 err("input line too long");
4778 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4781 if (c == '\n' && ec != '\"')
4782 return (my_getc(ec));
4789 static void unget(c)
4792 if (e.iop >= e.iobase)
4798 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4805 RCPRINTF(("READC: e.iop 0x%x, e.iobase 0x%x\n", e.iop, e.iobase));
4807 for (; e.iop >= e.iobase; e.iop--) {
4808 RCPRINTF(("READC: e.iop 0x%x, peekc 0x%x\n", e.iop, e.iop->peekc));
4809 if ((c = e.iop->peekc) != '\0') {
4813 if (e.iop->prev != 0) {
4814 if ((c = (*e.iop->iofn) (e.iop->argp, e.iop)) != '\0') {
4819 if (e.iop == iostack)
4821 return (e.iop->prev = c);
4822 } else if (e.iop->task == XIO && e.iop->prev != '\n') {
4824 if (e.iop == iostack)
4829 if (e.iop->task == XIO) {
4831 return e.iop->prev = 0;
4833 if (interactive && e.iop == iostack + 1) {
4834 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4835 current_prompt = prompt->value;
4845 if (e.iop >= iostack) {
4846 RCPRINTF(("READC: return 0, e.iop 0x%x\n", e.iop));
4850 DBGPRINTF(("READC: leave()...\n"));
4857 static void ioecho(c)
4861 write(2, &c, sizeof c);
4865 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4867 DBGPRINTF(("PUSHIO: argp 0x%x, argp->afid 0x%x, e.iop 0x%x\n", argp,
4868 argp->afid, e.iop));
4870 /* Set env ptr for io source to next array spot and check for array overflow */
4871 if (++e.iop >= &iostack[NPUSH]) {
4873 err("Shell input nested too deeply");
4878 /* We did not overflow the NPUSH array spots so setup data structs */
4880 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4882 if (argp->afid != AFID_NOBUF)
4886 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4887 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4889 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4891 if (e.iop == &iostack[0])
4892 e.iop->argp->afbuf = &mainbuf;
4894 e.iop->argp->afbuf = &sharedbuf;
4896 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4897 /* This line appears to be active when running scripts from command line */
4898 if ((isatty(e.iop->argp->afile) == 0)
4899 && (e.iop == &iostack[0]
4900 || lseek(e.iop->argp->afile, 0L, 1) != -1)) {
4901 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4902 bufid = AFID_ID; /* AFID_ID = 0 */
4904 e.iop->argp->afid = bufid; /* assign buffer id */
4907 DBGPRINTF(("PUSHIO: iostack 0x%x, e.iop 0x%x, afbuf 0x%x\n",
4908 iostack, e.iop, e.iop->argp->afbuf));
4909 DBGPRINTF(("PUSHIO: mbuf 0x%x, sbuf 0x%x, bid %d, e.iop 0x%x\n",
4910 &mainbuf, &sharedbuf, bufid, e.iop));
4914 e.iop->prev = ~'\n';
4919 if (fn == filechar || fn == linechar)
4921 else if (fn == (int (*)(struct ioarg *)) gravechar
4922 || fn == (int (*)(struct ioarg *)) qgravechar)
4923 e.iop->task = XGRAVE;
4925 e.iop->task = XOTHER;
4930 static struct io *setbase(ip)
4933 REGISTER struct io *xp;
4941 * Input generating functions
4945 * Produce the characters of a string, then a newline, then EOF.
4947 static int nlchar(ap)
4948 REGISTER struct ioarg *ap;
4952 if (ap->aword == NULL)
4954 if ((c = *ap->aword++) == 0) {
4962 * Given a list of words, produce the characters
4963 * in them, with a space after each word.
4965 static int wdchar(ap)
4966 REGISTER struct ioarg *ap;
4971 if ((wl = ap->awordlist) == NULL)
4974 if ((c = *(*wl)++) != 0)
4979 ap->awordlist = NULL;
4984 * Return the characters of a list of words,
4985 * producing a space between them.
4987 static int dolchar(ap)
4988 REGISTER struct ioarg *ap;
4992 if ((wp = *ap->awordlist++) != NULL) {
4993 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4999 static int xxchar(ap)
5000 REGISTER struct ioarg *ap;
5004 if (ap->aword == NULL)
5006 if ((c = *ap->aword++) == '\0') {
5014 * Produce the characters from a single word (string).
5016 static int strchar(ap)
5017 REGISTER struct ioarg *ap;
5021 if (ap->aword == NULL || (c = *ap->aword++) == 0)
5027 * Produce quoted characters from a single word (string).
5029 static int qstrchar(ap)
5030 REGISTER struct ioarg *ap;
5034 if (ap->aword == NULL || (c = *ap->aword++) == 0)
5040 * Return the characters from a file.
5042 static int filechar(ap)
5043 REGISTER struct ioarg *ap;
5047 struct iobuf *bp = ap->afbuf;
5049 if (ap->afid != AFID_NOBUF) {
5050 if ((i = ap->afid != bp->id) || bp->bufp == bp->ebufp) {
5053 lseek(ap->afile, ap->afpos, 0);
5055 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
5063 bp->ebufp = (bp->bufp = bp->buf) + i;
5067 return *bp->bufp++ & 0177;
5069 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5070 if (interactive && isatty(ap->afile)) {
5071 static char mycommand[BUFSIZ];
5072 static int position = 0, size = 0;
5074 while (size == 0 || position >= size) {
5075 cmdedit_read_input(current_prompt, mycommand);
5076 size = strlen(mycommand);
5079 c = mycommand[position];
5086 i = safe_read(ap->afile, &c, sizeof(c));
5087 return (i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0));
5092 * Return the characters from a here temp file.
5094 static int herechar(ap)
5095 REGISTER struct ioarg *ap;
5100 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
5109 * Return the characters produced by a process (`...`).
5110 * Quote them if required, and remove any trailing newline characters.
5112 static int gravechar(ap, iop)
5118 if ((c = qgravechar(ap, iop) & ~QUOTE) == '\n')
5123 static int qgravechar(ap, iop)
5124 REGISTER struct ioarg *ap;
5129 DBGPRINTF3(("QGRAVECHAR: enter, ap=0x%x, iop=0x%x\n", ap, iop));
5134 return ('\n' | QUOTE);
5138 } else if ((c = filechar(ap)) == '\n') {
5140 while ((c = filechar(ap)) == '\n')
5148 return (c != 0 ? c | QUOTE : 0);
5152 * Return a single command (usually the first line) from a file.
5154 static int linechar(ap)
5155 REGISTER struct ioarg *ap;
5159 if ((c = filechar(ap)) == '\n') {
5162 ap->afile = -1; /* illegal value */
5169 REGISTER const char *s;
5172 write(2, s, strlen(s));
5181 static void closef(i)
5188 static void closeall()
5192 for (u = NUFILE; u < NOFILE;)
5198 * remap fd into Shell's fd space
5200 static int remap(fd)
5208 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
5211 for (i = 0; i < NOFILE; i++)
5218 } while (fd >= 0 && fd < e.iofd);
5220 for (i = 0; i < NOFILE; i++)
5225 err("too many files open in shell");
5231 static int openpipe(pv)
5236 if ((i = pipe(pv)) < 0)
5237 err("can't create pipe - try again");
5241 static void closepipe(pv)
5250 /* -------- here.c -------- */
5256 static void markhere(s, iop)
5260 REGISTER struct here *h, *lh;
5262 DBGPRINTF7(("MARKHERE: enter, s=0x%x\n", s));
5264 h = (struct here *) space(sizeof(struct here));
5268 h->h_tag = evalstr(s, DOSUB);
5278 for (lh = inhere; lh != NULL; lh = lh->h_next)
5279 if (lh->h_next == 0) {
5283 iop->io_flag |= IOHERE | IOXHERE;
5284 for (s = h->h_tag; *s; s++)
5286 iop->io_flag &= ~IOXHERE;
5289 h->h_dosub = iop->io_flag & IOXHERE;
5292 static void gethere()
5294 REGISTER struct here *h, *hp;
5296 DBGPRINTF7(("GETHERE: enter...\n"));
5298 /* Scan here files first leaving inhere list in place */
5299 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5300 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5302 /* Make inhere list active - keep list intact for scraphere */
5304 hp->h_next = acthere;
5310 static void readhere(name, s, ec)
5316 char tname[30] = ".msh_XXXXXX";
5319 char myline[LINELIM + 1];
5322 DBGPRINTF7(("READHERE: enter, name=0x%x, s=0x%x\n", name, s));
5324 tf = mkstemp(tname);
5328 *name = strsave(tname, areanum);
5329 if (newenv(setjmp(errpt = ev)) != 0)
5332 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5335 if (interactive && e.iop <= iostack) {
5336 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5337 current_prompt = cprompt->value;
5339 prs(cprompt->value);
5343 while ((c = my_getc(ec)) != '\n' && c) {
5346 if (thenext >= &myline[LINELIM]) {
5353 if (strcmp(s, myline) == 0 || c == 0)
5356 write(tf, myline, (int) (thenext - myline));
5359 prs("here document `");
5369 * open here temp file.
5370 * if unquoted here, expand here temp file into second temp file.
5372 static int herein(hname, xdoll)
5380 /* Avoid longjmp clobbering */
5386 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5388 hf = open(hname, 0);
5394 char tname[30] = ".msh_XXXXXX";
5397 tf = mkstemp(tname);
5400 if (newenv(setjmp(errpt = ev)) == 0) {
5401 PUSHIO(afile, hf, herechar);
5403 while ((c = subgetc(0, 0)) != 0) {
5405 write(tf, &c, sizeof c);
5411 tf = open(tname, 0);
5418 static void scraphere()
5420 REGISTER struct here *h;
5422 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5424 for (h = inhere; h != NULL; h = h->h_next) {
5425 if (h->h_iop && h->h_iop->io_name)
5426 unlink(h->h_iop->io_name);
5431 /* unlink here temp files before a freearea(area) */
5432 static void freehere(area)
5435 REGISTER struct here *h, *hl;
5437 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5440 for (h = acthere; h != NULL; h = h->h_next)
5441 if (getarea((char *) h) >= area) {
5442 if (h->h_iop->io_name != NULL)
5443 unlink(h->h_iop->io_name);
5445 acthere = h->h_next;
5447 hl->h_next = h->h_next;
5455 * Copyright (c) 1987,1997, Prentice Hall
5456 * All rights reserved.
5458 * Redistribution and use of the MINIX operating system in source and
5459 * binary forms, with or without modification, are permitted provided
5460 * that the following conditions are met:
5462 * Redistributions of source code must retain the above copyright
5463 * notice, this list of conditions and the following disclaimer.
5465 * Redistributions in binary form must reproduce the above
5466 * copyright notice, this list of conditions and the following
5467 * disclaimer in the documentation and/or other materials provided
5468 * with the distribution.
5470 * Neither the name of Prentice Hall nor the names of the software
5471 * authors or contributors may be used to endorse or promote
5472 * products derived from this software without specific prior
5473 * written permission.
5475 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5476 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5477 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5478 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5479 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5480 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5481 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5482 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5483 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5484 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5485 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5486 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.