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.
17 #include <sys/times.h>
20 extern char **environ;
23 /*#define MSHDEBUG 1*/
26 int mshdbg = MSHDEBUG;
28 #define DBGPRINTF(x) if(mshdbg>0)printf x
29 #define DBGPRINTF0(x) if(mshdbg>0)printf x
30 #define DBGPRINTF1(x) if(mshdbg>1)printf x
31 #define DBGPRINTF2(x) if(mshdbg>2)printf x
32 #define DBGPRINTF3(x) if(mshdbg>3)printf x
33 #define DBGPRINTF4(x) if(mshdbg>4)printf x
34 #define DBGPRINTF5(x) if(mshdbg>5)printf x
35 #define DBGPRINTF6(x) if(mshdbg>6)printf x
36 #define DBGPRINTF7(x) if(mshdbg>7)printf x
37 #define DBGPRINTF8(x) if(mshdbg>8)printf x
38 #define DBGPRINTF9(x) if(mshdbg>9)printf x
42 #define RCPRINTF(x) if(mshdbg_rc)printf x
47 #define DBGPRINTF0(x) ((void)0)
48 #define DBGPRINTF1(x) ((void)0)
49 #define DBGPRINTF2(x) ((void)0)
50 #define DBGPRINTF3(x) ((void)0)
51 #define DBGPRINTF4(x) ((void)0)
52 #define DBGPRINTF5(x) ((void)0)
53 #define DBGPRINTF6(x) ((void)0)
54 #define DBGPRINTF7(x) ((void)0)
55 #define DBGPRINTF8(x) ((void)0)
56 #define DBGPRINTF9(x) ((void)0)
58 #define RCPRINTF(x) ((void)0)
63 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
64 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
65 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
67 # define DEFAULT_ROOT_PROMPT "# "
68 # define DEFAULT_USER_PROMPT "$ "
72 /* -------- sh.h -------- */
78 #define NPUSH 8 /* limit to input nesting */
81 #define NOFILE 20 /* Number of open files */
82 #define NUFILE 10 /* Number of user-accessible files */
83 #define FDBASE 10 /* First file usable by Shell */
86 * values returned by wait
88 #define WAITSIG(s) ((s)&0177)
89 #define WAITVAL(s) (((s)>>8)&0377)
90 #define WAITCORE(s) (((s)&0200)!=0)
93 * library and system definitions
95 typedef void xint; /* base type of jmp_buf, for not broken compilers */
103 #define NOBLOCK ((struct op *)NULL)
104 #define NOWORD ((char *)NULL)
105 #define NOWORDS ((char **)NULL)
106 #define NOPIPE ((int *)NULL)
109 * Description of a command or an operation on commands.
110 * Might eventually use a union.
113 int type; /* operation type, see below */
114 char **words; /* arguments to a command */
115 struct ioword **ioact; /* IO actions (eg, < > >>) */
118 char *str; /* identifier for case and for */
121 #define TCOM 1 /* command */
122 #define TPAREN 2 /* (c-list) */
123 #define TPIPE 3 /* a | b */
124 #define TLIST 4 /* a [&;] b */
125 #define TOR 5 /* || */
126 #define TAND 6 /* && */
134 #define TPAT 14 /* pattern in case */
135 #define TBRACE 15 /* {c-list} */
136 #define TASYNC 16 /* c & */
137 /* Added to support "." file expansion */
140 /* Strings for names to make debug easier */
142 static const char *const T_CMD_NAMES[] = {
165 * actions determining the environment of a process
167 #define BIT(i) (1<<(i))
168 #define FEXEC BIT(0) /* execute without forking */
170 #define AREASIZE (90000)
173 * flags to control evaluation of words
175 #define DOSUB 1 /* interpret $, `, and quotes */
176 #define DOBLANK 2 /* perform blank interpretation */
177 #define DOGLOB 4 /* interpret [?* */
178 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
179 #define DOTRIM 16 /* trim resulting string */
181 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
185 static int newfile(char *s);
186 static char *cclass(char *p, int sub);
191 struct brkcon *nextlev;
199 short io_unit; /* unit affected */
200 short io_flag; /* action (below) */
201 char *io_name; /* file name */
204 #define IOREAD 1 /* < */
205 #define IOHERE 2 /* << (here file) */
206 #define IOWRITE 4 /* > */
207 #define IOCAT 8 /* >> */
208 #define IOXHERE 16 /* ${}, ` in << */
209 #define IODUP 32 /* >&digit */
210 #define IOCLOSE 64 /* >&- */
212 #define IODEFAULT (-1) /* token for default IO unit */
217 * parsing & execution environment
223 xint *errpt; /* void * */
231 * -k: look for name=value everywhere on command line
233 * -t: exit after reading and executing one command
236 * -u: unset variables net diagnostic
238 static char flags['z' - 'a' + 1];
239 /* this looks weird, but is OK ... we index flag with 'a'...'z' */
240 static char *flag = flags - 'a';
242 static char *null; /* null value for variable */
243 static int intr; /* interrupt pending */
245 static char *trap[_NSIG + 1];
246 static char ourtrap[_NSIG + 1];
247 static int trapset; /* trap pending */
249 static int heedint; /* heed interrupt signals */
251 static int yynerrs; /* yacc */
253 static char line[LINELIM];
256 #if ENABLE_FEATURE_EDITING
257 static char *current_prompt;
258 static line_input_t *line_input_state;
261 static int areanum; /* current allocation area */
267 typedef int (*builtin_func_ptr)(struct op *);
268 static builtin_func_ptr inbuilt(char *s);
270 static char *rexecve(char *c, char **v, char **envp);
271 static char *evalstr(char *cp, int f);
272 static char *putn(int n);
273 static char *unquote(char *as);
274 static int rlookup(char *n);
275 static struct wdblock *glob(char *cp, struct wdblock *wb);
276 static int my_getc(int ec);
277 static int subgetc(char ec, int quoted);
278 static char **makenv(int all, struct wdblock *wb);
279 static char **eval(char **ap, int f);
280 static int setstatus(int s);
281 static int waitfor(int lastpid, int canintr);
283 static void onintr(int s); /* SIGINT handler */
285 static int newenv(int f);
286 static void quitenv(void);
287 static int anys(const char *s1, const char *s2);
288 static int any(int c, const char *s);
289 static void next(int f);
290 static void setdash(void);
291 static void onecommand(void);
292 static void runtrap(int i);
293 static int gmatch(char *s, char *p);
296 /* -------- area stuff -------- */
298 #define REGSIZE sizeof(struct region)
300 /* #define SHRINKBY (64) */
304 #define ALIGN (sizeof(int)-1)
313 /* -------- grammar stuff -------- */
338 /* Added for "." file expansion */
341 #define YYERRCODE 300
344 #define CONTIN 01 /* skip new lines to complete command */
346 static struct op *pipeline(int cf);
347 static struct op *andor(void);
348 static struct op *c_list(void);
349 static int synio(int cf);
350 static void musthave(int c, int cf);
351 static struct op *simple(void);
352 static struct op *nested(int type, int mark);
353 static struct op *command(int cf);
354 static struct op *dogroup(int onlydone);
355 static struct op *thenpart(void);
356 static struct op *elsepart(void);
357 static struct op *caselist(void);
358 static struct op *casepart(void);
359 static char **pattern(void);
360 static char **wordlist(void);
361 static struct op *list(struct op *t1, struct op *t2);
362 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
363 static struct op *newtp(void);
364 static struct op *namelist(struct op *t);
365 static char **copyw(void);
366 static void word(char *cp);
367 static struct ioword **copyio(void);
368 static struct ioword *io(int u, int f, char *cp);
369 static int yylex(int cf);
370 static int collect(int c, int c1);
371 static int dual(int c);
372 static void diag(int ec);
373 static char *tree(unsigned size);
375 /* -------- var.h -------- */
384 #define COPYV 1 /* flag to setval, suggesting copy */
385 #define RONLY 01 /* variable is read-only */
386 #define EXPORT 02 /* variable is to be exported */
387 #define GETCELL 04 /* name & value space was got with getcell */
389 static int yyparse(void);
391 static int execute(struct op *t, int *pin, int *pout, int act);
394 /* -------- io.h -------- */
397 unsigned id; /* buffer id */
398 char buf[512]; /* buffer */
399 char *bufp; /* pointer into buffer */
400 char *ebufp; /* pointer to end of buffer */
403 /* possible arguments to an IO function */
407 int afile; /* file descriptor */
408 unsigned afid; /* buffer id */
409 long afpos; /* file position */
410 struct iobuf *afbuf; /* buffer for this file */
413 //static struct ioarg ioargstack[NPUSH];
414 #define AFID_NOBUF (~0)
417 /* an input generator's state */
419 int (*iofn) (struct ioarg *, struct io *);
422 char prev; /* previous character read by readc() */
423 char nlcount; /* for `'s */
424 char xchar; /* for `'s */
425 char task; /* reason for pushed IO */
428 //static struct io iostack[NPUSH];
429 #define XOTHER 0 /* none of the below */
430 #define XDOLL 1 /* expanding ${} */
431 #define XGRAVE 2 /* expanding `'s */
432 #define XIO 3 /* file IO */
434 /* in substitution */
435 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
439 * input generators for IO structure
441 static int nlchar(struct ioarg *ap);
442 static int strchar(struct ioarg *ap);
443 static int qstrchar(struct ioarg *ap);
444 static int filechar(struct ioarg *ap);
445 static int herechar(struct ioarg *ap);
446 static int linechar(struct ioarg *ap);
447 static int gravechar(struct ioarg *ap, struct io *iop);
448 static int qgravechar(struct ioarg *ap, struct io *iop);
449 static int dolchar(struct ioarg *ap);
450 static int wdchar(struct ioarg *ap);
451 static void scraphere(void);
452 static void freehere(int area);
453 static void gethere(void);
454 static void markhere(char *s, struct ioword *iop);
455 static int herein(char *hname, int xdoll);
456 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
459 static int eofc(void);
460 static int readc(void);
461 static void unget(int c);
462 static void ioecho(char c);
468 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
469 static int remap(int fd);
470 static int openpipe(int *pv);
471 static void closepipe(int *pv);
472 static struct io *setbase(struct io *ip);
474 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)),pushio(&temparg,(gen)))
475 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
477 /* -------- word.h -------- */
479 #define NSTART 16 /* default number of words to allow for initially */
484 /* bounds are arbitrary */
488 static struct wdblock *addword(char *wd, struct wdblock *wb);
489 static struct wdblock *newword(int nw);
490 static char **getwords(struct wdblock *wb);
492 /* -------- misc stuff -------- */
494 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
495 static int iosetup(struct ioword *iop, int pipein, int pipeout);
496 static void echo(char **wp);
497 static struct op **find1case(struct op *t, char *w);
498 static struct op *findcase(struct op *t, char *w);
499 static void brkset(struct brkcon *bc);
500 static int dolabel(struct op *t);
501 static int dohelp(struct op *t);
502 static int dochdir(struct op *t);
503 static int doshift(struct op *t);
504 static int dologin(struct op *t);
505 static int doumask(struct op *t);
506 static int doexec(struct op *t);
507 static int dodot(struct op *t);
508 static int dowait(struct op *t);
509 static int doread(struct op *t);
510 static int doeval(struct op *t);
511 static int dotrap(struct op *t);
512 static int getsig(char *s);
513 static void setsig(int n, sighandler_t f);
514 static int getn(char *as);
515 static int dobreak(struct op *t);
516 static int docontinue(struct op *t);
517 static int brkcontin(char *cp, int val);
518 static int doexit(struct op *t);
519 static int doexport(struct op *t);
520 static int doreadonly(struct op *t);
521 static void rdexp(char **wp, void (*f) (struct var *), int key);
522 static void badid(char *s);
523 static int doset(struct op *t);
524 static void varput(char *s, int out);
525 static int dotimes(struct op *t);
526 static int expand(char *cp, struct wdblock **wbp, int f);
527 static char *blank(int f);
528 static int dollar(int quoted);
529 static int grave(int quoted);
530 static void globname(char *we, char *pp);
531 static char *generate(char *start1, char *end1, char *middle, char *end);
532 static int anyspcl(struct wdblock *wb);
533 static int xstrcmp(char *p1, char *p2);
534 static void glob0(char *a0, unsigned a1, int a2,
535 int (*a3) (char *, char *));
536 static void glob1(char *base, char *lim);
537 static void glob2(char *i, char *j);
538 static void glob3(char *i, char *j, char *k);
539 static void readhere(char **name, char *s, int ec);
540 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
541 static int xxchar(struct ioarg *ap);
546 struct ioword *h_iop;
550 static const char * const signame[] = {
553 NULL, /* interrupt */
555 "Illegal instruction",
559 "Floating Point Exception",
564 NULL, /* broken pipe */
569 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
575 static const struct res restab[] = {
601 int (*builtinfunc) (struct op * t);
603 static const struct builtincmd builtincmds[] = {
608 {"continue", docontinue},
612 {"export", doexport},
617 {"readonly", doreadonly},
627 static struct op *scantree(struct op *);
628 static struct op *dowholefile(int, int);
636 static int interactive; /* Is this an interactive shell */
638 static int multiline; /* \n changed to ; */
639 static struct op *outtree; /* result from parser */
642 static struct brkcon *brklist;
644 static struct wdblock *wdlist;
645 static struct wdblock *iolist;
646 static char *trap[_NSIG + 1];
647 static char ourtrap[_NSIG + 1];
648 static int trapset; /* trap pending */
651 static struct var *mshdbg_var;
653 static struct var *vlist; /* dictionary */
654 static struct var *homedir; /* home directory */
655 static struct var *prompt; /* main prompt */
656 static struct var *cprompt; /* continuation prompt */
657 static struct var *path; /* search path for commands */
658 static struct var *shell; /* shell to interpret command files */
659 static struct var *ifs; /* field separators */
661 static int areanum; /* current allocation area */
664 static char *null = "";
665 static int heedint = 1;
666 static void (*qflag) (int) = SIG_IGN;
670 static int iounit = IODEFAULT;
671 static YYSTYPE yylval;
672 static char *elinep = line + sizeof(line) - 5;
674 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
675 static struct ioarg ioargstack[NPUSH];
676 static struct io iostack[NPUSH];
677 static struct iobuf sharedbuf = { AFID_NOBUF };
678 static struct iobuf mainbuf = { AFID_NOBUF };
679 static unsigned bufid = AFID_ID; /* buffer id counter */
681 static struct here *inhere; /* list of hear docs while parsing */
682 static struct here *acthere; /* list of active here documents */
683 static struct region *areabot; /* bottom of area */
684 static struct region *areatop; /* top of area */
685 static struct region *areanxt; /* starting point of scan */
687 static void *brkaddr;
689 static struct env e = {
690 line, /* linep: char ptr */
691 iostack, /* iobase: struct io ptr */
692 iostack - 1, /* iop: struct io ptr */
693 (xint *) NULL, /* errpt: void ptr for errors? */
694 FDBASE, /* iofd: file desc */
695 (struct env *) NULL /* oenv: struct env ptr */
699 void print_t(struct op *t)
701 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
702 T_CMD_NAMES[t->type], t->words, t->ioact));
705 DBGPRINTF(("T: W1: %s", t->words[0]));
709 void print_tree(struct op *head)
712 DBGPRINTF(("PRINT_TREE: no tree\n"));
716 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
720 print_tree(head->left);
723 print_tree(head->right);
725 #endif /* MSHDEBUG */
731 static void prs(const char *s)
734 write(2, s, strlen(s));
737 static void prn(unsigned u)
742 static void closef(int i)
748 static void closeall(void)
752 for (u = NUFILE; u < NOFILE;)
757 /* fail but return to process next command */
758 static void fail(void) ATTRIBUTE_NORETURN;
759 static void fail(void)
765 /* abort shell (or fail in subshell) */
766 static void leave(void) ATTRIBUTE_NORETURN;
767 static void leave(void)
769 DBGPRINTF(("LEAVE: leave called!\n"));
780 static void warn(const char *s)
791 static void err(const char *s)
801 e.iop = e.iobase = iostack;
805 /* -------- area.c -------- */
808 * All memory between (char *)areabot and (char *)(areatop+1) is
809 * exclusively administered by the area management routines.
810 * It is assumed that sbrk() and brk() manipulate the high end.
814 void * __q = (void *)-1; \
815 if (brkaddr + (int)(X) < brktop) { \
817 brkaddr += (int)(X); \
822 static void initarea(void)
824 brkaddr = xmalloc(AREASIZE);
825 brktop = brkaddr + AREASIZE;
827 while ((long) sbrk(0) & ALIGN)
829 areabot = (struct region *) sbrk(REGSIZE);
831 areabot->next = areabot;
832 areabot->area = BUSY;
837 static char *getcell(unsigned nbytes)
840 struct region *p, *q;
847 /* silly and defeats the algorithm */
849 * round upwards and add administration area
851 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
854 if (p->area > areanum) {
858 while ((q = p->next)->area > areanum && q != areanxt)
861 * exit loop if cell big enough
870 i = nregio >= GROWBY ? nregio : GROWBY;
871 p = (struct region *) sbrk(i * REGSIZE);
872 if (p == (struct region *) -1)
877 abort(); /* allocated areas are contiguous */
887 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
889 areanxt = p + nregio;
892 * split into requested area and rest
894 if (areanxt + 1 > q) {
896 abort(); /* insufficient space left for admin */
899 areanxt->area = FREE;
903 return (char *) (p + 1);
906 static void freecell(char *cp)
910 p = (struct region *) cp;
918 #define DELETE(obj) freecell((char *)obj)
920 static void freearea(int a)
922 struct region *p, *top;
925 for (p = areabot; p != top; p = p->next)
930 static void setarea(char *cp, int a)
934 p = (struct region *) cp;
939 static int getarea(char *cp)
941 return ((struct region *) cp - 1)->area;
944 static void garbage(void)
946 struct region *p, *q, *top;
949 for (p = areabot; p != top; p = p->next) {
950 if (p->area > areanum) {
951 while ((q = p->next)->area > areanum)
957 if (areatop >= q + SHRINKBY && q->area > areanum) {
958 brk((char *) (q + 1));
966 static char *space(int n)
972 err("out of string space");
976 static char *strsave(const char *s, int a)
980 cp = space(strlen(s) + 1);
990 /* -------- var.c -------- */
992 static int eqname(const char *n1, const char *n2)
994 for (; *n1 != '=' && *n1 != '\0'; n1++)
997 return *n2 == '\0' || *n2 == '=';
1000 static char *findeq(const char *cp)
1002 while (*cp != '\0' && *cp != '=')
1008 * Find the given name in the dictionary
1009 * and return its value. If the name was
1010 * not previously there, enter it now and
1011 * return a null value.
1013 static struct var *lookup(const char *n)
1018 static struct var dummy;
1022 for (c = 0; isdigit(*n) && c < 1000; n++)
1023 c = c * 10 + *n - '0';
1024 dummy.status = RONLY;
1025 dummy.value = (c <= dolc ? dolv[c] : null);
1028 for (vp = vlist; vp; vp = vp->next)
1029 if (eqname(vp->name, n))
1032 vp = (struct var *) space(sizeof(*vp));
1033 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1034 dummy.name = dummy.value = "";
1037 for (cp = vp->name; (*cp = *n++) && *cp != '='; cp++);
1041 setarea((char *) vp, 0);
1042 setarea((char *) vp->name, 0);
1045 vp->status = GETCELL;
1051 * if name is not NULL, it must be
1052 * a prefix of the space `val',
1054 * this is all so that exporting
1055 * values is reasonably painless.
1057 static void nameval(struct var *vp, const char *val, const char *name)
1063 if (vp->status & RONLY) {
1065 while (*xp && *xp != '=')
1066 putc(*xp++, stderr);
1067 err(" is read-only");
1072 xp = space(strlen(vp->name) + strlen(val) + 2);
1075 /* make string: name=value */
1079 while ((*xp = *cp++) != '\0' && *xp != '=')
1086 if (vp->status & GETCELL)
1087 freecell(vp->name); /* form new string `name=value' */
1094 * give variable at `vp' the value `val'.
1096 static void setval(struct var *vp, const char *val)
1098 nameval(vp, val, NULL);
1101 static void export(struct var *vp)
1103 vp->status |= EXPORT;
1106 static void ronly(struct var *vp)
1108 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1109 vp->status |= RONLY;
1112 static int isassign(const char *s)
1115 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1117 /* no isalpha() - we shouldn't use locale */
1120 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1130 c |= 0x20; /* lowercase letters, doesn't affect numbers */
1132 && (unsigned)(c - '0') > 9 /* not number */
1133 && (unsigned)(c - 'a') > 25 /* not letter */
1140 static int assign(const char *s, int cf)
1145 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1147 if (!isalpha(*s) && *s != '_')
1149 for (cp = s; *cp != '='; cp++)
1150 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1153 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1155 vp->status &= ~GETCELL;
1159 static int checkname(char *cp)
1161 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1163 if (!isalpha(*cp++) && *(cp - 1) != '_')
1166 if (!isalnum(*cp++) && *(cp - 1) != '_')
1171 static void putvlist(int f, int out)
1175 for (vp = vlist; vp; vp = vp->next)
1176 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1177 if (vp->status & EXPORT)
1178 write(out, "export ", 7);
1179 if (vp->status & RONLY)
1180 write(out, "readonly ", 9);
1181 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1182 write(out, "\n", 1);
1190 static void sig(int i)
1196 static void runtrap(int i)
1201 if (trapstr == NULL)
1207 RUN(aword, trapstr, nlchar);
1211 static void setdash(void)
1215 char m['z' - 'a' + 1];
1218 for (c = 'a'; c <= 'z'; c++)
1222 setval(lookup("-"), m);
1225 static int newfile(char *s)
1229 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1232 if (NOT_LONE_DASH(s)) {
1233 DBGPRINTF(("NEWFILE: s is %s\n", s));
1237 err(": cannot open");
1247 struct op *scantree(struct op *head)
1254 if (head->left != NULL) {
1255 dotnode = scantree(head->left);
1260 if (head->right != NULL) {
1261 dotnode = scantree(head->right);
1266 if (head->words == NULL)
1269 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1271 if ((head->type != TDOT) && (strcmp(".", head->words[0]) == 0)) {
1272 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1280 static void onecommand(void)
1285 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1305 setjmp(failpt); /* Bruce Evans' fix */
1307 if (setjmp(failpt) || yyparse() || intr) {
1308 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1313 if (!interactive && intr)
1326 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1328 execute(outtree, NOPIPE, NOPIPE, 0);
1331 if (!interactive && intr) {
1343 static int newenv(int f)
1347 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1354 ep = (struct env *) space(sizeof(*ep));
1367 static void quitenv(void)
1372 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1378 /* should close `'d files */
1380 while (--fd >= e.iofd)
1386 * Is character c in s?
1388 static int any(int c, const char *s)
1397 * Is any character from s1 in s2?
1399 static int anys(const char *s1, const char *s2)
1407 static char *putn(int n)
1412 static void next(int f)
1414 PUSHIO(afile, f, filechar);
1417 static void onintr(int s) /* ANSI C requires a parameter */
1419 signal(SIGINT, onintr);
1426 } else if (heedint) {
1432 /* -------- gmatch.c -------- */
1434 * int gmatch(string, pattern)
1435 * char *string, *pattern;
1437 * Match a pattern as in sh(1).
1442 #define QMASK (CMASK&~QUOTE)
1443 #define NOT '!' /* might use ^ */
1445 static int gmatch(char *s, char *p)
1449 if (s == NULL || p == NULL)
1451 while ((pc = *p++ & CMASK) != '\0') {
1468 if (*p == '\0' || gmatch(s, p))
1470 } while (*s++ != '\0');
1474 if (sc != (pc & ~QUOTE))
1481 static char *cclass(char *p, int sub)
1483 int c, d, not, found;
1493 if (p[1] == '-' && p[2] != ']') {
1498 if (c == sub || (c <= sub && sub <= d))
1500 } while (*++p != ']');
1501 return found ? p + 1 : NULL;
1505 /* -------- csyn.c -------- */
1507 * shell: syntax (C version)
1510 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1511 static void yyerror(const char *s)
1514 if (interactive && e.iop <= iostack) {
1516 while (eofc() == 0 && yylex(0) != '\n');
1522 static void zzerr(void) ATTRIBUTE_NORETURN;
1523 static void zzerr(void)
1525 yyerror("syntax error");
1530 DBGPRINTF7(("YYPARSE: enter...\n"));
1537 return (yynerrs != 0);
1540 static struct op *pipeline(int cf)
1545 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1549 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1552 while ((c = yylex(0)) == '|') {
1553 p = command(CONTIN);
1555 DBGPRINTF8(("PIPELINE: error!\n"));
1559 if (t->type != TPAREN && t->type != TCOM) {
1560 /* shell statement */
1561 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1564 t = block(TPIPE, t, p, NOWORDS);
1569 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1573 static struct op *andor(void)
1578 DBGPRINTF7(("ANDOR: enter...\n"));
1582 DBGPRINTF9(("ANDOR: t=%p\n", t));
1585 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1586 p = pipeline(CONTIN);
1588 DBGPRINTF8(("ANDOR: error!\n"));
1592 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1598 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1602 static struct op *c_list(void)
1607 DBGPRINTF7(("C_LIST: enter...\n"));
1614 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1616 while ((c = yylex(0)) == ';' || c == '&'
1617 || (multiline && c == '\n')) {
1625 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1633 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1637 static int synio(int cf)
1643 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1646 if (c != '<' && c != '>') {
1653 iop = io(iounit, i, yylval.cp);
1657 markhere(yylval.cp, iop);
1659 DBGPRINTF7(("SYNIO: returning 1\n"));
1663 static void musthave(int c, int cf)
1665 peeksym = yylex(cf);
1667 DBGPRINTF7(("MUSTHAVE: error!\n"));
1674 static struct op *simple(void)
1680 switch (peeksym = yylex(0)) {
1701 static struct op *nested(int type, int mark)
1705 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1711 return block(type, t, NOBLOCK, NOWORDS);
1714 static struct op *command(int cf)
1717 struct wdblock *iosave;
1720 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1746 t = nested(TPAREN, ')');
1750 t = nested(TBRACE, '}');
1760 t->words = wordlist();
1762 if (c != '\n' && c != ';')
1764 t->left = dogroup(0);
1772 t->type = c == WHILE ? TWHILE : TUNTIL;
1774 t->right = dogroup(1);
1786 musthave(IN, CONTIN);
1789 t->left = caselist();
1800 t->right = thenpart();
1809 musthave(WORD, 0); /* gets name of file */
1810 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1812 word(yylval.cp); /* add word to wdlist */
1813 word(NOWORD); /* terminate wdlist */
1814 t->words = copyw(); /* dup wdlist */
1824 DBGPRINTF(("COMMAND: returning %p\n", t));
1829 static struct op *dowholefile(int type, int mark)
1833 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1838 t = block(type, t, NOBLOCK, NOWORDS);
1839 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1843 static struct op *dogroup(int onlydone)
1849 if (c == DONE && onlydone)
1858 static struct op *thenpart(void)
1871 if (t->left == NULL)
1873 t->right = elsepart();
1877 static struct op *elsepart(void)
1882 switch (c = yylex(0)) {
1893 t->right = thenpart();
1902 static struct op *caselist(void)
1907 while ((peeksym = yylex(CONTIN)) != ESAC) {
1908 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1909 t = list(t, casepart());
1912 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1916 static struct op *casepart(void)
1920 DBGPRINTF7(("CASEPART: enter...\n"));
1924 t->words = pattern();
1927 peeksym = yylex(CONTIN);
1928 if (peeksym != ESAC)
1929 musthave(BREAK, CONTIN);
1931 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
1936 static char **pattern(void)
1953 static char **wordlist(void)
1963 while ((c = yylex(0)) == WORD)
1971 * supporting functions
1973 static struct op *list(struct op *t1, struct op *t2)
1975 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
1982 return block(TLIST, t1, t2, NOWORDS);
1985 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
1989 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
1997 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2003 /* See if given string is a shell multiline (FOR, IF, etc) */
2004 static int rlookup(char *n)
2006 const struct res *rp;
2008 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2010 for (rp = restab; rp->r_name; rp++)
2011 if (strcmp(rp->r_name, n) == 0) {
2012 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2013 return rp->r_val; /* Return numeric code for shell multiline */
2016 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2017 return 0; /* Not a shell multiline */
2020 static struct op *newtp(void)
2024 t = (struct op *) tree(sizeof(*t));
2032 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2037 static struct op *namelist(struct op *t)
2040 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2041 T_CMD_NAMES[t->type], iolist));
2044 iolist = addword((char *) NULL, iolist);
2045 t->ioact = copyio();
2049 if (t->type != TCOM) {
2050 if (t->type != TPAREN && t->ioact != NULL) {
2051 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2052 t->ioact = t->left->ioact;
2053 t->left->ioact = NULL;
2064 static char **copyw(void)
2068 wd = getwords(wdlist);
2073 static void word(char *cp)
2075 wdlist = addword(cp, wdlist);
2078 static struct ioword **copyio(void)
2080 struct ioword **iop;
2082 iop = (struct ioword **) getwords(iolist);
2087 static struct ioword *io(int u, int f, char *cp)
2091 iop = (struct ioword *) tree(sizeof(*iop));
2095 iolist = addword((char *) iop, iolist);
2099 static int yylex(int cf)
2119 line[LINELIM - 1] = '\0';
2122 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2127 if (any(c, "0123456789")) {
2130 if (c1 == '<' || c1 == '>') {
2139 case '#': /* Comment, skip to next newline or End-of-string */
2140 while ((c = my_getc(0)) != '\0' && c != '\n');
2145 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2149 DBGPRINTF9(("YYLEX: found $\n"));
2153 c = collect(c, '}');
2172 /* If more chars process them, else return NULL char */
2190 if (multiline || cf & CONTIN) {
2191 if (interactive && e.iop <= iostack) {
2192 #if ENABLE_FEATURE_EDITING
2193 current_prompt = cprompt->value;
2195 prs(cprompt->value);
2212 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2213 if (e.linep >= elinep)
2214 err("word too long");
2221 if (any(c, "\"'`$"))
2234 yylval.cp = strsave(line, areanum);
2239 static int collect(int c, int c1)
2243 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2246 while ((c = my_getc(c1)) != c1) {
2255 if (interactive && c == '\n' && e.iop <= iostack) {
2256 #if ENABLE_FEATURE_EDITING
2257 current_prompt = cprompt->value;
2259 prs(cprompt->value);
2267 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2272 /* "multiline commands" helper func */
2273 /* see if next 2 chars form a shell multiline */
2274 static int dual(int c)
2279 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2281 *cp++ = c; /* c is the given "peek" char */
2282 *cp++ = my_getc(0); /* get next char of input */
2283 *cp = '\0'; /* add EOS marker */
2285 c = rlookup(s); /* see if 2 chars form a shell multiline */
2287 unget(*--cp); /* String is not a shell multiline, put peek char back */
2289 return c; /* String is multiline, return numeric multiline (restab) code */
2292 static void diag(int ec)
2296 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2299 if (c == '>' || c == '<') {
2302 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2305 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2306 if (c != '&' || yylval.i == IOHERE)
2312 static char *tree(unsigned size)
2318 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2319 prs("command line too complicated\n");
2329 /* -------- exec.c -------- */
2336 static int execute(struct op *t, int *pin, int *pout, int act)
2339 volatile int i, rv, a;
2340 char *cp, **wp, **wp2;
2342 struct op *outtree_save;
2346 /* Avoid longjmp clobbering */
2351 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2355 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2356 t->type, T_CMD_NAMES[t->type],
2357 ((t->words == NULL) ? "NULL" : t->words[0])));
2361 wp = (wp2 = t->words) != NULL
2362 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2367 DBGPRINTF3(("EXECUTE: TDOT\n"));
2369 outtree_save = outtree;
2371 newfile(evalstr(t->words[0], DOALL));
2373 t->left = dowholefile(TLIST, 0);
2376 outtree = outtree_save;
2379 rv = execute(t->left, pin, pout, 0);
2381 rv = execute(t->right, pin, pout, 0);
2385 rv = execute(t->left, pin, pout, 0);
2389 rv = forkexec(t, pin, pout, act, wp);
2399 pv[0] = remap(pv[0]);
2400 pv[1] = remap(pv[1]);
2401 (void) execute(t->left, pin, pv, 0);
2402 rv = execute(t->right, pv, pout, 0);
2407 (void) execute(t->left, pin, pout, 0);
2408 rv = execute(t->right, pin, pout, 0);
2413 int hinteractive = interactive;
2415 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2418 if (i == 0) { /* child */
2419 signal(SIGINT, SIG_IGN);
2420 signal(SIGQUIT, SIG_IGN);
2422 signal(SIGTERM, SIG_DFL);
2426 open(bb_dev_null, 0);
2428 _exit(execute(t->left, pin, pout, FEXEC));
2430 interactive = hinteractive;
2432 setval(lookup("!"), putn(i));
2447 rv = execute(t->left, pin, pout, 0);
2449 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2450 rv = execute(t1, pin, pout, 0);
2461 while (*wp++ != NULL);
2463 vp = lookup(t->str);
2464 while (setjmp(bc.brkpt))
2468 for (t1 = t->left; i-- && *wp != NULL;) {
2470 rv = execute(t1, pin, pout, 0);
2472 brklist = brklist->nextlev;
2477 while (setjmp(bc.brkpt))
2482 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2483 rv = execute(t->right, pin, pout, 0);
2484 brklist = brklist->nextlev;
2489 if (t->right != NULL) {
2490 rv = !execute(t->left, pin, pout, 0) ?
2491 execute(t->right->left, pin, pout, 0) :
2492 execute(t->right->right, pin, pout, 0);
2497 cp = evalstr(t->str, DOSUB | DOTRIM);
2501 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2502 ((t->str == NULL) ? "NULL" : t->str),
2503 ((cp == NULL) ? "NULL" : cp)));
2505 t1 = findcase(t->left, cp);
2507 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2508 rv = execute(t1, pin, pout, 0);
2509 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2518 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2526 rv = execute(t1, pin, pout, 0);
2539 if (interactive && intr) {
2550 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2555 forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2559 builtin_func_ptr shcom = NULL;
2562 struct ioword **iopp;
2572 struct brkcon *hbrklist;
2576 /* Avoid longjmp clobbering */
2586 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2588 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2589 ((t->words == NULL) ? "NULL" : t->words[0])));
2593 rv = -1; /* system-detected error */
2594 if (t->type == TCOM) {
2595 while ((cp = *wp++) != NULL);
2598 /* strip all initial assignments */
2599 /* not correct wrt PATH=yyy command etc */
2601 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2603 echo(cp ? wp : owp);
2606 if (cp == NULL && t->ioact == NULL) {
2607 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2609 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2610 return setstatus(0);
2613 shcom = inbuilt(cp);
2620 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2623 if (shcom == NULL && (f & FEXEC) == 0) {
2624 /* Save values in case the child process alters them */
2628 hinteractive = interactive;
2633 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2638 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2642 if (newpid > 0) { /* Parent */
2643 /* Restore values */
2647 interactive = hinteractive;
2658 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2661 /* Must be the child process, pid should be 0 */
2662 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2665 signal(SIGINT, SIG_IGN);
2666 signal(SIGQUIT, SIG_IGN);
2677 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2682 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2683 err("piping to/from shell builtins not yet done");
2701 if (shcom != NULL && shcom != doexec) {
2703 err(": cannot redirect shell command");
2709 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2717 i = setstatus((*shcom) (t));
2720 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2724 /* should use FIOCEXCL */
2725 for (i = FDBASE; i < NOFILE; i++)
2728 signal(SIGINT, SIG_DFL);
2729 signal(SIGQUIT, SIG_DFL);
2732 if (t->type == TPAREN)
2733 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2737 cp = rexecve(wp[0], wp, makenv(0, NULL));
2744 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2752 * 0< 1> are ignored as required
2755 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2758 char *cp = NULL, *msg;
2760 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2763 if (iop->io_unit == IODEFAULT) /* take default */
2764 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2766 if (pipein && iop->io_unit == 0)
2769 if (pipeout && iop->io_unit == 1)
2772 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2773 if ((iop->io_flag & IOHERE) == 0) {
2774 cp = iop->io_name; /* huh?? */
2775 cp = evalstr(cp, DOSUB | DOTRIM);
2780 if (iop->io_flag & IODUP) {
2781 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2783 err(": illegal >& argument");
2787 iop->io_flag = IOCLOSE;
2788 iop->io_flag &= ~(IOREAD | IOWRITE);
2790 switch (iop->io_flag) {
2796 case IOHERE | IOXHERE:
2797 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2801 case IOWRITE | IOCAT:
2804 lseek(u, (long) 0, SEEK_END);
2808 u = creat(cp, 0666);
2812 u = dup2(*cp - '0', iop->io_unit);
2816 close(iop->io_unit);
2825 if (u != iop->io_unit) {
2826 dup2(u, iop->io_unit);
2832 static void echo(char **wp)
2837 for (i = 0; wp[i]; i++) {
2845 static struct op **find1case(struct op *t, char *w)
2852 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2856 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2857 T_CMD_NAMES[t->type]));
2859 if (t->type == TLIST) {
2860 tp = find1case(t->left, w);
2862 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2865 t1 = t->right; /* TPAT */
2869 for (wp = t1->words; *wp;) {
2870 cp = evalstr(*wp++, DOSUB);
2871 if (cp && gmatch(w, cp)) {
2872 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2878 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2882 static struct op *findcase(struct op *t, char *w)
2886 tp = find1case(t, w);
2887 return tp != NULL ? *tp : NULL;
2891 * Enter a new loop level (marked for break/continue).
2893 static void brkset(struct brkcon *bc)
2895 bc->nextlev = brklist;
2900 * Wait for the last process created.
2901 * Print a message for each process found
2902 * that was killed by a signal.
2903 * Ignore interrupt signals while waiting
2904 * unless `canintr' is true.
2906 static int waitfor(int lastpid, int canintr)
2910 int oheedint = heedint;
2917 if (errno != EINTR || canintr)
2923 if (signame[rv] != NULL) {
2924 if (pid != lastpid) {
2931 if (pid != lastpid) {
2940 prs(" - core dumped");
2941 if (rv >= NSIGNAL || signame[rv])
2947 } while (pid != lastpid);
2962 static int setstatus(int s)
2965 setval(lookup("?"), putn(s));
2970 * PATH-searching interface to execve.
2971 * If getenv("PATH") were kept up-to-date,
2972 * execvp might be used.
2974 static char *rexecve(char *c, char **v, char **envp)
2978 int eacces = 0, asis = 0;
2981 if (ENABLE_FEATURE_SH_STANDALONE_SHELL) {
2983 if (find_applet_by_name(name)) {
2984 /* We have to exec here since we vforked. Running
2985 * run_applet_by_name() won't work and bad things
2987 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
2991 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
2993 sp = any('/', c) ? "" : path->value;
2995 while (asis || *sp != '\0') {
2998 for (; *sp != '\0'; tp++) {
3001 asis = (*sp == '\0');
3007 for (i = 0; (*tp++ = c[i++]) != '\0';);
3009 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3011 execve(e.linep, v, envp);
3018 execve(DEFAULT_SHELL, v, envp);
3023 return (char *) bb_msg_memory_exhausted;
3026 return "argument list too long";
3033 return errno == ENOENT ? "not found" : "cannot execute";
3037 * Run the command produced by generator `f'
3038 * applied to stream `arg'.
3040 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3043 struct wdblock *swdlist;
3044 struct wdblock *siolist;
3050 /* Avoid longjmp clobbering */
3054 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3055 areanum, outtree, failpt));
3065 if (newenv(setjmp(errpt)) == 0) {
3072 if (setjmp(failpt) == 0 && yyparse() == 0)
3073 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3076 DBGPRINTF(("RUN: error from newenv()!\n"));
3083 freearea(areanum--);
3088 /* -------- do.c -------- */
3091 * built-in commands: doX
3094 static int dohelp(struct op *t)
3097 const struct builtincmd *x;
3099 puts("\nBuilt-in commands:\n"
3100 "-------------------");
3102 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3105 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3111 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
3114 const struct BB_applet *applet;
3116 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3120 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3129 return EXIT_SUCCESS;
3134 static int dolabel(struct op *t)
3139 static int dochdir(struct op *t)
3145 cp = homedir->value;
3147 er = ": no home directory";
3148 } else if (chdir(cp) < 0)
3149 er = ": bad directory";
3152 prs(cp != NULL ? cp : "cd");
3157 static int doshift(struct op *t)
3161 n = t->words[1] ? getn(t->words[1]) : 1;
3163 err("nothing to shift");
3169 setval(lookup("#"), putn(dolc));
3174 * execute login and newgrp directly
3176 static int dologin(struct op *t)
3181 signal(SIGINT, SIG_DFL);
3182 signal(SIGQUIT, SIG_DFL);
3184 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3191 static int doumask(struct op *t)
3200 for (n = 3 * 4; (n -= 3) >= 0;)
3201 putc('0' + ((i >> n) & 07), stderr);
3204 /* huh??? '8','9' are not allowed! */
3205 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3206 n = n * 8 + (*cp - '0');
3212 static int doexec(struct op *t)
3219 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3225 if (setjmp(failpt) == 0)
3226 execute(t, NOPIPE, NOPIPE, FEXEC);
3232 static int dodot(struct op *t)
3239 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)));
3243 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3246 DBGPRINTF(("DODOT: cp is %s\n", cp));
3248 sp = any('/', cp) ? ":" : path->value;
3250 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3251 ((sp == NULL) ? "NULL" : sp),
3252 ((e.linep == NULL) ? "NULL" : e.linep)));
3256 while (*sp && (*tp = *sp++) != ':')
3261 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3264 i = open(e.linep, 0);
3268 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3270 next(maltmp); /* Basically a PUSHIO */
3272 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3284 static int dowait(struct op *t)
3296 setstatus(waitfor(i, 1));
3300 static int doread(struct op *t)
3306 if (t->words[1] == NULL) {
3307 err("Usage: read name ...");
3310 for (wp = t->words + 1; *wp; wp++) {
3311 for (cp = e.linep; !nl && cp < elinep - 1; cp++) {
3312 nb = read(0, cp, sizeof(*cp));
3313 if (nb != sizeof(*cp))
3316 if (nl || (wp[1] && any(*cp, ifs->value)))
3322 setval(lookup(*wp), e.linep);
3327 static int doeval(struct op *t)
3329 return RUN(awordlist, t->words + 1, wdchar);
3332 static int dotrap(struct op *t)
3337 if (t->words[1] == NULL) {
3338 for (i = 0; i <= _NSIG; i++)
3347 resetsig = isdigit(*t->words[1]);
3348 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3349 n = getsig(t->words[i]);
3353 if (*t->words[1] != '\0') {
3354 trap[n] = strsave(t->words[1], 0);
3363 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3371 static int getsig(char *s)
3376 if (n < 0 || n > _NSIG) {
3377 err("trap: bad signal number");
3383 static void setsig(int n, sighandler_t f)
3387 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3393 static int getn(char *as)
3404 for (n = 0; isdigit(*s); s++)
3405 n = (n * 10) + (*s - '0');
3408 err(": bad number");
3413 static int dobreak(struct op *t)
3415 return brkcontin(t->words[1], 1);
3418 static int docontinue(struct op *t)
3420 return brkcontin(t->words[1], 0);
3423 static int brkcontin(char *cp, int val)
3428 nl = cp == NULL ? 1 : getn(cp);
3435 brklist = bc->nextlev;
3438 err("bad break/continue level");
3442 longjmp(bc->brkpt, 1);
3446 static int doexit(struct op *t)
3453 setstatus(getn(cp));
3455 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3462 static int doexport(struct op *t)
3464 rdexp(t->words + 1, export, EXPORT);
3468 static int doreadonly(struct op *t)
3470 rdexp(t->words + 1, ronly, RONLY);
3474 static void rdexp(char **wp, void (*f) (struct var *), int key)
3476 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3477 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3480 for (; *wp != NULL; wp++) {
3481 if (isassign(*wp)) {
3485 for (cp = *wp; *cp != '='; cp++);
3497 static void badid(char *s)
3500 err(": bad identifier");
3503 static int doset(struct op *t)
3511 for (vp = vlist; vp; vp = vp->next)
3512 varput(vp->name, 1);
3516 /* bad: t->words++; */
3517 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3519 flag['x'] = flag['v'] = 0;
3529 if (*cp >= 'a' && *cp <= 'z')
3538 t->words[0] = dolv[0];
3539 for (n = 1; t->words[n]; n++)
3540 setarea((char *) t->words[n], 0);
3543 setval(lookup("#"), putn(dolc));
3544 setarea((char *) (dolv - 1), 0);
3549 static void varput(char *s, int out)
3551 if (isalnum(*s) || *s == '_') {
3552 write(out, s, strlen(s));
3553 write(out, "\n", 1);
3559 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3560 * This file contains code for the times builtin.
3562 static int dotimes(struct op *t)
3565 long clk_tck = sysconf(_SC_CLK_TCK);
3568 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3569 (int) (buf.tms_utime / clk_tck / 60),
3570 ((double) buf.tms_utime) / clk_tck,
3571 (int) (buf.tms_stime / clk_tck / 60),
3572 ((double) buf.tms_stime) / clk_tck,
3573 (int) (buf.tms_cutime / clk_tck / 60),
3574 ((double) buf.tms_cutime) / clk_tck,
3575 (int) (buf.tms_cstime / clk_tck / 60),
3576 ((double) buf.tms_cstime) / clk_tck);
3581 static builtin_func_ptr inbuilt(char *s) {
3582 const struct builtincmd *bp;
3584 for (bp = builtincmds; bp->name != NULL; bp++)
3585 if (strcmp(bp->name, s) == 0)
3586 return bp->builtinfunc;
3591 /* -------- eval.c -------- */
3596 * blank interpretation
3601 static char **eval(char **ap, int f)
3609 /* Avoid longjmp clobbering */
3614 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3620 if (newenv(setjmp(errpt)) == 0) {
3621 while (*ap && isassign(*ap))
3622 expand(*ap++, &wb, f & ~DOGLOB);
3624 for (wf = ap; *wf; wf++) {
3626 expand(*wf, &wb, f & ~DOGLOB);
3629 for (wb = addword((char *) 0, wb); *ap; ap++) {
3630 if (!flag['k'] || !isassign(*ap))
3631 expand(*ap, &wb, f & ~DOKEY);
3633 wb = addword((char *) 0, wb);
3639 return gflg ? (char **) NULL : wp;
3643 * Make the exported environment from the exported
3644 * names in the dictionary. Keyword assignments
3645 * will already have been done.
3647 static char **makenv(int all, struct wdblock *wb)
3651 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3653 for (vp = vlist; vp; vp = vp->next)
3654 if (all || vp->status & EXPORT)
3655 wb = addword(vp->name, wb);
3656 wb = addword((char *) 0, wb);
3657 return getwords(wb);
3660 static char *evalstr(char *cp, int f)
3664 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3667 if (expand(cp, &wb, f)) {
3668 if (wb == NULL || wb->w_nword == 0
3669 || (cp = wb->w_words[0]) == NULL)
3677 static int expand(char *cp, struct wdblock **wbp, int f)
3682 /* Avoid longjmp clobbering */
3686 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3693 if (!anys("$`'\"", cp) &&
3694 !anys(ifs->value, cp) && ((f & DOGLOB) == 0 || !anys("[*?", cp))) {
3695 cp = strsave(cp, areanum);
3698 *wbp = addword(cp, *wbp);
3702 if (newenv(setjmp(errpt)) == 0) {
3703 PUSHIO(aword, cp, strchar);
3705 while ((cp = blank(f)) && gflg == 0) {
3707 cp = strsave(cp, areanum);
3708 if ((f & DOGLOB) == 0) {
3711 *wbp = addword(cp, *wbp);
3713 *wbp = glob(cp, *wbp);
3722 * Blank interpretation and quoting
3724 static char *blank(int f)
3728 int scanequals, foundequals;
3730 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3733 scanequals = f & DOKEY;
3737 c = subgetc('"', foundequals);
3746 if (f & DOBLANK && any(c, ifs->value))
3755 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3758 if (c == '\'' || !any(c, "$`\""))
3765 if (!isalpha(c) && c != '_')
3768 c = subgetc('"', foundequals);
3770 f & (DOBLANK && any(c, ifs->value)) ||
3771 (!INSUB() && any(c, "\"'"))) {
3782 } else if (!isalnum(c) && c != '_')
3792 * Get characters, substituting for ` and $
3794 static int subgetc(char ec, int quoted)
3798 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3802 if (!INSUB() && ec != '\'') {
3804 if (grave(quoted) == 0)
3806 e.iop->task = XGRAVE;
3812 e.iop->task = XDOLL;
3821 * Prepare to generate the string returned by ${} substitution.
3823 static int dollar(int quoted)
3828 char *s, c, *cp = NULL;
3831 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3837 if (isalpha(c) || c == '_') {
3838 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3839 if (e.linep < elinep)
3846 otask = e.iop->task;
3848 e.iop->task = XOTHER;
3849 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3850 if (e.linep < elinep)
3853 e.iop->task = otask;
3860 if (e.linep >= elinep) {
3861 err("string in ${} too long");
3867 for (cp = s + 1; *cp; cp++)
3868 if (any(*cp, "=-+?")) {
3873 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3875 /* currently this does not distinguish $* and $@ */
3876 /* should check dollar */
3878 PUSHIO(awordlist, dolv + 1, dolchar);
3880 } else { /* trap the nasty ${=} */
3891 err("cannot use ${...=...} with $n");
3900 dolp = strsave(cp, areanum);
3905 prs("missing value for ");
3912 } else if (c == '+')
3913 dolp = strsave(cp, areanum);
3914 if (flag['u'] && dolp == null) {
3915 prs("unset variable: ");
3920 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
3925 * Run the command in `...` and read its output.
3928 static int grave(int quoted)
3934 static char child_cmd[LINELIM];
3940 char *argument_list[4];
3941 struct wdblock *wb = NULL;
3944 /* Avoid longjmp clobbering */
3948 for (cp = e.iop->argp->aword; *cp != '`'; cp++)
3950 err("no closing `");
3954 /* string copy with dollar expansion */
3955 src = e.iop->argp->aword;
3960 while ((*src != '`') && (count < LINELIM)) {
3965 if (*src == '$' && !ignore && !ignore_once) {
3967 char var_name[LINELIM];
3968 char alt_value[LINELIM];
3981 var_name[var_index++] = *src++;
3982 while (isalnum(*src) || *src=='_')
3983 var_name[var_index++] = *src++;
3984 var_name[var_index] = 0;
3997 err("unclosed ${\n");
4002 while (*src && (*src != '}')) {
4003 alt_value[alt_index++] = *src++;
4005 alt_value[alt_index] = 0;
4007 err("unclosed ${\n");
4014 if (isalpha(*var_name)) {
4015 /* let subshell handle it instead */
4017 char *namep = var_name;
4025 char *altp = alt_value;
4033 wb = addword(lookup(var_name)->name, wb);
4037 vp = lookup(var_name);
4038 if (vp->value != null)
4039 value = (operator == '+') ?
4040 alt_value : vp->value;
4041 else if (operator == '?') {
4044 } else if (alt_index && (operator != '+')) {
4046 if (operator == '=')
4051 while (*value && (count < LINELIM)) {
4064 if (openpipe(pf) < 0)
4067 while ((i = vfork()) == -1 && errno == EAGAIN);
4069 DBGPRINTF3(("GRAVE: i is %p\n", io));
4073 err((char *) bb_msg_memory_exhausted);
4077 waitpid(i, NULL, 0);
4078 e.iop->argp->aword = ++cp;
4080 PUSHIO(afile, remap(pf[0]),
4081 (int (*)(struct ioarg *)) ((quoted) ? qgravechar :
4085 /* allow trapped signals */
4086 /* XXX - Maybe this signal stuff should go as well? */
4087 for (j = 0; j <= _NSIG; j++)
4088 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4094 argument_list[0] = (char *) DEFAULT_SHELL;
4095 argument_list[1] = "-c";
4096 argument_list[2] = child_cmd;
4097 argument_list[3] = 0;
4099 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4100 prs(argument_list[0]);
4107 static char *unquote(char *as)
4118 /* -------- glob.c -------- */
4124 #define scopy(x) strsave((x), areanum)
4126 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4128 static struct wdblock *cl, *nl;
4129 static char spcl[] = "[?*";
4131 static struct wdblock *glob(char *cp, struct wdblock *wb)
4139 for (pp = cp; *pp; pp++)
4142 else if (!any(*pp & ~QUOTE, spcl))
4145 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4146 nl = newword(cl->w_nword * 2);
4147 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4148 for (pp = cl->w_words[i]; *pp; pp++)
4149 if (any(*pp, spcl)) {
4150 globname(cl->w_words[i], pp);
4154 nl = addword(scopy(cl->w_words[i]), nl);
4156 for (i = 0; i < cl->w_nword; i++)
4157 DELETE(cl->w_words[i]);
4160 for (i = 0; i < cl->w_nword; i++)
4161 unquote(cl->w_words[i]);
4162 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4164 for (i = 0; i < cl->w_nword; i++)
4165 wb = addword(cl->w_words[i], wb);
4170 wb = addword(unquote(cp), wb);
4174 static void globname(char *we, char *pp)
4177 char *name, *gp, *dp;
4181 char dname[NAME_MAX + 1];
4184 for (np = we; np != pp; pp--)
4187 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4191 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4200 dname[NAME_MAX] = '\0';
4201 while ((de = readdir(dirp)) != NULL) {
4202 /* XXX Hmmm... What this could be? (abial) */
4204 if (ent[j].d_ino == 0)
4207 strncpy(dname, de->d_name, NAME_MAX);
4208 if (dname[0] == '.')
4211 for (k = 0; k < NAME_MAX; k++)
4212 if (any(dname[k], spcl))
4214 if (gmatch(dname, gp)) {
4215 name = generate(we, pp, dname, np);
4216 if (*np && !anys(np, spcl)) {
4217 if (stat(name, &dbuf)) {
4222 nl = addword(name, nl);
4231 * generate a pathname as below.
4232 * start..end1 / middle end
4233 * the slashes come for free
4235 static char *generate(char *start1, char *end1, char *middle, char *end)
4240 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4241 for (xp = start1; xp != end1;)
4243 for (xp = middle; (*op++ = *xp++) != '\0';);
4245 for (xp = end; (*op++ = *xp++) != '\0';);
4249 static int anyspcl(struct wdblock *wb)
4255 for (i = 0; i < wb->w_nword; i++)
4256 if (anys(spcl, *wd++))
4261 static int xstrcmp(char *p1, char *p2)
4263 return strcmp(*(char **) p1, *(char **) p2);
4266 /* -------- word.c -------- */
4268 static struct wdblock *newword(int nw)
4272 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4278 static struct wdblock *addword(char *wd, struct wdblock *wb)
4280 struct wdblock *wb2;
4284 wb = newword(NSTART);
4286 if (nw >= wb->w_bsize) {
4287 wb2 = newword(nw * 2);
4288 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4289 nw * sizeof(char *));
4294 wb->w_words[wb->w_nword++] = wd;
4299 char **getwords(struct wdblock *wb)
4306 if (wb->w_nword == 0) {
4310 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4311 memcpy((char *) wd, (char *) wb->w_words, nb);
4312 DELETE(wb); /* perhaps should done by caller */
4316 static int (*func) (char *, char *);
4319 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4323 glob1(a0, a0 + a1 * a2);
4326 static void glob1(char *base, char *lim)
4337 n = (int) (lim - base);
4340 n = v2 * (n / (2 * v2));
4341 hptr = lptr = base + n;
4346 c = (*func) (i, lptr);
4360 c = (*func) (hptr, j);
4384 if (lptr - base >= lim - hptr) {
4385 glob1(hptr + v2, lim);
4400 static void glob2(char *i, char *j)
4402 char *index1, *index2, c;
4410 *index1++ = *index2;
4415 static void glob3(char *i, char *j, char *k)
4417 char *index1, *index2, *index3;
4427 *index1++ = *index3;
4428 *index3++ = *index2;
4433 /* -------- io.c -------- */
4439 static int my_getc(int ec)
4443 if (e.linep > elinep) {
4444 while ((c = readc()) != '\n' && c);
4445 err("input line too long");
4450 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4453 if (c == '\n' && ec != '\"')
4461 static void unget(int c)
4463 if (e.iop >= e.iobase)
4467 static int eofc(void)
4469 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4472 static int readc(void)
4476 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4478 for (; e.iop >= e.iobase; e.iop--) {
4479 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4485 if (e.iop->prev != 0) {
4486 c = (*e.iop->iofn)(e.iop->argp, e.iop);
4492 if (e.iop == iostack)
4497 if (e.iop->task == XIO && e.iop->prev != '\n') {
4499 if (e.iop == iostack)
4504 if (e.iop->task == XIO) {
4509 if (interactive && e.iop == iostack + 1) {
4510 #if ENABLE_FEATURE_EDITING
4511 current_prompt = prompt->value;
4519 if (e.iop >= iostack) {
4520 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4524 DBGPRINTF(("READC: leave()...\n"));
4531 static void ioecho(char c)
4534 write(2, &c, sizeof c);
4538 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4540 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4541 argp->afid, e.iop));
4543 /* Set env ptr for io source to next array spot and check for array overflow */
4544 if (++e.iop >= &iostack[NPUSH]) {
4546 err("Shell input nested too deeply");
4551 /* We did not overflow the NPUSH array spots so setup data structs */
4553 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4555 if (argp->afid != AFID_NOBUF)
4559 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4560 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4562 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4564 if (e.iop == &iostack[0])
4565 e.iop->argp->afbuf = &mainbuf;
4567 e.iop->argp->afbuf = &sharedbuf;
4569 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4570 /* This line appears to be active when running scripts from command line */
4571 if ((isatty(e.iop->argp->afile) == 0)
4572 && (e.iop == &iostack[0]
4573 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4574 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4575 bufid = AFID_ID; /* AFID_ID = 0 */
4577 e.iop->argp->afid = bufid; /* assign buffer id */
4580 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4581 iostack, e.iop, e.iop->argp->afbuf));
4582 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4583 &mainbuf, &sharedbuf, bufid, e.iop));
4587 e.iop->prev = ~'\n';
4592 if (fn == filechar || fn == linechar)
4594 else if (fn == (int (*)(struct ioarg *)) gravechar
4595 || fn == (int (*)(struct ioarg *)) qgravechar)
4596 e.iop->task = XGRAVE;
4598 e.iop->task = XOTHER;
4601 static struct io *setbase(struct io *ip)
4611 * Input generating functions
4615 * Produce the characters of a string, then a newline, then EOF.
4617 static int nlchar(struct ioarg *ap)
4621 if (ap->aword == NULL)
4632 * Given a list of words, produce the characters
4633 * in them, with a space after each word.
4635 static int wdchar(struct ioarg *ap)
4650 ap->awordlist = NULL;
4655 * Return the characters of a list of words,
4656 * producing a space between them.
4658 static int dolchar(struct ioarg *ap)
4662 wp = *ap->awordlist++;
4664 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4670 static int xxchar(struct ioarg *ap)
4674 if (ap->aword == NULL)
4685 * Produce the characters from a single word (string).
4687 static int strchar(struct ioarg *ap)
4689 if (ap->aword == NULL)
4691 return *ap->aword++;
4695 * Produce quoted characters from a single word (string).
4697 static int qstrchar(struct ioarg *ap)
4701 if (ap->aword == NULL)
4710 * Return the characters from a file.
4712 static int filechar(struct ioarg *ap)
4716 struct iobuf *bp = ap->afbuf;
4718 if (ap->afid != AFID_NOBUF) {
4719 i = (ap->afid != bp->id);
4720 if (i || bp->bufp == bp->ebufp) {
4722 lseek(ap->afile, ap->afpos, SEEK_SET);
4724 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4732 bp->ebufp = bp->bufp + i;
4736 return *bp->bufp++ & 0177;
4738 #if ENABLE_FEATURE_EDITING
4739 if (interactive && isatty(ap->afile)) {
4740 static char mycommand[BUFSIZ];
4741 static int position = 0, size = 0;
4743 while (size == 0 || position >= size) {
4744 read_line_input(current_prompt, mycommand, BUFSIZ, line_input_state);
4745 size = strlen(mycommand);
4748 c = mycommand[position];
4753 i = safe_read(ap->afile, &c, sizeof(c));
4754 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4758 * Return the characters from a here temp file.
4760 static int herechar(struct ioarg *ap)
4764 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4772 * Return the characters produced by a process (`...`).
4773 * Quote them if required, and remove any trailing newline characters.
4775 static int gravechar(struct ioarg *ap, struct io *iop)
4779 c = qgravechar(ap, iop) & ~QUOTE;
4785 static int qgravechar(struct ioarg *ap, struct io *iop)
4789 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4794 return '\n' | QUOTE;
4798 } else if ((c = filechar(ap)) == '\n') {
4800 while ((c = filechar(ap)) == '\n')
4808 return c != 0 ? c | QUOTE : 0;
4812 * Return a single command (usually the first line) from a file.
4814 static int linechar(struct ioarg *ap)
4822 ap->afile = -1; /* illegal value */
4829 * remap fd into Shell's fd space
4831 static int remap(int fd)
4837 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
4840 for (i = 0; i < NOFILE; i++)
4847 } while (fd >= 0 && fd < e.iofd);
4849 for (i = 0; i < NOFILE; i++)
4854 err("too many files open in shell");
4860 static int openpipe(int *pv)
4866 err("can't create pipe - try again");
4870 static void closepipe(int *pv)
4878 /* -------- here.c -------- */
4884 static void markhere(char *s, struct ioword *iop)
4886 struct here *h, *lh;
4888 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4890 h = (struct here *) space(sizeof(struct here));
4894 h->h_tag = evalstr(s, DOSUB);
4904 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4905 if (lh->h_next == 0) {
4911 iop->io_flag |= IOHERE | IOXHERE;
4912 for (s = h->h_tag; *s; s++) {
4914 iop->io_flag &= ~IOXHERE;
4918 h->h_dosub = iop->io_flag & IOXHERE;
4921 static void gethere(void)
4923 struct here *h, *hp;
4925 DBGPRINTF7(("GETHERE: enter...\n"));
4927 /* Scan here files first leaving inhere list in place */
4928 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
4929 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
4931 /* Make inhere list active - keep list intact for scraphere */
4933 hp->h_next = acthere;
4939 static void readhere(char **name, char *s, int ec)
4942 char tname[30] = ".msh_XXXXXX";
4945 char myline[LINELIM + 1];
4948 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
4950 tf = mkstemp(tname);
4954 *name = strsave(tname, areanum);
4956 if (newenv(setjmp(errpt)) != 0)
4959 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
4962 if (interactive && e.iop <= iostack) {
4963 #if ENABLE_FEATURE_EDITING
4964 current_prompt = cprompt->value;
4966 prs(cprompt->value);
4970 while ((c = my_getc(ec)) != '\n' && c) {
4973 if (thenext >= &myline[LINELIM]) {
4980 if (strcmp(s, myline) == 0 || c == 0)
4983 write(tf, myline, (int) (thenext - myline));
4986 prs("here document `");
4996 * open here temp file.
4997 * if unquoted here, expand here temp file into second temp file.
4999 static int herein(char *hname, int xdoll)
5005 /* Avoid longjmp clobbering */
5011 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5013 hf = open(hname, 0);
5019 char tname[30] = ".msh_XXXXXX";
5022 tf = mkstemp(tname);
5026 if (newenv(setjmp(errpt)) == 0) {
5027 PUSHIO(afile, hf, herechar);
5029 while ((c = subgetc(0, 0)) != 0) {
5031 write(tf, &c, sizeof c);
5037 tf = open(tname, 0);
5044 static void scraphere(void)
5048 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5050 for (h = inhere; h != NULL; h = h->h_next) {
5051 if (h->h_iop && h->h_iop->io_name)
5052 unlink(h->h_iop->io_name);
5057 /* unlink here temp files before a freearea(area) */
5058 static void freehere(int area)
5060 struct here *h, *hl;
5062 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5065 for (h = acthere; h != NULL; h = h->h_next)
5066 if (getarea((char *) h) >= area) {
5067 if (h->h_iop->io_name != NULL)
5068 unlink(h->h_iop->io_name);
5070 acthere = h->h_next;
5072 hl->h_next = h->h_next;
5078 /* -------- sh.c -------- */
5083 int msh_main(int argc, char **argv)
5089 int (*iof) (struct ioarg *);
5091 #if ENABLE_FEATURE_EDITING
5092 line_input_state = new_line_input_t(FOR_SHELL);
5095 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5101 assign(*ap++, !COPYV);
5102 for (ap = environ; *ap;)
5103 export(lookup(*ap++));
5108 shell = lookup("SHELL");
5109 if (shell->value == null)
5110 setval(shell, (char *)DEFAULT_SHELL);
5113 homedir = lookup("HOME");
5114 if (homedir->value == null)
5115 setval(homedir, "/");
5118 setval(lookup("$"), putn(getpid()));
5120 path = lookup("PATH");
5121 if (path->value == null) {
5123 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
5125 setval(path, "/bin:/usr/bin");
5129 ifs = lookup("IFS");
5130 if (ifs->value == null)
5131 setval(ifs, " \t\n");
5134 mshdbg_var = lookup("MSHDEBUG");
5135 if (mshdbg_var->value == null)
5136 setval(mshdbg_var, "0");
5139 prompt = lookup("PS1");
5140 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5141 if (prompt->value == null)
5143 setval(prompt, DEFAULT_USER_PROMPT);
5144 if (geteuid() == 0) {
5145 setval(prompt, DEFAULT_ROOT_PROMPT);
5146 prompt->status &= ~EXPORT;
5148 cprompt = lookup("PS2");
5149 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5150 if (cprompt->value == null)
5152 setval(cprompt, "> ");
5158 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5159 for (s = argv[0] + 1; *s; s++)
5162 prompt->status &= ~EXPORT;
5163 cprompt->status &= ~EXPORT;
5165 setval(cprompt, "");
5168 PUSHIO(aword, *++argv, iof = nlchar);
5176 /* standard input */
5180 prompt->status &= ~EXPORT;
5188 if (*s >= 'a' && *s <= 'z')
5196 if (iof == filechar && --argc > 0) {
5198 setval(cprompt, "");
5199 prompt->status &= ~EXPORT;
5200 cprompt->status &= ~EXPORT;
5202 /* Shell is non-interactive, activate printf-based debug */
5204 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5208 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5212 exit(1); /* Exit on error */
5218 /* This won't be true if PUSHIO has been called, say from newfile() above */
5219 if (e.iop < iostack) {
5220 PUSHIO(afile, 0, iof);
5221 if (isatty(0) && isatty(1) && !cflag) {
5223 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5225 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
5227 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
5229 printf("Enter 'help' for a list of built-in commands.\n\n");
5234 signal(SIGQUIT, qflag);
5235 if (name && name[0] == '-') {
5237 f = open(".profile", 0);
5240 f = open("/etc/profile", 0);
5245 signal(SIGTERM, sig);
5247 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5248 signal(SIGINT, onintr);
5253 for (ap = ++argv; --argc > 0;) {
5255 if (assign(*ap, !COPYV)) {
5256 dolc--; /* keyword */
5262 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5264 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
5267 if (interactive && e.iop <= iostack) {
5268 #if ENABLE_FEATURE_EDITING
5269 current_prompt = prompt->value;
5275 /* Ensure that getenv("PATH") stays current */
5276 setenv("PATH", path->value, 1);
5279 DBGPRINTF(("MSH_MAIN: returning.\n"));
5284 * Copyright (c) 1987,1997, Prentice Hall
5285 * All rights reserved.
5287 * Redistribution and use of the MINIX operating system in source and
5288 * binary forms, with or without modification, are permitted provided
5289 * that the following conditions are met:
5291 * Redistributions of source code must retain the above copyright
5292 * notice, this list of conditions and the following disclaimer.
5294 * Redistributions in binary form must reproduce the above
5295 * copyright notice, this list of conditions and the following
5296 * disclaimer in the documentation and/or other materials provided
5297 * with the distribution.
5299 * Neither the name of Prentice Hall nor the names of the software
5300 * authors or contributors may be used to endorse or promote
5301 * products derived from this software without specific prior
5302 * written permission.
5304 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5305 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5306 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5307 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5308 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5309 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5310 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5311 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5312 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5313 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5314 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5315 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.