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 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
18 #include <sys/times.h>
22 /*#define MSHDEBUG 1*/
25 int mshdbg = MSHDEBUG;
27 #define DBGPRINTF(x) if(mshdbg>0)printf x
28 #define DBGPRINTF0(x) if(mshdbg>0)printf x
29 #define DBGPRINTF1(x) if(mshdbg>1)printf x
30 #define DBGPRINTF2(x) if(mshdbg>2)printf x
31 #define DBGPRINTF3(x) if(mshdbg>3)printf x
32 #define DBGPRINTF4(x) if(mshdbg>4)printf x
33 #define DBGPRINTF5(x) if(mshdbg>5)printf x
34 #define DBGPRINTF6(x) if(mshdbg>6)printf x
35 #define DBGPRINTF7(x) if(mshdbg>7)printf x
36 #define DBGPRINTF8(x) if(mshdbg>8)printf x
37 #define DBGPRINTF9(x) if(mshdbg>9)printf x
41 #define RCPRINTF(x) if(mshdbg_rc)printf x
62 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
63 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
64 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
66 # define DEFAULT_ROOT_PROMPT "# "
67 # define DEFAULT_USER_PROMPT "$ "
71 /* -------- sh.h -------- */
77 #define NPUSH 8 /* limit to input nesting */
80 #define NOFILE 20 /* Number of open files */
81 #define NUFILE 10 /* Number of user-accessible files */
82 #define FDBASE 10 /* First file usable by Shell */
85 * values returned by wait
87 #define WAITSIG(s) ((s)&0177)
88 #define WAITVAL(s) (((s)>>8)&0377)
89 #define WAITCORE(s) (((s)&0200)!=0)
92 * library and system definitions
94 typedef void xint; /* base type of jmp_buf, for not broken compilers */
102 #define NOBLOCK ((struct op *)NULL)
103 #define NOWORD ((char *)NULL)
104 #define NOWORDS ((char **)NULL)
105 #define NOPIPE ((int *)NULL)
108 * Description of a command or an operation on commands.
109 * Might eventually use a union.
112 int type; /* operation type, see below */
113 char **words; /* arguments to a command */
114 struct ioword **ioact; /* IO actions (eg, < > >>) */
117 char *str; /* identifier for case and for */
120 #define TCOM 1 /* command */
121 #define TPAREN 2 /* (c-list) */
122 #define TPIPE 3 /* a | b */
123 #define TLIST 4 /* a [&;] b */
124 #define TOR 5 /* || */
125 #define TAND 6 /* && */
133 #define TPAT 14 /* pattern in case */
134 #define TBRACE 15 /* {c-list} */
135 #define TASYNC 16 /* c & */
136 /* Added to support "." file expansion */
139 /* Strings for names to make debug easier */
141 static char *T_CMD_NAMES[] = {
164 * actions determining the environment of a process
166 #define BIT(i) (1<<(i))
167 #define FEXEC BIT(0) /* execute without forking */
169 #define AREASIZE (90000)
172 * flags to control evaluation of words
174 #define DOSUB 1 /* interpret $, `, and quotes */
175 #define DOBLANK 2 /* perform blank interpretation */
176 #define DOGLOB 4 /* interpret [?* */
177 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
178 #define DOTRIM 16 /* trim resulting string */
180 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
184 static int newfile(char *s);
185 static char *findeq(char *cp);
186 static char *cclass(char *p, int sub);
187 static void initarea(void);
188 extern int msh_main(int argc, char **argv);
193 struct brkcon *nextlev;
201 short io_unit; /* unit affected */
202 short io_flag; /* action (below) */
203 char *io_name; /* file name */
206 #define IOREAD 1 /* < */
207 #define IOHERE 2 /* << (here file) */
208 #define IOWRITE 4 /* > */
209 #define IOCAT 8 /* >> */
210 #define IOXHERE 16 /* ${}, ` in << */
211 #define IODUP 32 /* >&digit */
212 #define IOCLOSE 64 /* >&- */
214 #define IODEFAULT (-1) /* token for default IO unit */
219 * parsing & execution environment
225 xint *errpt; /* void * */
233 * -k: look for name=value everywhere on command line
235 * -t: exit after reading and executing one command
238 * -u: unset variables net diagnostic
240 static char flags['z' - 'a' + 1];
241 /* this looks weird, but is OK ... we index flag with 'a'...'z' */
242 static char *flag = flags - 'a';
244 static char *null; /* null value for variable */
245 static int intr; /* interrupt pending */
247 static char *trap[_NSIG + 1];
248 static char ourtrap[_NSIG + 1];
249 static int trapset; /* trap pending */
251 static int heedint; /* heed interrupt signals */
253 static int yynerrs; /* yacc */
255 static char line[LINELIM];
262 static int (*inbuilt(char *s)) (struct op *);
264 static char *rexecve(char *c, char **v, char **envp);
265 static char *space(int n);
266 static char *strsave(char *s, int a);
267 static char *evalstr(char *cp, int f);
268 static char *putn(int n);
269 static char *unquote(char *as);
270 static struct var *lookup(char *n);
271 static int rlookup(char *n);
272 static struct wdblock *glob(char *cp, struct wdblock *wb);
273 static int my_getc(int ec);
274 static int subgetc(char ec, int quoted);
275 static char **makenv(int all, struct wdblock *wb);
276 static char **eval(char **ap, int f);
277 static int setstatus(int s);
278 static int waitfor(int lastpid, int canintr);
280 static void onintr(int s); /* SIGINT handler */
282 static int newenv(int f);
283 static void quitenv(void);
284 static void err(char *s);
285 static int anys(char *s1, char *s2);
286 static int any(int c, char *s);
287 static void next(int f);
288 static void setdash(void);
289 static void onecommand(void);
290 static void runtrap(int i);
291 static int gmatch(char *s, char *p);
297 static void leave(void); /* abort shell (or fail in subshell) */
298 static void fail(void); /* fail but return to process next command */
299 static void warn(char *s);
300 static void sig(int i); /* default signal handler */
304 /* -------- area stuff -------- */
306 #define REGSIZE sizeof(struct region)
308 /* #define SHRINKBY (64) */
312 #define ALIGN (sizeof(int)-1)
322 /* -------- grammar stuff -------- */
347 /* Added for "." file expansion */
350 #define YYERRCODE 300
353 #define CONTIN 01 /* skip new lines to complete command */
355 #define SYNTAXERR zzerr()
357 static struct op *pipeline(int cf);
358 static struct op *andor(void);
359 static struct op *c_list(void);
360 static int synio(int cf);
361 static void musthave(int c, int cf);
362 static struct op *simple(void);
363 static struct op *nested(int type, int mark);
364 static struct op *command(int cf);
365 static struct op *dogroup(int onlydone);
366 static struct op *thenpart(void);
367 static struct op *elsepart(void);
368 static struct op *caselist(void);
369 static struct op *casepart(void);
370 static char **pattern(void);
371 static char **wordlist(void);
372 static struct op *list(struct op *t1, struct op *t2);
373 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
374 static struct op *newtp(void);
375 static struct op *namelist(struct op *t);
376 static char **copyw(void);
377 static void word(char *cp);
378 static struct ioword **copyio(void);
379 static struct ioword *io(int u, int f, char *cp);
380 static void zzerr(void);
381 static void yyerror(char *s);
382 static int yylex(int cf);
383 static int collect(int c, int c1);
384 static int dual(int c);
385 static void diag(int ec);
386 static char *tree(unsigned size);
388 /* -------- var.h -------- */
397 #define COPYV 1 /* flag to setval, suggesting copy */
398 #define RONLY 01 /* variable is read-only */
399 #define EXPORT 02 /* variable is to be exported */
400 #define GETCELL 04 /* name & value space was got with getcell */
402 static int yyparse(void);
403 static struct var *lookup(char *n);
404 static void setval(struct var *vp, char *val);
405 static void nameval(struct var *vp, char *val, char *name);
406 static void export(struct var *vp);
407 static void ronly(struct var *vp);
408 static int isassign(char *s);
409 static int checkname(char *cp);
410 static int assign(char *s, int cf);
411 static void putvlist(int f, int out);
412 static int eqname(char *n1, char *n2);
414 static int execute(struct op *t, int *pin, int *pout, int act);
417 /* -------- io.h -------- */
420 unsigned id; /* buffer id */
421 char buf[512]; /* buffer */
422 char *bufp; /* pointer into buffer */
423 char *ebufp; /* pointer to end of buffer */
426 /* possible arguments to an IO function */
430 int afile; /* file descriptor */
431 unsigned afid; /* buffer id */
432 long afpos; /* file position */
433 struct iobuf *afbuf; /* buffer for this file */
436 //static struct ioarg ioargstack[NPUSH];
437 #define AFID_NOBUF (~0)
440 /* an input generator's state */
442 int (*iofn) (struct ioarg *, struct io *);
445 char prev; /* previous character read by readc() */
446 char nlcount; /* for `'s */
447 char xchar; /* for `'s */
448 char task; /* reason for pushed IO */
451 //static struct io iostack[NPUSH];
452 #define XOTHER 0 /* none of the below */
453 #define XDOLL 1 /* expanding ${} */
454 #define XGRAVE 2 /* expanding `'s */
455 #define XIO 3 /* file IO */
457 /* in substitution */
458 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
462 * input generators for IO structure
464 static int nlchar(struct ioarg *ap);
465 static int strchar(struct ioarg *ap);
466 static int qstrchar(struct ioarg *ap);
467 static int filechar(struct ioarg *ap);
468 static int herechar(struct ioarg *ap);
469 static int linechar(struct ioarg *ap);
470 static int gravechar(struct ioarg *ap, struct io *iop);
471 static int qgravechar(struct ioarg *ap, struct io *iop);
472 static int dolchar(struct ioarg *ap);
473 static int wdchar(struct ioarg *ap);
474 static void scraphere(void);
475 static void freehere(int area);
476 static void gethere(void);
477 static void markhere(char *s, struct ioword *iop);
478 static int herein(char *hname, int xdoll);
479 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
485 static int eofc(void);
486 static int readc(void);
487 static void unget(int c);
488 static void ioecho(char c);
489 static void prs(const char *s);
490 static void prn(unsigned u);
491 static void closef(int i);
492 static void closeall(void);
498 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
499 static int remap(int fd);
500 static int openpipe(int *pv);
501 static void closepipe(int *pv);
502 static struct io *setbase(struct io *ip);
504 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)),pushio(&temparg,(gen)))
505 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
507 /* -------- word.h -------- */
509 #define NSTART 16 /* default number of words to allow for initially */
514 /* bounds are arbitrary */
518 static struct wdblock *addword(char *wd, struct wdblock *wb);
519 static struct wdblock *newword(int nw);
520 static char **getwords(struct wdblock *wb);
522 /* -------- area.h -------- */
527 static char *getcell(unsigned nbytes);
528 static void garbage(void);
529 static void setarea(char *cp, int a);
530 static int getarea(char *cp);
531 static void freearea(int a);
532 static void freecell(char *cp);
533 static int areanum; /* current allocation area */
535 #define NEW(type) (type *)getcell(sizeof(type))
536 #define DELETE(obj) freecell((char *)obj)
539 /* -------- misc stuff -------- */
541 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
542 static int iosetup(struct ioword *iop, int pipein, int pipeout);
543 static void echo(char **wp);
544 static struct op **find1case(struct op *t, char *w);
545 static struct op *findcase(struct op *t, char *w);
546 static void brkset(struct brkcon *bc);
547 static int dolabel(struct op *t);
548 static int dohelp(struct op *t);
549 static int dochdir(struct op *t);
550 static int doshift(struct op *t);
551 static int dologin(struct op *t);
552 static int doumask(struct op *t);
553 static int doexec(struct op *t);
554 static int dodot(struct op *t);
555 static int dowait(struct op *t);
556 static int doread(struct op *t);
557 static int doeval(struct op *t);
558 static int dotrap(struct op *t);
559 static int getsig(char *s);
560 static void setsig(int n, sighandler_t f);
561 static int getn(char *as);
562 static int dobreak(struct op *t);
563 static int docontinue(struct op *t);
564 static int brkcontin(char *cp, int val);
565 static int doexit(struct op *t);
566 static int doexport(struct op *t);
567 static int doreadonly(struct op *t);
568 static void rdexp(char **wp, void (*f) (struct var *), int key);
569 static void badid(char *s);
570 static int doset(struct op *t);
571 static void varput(char *s, int out);
572 static int dotimes(struct op *t);
573 static int expand(char *cp, struct wdblock **wbp, int f);
574 static char *blank(int f);
575 static int dollar(int quoted);
576 static int grave(int quoted);
577 static void globname(char *we, char *pp);
578 static char *generate(char *start1, char *end1, char *middle, char *end);
579 static int anyspcl(struct wdblock *wb);
580 static int xstrcmp(char *p1, char *p2);
581 static void glob0(char *a0, unsigned int a1, int a2,
582 int (*a3) (char *, char *));
583 static void glob1(char *base, char *lim);
584 static void glob2(char *i, char *j);
585 static void glob3(char *i, char *j, char *k);
586 static void readhere(char **name, char *s, int ec);
587 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
588 static int xxchar(struct ioarg *ap);
593 struct ioword *h_iop;
597 static const char * const signame[] = {
600 (char *) NULL, /* interrupt */
602 "Illegal instruction",
606 "Floating Point Exception",
611 (char *) NULL, /* broken pipe */
616 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
622 static const struct res restab[] = {
648 int (*builtinfunc) (struct op * t);
650 static const struct builtincmd builtincmds[] = {
655 {"continue", docontinue},
659 {"export", doexport},
664 {"readonly", doreadonly},
674 static struct op *scantree(struct op *);
675 static struct op *dowholefile(int, int);
678 extern char **environ; /* environment pointer */
684 static int interactive; /* Is this an interactive shell */
686 static int multiline; /* \n changed to ; */
687 static struct op *outtree; /* result from parser */
690 static struct brkcon *brklist;
692 static struct wdblock *wdlist;
693 static struct wdblock *iolist;
694 static char *trap[_NSIG + 1];
695 static char ourtrap[_NSIG + 1];
696 static int trapset; /* trap pending */
697 static int yynerrs; /* yacc */
698 static char line[LINELIM];
701 static struct var *mshdbg_var;
703 static struct var *vlist; /* dictionary */
704 static struct var *homedir; /* home directory */
705 static struct var *prompt; /* main prompt */
706 static struct var *cprompt; /* continuation prompt */
707 static struct var *path; /* search path for commands */
708 static struct var *shell; /* shell to interpret command files */
709 static struct var *ifs; /* field separators */
711 static int areanum; /* current allocation area */
714 static char *null = "";
715 static int heedint = 1;
716 static void (*qflag) (int) = SIG_IGN;
720 static int iounit = IODEFAULT;
721 static YYSTYPE yylval;
722 static char *elinep = line + sizeof(line) - 5;
724 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
725 static struct ioarg ioargstack[NPUSH];
726 static struct io iostack[NPUSH];
727 static struct iobuf sharedbuf = { AFID_NOBUF };
728 static struct iobuf mainbuf = { AFID_NOBUF };
729 static unsigned bufid = AFID_ID; /* buffer id counter */
731 static struct here *inhere; /* list of hear docs while parsing */
732 static struct here *acthere; /* list of active here documents */
733 static struct region *areabot; /* bottom of area */
734 static struct region *areatop; /* top of area */
735 static struct region *areanxt; /* starting point of scan */
737 static void *brkaddr;
739 static struct env e = {
740 line, /* linep: char ptr */
741 iostack, /* iobase: struct io ptr */
742 iostack - 1, /* iop: struct io ptr */
743 (xint *) NULL, /* errpt: void ptr for errors? */
744 FDBASE, /* iofd: file desc */
745 (struct env *) NULL /* oenv: struct env ptr */
749 void print_t(struct op *t);
750 void print_t(struct op *t)
752 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
753 T_CMD_NAMES[t->type], t->words, t->ioact));
756 DBGPRINTF(("T: W1: %s", t->words[0]));
762 void print_tree(struct op *head);
763 void print_tree(struct op *head)
766 DBGPRINTF(("PRINT_TREE: no tree\n"));
770 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
774 print_tree(head->left);
777 print_tree(head->right);
781 #endif /* MSHDEBUG */
784 #ifdef CONFIG_FEATURE_COMMAND_EDITING
785 static char *current_prompt;
788 /* -------- sh.c -------- */
794 int msh_main(int argc, char **argv)
800 int (*iof) (struct ioarg *);
802 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
805 if ((ap = environ) != NULL) {
807 assign(*ap++, !COPYV);
808 for (ap = environ; *ap;)
809 export(lookup(*ap++));
814 shell = lookup("SHELL");
815 if (shell->value == null)
816 setval(shell, (char *)DEFAULT_SHELL);
819 homedir = lookup("HOME");
820 if (homedir->value == null)
821 setval(homedir, "/");
824 setval(lookup("$"), putn(getpid()));
826 path = lookup("PATH");
827 if (path->value == null) {
829 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
831 setval(path, "/bin:/usr/bin");
836 if (ifs->value == null)
837 setval(ifs, " \t\n");
840 mshdbg_var = lookup("MSHDEBUG");
841 if (mshdbg_var->value == null)
842 setval(mshdbg_var, "0");
845 prompt = lookup("PS1");
846 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
847 if (prompt->value == null)
849 setval(prompt, DEFAULT_USER_PROMPT);
850 if (geteuid() == 0) {
851 setval(prompt, DEFAULT_ROOT_PROMPT);
852 prompt->status &= ~EXPORT;
854 cprompt = lookup("PS2");
855 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
856 if (cprompt->value == null)
858 setval(cprompt, "> ");
864 if (argv[0][0] == '-' && argv[0][1] != '\0') {
865 for (s = argv[0] + 1; *s; s++)
868 prompt->status &= ~EXPORT;
869 cprompt->status &= ~EXPORT;
874 PUSHIO(aword, *++argv, iof = nlchar);
886 prompt->status &= ~EXPORT;
894 if (*s >= 'a' && *s <= 'z')
902 if (iof == filechar && --argc > 0) {
905 prompt->status &= ~EXPORT;
906 cprompt->status &= ~EXPORT;
908 /* Shell is non-interactive, activate printf-based debug */
910 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
914 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
916 if (newfile(name = *++argv))
917 exit(1); /* Exit on error */
923 /* This won't be true if PUSHIO has been called, say from newfile() above */
924 if (e.iop < iostack) {
925 PUSHIO(afile, 0, iof);
926 if (isatty(0) && isatty(1) && !cflag) {
928 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
930 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
932 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
934 printf("Enter 'help' for a list of built-in commands.\n\n");
939 signal(SIGQUIT, qflag);
940 if (name && name[0] == '-') {
942 if ((f = open(".profile", 0)) >= 0)
944 if ((f = open("/etc/profile", 0)) >= 0)
948 signal(SIGTERM, sig);
950 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
951 signal(SIGINT, onintr);
956 for (ap = ++argv; --argc > 0;) {
957 if (assign(*ap = *argv++, !COPYV)) {
958 dolc--; /* keyword */
964 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
966 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
969 if (interactive && e.iop <= iostack) {
970 #ifdef CONFIG_FEATURE_COMMAND_EDITING
971 current_prompt = prompt->value;
977 /* Ensure that getenv("PATH") stays current */
978 setenv("PATH", path->value, 1);
981 DBGPRINTF(("MSH_MAIN: returning.\n"));
984 static void setdash(void)
988 char m['z' - 'a' + 1];
991 for (c = 'a'; c <= 'z'; c++)
995 setval(lookup("-"), m);
998 static int newfile(char *s)
1002 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1004 if (strcmp(s, "-") != 0) {
1005 DBGPRINTF(("NEWFILE: s is %s\n", s));
1009 err(": cannot open");
1020 struct op *scantree(struct op *head)
1027 if (head->left != NULL) {
1028 dotnode = scantree(head->left);
1033 if (head->right != NULL) {
1034 dotnode = scantree(head->right);
1039 if (head->words == NULL)
1042 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1044 if ((head->type != TDOT) && (strcmp(".", head->words[0]) == 0)) {
1045 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1053 static void onecommand(void)
1058 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1077 setjmp(failpt = m1); /* Bruce Evans' fix */
1078 if (setjmp(failpt = m1) || yyparse() || intr) {
1080 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1085 if (!interactive && intr)
1098 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1100 execute(outtree, NOPIPE, NOPIPE, 0);
1103 if (!interactive && intr) {
1108 if ((i = trapset) != 0) {
1114 static void fail(void)
1120 static void leave(void)
1122 DBGPRINTF(("LEAVE: leave called!\n"));
1133 static void warn(char *s)
1144 static void err(char *s)
1152 longjmp(e.errpt, 1);
1154 e.iop = e.iobase = iostack;
1157 static int newenv(int f)
1161 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1168 ep = (struct env *) space(sizeof(*ep));
1181 static void quitenv(void)
1186 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1188 if ((ep = e.oenv) != NULL) {
1191 /* should close `'d files */
1193 while (--fd >= e.iofd)
1199 * Is any character from s1 in s2?
1201 static int anys(char *s1, char *s2)
1210 * Is character c in s?
1212 static int any(int c, char *s)
1220 static char *putn(int n)
1225 static void next(int f)
1227 PUSHIO(afile, f, filechar);
1230 static void onintr(int s) /* ANSI C requires a parameter */
1232 signal(SIGINT, onintr);
1239 } else if (heedint) {
1245 static char *space(int n)
1249 if ((cp = getcell(n)) == 0)
1250 err("out of string space");
1254 static char *strsave(char *s, int a)
1258 if ((cp = space(strlen(s) + 1)) != NULL) {
1259 setarea((char *) cp, a);
1260 for (xp = cp; (*xp++ = *s++) != '\0';);
1269 static void sig(int i)
1275 static void runtrap(int i)
1279 if ((trapstr = trap[i]) == NULL)
1285 RUN(aword, trapstr, nlchar);
1288 /* -------- var.c -------- */
1291 * Find the given name in the dictionary
1292 * and return its value. If the name was
1293 * not previously there, enter it now and
1294 * return a null value.
1296 static struct var *lookup(char *n)
1301 static struct var dummy;
1305 for (c = 0; isdigit(*n) && c < 1000; n++)
1306 c = c * 10 + *n - '0';
1307 dummy.status = RONLY;
1308 dummy.value = c <= dolc ? dolv[c] : null;
1311 for (vp = vlist; vp; vp = vp->next)
1312 if (eqname(vp->name, n))
1315 vp = (struct var *) space(sizeof(*vp));
1316 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1317 dummy.name = dummy.value = "";
1320 for (cp = vp->name; (*cp = *n++) && *cp != '='; cp++);
1324 setarea((char *) vp, 0);
1325 setarea((char *) vp->name, 0);
1328 vp->status = GETCELL;
1334 * give variable at `vp' the value `val'.
1336 static void setval(struct var *vp, char *val)
1338 nameval(vp, val, (char *) NULL);
1342 * if name is not NULL, it must be
1343 * a prefix of the space `val',
1345 * this is all so that exporting
1346 * values is reasonably painless.
1348 static void nameval(struct var *vp, char *val, char *name)
1354 if (vp->status & RONLY) {
1355 for (xp = vp->name; *xp && *xp != '=';)
1356 putc(*xp++, stderr);
1357 err(" is read-only");
1362 xp = space(strlen(vp->name) + strlen(val) + 2);
1365 /* make string: name=value */
1366 setarea((char *) xp, 0);
1368 for (cp = vp->name; (*xp = *cp++) && *xp != '='; xp++);
1372 for (cp = val; (*xp++ = *cp++) != '\0';);
1376 if (vp->status & GETCELL)
1377 freecell(vp->name); /* form new string `name=value' */
1383 static void export(struct var *vp)
1385 vp->status |= EXPORT;
1388 static void ronly(struct var *vp)
1390 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1391 vp->status |= RONLY;
1394 static int isassign(char *s)
1396 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1398 if (!isalpha((int) *s) && *s != '_')
1400 for (; *s != '='; s++)
1401 if (*s == 0 || (!isalnum(*s) && *s != '_'))
1407 static int assign(char *s, int cf)
1412 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1414 if (!isalpha(*s) && *s != '_')
1416 for (cp = s; *cp != '='; cp++)
1417 if (*cp == 0 || (!isalnum(*cp) && *cp != '_'))
1420 nameval(vp, ++cp, cf == COPYV ? (char *) NULL : s);
1422 vp->status &= ~GETCELL;
1426 static int checkname(char *cp)
1428 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1430 if (!isalpha(*cp++) && *(cp - 1) != '_')
1433 if (!isalnum(*cp++) && *(cp - 1) != '_')
1438 static void putvlist(int f, int out)
1442 for (vp = vlist; vp; vp = vp->next)
1443 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1444 if (vp->status & EXPORT)
1445 write(out, "export ", 7);
1446 if (vp->status & RONLY)
1447 write(out, "readonly ", 9);
1448 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1449 write(out, "\n", 1);
1453 static int eqname(char *n1, char *n2)
1455 for (; *n1 != '=' && *n1 != 0; n1++)
1458 return (*n2 == 0 || *n2 == '=');
1461 static char *findeq(char *cp)
1463 while (*cp != '\0' && *cp != '=')
1468 /* -------- gmatch.c -------- */
1470 * int gmatch(string, pattern)
1471 * char *string, *pattern;
1473 * Match a pattern as in sh(1).
1478 #define QMASK (CMASK&~QUOTE)
1479 #define NOT '!' /* might use ^ */
1481 static int gmatch(char *s, char *p)
1485 if (s == NULL || p == NULL)
1487 while ((pc = *p++ & CMASK) != '\0') {
1491 if ((p = cclass(p, sc)) == NULL)
1503 if (*p == '\0' || gmatch(s, p))
1505 } while (*s++ != '\0');
1509 if (sc != (pc & ~QUOTE))
1516 static char *cclass(char *p, int sub)
1518 int c, d, not, found;
1520 if ((not = *p == NOT) != 0)
1525 return ((char *) NULL);
1527 if (p[1] == '-' && p[2] != ']') {
1532 if (c == sub || (c <= sub && sub <= d))
1534 } while (*++p != ']');
1535 return (found ? p + 1 : (char *) NULL);
1539 /* -------- area.c -------- */
1542 * All memory between (char *)areabot and (char *)(areatop+1) is
1543 * exclusively administered by the area management routines.
1544 * It is assumed that sbrk() and brk() manipulate the high end.
1547 #define sbrk(X) ({ void * __q = (void *)-1; if (brkaddr + (int)(X) < brktop) { __q = brkaddr; brkaddr+=(int)(X); } __q;})
1549 static void initarea(void)
1551 brkaddr = xmalloc(AREASIZE);
1552 brktop = brkaddr + AREASIZE;
1554 while ((long) sbrk(0) & ALIGN)
1556 areabot = (struct region *) sbrk(REGSIZE);
1558 areabot->next = areabot;
1559 areabot->area = BUSY;
1564 char *getcell(unsigned nbytes)
1567 struct region *p, *q;
1574 /* silly and defeats the algorithm */
1576 * round upwards and add administration area
1578 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
1579 for (p = areanxt;;) {
1580 if (p->area > areanum) {
1584 while ((q = p->next)->area > areanum && q != areanxt)
1587 * exit loop if cell big enough
1589 if (q >= p + nregio)
1596 i = nregio >= GROWBY ? nregio : GROWBY;
1597 p = (struct region *) sbrk(i * REGSIZE);
1598 if (p == (struct region *) -1)
1599 return ((char *) NULL);
1603 abort(); /* allocated areas are contiguous */
1613 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
1615 areanxt = p + nregio;
1618 * split into requested area and rest
1620 if (areanxt + 1 > q) {
1622 abort(); /* insufficient space left for admin */
1625 areanxt->area = FREE;
1629 return ((char *) (p + 1));
1632 static void freecell(char *cp)
1636 if ((p = (struct region *) cp) != NULL) {
1644 static void freearea(int a)
1646 struct region *p, *top;
1649 for (p = areabot; p != top; p = p->next)
1654 static void setarea(char *cp, int a)
1658 if ((p = (struct region *) cp) != NULL)
1662 int getarea(char *cp)
1664 return ((struct region *) cp - 1)->area;
1667 static void garbage(void)
1669 struct region *p, *q, *top;
1672 for (p = areabot; p != top; p = p->next) {
1673 if (p->area > areanum) {
1674 while ((q = p->next)->area > areanum)
1680 if (areatop >= q + SHRINKBY && q->area > areanum) {
1681 brk((char *) (q + 1));
1689 /* -------- csyn.c -------- */
1691 * shell: syntax (C version)
1696 DBGPRINTF7(("YYPARSE: enter...\n"));
1703 return (yynerrs != 0);
1706 static struct op *pipeline(int cf)
1711 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1715 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1718 while ((c = yylex(0)) == '|') {
1719 if ((p = command(CONTIN)) == NULL) {
1720 DBGPRINTF8(("PIPELINE: error!\n"));
1724 if (t->type != TPAREN && t->type != TCOM) {
1725 /* shell statement */
1726 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1729 t = block(TPIPE, t, p, NOWORDS);
1734 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1738 static struct op *andor(void)
1743 DBGPRINTF7(("ANDOR: enter...\n"));
1747 DBGPRINTF9(("ANDOR: t=%p\n", t));
1750 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1751 if ((p = pipeline(CONTIN)) == NULL) {
1752 DBGPRINTF8(("ANDOR: error!\n"));
1756 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1762 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1766 static struct op *c_list(void)
1771 DBGPRINTF7(("C_LIST: enter...\n"));
1776 if ((peeksym = yylex(0)) == '&')
1777 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1779 while ((c = yylex(0)) == ';' || c == '&'
1780 || (multiline && c == '\n')) {
1782 if ((p = andor()) == NULL)
1785 if ((peeksym = yylex(0)) == '&')
1786 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1794 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1798 static int synio(int cf)
1804 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1806 if ((c = yylex(cf)) != '<' && c != '>') {
1813 iop = io(iounit, i, yylval.cp);
1817 markhere(yylval.cp, iop);
1819 DBGPRINTF7(("SYNIO: returning 1\n"));
1823 static void musthave(int c, int cf)
1825 if ((peeksym = yylex(cf)) != c) {
1826 DBGPRINTF7(("MUSTHAVE: error!\n"));
1833 static struct op *simple(void)
1839 switch (peeksym = yylex(0)) {
1860 static struct op *nested(int type, int mark)
1864 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1870 return (block(type, t, NOBLOCK, NOWORDS));
1873 static struct op *command(int cf)
1876 struct wdblock *iosave;
1879 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1895 if ((t = simple()) == NULL) {
1897 return ((struct op *) NULL);
1904 t = nested(TPAREN, ')');
1908 t = nested(TBRACE, '}');
1918 t->words = wordlist();
1919 if ((c = yylex(0)) != '\n' && c != ';')
1921 t->left = dogroup(0);
1929 t->type = c == WHILE ? TWHILE : TUNTIL;
1931 t->right = dogroup(1);
1943 musthave(IN, CONTIN);
1946 t->left = caselist();
1957 t->right = thenpart();
1966 musthave(WORD, 0); /* gets name of file */
1967 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1969 word(yylval.cp); /* add word to wdlist */
1970 word(NOWORD); /* terminate wdlist */
1971 t->words = copyw(); /* dup wdlist */
1981 DBGPRINTF(("COMMAND: returning %p\n", t));
1986 static struct op *dowholefile(int type, int mark)
1990 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1995 t = block(type, t, NOBLOCK, NOWORDS);
1996 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
2000 static struct op *dogroup(int onlydone)
2006 if (c == DONE && onlydone)
2007 return ((struct op *) NULL);
2015 static struct op *thenpart(void)
2020 if ((c = yylex(0)) != THEN) {
2022 return ((struct op *) NULL);
2027 if (t->left == NULL)
2029 t->right = elsepart();
2033 static struct op *elsepart(void)
2038 switch (c = yylex(0)) {
2040 if ((t = c_list()) == NULL)
2048 t->right = thenpart();
2053 return ((struct op *) NULL);
2057 static struct op *caselist(void)
2062 while ((peeksym = yylex(CONTIN)) != ESAC) {
2063 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
2064 t = list(t, casepart());
2067 DBGPRINTF(("CASELIST, returning t=%p\n", t));
2071 static struct op *casepart(void)
2075 DBGPRINTF7(("CASEPART: enter...\n"));
2079 t->words = pattern();
2082 if ((peeksym = yylex(CONTIN)) != ESAC)
2083 musthave(BREAK, CONTIN);
2085 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2090 static char **pattern(void)
2099 } while ((c = yylex(0)) == '|');
2106 static char **wordlist(void)
2110 if ((c = yylex(0)) != IN) {
2112 return ((char **) NULL);
2115 while ((c = yylex(0)) == WORD)
2123 * supporting functions
2125 static struct op *list(struct op *t1, struct op *t2)
2127 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2134 return (block(TLIST, t1, t2, NOWORDS));
2137 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2141 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2149 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2155 /* See if given string is a shell multiline (FOR, IF, etc) */
2156 static int rlookup(char *n)
2158 const struct res *rp;
2160 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2162 for (rp = restab; rp->r_name; rp++)
2163 if (strcmp(rp->r_name, n) == 0) {
2164 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2165 return (rp->r_val); /* Return numeric code for shell multiline */
2168 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2169 return (0); /* Not a shell multiline */
2172 static struct op *newtp(void)
2176 t = (struct op *) tree(sizeof(*t));
2184 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2189 static struct op *namelist(struct op *t)
2192 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2193 T_CMD_NAMES[t->type], iolist));
2196 iolist = addword((char *) NULL, iolist);
2197 t->ioact = copyio();
2201 if (t->type != TCOM) {
2202 if (t->type != TPAREN && t->ioact != NULL) {
2203 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2204 t->ioact = t->left->ioact;
2205 t->left->ioact = NULL;
2217 static char **copyw(void)
2221 wd = getwords(wdlist);
2226 static void word(char *cp)
2228 wdlist = addword(cp, wdlist);
2231 static struct ioword **copyio(void)
2233 struct ioword **iop;
2235 iop = (struct ioword **) getwords(iolist);
2240 static struct ioword *io(int u, int f, char *cp)
2244 iop = (struct ioword *) tree(sizeof(*iop));
2248 iolist = addword((char *) iop, iolist);
2252 static void zzerr(void)
2254 yyerror("syntax error");
2257 static void yyerror(char *s)
2260 if (interactive && e.iop <= iostack) {
2262 while (eofc() == 0 && yylex(0) != '\n');
2268 static int yylex(int cf)
2273 if ((c = peeksym) > 0) {
2288 line[LINELIM - 1] = '\0';
2291 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2296 if (any(c, "0123456789")) {
2297 unget(c1 = my_getc(0));
2298 if (c1 == '<' || c1 == '>') {
2307 case '#': /* Comment, skip to next newline or End-of-string */
2308 while ((c = my_getc(0)) != 0 && c != '\n');
2313 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2317 DBGPRINTF9(("YYLEX: found $\n"));
2319 if ((c = my_getc(0)) == '{') {
2320 if ((c = collect(c, '}')) != '\0')
2329 if ((c = collect(c, c)) != '\0')
2337 /* If more chars process them, else return NULL char */
2338 if ((c1 = dual(c)) != '\0')
2355 if (multiline || cf & CONTIN) {
2356 if (interactive && e.iop <= iostack) {
2357 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2358 current_prompt = cprompt->value;
2360 prs(cprompt->value);
2377 while ((c = my_getc(0)) != 0 && !any(c, "`$ '\"\t;&<>()|^\n")) {
2378 if (e.linep >= elinep)
2379 err("word too long");
2386 if (any(c, "\"'`$"))
2391 if (atstart && (c = rlookup(line)) != 0) {
2396 yylval.cp = strsave(line, areanum);
2401 static int collect(int c, int c1)
2405 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2408 while ((c = my_getc(c1)) != c1) {
2417 if (interactive && c == '\n' && e.iop <= iostack) {
2418 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2419 current_prompt = cprompt->value;
2421 prs(cprompt->value);
2429 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2434 /* "multiline commands" helper func */
2435 /* see if next 2 chars form a shell multiline */
2436 static int dual(int c)
2441 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2443 *cp++ = c; /* c is the given "peek" char */
2444 *cp++ = my_getc(0); /* get next char of input */
2445 *cp = 0; /* add EOS marker */
2447 c = rlookup(s); /* see if 2 chars form a shell multiline */
2449 unget(*--cp); /* String is not a shell multiline, put peek char back */
2451 return (c); /* String is multiline, return numeric multiline (restab) code */
2454 static void diag(int ec)
2458 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2461 if (c == '>' || c == '<') {
2464 yylval.i = ec == '>' ? IOWRITE | IOCAT : IOHERE;
2467 yylval.i = ec == '>' ? IOWRITE : IOREAD;
2468 if (c != '&' || yylval.i == IOHERE)
2474 static char *tree(unsigned size)
2478 if ((t = getcell(size)) == NULL) {
2479 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2480 prs("command line too complicated\n");
2490 /* -------- exec.c -------- */
2497 static int execute(struct op *t, int *pin, int *pout, int act)
2500 volatile int i, rv, a;
2501 char *cp, **wp, **wp2;
2503 struct op *outtree_save;
2507 /* Avoid longjmp clobbering */
2512 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2516 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2517 t->type, T_CMD_NAMES[t->type],
2518 ((t->words == NULL) ? "NULL" : t->words[0])));
2522 wp = (wp2 = t->words) != NULL
2523 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2528 DBGPRINTF3(("EXECUTE: TDOT\n"));
2530 outtree_save = outtree;
2532 newfile(evalstr(t->words[0], DOALL));
2534 t->left = dowholefile(TLIST, 0);
2537 outtree = outtree_save;
2540 rv = execute(t->left, pin, pout, 0);
2542 rv = execute(t->right, pin, pout, 0);
2546 rv = execute(t->left, pin, pout, 0);
2551 rv = forkexec(t, pin, pout, act, wp);
2559 if ((rv = openpipe(pv)) < 0)
2561 pv[0] = remap(pv[0]);
2562 pv[1] = remap(pv[1]);
2563 (void) execute(t->left, pin, pv, 0);
2564 rv = execute(t->right, pv, pout, 0);
2569 (void) execute(t->left, pin, pout, 0);
2570 rv = execute(t->right, pin, pout, 0);
2575 int hinteractive = interactive;
2577 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2581 interactive = hinteractive;
2583 setval(lookup("!"), putn(i));
2594 signal(SIGINT, SIG_IGN);
2595 signal(SIGQUIT, SIG_IGN);
2597 signal(SIGTERM, SIG_DFL);
2601 open(bb_dev_null, 0);
2603 _exit(execute(t->left, pin, pout, FEXEC));
2610 rv = execute(t->left, pin, pout, 0);
2611 if ((t1 = t->right) != NULL && (rv == 0) == (t->type == TAND))
2612 rv = execute(t1, pin, pout, 0);
2622 while (*wp++ != NULL);
2624 vp = lookup(t->str);
2625 while (setjmp(bc.brkpt))
2629 for (t1 = t->left; i-- && *wp != NULL;) {
2631 rv = execute(t1, pin, pout, 0);
2633 brklist = brklist->nextlev;
2638 while (setjmp(bc.brkpt))
2643 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2644 rv = execute(t->right, pin, pout, 0);
2645 brklist = brklist->nextlev;
2650 if (t->right != NULL) {
2651 rv = !execute(t->left, pin, pout, 0) ?
2652 execute(t->right->left, pin, pout, 0) :
2653 execute(t->right->right, pin, pout, 0);
2658 if ((cp = evalstr(t->str, DOSUB | DOTRIM)) == 0)
2661 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2662 ((t->str == NULL) ? "NULL" : t->str),
2663 ((cp == NULL) ? "NULL" : cp)));
2665 if ((t1 = findcase(t->left, cp)) != NULL) {
2666 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2667 rv = execute(t1, pin, pout, 0);
2668 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2674 if (iopp = t->ioact)
2676 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2681 if (rv >= 0 && (t1 = t->left))
2682 rv = execute(t1, pin, pout, 0);
2693 if (interactive && intr) {
2698 if ((i = trapset) != 0) {
2703 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2708 forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2712 int (*shcom) (struct op *) = NULL;
2715 struct ioword **iopp;
2725 struct brkcon *hbrklist;
2729 /* Avoid longjmp clobbering */
2739 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2741 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2742 ((t->words == NULL) ? "NULL" : t->words[0])));
2746 rv = -1; /* system-detected error */
2747 if (t->type == TCOM) {
2748 while ((cp = *wp++) != NULL);
2751 /* strip all initial assignments */
2752 /* not correct wrt PATH=yyy command etc */
2754 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2756 echo(cp ? wp : owp);
2759 if (cp == NULL && t->ioact == NULL) {
2760 while ((cp = *owp++) != NULL && assign(cp, COPYV));
2761 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2762 return (setstatus(0));
2763 } else if (cp != NULL) {
2764 shcom = inbuilt(cp);
2771 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2774 if (shcom == NULL && (f & FEXEC) == 0) {
2775 /* Save values in case the child process alters them */
2779 hinteractive = interactive;
2784 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2789 DBGPRINTF(("FORKEXEC: ERROR, unable to vfork()!\n"));
2794 if (newpid > 0) { /* Parent */
2796 /* Restore values */
2800 interactive = hinteractive;
2813 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2816 /* Must be the child process, pid should be 0 */
2817 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2820 signal(SIGINT, SIG_IGN);
2821 signal(SIGQUIT, SIG_IGN);
2833 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2838 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2839 err("piping to/from shell builtins not yet done");
2855 if ((iopp = t->ioact) != NULL) {
2856 if (shcom != NULL && shcom != doexec) {
2858 err(": cannot redirect shell command");
2864 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2872 i = setstatus((*shcom) (t));
2875 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2879 /* should use FIOCEXCL */
2880 for (i = FDBASE; i < NOFILE; i++)
2883 signal(SIGINT, SIG_DFL);
2884 signal(SIGQUIT, SIG_DFL);
2887 if (t->type == TPAREN)
2888 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2892 cp = rexecve(wp[0], wp, makenv(0, NULL));
2899 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2907 * 0< 1> are ignored as required
2910 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2913 char *cp = NULL, *msg;
2915 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2918 if (iop->io_unit == IODEFAULT) /* take default */
2919 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2921 if (pipein && iop->io_unit == 0)
2924 if (pipeout && iop->io_unit == 1)
2927 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2928 if ((iop->io_flag & IOHERE) == 0) {
2930 if ((cp = evalstr(cp, DOSUB | DOTRIM)) == NULL)
2934 if (iop->io_flag & IODUP) {
2935 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2937 err(": illegal >& argument");
2941 iop->io_flag = IOCLOSE;
2942 iop->io_flag &= ~(IOREAD | IOWRITE);
2944 switch (iop->io_flag) {
2950 case IOHERE | IOXHERE:
2951 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2955 case IOWRITE | IOCAT:
2956 if ((u = open(cp, 1)) >= 0) {
2957 lseek(u, (long) 0, SEEK_END);
2961 u = creat(cp, 0666);
2965 u = dup2(*cp - '0', iop->io_unit);
2969 close(iop->io_unit);
2978 if (u != iop->io_unit) {
2979 dup2(u, iop->io_unit);
2986 static void echo(char **wp)
2991 for (i = 0; wp[i]; i++) {
2999 static struct op **find1case(struct op *t, char *w)
3007 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
3008 return ((struct op **) NULL);
3011 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
3012 T_CMD_NAMES[t->type]));
3014 if (t->type == TLIST) {
3015 if ((tp = find1case(t->left, w)) != NULL) {
3016 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
3019 t1 = t->right; /* TPAT */
3023 for (wp = t1->words; *wp;)
3024 if ((cp = evalstr(*wp++, DOSUB)) && gmatch(w, cp)) {
3025 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
3030 DBGPRINTF(("FIND1CASE: returning NULL\n"));
3031 return ((struct op **) NULL);
3034 static struct op *findcase(struct op *t, char *w)
3038 return ((tp = find1case(t, w)) != NULL ? *tp : (struct op *) NULL);
3042 * Enter a new loop level (marked for break/continue).
3044 static void brkset(struct brkcon *bc)
3046 bc->nextlev = brklist;
3051 * Wait for the last process created.
3052 * Print a message for each process found
3053 * that was killed by a signal.
3054 * Ignore interrupt signals while waiting
3055 * unless `canintr' is true.
3057 static int waitfor(int lastpid, int canintr)
3061 int oheedint = heedint;
3068 if (errno != EINTR || canintr)
3071 if ((rv = WAITSIG(s)) != 0) {
3073 if (signame[rv] != NULL) {
3074 if (pid != lastpid) {
3081 if (pid != lastpid) {
3090 prs(" - core dumped");
3091 if (rv >= NSIGNAL || signame[rv])
3097 } while (pid != lastpid);
3112 static int setstatus(int s)
3115 setval(lookup("?"), putn(s));
3120 * PATH-searching interface to execve.
3121 * If getenv("PATH") were kept up-to-date,
3122 * execvp might be used.
3124 static char *rexecve(char *c, char **v, char **envp)
3128 int eacces = 0, asis = 0;
3131 if (ENABLE_FEATURE_SH_STANDALONE_SHELL) {
3133 if (find_applet_by_name(name)) {
3134 /* We have to exec here since we vforked. Running
3135 * run_applet_by_name() won't work and bad things
3137 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3141 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3143 sp = any('/', c) ? "" : path->value;
3145 while (asis || *sp != '\0') {
3148 for (; *sp != '\0'; tp++)
3149 if ((*tp = *sp++) == ':') {
3155 for (i = 0; (*tp++ = c[i++]) != '\0';);
3157 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3159 execve(e.linep, v, envp);
3166 execve(DEFAULT_SHELL, v, envp);
3168 return ("no Shell");
3171 return ((char *) bb_msg_memory_exhausted);
3174 return ("argument list too long");
3181 return (errno == ENOENT ? "not found" : "cannot execute");
3185 * Run the command produced by generator `f'
3186 * applied to stream `arg'.
3188 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3191 struct wdblock *swdlist;
3192 struct wdblock *siolist;
3198 /* Avoid longjmp clobbering */
3202 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3203 areanum, outtree, failpt));
3212 if (newenv(setjmp(errpt = ev)) == 0) {
3218 if (setjmp(failpt = rt) == 0 && yyparse() == 0)
3219 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3222 DBGPRINTF(("RUN: error from newenv()!\n"));
3229 freearea(areanum--);
3234 /* -------- do.c -------- */
3237 * built-in commands: doX
3240 static int dohelp(struct op *t)
3243 const struct builtincmd *x;
3245 printf("\nBuilt-in commands:\n");
3246 printf("-------------------\n");
3248 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3251 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3257 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3260 const struct BB_applet *applet;
3261 extern const struct BB_applet applets[];
3262 extern const size_t NUM_APPLETS;
3264 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3268 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3277 return EXIT_SUCCESS;
3282 static int dolabel(struct op *t)
3287 static int dochdir(struct op *t)
3291 if ((cp = t->words[1]) == NULL && (cp = homedir->value) == NULL)
3292 er = ": no home directory";
3293 else if (chdir(cp) < 0)
3294 er = ": bad directory";
3297 prs(cp != NULL ? cp : "cd");
3302 static int doshift(struct op *t)
3306 n = t->words[1] ? getn(t->words[1]) : 1;
3308 err("nothing to shift");
3314 setval(lookup("#"), putn(dolc));
3319 * execute login and newgrp directly
3321 static int dologin(struct op *t)
3326 signal(SIGINT, SIG_DFL);
3327 signal(SIGQUIT, SIG_DFL);
3329 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3336 static int doumask(struct op *t)
3341 if ((cp = t->words[1]) == NULL) {
3344 for (n = 3 * 4; (n -= 3) >= 0;)
3345 putc('0' + ((i >> n) & 07), stderr);
3348 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3349 n = n * 8 + (*cp - '0');
3355 static int doexec(struct op *t)
3362 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3367 if (setjmp(failpt = ex) == 0)
3368 execute(t, NOPIPE, NOPIPE, FEXEC);
3374 static int dodot(struct op *t)
3381 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)));
3383 if ((cp = t->words[1]) == NULL) {
3384 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3387 DBGPRINTF(("DODOT: cp is %s\n", cp));
3390 sp = any('/', cp) ? ":" : path->value;
3392 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3393 ((sp == NULL) ? "NULL" : sp),
3394 ((e.linep == NULL) ? "NULL" : e.linep)));
3398 while (*sp && (*tp = *sp++) != ':')
3403 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3406 if ((i = open(e.linep, 0)) >= 0) {
3409 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3411 next(maltmp); /* Basically a PUSHIO */
3413 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3426 static int dowait(struct op *t)
3431 if ((cp = t->words[1]) != NULL) {
3437 setstatus(waitfor(i, 1));
3441 static int doread(struct op *t)
3447 if (t->words[1] == NULL) {
3448 err("Usage: read name ...");
3451 for (wp = t->words + 1; *wp; wp++) {
3452 for (cp = e.linep; !nl && cp < elinep - 1; cp++)
3453 if ((nb = read(0, cp, sizeof(*cp))) != sizeof(*cp) ||
3454 (nl = (*cp == '\n')) || (wp[1] && any(*cp, ifs->value)))
3459 setval(lookup(*wp), e.linep);
3464 static int doeval(struct op *t)
3466 return (RUN(awordlist, t->words + 1, wdchar));
3469 static int dotrap(struct op *t)
3474 if (t->words[1] == NULL) {
3475 for (i = 0; i <= _NSIG; i++)
3484 resetsig = isdigit(*t->words[1]);
3485 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3486 n = getsig(t->words[i]);
3490 if (*t->words[1] != '\0') {
3491 trap[n] = strsave(t->words[1], 0);
3500 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3508 static int getsig(char *s)
3512 if ((n = getn(s)) < 0 || n > _NSIG) {
3513 err("trap: bad signal number");
3519 static void setsig(int n, sighandler_t f)
3523 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3529 static int getn(char *as)
3540 for (n = 0; isdigit(*s); s++)
3541 n = (n * 10) + (*s - '0');
3544 err(": bad number");
3549 static int dobreak(struct op *t)
3551 return (brkcontin(t->words[1], 1));
3554 static int docontinue(struct op *t)
3556 return (brkcontin(t->words[1], 0));
3559 static int brkcontin(char *cp, int val)
3564 nl = cp == NULL ? 1 : getn(cp);
3568 if ((bc = brklist) == NULL)
3570 brklist = bc->nextlev;
3573 err("bad break/continue level");
3577 longjmp(bc->brkpt, 1);
3581 static int doexit(struct op *t)
3586 if ((cp = t->words[1]) != NULL)
3587 setstatus(getn(cp));
3589 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3596 static int doexport(struct op *t)
3598 rdexp(t->words + 1, export, EXPORT);
3602 static int doreadonly(struct op *t)
3604 rdexp(t->words + 1, ronly, RONLY);
3608 static void rdexp(char **wp, void (*f) (struct var *), int key)
3610 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3611 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3614 for (; *wp != NULL; wp++) {
3615 if (isassign(*wp)) {
3619 for (cp = *wp; *cp != '='; cp++);
3631 static void badid(char *s)
3634 err(": bad identifier");
3637 static int doset(struct op *t)
3643 if ((cp = t->words[1]) == NULL) {
3644 for (vp = vlist; vp; vp = vp->next)
3645 varput(vp->name, 1);
3649 /* bad: t->words++; */
3650 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3652 flag['x'] = flag['v'] = 0;
3662 if (*cp >= 'a' && *cp <= 'z')
3669 t->words[0] = dolv[0];
3670 for (n = 1; t->words[n]; n++)
3671 setarea((char *) t->words[n], 0);
3674 setval(lookup("#"), putn(dolc));
3675 setarea((char *) (dolv - 1), 0);
3680 static void varput(char *s, int out)
3682 if (isalnum(*s) || *s == '_') {
3683 write(out, s, strlen(s));
3684 write(out, "\n", 1);
3690 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3691 * This file contains code for the times builtin.
3693 static int dotimes(struct op *t)
3696 long int clk_tck = sysconf(_SC_CLK_TCK);
3699 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3700 (int) (buf.tms_utime / clk_tck / 60),
3701 ((double) buf.tms_utime) / clk_tck,
3702 (int) (buf.tms_stime / clk_tck / 60),
3703 ((double) buf.tms_stime) / clk_tck,
3704 (int) (buf.tms_cutime / clk_tck / 60),
3705 ((double) buf.tms_cutime) / clk_tck,
3706 (int) (buf.tms_cstime / clk_tck / 60),
3707 ((double) buf.tms_cstime) / clk_tck);
3712 static int (*inbuilt(char *s)) (struct op *) {
3713 const struct builtincmd *bp;
3715 for (bp = builtincmds; bp->name != NULL; bp++)
3716 if (strcmp(bp->name, s) == 0)
3717 return (bp->builtinfunc);
3722 /* -------- eval.c -------- */
3727 * blank interpretation
3732 static char **eval(char **ap, int f)
3740 /* Avoid longjmp clobbering */
3745 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3750 if (newenv(setjmp(errpt = ev)) == 0) {
3751 while (*ap && isassign(*ap))
3752 expand(*ap++, &wb, f & ~DOGLOB);
3754 for (wf = ap; *wf; wf++) {
3756 expand(*wf, &wb, f & ~DOGLOB);
3759 for (wb = addword((char *) 0, wb); *ap; ap++) {
3760 if (!flag['k'] || !isassign(*ap))
3761 expand(*ap, &wb, f & ~DOKEY);
3763 wb = addword((char *) 0, wb);
3769 return (gflg ? (char **) NULL : wp);
3773 * Make the exported environment from the exported
3774 * names in the dictionary. Keyword assignments
3775 * will already have been done.
3777 static char **makenv(int all, struct wdblock *wb)
3781 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3783 for (vp = vlist; vp; vp = vp->next)
3784 if (all || vp->status & EXPORT)
3785 wb = addword(vp->name, wb);
3786 wb = addword((char *) 0, wb);
3787 return (getwords(wb));
3790 static char *evalstr(char *cp, int f)
3794 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3797 if (expand(cp, &wb, f)) {
3798 if (wb == NULL || wb->w_nword == 0
3799 || (cp = wb->w_words[0]) == NULL)
3807 static int expand(char *cp, struct wdblock **wbp, int f)
3812 /* Avoid longjmp clobbering */
3816 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3823 if (!anys("$`'\"", cp) &&
3824 !anys(ifs->value, cp) && ((f & DOGLOB) == 0 || !anys("[*?", cp))) {
3825 cp = strsave(cp, areanum);
3828 *wbp = addword(cp, *wbp);
3831 if (newenv(setjmp(errpt = ev)) == 0) {
3832 PUSHIO(aword, cp, strchar);
3834 while ((cp = blank(f)) && gflg == 0) {
3836 cp = strsave(cp, areanum);
3837 if ((f & DOGLOB) == 0) {
3840 *wbp = addword(cp, *wbp);
3842 *wbp = glob(cp, *wbp);
3851 * Blank interpretation and quoting
3853 static char *blank(int f)
3857 int scanequals, foundequals;
3859 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3862 scanequals = f & DOKEY;
3866 switch (c = subgetc('"', foundequals)) {
3874 if (f & DOBLANK && any(c, ifs->value))
3883 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3886 if (c == '\'' || !any(c, "$`\""))
3893 if (!isalpha(c) && c != '_')
3896 c = subgetc('"', foundequals);
3898 f & (DOBLANK && any(c, ifs->value)) ||
3899 (!INSUB() && any(c, "\"'"))) {
3910 } else if (!isalnum(c) && c != '_')
3920 * Get characters, substituting for ` and $
3922 static int subgetc(char ec, int quoted)
3926 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3930 if (!INSUB() && ec != '\'') {
3932 if (grave(quoted) == 0)
3934 e.iop->task = XGRAVE;
3937 if (c == '$' && (c = dollar(quoted)) == 0) {
3938 e.iop->task = XDOLL;
3946 * Prepare to generate the string returned by ${} substitution.
3948 static int dollar(int quoted)
3953 char *s, c, *cp = NULL;
3956 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3962 if (isalpha(c) || c == '_') {
3963 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3964 if (e.linep < elinep)
3971 otask = e.iop->task;
3973 e.iop->task = XOTHER;
3974 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3975 if (e.linep < elinep)
3978 e.iop->task = otask;
3985 if (e.linep >= elinep) {
3986 err("string in ${} too long");
3992 for (cp = s + 1; *cp; cp++)
3993 if (any(*cp, "=-+?")) {
3998 if (s[1] == 0 && (*s == '*' || *s == '@')) {
4000 /* currently this does not distinguish $* and $@ */
4001 /* should check dollar */
4003 PUSHIO(awordlist, dolv + 1, dolchar);
4005 } else { /* trap the nasty ${=} */
4011 if ((dolp = vp->value) == null) {
4015 err("cannot use ${...=...} with $n");
4024 dolp = strsave(cp, areanum);
4029 prs("missing value for ");
4036 } else if (c == '+')
4037 dolp = strsave(cp, areanum);
4038 if (flag['u'] && dolp == null) {
4039 prs("unset variable: ");
4044 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4049 * Run the command in `...` and read its output.
4052 static int grave(int quoted)
4058 static char child_cmd[LINELIM];
4064 char *argument_list[4];
4065 struct wdblock *wb = NULL;
4068 /* Avoid longjmp clobbering */
4072 for (cp = e.iop->argp->aword; *cp != '`'; cp++)
4074 err("no closing `");
4078 /* string copy with dollar expansion */
4079 src = e.iop->argp->aword;
4084 while ((*src != '`') && (count < LINELIM)) {
4089 if (*src == '$' && !ignore && !ignore_once) {
4091 char var_name[LINELIM];
4092 char alt_value[LINELIM];
4105 var_name[var_index++] = *src++;
4106 while (isalnum(*src) || *src=='_')
4107 var_name[var_index++] = *src++;
4108 var_name[var_index] = 0;
4121 err("unclosed ${\n");
4126 while (*src && (*src != '}')) {
4127 alt_value[alt_index++] = *src++;
4129 alt_value[alt_index] = 0;
4131 err("unclosed ${\n");
4138 if (isalpha(*var_name)) {
4139 /* let subshell handle it instead */
4141 char *namep = var_name;
4149 char *altp = alt_value;
4157 wb = addword(lookup(var_name)->name, wb);
4161 vp = lookup(var_name);
4162 if (vp->value != null)
4163 value = (operator == '+') ?
4164 alt_value : vp->value;
4165 else if (operator == '?') {
4168 } else if (alt_index && (operator != '+')) {
4170 if (operator == '=')
4175 while (*value && (count < LINELIM)) {
4188 if (openpipe(pf) < 0)
4191 while ((i = vfork()) == -1 && errno == EAGAIN);
4193 DBGPRINTF3(("GRAVE: i is %p\n", io));
4197 err((char *) bb_msg_memory_exhausted);
4201 waitpid(i, NULL, 0);
4202 e.iop->argp->aword = ++cp;
4204 PUSHIO(afile, remap(pf[0]),
4205 (int (*)(struct ioarg *)) ((quoted) ? qgravechar :
4209 /* allow trapped signals */
4210 /* XXX - Maybe this signal stuff should go as well? */
4211 for (j = 0; j <= _NSIG; j++)
4212 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4218 argument_list[0] = (char *) DEFAULT_SHELL;
4219 argument_list[1] = "-c";
4220 argument_list[2] = child_cmd;
4221 argument_list[3] = 0;
4223 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4224 prs(argument_list[0]);
4231 static char *unquote(char *as)
4235 if ((s = as) != NULL)
4241 /* -------- glob.c -------- */
4247 #define scopy(x) strsave((x), areanum)
4249 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4251 static struct wdblock *cl, *nl;
4252 static char spcl[] = "[?*";
4254 static struct wdblock *glob(char *cp, struct wdblock *wb)
4262 for (pp = cp; *pp; pp++)
4265 else if (!any(*pp & ~QUOTE, spcl))
4268 for (cl = addword(scopy(cp), (struct wdblock *) 0); anyspcl(cl);
4270 nl = newword(cl->w_nword * 2);
4271 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4272 for (pp = cl->w_words[i]; *pp; pp++)
4273 if (any(*pp, spcl)) {
4274 globname(cl->w_words[i], pp);
4278 nl = addword(scopy(cl->w_words[i]), nl);
4280 for (i = 0; i < cl->w_nword; i++)
4281 DELETE(cl->w_words[i]);
4284 for (i = 0; i < cl->w_nword; i++)
4285 unquote(cl->w_words[i]);
4286 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4288 for (i = 0; i < cl->w_nword; i++)
4289 wb = addword(cl->w_words[i], wb);
4294 wb = addword(unquote(cp), wb);
4298 static void globname(char *we, char *pp)
4301 char *name, *gp, *dp;
4305 char dname[NAME_MAX + 1];
4308 for (np = we; np != pp; pp--)
4311 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4315 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4324 dname[NAME_MAX] = '\0';
4325 while ((de = readdir(dirp)) != NULL) {
4326 /* XXX Hmmm... What this could be? (abial) */
4328 if (ent[j].d_ino == 0)
4331 strncpy(dname, de->d_name, NAME_MAX);
4332 if (dname[0] == '.')
4335 for (k = 0; k < NAME_MAX; k++)
4336 if (any(dname[k], spcl))
4338 if (gmatch(dname, gp)) {
4339 name = generate(we, pp, dname, np);
4340 if (*np && !anys(np, spcl)) {
4341 if (stat(name, &dbuf)) {
4346 nl = addword(name, nl);
4355 * generate a pathname as below.
4356 * start..end1 / middle end
4357 * the slashes come for free
4359 static char *generate(char *start1, char *end1, char *middle, char *end)
4365 space((int) (end1 - start1) + strlen(middle) + strlen(end) + 2);
4366 for (xp = start1; xp != end1;)
4368 for (xp = middle; (*op++ = *xp++) != '\0';);
4370 for (xp = end; (*op++ = *xp++) != '\0';);
4374 static int anyspcl(struct wdblock *wb)
4380 for (i = 0; i < wb->w_nword; i++)
4381 if (anys(spcl, *wd++))
4386 static int xstrcmp(char *p1, char *p2)
4388 return (strcmp(*(char **) p1, *(char **) p2));
4391 /* -------- word.c -------- */
4393 static struct wdblock *newword(int nw)
4397 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4403 static struct wdblock *addword(char *wd, struct wdblock *wb)
4405 struct wdblock *wb2;
4409 wb = newword(NSTART);
4410 if ((nw = wb->w_nword) >= wb->w_bsize) {
4411 wb2 = newword(nw * 2);
4412 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4413 nw * sizeof(char *));
4418 wb->w_words[wb->w_nword++] = wd;
4423 char **getwords(struct wdblock *wb)
4429 return ((char **) NULL);
4430 if (wb->w_nword == 0) {
4432 return ((char **) NULL);
4434 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4435 memcpy((char *) wd, (char *) wb->w_words, nb);
4436 DELETE(wb); /* perhaps should done by caller */
4440 static int (*func) (char *, char *);
4443 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4447 glob1(a0, a0 + a1 * a2);
4450 static void glob1(char *base, char *lim)
4462 if ((n = (int) (lim - base)) <= v2)
4464 n = v2 * (n / (2 * v2));
4465 hptr = lptr = base + n;
4470 if ((c = (*func) (i, lptr)) == 0) {
4471 glob2(i, lptr -= v2);
4482 if ((c = (*func) (hptr, j)) == 0) {
4483 glob2(hptr += v2, j);
4488 glob3(i, hptr += v2, j);
4503 if (lptr - base >= lim - hptr) {
4504 glob1(hptr + v2, lim);
4514 glob3(j, lptr -= v2, i);
4519 static void glob2(char *i, char *j)
4521 char *index1, *index2, c;
4529 *index1++ = *index2;
4534 static void glob3(char *i, char *j, char *k)
4536 char *index1, *index2, *index3;
4546 *index1++ = *index3;
4547 *index3++ = *index2;
4552 /* -------- io.c -------- */
4558 static int my_getc(int ec)
4562 if (e.linep > elinep) {
4563 while ((c = readc()) != '\n' && c);
4564 err("input line too long");
4569 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4572 if (c == '\n' && ec != '\"')
4573 return (my_getc(ec));
4580 static void unget(int c)
4582 if (e.iop >= e.iobase)
4586 static int eofc(void)
4588 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4591 static int readc(void)
4595 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4597 for (; e.iop >= e.iobase; e.iop--) {
4598 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4599 if ((c = e.iop->peekc) != '\0') {
4603 if (e.iop->prev != 0) {
4604 if ((c = (*e.iop->iofn) (e.iop->argp, e.iop)) != '\0') {
4609 if (e.iop == iostack)
4611 return (e.iop->prev = c);
4612 } else if (e.iop->task == XIO && e.iop->prev != '\n') {
4614 if (e.iop == iostack)
4619 if (e.iop->task == XIO) {
4621 return e.iop->prev = 0;
4623 if (interactive && e.iop == iostack + 1) {
4624 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4625 current_prompt = prompt->value;
4635 if (e.iop >= iostack) {
4636 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4640 DBGPRINTF(("READC: leave()...\n"));
4647 static void ioecho(char c)
4650 write(2, &c, sizeof c);
4654 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4656 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4657 argp->afid, e.iop));
4659 /* Set env ptr for io source to next array spot and check for array overflow */
4660 if (++e.iop >= &iostack[NPUSH]) {
4662 err("Shell input nested too deeply");
4667 /* We did not overflow the NPUSH array spots so setup data structs */
4669 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4671 if (argp->afid != AFID_NOBUF)
4675 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4676 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4678 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4680 if (e.iop == &iostack[0])
4681 e.iop->argp->afbuf = &mainbuf;
4683 e.iop->argp->afbuf = &sharedbuf;
4685 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4686 /* This line appears to be active when running scripts from command line */
4687 if ((isatty(e.iop->argp->afile) == 0)
4688 && (e.iop == &iostack[0]
4689 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4690 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4691 bufid = AFID_ID; /* AFID_ID = 0 */
4693 e.iop->argp->afid = bufid; /* assign buffer id */
4696 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4697 iostack, e.iop, e.iop->argp->afbuf));
4698 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4699 &mainbuf, &sharedbuf, bufid, e.iop));
4703 e.iop->prev = ~'\n';
4708 if (fn == filechar || fn == linechar)
4710 else if (fn == (int (*)(struct ioarg *)) gravechar
4711 || fn == (int (*)(struct ioarg *)) qgravechar)
4712 e.iop->task = XGRAVE;
4714 e.iop->task = XOTHER;
4719 static struct io *setbase(struct io *ip)
4729 * Input generating functions
4733 * Produce the characters of a string, then a newline, then EOF.
4735 static int nlchar(struct ioarg *ap)
4739 if (ap->aword == NULL)
4741 if ((c = *ap->aword++) == 0) {
4749 * Given a list of words, produce the characters
4750 * in them, with a space after each word.
4752 static int wdchar(struct ioarg *ap)
4757 if ((wl = ap->awordlist) == NULL)
4760 if ((c = *(*wl)++) != 0)
4765 ap->awordlist = NULL;
4770 * Return the characters of a list of words,
4771 * producing a space between them.
4773 static int dolchar(struct ioarg *ap)
4777 if ((wp = *ap->awordlist++) != NULL) {
4778 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4784 static int xxchar(struct ioarg *ap)
4788 if (ap->aword == NULL)
4790 if ((c = *ap->aword++) == '\0') {
4798 * Produce the characters from a single word (string).
4800 static int strchar(struct ioarg *ap)
4804 if (ap->aword == NULL || (c = *ap->aword++) == 0)
4810 * Produce quoted characters from a single word (string).
4812 static int qstrchar(struct ioarg *ap)
4816 if (ap->aword == NULL || (c = *ap->aword++) == 0)
4822 * Return the characters from a file.
4824 static int filechar(struct ioarg *ap)
4828 struct iobuf *bp = ap->afbuf;
4830 if (ap->afid != AFID_NOBUF) {
4831 if ((i = ap->afid != bp->id) || bp->bufp == bp->ebufp) {
4834 lseek(ap->afile, ap->afpos, SEEK_SET);
4836 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4844 bp->ebufp = (bp->bufp = bp->buf) + i;
4848 return *bp->bufp++ & 0177;
4850 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4851 if (interactive && isatty(ap->afile)) {
4852 static char mycommand[BUFSIZ];
4853 static int position = 0, size = 0;
4855 while (size == 0 || position >= size) {
4856 cmdedit_read_input(current_prompt, mycommand);
4857 size = strlen(mycommand);
4860 c = mycommand[position];
4867 i = safe_read(ap->afile, &c, sizeof(c));
4868 return (i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0));
4873 * Return the characters from a here temp file.
4875 static int herechar(struct ioarg *ap)
4880 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4889 * Return the characters produced by a process (`...`).
4890 * Quote them if required, and remove any trailing newline characters.
4892 static int gravechar(struct ioarg *ap, struct io *iop)
4896 if ((c = qgravechar(ap, iop) & ~QUOTE) == '\n')
4901 static int qgravechar(struct ioarg *ap, struct io *iop)
4905 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4910 return ('\n' | QUOTE);
4914 } else if ((c = filechar(ap)) == '\n') {
4916 while ((c = filechar(ap)) == '\n')
4924 return (c != 0 ? c | QUOTE : 0);
4928 * Return a single command (usually the first line) from a file.
4930 static int linechar(struct ioarg *ap)
4934 if ((c = filechar(ap)) == '\n') {
4937 ap->afile = -1; /* illegal value */
4943 static void prs(const char *s)
4946 write(2, s, strlen(s));
4949 static void prn(unsigned u)
4954 static void closef(int i)
4960 static void closeall(void)
4964 for (u = NUFILE; u < NOFILE;)
4970 * remap fd into Shell's fd space
4972 static int remap(int fd)
4979 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
4982 for (i = 0; i < NOFILE; i++)
4989 } while (fd >= 0 && fd < e.iofd);
4991 for (i = 0; i < NOFILE; i++)
4996 err("too many files open in shell");
5002 static int openpipe(int *pv)
5006 if ((i = pipe(pv)) < 0)
5007 err("can't create pipe - try again");
5011 static void closepipe(int *pv)
5019 /* -------- here.c -------- */
5025 static void markhere(char *s, struct ioword *iop)
5027 struct here *h, *lh;
5029 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
5031 h = (struct here *) space(sizeof(struct here));
5035 h->h_tag = evalstr(s, DOSUB);
5045 for (lh = inhere; lh != NULL; lh = lh->h_next)
5046 if (lh->h_next == 0) {
5050 iop->io_flag |= IOHERE | IOXHERE;
5051 for (s = h->h_tag; *s; s++)
5053 iop->io_flag &= ~IOXHERE;
5056 h->h_dosub = iop->io_flag & IOXHERE;
5059 static void gethere(void)
5061 struct here *h, *hp;
5063 DBGPRINTF7(("GETHERE: enter...\n"));
5065 /* Scan here files first leaving inhere list in place */
5066 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5067 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5069 /* Make inhere list active - keep list intact for scraphere */
5071 hp->h_next = acthere;
5077 static void readhere(char **name, char *s, int ec)
5080 char tname[30] = ".msh_XXXXXX";
5083 char myline[LINELIM + 1];
5086 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5088 tf = mkstemp(tname);
5092 *name = strsave(tname, areanum);
5093 if (newenv(setjmp(errpt = ev)) != 0)
5096 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5099 if (interactive && e.iop <= iostack) {
5100 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5101 current_prompt = cprompt->value;
5103 prs(cprompt->value);
5107 while ((c = my_getc(ec)) != '\n' && c) {
5110 if (thenext >= &myline[LINELIM]) {
5117 if (strcmp(s, myline) == 0 || c == 0)
5120 write(tf, myline, (int) (thenext - myline));
5123 prs("here document `");
5133 * open here temp file.
5134 * if unquoted here, expand here temp file into second temp file.
5136 static int herein(char *hname, int xdoll)
5142 /* Avoid longjmp clobbering */
5148 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5150 hf = open(hname, 0);
5156 char tname[30] = ".msh_XXXXXX";
5159 tf = mkstemp(tname);
5162 if (newenv(setjmp(errpt = ev)) == 0) {
5163 PUSHIO(afile, hf, herechar);
5165 while ((c = subgetc(0, 0)) != 0) {
5167 write(tf, &c, sizeof c);
5173 tf = open(tname, 0);
5180 static void scraphere(void)
5184 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5186 for (h = inhere; h != NULL; h = h->h_next) {
5187 if (h->h_iop && h->h_iop->io_name)
5188 unlink(h->h_iop->io_name);
5193 /* unlink here temp files before a freearea(area) */
5194 static void freehere(int area)
5196 struct here *h, *hl;
5198 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5201 for (h = acthere; h != NULL; h = h->h_next)
5202 if (getarea((char *) h) >= area) {
5203 if (h->h_iop->io_name != NULL)
5204 unlink(h->h_iop->io_name);
5206 acthere = h->h_next;
5208 hl->h_next = h->h_next;
5216 * Copyright (c) 1987,1997, Prentice Hall
5217 * All rights reserved.
5219 * Redistribution and use of the MINIX operating system in source and
5220 * binary forms, with or without modification, are permitted provided
5221 * that the following conditions are met:
5223 * Redistributions of source code must retain the above copyright
5224 * notice, this list of conditions and the following disclaimer.
5226 * Redistributions in binary form must reproduce the above
5227 * copyright notice, this list of conditions and the following
5228 * disclaimer in the documentation and/or other materials provided
5229 * with the distribution.
5231 * Neither the name of Prentice Hall nor the names of the software
5232 * authors or contributors may be used to endorse or promote
5233 * products derived from this software without specific prior
5234 * written permission.
5236 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5237 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5238 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5239 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5240 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5241 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5242 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5243 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5244 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5245 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5246 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5247 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.