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);
780 void print_t(struct op *t)
782 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
783 T_CMD_NAMES[t->type], t->words, t->ioact));
786 DBGPRINTF(("T: W1: %s", t->words[0]));
792 void print_tree(struct op *head);
793 void print_tree(struct op *head)
796 DBGPRINTF(("PRINT_TREE: no tree\n"));
800 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
804 print_tree(head->left);
807 print_tree(head->right);
811 #endif /* MSHDEBUG */
814 #ifdef CONFIG_FEATURE_COMMAND_EDITING
815 static char *current_prompt;
818 /* -------- sh.c -------- */
824 int msh_main(int argc, char **argv)
830 int (*iof) (struct ioarg *);
832 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
835 if ((ap = environ) != NULL) {
837 assign(*ap++, !COPYV);
838 for (ap = environ; *ap;)
839 export(lookup(*ap++));
844 shell = lookup("SHELL");
845 if (shell->value == null)
846 setval(shell, (char *)DEFAULT_SHELL);
849 homedir = lookup("HOME");
850 if (homedir->value == null)
851 setval(homedir, "/");
854 setval(lookup("$"), putn(getpid()));
856 path = lookup("PATH");
857 if (path->value == null) {
859 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
861 setval(path, "/bin:/usr/bin");
866 if (ifs->value == null)
867 setval(ifs, " \t\n");
870 mshdbg_var = lookup("MSHDEBUG");
871 if (mshdbg_var->value == null)
872 setval(mshdbg_var, "0");
876 prompt = lookup("PS1");
877 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
878 if (prompt->value == null)
880 setval(prompt, "$ ");
881 if (geteuid() == 0) {
882 setval(prompt, "# ");
883 prompt->status &= ~EXPORT;
885 cprompt = lookup("PS2");
886 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
887 if (cprompt->value == null)
889 setval(cprompt, "> ");
895 if (argv[0][0] == '-' && argv[0][1] != '\0') {
896 for (s = argv[0] + 1; *s; s++)
899 prompt->status &= ~EXPORT;
900 cprompt->status &= ~EXPORT;
905 PUSHIO(aword, *++argv, iof = nlchar);
917 prompt->status &= ~EXPORT;
925 if (*s >= 'a' && *s <= 'z')
933 if (iof == filechar && --argc > 0) {
936 prompt->status &= ~EXPORT;
937 cprompt->status &= ~EXPORT;
939 /* Shell is non-interactive, activate printf-based debug */
941 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
945 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
947 if (newfile(name = *++argv))
948 exit(1); /* Exit on error */
954 /* This won't be true if PUSHIO has been called, say from newfile() above */
955 if (e.iop < iostack) {
956 PUSHIO(afile, 0, iof);
957 if (isatty(0) && isatty(1) && !cflag) {
959 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
961 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
963 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
965 printf("Enter 'help' for a list of built-in commands.\n\n");
970 signal(SIGQUIT, qflag);
971 if (name && name[0] == '-') {
973 if ((f = open(".profile", 0)) >= 0)
975 if ((f = open("/etc/profile", 0)) >= 0)
979 signal(SIGTERM, sig);
981 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
982 signal(SIGINT, onintr);
987 for (ap = ++argv; --argc > 0;) {
988 if (assign(*ap = *argv++, !COPYV)) {
989 dolc--; /* keyword */
995 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
997 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
1000 if (interactive && e.iop <= iostack) {
1001 #ifdef CONFIG_FEATURE_COMMAND_EDITING
1002 current_prompt = prompt->value;
1008 /* Ensure that getenv("PATH") stays current */
1009 setenv("PATH", path->value, 1);
1012 DBGPRINTF(("MSH_MAIN: returning.\n"));
1015 static void setdash()
1019 char m['z' - 'a' + 1];
1022 for (c = 'a'; c <= 'z'; c++)
1026 setval(lookup("-"), m);
1029 static int newfile(s)
1034 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1036 if (strcmp(s, "-") != 0) {
1037 DBGPRINTF(("NEWFILE: s is %s\n", s));
1041 err(": cannot open");
1052 struct op *scantree(head)
1060 if (head->left != NULL) {
1061 dotnode = scantree(head->left);
1066 if (head->right != NULL) {
1067 dotnode = scantree(head->right);
1072 if (head->words == NULL)
1075 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1077 if ((head->type != TDOT) && (strcmp(".", head->words[0]) == 0)) {
1078 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1086 static void onecommand()
1091 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1110 setjmp(failpt = m1); /* Bruce Evans' fix */
1111 if (setjmp(failpt = m1) || yyparse() || intr) {
1113 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1118 if (!interactive && intr)
1131 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1133 execute(outtree, NOPIPE, NOPIPE, 0);
1136 if (!interactive && intr) {
1141 if ((i = trapset) != 0) {
1155 DBGPRINTF(("LEAVE: leave called!\n"));
1187 longjmp(e.errpt, 1);
1189 e.iop = e.iobase = iostack;
1192 static int newenv(f)
1195 REGISTER struct env *ep;
1197 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1204 ep = (struct env *) space(sizeof(*ep));
1217 static void quitenv()
1219 REGISTER struct env *ep;
1222 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1224 if ((ep = e.oenv) != NULL) {
1227 /* should close `'d files */
1229 while (--fd >= e.iofd)
1235 * Is any character from s1 in s2?
1237 static int anys(s1, s2)
1238 REGISTER char *s1, *s2;
1247 * Is character c in s?
1249 static int any(c, s)
1259 static char *putn(n)
1265 static char *itoa(n)
1270 snprintf(s, sizeof(s), "%u", n);
1275 static void next(int f)
1277 PUSHIO(afile, f, filechar);
1280 static void onintr(s)
1281 int s; /* ANSI C requires a parameter */
1283 signal(SIGINT, onintr);
1290 } else if (heedint) {
1296 static char *space(n)
1301 if ((cp = getcell(n)) == 0)
1302 err("out of string space");
1306 static char *strsave(s, a)
1310 REGISTER char *cp, *xp;
1312 if ((cp = space(strlen(s) + 1)) != NULL) {
1313 setarea((char *) cp, a);
1314 for (xp = cp; (*xp++ = *s++) != '\0';);
1330 static void runtrap(i)
1335 if ((trapstr = trap[i]) == NULL)
1341 RUN(aword, trapstr, nlchar);
1344 /* -------- var.c -------- */
1347 * Find the given name in the dictionary
1348 * and return its value. If the name was
1349 * not previously there, enter it now and
1350 * return a null value.
1352 static struct var *lookup(n)
1355 REGISTER struct var *vp;
1358 static struct var dummy;
1362 for (c = 0; isdigit(*n) && c < 1000; n++)
1363 c = c * 10 + *n - '0';
1364 dummy.status = RONLY;
1365 dummy.value = c <= dolc ? dolv[c] : null;
1368 for (vp = vlist; vp; vp = vp->next)
1369 if (eqname(vp->name, n))
1372 vp = (struct var *) space(sizeof(*vp));
1373 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1374 dummy.name = dummy.value = "";
1377 for (cp = vp->name; (*cp = *n++) && *cp != '='; cp++);
1381 setarea((char *) vp, 0);
1382 setarea((char *) vp->name, 0);
1385 vp->status = GETCELL;
1391 * give variable at `vp' the value `val'.
1393 static void setval(vp, val)
1397 nameval(vp, val, (char *) NULL);
1401 * if name is not NULL, it must be
1402 * a prefix of the space `val',
1404 * this is all so that exporting
1405 * values is reasonably painless.
1407 static void nameval(vp, val, name)
1408 REGISTER struct var *vp;
1411 REGISTER char *cp, *xp;
1415 if (vp->status & RONLY) {
1416 for (xp = vp->name; *xp && *xp != '=';)
1417 putc(*xp++, stderr);
1418 err(" is read-only");
1423 xp = space(strlen(vp->name) + strlen(val) + 2);
1426 /* make string: name=value */
1427 setarea((char *) xp, 0);
1429 for (cp = vp->name; (*xp = *cp++) && *xp != '='; xp++);
1433 for (cp = val; (*xp++ = *cp++) != '\0';);
1437 if (vp->status & GETCELL)
1438 freecell(vp->name); /* form new string `name=value' */
1444 static void export(vp)
1447 vp->status |= EXPORT;
1450 static void ronly(vp)
1453 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1454 vp->status |= RONLY;
1457 static int isassign(s)
1460 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1462 if (!isalpha((int) *s) && *s != '_')
1464 for (; *s != '='; s++)
1465 if (*s == 0 || (!isalnum(*s) && *s != '_'))
1471 static int assign(s, cf)
1478 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1480 if (!isalpha(*s) && *s != '_')
1482 for (cp = s; *cp != '='; cp++)
1483 if (*cp == 0 || (!isalnum(*cp) && *cp != '_'))
1486 nameval(vp, ++cp, cf == COPYV ? (char *) NULL : s);
1488 vp->status &= ~GETCELL;
1492 static int checkname(cp)
1495 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1497 if (!isalpha(*cp++) && *(cp - 1) != '_')
1500 if (!isalnum(*cp++) && *(cp - 1) != '_')
1505 static void putvlist(f, out)
1506 REGISTER int f, out;
1508 REGISTER struct var *vp;
1510 for (vp = vlist; vp; vp = vp->next)
1511 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1512 if (vp->status & EXPORT)
1513 write(out, "export ", 7);
1514 if (vp->status & RONLY)
1515 write(out, "readonly ", 9);
1516 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1517 write(out, "\n", 1);
1521 static int eqname(n1, n2)
1522 REGISTER char *n1, *n2;
1524 for (; *n1 != '=' && *n1 != 0; n1++)
1527 return (*n2 == 0 || *n2 == '=');
1530 static char *findeq(cp)
1533 while (*cp != '\0' && *cp != '=')
1538 /* -------- gmatch.c -------- */
1540 * int gmatch(string, pattern)
1541 * char *string, *pattern;
1543 * Match a pattern as in sh(1).
1548 #define QMASK (CMASK&~QUOTE)
1549 #define NOT '!' /* might use ^ */
1551 static int gmatch(s, p)
1552 REGISTER char *s, *p;
1554 REGISTER int sc, pc;
1556 if (s == NULL || p == NULL)
1558 while ((pc = *p++ & CMASK) != '\0') {
1562 if ((p = cclass(p, sc)) == NULL)
1574 if (*p == '\0' || gmatch(s, p))
1576 } while (*s++ != '\0');
1580 if (sc != (pc & ~QUOTE))
1587 static char *cclass(p, sub)
1591 REGISTER int c, d, not, found;
1593 if ((not = *p == NOT) != 0)
1598 return ((char *) NULL);
1600 if (p[1] == '-' && p[2] != ']') {
1605 if (c == sub || (c <= sub && sub <= d))
1607 } while (*++p != ']');
1608 return (found ? p + 1 : (char *) NULL);
1612 /* -------- area.c -------- */
1615 * All memory between (char *)areabot and (char *)(areatop+1) is
1616 * exclusively administered by the area management routines.
1617 * It is assumed that sbrk() and brk() manipulate the high end.
1620 #define sbrk(X) ({ void * __q = (void *)-1; if (brkaddr + (int)(X) < brktop) { __q = brkaddr; brkaddr+=(int)(X); } __q;})
1622 static void initarea()
1624 brkaddr = malloc(AREASIZE);
1625 brktop = brkaddr + AREASIZE;
1627 while ((long) sbrk(0) & ALIGN)
1629 areabot = (struct region *) sbrk(REGSIZE);
1631 areabot->next = areabot;
1632 areabot->area = BUSY;
1637 char *getcell(nbytes)
1640 REGISTER int nregio;
1641 REGISTER struct region *p, *q;
1648 /* silly and defeats the algorithm */
1650 * round upwards and add administration area
1652 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
1653 for (p = areanxt;;) {
1654 if (p->area > areanum) {
1658 while ((q = p->next)->area > areanum && q != areanxt)
1661 * exit loop if cell big enough
1663 if (q >= p + nregio)
1670 i = nregio >= GROWBY ? nregio : GROWBY;
1671 p = (struct region *) sbrk(i * REGSIZE);
1672 if (p == (struct region *) -1)
1673 return ((char *) NULL);
1677 abort(); /* allocated areas are contiguous */
1687 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
1689 areanxt = p + nregio;
1692 * split into requested area and rest
1694 if (areanxt + 1 > q) {
1696 abort(); /* insufficient space left for admin */
1699 areanxt->area = FREE;
1703 return ((char *) (p + 1));
1706 static void freecell(cp)
1709 REGISTER struct region *p;
1711 if ((p = (struct region *) cp) != NULL) {
1719 static void freearea(a)
1722 REGISTER struct region *p, *top;
1725 for (p = areabot; p != top; p = p->next)
1730 static void setarea(cp, a)
1734 REGISTER struct region *p;
1736 if ((p = (struct region *) cp) != NULL)
1743 return ((struct region *) cp - 1)->area;
1746 static void garbage()
1748 REGISTER struct region *p, *q, *top;
1751 for (p = areabot; p != top; p = p->next) {
1752 if (p->area > areanum) {
1753 while ((q = p->next)->area > areanum)
1759 if (areatop >= q + SHRINKBY && q->area > areanum) {
1760 brk((char *) (q + 1));
1768 /* -------- csyn.c -------- */
1770 * shell: syntax (C version)
1775 DBGPRINTF7(("YYPARSE: enter...\n"));
1782 return (yynerrs != 0);
1785 static struct op *pipeline(cf)
1788 REGISTER struct op *t, *p;
1791 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1795 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1798 while ((c = yylex(0)) == '|') {
1799 if ((p = command(CONTIN)) == NULL) {
1800 DBGPRINTF8(("PIPELINE: error!\n"));
1804 if (t->type != TPAREN && t->type != TCOM) {
1805 /* shell statement */
1806 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1809 t = block(TPIPE, t, p, NOWORDS);
1814 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1818 static struct op *andor()
1820 REGISTER struct op *t, *p;
1823 DBGPRINTF7(("ANDOR: enter...\n"));
1827 DBGPRINTF9(("ANDOR: t=%p\n", t));
1830 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1831 if ((p = pipeline(CONTIN)) == NULL) {
1832 DBGPRINTF8(("ANDOR: error!\n"));
1836 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1842 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1846 static struct op *c_list()
1848 REGISTER struct op *t, *p;
1851 DBGPRINTF7(("C_LIST: enter...\n"));
1856 if ((peeksym = yylex(0)) == '&')
1857 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1859 while ((c = yylex(0)) == ';' || c == '&'
1860 || (multiline && c == '\n')) {
1862 if ((p = andor()) == NULL)
1865 if ((peeksym = yylex(0)) == '&')
1866 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1874 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1878 static int synio(cf)
1881 REGISTER struct ioword *iop;
1885 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1887 if ((c = yylex(cf)) != '<' && c != '>') {
1894 iop = io(iounit, i, yylval.cp);
1898 markhere(yylval.cp, iop);
1900 DBGPRINTF7(("SYNIO: returning 1\n"));
1904 static void musthave(c, cf)
1907 if ((peeksym = yylex(cf)) != c) {
1908 DBGPRINTF7(("MUSTHAVE: error!\n"));
1915 static struct op *simple()
1917 REGISTER struct op *t;
1921 switch (peeksym = yylex(0)) {
1942 static struct op *nested(type, mark)
1945 REGISTER struct op *t;
1947 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1953 return (block(type, t, NOBLOCK, NOWORDS));
1956 static struct op *command(cf)
1959 REGISTER struct op *t;
1960 struct wdblock *iosave;
1963 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1979 if ((t = simple()) == NULL) {
1981 return ((struct op *) NULL);
1988 t = nested(TPAREN, ')');
1992 t = nested(TBRACE, '}');
2002 t->words = wordlist();
2003 if ((c = yylex(0)) != '\n' && c != ';')
2005 t->left = dogroup(0);
2013 t->type = c == WHILE ? TWHILE : TUNTIL;
2015 t->right = dogroup(1);
2027 musthave(IN, CONTIN);
2030 t->left = caselist();
2041 t->right = thenpart();
2050 musthave(WORD, 0); /* gets name of file */
2051 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
2053 word(yylval.cp); /* add word to wdlist */
2054 word(NOWORD); /* terminate wdlist */
2055 t->words = copyw(); /* dup wdlist */
2065 DBGPRINTF(("COMMAND: returning %p\n", t));
2070 static struct op *dowholefile(type, mark)
2074 REGISTER struct op *t;
2076 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
2081 t = block(type, t, NOBLOCK, NOWORDS);
2082 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
2086 static struct op *dogroup(onlydone)
2090 REGISTER struct op *mylist;
2093 if (c == DONE && onlydone)
2094 return ((struct op *) NULL);
2102 static struct op *thenpart()
2105 REGISTER struct op *t;
2107 if ((c = yylex(0)) != THEN) {
2109 return ((struct op *) NULL);
2114 if (t->left == NULL)
2116 t->right = elsepart();
2120 static struct op *elsepart()
2123 REGISTER struct op *t;
2125 switch (c = yylex(0)) {
2127 if ((t = c_list()) == NULL)
2135 t->right = thenpart();
2140 return ((struct op *) NULL);
2144 static struct op *caselist()
2146 REGISTER struct op *t;
2149 while ((peeksym = yylex(CONTIN)) != ESAC) {
2150 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
2151 t = list(t, casepart());
2154 DBGPRINTF(("CASELIST, returning t=%p\n", t));
2158 static struct op *casepart()
2160 REGISTER struct op *t;
2162 DBGPRINTF7(("CASEPART: enter...\n"));
2166 t->words = pattern();
2169 if ((peeksym = yylex(CONTIN)) != ESAC)
2170 musthave(BREAK, CONTIN);
2172 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2177 static char **pattern()
2186 } while ((c = yylex(0)) == '|');
2193 static char **wordlist()
2197 if ((c = yylex(0)) != IN) {
2199 return ((char **) NULL);
2202 while ((c = yylex(0)) == WORD)
2210 * supporting functions
2212 static struct op *list(t1, t2)
2213 REGISTER struct op *t1, *t2;
2215 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2222 return (block(TLIST, t1, t2, NOWORDS));
2225 static struct op *block(type, t1, t2, wp)
2230 REGISTER struct op *t;
2232 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2240 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2246 /* See if given string is a shell multiline (FOR, IF, etc) */
2247 static int rlookup(n)
2250 REGISTER const struct res *rp;
2252 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2254 for (rp = restab; rp->r_name; rp++)
2255 if (strcmp(rp->r_name, n) == 0) {
2256 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2257 return (rp->r_val); /* Return numeric code for shell multiline */
2260 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2261 return (0); /* Not a shell multiline */
2264 static struct op *newtp()
2266 REGISTER struct op *t;
2268 t = (struct op *) tree(sizeof(*t));
2276 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2281 static struct op *namelist(t)
2282 REGISTER struct op *t;
2285 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2286 T_CMD_NAMES[t->type], iolist));
2289 iolist = addword((char *) NULL, iolist);
2290 t->ioact = copyio();
2294 if (t->type != TCOM) {
2295 if (t->type != TPAREN && t->ioact != NULL) {
2296 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2297 t->ioact = t->left->ioact;
2298 t->left->ioact = NULL;
2310 static char **copyw()
2314 wd = getwords(wdlist);
2319 static void word(cp)
2322 wdlist = addword(cp, wdlist);
2325 static struct ioword **copyio()
2327 REGISTER struct ioword **iop;
2329 iop = (struct ioword **) getwords(iolist);
2334 static struct ioword *io(u, f, cp)
2339 REGISTER struct ioword *iop;
2341 iop = (struct ioword *) tree(sizeof(*iop));
2345 iolist = addword((char *) iop, iolist);
2351 yyerror("syntax error");
2354 static void yyerror(s)
2358 if (interactive && e.iop <= iostack) {
2360 while (eofc() == 0 && yylex(0) != '\n');
2366 static int yylex(cf)
2372 if ((c = peeksym) > 0) {
2387 line[LINELIM - 1] = '\0';
2390 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2395 if (any(c, "0123456789")) {
2396 unget(c1 = my_getc(0));
2397 if (c1 == '<' || c1 == '>') {
2406 case '#': /* Comment, skip to next newline or End-of-string */
2407 while ((c = my_getc(0)) != 0 && c != '\n');
2412 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2416 DBGPRINTF9(("YYLEX: found $\n"));
2418 if ((c = my_getc(0)) == '{') {
2419 if ((c = collect(c, '}')) != '\0')
2428 if ((c = collect(c, c)) != '\0')
2436 /* If more chars process them, else return NULL char */
2437 if ((c1 = dual(c)) != '\0')
2454 if (multiline || cf & CONTIN) {
2455 if (interactive && e.iop <= iostack) {
2456 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2457 current_prompt = cprompt->value;
2459 prs(cprompt->value);
2476 while ((c = my_getc(0)) != 0 && !any(c, "`$ '\"\t;&<>()|^\n")) {
2477 if (e.linep >= elinep)
2478 err("word too long");
2485 if (any(c, "\"'`$"))
2490 if (atstart && (c = rlookup(line)) != 0) {
2495 yylval.cp = strsave(line, areanum);
2500 static int collect(c, c1)
2505 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2508 while ((c = my_getc(c1)) != c1) {
2517 if (interactive && c == '\n' && e.iop <= iostack) {
2518 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2519 current_prompt = cprompt->value;
2521 prs(cprompt->value);
2529 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2534 /* "multiline commands" helper func */
2535 /* see if next 2 chars form a shell multiline */
2540 REGISTER char *cp = s;
2542 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2544 *cp++ = c; /* c is the given "peek" char */
2545 *cp++ = my_getc(0); /* get next char of input */
2546 *cp = 0; /* add EOS marker */
2548 c = rlookup(s); /* see if 2 chars form a shell multiline */
2550 unget(*--cp); /* String is not a shell multiline, put peek char back */
2552 return (c); /* String is multiline, return numeric multiline (restab) code */
2555 static void diag(ec)
2560 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2563 if (c == '>' || c == '<') {
2566 yylval.i = ec == '>' ? IOWRITE | IOCAT : IOHERE;
2569 yylval.i = ec == '>' ? IOWRITE : IOREAD;
2570 if (c != '&' || yylval.i == IOHERE)
2576 static char *tree(size)
2581 if ((t = getcell(size)) == NULL) {
2582 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2583 prs("command line too complicated\n");
2593 /* -------- exec.c -------- */
2600 static int execute(t, pin, pout, act)
2601 REGISTER struct op *t;
2605 REGISTER struct op *t1;
2606 volatile int i, rv, a;
2607 char *cp, **wp, **wp2;
2609 struct op *outtree_save;
2613 /* Avoid longjmp clobbering */
2618 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2622 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2623 t->type, T_CMD_NAMES[t->type],
2624 ((t->words == NULL) ? "NULL" : t->words[0])));
2628 wp = (wp2 = t->words) != NULL
2629 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2632 /* Hard to know how many words there are, be careful of garbage pointer values */
2633 /* They are likely to cause "PCI bus fault" errors */
2635 DBGPRINTF(("EXECUTE: t->left=%p, t->right=%p, t->words[1] is %s\n",
2637 ((t->words[1] == NULL) ? "NULL" : t->words[1])));
2638 DBGPRINTF7(("EXECUTE: t->words[2] is %s, t->words[3] is %s\n",
2639 ((t->words[2] == NULL) ? "NULL" : t->words[2]),
2640 ((t->words[3] == NULL) ? "NULL" : t->words[3])));
2646 DBGPRINTF3(("EXECUTE: TDOT\n"));
2648 outtree_save = outtree;
2650 newfile(evalstr(t->words[0], DOALL));
2652 t->left = dowholefile(TLIST, 0);
2655 outtree = outtree_save;
2658 rv = execute(t->left, pin, pout, 0);
2660 rv = execute(t->right, pin, pout, 0);
2664 rv = execute(t->left, pin, pout, 0);
2669 rv = forkexec(t, pin, pout, act, wp);
2677 if ((rv = openpipe(pv)) < 0)
2679 pv[0] = remap(pv[0]);
2680 pv[1] = remap(pv[1]);
2681 (void) execute(t->left, pin, pv, 0);
2682 rv = execute(t->right, pv, pout, 0);
2687 (void) execute(t->left, pin, pout, 0);
2688 rv = execute(t->right, pin, pout, 0);
2693 int hinteractive = interactive;
2695 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2699 interactive = hinteractive;
2701 setval(lookup("!"), putn(i));
2712 signal(SIGINT, SIG_IGN);
2713 signal(SIGQUIT, SIG_IGN);
2715 signal(SIGTERM, SIG_DFL);
2719 open(bb_dev_null, 0);
2721 _exit(execute(t->left, pin, pout, FEXEC));
2728 rv = execute(t->left, pin, pout, 0);
2729 if ((t1 = t->right) != NULL && (rv == 0) == (t->type == TAND))
2730 rv = execute(t1, pin, pout, 0);
2740 while (*wp++ != NULL);
2742 vp = lookup(t->str);
2743 while (setjmp(bc.brkpt))
2747 for (t1 = t->left; i-- && *wp != NULL;) {
2749 rv = execute(t1, pin, pout, 0);
2751 brklist = brklist->nextlev;
2756 while (setjmp(bc.brkpt))
2761 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2762 rv = execute(t->right, pin, pout, 0);
2763 brklist = brklist->nextlev;
2768 if (t->right != NULL) {
2769 rv = !execute(t->left, pin, pout, 0) ?
2770 execute(t->right->left, pin, pout, 0) :
2771 execute(t->right->right, pin, pout, 0);
2776 if ((cp = evalstr(t->str, DOSUB | DOTRIM)) == 0)
2779 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2780 ((t->str == NULL) ? "NULL" : t->str),
2781 ((cp == NULL) ? "NULL" : cp)));
2783 if ((t1 = findcase(t->left, cp)) != NULL) {
2784 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2785 rv = execute(t1, pin, pout, 0);
2786 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2792 if (iopp = t->ioact)
2794 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2799 if (rv >= 0 && (t1 = t->left))
2800 rv = execute(t1, pin, pout, 0);
2811 if (interactive && intr) {
2816 if ((i = trapset) != 0) {
2821 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2826 forkexec(REGISTER struct op *t, int *pin, int *pout, int act, char **wp)
2830 int (*shcom) (struct op *) = NULL;
2833 struct ioword **iopp;
2843 struct brkcon *hbrklist;
2847 /* Avoid longjmp clobbering */
2857 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2859 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2860 ((t->words == NULL) ? "NULL" : t->words[0])));
2862 /* Hard to know how many words there are, be careful of garbage pointer values */
2863 /* They are likely to cause "PCI bus fault" errors */
2865 DBGPRINTF7(("FORKEXEC: t->words is %s, t->words[1] is %s\n",
2866 ((t->words == NULL) ? "NULL" : t->words[0]),
2867 ((t->words == NULL) ? "NULL" : t->words[1])));
2868 DBGPRINTF7(("FORKEXEC: wp is %s, wp[1] is %s\n",
2869 ((wp == NULL) ? "NULL" : wp[0]),
2870 ((wp[1] == NULL) ? "NULL" : wp[1])));
2871 DBGPRINTF7(("FORKEXEC: wp2 is %s, wp[3] is %s\n",
2872 ((wp[2] == NULL) ? "NULL" : wp[2]),
2873 ((wp[3] == NULL) ? "NULL" : wp[3])));
2879 rv = -1; /* system-detected error */
2880 if (t->type == TCOM) {
2881 while ((cp = *wp++) != NULL);
2884 /* strip all initial assignments */
2885 /* not correct wrt PATH=yyy command etc */
2887 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2889 echo(cp ? wp : owp);
2892 DBGPRINTF9(("FORKEXEC: t->words is %s, t->words[1] is %s\n",
2893 ((t->words == NULL) ? "NULL" : t->words[0]),
2894 ((t->words == NULL) ? "NULL" : t->words[1])));
2895 DBGPRINTF9(("FORKEXEC: wp is %s, wp[1] is %s\n",
2896 ((wp == NULL) ? "NULL" : wp[0]),
2897 ((wp == NULL) ? "NULL" : wp[1])));
2900 if (cp == NULL && t->ioact == NULL) {
2901 while ((cp = *owp++) != NULL && assign(cp, COPYV));
2902 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2903 return (setstatus(0));
2904 } else if (cp != NULL) {
2905 shcom = inbuilt(cp);
2913 DBGPRINTF3(("FORKEXEC: t->words is %s, t->words[1] is %s\n",
2914 ((t->words == NULL) ? "NULL" : t->words[0]),
2915 ((t->words == NULL) ? "NULL" : t->words[1])));
2917 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2920 if (shcom == NULL && (f & FEXEC) == 0) {
2921 /* Save values in case the child process alters them */
2925 hinteractive = interactive;
2930 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2935 DBGPRINTF(("FORKEXEC: ERROR, unable to vfork()!\n"));
2940 if (newpid > 0) { /* Parent */
2942 /* Restore values */
2946 interactive = hinteractive;
2959 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2962 /* Must be the child process, pid should be 0 */
2963 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2966 signal(SIGINT, SIG_IGN);
2967 signal(SIGQUIT, SIG_IGN);
2979 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2984 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2985 err("piping to/from shell builtins not yet done");
3001 if ((iopp = t->ioact) != NULL) {
3002 if (shcom != NULL && shcom != doexec) {
3004 err(": cannot redirect shell command");
3010 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
3018 i = setstatus((*shcom) (t));
3021 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
3025 /* should use FIOCEXCL */
3026 for (i = FDBASE; i < NOFILE; i++)
3029 signal(SIGINT, SIG_DFL);
3030 signal(SIGQUIT, SIG_DFL);
3032 /* put non-interactive processes into a different process group.
3033 * we don't support jobs, but this is at least sane: see Bug 659 */
3037 if (t->type == TPAREN)
3038 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
3042 cp = rexecve(wp[0], wp, makenv(0, NULL));
3049 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
3057 * 0< 1> are ignored as required
3060 static int iosetup(iop, pipein, pipeout)
3061 REGISTER struct ioword *iop;
3062 int pipein, pipeout;
3064 REGISTER int u = -1;
3065 char *cp = NULL, *msg;
3067 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
3070 if (iop->io_unit == IODEFAULT) /* take default */
3071 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
3073 if (pipein && iop->io_unit == 0)
3076 if (pipeout && iop->io_unit == 1)
3079 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
3080 if ((iop->io_flag & IOHERE) == 0) {
3082 if ((cp = evalstr(cp, DOSUB | DOTRIM)) == NULL)
3086 if (iop->io_flag & IODUP) {
3087 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
3089 err(": illegal >& argument");
3093 iop->io_flag = IOCLOSE;
3094 iop->io_flag &= ~(IOREAD | IOWRITE);
3096 switch (iop->io_flag) {
3102 case IOHERE | IOXHERE:
3103 u = herein(iop->io_name, iop->io_flag & IOXHERE);
3107 case IOWRITE | IOCAT:
3108 if ((u = open(cp, 1)) >= 0) {
3109 lseek(u, (long) 0, 2);
3113 u = creat(cp, 0666);
3117 u = dup2(*cp - '0', iop->io_unit);
3121 close(iop->io_unit);
3130 if (u != iop->io_unit) {
3131 dup2(u, iop->io_unit);
3138 static void echo(wp)
3144 for (i = 0; wp[i]; i++) {
3152 static struct op **find1case(t, w)
3156 REGISTER struct op *t1;
3158 REGISTER char **wp, *cp;
3162 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
3163 return ((struct op **) NULL);
3166 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
3167 T_CMD_NAMES[t->type]));
3169 if (t->type == TLIST) {
3170 if ((tp = find1case(t->left, w)) != NULL) {
3171 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
3174 t1 = t->right; /* TPAT */
3178 for (wp = t1->words; *wp;)
3179 if ((cp = evalstr(*wp++, DOSUB)) && gmatch(w, cp)) {
3180 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
3185 DBGPRINTF(("FIND1CASE: returning NULL\n"));
3186 return ((struct op **) NULL);
3189 static struct op *findcase(t, w)
3193 REGISTER struct op **tp;
3195 return ((tp = find1case(t, w)) != NULL ? *tp : (struct op *) NULL);
3199 * Enter a new loop level (marked for break/continue).
3201 static void brkset(bc)
3204 bc->nextlev = brklist;
3209 * Wait for the last process created.
3210 * Print a message for each process found
3211 * that was killed by a signal.
3212 * Ignore interrupt signals while waiting
3213 * unless `canintr' is true.
3215 static int waitfor(lastpid, canintr)
3216 REGISTER int lastpid;
3219 REGISTER int pid, rv;
3221 int oheedint = heedint;
3228 if (errno != EINTR || canintr)
3231 if ((rv = WAITSIG(s)) != 0) {
3233 if (signame[rv] != NULL) {
3234 if (pid != lastpid) {
3241 if (pid != lastpid) {
3250 prs(" - core dumped");
3251 if (rv >= NSIGNAL || signame[rv])
3257 } while (pid != lastpid);
3272 static int setstatus(s)
3276 setval(lookup("?"), putn(s));
3281 * PATH-searching interface to execve.
3282 * If getenv("PATH") were kept up-to-date,
3283 * execvp might be used.
3285 static char *rexecve(c, v, envp)
3286 char *c, **v, **envp;
3289 REGISTER char *sp, *tp;
3290 int eacces = 0, asis = 0;
3292 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3296 if (find_applet_by_name(name)) {
3297 /* We have to exec here since we vforked. Running
3298 * run_applet_by_name() won't work and bad things
3300 execve("/proc/self/exe", v, envp);
3301 execve("busybox", v, envp);
3305 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3307 sp = any('/', c) ? "" : path->value;
3309 while (asis || *sp != '\0') {
3312 for (; *sp != '\0'; tp++)
3313 if ((*tp = *sp++) == ':') {
3319 for (i = 0; (*tp++ = c[i++]) != '\0';);
3321 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3323 execve(e.linep, v, envp);
3330 execve(DEFAULT_SHELL, v, envp);
3332 return ("no Shell");
3335 return ((char *) bb_msg_memory_exhausted);
3338 return ("argument list too long");
3345 return (errno == ENOENT ? "not found" : "cannot execute");
3349 * Run the command produced by generator `f'
3350 * applied to stream `arg'.
3352 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3355 struct wdblock *swdlist;
3356 struct wdblock *siolist;
3362 /* Avoid longjmp clobbering */
3366 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3367 areanum, outtree, failpt));
3376 if (newenv(setjmp(errpt = ev)) == 0) {
3382 if (setjmp(failpt = rt) == 0 && yyparse() == 0)
3383 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3386 DBGPRINTF(("RUN: error from newenv()!\n"));
3393 freearea(areanum--);
3398 /* -------- do.c -------- */
3401 * built-in commands: doX
3404 static int dohelp(struct op *t)
3407 const struct builtincmd *x;
3409 printf("\nBuilt-in commands:\n");
3410 printf("-------------------\n");
3412 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3415 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3421 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3424 const struct BB_applet *applet;
3425 extern const struct BB_applet applets[];
3426 extern const size_t NUM_APPLETS;
3428 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3432 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3441 return EXIT_SUCCESS;
3446 static int dolabel(struct op *t)
3451 static int dochdir(t)
3452 REGISTER struct op *t;
3454 REGISTER char *cp, *er;
3456 if ((cp = t->words[1]) == NULL && (cp = homedir->value) == NULL)
3457 er = ": no home directory";
3458 else if (chdir(cp) < 0)
3459 er = ": bad directory";
3462 prs(cp != NULL ? cp : "cd");
3467 static int doshift(t)
3468 REGISTER struct op *t;
3472 n = t->words[1] ? getn(t->words[1]) : 1;
3474 err("nothing to shift");
3480 setval(lookup("#"), putn(dolc));
3485 * execute login and newgrp directly
3487 static int dologin(t)
3493 signal(SIGINT, SIG_DFL);
3494 signal(SIGQUIT, SIG_DFL);
3496 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3503 static int doumask(t)
3504 REGISTER struct op *t;
3509 if ((cp = t->words[1]) == NULL) {
3512 for (n = 3 * 4; (n -= 3) >= 0;)
3513 putc('0' + ((i >> n) & 07), stderr);
3516 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3517 n = n * 8 + (*cp - '0');
3523 static int doexec(t)
3524 REGISTER struct op *t;
3531 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3536 if (setjmp(failpt = ex) == 0)
3537 execute(t, NOPIPE, NOPIPE, FEXEC);
3547 REGISTER char *sp, *tp;
3551 DBGPRINTF(("DODOT: enter, t=%p, tleft %p, tright %p, e.linep is %s\n", t, t->left, t->right, ((e.linep == NULL) ? "NULL" : e.linep)));
3553 if ((cp = t->words[1]) == NULL) {
3554 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3557 DBGPRINTF(("DODOT: cp is %s\n", cp));
3560 sp = any('/', cp) ? ":" : path->value;
3562 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3563 ((sp == NULL) ? "NULL" : sp),
3564 ((e.linep == NULL) ? "NULL" : e.linep)));
3568 while (*sp && (*tp = *sp++) != ':')
3573 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3576 if ((i = open(e.linep, 0)) >= 0) {
3579 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3581 next(maltmp); /* Basically a PUSHIO */
3583 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3596 static int dowait(t)
3602 if ((cp = t->words[1]) != NULL) {
3608 setstatus(waitfor(i, 1));
3612 static int doread(t)
3615 REGISTER char *cp, **wp;
3616 REGISTER int nb = 0;
3617 REGISTER int nl = 0;
3619 if (t->words[1] == NULL) {
3620 err("Usage: read name ...");
3623 for (wp = t->words + 1; *wp; wp++) {
3624 for (cp = e.linep; !nl && cp < elinep - 1; cp++)
3625 if ((nb = read(0, cp, sizeof(*cp))) != sizeof(*cp) ||
3626 (nl = (*cp == '\n')) || (wp[1] && any(*cp, ifs->value)))
3631 setval(lookup(*wp), e.linep);
3636 static int doeval(t)
3637 REGISTER struct op *t;
3639 return (RUN(awordlist, t->words + 1, wdchar));
3642 static int dotrap(t)
3643 REGISTER struct op *t;
3646 REGISTER int resetsig;
3648 if (t->words[1] == NULL) {
3649 for (i = 0; i <= _NSIG; i++)
3658 resetsig = isdigit(*t->words[1]);
3659 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3660 n = getsig(t->words[i]);
3664 if (*t->words[1] != '\0') {
3665 trap[n] = strsave(t->words[1], 0);
3674 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3682 static int getsig(s)
3687 if ((n = getn(s)) < 0 || n > _NSIG) {
3688 err("trap: bad signal number");
3694 static void setsig(REGISTER int n, sighandler_t f)
3698 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3716 for (n = 0; isdigit(*s); s++)
3717 n = (n * 10) + (*s - '0');
3720 err(": bad number");
3725 static int dobreak(t)
3728 return (brkcontin(t->words[1], 1));
3731 static int docontinue(t)
3734 return (brkcontin(t->words[1], 0));
3737 static int brkcontin(cp, val)
3741 REGISTER struct brkcon *bc;
3744 nl = cp == NULL ? 1 : getn(cp);
3748 if ((bc = brklist) == NULL)
3750 brklist = bc->nextlev;
3753 err("bad break/continue level");
3757 longjmp(bc->brkpt, 1);
3761 static int doexit(t)
3767 if ((cp = t->words[1]) != NULL)
3768 setstatus(getn(cp));
3770 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3777 static int doexport(t)
3780 rdexp(t->words + 1, export, EXPORT);
3784 static int doreadonly(t)
3787 rdexp(t->words + 1, ronly, RONLY);
3791 static void rdexp(char **wp, void (*f) (struct var *), int key)
3793 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3794 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3797 for (; *wp != NULL; wp++) {
3798 if (isassign(*wp)) {
3802 for (cp = *wp; *cp != '='; cp++);
3814 static void badid(s)
3818 err(": bad identifier");
3822 REGISTER struct op *t;
3824 REGISTER struct var *vp;
3828 if ((cp = t->words[1]) == NULL) {
3829 for (vp = vlist; vp; vp = vp->next)
3830 varput(vp->name, 1);
3834 /* bad: t->words++; */
3835 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3837 flag['x'] = flag['v'] = 0;
3847 if (*cp >= 'a' && *cp <= 'z')
3854 t->words[0] = dolv[0];
3855 for (n = 1; t->words[n]; n++)
3856 setarea((char *) t->words[n], 0);
3859 setval(lookup("#"), putn(dolc));
3860 setarea((char *) (dolv - 1), 0);
3865 static void varput(s, out)
3869 if (isalnum(*s) || *s == '_') {
3870 write(out, s, strlen(s));
3871 write(out, "\n", 1);
3877 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3878 * This file contains code for the times builtin.
3880 static int dotimes(struct op *t)
3883 long int clk_tck = sysconf(_SC_CLK_TCK);
3886 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3887 (int) (buf.tms_utime / clk_tck / 60),
3888 ((double) buf.tms_utime) / clk_tck,
3889 (int) (buf.tms_stime / clk_tck / 60),
3890 ((double) buf.tms_stime) / clk_tck,
3891 (int) (buf.tms_cutime / clk_tck / 60),
3892 ((double) buf.tms_cutime) / clk_tck,
3893 (int) (buf.tms_cstime / clk_tck / 60),
3894 ((double) buf.tms_cstime) / clk_tck);
3899 static int (*inbuilt(char *s)) (struct op *) {
3900 const struct builtincmd *bp;
3902 for (bp = builtincmds; bp->name != NULL; bp++)
3903 if (strcmp(bp->name, s) == 0)
3904 return (bp->builtinfunc);
3909 /* -------- eval.c -------- */
3914 * blank interpretation
3919 static char **eval(char **ap, int f)
3927 /* Avoid longjmp clobbering */
3932 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3937 if (newenv(setjmp(errpt = ev)) == 0) {
3938 while (*ap && isassign(*ap))
3939 expand(*ap++, &wb, f & ~DOGLOB);
3941 for (wf = ap; *wf; wf++) {
3943 expand(*wf, &wb, f & ~DOGLOB);
3946 for (wb = addword((char *) 0, wb); *ap; ap++) {
3947 if (!flag['k'] || !isassign(*ap))
3948 expand(*ap, &wb, f & ~DOKEY);
3950 wb = addword((char *) 0, wb);
3956 return (gflg ? (char **) NULL : wp);
3960 * Make the exported environment from the exported
3961 * names in the dictionary. Keyword assignments
3962 * will already have been done.
3964 static char **makenv(int all, struct wdblock *wb)
3966 REGISTER struct var *vp;
3968 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3970 for (vp = vlist; vp; vp = vp->next)
3971 if (all || vp->status & EXPORT)
3972 wb = addword(vp->name, wb);
3973 wb = addword((char *) 0, wb);
3974 return (getwords(wb));
3977 static char *evalstr(cp, f)
3983 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3986 if (expand(cp, &wb, f)) {
3987 if (wb == NULL || wb->w_nword == 0
3988 || (cp = wb->w_words[0]) == NULL)
3996 static int expand(char *cp, REGISTER struct wdblock **wbp, int f)
4001 /* Avoid longjmp clobbering */
4005 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
4012 if (!anys("$`'\"", cp) &&
4013 !anys(ifs->value, cp) && ((f & DOGLOB) == 0 || !anys("[*?", cp))) {
4014 cp = strsave(cp, areanum);
4017 *wbp = addword(cp, *wbp);
4020 if (newenv(setjmp(errpt = ev)) == 0) {
4021 PUSHIO(aword, cp, strchar);
4023 while ((cp = blank(f)) && gflg == 0) {
4025 cp = strsave(cp, areanum);
4026 if ((f & DOGLOB) == 0) {
4029 *wbp = addword(cp, *wbp);
4031 *wbp = glob(cp, *wbp);
4040 * Blank interpretation and quoting
4042 static char *blank(f)
4047 int scanequals, foundequals;
4049 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
4052 scanequals = f & DOKEY;
4056 switch (c = subgetc('"', foundequals)) {
4064 if (f & DOBLANK && any(c, ifs->value))
4073 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
4076 if (c == '\'' || !any(c, "$`\""))
4083 if (!isalpha(c) && c != '_')
4086 c = subgetc('"', foundequals);
4088 f & (DOBLANK && any(c, ifs->value)) ||
4089 (!INSUB() && any(c, "\"'"))) {
4100 } else if (!isalnum(c) && c != '_')
4110 * Get characters, substituting for ` and $
4112 static int subgetc(ec, quoted)
4118 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
4122 if (!INSUB() && ec != '\'') {
4124 if (grave(quoted) == 0)
4126 e.iop->task = XGRAVE;
4129 if (c == '$' && (c = dollar(quoted)) == 0) {
4130 e.iop->task = XDOLL;
4138 * Prepare to generate the string returned by ${} substitution.
4140 static int dollar(quoted)
4146 REGISTER char *s, c, *cp = NULL;
4149 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
4155 if (isalpha(c) || c == '_') {
4156 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
4157 if (e.linep < elinep)
4164 otask = e.iop->task;
4166 e.iop->task = XOTHER;
4167 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
4168 if (e.linep < elinep)
4171 e.iop->task = otask;
4178 if (e.linep >= elinep) {
4179 err("string in ${} too long");
4185 for (cp = s + 1; *cp; cp++)
4186 if (any(*cp, "=-+?")) {
4191 if (s[1] == 0 && (*s == '*' || *s == '@')) {
4193 /* currently this does not distinguish $* and $@ */
4194 /* should check dollar */
4196 PUSHIO(awordlist, dolv + 1, dolchar);
4198 } else { /* trap the nasty ${=} */
4204 if ((dolp = vp->value) == null) {
4208 err("cannot use ${...=...} with $n");
4217 dolp = strsave(cp, areanum);
4222 prs("missing value for ");
4229 } else if (c == '+')
4230 dolp = strsave(cp, areanum);
4231 if (flag['u'] && dolp == null) {
4232 prs("unset variable: ");
4237 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4242 * Run the command in `...` and read its output.
4245 static int grave(quoted)
4252 static char child_cmd[LINELIM];
4258 char *argument_list[4];
4259 struct wdblock *wb = NULL;
4262 /* Avoid longjmp clobbering */
4266 for (cp = e.iop->argp->aword; *cp != '`'; cp++)
4268 err("no closing `");
4272 /* string copy with dollar expansion */
4273 src = e.iop->argp->aword;
4278 while ((*src != '`') && (count < LINELIM)) {
4283 if (*src == '$' && !ignore && !ignore_once) {
4285 char var_name[LINELIM];
4286 char alt_value[LINELIM];
4299 var_name[var_index++] = *src++;
4300 while (isalnum(*src) || *src=='_')
4301 var_name[var_index++] = *src++;
4302 var_name[var_index] = 0;
4315 err("unclosed ${\n");
4320 while (*src && (*src != '}')) {
4321 alt_value[alt_index++] = *src++;
4323 alt_value[alt_index] = 0;
4325 err("unclosed ${\n");
4332 if (isalpha(*var_name)) {
4333 /* let subshell handle it instead */
4335 char *namep = var_name;
4343 char *altp = alt_value;
4351 wb = addword(lookup(var_name)->name, wb);
4355 vp = lookup(var_name);
4356 if (vp->value != null)
4357 value = (operator == '+') ?
4358 alt_value : vp->value;
4359 else if (operator == '?') {
4362 } else if (alt_index && (operator != '+')) {
4364 if (operator == '=')
4369 while (*value && (count < LINELIM)) {
4382 if (openpipe(pf) < 0)
4385 while ((i = vfork()) == -1 && errno == EAGAIN);
4387 DBGPRINTF3(("GRAVE: i is %p\n", io));
4391 err((char *) bb_msg_memory_exhausted);
4395 waitpid(i, NULL, 0);
4396 e.iop->argp->aword = ++cp;
4398 PUSHIO(afile, remap(pf[0]),
4399 (int (*)(struct ioarg *)) ((quoted) ? qgravechar :
4403 /* allow trapped signals */
4404 /* XXX - Maybe this signal stuff should go as well? */
4405 for (j = 0; j <= _NSIG; j++)
4406 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4412 argument_list[0] = (char *) DEFAULT_SHELL;
4413 argument_list[1] = "-c";
4414 argument_list[2] = child_cmd;
4415 argument_list[3] = 0;
4417 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4418 prs(argument_list[0]);
4425 static char *unquote(as)
4430 if ((s = as) != NULL)
4436 /* -------- glob.c -------- */
4442 #define scopy(x) strsave((x), areanum)
4444 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4446 static struct wdblock *cl, *nl;
4447 static char spcl[] = "[?*";
4449 static struct wdblock *glob(cp, wb)
4459 for (pp = cp; *pp; pp++)
4462 else if (!any(*pp & ~QUOTE, spcl))
4465 for (cl = addword(scopy(cp), (struct wdblock *) 0); anyspcl(cl);
4467 nl = newword(cl->w_nword * 2);
4468 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4469 for (pp = cl->w_words[i]; *pp; pp++)
4470 if (any(*pp, spcl)) {
4471 globname(cl->w_words[i], pp);
4475 nl = addword(scopy(cl->w_words[i]), nl);
4477 for (i = 0; i < cl->w_nword; i++)
4478 DELETE(cl->w_words[i]);
4481 for (i = 0; i < cl->w_nword; i++)
4482 unquote(cl->w_words[i]);
4483 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4485 for (i = 0; i < cl->w_nword; i++)
4486 wb = addword(cl->w_words[i], wb);
4491 wb = addword(unquote(cp), wb);
4495 static void globname(we, pp)
4499 REGISTER char *np, *cp;
4500 char *name, *gp, *dp;
4504 char dname[NAME_MAX + 1];
4507 for (np = we; np != pp; pp--)
4510 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4514 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4523 dname[NAME_MAX] = '\0';
4524 while ((de = readdir(dirp)) != NULL) {
4525 /* XXX Hmmm... What this could be? (abial) */
4527 if (ent[j].d_ino == 0)
4530 strncpy(dname, de->d_name, NAME_MAX);
4531 if (dname[0] == '.')
4534 for (k = 0; k < NAME_MAX; k++)
4535 if (any(dname[k], spcl))
4537 if (gmatch(dname, gp)) {
4538 name = generate(we, pp, dname, np);
4539 if (*np && !anys(np, spcl)) {
4540 if (stat(name, &dbuf)) {
4545 nl = addword(name, nl);
4554 * generate a pathname as below.
4555 * start..end1 / middle end
4556 * the slashes come for free
4558 static char *generate(start1, end1, middle, end)
4560 REGISTER char *end1;
4564 REGISTER char *op, *xp;
4567 space((int) (end1 - start1) + strlen(middle) + strlen(end) + 2);
4568 for (xp = start1; xp != end1;)
4570 for (xp = middle; (*op++ = *xp++) != '\0';);
4572 for (xp = end; (*op++ = *xp++) != '\0';);
4576 static int anyspcl(wb)
4577 REGISTER struct wdblock *wb;
4583 for (i = 0; i < wb->w_nword; i++)
4584 if (anys(spcl, *wd++))
4589 static int xstrcmp(p1, p2)
4592 return (strcmp(*(char **) p1, *(char **) p2));
4595 /* -------- word.c -------- */
4597 static struct wdblock *newword(nw)
4600 REGISTER struct wdblock *wb;
4602 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4608 static struct wdblock *addword(wd, wb)
4610 REGISTER struct wdblock *wb;
4612 REGISTER struct wdblock *wb2;
4616 wb = newword(NSTART);
4617 if ((nw = wb->w_nword) >= wb->w_bsize) {
4618 wb2 = newword(nw * 2);
4619 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4620 nw * sizeof(char *));
4625 wb->w_words[wb->w_nword++] = wd;
4631 REGISTER struct wdblock *wb;
4637 return ((char **) NULL);
4638 if (wb->w_nword == 0) {
4640 return ((char **) NULL);
4642 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4643 memcpy((char *) wd, (char *) wb->w_words, nb);
4644 DELETE(wb); /* perhaps should done by caller */
4648 static int (*func) (char *, char *);
4651 static void glob0(a0, a1, a2, a3)
4655 int (*a3) (char *, char *);
4659 glob1(a0, a0 + a1 * a2);
4662 static void glob1(base, lim)
4665 REGISTER char *i, *j;
4675 if ((n = (int) (lim - base)) <= v2)
4677 n = v2 * (n / (2 * v2));
4678 hptr = lptr = base + n;
4683 if ((c = (*func) (i, lptr)) == 0) {
4684 glob2(i, lptr -= v2);
4695 if ((c = (*func) (hptr, j)) == 0) {
4696 glob2(hptr += v2, j);
4701 glob3(i, hptr += v2, j);
4716 if (lptr - base >= lim - hptr) {
4717 glob1(hptr + v2, lim);
4727 glob3(j, lptr -= v2, i);
4732 static void glob2(i, j)
4735 REGISTER char *index1, *index2, c;
4743 *index1++ = *index2;
4748 static void glob3(i, j, k)
4751 REGISTER char *index1, *index2, *index3;
4761 *index1++ = *index3;
4762 *index3++ = *index2;
4767 /* -------- io.c -------- */
4773 static int my_getc(int ec)
4777 if (e.linep > elinep) {
4778 while ((c = readc()) != '\n' && c);
4779 err("input line too long");
4784 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4787 if (c == '\n' && ec != '\"')
4788 return (my_getc(ec));
4795 static void unget(c)
4798 if (e.iop >= e.iobase)
4804 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4811 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4813 for (; e.iop >= e.iobase; e.iop--) {
4814 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4815 if ((c = e.iop->peekc) != '\0') {
4819 if (e.iop->prev != 0) {
4820 if ((c = (*e.iop->iofn) (e.iop->argp, e.iop)) != '\0') {
4825 if (e.iop == iostack)
4827 return (e.iop->prev = c);
4828 } else if (e.iop->task == XIO && e.iop->prev != '\n') {
4830 if (e.iop == iostack)
4835 if (e.iop->task == XIO) {
4837 return e.iop->prev = 0;
4839 if (interactive && e.iop == iostack + 1) {
4840 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4841 current_prompt = prompt->value;
4851 if (e.iop >= iostack) {
4852 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4856 DBGPRINTF(("READC: leave()...\n"));
4863 static void ioecho(c)
4867 write(2, &c, sizeof c);
4871 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4873 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4874 argp->afid, e.iop));
4876 /* Set env ptr for io source to next array spot and check for array overflow */
4877 if (++e.iop >= &iostack[NPUSH]) {
4879 err("Shell input nested too deeply");
4884 /* We did not overflow the NPUSH array spots so setup data structs */
4886 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4888 if (argp->afid != AFID_NOBUF)
4892 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4893 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4895 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4897 if (e.iop == &iostack[0])
4898 e.iop->argp->afbuf = &mainbuf;
4900 e.iop->argp->afbuf = &sharedbuf;
4902 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4903 /* This line appears to be active when running scripts from command line */
4904 if ((isatty(e.iop->argp->afile) == 0)
4905 && (e.iop == &iostack[0]
4906 || lseek(e.iop->argp->afile, 0L, 1) != -1)) {
4907 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4908 bufid = AFID_ID; /* AFID_ID = 0 */
4910 e.iop->argp->afid = bufid; /* assign buffer id */
4913 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4914 iostack, e.iop, e.iop->argp->afbuf));
4915 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4916 &mainbuf, &sharedbuf, bufid, e.iop));
4920 e.iop->prev = ~'\n';
4925 if (fn == filechar || fn == linechar)
4927 else if (fn == (int (*)(struct ioarg *)) gravechar
4928 || fn == (int (*)(struct ioarg *)) qgravechar)
4929 e.iop->task = XGRAVE;
4931 e.iop->task = XOTHER;
4936 static struct io *setbase(ip)
4939 REGISTER struct io *xp;
4947 * Input generating functions
4951 * Produce the characters of a string, then a newline, then EOF.
4953 static int nlchar(ap)
4954 REGISTER struct ioarg *ap;
4958 if (ap->aword == NULL)
4960 if ((c = *ap->aword++) == 0) {
4968 * Given a list of words, produce the characters
4969 * in them, with a space after each word.
4971 static int wdchar(ap)
4972 REGISTER struct ioarg *ap;
4977 if ((wl = ap->awordlist) == NULL)
4980 if ((c = *(*wl)++) != 0)
4985 ap->awordlist = NULL;
4990 * Return the characters of a list of words,
4991 * producing a space between them.
4993 static int dolchar(ap)
4994 REGISTER struct ioarg *ap;
4998 if ((wp = *ap->awordlist++) != NULL) {
4999 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
5005 static int xxchar(ap)
5006 REGISTER struct ioarg *ap;
5010 if (ap->aword == NULL)
5012 if ((c = *ap->aword++) == '\0') {
5020 * Produce the characters from a single word (string).
5022 static int strchar(ap)
5023 REGISTER struct ioarg *ap;
5027 if (ap->aword == NULL || (c = *ap->aword++) == 0)
5033 * Produce quoted characters from a single word (string).
5035 static int qstrchar(ap)
5036 REGISTER struct ioarg *ap;
5040 if (ap->aword == NULL || (c = *ap->aword++) == 0)
5046 * Return the characters from a file.
5048 static int filechar(ap)
5049 REGISTER struct ioarg *ap;
5053 struct iobuf *bp = ap->afbuf;
5055 if (ap->afid != AFID_NOBUF) {
5056 if ((i = ap->afid != bp->id) || bp->bufp == bp->ebufp) {
5059 lseek(ap->afile, ap->afpos, 0);
5061 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
5069 bp->ebufp = (bp->bufp = bp->buf) + i;
5073 return *bp->bufp++ & 0177;
5075 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5076 if (interactive && isatty(ap->afile)) {
5077 static char mycommand[BUFSIZ];
5078 static int position = 0, size = 0;
5080 while (size == 0 || position >= size) {
5081 cmdedit_read_input(current_prompt, mycommand);
5082 size = strlen(mycommand);
5085 c = mycommand[position];
5092 i = safe_read(ap->afile, &c, sizeof(c));
5093 return (i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0));
5098 * Return the characters from a here temp file.
5100 static int herechar(ap)
5101 REGISTER struct ioarg *ap;
5106 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
5115 * Return the characters produced by a process (`...`).
5116 * Quote them if required, and remove any trailing newline characters.
5118 static int gravechar(ap, iop)
5124 if ((c = qgravechar(ap, iop) & ~QUOTE) == '\n')
5129 static int qgravechar(ap, iop)
5130 REGISTER struct ioarg *ap;
5135 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
5140 return ('\n' | QUOTE);
5144 } else if ((c = filechar(ap)) == '\n') {
5146 while ((c = filechar(ap)) == '\n')
5154 return (c != 0 ? c | QUOTE : 0);
5158 * Return a single command (usually the first line) from a file.
5160 static int linechar(ap)
5161 REGISTER struct ioarg *ap;
5165 if ((c = filechar(ap)) == '\n') {
5168 ap->afile = -1; /* illegal value */
5175 REGISTER const char *s;
5178 write(2, s, strlen(s));
5187 static void closef(i)
5194 static void closeall()
5198 for (u = NUFILE; u < NOFILE;)
5204 * remap fd into Shell's fd space
5206 static int remap(fd)
5214 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
5217 for (i = 0; i < NOFILE; i++)
5224 } while (fd >= 0 && fd < e.iofd);
5226 for (i = 0; i < NOFILE; i++)
5231 err("too many files open in shell");
5237 static int openpipe(pv)
5242 if ((i = pipe(pv)) < 0)
5243 err("can't create pipe - try again");
5247 static void closepipe(pv)
5256 /* -------- here.c -------- */
5262 static void markhere(s, iop)
5266 REGISTER struct here *h, *lh;
5268 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
5270 h = (struct here *) space(sizeof(struct here));
5274 h->h_tag = evalstr(s, DOSUB);
5284 for (lh = inhere; lh != NULL; lh = lh->h_next)
5285 if (lh->h_next == 0) {
5289 iop->io_flag |= IOHERE | IOXHERE;
5290 for (s = h->h_tag; *s; s++)
5292 iop->io_flag &= ~IOXHERE;
5295 h->h_dosub = iop->io_flag & IOXHERE;
5298 static void gethere()
5300 REGISTER struct here *h, *hp;
5302 DBGPRINTF7(("GETHERE: enter...\n"));
5304 /* Scan here files first leaving inhere list in place */
5305 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5306 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5308 /* Make inhere list active - keep list intact for scraphere */
5310 hp->h_next = acthere;
5316 static void readhere(name, s, ec)
5322 char tname[30] = ".msh_XXXXXX";
5325 char myline[LINELIM + 1];
5328 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5330 tf = mkstemp(tname);
5334 *name = strsave(tname, areanum);
5335 if (newenv(setjmp(errpt = ev)) != 0)
5338 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5341 if (interactive && e.iop <= iostack) {
5342 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5343 current_prompt = cprompt->value;
5345 prs(cprompt->value);
5349 while ((c = my_getc(ec)) != '\n' && c) {
5352 if (thenext >= &myline[LINELIM]) {
5359 if (strcmp(s, myline) == 0 || c == 0)
5362 write(tf, myline, (int) (thenext - myline));
5365 prs("here document `");
5375 * open here temp file.
5376 * if unquoted here, expand here temp file into second temp file.
5378 static int herein(hname, xdoll)
5386 /* Avoid longjmp clobbering */
5392 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5394 hf = open(hname, 0);
5400 char tname[30] = ".msh_XXXXXX";
5403 tf = mkstemp(tname);
5406 if (newenv(setjmp(errpt = ev)) == 0) {
5407 PUSHIO(afile, hf, herechar);
5409 while ((c = subgetc(0, 0)) != 0) {
5411 write(tf, &c, sizeof c);
5417 tf = open(tname, 0);
5424 static void scraphere()
5426 REGISTER struct here *h;
5428 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5430 for (h = inhere; h != NULL; h = h->h_next) {
5431 if (h->h_iop && h->h_iop->io_name)
5432 unlink(h->h_iop->io_name);
5437 /* unlink here temp files before a freearea(area) */
5438 static void freehere(area)
5441 REGISTER struct here *h, *hl;
5443 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5446 for (h = acthere; h != NULL; h = h->h_next)
5447 if (getarea((char *) h) >= area) {
5448 if (h->h_iop->io_name != NULL)
5449 unlink(h->h_iop->io_name);
5451 acthere = h->h_next;
5453 hl->h_next = h->h_next;
5461 * Copyright (c) 1987,1997, Prentice Hall
5462 * All rights reserved.
5464 * Redistribution and use of the MINIX operating system in source and
5465 * binary forms, with or without modification, are permitted provided
5466 * that the following conditions are met:
5468 * Redistributions of source code must retain the above copyright
5469 * notice, this list of conditions and the following disclaimer.
5471 * Redistributions in binary form must reproduce the above
5472 * copyright notice, this list of conditions and the following
5473 * disclaimer in the documentation and/or other materials provided
5474 * with the distribution.
5476 * Neither the name of Prentice Hall nor the names of the software
5477 * authors or contributors may be used to endorse or promote
5478 * products derived from this software without specific prior
5479 * written permission.
5481 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5482 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5483 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5484 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5485 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5486 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5487 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5488 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5489 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5490 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5491 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5492 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.