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>
51 /*#define MSHDEBUG 1*/
54 int mshdbg = MSHDEBUG;
56 #define DBGPRINTF(x) if(mshdbg>0)printf x
57 #define DBGPRINTF0(x) if(mshdbg>0)printf x
58 #define DBGPRINTF1(x) if(mshdbg>1)printf x
59 #define DBGPRINTF2(x) if(mshdbg>2)printf x
60 #define DBGPRINTF3(x) if(mshdbg>3)printf x
61 #define DBGPRINTF4(x) if(mshdbg>4)printf x
62 #define DBGPRINTF5(x) if(mshdbg>5)printf x
63 #define DBGPRINTF6(x) if(mshdbg>6)printf x
64 #define DBGPRINTF7(x) if(mshdbg>7)printf x
65 #define DBGPRINTF8(x) if(mshdbg>8)printf x
66 #define DBGPRINTF9(x) if(mshdbg>9)printf x
70 #define RCPRINTF(x) if(mshdbg_rc)printf x
91 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
92 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
93 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
95 # define DEFAULT_ROOT_PROMPT "# "
96 # define DEFAULT_USER_PROMPT "$ "
100 /* -------- sh.h -------- */
106 #define NPUSH 8 /* limit to input nesting */
109 #define NOFILE 20 /* Number of open files */
110 #define NUFILE 10 /* Number of user-accessible files */
111 #define FDBASE 10 /* First file usable by Shell */
114 * values returned by wait
116 #define WAITSIG(s) ((s)&0177)
117 #define WAITVAL(s) (((s)>>8)&0377)
118 #define WAITCORE(s) (((s)&0200)!=0)
121 * library and system definitions
123 typedef void xint; /* base type of jmp_buf, for not broken compilers */
131 #define NOBLOCK ((struct op *)NULL)
132 #define NOWORD ((char *)NULL)
133 #define NOWORDS ((char **)NULL)
134 #define NOPIPE ((int *)NULL)
137 * Description of a command or an operation on commands.
138 * Might eventually use a union.
141 int type; /* operation type, see below */
142 char **words; /* arguments to a command */
143 struct ioword **ioact; /* IO actions (eg, < > >>) */
146 char *str; /* identifier for case and for */
149 #define TCOM 1 /* command */
150 #define TPAREN 2 /* (c-list) */
151 #define TPIPE 3 /* a | b */
152 #define TLIST 4 /* a [&;] b */
153 #define TOR 5 /* || */
154 #define TAND 6 /* && */
162 #define TPAT 14 /* pattern in case */
163 #define TBRACE 15 /* {c-list} */
164 #define TASYNC 16 /* c & */
165 /* Added to support "." file expansion */
168 /* Strings for names to make debug easier */
170 static char *T_CMD_NAMES[] = {
193 * actions determining the environment of a process
195 #define BIT(i) (1<<(i))
196 #define FEXEC BIT(0) /* execute without forking */
198 #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(char 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(char 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");
875 prompt = lookup("PS1");
876 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
877 if (prompt->value == null)
879 setval(prompt, DEFAULT_USER_PROMPT);
880 if (geteuid() == 0) {
881 setval(prompt, DEFAULT_ROOT_PROMPT);
882 prompt->status &= ~EXPORT;
884 cprompt = lookup("PS2");
885 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
886 if (cprompt->value == null)
888 setval(cprompt, "> ");
894 if (argv[0][0] == '-' && argv[0][1] != '\0') {
895 for (s = argv[0] + 1; *s; s++)
898 prompt->status &= ~EXPORT;
899 cprompt->status &= ~EXPORT;
904 PUSHIO(aword, *++argv, iof = nlchar);
916 prompt->status &= ~EXPORT;
924 if (*s >= 'a' && *s <= 'z')
932 if (iof == filechar && --argc > 0) {
935 prompt->status &= ~EXPORT;
936 cprompt->status &= ~EXPORT;
938 /* Shell is non-interactive, activate printf-based debug */
940 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
944 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
946 if (newfile(name = *++argv))
947 exit(1); /* Exit on error */
953 /* This won't be true if PUSHIO has been called, say from newfile() above */
954 if (e.iop < iostack) {
955 PUSHIO(afile, 0, iof);
956 if (isatty(0) && isatty(1) && !cflag) {
958 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
960 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
962 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
964 printf("Enter 'help' for a list of built-in commands.\n\n");
969 signal(SIGQUIT, qflag);
970 if (name && name[0] == '-') {
972 if ((f = open(".profile", 0)) >= 0)
974 if ((f = open("/etc/profile", 0)) >= 0)
978 signal(SIGTERM, sig);
980 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
981 signal(SIGINT, onintr);
986 for (ap = ++argv; --argc > 0;) {
987 if (assign(*ap = *argv++, !COPYV)) {
988 dolc--; /* keyword */
994 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
996 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
999 if (interactive && e.iop <= iostack) {
1000 #ifdef CONFIG_FEATURE_COMMAND_EDITING
1001 current_prompt = prompt->value;
1007 /* Ensure that getenv("PATH") stays current */
1008 setenv("PATH", path->value, 1);
1011 DBGPRINTF(("MSH_MAIN: returning.\n"));
1014 static void setdash(void)
1018 char m['z' - 'a' + 1];
1021 for (c = 'a'; c <= 'z'; c++)
1025 setval(lookup("-"), m);
1028 static int newfile(char *s)
1032 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1034 if (strcmp(s, "-") != 0) {
1035 DBGPRINTF(("NEWFILE: s is %s\n", s));
1039 err(": cannot open");
1050 struct op *scantree(struct op *head)
1057 if (head->left != NULL) {
1058 dotnode = scantree(head->left);
1063 if (head->right != NULL) {
1064 dotnode = scantree(head->right);
1069 if (head->words == NULL)
1072 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1074 if ((head->type != TDOT) && (strcmp(".", head->words[0]) == 0)) {
1075 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1083 static void onecommand(void)
1088 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1107 setjmp(failpt = m1); /* Bruce Evans' fix */
1108 if (setjmp(failpt = m1) || yyparse() || intr) {
1110 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1115 if (!interactive && intr)
1128 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1130 execute(outtree, NOPIPE, NOPIPE, 0);
1133 if (!interactive && intr) {
1138 if ((i = trapset) != 0) {
1144 static void fail(void)
1150 static void leave(void)
1152 DBGPRINTF(("LEAVE: leave called!\n"));
1163 static void warn(char *s)
1174 static void err(char *s)
1182 longjmp(e.errpt, 1);
1184 e.iop = e.iobase = iostack;
1187 static int newenv(int f)
1191 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1198 ep = (struct env *) space(sizeof(*ep));
1211 static void quitenv(void)
1216 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1218 if ((ep = e.oenv) != NULL) {
1221 /* should close `'d files */
1223 while (--fd >= e.iofd)
1229 * Is any character from s1 in s2?
1231 static int anys(char *s1, char *s2)
1240 * Is character c in s?
1242 static int any(int c, char *s)
1250 static char *putn(int n)
1255 static char *itoa(int n)
1259 snprintf(s, sizeof(s), "%u", n);
1264 static void next(int f)
1266 PUSHIO(afile, f, filechar);
1269 static void onintr(int s) /* ANSI C requires a parameter */
1271 signal(SIGINT, onintr);
1278 } else if (heedint) {
1284 static char *space(int n)
1288 if ((cp = getcell(n)) == 0)
1289 err("out of string space");
1293 static char *strsave(char *s, int a)
1297 if ((cp = space(strlen(s) + 1)) != NULL) {
1298 setarea((char *) cp, a);
1299 for (xp = cp; (*xp++ = *s++) != '\0';);
1308 static void sig(int i)
1314 static void runtrap(int i)
1318 if ((trapstr = trap[i]) == NULL)
1324 RUN(aword, trapstr, nlchar);
1327 /* -------- var.c -------- */
1330 * Find the given name in the dictionary
1331 * and return its value. If the name was
1332 * not previously there, enter it now and
1333 * return a null value.
1335 static struct var *lookup(char *n)
1340 static struct var dummy;
1344 for (c = 0; isdigit(*n) && c < 1000; n++)
1345 c = c * 10 + *n - '0';
1346 dummy.status = RONLY;
1347 dummy.value = c <= dolc ? dolv[c] : null;
1350 for (vp = vlist; vp; vp = vp->next)
1351 if (eqname(vp->name, n))
1354 vp = (struct var *) space(sizeof(*vp));
1355 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1356 dummy.name = dummy.value = "";
1359 for (cp = vp->name; (*cp = *n++) && *cp != '='; cp++);
1363 setarea((char *) vp, 0);
1364 setarea((char *) vp->name, 0);
1367 vp->status = GETCELL;
1373 * give variable at `vp' the value `val'.
1375 static void setval(struct var *vp, char *val)
1377 nameval(vp, val, (char *) NULL);
1381 * if name is not NULL, it must be
1382 * a prefix of the space `val',
1384 * this is all so that exporting
1385 * values is reasonably painless.
1387 static void nameval(struct var *vp, char *val, char *name)
1393 if (vp->status & RONLY) {
1394 for (xp = vp->name; *xp && *xp != '=';)
1395 putc(*xp++, stderr);
1396 err(" is read-only");
1401 xp = space(strlen(vp->name) + strlen(val) + 2);
1404 /* make string: name=value */
1405 setarea((char *) xp, 0);
1407 for (cp = vp->name; (*xp = *cp++) && *xp != '='; xp++);
1411 for (cp = val; (*xp++ = *cp++) != '\0';);
1415 if (vp->status & GETCELL)
1416 freecell(vp->name); /* form new string `name=value' */
1422 static void export(struct var *vp)
1424 vp->status |= EXPORT;
1427 static void ronly(struct var *vp)
1429 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1430 vp->status |= RONLY;
1433 static int isassign(char *s)
1435 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1437 if (!isalpha((int) *s) && *s != '_')
1439 for (; *s != '='; s++)
1440 if (*s == 0 || (!isalnum(*s) && *s != '_'))
1446 static int assign(char *s, int cf)
1451 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1453 if (!isalpha(*s) && *s != '_')
1455 for (cp = s; *cp != '='; cp++)
1456 if (*cp == 0 || (!isalnum(*cp) && *cp != '_'))
1459 nameval(vp, ++cp, cf == COPYV ? (char *) NULL : s);
1461 vp->status &= ~GETCELL;
1465 static int checkname(char *cp)
1467 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1469 if (!isalpha(*cp++) && *(cp - 1) != '_')
1472 if (!isalnum(*cp++) && *(cp - 1) != '_')
1477 static void putvlist(int f, int out)
1481 for (vp = vlist; vp; vp = vp->next)
1482 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1483 if (vp->status & EXPORT)
1484 write(out, "export ", 7);
1485 if (vp->status & RONLY)
1486 write(out, "readonly ", 9);
1487 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1488 write(out, "\n", 1);
1492 static int eqname(char *n1, char *n2)
1494 for (; *n1 != '=' && *n1 != 0; n1++)
1497 return (*n2 == 0 || *n2 == '=');
1500 static char *findeq(char *cp)
1502 while (*cp != '\0' && *cp != '=')
1507 /* -------- gmatch.c -------- */
1509 * int gmatch(string, pattern)
1510 * char *string, *pattern;
1512 * Match a pattern as in sh(1).
1517 #define QMASK (CMASK&~QUOTE)
1518 #define NOT '!' /* might use ^ */
1520 static int gmatch(char *s, char *p)
1524 if (s == NULL || p == NULL)
1526 while ((pc = *p++ & CMASK) != '\0') {
1530 if ((p = cclass(p, sc)) == NULL)
1542 if (*p == '\0' || gmatch(s, p))
1544 } while (*s++ != '\0');
1548 if (sc != (pc & ~QUOTE))
1555 static char *cclass(char *p, int sub)
1557 int c, d, not, found;
1559 if ((not = *p == NOT) != 0)
1564 return ((char *) NULL);
1566 if (p[1] == '-' && p[2] != ']') {
1571 if (c == sub || (c <= sub && sub <= d))
1573 } while (*++p != ']');
1574 return (found ? p + 1 : (char *) NULL);
1578 /* -------- area.c -------- */
1581 * All memory between (char *)areabot and (char *)(areatop+1) is
1582 * exclusively administered by the area management routines.
1583 * It is assumed that sbrk() and brk() manipulate the high end.
1586 #define sbrk(X) ({ void * __q = (void *)-1; if (brkaddr + (int)(X) < brktop) { __q = brkaddr; brkaddr+=(int)(X); } __q;})
1588 static void initarea(void)
1590 brkaddr = xmalloc(AREASIZE);
1591 brktop = brkaddr + AREASIZE;
1593 while ((long) sbrk(0) & ALIGN)
1595 areabot = (struct region *) sbrk(REGSIZE);
1597 areabot->next = areabot;
1598 areabot->area = BUSY;
1603 char *getcell(unsigned nbytes)
1606 struct region *p, *q;
1613 /* silly and defeats the algorithm */
1615 * round upwards and add administration area
1617 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
1618 for (p = areanxt;;) {
1619 if (p->area > areanum) {
1623 while ((q = p->next)->area > areanum && q != areanxt)
1626 * exit loop if cell big enough
1628 if (q >= p + nregio)
1635 i = nregio >= GROWBY ? nregio : GROWBY;
1636 p = (struct region *) sbrk(i * REGSIZE);
1637 if (p == (struct region *) -1)
1638 return ((char *) NULL);
1642 abort(); /* allocated areas are contiguous */
1652 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
1654 areanxt = p + nregio;
1657 * split into requested area and rest
1659 if (areanxt + 1 > q) {
1661 abort(); /* insufficient space left for admin */
1664 areanxt->area = FREE;
1668 return ((char *) (p + 1));
1671 static void freecell(char *cp)
1675 if ((p = (struct region *) cp) != NULL) {
1683 static void freearea(int a)
1685 struct region *p, *top;
1688 for (p = areabot; p != top; p = p->next)
1693 static void setarea(char *cp, int a)
1697 if ((p = (struct region *) cp) != NULL)
1701 int getarea(char *cp)
1703 return ((struct region *) cp - 1)->area;
1706 static void garbage(void)
1708 struct region *p, *q, *top;
1711 for (p = areabot; p != top; p = p->next) {
1712 if (p->area > areanum) {
1713 while ((q = p->next)->area > areanum)
1719 if (areatop >= q + SHRINKBY && q->area > areanum) {
1720 brk((char *) (q + 1));
1728 /* -------- csyn.c -------- */
1730 * shell: syntax (C version)
1735 DBGPRINTF7(("YYPARSE: enter...\n"));
1742 return (yynerrs != 0);
1745 static struct op *pipeline(int cf)
1750 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1754 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1757 while ((c = yylex(0)) == '|') {
1758 if ((p = command(CONTIN)) == NULL) {
1759 DBGPRINTF8(("PIPELINE: error!\n"));
1763 if (t->type != TPAREN && t->type != TCOM) {
1764 /* shell statement */
1765 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1768 t = block(TPIPE, t, p, NOWORDS);
1773 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1777 static struct op *andor(void)
1782 DBGPRINTF7(("ANDOR: enter...\n"));
1786 DBGPRINTF9(("ANDOR: t=%p\n", t));
1789 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1790 if ((p = pipeline(CONTIN)) == NULL) {
1791 DBGPRINTF8(("ANDOR: error!\n"));
1795 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1801 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1805 static struct op *c_list(void)
1810 DBGPRINTF7(("C_LIST: enter...\n"));
1815 if ((peeksym = yylex(0)) == '&')
1816 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1818 while ((c = yylex(0)) == ';' || c == '&'
1819 || (multiline && c == '\n')) {
1821 if ((p = andor()) == NULL)
1824 if ((peeksym = yylex(0)) == '&')
1825 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1833 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1837 static int synio(int cf)
1843 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1845 if ((c = yylex(cf)) != '<' && c != '>') {
1852 iop = io(iounit, i, yylval.cp);
1856 markhere(yylval.cp, iop);
1858 DBGPRINTF7(("SYNIO: returning 1\n"));
1862 static void musthave(int c, int cf)
1864 if ((peeksym = yylex(cf)) != c) {
1865 DBGPRINTF7(("MUSTHAVE: error!\n"));
1872 static struct op *simple(void)
1878 switch (peeksym = yylex(0)) {
1899 static struct op *nested(int type, int mark)
1903 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1909 return (block(type, t, NOBLOCK, NOWORDS));
1912 static struct op *command(int cf)
1915 struct wdblock *iosave;
1918 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1934 if ((t = simple()) == NULL) {
1936 return ((struct op *) NULL);
1943 t = nested(TPAREN, ')');
1947 t = nested(TBRACE, '}');
1957 t->words = wordlist();
1958 if ((c = yylex(0)) != '\n' && c != ';')
1960 t->left = dogroup(0);
1968 t->type = c == WHILE ? TWHILE : TUNTIL;
1970 t->right = dogroup(1);
1982 musthave(IN, CONTIN);
1985 t->left = caselist();
1996 t->right = thenpart();
2005 musthave(WORD, 0); /* gets name of file */
2006 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
2008 word(yylval.cp); /* add word to wdlist */
2009 word(NOWORD); /* terminate wdlist */
2010 t->words = copyw(); /* dup wdlist */
2020 DBGPRINTF(("COMMAND: returning %p\n", t));
2025 static struct op *dowholefile(int type, int mark)
2029 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
2034 t = block(type, t, NOBLOCK, NOWORDS);
2035 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
2039 static struct op *dogroup(int onlydone)
2045 if (c == DONE && onlydone)
2046 return ((struct op *) NULL);
2054 static struct op *thenpart(void)
2059 if ((c = yylex(0)) != THEN) {
2061 return ((struct op *) NULL);
2066 if (t->left == NULL)
2068 t->right = elsepart();
2072 static struct op *elsepart(void)
2077 switch (c = yylex(0)) {
2079 if ((t = c_list()) == NULL)
2087 t->right = thenpart();
2092 return ((struct op *) NULL);
2096 static struct op *caselist(void)
2101 while ((peeksym = yylex(CONTIN)) != ESAC) {
2102 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
2103 t = list(t, casepart());
2106 DBGPRINTF(("CASELIST, returning t=%p\n", t));
2110 static struct op *casepart(void)
2114 DBGPRINTF7(("CASEPART: enter...\n"));
2118 t->words = pattern();
2121 if ((peeksym = yylex(CONTIN)) != ESAC)
2122 musthave(BREAK, CONTIN);
2124 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2129 static char **pattern(void)
2138 } while ((c = yylex(0)) == '|');
2145 static char **wordlist(void)
2149 if ((c = yylex(0)) != IN) {
2151 return ((char **) NULL);
2154 while ((c = yylex(0)) == WORD)
2162 * supporting functions
2164 static struct op *list(struct op *t1, struct op *t2)
2166 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2173 return (block(TLIST, t1, t2, NOWORDS));
2176 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2180 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2188 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2194 /* See if given string is a shell multiline (FOR, IF, etc) */
2195 static int rlookup(char *n)
2197 const struct res *rp;
2199 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2201 for (rp = restab; rp->r_name; rp++)
2202 if (strcmp(rp->r_name, n) == 0) {
2203 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2204 return (rp->r_val); /* Return numeric code for shell multiline */
2207 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2208 return (0); /* Not a shell multiline */
2211 static struct op *newtp(void)
2215 t = (struct op *) tree(sizeof(*t));
2223 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2228 static struct op *namelist(struct op *t)
2231 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2232 T_CMD_NAMES[t->type], iolist));
2235 iolist = addword((char *) NULL, iolist);
2236 t->ioact = copyio();
2240 if (t->type != TCOM) {
2241 if (t->type != TPAREN && t->ioact != NULL) {
2242 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2243 t->ioact = t->left->ioact;
2244 t->left->ioact = NULL;
2256 static char **copyw(void)
2260 wd = getwords(wdlist);
2265 static void word(char *cp)
2267 wdlist = addword(cp, wdlist);
2270 static struct ioword **copyio(void)
2272 struct ioword **iop;
2274 iop = (struct ioword **) getwords(iolist);
2279 static struct ioword *io(int u, int f, char *cp)
2283 iop = (struct ioword *) tree(sizeof(*iop));
2287 iolist = addword((char *) iop, iolist);
2291 static void zzerr(void)
2293 yyerror("syntax error");
2296 static void yyerror(char *s)
2299 if (interactive && e.iop <= iostack) {
2301 while (eofc() == 0 && yylex(0) != '\n');
2307 static int yylex(int cf)
2312 if ((c = peeksym) > 0) {
2327 line[LINELIM - 1] = '\0';
2330 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2335 if (any(c, "0123456789")) {
2336 unget(c1 = my_getc(0));
2337 if (c1 == '<' || c1 == '>') {
2346 case '#': /* Comment, skip to next newline or End-of-string */
2347 while ((c = my_getc(0)) != 0 && c != '\n');
2352 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2356 DBGPRINTF9(("YYLEX: found $\n"));
2358 if ((c = my_getc(0)) == '{') {
2359 if ((c = collect(c, '}')) != '\0')
2368 if ((c = collect(c, c)) != '\0')
2376 /* If more chars process them, else return NULL char */
2377 if ((c1 = dual(c)) != '\0')
2394 if (multiline || cf & CONTIN) {
2395 if (interactive && e.iop <= iostack) {
2396 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2397 current_prompt = cprompt->value;
2399 prs(cprompt->value);
2416 while ((c = my_getc(0)) != 0 && !any(c, "`$ '\"\t;&<>()|^\n")) {
2417 if (e.linep >= elinep)
2418 err("word too long");
2425 if (any(c, "\"'`$"))
2430 if (atstart && (c = rlookup(line)) != 0) {
2435 yylval.cp = strsave(line, areanum);
2440 static int collect(int c, int c1)
2444 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2447 while ((c = my_getc(c1)) != c1) {
2456 if (interactive && c == '\n' && e.iop <= iostack) {
2457 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2458 current_prompt = cprompt->value;
2460 prs(cprompt->value);
2468 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2473 /* "multiline commands" helper func */
2474 /* see if next 2 chars form a shell multiline */
2475 static int dual(int c)
2480 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2482 *cp++ = c; /* c is the given "peek" char */
2483 *cp++ = my_getc(0); /* get next char of input */
2484 *cp = 0; /* add EOS marker */
2486 c = rlookup(s); /* see if 2 chars form a shell multiline */
2488 unget(*--cp); /* String is not a shell multiline, put peek char back */
2490 return (c); /* String is multiline, return numeric multiline (restab) code */
2493 static void diag(int ec)
2497 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2500 if (c == '>' || c == '<') {
2503 yylval.i = ec == '>' ? IOWRITE | IOCAT : IOHERE;
2506 yylval.i = ec == '>' ? IOWRITE : IOREAD;
2507 if (c != '&' || yylval.i == IOHERE)
2513 static char *tree(unsigned size)
2517 if ((t = getcell(size)) == NULL) {
2518 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2519 prs("command line too complicated\n");
2529 /* -------- exec.c -------- */
2536 static int execute(struct op *t, int *pin, int *pout, int act)
2539 volatile int i, rv, a;
2540 char *cp, **wp, **wp2;
2542 struct op *outtree_save;
2546 /* Avoid longjmp clobbering */
2551 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2555 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2556 t->type, T_CMD_NAMES[t->type],
2557 ((t->words == NULL) ? "NULL" : t->words[0])));
2561 wp = (wp2 = t->words) != NULL
2562 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2567 DBGPRINTF3(("EXECUTE: TDOT\n"));
2569 outtree_save = outtree;
2571 newfile(evalstr(t->words[0], DOALL));
2573 t->left = dowholefile(TLIST, 0);
2576 outtree = outtree_save;
2579 rv = execute(t->left, pin, pout, 0);
2581 rv = execute(t->right, pin, pout, 0);
2585 rv = execute(t->left, pin, pout, 0);
2590 rv = forkexec(t, pin, pout, act, wp);
2598 if ((rv = openpipe(pv)) < 0)
2600 pv[0] = remap(pv[0]);
2601 pv[1] = remap(pv[1]);
2602 (void) execute(t->left, pin, pv, 0);
2603 rv = execute(t->right, pv, pout, 0);
2608 (void) execute(t->left, pin, pout, 0);
2609 rv = execute(t->right, pin, pout, 0);
2614 int hinteractive = interactive;
2616 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2620 interactive = hinteractive;
2622 setval(lookup("!"), putn(i));
2633 signal(SIGINT, SIG_IGN);
2634 signal(SIGQUIT, SIG_IGN);
2636 signal(SIGTERM, SIG_DFL);
2640 open(bb_dev_null, 0);
2642 _exit(execute(t->left, pin, pout, FEXEC));
2649 rv = execute(t->left, pin, pout, 0);
2650 if ((t1 = t->right) != NULL && (rv == 0) == (t->type == TAND))
2651 rv = execute(t1, pin, pout, 0);
2661 while (*wp++ != NULL);
2663 vp = lookup(t->str);
2664 while (setjmp(bc.brkpt))
2668 for (t1 = t->left; i-- && *wp != NULL;) {
2670 rv = execute(t1, pin, pout, 0);
2672 brklist = brklist->nextlev;
2677 while (setjmp(bc.brkpt))
2682 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2683 rv = execute(t->right, pin, pout, 0);
2684 brklist = brklist->nextlev;
2689 if (t->right != NULL) {
2690 rv = !execute(t->left, pin, pout, 0) ?
2691 execute(t->right->left, pin, pout, 0) :
2692 execute(t->right->right, pin, pout, 0);
2697 if ((cp = evalstr(t->str, DOSUB | DOTRIM)) == 0)
2700 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2701 ((t->str == NULL) ? "NULL" : t->str),
2702 ((cp == NULL) ? "NULL" : cp)));
2704 if ((t1 = findcase(t->left, cp)) != NULL) {
2705 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2706 rv = execute(t1, pin, pout, 0);
2707 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2713 if (iopp = t->ioact)
2715 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2720 if (rv >= 0 && (t1 = t->left))
2721 rv = execute(t1, pin, pout, 0);
2732 if (interactive && intr) {
2737 if ((i = trapset) != 0) {
2742 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2747 forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2751 int (*shcom) (struct op *) = NULL;
2754 struct ioword **iopp;
2764 struct brkcon *hbrklist;
2768 /* Avoid longjmp clobbering */
2778 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2780 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2781 ((t->words == NULL) ? "NULL" : t->words[0])));
2785 rv = -1; /* system-detected error */
2786 if (t->type == TCOM) {
2787 while ((cp = *wp++) != NULL);
2790 /* strip all initial assignments */
2791 /* not correct wrt PATH=yyy command etc */
2793 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2795 echo(cp ? wp : owp);
2798 if (cp == NULL && t->ioact == NULL) {
2799 while ((cp = *owp++) != NULL && assign(cp, COPYV));
2800 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2801 return (setstatus(0));
2802 } else if (cp != NULL) {
2803 shcom = inbuilt(cp);
2810 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2813 if (shcom == NULL && (f & FEXEC) == 0) {
2814 /* Save values in case the child process alters them */
2818 hinteractive = interactive;
2823 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2828 DBGPRINTF(("FORKEXEC: ERROR, unable to vfork()!\n"));
2833 if (newpid > 0) { /* Parent */
2835 /* Restore values */
2839 interactive = hinteractive;
2852 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2855 /* Must be the child process, pid should be 0 */
2856 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2859 signal(SIGINT, SIG_IGN);
2860 signal(SIGQUIT, SIG_IGN);
2872 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2877 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2878 err("piping to/from shell builtins not yet done");
2894 if ((iopp = t->ioact) != NULL) {
2895 if (shcom != NULL && shcom != doexec) {
2897 err(": cannot redirect shell command");
2903 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2911 i = setstatus((*shcom) (t));
2914 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2918 /* should use FIOCEXCL */
2919 for (i = FDBASE; i < NOFILE; i++)
2922 signal(SIGINT, SIG_DFL);
2923 signal(SIGQUIT, SIG_DFL);
2926 if (t->type == TPAREN)
2927 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2931 cp = rexecve(wp[0], wp, makenv(0, NULL));
2938 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2946 * 0< 1> are ignored as required
2949 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2952 char *cp = NULL, *msg;
2954 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2957 if (iop->io_unit == IODEFAULT) /* take default */
2958 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2960 if (pipein && iop->io_unit == 0)
2963 if (pipeout && iop->io_unit == 1)
2966 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2967 if ((iop->io_flag & IOHERE) == 0) {
2969 if ((cp = evalstr(cp, DOSUB | DOTRIM)) == NULL)
2973 if (iop->io_flag & IODUP) {
2974 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2976 err(": illegal >& argument");
2980 iop->io_flag = IOCLOSE;
2981 iop->io_flag &= ~(IOREAD | IOWRITE);
2983 switch (iop->io_flag) {
2989 case IOHERE | IOXHERE:
2990 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2994 case IOWRITE | IOCAT:
2995 if ((u = open(cp, 1)) >= 0) {
2996 lseek(u, (long) 0, 2);
3000 u = creat(cp, 0666);
3004 u = dup2(*cp - '0', iop->io_unit);
3008 close(iop->io_unit);
3017 if (u != iop->io_unit) {
3018 dup2(u, iop->io_unit);
3025 static void echo(char **wp)
3030 for (i = 0; wp[i]; i++) {
3038 static struct op **find1case(struct op *t, char *w)
3046 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
3047 return ((struct op **) NULL);
3050 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
3051 T_CMD_NAMES[t->type]));
3053 if (t->type == TLIST) {
3054 if ((tp = find1case(t->left, w)) != NULL) {
3055 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
3058 t1 = t->right; /* TPAT */
3062 for (wp = t1->words; *wp;)
3063 if ((cp = evalstr(*wp++, DOSUB)) && gmatch(w, cp)) {
3064 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
3069 DBGPRINTF(("FIND1CASE: returning NULL\n"));
3070 return ((struct op **) NULL);
3073 static struct op *findcase(struct op *t, char *w)
3077 return ((tp = find1case(t, w)) != NULL ? *tp : (struct op *) NULL);
3081 * Enter a new loop level (marked for break/continue).
3083 static void brkset(struct brkcon *bc)
3085 bc->nextlev = brklist;
3090 * Wait for the last process created.
3091 * Print a message for each process found
3092 * that was killed by a signal.
3093 * Ignore interrupt signals while waiting
3094 * unless `canintr' is true.
3096 static int waitfor(int lastpid, int canintr)
3100 int oheedint = heedint;
3107 if (errno != EINTR || canintr)
3110 if ((rv = WAITSIG(s)) != 0) {
3112 if (signame[rv] != NULL) {
3113 if (pid != lastpid) {
3120 if (pid != lastpid) {
3129 prs(" - core dumped");
3130 if (rv >= NSIGNAL || signame[rv])
3136 } while (pid != lastpid);
3151 static int setstatus(int s)
3154 setval(lookup("?"), putn(s));
3159 * PATH-searching interface to execve.
3160 * If getenv("PATH") were kept up-to-date,
3161 * execvp might be used.
3163 static char *rexecve(char *c, char **v, char **envp)
3167 int eacces = 0, asis = 0;
3169 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3173 if (find_applet_by_name(name)) {
3174 /* We have to exec here since we vforked. Running
3175 * run_applet_by_name() won't work and bad things
3177 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3181 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3183 sp = any('/', c) ? "" : path->value;
3185 while (asis || *sp != '\0') {
3188 for (; *sp != '\0'; tp++)
3189 if ((*tp = *sp++) == ':') {
3195 for (i = 0; (*tp++ = c[i++]) != '\0';);
3197 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3199 execve(e.linep, v, envp);
3206 execve(DEFAULT_SHELL, v, envp);
3208 return ("no Shell");
3211 return ((char *) bb_msg_memory_exhausted);
3214 return ("argument list too long");
3221 return (errno == ENOENT ? "not found" : "cannot execute");
3225 * Run the command produced by generator `f'
3226 * applied to stream `arg'.
3228 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3231 struct wdblock *swdlist;
3232 struct wdblock *siolist;
3238 /* Avoid longjmp clobbering */
3242 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3243 areanum, outtree, failpt));
3252 if (newenv(setjmp(errpt = ev)) == 0) {
3258 if (setjmp(failpt = rt) == 0 && yyparse() == 0)
3259 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3262 DBGPRINTF(("RUN: error from newenv()!\n"));
3269 freearea(areanum--);
3274 /* -------- do.c -------- */
3277 * built-in commands: doX
3280 static int dohelp(struct op *t)
3283 const struct builtincmd *x;
3285 printf("\nBuilt-in commands:\n");
3286 printf("-------------------\n");
3288 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3291 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3297 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3300 const struct BB_applet *applet;
3301 extern const struct BB_applet applets[];
3302 extern const size_t NUM_APPLETS;
3304 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3308 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3317 return EXIT_SUCCESS;
3322 static int dolabel(struct op *t)
3327 static int dochdir(struct op *t)
3331 if ((cp = t->words[1]) == NULL && (cp = homedir->value) == NULL)
3332 er = ": no home directory";
3333 else if (chdir(cp) < 0)
3334 er = ": bad directory";
3337 prs(cp != NULL ? cp : "cd");
3342 static int doshift(struct op *t)
3346 n = t->words[1] ? getn(t->words[1]) : 1;
3348 err("nothing to shift");
3354 setval(lookup("#"), putn(dolc));
3359 * execute login and newgrp directly
3361 static int dologin(struct op *t)
3366 signal(SIGINT, SIG_DFL);
3367 signal(SIGQUIT, SIG_DFL);
3369 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3376 static int doumask(struct op *t)
3381 if ((cp = t->words[1]) == NULL) {
3384 for (n = 3 * 4; (n -= 3) >= 0;)
3385 putc('0' + ((i >> n) & 07), stderr);
3388 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3389 n = n * 8 + (*cp - '0');
3395 static int doexec(struct op *t)
3402 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3407 if (setjmp(failpt = ex) == 0)
3408 execute(t, NOPIPE, NOPIPE, FEXEC);
3414 static int dodot(struct op *t)
3421 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)));
3423 if ((cp = t->words[1]) == NULL) {
3424 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3427 DBGPRINTF(("DODOT: cp is %s\n", cp));
3430 sp = any('/', cp) ? ":" : path->value;
3432 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3433 ((sp == NULL) ? "NULL" : sp),
3434 ((e.linep == NULL) ? "NULL" : e.linep)));
3438 while (*sp && (*tp = *sp++) != ':')
3443 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3446 if ((i = open(e.linep, 0)) >= 0) {
3449 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3451 next(maltmp); /* Basically a PUSHIO */
3453 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3466 static int dowait(struct op *t)
3471 if ((cp = t->words[1]) != NULL) {
3477 setstatus(waitfor(i, 1));
3481 static int doread(struct op *t)
3487 if (t->words[1] == NULL) {
3488 err("Usage: read name ...");
3491 for (wp = t->words + 1; *wp; wp++) {
3492 for (cp = e.linep; !nl && cp < elinep - 1; cp++)
3493 if ((nb = read(0, cp, sizeof(*cp))) != sizeof(*cp) ||
3494 (nl = (*cp == '\n')) || (wp[1] && any(*cp, ifs->value)))
3499 setval(lookup(*wp), e.linep);
3504 static int doeval(struct op *t)
3506 return (RUN(awordlist, t->words + 1, wdchar));
3509 static int dotrap(struct op *t)
3514 if (t->words[1] == NULL) {
3515 for (i = 0; i <= _NSIG; i++)
3524 resetsig = isdigit(*t->words[1]);
3525 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3526 n = getsig(t->words[i]);
3530 if (*t->words[1] != '\0') {
3531 trap[n] = strsave(t->words[1], 0);
3540 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3548 static int getsig(char *s)
3552 if ((n = getn(s)) < 0 || n > _NSIG) {
3553 err("trap: bad signal number");
3559 static void setsig(int n, sighandler_t f)
3563 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3569 static int getn(char *as)
3580 for (n = 0; isdigit(*s); s++)
3581 n = (n * 10) + (*s - '0');
3584 err(": bad number");
3589 static int dobreak(struct op *t)
3591 return (brkcontin(t->words[1], 1));
3594 static int docontinue(struct op *t)
3596 return (brkcontin(t->words[1], 0));
3599 static int brkcontin(char *cp, int val)
3604 nl = cp == NULL ? 1 : getn(cp);
3608 if ((bc = brklist) == NULL)
3610 brklist = bc->nextlev;
3613 err("bad break/continue level");
3617 longjmp(bc->brkpt, 1);
3621 static int doexit(struct op *t)
3626 if ((cp = t->words[1]) != NULL)
3627 setstatus(getn(cp));
3629 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3636 static int doexport(struct op *t)
3638 rdexp(t->words + 1, export, EXPORT);
3642 static int doreadonly(struct op *t)
3644 rdexp(t->words + 1, ronly, RONLY);
3648 static void rdexp(char **wp, void (*f) (struct var *), int key)
3650 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3651 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3654 for (; *wp != NULL; wp++) {
3655 if (isassign(*wp)) {
3659 for (cp = *wp; *cp != '='; cp++);
3671 static void badid(char *s)
3674 err(": bad identifier");
3677 static int doset(struct op *t)
3683 if ((cp = t->words[1]) == NULL) {
3684 for (vp = vlist; vp; vp = vp->next)
3685 varput(vp->name, 1);
3689 /* bad: t->words++; */
3690 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3692 flag['x'] = flag['v'] = 0;
3702 if (*cp >= 'a' && *cp <= 'z')
3709 t->words[0] = dolv[0];
3710 for (n = 1; t->words[n]; n++)
3711 setarea((char *) t->words[n], 0);
3714 setval(lookup("#"), putn(dolc));
3715 setarea((char *) (dolv - 1), 0);
3720 static void varput(char *s, int out)
3722 if (isalnum(*s) || *s == '_') {
3723 write(out, s, strlen(s));
3724 write(out, "\n", 1);
3730 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3731 * This file contains code for the times builtin.
3733 static int dotimes(struct op *t)
3736 long int clk_tck = sysconf(_SC_CLK_TCK);
3739 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3740 (int) (buf.tms_utime / clk_tck / 60),
3741 ((double) buf.tms_utime) / clk_tck,
3742 (int) (buf.tms_stime / clk_tck / 60),
3743 ((double) buf.tms_stime) / clk_tck,
3744 (int) (buf.tms_cutime / clk_tck / 60),
3745 ((double) buf.tms_cutime) / clk_tck,
3746 (int) (buf.tms_cstime / clk_tck / 60),
3747 ((double) buf.tms_cstime) / clk_tck);
3752 static int (*inbuilt(char *s)) (struct op *) {
3753 const struct builtincmd *bp;
3755 for (bp = builtincmds; bp->name != NULL; bp++)
3756 if (strcmp(bp->name, s) == 0)
3757 return (bp->builtinfunc);
3762 /* -------- eval.c -------- */
3767 * blank interpretation
3772 static char **eval(char **ap, int f)
3780 /* Avoid longjmp clobbering */
3785 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3790 if (newenv(setjmp(errpt = ev)) == 0) {
3791 while (*ap && isassign(*ap))
3792 expand(*ap++, &wb, f & ~DOGLOB);
3794 for (wf = ap; *wf; wf++) {
3796 expand(*wf, &wb, f & ~DOGLOB);
3799 for (wb = addword((char *) 0, wb); *ap; ap++) {
3800 if (!flag['k'] || !isassign(*ap))
3801 expand(*ap, &wb, f & ~DOKEY);
3803 wb = addword((char *) 0, wb);
3809 return (gflg ? (char **) NULL : wp);
3813 * Make the exported environment from the exported
3814 * names in the dictionary. Keyword assignments
3815 * will already have been done.
3817 static char **makenv(int all, struct wdblock *wb)
3821 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3823 for (vp = vlist; vp; vp = vp->next)
3824 if (all || vp->status & EXPORT)
3825 wb = addword(vp->name, wb);
3826 wb = addword((char *) 0, wb);
3827 return (getwords(wb));
3830 static char *evalstr(char *cp, int f)
3834 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3837 if (expand(cp, &wb, f)) {
3838 if (wb == NULL || wb->w_nword == 0
3839 || (cp = wb->w_words[0]) == NULL)
3847 static int expand(char *cp, struct wdblock **wbp, int f)
3852 /* Avoid longjmp clobbering */
3856 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3863 if (!anys("$`'\"", cp) &&
3864 !anys(ifs->value, cp) && ((f & DOGLOB) == 0 || !anys("[*?", cp))) {
3865 cp = strsave(cp, areanum);
3868 *wbp = addword(cp, *wbp);
3871 if (newenv(setjmp(errpt = ev)) == 0) {
3872 PUSHIO(aword, cp, strchar);
3874 while ((cp = blank(f)) && gflg == 0) {
3876 cp = strsave(cp, areanum);
3877 if ((f & DOGLOB) == 0) {
3880 *wbp = addword(cp, *wbp);
3882 *wbp = glob(cp, *wbp);
3891 * Blank interpretation and quoting
3893 static char *blank(int f)
3897 int scanequals, foundequals;
3899 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3902 scanequals = f & DOKEY;
3906 switch (c = subgetc('"', foundequals)) {
3914 if (f & DOBLANK && any(c, ifs->value))
3923 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3926 if (c == '\'' || !any(c, "$`\""))
3933 if (!isalpha(c) && c != '_')
3936 c = subgetc('"', foundequals);
3938 f & (DOBLANK && any(c, ifs->value)) ||
3939 (!INSUB() && any(c, "\"'"))) {
3950 } else if (!isalnum(c) && c != '_')
3960 * Get characters, substituting for ` and $
3962 static int subgetc(char ec, int quoted)
3966 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3970 if (!INSUB() && ec != '\'') {
3972 if (grave(quoted) == 0)
3974 e.iop->task = XGRAVE;
3977 if (c == '$' && (c = dollar(quoted)) == 0) {
3978 e.iop->task = XDOLL;
3986 * Prepare to generate the string returned by ${} substitution.
3988 static int dollar(int quoted)
3993 char *s, c, *cp = NULL;
3996 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
4002 if (isalpha(c) || c == '_') {
4003 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
4004 if (e.linep < elinep)
4011 otask = e.iop->task;
4013 e.iop->task = XOTHER;
4014 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
4015 if (e.linep < elinep)
4018 e.iop->task = otask;
4025 if (e.linep >= elinep) {
4026 err("string in ${} too long");
4032 for (cp = s + 1; *cp; cp++)
4033 if (any(*cp, "=-+?")) {
4038 if (s[1] == 0 && (*s == '*' || *s == '@')) {
4040 /* currently this does not distinguish $* and $@ */
4041 /* should check dollar */
4043 PUSHIO(awordlist, dolv + 1, dolchar);
4045 } else { /* trap the nasty ${=} */
4051 if ((dolp = vp->value) == null) {
4055 err("cannot use ${...=...} with $n");
4064 dolp = strsave(cp, areanum);
4069 prs("missing value for ");
4076 } else if (c == '+')
4077 dolp = strsave(cp, areanum);
4078 if (flag['u'] && dolp == null) {
4079 prs("unset variable: ");
4084 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4089 * Run the command in `...` and read its output.
4092 static int grave(int quoted)
4098 static char child_cmd[LINELIM];
4104 char *argument_list[4];
4105 struct wdblock *wb = NULL;
4108 /* Avoid longjmp clobbering */
4112 for (cp = e.iop->argp->aword; *cp != '`'; cp++)
4114 err("no closing `");
4118 /* string copy with dollar expansion */
4119 src = e.iop->argp->aword;
4124 while ((*src != '`') && (count < LINELIM)) {
4129 if (*src == '$' && !ignore && !ignore_once) {
4131 char var_name[LINELIM];
4132 char alt_value[LINELIM];
4145 var_name[var_index++] = *src++;
4146 while (isalnum(*src) || *src=='_')
4147 var_name[var_index++] = *src++;
4148 var_name[var_index] = 0;
4161 err("unclosed ${\n");
4166 while (*src && (*src != '}')) {
4167 alt_value[alt_index++] = *src++;
4169 alt_value[alt_index] = 0;
4171 err("unclosed ${\n");
4178 if (isalpha(*var_name)) {
4179 /* let subshell handle it instead */
4181 char *namep = var_name;
4189 char *altp = alt_value;
4197 wb = addword(lookup(var_name)->name, wb);
4201 vp = lookup(var_name);
4202 if (vp->value != null)
4203 value = (operator == '+') ?
4204 alt_value : vp->value;
4205 else if (operator == '?') {
4208 } else if (alt_index && (operator != '+')) {
4210 if (operator == '=')
4215 while (*value && (count < LINELIM)) {
4228 if (openpipe(pf) < 0)
4231 while ((i = vfork()) == -1 && errno == EAGAIN);
4233 DBGPRINTF3(("GRAVE: i is %p\n", io));
4237 err((char *) bb_msg_memory_exhausted);
4241 waitpid(i, NULL, 0);
4242 e.iop->argp->aword = ++cp;
4244 PUSHIO(afile, remap(pf[0]),
4245 (int (*)(struct ioarg *)) ((quoted) ? qgravechar :
4249 /* allow trapped signals */
4250 /* XXX - Maybe this signal stuff should go as well? */
4251 for (j = 0; j <= _NSIG; j++)
4252 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4258 argument_list[0] = (char *) DEFAULT_SHELL;
4259 argument_list[1] = "-c";
4260 argument_list[2] = child_cmd;
4261 argument_list[3] = 0;
4263 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4264 prs(argument_list[0]);
4271 static char *unquote(char *as)
4275 if ((s = as) != NULL)
4281 /* -------- glob.c -------- */
4287 #define scopy(x) strsave((x), areanum)
4289 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4291 static struct wdblock *cl, *nl;
4292 static char spcl[] = "[?*";
4294 static struct wdblock *glob(char *cp, struct wdblock *wb)
4302 for (pp = cp; *pp; pp++)
4305 else if (!any(*pp & ~QUOTE, spcl))
4308 for (cl = addword(scopy(cp), (struct wdblock *) 0); anyspcl(cl);
4310 nl = newword(cl->w_nword * 2);
4311 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4312 for (pp = cl->w_words[i]; *pp; pp++)
4313 if (any(*pp, spcl)) {
4314 globname(cl->w_words[i], pp);
4318 nl = addword(scopy(cl->w_words[i]), nl);
4320 for (i = 0; i < cl->w_nword; i++)
4321 DELETE(cl->w_words[i]);
4324 for (i = 0; i < cl->w_nword; i++)
4325 unquote(cl->w_words[i]);
4326 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4328 for (i = 0; i < cl->w_nword; i++)
4329 wb = addword(cl->w_words[i], wb);
4334 wb = addword(unquote(cp), wb);
4338 static void globname(char *we, char *pp)
4341 char *name, *gp, *dp;
4345 char dname[NAME_MAX + 1];
4348 for (np = we; np != pp; pp--)
4351 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4355 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4364 dname[NAME_MAX] = '\0';
4365 while ((de = readdir(dirp)) != NULL) {
4366 /* XXX Hmmm... What this could be? (abial) */
4368 if (ent[j].d_ino == 0)
4371 strncpy(dname, de->d_name, NAME_MAX);
4372 if (dname[0] == '.')
4375 for (k = 0; k < NAME_MAX; k++)
4376 if (any(dname[k], spcl))
4378 if (gmatch(dname, gp)) {
4379 name = generate(we, pp, dname, np);
4380 if (*np && !anys(np, spcl)) {
4381 if (stat(name, &dbuf)) {
4386 nl = addword(name, nl);
4395 * generate a pathname as below.
4396 * start..end1 / middle end
4397 * the slashes come for free
4399 static char *generate(char *start1, char *end1, char *middle, char *end)
4405 space((int) (end1 - start1) + strlen(middle) + strlen(end) + 2);
4406 for (xp = start1; xp != end1;)
4408 for (xp = middle; (*op++ = *xp++) != '\0';);
4410 for (xp = end; (*op++ = *xp++) != '\0';);
4414 static int anyspcl(struct wdblock *wb)
4420 for (i = 0; i < wb->w_nword; i++)
4421 if (anys(spcl, *wd++))
4426 static int xstrcmp(char *p1, char *p2)
4428 return (strcmp(*(char **) p1, *(char **) p2));
4431 /* -------- word.c -------- */
4433 static struct wdblock *newword(int nw)
4437 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4443 static struct wdblock *addword(char *wd, struct wdblock *wb)
4445 struct wdblock *wb2;
4449 wb = newword(NSTART);
4450 if ((nw = wb->w_nword) >= wb->w_bsize) {
4451 wb2 = newword(nw * 2);
4452 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4453 nw * sizeof(char *));
4458 wb->w_words[wb->w_nword++] = wd;
4463 char **getwords(struct wdblock *wb)
4469 return ((char **) NULL);
4470 if (wb->w_nword == 0) {
4472 return ((char **) NULL);
4474 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4475 memcpy((char *) wd, (char *) wb->w_words, nb);
4476 DELETE(wb); /* perhaps should done by caller */
4480 static int (*func) (char *, char *);
4483 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4487 glob1(a0, a0 + a1 * a2);
4490 static void glob1(char *base, char *lim)
4502 if ((n = (int) (lim - base)) <= v2)
4504 n = v2 * (n / (2 * v2));
4505 hptr = lptr = base + n;
4510 if ((c = (*func) (i, lptr)) == 0) {
4511 glob2(i, lptr -= v2);
4522 if ((c = (*func) (hptr, j)) == 0) {
4523 glob2(hptr += v2, j);
4528 glob3(i, hptr += v2, j);
4543 if (lptr - base >= lim - hptr) {
4544 glob1(hptr + v2, lim);
4554 glob3(j, lptr -= v2, i);
4559 static void glob2(char *i, char *j)
4561 char *index1, *index2, c;
4569 *index1++ = *index2;
4574 static void glob3(char *i, char *j, char *k)
4576 char *index1, *index2, *index3;
4586 *index1++ = *index3;
4587 *index3++ = *index2;
4592 /* -------- io.c -------- */
4598 static int my_getc(int ec)
4602 if (e.linep > elinep) {
4603 while ((c = readc()) != '\n' && c);
4604 err("input line too long");
4609 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4612 if (c == '\n' && ec != '\"')
4613 return (my_getc(ec));
4620 static void unget(int c)
4622 if (e.iop >= e.iobase)
4626 static int eofc(void)
4628 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4631 static int readc(void)
4635 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4637 for (; e.iop >= e.iobase; e.iop--) {
4638 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4639 if ((c = e.iop->peekc) != '\0') {
4643 if (e.iop->prev != 0) {
4644 if ((c = (*e.iop->iofn) (e.iop->argp, e.iop)) != '\0') {
4649 if (e.iop == iostack)
4651 return (e.iop->prev = c);
4652 } else if (e.iop->task == XIO && e.iop->prev != '\n') {
4654 if (e.iop == iostack)
4659 if (e.iop->task == XIO) {
4661 return e.iop->prev = 0;
4663 if (interactive && e.iop == iostack + 1) {
4664 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4665 current_prompt = prompt->value;
4675 if (e.iop >= iostack) {
4676 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4680 DBGPRINTF(("READC: leave()...\n"));
4687 static void ioecho(char c)
4690 write(2, &c, sizeof c);
4694 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4696 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4697 argp->afid, e.iop));
4699 /* Set env ptr for io source to next array spot and check for array overflow */
4700 if (++e.iop >= &iostack[NPUSH]) {
4702 err("Shell input nested too deeply");
4707 /* We did not overflow the NPUSH array spots so setup data structs */
4709 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4711 if (argp->afid != AFID_NOBUF)
4715 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4716 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4718 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4720 if (e.iop == &iostack[0])
4721 e.iop->argp->afbuf = &mainbuf;
4723 e.iop->argp->afbuf = &sharedbuf;
4725 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4726 /* This line appears to be active when running scripts from command line */
4727 if ((isatty(e.iop->argp->afile) == 0)
4728 && (e.iop == &iostack[0]
4729 || lseek(e.iop->argp->afile, 0L, 1) != -1)) {
4730 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4731 bufid = AFID_ID; /* AFID_ID = 0 */
4733 e.iop->argp->afid = bufid; /* assign buffer id */
4736 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4737 iostack, e.iop, e.iop->argp->afbuf));
4738 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4739 &mainbuf, &sharedbuf, bufid, e.iop));
4743 e.iop->prev = ~'\n';
4748 if (fn == filechar || fn == linechar)
4750 else if (fn == (int (*)(struct ioarg *)) gravechar
4751 || fn == (int (*)(struct ioarg *)) qgravechar)
4752 e.iop->task = XGRAVE;
4754 e.iop->task = XOTHER;
4759 static struct io *setbase(struct io *ip)
4769 * Input generating functions
4773 * Produce the characters of a string, then a newline, then EOF.
4775 static int nlchar(struct ioarg *ap)
4779 if (ap->aword == NULL)
4781 if ((c = *ap->aword++) == 0) {
4789 * Given a list of words, produce the characters
4790 * in them, with a space after each word.
4792 static int wdchar(struct ioarg *ap)
4797 if ((wl = ap->awordlist) == NULL)
4800 if ((c = *(*wl)++) != 0)
4805 ap->awordlist = NULL;
4810 * Return the characters of a list of words,
4811 * producing a space between them.
4813 static int dolchar(struct ioarg *ap)
4817 if ((wp = *ap->awordlist++) != NULL) {
4818 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4824 static int xxchar(struct ioarg *ap)
4828 if (ap->aword == NULL)
4830 if ((c = *ap->aword++) == '\0') {
4838 * Produce the characters from a single word (string).
4840 static int strchar(struct ioarg *ap)
4844 if (ap->aword == NULL || (c = *ap->aword++) == 0)
4850 * Produce quoted characters from a single word (string).
4852 static int qstrchar(struct ioarg *ap)
4856 if (ap->aword == NULL || (c = *ap->aword++) == 0)
4862 * Return the characters from a file.
4864 static int filechar(struct ioarg *ap)
4868 struct iobuf *bp = ap->afbuf;
4870 if (ap->afid != AFID_NOBUF) {
4871 if ((i = ap->afid != bp->id) || bp->bufp == bp->ebufp) {
4874 lseek(ap->afile, ap->afpos, 0);
4876 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4884 bp->ebufp = (bp->bufp = bp->buf) + i;
4888 return *bp->bufp++ & 0177;
4890 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4891 if (interactive && isatty(ap->afile)) {
4892 static char mycommand[BUFSIZ];
4893 static int position = 0, size = 0;
4895 while (size == 0 || position >= size) {
4896 cmdedit_read_input(current_prompt, mycommand);
4897 size = strlen(mycommand);
4900 c = mycommand[position];
4907 i = safe_read(ap->afile, &c, sizeof(c));
4908 return (i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0));
4913 * Return the characters from a here temp file.
4915 static int herechar(struct ioarg *ap)
4920 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4929 * Return the characters produced by a process (`...`).
4930 * Quote them if required, and remove any trailing newline characters.
4932 static int gravechar(struct ioarg *ap, struct io *iop)
4936 if ((c = qgravechar(ap, iop) & ~QUOTE) == '\n')
4941 static int qgravechar(struct ioarg *ap, struct io *iop)
4945 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4950 return ('\n' | QUOTE);
4954 } else if ((c = filechar(ap)) == '\n') {
4956 while ((c = filechar(ap)) == '\n')
4964 return (c != 0 ? c | QUOTE : 0);
4968 * Return a single command (usually the first line) from a file.
4970 static int linechar(struct ioarg *ap)
4974 if ((c = filechar(ap)) == '\n') {
4977 ap->afile = -1; /* illegal value */
4983 static void prs(const char *s)
4986 write(2, s, strlen(s));
4989 static void prn(unsigned u)
4994 static void closef(int i)
5000 static void closeall(void)
5004 for (u = NUFILE; u < NOFILE;)
5010 * remap fd into Shell's fd space
5012 static int remap(int fd)
5019 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
5022 for (i = 0; i < NOFILE; i++)
5029 } while (fd >= 0 && fd < e.iofd);
5031 for (i = 0; i < NOFILE; i++)
5036 err("too many files open in shell");
5042 static int openpipe(int *pv)
5046 if ((i = pipe(pv)) < 0)
5047 err("can't create pipe - try again");
5051 static void closepipe(int *pv)
5059 /* -------- here.c -------- */
5065 static void markhere(char *s, struct ioword *iop)
5067 struct here *h, *lh;
5069 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
5071 h = (struct here *) space(sizeof(struct here));
5075 h->h_tag = evalstr(s, DOSUB);
5085 for (lh = inhere; lh != NULL; lh = lh->h_next)
5086 if (lh->h_next == 0) {
5090 iop->io_flag |= IOHERE | IOXHERE;
5091 for (s = h->h_tag; *s; s++)
5093 iop->io_flag &= ~IOXHERE;
5096 h->h_dosub = iop->io_flag & IOXHERE;
5099 static void gethere(void)
5101 struct here *h, *hp;
5103 DBGPRINTF7(("GETHERE: enter...\n"));
5105 /* Scan here files first leaving inhere list in place */
5106 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5107 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5109 /* Make inhere list active - keep list intact for scraphere */
5111 hp->h_next = acthere;
5117 static void readhere(char **name, char *s, int ec)
5120 char tname[30] = ".msh_XXXXXX";
5123 char myline[LINELIM + 1];
5126 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5128 tf = mkstemp(tname);
5132 *name = strsave(tname, areanum);
5133 if (newenv(setjmp(errpt = ev)) != 0)
5136 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5139 if (interactive && e.iop <= iostack) {
5140 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5141 current_prompt = cprompt->value;
5143 prs(cprompt->value);
5147 while ((c = my_getc(ec)) != '\n' && c) {
5150 if (thenext >= &myline[LINELIM]) {
5157 if (strcmp(s, myline) == 0 || c == 0)
5160 write(tf, myline, (int) (thenext - myline));
5163 prs("here document `");
5173 * open here temp file.
5174 * if unquoted here, expand here temp file into second temp file.
5176 static int herein(char *hname, int xdoll)
5182 /* Avoid longjmp clobbering */
5188 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5190 hf = open(hname, 0);
5196 char tname[30] = ".msh_XXXXXX";
5199 tf = mkstemp(tname);
5202 if (newenv(setjmp(errpt = ev)) == 0) {
5203 PUSHIO(afile, hf, herechar);
5205 while ((c = subgetc(0, 0)) != 0) {
5207 write(tf, &c, sizeof c);
5213 tf = open(tname, 0);
5220 static void scraphere(void)
5224 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5226 for (h = inhere; h != NULL; h = h->h_next) {
5227 if (h->h_iop && h->h_iop->io_name)
5228 unlink(h->h_iop->io_name);
5233 /* unlink here temp files before a freearea(area) */
5234 static void freehere(int area)
5236 struct here *h, *hl;
5238 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5241 for (h = acthere; h != NULL; h = h->h_next)
5242 if (getarea((char *) h) >= area) {
5243 if (h->h_iop->io_name != NULL)
5244 unlink(h->h_iop->io_name);
5246 acthere = h->h_next;
5248 hl->h_next = h->h_next;
5256 * Copyright (c) 1987,1997, Prentice Hall
5257 * All rights reserved.
5259 * Redistribution and use of the MINIX operating system in source and
5260 * binary forms, with or without modification, are permitted provided
5261 * that the following conditions are met:
5263 * Redistributions of source code must retain the above copyright
5264 * notice, this list of conditions and the following disclaimer.
5266 * Redistributions in binary form must reproduce the above
5267 * copyright notice, this list of conditions and the following
5268 * disclaimer in the documentation and/or other materials provided
5269 * with the distribution.
5271 * Neither the name of Prentice Hall nor the names of the software
5272 * authors or contributors may be used to endorse or promote
5273 * products derived from this software without specific prior
5274 * written permission.
5276 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5277 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5278 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5279 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5280 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5281 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5282 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5283 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5284 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5285 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5286 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5287 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.