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.
45 #include <sys/times.h>
46 #include <sys/types.h>
52 /* Conditional use of "register" keyword */
53 #define REGISTER register
56 /*#define MSHDEBUG 1*/
59 int mshdbg = MSHDEBUG;
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 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
97 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
98 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
100 # define DEFAULT_ROOT_PROMPT "# "
101 # define DEFAULT_USER_PROMPT "$ "
105 /* -------- sh.h -------- */
111 #define NPUSH 8 /* limit to input nesting */
114 #define NOFILE 20 /* Number of open files */
115 #define NUFILE 10 /* Number of user-accessible files */
116 #define FDBASE 10 /* First file usable by Shell */
119 * values returned by wait
121 #define WAITSIG(s) ((s)&0177)
122 #define WAITVAL(s) (((s)>>8)&0377)
123 #define WAITCORE(s) (((s)&0200)!=0)
126 * library and system definitions
128 typedef void xint; /* base type of jmp_buf, for not broken compilers */
136 #define NOBLOCK ((struct op *)NULL)
137 #define NOWORD ((char *)NULL)
138 #define NOWORDS ((char **)NULL)
139 #define NOPIPE ((int *)NULL)
142 * Description of a command or an operation on commands.
143 * Might eventually use a union.
146 int type; /* operation type, see below */
147 char **words; /* arguments to a command */
148 struct ioword **ioact; /* IO actions (eg, < > >>) */
151 char *str; /* identifier for case and for */
154 #define TCOM 1 /* command */
155 #define TPAREN 2 /* (c-list) */
156 #define TPIPE 3 /* a | b */
157 #define TLIST 4 /* a [&;] b */
158 #define TOR 5 /* || */
159 #define TAND 6 /* && */
167 #define TPAT 14 /* pattern in case */
168 #define TBRACE 15 /* {c-list} */
169 #define TASYNC 16 /* c & */
170 /* Added to support "." file expansion */
173 /* Strings for names to make debug easier */
175 static char *T_CMD_NAMES[] = {
198 * actions determining the environment of a process
200 #define BIT(i) (1<<(i))
201 #define FEXEC BIT(0) /* execute without forking */
203 #if 0 /* Original value */
204 #define AREASIZE (65000)
206 #define AREASIZE (90000)
210 * flags to control evaluation of words
212 #define DOSUB 1 /* interpret $, `, and quotes */
213 #define DOBLANK 2 /* perform blank interpretation */
214 #define DOGLOB 4 /* interpret [?* */
215 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
216 #define DOTRIM 16 /* trim resulting string */
218 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
222 static int newfile(char *s);
223 static char *findeq(char *cp);
224 static char *cclass(char *p, int sub);
225 static void initarea(void);
226 extern int msh_main(int argc, char **argv);
231 struct brkcon *nextlev;
239 short io_unit; /* unit affected */
240 short io_flag; /* action (below) */
241 char *io_name; /* file name */
244 #define IOREAD 1 /* < */
245 #define IOHERE 2 /* << (here file) */
246 #define IOWRITE 4 /* > */
247 #define IOCAT 8 /* >> */
248 #define IOXHERE 16 /* ${}, ` in << */
249 #define IODUP 32 /* >&digit */
250 #define IOCLOSE 64 /* >&- */
252 #define IODEFAULT (-1) /* token for default IO unit */
257 * parsing & execution environment
263 xint *errpt; /* void * */
271 * -k: look for name=value everywhere on command line
273 * -t: exit after reading and executing one command
276 * -u: unset variables net diagnostic
280 static char *null; /* null value for variable */
281 static int intr; /* interrupt pending */
283 static char *trap[_NSIG + 1];
284 static char ourtrap[_NSIG + 1];
285 static int trapset; /* trap pending */
287 static int heedint; /* heed interrupt signals */
289 static int yynerrs; /* yacc */
291 static char line[LINELIM];
298 static int (*inbuilt(char *s)) (struct op *);
300 static char *rexecve(char *c, char **v, char **envp);
301 static char *space(int n);
302 static char *strsave(char *s, int a);
303 static char *evalstr(char *cp, int f);
304 static char *putn(int n);
305 static char *itoa(int n);
306 static char *unquote(char *as);
307 static struct var *lookup(char *n);
308 static int rlookup(char *n);
309 static struct wdblock *glob(char *cp, struct wdblock *wb);
310 static int my_getc(int ec);
311 static int subgetc(char ec, int quoted);
312 static char **makenv(int all, struct wdblock *wb);
313 static char **eval(char **ap, int f);
314 static int setstatus(int s);
315 static int waitfor(int lastpid, int canintr);
317 static void onintr(int s); /* SIGINT handler */
319 static int newenv(int f);
320 static void quitenv(void);
321 static void err(char *s);
322 static int anys(char *s1, char *s2);
323 static int any(int c, char *s);
324 static void next(int f);
325 static void setdash(void);
326 static void onecommand(void);
327 static void runtrap(int i);
328 static int gmatch(char *s, char *p);
334 static void leave(void); /* abort shell (or fail in subshell) */
335 static void fail(void); /* fail but return to process next command */
336 static void warn(char *s);
337 static void sig(int i); /* default signal handler */
341 /* -------- area stuff -------- */
343 #define REGSIZE sizeof(struct region)
345 /* #define SHRINKBY (64) */
349 #define ALIGN (sizeof(int)-1)
359 /* -------- grammar stuff -------- */
384 /* Added for "." file expansion */
387 #define YYERRCODE 300
390 #define CONTIN 01 /* skip new lines to complete command */
392 #define SYNTAXERR zzerr()
394 static struct op *pipeline(int cf);
395 static struct op *andor(void);
396 static struct op *c_list(void);
397 static int synio(int cf);
398 static void musthave(int c, int cf);
399 static struct op *simple(void);
400 static struct op *nested(int type, int mark);
401 static struct op *command(int cf);
402 static struct op *dogroup(int onlydone);
403 static struct op *thenpart(void);
404 static struct op *elsepart(void);
405 static struct op *caselist(void);
406 static struct op *casepart(void);
407 static char **pattern(void);
408 static char **wordlist(void);
409 static struct op *list(struct op *t1, struct op *t2);
410 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
411 static struct op *newtp(void);
412 static struct op *namelist(struct op *t);
413 static char **copyw(void);
414 static void word(char *cp);
415 static struct ioword **copyio(void);
416 static struct ioword *io(int u, int f, char *cp);
417 static void zzerr(void);
418 static void yyerror(char *s);
419 static int yylex(int cf);
420 static int collect(int c, int c1);
421 static int dual(int c);
422 static void diag(int ec);
423 static char *tree(unsigned size);
425 /* -------- var.h -------- */
434 #define COPYV 1 /* flag to setval, suggesting copy */
435 #define RONLY 01 /* variable is read-only */
436 #define EXPORT 02 /* variable is to be exported */
437 #define GETCELL 04 /* name & value space was got with getcell */
439 static int yyparse(void);
440 static struct var *lookup(char *n);
441 static void setval(struct var *vp, char *val);
442 static void nameval(struct var *vp, char *val, char *name);
443 static void export(struct var *vp);
444 static void ronly(struct var *vp);
445 static int isassign(char *s);
446 static int checkname(char *cp);
447 static int assign(char *s, int cf);
448 static void putvlist(int f, int out);
449 static int eqname(char *n1, char *n2);
451 static int execute(struct op *t, int *pin, int *pout, int act);
454 /* -------- io.h -------- */
457 unsigned id; /* buffer id */
458 char buf[512]; /* buffer */
459 char *bufp; /* pointer into buffer */
460 char *ebufp; /* pointer to end of buffer */
463 /* possible arguments to an IO function */
467 int afile; /* file descriptor */
468 unsigned afid; /* buffer id */
469 long afpos; /* file position */
470 struct iobuf *afbuf; /* buffer for this file */
473 //static struct ioarg ioargstack[NPUSH];
474 #define AFID_NOBUF (~0)
477 /* an input generator's state */
479 int (*iofn) (struct ioarg *, struct io *);
482 char prev; /* previous character read by readc() */
483 char nlcount; /* for `'s */
484 char xchar; /* for `'s */
485 char task; /* reason for pushed IO */
488 //static struct io iostack[NPUSH];
489 #define XOTHER 0 /* none of the below */
490 #define XDOLL 1 /* expanding ${} */
491 #define XGRAVE 2 /* expanding `'s */
492 #define XIO 3 /* file IO */
494 /* in substitution */
495 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
499 * input generators for IO structure
501 static int nlchar(struct ioarg *ap);
502 static int strchar(struct ioarg *ap);
503 static int qstrchar(struct ioarg *ap);
504 static int filechar(struct ioarg *ap);
505 static int herechar(struct ioarg *ap);
506 static int linechar(struct ioarg *ap);
507 static int gravechar(struct ioarg *ap, struct io *iop);
508 static int qgravechar(struct ioarg *ap, struct io *iop);
509 static int dolchar(struct ioarg *ap);
510 static int wdchar(struct ioarg *ap);
511 static void scraphere(void);
512 static void freehere(int area);
513 static void gethere(void);
514 static void markhere(char *s, struct ioword *iop);
515 static int herein(char *hname, int xdoll);
516 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
522 static int eofc(void);
523 static int readc(void);
524 static void unget(int c);
525 static void ioecho(char c);
526 static void prs(const char *s);
527 static void prn(unsigned u);
528 static void closef(int i);
529 static void closeall(void);
535 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
536 static int remap(int fd);
537 static int openpipe(int *pv);
538 static void closepipe(int *pv);
539 static struct io *setbase(struct io *ip);
541 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)),pushio(&temparg,(gen)))
542 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
544 /* -------- word.h -------- */
546 #define NSTART 16 /* default number of words to allow for initially */
551 /* bounds are arbitrary */
555 static struct wdblock *addword(char *wd, struct wdblock *wb);
556 static struct wdblock *newword(int nw);
557 static char **getwords(struct wdblock *wb);
559 /* -------- area.h -------- */
564 static char *getcell(unsigned nbytes);
565 static void garbage(void);
566 static void setarea(char *cp, int a);
567 static int getarea(char *cp);
568 static void freearea(int a);
569 static void freecell(char *cp);
570 static int areanum; /* current allocation area */
572 #define NEW(type) (type *)getcell(sizeof(type))
573 #define DELETE(obj) freecell((char *)obj)
576 /* -------- misc stuff -------- */
578 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
579 static int iosetup(struct ioword *iop, int pipein, int pipeout);
580 static void echo(char **wp);
581 static struct op **find1case(struct op *t, char *w);
582 static struct op *findcase(struct op *t, char *w);
583 static void brkset(struct brkcon *bc);
584 static int dolabel(struct op *t);
585 static int dohelp(struct op *t);
586 static int dochdir(struct op *t);
587 static int doshift(struct op *t);
588 static int dologin(struct op *t);
589 static int doumask(struct op *t);
590 static int doexec(struct op *t);
591 static int dodot(struct op *t);
592 static int dowait(struct op *t);
593 static int doread(struct op *t);
594 static int doeval(struct op *t);
595 static int dotrap(struct op *t);
596 static int getsig(char *s);
597 static void setsig(int n, sighandler_t f);
598 static int getn(char *as);
599 static int dobreak(struct op *t);
600 static int docontinue(struct op *t);
601 static int brkcontin(char *cp, int val);
602 static int doexit(struct op *t);
603 static int doexport(struct op *t);
604 static int doreadonly(struct op *t);
605 static void rdexp(char **wp, void (*f) (struct var *), int key);
606 static void badid(char *s);
607 static int doset(struct op *t);
608 static void varput(char *s, int out);
609 static int dotimes(struct op *t);
610 static int expand(char *cp, struct wdblock **wbp, int f);
611 static char *blank(int f);
612 static int dollar(int quoted);
613 static int grave(int quoted);
614 static void globname(char *we, char *pp);
615 static char *generate(char *start1, char *end1, char *middle, char *end);
616 static int anyspcl(struct wdblock *wb);
617 static int xstrcmp(char *p1, char *p2);
618 static void glob0(char *a0, unsigned int a1, int a2,
619 int (*a3) (char *, char *));
620 static void glob1(char *base, char *lim);
621 static void glob2(char *i, char *j);
622 static void glob3(char *i, char *j, char *k);
623 static void readhere(char **name, char *s, int ec);
624 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
625 static int xxchar(struct ioarg *ap);
630 struct ioword *h_iop;
634 static const char * const signame[] = {
637 (char *) NULL, /* interrupt */
639 "Illegal instruction",
643 "Floating Point Exception",
648 (char *) NULL, /* broken pipe */
653 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
659 static const struct res restab[] = {
685 int (*builtinfunc) (struct op * t);
687 static const struct builtincmd builtincmds[] = {
692 {"continue", docontinue},
696 {"export", doexport},
701 {"readonly", doreadonly},
711 static struct op *scantree(struct op *);
712 static struct op *dowholefile(int, int);
715 extern char **environ; /* environment pointer */
721 static int interactive; /* Is this an interactive shell */
723 static int multiline; /* \n changed to ; */
724 static struct op *outtree; /* result from parser */
727 static struct brkcon *brklist;
729 static struct wdblock *wdlist;
730 static struct wdblock *iolist;
731 static char *trap[_NSIG + 1];
732 static char ourtrap[_NSIG + 1];
733 static int trapset; /* trap pending */
734 static int yynerrs; /* yacc */
735 static char line[LINELIM];
738 static struct var *mshdbg_var;
740 static struct var *vlist; /* dictionary */
741 static struct var *homedir; /* home directory */
742 static struct var *prompt; /* main prompt */
743 static struct var *cprompt; /* continuation prompt */
744 static struct var *path; /* search path for commands */
745 static struct var *shell; /* shell to interpret command files */
746 static struct var *ifs; /* field separators */
748 static int areanum; /* current allocation area */
751 static char flags['z' - 'a' + 1];
752 static char *flag = flags - 'a';
753 static char *null = "";
754 static int heedint = 1;
755 static void (*qflag) (int) = SIG_IGN;
759 static int iounit = IODEFAULT;
760 static YYSTYPE yylval;
761 static char *elinep = line + sizeof(line) - 5;
763 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
764 static struct ioarg ioargstack[NPUSH];
765 static struct io iostack[NPUSH];
766 static struct iobuf sharedbuf = { AFID_NOBUF };
767 static struct iobuf mainbuf = { AFID_NOBUF };
768 static unsigned bufid = AFID_ID; /* buffer id counter */
770 static struct here *inhere; /* list of hear docs while parsing */
771 static struct here *acthere; /* list of active here documents */
772 static struct region *areabot; /* bottom of area */
773 static struct region *areatop; /* top of area */
774 static struct region *areanxt; /* starting point of scan */
776 static void *brkaddr;
778 static struct env e = {
779 line, /* linep: char ptr */
780 iostack, /* iobase: struct io ptr */
781 iostack - 1, /* iop: struct io ptr */
782 (xint *) NULL, /* errpt: void ptr for errors? */
783 FDBASE, /* iofd: file desc */
784 (struct env *) NULL /* oenv: struct env ptr */
788 void print_t(struct op *t);
789 void print_t(struct op *t)
791 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
792 T_CMD_NAMES[t->type], t->words, t->ioact));
795 DBGPRINTF(("T: W1: %s", t->words[0]));
801 void print_tree(struct op *head);
802 void print_tree(struct op *head)
805 DBGPRINTF(("PRINT_TREE: no tree\n"));
809 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
813 print_tree(head->left);
816 print_tree(head->right);
820 #endif /* MSHDEBUG */
823 #ifdef CONFIG_FEATURE_COMMAND_EDITING
824 static char *current_prompt;
827 /* -------- sh.c -------- */
833 int msh_main(int argc, char **argv)
839 int (*iof) (struct ioarg *);
841 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
844 if ((ap = environ) != NULL) {
846 assign(*ap++, !COPYV);
847 for (ap = environ; *ap;)
848 export(lookup(*ap++));
853 shell = lookup("SHELL");
854 if (shell->value == null)
855 setval(shell, (char *)DEFAULT_SHELL);
858 homedir = lookup("HOME");
859 if (homedir->value == null)
860 setval(homedir, "/");
863 setval(lookup("$"), putn(getpid()));
865 path = lookup("PATH");
866 if (path->value == null) {
868 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
870 setval(path, "/bin:/usr/bin");
875 if (ifs->value == null)
876 setval(ifs, " \t\n");
879 mshdbg_var = lookup("MSHDEBUG");
880 if (mshdbg_var->value == null)
881 setval(mshdbg_var, "0");
884 prompt = lookup("PS1");
885 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
886 if (prompt->value == null)
888 setval(prompt, DEFAULT_USER_PROMPT);
889 if (geteuid() == 0) {
890 setval(prompt, DEFAULT_ROOT_PROMPT);
891 prompt->status &= ~EXPORT;
893 cprompt = lookup("PS2");
894 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
895 if (cprompt->value == null)
897 setval(cprompt, "> ");
903 if (argv[0][0] == '-' && argv[0][1] != '\0') {
904 for (s = argv[0] + 1; *s; s++)
907 prompt->status &= ~EXPORT;
908 cprompt->status &= ~EXPORT;
913 PUSHIO(aword, *++argv, iof = nlchar);
925 prompt->status &= ~EXPORT;
933 if (*s >= 'a' && *s <= 'z')
941 if (iof == filechar && --argc > 0) {
944 prompt->status &= ~EXPORT;
945 cprompt->status &= ~EXPORT;
947 /* Shell is non-interactive, activate printf-based debug */
949 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
953 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
955 if (newfile(name = *++argv))
956 exit(1); /* Exit on error */
962 /* This won't be true if PUSHIO has been called, say from newfile() above */
963 if (e.iop < iostack) {
964 PUSHIO(afile, 0, iof);
965 if (isatty(0) && isatty(1) && !cflag) {
967 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
969 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
971 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
973 printf("Enter 'help' for a list of built-in commands.\n\n");
978 signal(SIGQUIT, qflag);
979 if (name && name[0] == '-') {
981 if ((f = open(".profile", 0)) >= 0)
983 if ((f = open("/etc/profile", 0)) >= 0)
987 signal(SIGTERM, sig);
989 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
990 signal(SIGINT, onintr);
995 for (ap = ++argv; --argc > 0;) {
996 if (assign(*ap = *argv++, !COPYV)) {
997 dolc--; /* keyword */
1003 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
1005 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
1008 if (interactive && e.iop <= iostack) {
1009 #ifdef CONFIG_FEATURE_COMMAND_EDITING
1010 current_prompt = prompt->value;
1016 /* Ensure that getenv("PATH") stays current */
1017 setenv("PATH", path->value, 1);
1020 DBGPRINTF(("MSH_MAIN: returning.\n"));
1023 static void setdash(void)
1027 char m['z' - 'a' + 1];
1030 for (c = 'a'; c <= 'z'; c++)
1034 setval(lookup("-"), m);
1037 static int newfile(REGISTER char *s)
1041 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1043 if (strcmp(s, "-") != 0) {
1044 DBGPRINTF(("NEWFILE: s is %s\n", s));
1048 err(": cannot open");
1059 struct op *scantree(struct op *head)
1066 if (head->left != NULL) {
1067 dotnode = scantree(head->left);
1072 if (head->right != NULL) {
1073 dotnode = scantree(head->right);
1078 if (head->words == NULL)
1081 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1083 if ((head->type != TDOT) && (strcmp(".", head->words[0]) == 0)) {
1084 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1092 static void onecommand(void)
1097 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1116 setjmp(failpt = m1); /* Bruce Evans' fix */
1117 if (setjmp(failpt = m1) || yyparse() || intr) {
1119 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1124 if (!interactive && intr)
1137 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1139 execute(outtree, NOPIPE, NOPIPE, 0);
1142 if (!interactive && intr) {
1147 if ((i = trapset) != 0) {
1153 static void fail(void)
1159 static void leave(void)
1161 DBGPRINTF(("LEAVE: leave called!\n"));
1172 static void warn(REGISTER char *s)
1183 static void err(char *s)
1191 longjmp(e.errpt, 1);
1193 e.iop = e.iobase = iostack;
1196 static int newenv(int f)
1198 REGISTER struct env *ep;
1200 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1207 ep = (struct env *) space(sizeof(*ep));
1220 static void quitenv(void)
1222 REGISTER struct env *ep;
1225 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1227 if ((ep = e.oenv) != NULL) {
1230 /* should close `'d files */
1232 while (--fd >= e.iofd)
1238 * Is any character from s1 in s2?
1240 static int anys(REGISTER char *s1, REGISTER char *s2)
1249 * Is character c in s?
1251 static int any(REGISTER int c, REGISTER char *s)
1259 static char *putn(REGISTER int n)
1264 static char *itoa(REGISTER int n)
1268 snprintf(s, sizeof(s), "%u", n);
1273 static void next(int f)
1275 PUSHIO(afile, f, filechar);
1278 static void onintr(int s) /* ANSI C requires a parameter */
1280 signal(SIGINT, onintr);
1287 } else if (heedint) {
1293 static char *space(int n)
1297 if ((cp = getcell(n)) == 0)
1298 err("out of string space");
1302 static char *strsave(REGISTER char *s, int a)
1304 REGISTER char *cp, *xp;
1306 if ((cp = space(strlen(s) + 1)) != NULL) {
1307 setarea((char *) cp, a);
1308 for (xp = cp; (*xp++ = *s++) != '\0';);
1317 static void sig(REGISTER int i)
1323 static void runtrap(int i)
1327 if ((trapstr = trap[i]) == NULL)
1333 RUN(aword, trapstr, nlchar);
1336 /* -------- var.c -------- */
1339 * Find the given name in the dictionary
1340 * and return its value. If the name was
1341 * not previously there, enter it now and
1342 * return a null value.
1344 static struct var *lookup(REGISTER char *n)
1346 REGISTER struct var *vp;
1349 static struct var dummy;
1353 for (c = 0; isdigit(*n) && c < 1000; n++)
1354 c = c * 10 + *n - '0';
1355 dummy.status = RONLY;
1356 dummy.value = c <= dolc ? dolv[c] : null;
1359 for (vp = vlist; vp; vp = vp->next)
1360 if (eqname(vp->name, n))
1363 vp = (struct var *) space(sizeof(*vp));
1364 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1365 dummy.name = dummy.value = "";
1368 for (cp = vp->name; (*cp = *n++) && *cp != '='; cp++);
1372 setarea((char *) vp, 0);
1373 setarea((char *) vp->name, 0);
1376 vp->status = GETCELL;
1382 * give variable at `vp' the value `val'.
1384 static void setval(struct var *vp, char *val)
1386 nameval(vp, val, (char *) NULL);
1390 * if name is not NULL, it must be
1391 * a prefix of the space `val',
1393 * this is all so that exporting
1394 * values is reasonably painless.
1396 static void nameval(REGISTER struct var *vp, char *val, char *name)
1398 REGISTER char *cp, *xp;
1402 if (vp->status & RONLY) {
1403 for (xp = vp->name; *xp && *xp != '=';)
1404 putc(*xp++, stderr);
1405 err(" is read-only");
1410 xp = space(strlen(vp->name) + strlen(val) + 2);
1413 /* make string: name=value */
1414 setarea((char *) xp, 0);
1416 for (cp = vp->name; (*xp = *cp++) && *xp != '='; xp++);
1420 for (cp = val; (*xp++ = *cp++) != '\0';);
1424 if (vp->status & GETCELL)
1425 freecell(vp->name); /* form new string `name=value' */
1431 static void export(struct var *vp)
1433 vp->status |= EXPORT;
1436 static void ronly(struct var *vp)
1438 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1439 vp->status |= RONLY;
1442 static int isassign(REGISTER char *s)
1444 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1446 if (!isalpha((int) *s) && *s != '_')
1448 for (; *s != '='; s++)
1449 if (*s == 0 || (!isalnum(*s) && *s != '_'))
1455 static int assign(REGISTER char *s, int cf)
1460 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1462 if (!isalpha(*s) && *s != '_')
1464 for (cp = s; *cp != '='; cp++)
1465 if (*cp == 0 || (!isalnum(*cp) && *cp != '_'))
1468 nameval(vp, ++cp, cf == COPYV ? (char *) NULL : s);
1470 vp->status &= ~GETCELL;
1474 static int checkname(REGISTER char *cp)
1476 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1478 if (!isalpha(*cp++) && *(cp - 1) != '_')
1481 if (!isalnum(*cp++) && *(cp - 1) != '_')
1486 static void putvlist(REGISTER int f, REGISTER int out)
1488 REGISTER struct var *vp;
1490 for (vp = vlist; vp; vp = vp->next)
1491 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1492 if (vp->status & EXPORT)
1493 write(out, "export ", 7);
1494 if (vp->status & RONLY)
1495 write(out, "readonly ", 9);
1496 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1497 write(out, "\n", 1);
1501 static int eqname(REGISTER char *n1, REGISTER char *n2)
1503 for (; *n1 != '=' && *n1 != 0; n1++)
1506 return (*n2 == 0 || *n2 == '=');
1509 static char *findeq(REGISTER char *cp)
1511 while (*cp != '\0' && *cp != '=')
1516 /* -------- gmatch.c -------- */
1518 * int gmatch(string, pattern)
1519 * char *string, *pattern;
1521 * Match a pattern as in sh(1).
1526 #define QMASK (CMASK&~QUOTE)
1527 #define NOT '!' /* might use ^ */
1529 static int gmatch(REGISTER char *s, REGISTER char *p)
1531 REGISTER int sc, pc;
1533 if (s == NULL || p == NULL)
1535 while ((pc = *p++ & CMASK) != '\0') {
1539 if ((p = cclass(p, sc)) == NULL)
1551 if (*p == '\0' || gmatch(s, p))
1553 } while (*s++ != '\0');
1557 if (sc != (pc & ~QUOTE))
1564 static char *cclass(REGISTER char *p, REGISTER int sub)
1566 REGISTER int c, d, not, found;
1568 if ((not = *p == NOT) != 0)
1573 return ((char *) NULL);
1575 if (p[1] == '-' && p[2] != ']') {
1580 if (c == sub || (c <= sub && sub <= d))
1582 } while (*++p != ']');
1583 return (found ? p + 1 : (char *) NULL);
1587 /* -------- area.c -------- */
1590 * All memory between (char *)areabot and (char *)(areatop+1) is
1591 * exclusively administered by the area management routines.
1592 * It is assumed that sbrk() and brk() manipulate the high end.
1595 #define sbrk(X) ({ void * __q = (void *)-1; if (brkaddr + (int)(X) < brktop) { __q = brkaddr; brkaddr+=(int)(X); } __q;})
1597 static void initarea(void)
1599 brkaddr = xmalloc(AREASIZE);
1600 brktop = brkaddr + AREASIZE;
1602 while ((long) sbrk(0) & ALIGN)
1604 areabot = (struct region *) sbrk(REGSIZE);
1606 areabot->next = areabot;
1607 areabot->area = BUSY;
1612 char *getcell(unsigned nbytes)
1614 REGISTER int nregio;
1615 REGISTER struct region *p, *q;
1622 /* silly and defeats the algorithm */
1624 * round upwards and add administration area
1626 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
1627 for (p = areanxt;;) {
1628 if (p->area > areanum) {
1632 while ((q = p->next)->area > areanum && q != areanxt)
1635 * exit loop if cell big enough
1637 if (q >= p + nregio)
1644 i = nregio >= GROWBY ? nregio : GROWBY;
1645 p = (struct region *) sbrk(i * REGSIZE);
1646 if (p == (struct region *) -1)
1647 return ((char *) NULL);
1651 abort(); /* allocated areas are contiguous */
1661 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
1663 areanxt = p + nregio;
1666 * split into requested area and rest
1668 if (areanxt + 1 > q) {
1670 abort(); /* insufficient space left for admin */
1673 areanxt->area = FREE;
1677 return ((char *) (p + 1));
1680 static void freecell(char *cp)
1682 REGISTER struct region *p;
1684 if ((p = (struct region *) cp) != NULL) {
1692 static void freearea(REGISTER int a)
1694 REGISTER struct region *p, *top;
1697 for (p = areabot; p != top; p = p->next)
1702 static void setarea(char *cp, int a)
1704 REGISTER struct region *p;
1706 if ((p = (struct region *) cp) != NULL)
1710 int getarea(char *cp)
1712 return ((struct region *) cp - 1)->area;
1715 static void garbage(void)
1717 REGISTER struct region *p, *q, *top;
1720 for (p = areabot; p != top; p = p->next) {
1721 if (p->area > areanum) {
1722 while ((q = p->next)->area > areanum)
1728 if (areatop >= q + SHRINKBY && q->area > areanum) {
1729 brk((char *) (q + 1));
1737 /* -------- csyn.c -------- */
1739 * shell: syntax (C version)
1744 DBGPRINTF7(("YYPARSE: enter...\n"));
1751 return (yynerrs != 0);
1754 static struct op *pipeline(int cf)
1756 REGISTER struct op *t, *p;
1759 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1763 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1766 while ((c = yylex(0)) == '|') {
1767 if ((p = command(CONTIN)) == NULL) {
1768 DBGPRINTF8(("PIPELINE: error!\n"));
1772 if (t->type != TPAREN && t->type != TCOM) {
1773 /* shell statement */
1774 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1777 t = block(TPIPE, t, p, NOWORDS);
1782 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1786 static struct op *andor(void)
1788 REGISTER struct op *t, *p;
1791 DBGPRINTF7(("ANDOR: enter...\n"));
1795 DBGPRINTF9(("ANDOR: t=%p\n", t));
1798 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1799 if ((p = pipeline(CONTIN)) == NULL) {
1800 DBGPRINTF8(("ANDOR: error!\n"));
1804 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1810 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1814 static struct op *c_list(void)
1816 REGISTER struct op *t, *p;
1819 DBGPRINTF7(("C_LIST: enter...\n"));
1824 if ((peeksym = yylex(0)) == '&')
1825 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1827 while ((c = yylex(0)) == ';' || c == '&'
1828 || (multiline && c == '\n')) {
1830 if ((p = andor()) == NULL)
1833 if ((peeksym = yylex(0)) == '&')
1834 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1842 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1846 static int synio(int cf)
1848 REGISTER struct ioword *iop;
1852 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1854 if ((c = yylex(cf)) != '<' && c != '>') {
1861 iop = io(iounit, i, yylval.cp);
1865 markhere(yylval.cp, iop);
1867 DBGPRINTF7(("SYNIO: returning 1\n"));
1871 static void musthave(int c, int cf)
1873 if ((peeksym = yylex(cf)) != c) {
1874 DBGPRINTF7(("MUSTHAVE: error!\n"));
1881 static struct op *simple(void)
1883 REGISTER struct op *t;
1887 switch (peeksym = yylex(0)) {
1908 static struct op *nested(int type, int mark)
1910 REGISTER struct op *t;
1912 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1918 return (block(type, t, NOBLOCK, NOWORDS));
1921 static struct op *command(int cf)
1923 REGISTER struct op *t;
1924 struct wdblock *iosave;
1927 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1943 if ((t = simple()) == NULL) {
1945 return ((struct op *) NULL);
1952 t = nested(TPAREN, ')');
1956 t = nested(TBRACE, '}');
1966 t->words = wordlist();
1967 if ((c = yylex(0)) != '\n' && c != ';')
1969 t->left = dogroup(0);
1977 t->type = c == WHILE ? TWHILE : TUNTIL;
1979 t->right = dogroup(1);
1991 musthave(IN, CONTIN);
1994 t->left = caselist();
2005 t->right = thenpart();
2014 musthave(WORD, 0); /* gets name of file */
2015 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
2017 word(yylval.cp); /* add word to wdlist */
2018 word(NOWORD); /* terminate wdlist */
2019 t->words = copyw(); /* dup wdlist */
2029 DBGPRINTF(("COMMAND: returning %p\n", t));
2034 static struct op *dowholefile(int type, int mark)
2036 REGISTER struct op *t;
2038 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
2043 t = block(type, t, NOBLOCK, NOWORDS);
2044 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
2048 static struct op *dogroup(int onlydone)
2051 REGISTER struct op *mylist;
2054 if (c == DONE && onlydone)
2055 return ((struct op *) NULL);
2063 static struct op *thenpart(void)
2066 REGISTER struct op *t;
2068 if ((c = yylex(0)) != THEN) {
2070 return ((struct op *) NULL);
2075 if (t->left == NULL)
2077 t->right = elsepart();
2081 static struct op *elsepart(void)
2084 REGISTER struct op *t;
2086 switch (c = yylex(0)) {
2088 if ((t = c_list()) == NULL)
2096 t->right = thenpart();
2101 return ((struct op *) NULL);
2105 static struct op *caselist(void)
2107 REGISTER struct op *t;
2110 while ((peeksym = yylex(CONTIN)) != ESAC) {
2111 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
2112 t = list(t, casepart());
2115 DBGPRINTF(("CASELIST, returning t=%p\n", t));
2119 static struct op *casepart(void)
2121 REGISTER struct op *t;
2123 DBGPRINTF7(("CASEPART: enter...\n"));
2127 t->words = pattern();
2130 if ((peeksym = yylex(CONTIN)) != ESAC)
2131 musthave(BREAK, CONTIN);
2133 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2138 static char **pattern(void)
2147 } while ((c = yylex(0)) == '|');
2154 static char **wordlist(void)
2158 if ((c = yylex(0)) != IN) {
2160 return ((char **) NULL);
2163 while ((c = yylex(0)) == WORD)
2171 * supporting functions
2173 static struct op *list(REGISTER struct op *t1, REGISTER struct op *t2)
2175 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2182 return (block(TLIST, t1, t2, NOWORDS));
2185 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2187 REGISTER struct op *t;
2189 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2197 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2203 /* See if given string is a shell multiline (FOR, IF, etc) */
2204 static int rlookup(REGISTER char *n)
2206 REGISTER const struct res *rp;
2208 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2210 for (rp = restab; rp->r_name; rp++)
2211 if (strcmp(rp->r_name, n) == 0) {
2212 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2213 return (rp->r_val); /* Return numeric code for shell multiline */
2216 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2217 return (0); /* Not a shell multiline */
2220 static struct op *newtp(void)
2222 REGISTER struct op *t;
2224 t = (struct op *) tree(sizeof(*t));
2232 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2237 static struct op *namelist(REGISTER struct op *t)
2240 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2241 T_CMD_NAMES[t->type], iolist));
2244 iolist = addword((char *) NULL, iolist);
2245 t->ioact = copyio();
2249 if (t->type != TCOM) {
2250 if (t->type != TPAREN && t->ioact != NULL) {
2251 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2252 t->ioact = t->left->ioact;
2253 t->left->ioact = NULL;
2265 static char **copyw(void)
2269 wd = getwords(wdlist);
2274 static void word(char *cp)
2276 wdlist = addword(cp, wdlist);
2279 static struct ioword **copyio(void)
2281 REGISTER struct ioword **iop;
2283 iop = (struct ioword **) getwords(iolist);
2288 static struct ioword *io(int u, int f, char *cp)
2290 REGISTER struct ioword *iop;
2292 iop = (struct ioword *) tree(sizeof(*iop));
2296 iolist = addword((char *) iop, iolist);
2300 static void zzerr(void)
2302 yyerror("syntax error");
2305 static void yyerror(char *s)
2308 if (interactive && e.iop <= iostack) {
2310 while (eofc() == 0 && yylex(0) != '\n');
2316 static int yylex(int cf)
2321 if ((c = peeksym) > 0) {
2336 line[LINELIM - 1] = '\0';
2339 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2344 if (any(c, "0123456789")) {
2345 unget(c1 = my_getc(0));
2346 if (c1 == '<' || c1 == '>') {
2355 case '#': /* Comment, skip to next newline or End-of-string */
2356 while ((c = my_getc(0)) != 0 && c != '\n');
2361 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2365 DBGPRINTF9(("YYLEX: found $\n"));
2367 if ((c = my_getc(0)) == '{') {
2368 if ((c = collect(c, '}')) != '\0')
2377 if ((c = collect(c, c)) != '\0')
2385 /* If more chars process them, else return NULL char */
2386 if ((c1 = dual(c)) != '\0')
2403 if (multiline || cf & CONTIN) {
2404 if (interactive && e.iop <= iostack) {
2405 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2406 current_prompt = cprompt->value;
2408 prs(cprompt->value);
2425 while ((c = my_getc(0)) != 0 && !any(c, "`$ '\"\t;&<>()|^\n")) {
2426 if (e.linep >= elinep)
2427 err("word too long");
2434 if (any(c, "\"'`$"))
2439 if (atstart && (c = rlookup(line)) != 0) {
2444 yylval.cp = strsave(line, areanum);
2449 static int collect(REGISTER int c, REGISTER int c1)
2453 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2456 while ((c = my_getc(c1)) != c1) {
2465 if (interactive && c == '\n' && e.iop <= iostack) {
2466 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2467 current_prompt = cprompt->value;
2469 prs(cprompt->value);
2477 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2482 /* "multiline commands" helper func */
2483 /* see if next 2 chars form a shell multiline */
2484 static int dual(REGISTER int c)
2487 REGISTER char *cp = s;
2489 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2491 *cp++ = c; /* c is the given "peek" char */
2492 *cp++ = my_getc(0); /* get next char of input */
2493 *cp = 0; /* add EOS marker */
2495 c = rlookup(s); /* see if 2 chars form a shell multiline */
2497 unget(*--cp); /* String is not a shell multiline, put peek char back */
2499 return (c); /* String is multiline, return numeric multiline (restab) code */
2502 static void diag(REGISTER int ec)
2506 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2509 if (c == '>' || c == '<') {
2512 yylval.i = ec == '>' ? IOWRITE | IOCAT : IOHERE;
2515 yylval.i = ec == '>' ? IOWRITE : IOREAD;
2516 if (c != '&' || yylval.i == IOHERE)
2522 static char *tree(unsigned size)
2526 if ((t = getcell(size)) == NULL) {
2527 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2528 prs("command line too complicated\n");
2538 /* -------- exec.c -------- */
2545 static int execute(REGISTER struct op *t, int *pin, int *pout, int act)
2547 REGISTER struct op *t1;
2548 volatile int i, rv, a;
2549 char *cp, **wp, **wp2;
2551 struct op *outtree_save;
2555 /* Avoid longjmp clobbering */
2560 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2564 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2565 t->type, T_CMD_NAMES[t->type],
2566 ((t->words == NULL) ? "NULL" : t->words[0])));
2570 wp = (wp2 = t->words) != NULL
2571 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2574 /* Hard to know how many words there are, be careful of garbage pointer values */
2575 /* They are likely to cause "PCI bus fault" errors */
2577 DBGPRINTF(("EXECUTE: t->left=%p, t->right=%p, t->words[1] is %s\n",
2579 ((t->words[1] == NULL) ? "NULL" : t->words[1])));
2580 DBGPRINTF7(("EXECUTE: t->words[2] is %s, t->words[3] is %s\n",
2581 ((t->words[2] == NULL) ? "NULL" : t->words[2]),
2582 ((t->words[3] == NULL) ? "NULL" : t->words[3])));
2588 DBGPRINTF3(("EXECUTE: TDOT\n"));
2590 outtree_save = outtree;
2592 newfile(evalstr(t->words[0], DOALL));
2594 t->left = dowholefile(TLIST, 0);
2597 outtree = outtree_save;
2600 rv = execute(t->left, pin, pout, 0);
2602 rv = execute(t->right, pin, pout, 0);
2606 rv = execute(t->left, pin, pout, 0);
2611 rv = forkexec(t, pin, pout, act, wp);
2619 if ((rv = openpipe(pv)) < 0)
2621 pv[0] = remap(pv[0]);
2622 pv[1] = remap(pv[1]);
2623 (void) execute(t->left, pin, pv, 0);
2624 rv = execute(t->right, pv, pout, 0);
2629 (void) execute(t->left, pin, pout, 0);
2630 rv = execute(t->right, pin, pout, 0);
2635 int hinteractive = interactive;
2637 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2641 interactive = hinteractive;
2643 setval(lookup("!"), putn(i));
2654 signal(SIGINT, SIG_IGN);
2655 signal(SIGQUIT, SIG_IGN);
2657 signal(SIGTERM, SIG_DFL);
2661 open(bb_dev_null, 0);
2663 _exit(execute(t->left, pin, pout, FEXEC));
2670 rv = execute(t->left, pin, pout, 0);
2671 if ((t1 = t->right) != NULL && (rv == 0) == (t->type == TAND))
2672 rv = execute(t1, pin, pout, 0);
2682 while (*wp++ != NULL);
2684 vp = lookup(t->str);
2685 while (setjmp(bc.brkpt))
2689 for (t1 = t->left; i-- && *wp != NULL;) {
2691 rv = execute(t1, pin, pout, 0);
2693 brklist = brklist->nextlev;
2698 while (setjmp(bc.brkpt))
2703 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2704 rv = execute(t->right, pin, pout, 0);
2705 brklist = brklist->nextlev;
2710 if (t->right != NULL) {
2711 rv = !execute(t->left, pin, pout, 0) ?
2712 execute(t->right->left, pin, pout, 0) :
2713 execute(t->right->right, pin, pout, 0);
2718 if ((cp = evalstr(t->str, DOSUB | DOTRIM)) == 0)
2721 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2722 ((t->str == NULL) ? "NULL" : t->str),
2723 ((cp == NULL) ? "NULL" : cp)));
2725 if ((t1 = findcase(t->left, cp)) != NULL) {
2726 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2727 rv = execute(t1, pin, pout, 0);
2728 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2734 if (iopp = t->ioact)
2736 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2741 if (rv >= 0 && (t1 = t->left))
2742 rv = execute(t1, pin, pout, 0);
2753 if (interactive && intr) {
2758 if ((i = trapset) != 0) {
2763 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2768 forkexec(REGISTER struct op *t, int *pin, int *pout, int act, char **wp)
2772 int (*shcom) (struct op *) = NULL;
2775 struct ioword **iopp;
2785 struct brkcon *hbrklist;
2789 /* Avoid longjmp clobbering */
2799 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2801 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2802 ((t->words == NULL) ? "NULL" : t->words[0])));
2804 /* Hard to know how many words there are, be careful of garbage pointer values */
2805 /* They are likely to cause "PCI bus fault" errors */
2807 DBGPRINTF7(("FORKEXEC: t->words is %s, t->words[1] is %s\n",
2808 ((t->words == NULL) ? "NULL" : t->words[0]),
2809 ((t->words == NULL) ? "NULL" : t->words[1])));
2810 DBGPRINTF7(("FORKEXEC: wp is %s, wp[1] is %s\n",
2811 ((wp == NULL) ? "NULL" : wp[0]),
2812 ((wp[1] == NULL) ? "NULL" : wp[1])));
2813 DBGPRINTF7(("FORKEXEC: wp2 is %s, wp[3] is %s\n",
2814 ((wp[2] == NULL) ? "NULL" : wp[2]),
2815 ((wp[3] == NULL) ? "NULL" : wp[3])));
2821 rv = -1; /* system-detected error */
2822 if (t->type == TCOM) {
2823 while ((cp = *wp++) != NULL);
2826 /* strip all initial assignments */
2827 /* not correct wrt PATH=yyy command etc */
2829 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2831 echo(cp ? wp : owp);
2834 DBGPRINTF9(("FORKEXEC: t->words is %s, t->words[1] is %s\n",
2835 ((t->words == NULL) ? "NULL" : t->words[0]),
2836 ((t->words == NULL) ? "NULL" : t->words[1])));
2837 DBGPRINTF9(("FORKEXEC: wp is %s, wp[1] is %s\n",
2838 ((wp == NULL) ? "NULL" : wp[0]),
2839 ((wp == NULL) ? "NULL" : wp[1])));
2842 if (cp == NULL && t->ioact == NULL) {
2843 while ((cp = *owp++) != NULL && assign(cp, COPYV));
2844 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2845 return (setstatus(0));
2846 } else if (cp != NULL) {
2847 shcom = inbuilt(cp);
2855 DBGPRINTF3(("FORKEXEC: t->words is %s, t->words[1] is %s\n",
2856 ((t->words == NULL) ? "NULL" : t->words[0]),
2857 ((t->words == NULL) ? "NULL" : t->words[1])));
2859 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2862 if (shcom == NULL && (f & FEXEC) == 0) {
2863 /* Save values in case the child process alters them */
2867 hinteractive = interactive;
2872 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2877 DBGPRINTF(("FORKEXEC: ERROR, unable to vfork()!\n"));
2882 if (newpid > 0) { /* Parent */
2884 /* Restore values */
2888 interactive = hinteractive;
2901 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2904 /* Must be the child process, pid should be 0 */
2905 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2908 signal(SIGINT, SIG_IGN);
2909 signal(SIGQUIT, SIG_IGN);
2921 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2926 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2927 err("piping to/from shell builtins not yet done");
2943 if ((iopp = t->ioact) != NULL) {
2944 if (shcom != NULL && shcom != doexec) {
2946 err(": cannot redirect shell command");
2952 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2960 i = setstatus((*shcom) (t));
2963 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2967 /* should use FIOCEXCL */
2968 for (i = FDBASE; i < NOFILE; i++)
2971 signal(SIGINT, SIG_DFL);
2972 signal(SIGQUIT, SIG_DFL);
2975 if (t->type == TPAREN)
2976 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2980 cp = rexecve(wp[0], wp, makenv(0, NULL));
2987 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2995 * 0< 1> are ignored as required
2998 static int iosetup(REGISTER struct ioword *iop, int pipein, int pipeout)
3000 REGISTER int u = -1;
3001 char *cp = NULL, *msg;
3003 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
3006 if (iop->io_unit == IODEFAULT) /* take default */
3007 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
3009 if (pipein && iop->io_unit == 0)
3012 if (pipeout && iop->io_unit == 1)
3015 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
3016 if ((iop->io_flag & IOHERE) == 0) {
3018 if ((cp = evalstr(cp, DOSUB | DOTRIM)) == NULL)
3022 if (iop->io_flag & IODUP) {
3023 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
3025 err(": illegal >& argument");
3029 iop->io_flag = IOCLOSE;
3030 iop->io_flag &= ~(IOREAD | IOWRITE);
3032 switch (iop->io_flag) {
3038 case IOHERE | IOXHERE:
3039 u = herein(iop->io_name, iop->io_flag & IOXHERE);
3043 case IOWRITE | IOCAT:
3044 if ((u = open(cp, 1)) >= 0) {
3045 lseek(u, (long) 0, 2);
3049 u = creat(cp, 0666);
3053 u = dup2(*cp - '0', iop->io_unit);
3057 close(iop->io_unit);
3066 if (u != iop->io_unit) {
3067 dup2(u, iop->io_unit);
3074 static void echo(REGISTER char **wp)
3079 for (i = 0; wp[i]; i++) {
3087 static struct op **find1case(struct op *t, char *w)
3089 REGISTER struct op *t1;
3091 REGISTER char **wp, *cp;
3095 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
3096 return ((struct op **) NULL);
3099 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
3100 T_CMD_NAMES[t->type]));
3102 if (t->type == TLIST) {
3103 if ((tp = find1case(t->left, w)) != NULL) {
3104 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
3107 t1 = t->right; /* TPAT */
3111 for (wp = t1->words; *wp;)
3112 if ((cp = evalstr(*wp++, DOSUB)) && gmatch(w, cp)) {
3113 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
3118 DBGPRINTF(("FIND1CASE: returning NULL\n"));
3119 return ((struct op **) NULL);
3122 static struct op *findcase(struct op *t, char *w)
3124 REGISTER struct op **tp;
3126 return ((tp = find1case(t, w)) != NULL ? *tp : (struct op *) NULL);
3130 * Enter a new loop level (marked for break/continue).
3132 static void brkset(struct brkcon *bc)
3134 bc->nextlev = brklist;
3139 * Wait for the last process created.
3140 * Print a message for each process found
3141 * that was killed by a signal.
3142 * Ignore interrupt signals while waiting
3143 * unless `canintr' is true.
3145 static int waitfor(REGISTER int lastpid, int canintr)
3147 REGISTER int pid, rv;
3149 int oheedint = heedint;
3156 if (errno != EINTR || canintr)
3159 if ((rv = WAITSIG(s)) != 0) {
3161 if (signame[rv] != NULL) {
3162 if (pid != lastpid) {
3169 if (pid != lastpid) {
3178 prs(" - core dumped");
3179 if (rv >= NSIGNAL || signame[rv])
3185 } while (pid != lastpid);
3200 static int setstatus(REGISTER int s)
3203 setval(lookup("?"), putn(s));
3208 * PATH-searching interface to execve.
3209 * If getenv("PATH") were kept up-to-date,
3210 * execvp might be used.
3212 static char *rexecve(char *c, char **v, char **envp)
3215 REGISTER char *sp, *tp;
3216 int eacces = 0, asis = 0;
3218 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3222 if (find_applet_by_name(name)) {
3223 /* We have to exec here since we vforked. Running
3224 * run_applet_by_name() won't work and bad things
3226 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3230 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3232 sp = any('/', c) ? "" : path->value;
3234 while (asis || *sp != '\0') {
3237 for (; *sp != '\0'; tp++)
3238 if ((*tp = *sp++) == ':') {
3244 for (i = 0; (*tp++ = c[i++]) != '\0';);
3246 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3248 execve(e.linep, v, envp);
3255 execve(DEFAULT_SHELL, v, envp);
3257 return ("no Shell");
3260 return ((char *) bb_msg_memory_exhausted);
3263 return ("argument list too long");
3270 return (errno == ENOENT ? "not found" : "cannot execute");
3274 * Run the command produced by generator `f'
3275 * applied to stream `arg'.
3277 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3280 struct wdblock *swdlist;
3281 struct wdblock *siolist;
3287 /* Avoid longjmp clobbering */
3291 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3292 areanum, outtree, failpt));
3301 if (newenv(setjmp(errpt = ev)) == 0) {
3307 if (setjmp(failpt = rt) == 0 && yyparse() == 0)
3308 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3311 DBGPRINTF(("RUN: error from newenv()!\n"));
3318 freearea(areanum--);
3323 /* -------- do.c -------- */
3326 * built-in commands: doX
3329 static int dohelp(struct op *t)
3332 const struct builtincmd *x;
3334 printf("\nBuilt-in commands:\n");
3335 printf("-------------------\n");
3337 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3340 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3346 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3349 const struct BB_applet *applet;
3350 extern const struct BB_applet applets[];
3351 extern const size_t NUM_APPLETS;
3353 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3357 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3366 return EXIT_SUCCESS;
3371 static int dolabel(struct op *t)
3376 static int dochdir(REGISTER struct op *t)
3378 REGISTER char *cp, *er;
3380 if ((cp = t->words[1]) == NULL && (cp = homedir->value) == NULL)
3381 er = ": no home directory";
3382 else if (chdir(cp) < 0)
3383 er = ": bad directory";
3386 prs(cp != NULL ? cp : "cd");
3391 static int doshift(REGISTER struct op *t)
3395 n = t->words[1] ? getn(t->words[1]) : 1;
3397 err("nothing to shift");
3403 setval(lookup("#"), putn(dolc));
3408 * execute login and newgrp directly
3410 static int dologin(struct op *t)
3415 signal(SIGINT, SIG_DFL);
3416 signal(SIGQUIT, SIG_DFL);
3418 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3425 static int doumask(REGISTER struct op *t)
3430 if ((cp = t->words[1]) == NULL) {
3433 for (n = 3 * 4; (n -= 3) >= 0;)
3434 putc('0' + ((i >> n) & 07), stderr);
3437 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3438 n = n * 8 + (*cp - '0');
3444 static int doexec(REGISTER struct op *t)
3451 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3456 if (setjmp(failpt = ex) == 0)
3457 execute(t, NOPIPE, NOPIPE, FEXEC);
3463 static int dodot(struct op *t)
3466 REGISTER char *sp, *tp;
3470 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)));
3472 if ((cp = t->words[1]) == NULL) {
3473 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3476 DBGPRINTF(("DODOT: cp is %s\n", cp));
3479 sp = any('/', cp) ? ":" : path->value;
3481 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3482 ((sp == NULL) ? "NULL" : sp),
3483 ((e.linep == NULL) ? "NULL" : e.linep)));
3487 while (*sp && (*tp = *sp++) != ':')
3492 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3495 if ((i = open(e.linep, 0)) >= 0) {
3498 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3500 next(maltmp); /* Basically a PUSHIO */
3502 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3515 static int dowait(struct op *t)
3520 if ((cp = t->words[1]) != NULL) {
3526 setstatus(waitfor(i, 1));
3530 static int doread(struct op *t)
3532 REGISTER char *cp, **wp;
3533 REGISTER int nb = 0;
3534 REGISTER int nl = 0;
3536 if (t->words[1] == NULL) {
3537 err("Usage: read name ...");
3540 for (wp = t->words + 1; *wp; wp++) {
3541 for (cp = e.linep; !nl && cp < elinep - 1; cp++)
3542 if ((nb = read(0, cp, sizeof(*cp))) != sizeof(*cp) ||
3543 (nl = (*cp == '\n')) || (wp[1] && any(*cp, ifs->value)))
3548 setval(lookup(*wp), e.linep);
3553 static int doeval(REGISTER struct op *t)
3555 return (RUN(awordlist, t->words + 1, wdchar));
3558 static int dotrap(REGISTER struct op *t)
3561 REGISTER int resetsig;
3563 if (t->words[1] == NULL) {
3564 for (i = 0; i <= _NSIG; i++)
3573 resetsig = isdigit(*t->words[1]);
3574 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3575 n = getsig(t->words[i]);
3579 if (*t->words[1] != '\0') {
3580 trap[n] = strsave(t->words[1], 0);
3589 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3597 static int getsig(char *s)
3601 if ((n = getn(s)) < 0 || n > _NSIG) {
3602 err("trap: bad signal number");
3608 static void setsig(REGISTER int n, sighandler_t f)
3612 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3618 static int getn(char *as)
3629 for (n = 0; isdigit(*s); s++)
3630 n = (n * 10) + (*s - '0');
3633 err(": bad number");
3638 static int dobreak(struct op *t)
3640 return (brkcontin(t->words[1], 1));
3643 static int docontinue(struct op *t)
3645 return (brkcontin(t->words[1], 0));
3648 static int brkcontin(REGISTER char *cp, int val)
3650 REGISTER struct brkcon *bc;
3653 nl = cp == NULL ? 1 : getn(cp);
3657 if ((bc = brklist) == NULL)
3659 brklist = bc->nextlev;
3662 err("bad break/continue level");
3666 longjmp(bc->brkpt, 1);
3670 static int doexit(struct op *t)
3675 if ((cp = t->words[1]) != NULL)
3676 setstatus(getn(cp));
3678 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3685 static int doexport(struct op *t)
3687 rdexp(t->words + 1, export, EXPORT);
3691 static int doreadonly(struct op *t)
3693 rdexp(t->words + 1, ronly, RONLY);
3697 static void rdexp(char **wp, void (*f) (struct var *), int key)
3699 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3700 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3703 for (; *wp != NULL; wp++) {
3704 if (isassign(*wp)) {
3708 for (cp = *wp; *cp != '='; cp++);
3720 static void badid(REGISTER char *s)
3723 err(": bad identifier");
3726 static int doset(REGISTER struct op *t)
3728 REGISTER struct var *vp;
3732 if ((cp = t->words[1]) == NULL) {
3733 for (vp = vlist; vp; vp = vp->next)
3734 varput(vp->name, 1);
3738 /* bad: t->words++; */
3739 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3741 flag['x'] = flag['v'] = 0;
3751 if (*cp >= 'a' && *cp <= 'z')
3758 t->words[0] = dolv[0];
3759 for (n = 1; t->words[n]; n++)
3760 setarea((char *) t->words[n], 0);
3763 setval(lookup("#"), putn(dolc));
3764 setarea((char *) (dolv - 1), 0);
3769 static void varput(REGISTER char *s, int out)
3771 if (isalnum(*s) || *s == '_') {
3772 write(out, s, strlen(s));
3773 write(out, "\n", 1);
3779 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3780 * This file contains code for the times builtin.
3782 static int dotimes(struct op *t)
3785 long int clk_tck = sysconf(_SC_CLK_TCK);
3788 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3789 (int) (buf.tms_utime / clk_tck / 60),
3790 ((double) buf.tms_utime) / clk_tck,
3791 (int) (buf.tms_stime / clk_tck / 60),
3792 ((double) buf.tms_stime) / clk_tck,
3793 (int) (buf.tms_cutime / clk_tck / 60),
3794 ((double) buf.tms_cutime) / clk_tck,
3795 (int) (buf.tms_cstime / clk_tck / 60),
3796 ((double) buf.tms_cstime) / clk_tck);
3801 static int (*inbuilt(char *s)) (struct op *) {
3802 const struct builtincmd *bp;
3804 for (bp = builtincmds; bp->name != NULL; bp++)
3805 if (strcmp(bp->name, s) == 0)
3806 return (bp->builtinfunc);
3811 /* -------- eval.c -------- */
3816 * blank interpretation
3821 static char **eval(char **ap, int f)
3829 /* Avoid longjmp clobbering */
3834 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3839 if (newenv(setjmp(errpt = ev)) == 0) {
3840 while (*ap && isassign(*ap))
3841 expand(*ap++, &wb, f & ~DOGLOB);
3843 for (wf = ap; *wf; wf++) {
3845 expand(*wf, &wb, f & ~DOGLOB);
3848 for (wb = addword((char *) 0, wb); *ap; ap++) {
3849 if (!flag['k'] || !isassign(*ap))
3850 expand(*ap, &wb, f & ~DOKEY);
3852 wb = addword((char *) 0, wb);
3858 return (gflg ? (char **) NULL : wp);
3862 * Make the exported environment from the exported
3863 * names in the dictionary. Keyword assignments
3864 * will already have been done.
3866 static char **makenv(int all, struct wdblock *wb)
3868 REGISTER struct var *vp;
3870 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3872 for (vp = vlist; vp; vp = vp->next)
3873 if (all || vp->status & EXPORT)
3874 wb = addword(vp->name, wb);
3875 wb = addword((char *) 0, wb);
3876 return (getwords(wb));
3879 static char *evalstr(REGISTER char *cp, int f)
3883 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3886 if (expand(cp, &wb, f)) {
3887 if (wb == NULL || wb->w_nword == 0
3888 || (cp = wb->w_words[0]) == NULL)
3896 static int expand(char *cp, REGISTER struct wdblock **wbp, int f)
3901 /* Avoid longjmp clobbering */
3905 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3912 if (!anys("$`'\"", cp) &&
3913 !anys(ifs->value, cp) && ((f & DOGLOB) == 0 || !anys("[*?", cp))) {
3914 cp = strsave(cp, areanum);
3917 *wbp = addword(cp, *wbp);
3920 if (newenv(setjmp(errpt = ev)) == 0) {
3921 PUSHIO(aword, cp, strchar);
3923 while ((cp = blank(f)) && gflg == 0) {
3925 cp = strsave(cp, areanum);
3926 if ((f & DOGLOB) == 0) {
3929 *wbp = addword(cp, *wbp);
3931 *wbp = glob(cp, *wbp);
3940 * Blank interpretation and quoting
3942 static char *blank(int f)
3946 int scanequals, foundequals;
3948 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3951 scanequals = f & DOKEY;
3955 switch (c = subgetc('"', foundequals)) {
3963 if (f & DOBLANK && any(c, ifs->value))
3972 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3975 if (c == '\'' || !any(c, "$`\""))
3982 if (!isalpha(c) && c != '_')
3985 c = subgetc('"', foundequals);
3987 f & (DOBLANK && any(c, ifs->value)) ||
3988 (!INSUB() && any(c, "\"'"))) {
3999 } else if (!isalnum(c) && c != '_')
4009 * Get characters, substituting for ` and $
4011 static int subgetc(REGISTER char ec, int quoted)
4015 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
4019 if (!INSUB() && ec != '\'') {
4021 if (grave(quoted) == 0)
4023 e.iop->task = XGRAVE;
4026 if (c == '$' && (c = dollar(quoted)) == 0) {
4027 e.iop->task = XDOLL;
4035 * Prepare to generate the string returned by ${} substitution.
4037 static int dollar(int quoted)
4042 REGISTER char *s, c, *cp = NULL;
4045 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
4051 if (isalpha(c) || c == '_') {
4052 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
4053 if (e.linep < elinep)
4060 otask = e.iop->task;
4062 e.iop->task = XOTHER;
4063 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
4064 if (e.linep < elinep)
4067 e.iop->task = otask;
4074 if (e.linep >= elinep) {
4075 err("string in ${} too long");
4081 for (cp = s + 1; *cp; cp++)
4082 if (any(*cp, "=-+?")) {
4087 if (s[1] == 0 && (*s == '*' || *s == '@')) {
4089 /* currently this does not distinguish $* and $@ */
4090 /* should check dollar */
4092 PUSHIO(awordlist, dolv + 1, dolchar);
4094 } else { /* trap the nasty ${=} */
4100 if ((dolp = vp->value) == null) {
4104 err("cannot use ${...=...} with $n");
4113 dolp = strsave(cp, areanum);
4118 prs("missing value for ");
4125 } else if (c == '+')
4126 dolp = strsave(cp, areanum);
4127 if (flag['u'] && dolp == null) {
4128 prs("unset variable: ");
4133 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4138 * Run the command in `...` and read its output.
4141 static int grave(int quoted)
4147 static char child_cmd[LINELIM];
4153 char *argument_list[4];
4154 struct wdblock *wb = NULL;
4157 /* Avoid longjmp clobbering */
4161 for (cp = e.iop->argp->aword; *cp != '`'; cp++)
4163 err("no closing `");
4167 /* string copy with dollar expansion */
4168 src = e.iop->argp->aword;
4173 while ((*src != '`') && (count < LINELIM)) {
4178 if (*src == '$' && !ignore && !ignore_once) {
4180 char var_name[LINELIM];
4181 char alt_value[LINELIM];
4194 var_name[var_index++] = *src++;
4195 while (isalnum(*src) || *src=='_')
4196 var_name[var_index++] = *src++;
4197 var_name[var_index] = 0;
4210 err("unclosed ${\n");
4215 while (*src && (*src != '}')) {
4216 alt_value[alt_index++] = *src++;
4218 alt_value[alt_index] = 0;
4220 err("unclosed ${\n");
4227 if (isalpha(*var_name)) {
4228 /* let subshell handle it instead */
4230 char *namep = var_name;
4238 char *altp = alt_value;
4246 wb = addword(lookup(var_name)->name, wb);
4250 vp = lookup(var_name);
4251 if (vp->value != null)
4252 value = (operator == '+') ?
4253 alt_value : vp->value;
4254 else if (operator == '?') {
4257 } else if (alt_index && (operator != '+')) {
4259 if (operator == '=')
4264 while (*value && (count < LINELIM)) {
4277 if (openpipe(pf) < 0)
4280 while ((i = vfork()) == -1 && errno == EAGAIN);
4282 DBGPRINTF3(("GRAVE: i is %p\n", io));
4286 err((char *) bb_msg_memory_exhausted);
4290 waitpid(i, NULL, 0);
4291 e.iop->argp->aword = ++cp;
4293 PUSHIO(afile, remap(pf[0]),
4294 (int (*)(struct ioarg *)) ((quoted) ? qgravechar :
4298 /* allow trapped signals */
4299 /* XXX - Maybe this signal stuff should go as well? */
4300 for (j = 0; j <= _NSIG; j++)
4301 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4307 argument_list[0] = (char *) DEFAULT_SHELL;
4308 argument_list[1] = "-c";
4309 argument_list[2] = child_cmd;
4310 argument_list[3] = 0;
4312 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4313 prs(argument_list[0]);
4320 static char *unquote(REGISTER char *as)
4324 if ((s = as) != NULL)
4330 /* -------- glob.c -------- */
4336 #define scopy(x) strsave((x), areanum)
4338 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4340 static struct wdblock *cl, *nl;
4341 static char spcl[] = "[?*";
4343 static struct wdblock *glob(char *cp, struct wdblock *wb)
4351 for (pp = cp; *pp; pp++)
4354 else if (!any(*pp & ~QUOTE, spcl))
4357 for (cl = addword(scopy(cp), (struct wdblock *) 0); anyspcl(cl);
4359 nl = newword(cl->w_nword * 2);
4360 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4361 for (pp = cl->w_words[i]; *pp; pp++)
4362 if (any(*pp, spcl)) {
4363 globname(cl->w_words[i], pp);
4367 nl = addword(scopy(cl->w_words[i]), nl);
4369 for (i = 0; i < cl->w_nword; i++)
4370 DELETE(cl->w_words[i]);
4373 for (i = 0; i < cl->w_nword; i++)
4374 unquote(cl->w_words[i]);
4375 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4377 for (i = 0; i < cl->w_nword; i++)
4378 wb = addword(cl->w_words[i], wb);
4383 wb = addword(unquote(cp), wb);
4387 static void globname(char *we, REGISTER char *pp)
4389 REGISTER char *np, *cp;
4390 char *name, *gp, *dp;
4394 char dname[NAME_MAX + 1];
4397 for (np = we; np != pp; pp--)
4400 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4404 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4413 dname[NAME_MAX] = '\0';
4414 while ((de = readdir(dirp)) != NULL) {
4415 /* XXX Hmmm... What this could be? (abial) */
4417 if (ent[j].d_ino == 0)
4420 strncpy(dname, de->d_name, NAME_MAX);
4421 if (dname[0] == '.')
4424 for (k = 0; k < NAME_MAX; k++)
4425 if (any(dname[k], spcl))
4427 if (gmatch(dname, gp)) {
4428 name = generate(we, pp, dname, np);
4429 if (*np && !anys(np, spcl)) {
4430 if (stat(name, &dbuf)) {
4435 nl = addword(name, nl);
4444 * generate a pathname as below.
4445 * start..end1 / middle end
4446 * the slashes come for free
4448 static char *generate(char *start1, REGISTER char *end1, char *middle, char *end)
4451 REGISTER char *op, *xp;
4454 space((int) (end1 - start1) + strlen(middle) + strlen(end) + 2);
4455 for (xp = start1; xp != end1;)
4457 for (xp = middle; (*op++ = *xp++) != '\0';);
4459 for (xp = end; (*op++ = *xp++) != '\0';);
4463 static int anyspcl(REGISTER struct wdblock *wb)
4469 for (i = 0; i < wb->w_nword; i++)
4470 if (anys(spcl, *wd++))
4475 static int xstrcmp(char *p1, char *p2)
4477 return (strcmp(*(char **) p1, *(char **) p2));
4480 /* -------- word.c -------- */
4482 static struct wdblock *newword(REGISTER int nw)
4484 REGISTER struct wdblock *wb;
4486 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4492 static struct wdblock *addword(char *wd, REGISTER struct wdblock *wb)
4494 REGISTER struct wdblock *wb2;
4498 wb = newword(NSTART);
4499 if ((nw = wb->w_nword) >= wb->w_bsize) {
4500 wb2 = newword(nw * 2);
4501 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4502 nw * sizeof(char *));
4507 wb->w_words[wb->w_nword++] = wd;
4512 char **getwords(REGISTER struct wdblock *wb)
4518 return ((char **) NULL);
4519 if (wb->w_nword == 0) {
4521 return ((char **) NULL);
4523 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4524 memcpy((char *) wd, (char *) wb->w_words, nb);
4525 DELETE(wb); /* perhaps should done by caller */
4529 static int (*func) (char *, char *);
4532 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4536 glob1(a0, a0 + a1 * a2);
4539 static void glob1(char *base, char *lim)
4541 REGISTER char *i, *j;
4551 if ((n = (int) (lim - base)) <= v2)
4553 n = v2 * (n / (2 * v2));
4554 hptr = lptr = base + n;
4559 if ((c = (*func) (i, lptr)) == 0) {
4560 glob2(i, lptr -= v2);
4571 if ((c = (*func) (hptr, j)) == 0) {
4572 glob2(hptr += v2, j);
4577 glob3(i, hptr += v2, j);
4592 if (lptr - base >= lim - hptr) {
4593 glob1(hptr + v2, lim);
4603 glob3(j, lptr -= v2, i);
4608 static void glob2(char *i, char *j)
4610 REGISTER char *index1, *index2, c;
4618 *index1++ = *index2;
4623 static void glob3(char *i, char *j, char *k)
4625 REGISTER char *index1, *index2, *index3;
4635 *index1++ = *index3;
4636 *index3++ = *index2;
4641 /* -------- io.c -------- */
4647 static int my_getc(int ec)
4651 if (e.linep > elinep) {
4652 while ((c = readc()) != '\n' && c);
4653 err("input line too long");
4658 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4661 if (c == '\n' && ec != '\"')
4662 return (my_getc(ec));
4669 static void unget(int c)
4671 if (e.iop >= e.iobase)
4675 static int eofc(void)
4677 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4680 static int readc(void)
4684 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4686 for (; e.iop >= e.iobase; e.iop--) {
4687 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4688 if ((c = e.iop->peekc) != '\0') {
4692 if (e.iop->prev != 0) {
4693 if ((c = (*e.iop->iofn) (e.iop->argp, e.iop)) != '\0') {
4698 if (e.iop == iostack)
4700 return (e.iop->prev = c);
4701 } else if (e.iop->task == XIO && e.iop->prev != '\n') {
4703 if (e.iop == iostack)
4708 if (e.iop->task == XIO) {
4710 return e.iop->prev = 0;
4712 if (interactive && e.iop == iostack + 1) {
4713 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4714 current_prompt = prompt->value;
4724 if (e.iop >= iostack) {
4725 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4729 DBGPRINTF(("READC: leave()...\n"));
4736 static void ioecho(char c)
4739 write(2, &c, sizeof c);
4743 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4745 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4746 argp->afid, e.iop));
4748 /* Set env ptr for io source to next array spot and check for array overflow */
4749 if (++e.iop >= &iostack[NPUSH]) {
4751 err("Shell input nested too deeply");
4756 /* We did not overflow the NPUSH array spots so setup data structs */
4758 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4760 if (argp->afid != AFID_NOBUF)
4764 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4765 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4767 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4769 if (e.iop == &iostack[0])
4770 e.iop->argp->afbuf = &mainbuf;
4772 e.iop->argp->afbuf = &sharedbuf;
4774 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4775 /* This line appears to be active when running scripts from command line */
4776 if ((isatty(e.iop->argp->afile) == 0)
4777 && (e.iop == &iostack[0]
4778 || lseek(e.iop->argp->afile, 0L, 1) != -1)) {
4779 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4780 bufid = AFID_ID; /* AFID_ID = 0 */
4782 e.iop->argp->afid = bufid; /* assign buffer id */
4785 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4786 iostack, e.iop, e.iop->argp->afbuf));
4787 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4788 &mainbuf, &sharedbuf, bufid, e.iop));
4792 e.iop->prev = ~'\n';
4797 if (fn == filechar || fn == linechar)
4799 else if (fn == (int (*)(struct ioarg *)) gravechar
4800 || fn == (int (*)(struct ioarg *)) qgravechar)
4801 e.iop->task = XGRAVE;
4803 e.iop->task = XOTHER;
4808 static struct io *setbase(struct io *ip)
4810 REGISTER struct io *xp;
4818 * Input generating functions
4822 * Produce the characters of a string, then a newline, then EOF.
4824 static int nlchar(REGISTER struct ioarg *ap)
4828 if (ap->aword == NULL)
4830 if ((c = *ap->aword++) == 0) {
4838 * Given a list of words, produce the characters
4839 * in them, with a space after each word.
4841 static int wdchar(REGISTER struct ioarg *ap)
4846 if ((wl = ap->awordlist) == NULL)
4849 if ((c = *(*wl)++) != 0)
4854 ap->awordlist = NULL;
4859 * Return the characters of a list of words,
4860 * producing a space between them.
4862 static int dolchar(REGISTER struct ioarg *ap)
4866 if ((wp = *ap->awordlist++) != NULL) {
4867 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4873 static int xxchar(REGISTER struct ioarg *ap)
4877 if (ap->aword == NULL)
4879 if ((c = *ap->aword++) == '\0') {
4887 * Produce the characters from a single word (string).
4889 static int strchar(REGISTER struct ioarg *ap)
4893 if (ap->aword == NULL || (c = *ap->aword++) == 0)
4899 * Produce quoted characters from a single word (string).
4901 static int qstrchar(REGISTER struct ioarg *ap)
4905 if (ap->aword == NULL || (c = *ap->aword++) == 0)
4911 * Return the characters from a file.
4913 static int filechar(REGISTER struct ioarg *ap)
4917 struct iobuf *bp = ap->afbuf;
4919 if (ap->afid != AFID_NOBUF) {
4920 if ((i = ap->afid != bp->id) || bp->bufp == bp->ebufp) {
4923 lseek(ap->afile, ap->afpos, 0);
4925 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4933 bp->ebufp = (bp->bufp = bp->buf) + i;
4937 return *bp->bufp++ & 0177;
4939 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4940 if (interactive && isatty(ap->afile)) {
4941 static char mycommand[BUFSIZ];
4942 static int position = 0, size = 0;
4944 while (size == 0 || position >= size) {
4945 cmdedit_read_input(current_prompt, mycommand);
4946 size = strlen(mycommand);
4949 c = mycommand[position];
4956 i = safe_read(ap->afile, &c, sizeof(c));
4957 return (i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0));
4962 * Return the characters from a here temp file.
4964 static int herechar(REGISTER struct ioarg *ap)
4969 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4978 * Return the characters produced by a process (`...`).
4979 * Quote them if required, and remove any trailing newline characters.
4981 static int gravechar(struct ioarg *ap, struct io *iop)
4985 if ((c = qgravechar(ap, iop) & ~QUOTE) == '\n')
4990 static int qgravechar(REGISTER struct ioarg *ap, struct io *iop)
4994 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4999 return ('\n' | QUOTE);
5003 } else if ((c = filechar(ap)) == '\n') {
5005 while ((c = filechar(ap)) == '\n')
5013 return (c != 0 ? c | QUOTE : 0);
5017 * Return a single command (usually the first line) from a file.
5019 static int linechar(REGISTER struct ioarg *ap)
5023 if ((c = filechar(ap)) == '\n') {
5026 ap->afile = -1; /* illegal value */
5032 static void prs(REGISTER const char *s)
5035 write(2, s, strlen(s));
5038 static void prn(unsigned u)
5043 static void closef(REGISTER int i)
5049 static void closeall(void)
5053 for (u = NUFILE; u < NOFILE;)
5059 * remap fd into Shell's fd space
5061 static int remap(REGISTER int fd)
5068 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
5071 for (i = 0; i < NOFILE; i++)
5078 } while (fd >= 0 && fd < e.iofd);
5080 for (i = 0; i < NOFILE; i++)
5085 err("too many files open in shell");
5091 static int openpipe(REGISTER int *pv)
5095 if ((i = pipe(pv)) < 0)
5096 err("can't create pipe - try again");
5100 static void closepipe(REGISTER int *pv)
5108 /* -------- here.c -------- */
5114 static void markhere(REGISTER char *s, struct ioword *iop)
5116 REGISTER struct here *h, *lh;
5118 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
5120 h = (struct here *) space(sizeof(struct here));
5124 h->h_tag = evalstr(s, DOSUB);
5134 for (lh = inhere; lh != NULL; lh = lh->h_next)
5135 if (lh->h_next == 0) {
5139 iop->io_flag |= IOHERE | IOXHERE;
5140 for (s = h->h_tag; *s; s++)
5142 iop->io_flag &= ~IOXHERE;
5145 h->h_dosub = iop->io_flag & IOXHERE;
5148 static void gethere(void)
5150 REGISTER struct here *h, *hp;
5152 DBGPRINTF7(("GETHERE: enter...\n"));
5154 /* Scan here files first leaving inhere list in place */
5155 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5156 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5158 /* Make inhere list active - keep list intact for scraphere */
5160 hp->h_next = acthere;
5166 static void readhere(char **name, REGISTER char *s, int ec)
5169 char tname[30] = ".msh_XXXXXX";
5172 char myline[LINELIM + 1];
5175 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5177 tf = mkstemp(tname);
5181 *name = strsave(tname, areanum);
5182 if (newenv(setjmp(errpt = ev)) != 0)
5185 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5188 if (interactive && e.iop <= iostack) {
5189 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5190 current_prompt = cprompt->value;
5192 prs(cprompt->value);
5196 while ((c = my_getc(ec)) != '\n' && c) {
5199 if (thenext >= &myline[LINELIM]) {
5206 if (strcmp(s, myline) == 0 || c == 0)
5209 write(tf, myline, (int) (thenext - myline));
5212 prs("here document `");
5222 * open here temp file.
5223 * if unquoted here, expand here temp file into second temp file.
5225 static int herein(char *hname, int xdoll)
5231 /* Avoid longjmp clobbering */
5237 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5239 hf = open(hname, 0);
5245 char tname[30] = ".msh_XXXXXX";
5248 tf = mkstemp(tname);
5251 if (newenv(setjmp(errpt = ev)) == 0) {
5252 PUSHIO(afile, hf, herechar);
5254 while ((c = subgetc(0, 0)) != 0) {
5256 write(tf, &c, sizeof c);
5262 tf = open(tname, 0);
5269 static void scraphere(void)
5271 REGISTER struct here *h;
5273 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5275 for (h = inhere; h != NULL; h = h->h_next) {
5276 if (h->h_iop && h->h_iop->io_name)
5277 unlink(h->h_iop->io_name);
5282 /* unlink here temp files before a freearea(area) */
5283 static void freehere(int area)
5285 REGISTER struct here *h, *hl;
5287 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5290 for (h = acthere; h != NULL; h = h->h_next)
5291 if (getarea((char *) h) >= area) {
5292 if (h->h_iop->io_name != NULL)
5293 unlink(h->h_iop->io_name);
5295 acthere = h->h_next;
5297 hl->h_next = h->h_next;
5305 * Copyright (c) 1987,1997, Prentice Hall
5306 * All rights reserved.
5308 * Redistribution and use of the MINIX operating system in source and
5309 * binary forms, with or without modification, are permitted provided
5310 * that the following conditions are met:
5312 * Redistributions of source code must retain the above copyright
5313 * notice, this list of conditions and the following disclaimer.
5315 * Redistributions in binary form must reproduce the above
5316 * copyright notice, this list of conditions and the following
5317 * disclaimer in the documentation and/or other materials provided
5318 * with the distribution.
5320 * Neither the name of Prentice Hall nor the names of the software
5321 * authors or contributors may be used to endorse or promote
5322 * products derived from this software without specific prior
5323 * written permission.
5325 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5326 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5327 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5328 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5329 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5330 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5331 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5332 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5333 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5334 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5335 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5336 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.