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 void err(const char *s);
288 static int anys(const char *s1, const char *s2);
289 static int any(int c, const char *s);
290 static void next(int f);
291 static void setdash(void);
292 static void onecommand(void);
293 static void runtrap(int i);
294 static int gmatch(char *s, char *p);
297 /* -------- area stuff -------- */
299 #define REGSIZE sizeof(struct region)
301 /* #define SHRINKBY (64) */
305 #define ALIGN (sizeof(int)-1)
314 /* -------- grammar stuff -------- */
339 /* Added for "." file expansion */
342 #define YYERRCODE 300
345 #define CONTIN 01 /* skip new lines to complete command */
347 #define SYNTAXERR zzerr()
349 static struct op *pipeline(int cf);
350 static struct op *andor(void);
351 static struct op *c_list(void);
352 static int synio(int cf);
353 static void musthave(int c, int cf);
354 static struct op *simple(void);
355 static struct op *nested(int type, int mark);
356 static struct op *command(int cf);
357 static struct op *dogroup(int onlydone);
358 static struct op *thenpart(void);
359 static struct op *elsepart(void);
360 static struct op *caselist(void);
361 static struct op *casepart(void);
362 static char **pattern(void);
363 static char **wordlist(void);
364 static struct op *list(struct op *t1, struct op *t2);
365 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
366 static struct op *newtp(void);
367 static struct op *namelist(struct op *t);
368 static char **copyw(void);
369 static void word(char *cp);
370 static struct ioword **copyio(void);
371 static struct ioword *io(int u, int f, char *cp);
372 static void zzerr(void);
373 static void yyerror(char *s);
374 static int yylex(int cf);
375 static int collect(int c, int c1);
376 static int dual(int c);
377 static void diag(int ec);
378 static char *tree(unsigned size);
380 /* -------- var.h -------- */
389 #define COPYV 1 /* flag to setval, suggesting copy */
390 #define RONLY 01 /* variable is read-only */
391 #define EXPORT 02 /* variable is to be exported */
392 #define GETCELL 04 /* name & value space was got with getcell */
394 static int yyparse(void);
396 static int execute(struct op *t, int *pin, int *pout, int act);
399 /* -------- io.h -------- */
402 unsigned id; /* buffer id */
403 char buf[512]; /* buffer */
404 char *bufp; /* pointer into buffer */
405 char *ebufp; /* pointer to end of buffer */
408 /* possible arguments to an IO function */
412 int afile; /* file descriptor */
413 unsigned afid; /* buffer id */
414 long afpos; /* file position */
415 struct iobuf *afbuf; /* buffer for this file */
418 //static struct ioarg ioargstack[NPUSH];
419 #define AFID_NOBUF (~0)
422 /* an input generator's state */
424 int (*iofn) (struct ioarg *, struct io *);
427 char prev; /* previous character read by readc() */
428 char nlcount; /* for `'s */
429 char xchar; /* for `'s */
430 char task; /* reason for pushed IO */
433 //static struct io iostack[NPUSH];
434 #define XOTHER 0 /* none of the below */
435 #define XDOLL 1 /* expanding ${} */
436 #define XGRAVE 2 /* expanding `'s */
437 #define XIO 3 /* file IO */
439 /* in substitution */
440 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
444 * input generators for IO structure
446 static int nlchar(struct ioarg *ap);
447 static int strchar(struct ioarg *ap);
448 static int qstrchar(struct ioarg *ap);
449 static int filechar(struct ioarg *ap);
450 static int herechar(struct ioarg *ap);
451 static int linechar(struct ioarg *ap);
452 static int gravechar(struct ioarg *ap, struct io *iop);
453 static int qgravechar(struct ioarg *ap, struct io *iop);
454 static int dolchar(struct ioarg *ap);
455 static int wdchar(struct ioarg *ap);
456 static void scraphere(void);
457 static void freehere(int area);
458 static void gethere(void);
459 static void markhere(char *s, struct ioword *iop);
460 static int herein(char *hname, int xdoll);
461 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
467 static int eofc(void);
468 static int readc(void);
469 static void unget(int c);
470 static void ioecho(char c);
471 static void prs(const char *s);
472 static void prn(unsigned u);
473 static void closef(int i);
474 static void closeall(void);
480 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
481 static int remap(int fd);
482 static int openpipe(int *pv);
483 static void closepipe(int *pv);
484 static struct io *setbase(struct io *ip);
486 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)),pushio(&temparg,(gen)))
487 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
489 /* -------- word.h -------- */
491 #define NSTART 16 /* default number of words to allow for initially */
496 /* bounds are arbitrary */
500 static struct wdblock *addword(char *wd, struct wdblock *wb);
501 static struct wdblock *newword(int nw);
502 static char **getwords(struct wdblock *wb);
504 /* -------- misc stuff -------- */
506 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
507 static int iosetup(struct ioword *iop, int pipein, int pipeout);
508 static void echo(char **wp);
509 static struct op **find1case(struct op *t, char *w);
510 static struct op *findcase(struct op *t, char *w);
511 static void brkset(struct brkcon *bc);
512 static int dolabel(struct op *t);
513 static int dohelp(struct op *t);
514 static int dochdir(struct op *t);
515 static int doshift(struct op *t);
516 static int dologin(struct op *t);
517 static int doumask(struct op *t);
518 static int doexec(struct op *t);
519 static int dodot(struct op *t);
520 static int dowait(struct op *t);
521 static int doread(struct op *t);
522 static int doeval(struct op *t);
523 static int dotrap(struct op *t);
524 static int getsig(char *s);
525 static void setsig(int n, sighandler_t f);
526 static int getn(char *as);
527 static int dobreak(struct op *t);
528 static int docontinue(struct op *t);
529 static int brkcontin(char *cp, int val);
530 static int doexit(struct op *t);
531 static int doexport(struct op *t);
532 static int doreadonly(struct op *t);
533 static void rdexp(char **wp, void (*f) (struct var *), int key);
534 static void badid(char *s);
535 static int doset(struct op *t);
536 static void varput(char *s, int out);
537 static int dotimes(struct op *t);
538 static int expand(char *cp, struct wdblock **wbp, int f);
539 static char *blank(int f);
540 static int dollar(int quoted);
541 static int grave(int quoted);
542 static void globname(char *we, char *pp);
543 static char *generate(char *start1, char *end1, char *middle, char *end);
544 static int anyspcl(struct wdblock *wb);
545 static int xstrcmp(char *p1, char *p2);
546 static void glob0(char *a0, unsigned a1, int a2,
547 int (*a3) (char *, char *));
548 static void glob1(char *base, char *lim);
549 static void glob2(char *i, char *j);
550 static void glob3(char *i, char *j, char *k);
551 static void readhere(char **name, char *s, int ec);
552 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
553 static int xxchar(struct ioarg *ap);
558 struct ioword *h_iop;
562 static const char * const signame[] = {
565 NULL, /* interrupt */
567 "Illegal instruction",
571 "Floating Point Exception",
576 NULL, /* broken pipe */
581 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
587 static const struct res restab[] = {
613 int (*builtinfunc) (struct op * t);
615 static const struct builtincmd builtincmds[] = {
620 {"continue", docontinue},
624 {"export", doexport},
629 {"readonly", doreadonly},
639 static struct op *scantree(struct op *);
640 static struct op *dowholefile(int, int);
648 static int interactive; /* Is this an interactive shell */
650 static int multiline; /* \n changed to ; */
651 static struct op *outtree; /* result from parser */
654 static struct brkcon *brklist;
656 static struct wdblock *wdlist;
657 static struct wdblock *iolist;
658 static char *trap[_NSIG + 1];
659 static char ourtrap[_NSIG + 1];
660 static int trapset; /* trap pending */
663 static struct var *mshdbg_var;
665 static struct var *vlist; /* dictionary */
666 static struct var *homedir; /* home directory */
667 static struct var *prompt; /* main prompt */
668 static struct var *cprompt; /* continuation prompt */
669 static struct var *path; /* search path for commands */
670 static struct var *shell; /* shell to interpret command files */
671 static struct var *ifs; /* field separators */
673 static int areanum; /* current allocation area */
676 static char *null = "";
677 static int heedint = 1;
678 static void (*qflag) (int) = SIG_IGN;
682 static int iounit = IODEFAULT;
683 static YYSTYPE yylval;
684 static char *elinep = line + sizeof(line) - 5;
686 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
687 static struct ioarg ioargstack[NPUSH];
688 static struct io iostack[NPUSH];
689 static struct iobuf sharedbuf = { AFID_NOBUF };
690 static struct iobuf mainbuf = { AFID_NOBUF };
691 static unsigned bufid = AFID_ID; /* buffer id counter */
693 static struct here *inhere; /* list of hear docs while parsing */
694 static struct here *acthere; /* list of active here documents */
695 static struct region *areabot; /* bottom of area */
696 static struct region *areatop; /* top of area */
697 static struct region *areanxt; /* starting point of scan */
699 static void *brkaddr;
701 static struct env e = {
702 line, /* linep: char ptr */
703 iostack, /* iobase: struct io ptr */
704 iostack - 1, /* iop: struct io ptr */
705 (xint *) NULL, /* errpt: void ptr for errors? */
706 FDBASE, /* iofd: file desc */
707 (struct env *) NULL /* oenv: struct env ptr */
711 void print_t(struct op *t)
713 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
714 T_CMD_NAMES[t->type], t->words, t->ioact));
717 DBGPRINTF(("T: W1: %s", t->words[0]));
721 void print_tree(struct op *head)
724 DBGPRINTF(("PRINT_TREE: no tree\n"));
728 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
732 print_tree(head->left);
735 print_tree(head->right);
737 #endif /* MSHDEBUG */
740 /* fail but return to process next command */
741 static void fail(void)
747 /* abort shell (or fail in subshell) */
748 static void leave(void) ATTRIBUTE_NORETURN;
749 static void leave(void)
751 DBGPRINTF(("LEAVE: leave called!\n"));
762 static void warn(const char *s)
773 static void err(const char *s)
783 e.iop = e.iobase = iostack;
786 /* -------- area.c -------- */
789 * All memory between (char *)areabot and (char *)(areatop+1) is
790 * exclusively administered by the area management routines.
791 * It is assumed that sbrk() and brk() manipulate the high end.
795 void * __q = (void *)-1; \
796 if (brkaddr + (int)(X) < brktop) { \
798 brkaddr += (int)(X); \
803 static void initarea(void)
805 brkaddr = xmalloc(AREASIZE);
806 brktop = brkaddr + AREASIZE;
808 while ((long) sbrk(0) & ALIGN)
810 areabot = (struct region *) sbrk(REGSIZE);
812 areabot->next = areabot;
813 areabot->area = BUSY;
818 static char *getcell(unsigned nbytes)
821 struct region *p, *q;
828 /* silly and defeats the algorithm */
830 * round upwards and add administration area
832 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
835 if (p->area > areanum) {
839 while ((q = p->next)->area > areanum && q != areanxt)
842 * exit loop if cell big enough
851 i = nregio >= GROWBY ? nregio : GROWBY;
852 p = (struct region *) sbrk(i * REGSIZE);
853 if (p == (struct region *) -1)
858 abort(); /* allocated areas are contiguous */
868 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
870 areanxt = p + nregio;
873 * split into requested area and rest
875 if (areanxt + 1 > q) {
877 abort(); /* insufficient space left for admin */
880 areanxt->area = FREE;
884 return (char *) (p + 1);
887 static void freecell(char *cp)
891 p = (struct region *) cp;
899 #define DELETE(obj) freecell((char *)obj)
901 static void freearea(int a)
903 struct region *p, *top;
906 for (p = areabot; p != top; p = p->next)
911 static void setarea(char *cp, int a)
915 p = (struct region *) cp;
920 static int getarea(char *cp)
922 return ((struct region *) cp - 1)->area;
925 static void garbage(void)
927 struct region *p, *q, *top;
930 for (p = areabot; p != top; p = p->next) {
931 if (p->area > areanum) {
932 while ((q = p->next)->area > areanum)
938 if (areatop >= q + SHRINKBY && q->area > areanum) {
939 brk((char *) (q + 1));
947 static char *space(int n)
953 err("out of string space");
957 static char *strsave(const char *s, int a)
961 cp = space(strlen(s) + 1);
970 /* -------- var.c -------- */
972 static int eqname(const char *n1, const char *n2)
974 for (; *n1 != '=' && *n1 != '\0'; n1++)
977 return *n2 == '\0' || *n2 == '=';
980 static char *findeq(const char *cp)
982 while (*cp != '\0' && *cp != '=')
988 * Find the given name in the dictionary
989 * and return its value. If the name was
990 * not previously there, enter it now and
991 * return a null value.
993 static struct var *lookup(const char *n)
998 static struct var dummy;
1002 for (c = 0; isdigit(*n) && c < 1000; n++)
1003 c = c * 10 + *n - '0';
1004 dummy.status = RONLY;
1005 dummy.value = (c <= dolc ? dolv[c] : null);
1008 for (vp = vlist; vp; vp = vp->next)
1009 if (eqname(vp->name, n))
1012 vp = (struct var *) space(sizeof(*vp));
1013 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1014 dummy.name = dummy.value = "";
1017 for (cp = vp->name; (*cp = *n++) && *cp != '='; cp++);
1021 setarea((char *) vp, 0);
1022 setarea((char *) vp->name, 0);
1025 vp->status = GETCELL;
1031 * if name is not NULL, it must be
1032 * a prefix of the space `val',
1034 * this is all so that exporting
1035 * values is reasonably painless.
1037 static void nameval(struct var *vp, const char *val, const char *name)
1043 if (vp->status & RONLY) {
1045 while (*xp && *xp != '=')
1046 putc(*xp++, stderr);
1047 err(" is read-only");
1052 xp = space(strlen(vp->name) + strlen(val) + 2);
1055 /* make string: name=value */
1059 while ((*xp = *cp++) != '\0' && *xp != '=')
1066 if (vp->status & GETCELL)
1067 freecell(vp->name); /* form new string `name=value' */
1074 * give variable at `vp' the value `val'.
1076 static void setval(struct var *vp, const char *val)
1078 nameval(vp, val, NULL);
1081 static void export(struct var *vp)
1083 vp->status |= EXPORT;
1086 static void ronly(struct var *vp)
1088 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1089 vp->status |= RONLY;
1092 static int isassign(const char *s)
1095 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1097 /* no isalpha() - we shouldn't use locale */
1100 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1110 c |= 0x20; /* lowercase letters, doesn't affect numbers */
1112 && (unsigned)(c - '0') > 9 /* not number */
1113 && (unsigned)(c - 'a') > 25 /* not letter */
1120 static int assign(const char *s, int cf)
1125 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1127 if (!isalpha(*s) && *s != '_')
1129 for (cp = s; *cp != '='; cp++)
1130 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1133 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1135 vp->status &= ~GETCELL;
1139 static int checkname(char *cp)
1141 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1143 if (!isalpha(*cp++) && *(cp - 1) != '_')
1146 if (!isalnum(*cp++) && *(cp - 1) != '_')
1151 static void putvlist(int f, int out)
1155 for (vp = vlist; vp; vp = vp->next)
1156 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1157 if (vp->status & EXPORT)
1158 write(out, "export ", 7);
1159 if (vp->status & RONLY)
1160 write(out, "readonly ", 9);
1161 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1162 write(out, "\n", 1);
1170 static void sig(int i)
1176 static void runtrap(int i)
1181 if (trapstr == NULL)
1187 RUN(aword, trapstr, nlchar);
1191 static void setdash(void)
1195 char m['z' - 'a' + 1];
1198 for (c = 'a'; c <= 'z'; c++)
1202 setval(lookup("-"), m);
1205 static int newfile(char *s)
1209 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1212 if (NOT_LONE_DASH(s)) {
1213 DBGPRINTF(("NEWFILE: s is %s\n", s));
1217 err(": cannot open");
1227 struct op *scantree(struct op *head)
1234 if (head->left != NULL) {
1235 dotnode = scantree(head->left);
1240 if (head->right != NULL) {
1241 dotnode = scantree(head->right);
1246 if (head->words == NULL)
1249 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1251 if ((head->type != TDOT) && (strcmp(".", head->words[0]) == 0)) {
1252 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1260 static void onecommand(void)
1265 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1285 setjmp(failpt); /* Bruce Evans' fix */
1287 if (setjmp(failpt) || yyparse() || intr) {
1288 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1293 if (!interactive && intr)
1306 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1308 execute(outtree, NOPIPE, NOPIPE, 0);
1311 if (!interactive && intr) {
1323 static int newenv(int f)
1327 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1334 ep = (struct env *) space(sizeof(*ep));
1347 static void quitenv(void)
1352 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1358 /* should close `'d files */
1360 while (--fd >= e.iofd)
1366 * Is character c in s?
1368 static int any(int c, const char *s)
1377 * Is any character from s1 in s2?
1379 static int anys(const char *s1, const char *s2)
1387 static char *putn(int n)
1392 static void next(int f)
1394 PUSHIO(afile, f, filechar);
1397 static void onintr(int s) /* ANSI C requires a parameter */
1399 signal(SIGINT, onintr);
1406 } else if (heedint) {
1412 /* -------- gmatch.c -------- */
1414 * int gmatch(string, pattern)
1415 * char *string, *pattern;
1417 * Match a pattern as in sh(1).
1422 #define QMASK (CMASK&~QUOTE)
1423 #define NOT '!' /* might use ^ */
1425 static int gmatch(char *s, char *p)
1429 if (s == NULL || p == NULL)
1431 while ((pc = *p++ & CMASK) != '\0') {
1448 if (*p == '\0' || gmatch(s, p))
1450 } while (*s++ != '\0');
1454 if (sc != (pc & ~QUOTE))
1461 static char *cclass(char *p, int sub)
1463 int c, d, not, found;
1473 if (p[1] == '-' && p[2] != ']') {
1478 if (c == sub || (c <= sub && sub <= d))
1480 } while (*++p != ']');
1481 return found ? p + 1 : NULL;
1485 /* -------- csyn.c -------- */
1487 * shell: syntax (C version)
1492 DBGPRINTF7(("YYPARSE: enter...\n"));
1499 return (yynerrs != 0);
1502 static struct op *pipeline(int cf)
1507 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1511 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1514 while ((c = yylex(0)) == '|') {
1515 p = command(CONTIN);
1517 DBGPRINTF8(("PIPELINE: error!\n"));
1521 if (t->type != TPAREN && t->type != TCOM) {
1522 /* shell statement */
1523 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1526 t = block(TPIPE, t, p, NOWORDS);
1531 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1535 static struct op *andor(void)
1540 DBGPRINTF7(("ANDOR: enter...\n"));
1544 DBGPRINTF9(("ANDOR: t=%p\n", t));
1547 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1548 p = pipeline(CONTIN);
1550 DBGPRINTF8(("ANDOR: error!\n"));
1554 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1560 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1564 static struct op *c_list(void)
1569 DBGPRINTF7(("C_LIST: enter...\n"));
1576 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1578 while ((c = yylex(0)) == ';' || c == '&'
1579 || (multiline && c == '\n')) {
1587 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1595 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1599 static int synio(int cf)
1605 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1608 if (c != '<' && c != '>') {
1615 iop = io(iounit, i, yylval.cp);
1619 markhere(yylval.cp, iop);
1621 DBGPRINTF7(("SYNIO: returning 1\n"));
1625 static void musthave(int c, int cf)
1627 peeksym = yylex(cf);
1629 DBGPRINTF7(("MUSTHAVE: error!\n"));
1636 static struct op *simple(void)
1642 switch (peeksym = yylex(0)) {
1663 static struct op *nested(int type, int mark)
1667 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1673 return block(type, t, NOBLOCK, NOWORDS);
1676 static struct op *command(int cf)
1679 struct wdblock *iosave;
1682 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1708 t = nested(TPAREN, ')');
1712 t = nested(TBRACE, '}');
1722 t->words = wordlist();
1724 if (c != '\n' && c != ';')
1726 t->left = dogroup(0);
1734 t->type = c == WHILE ? TWHILE : TUNTIL;
1736 t->right = dogroup(1);
1748 musthave(IN, CONTIN);
1751 t->left = caselist();
1762 t->right = thenpart();
1771 musthave(WORD, 0); /* gets name of file */
1772 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1774 word(yylval.cp); /* add word to wdlist */
1775 word(NOWORD); /* terminate wdlist */
1776 t->words = copyw(); /* dup wdlist */
1786 DBGPRINTF(("COMMAND: returning %p\n", t));
1791 static struct op *dowholefile(int type, int mark)
1795 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1800 t = block(type, t, NOBLOCK, NOWORDS);
1801 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1805 static struct op *dogroup(int onlydone)
1811 if (c == DONE && onlydone)
1820 static struct op *thenpart(void)
1833 if (t->left == NULL)
1835 t->right = elsepart();
1839 static struct op *elsepart(void)
1844 switch (c = yylex(0)) {
1855 t->right = thenpart();
1864 static struct op *caselist(void)
1869 while ((peeksym = yylex(CONTIN)) != ESAC) {
1870 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1871 t = list(t, casepart());
1874 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1878 static struct op *casepart(void)
1882 DBGPRINTF7(("CASEPART: enter...\n"));
1886 t->words = pattern();
1889 peeksym = yylex(CONTIN);
1890 if (peeksym != ESAC)
1891 musthave(BREAK, CONTIN);
1893 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
1898 static char **pattern(void)
1915 static char **wordlist(void)
1925 while ((c = yylex(0)) == WORD)
1933 * supporting functions
1935 static struct op *list(struct op *t1, struct op *t2)
1937 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
1944 return block(TLIST, t1, t2, NOWORDS);
1947 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
1951 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
1959 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
1965 /* See if given string is a shell multiline (FOR, IF, etc) */
1966 static int rlookup(char *n)
1968 const struct res *rp;
1970 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
1972 for (rp = restab; rp->r_name; rp++)
1973 if (strcmp(rp->r_name, n) == 0) {
1974 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
1975 return rp->r_val; /* Return numeric code for shell multiline */
1978 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
1979 return 0; /* Not a shell multiline */
1982 static struct op *newtp(void)
1986 t = (struct op *) tree(sizeof(*t));
1994 DBGPRINTF3(("NEWTP: allocated %p\n", t));
1999 static struct op *namelist(struct op *t)
2002 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2003 T_CMD_NAMES[t->type], iolist));
2006 iolist = addword((char *) NULL, iolist);
2007 t->ioact = copyio();
2011 if (t->type != TCOM) {
2012 if (t->type != TPAREN && t->ioact != NULL) {
2013 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2014 t->ioact = t->left->ioact;
2015 t->left->ioact = NULL;
2026 static char **copyw(void)
2030 wd = getwords(wdlist);
2035 static void word(char *cp)
2037 wdlist = addword(cp, wdlist);
2040 static struct ioword **copyio(void)
2042 struct ioword **iop;
2044 iop = (struct ioword **) getwords(iolist);
2049 static struct ioword *io(int u, int f, char *cp)
2053 iop = (struct ioword *) tree(sizeof(*iop));
2057 iolist = addword((char *) iop, iolist);
2061 static void zzerr(void)
2063 yyerror("syntax error");
2066 static void yyerror(char *s)
2069 if (interactive && e.iop <= iostack) {
2071 while (eofc() == 0 && yylex(0) != '\n');
2077 static int yylex(int cf)
2097 line[LINELIM - 1] = '\0';
2100 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2105 if (any(c, "0123456789")) {
2108 if (c1 == '<' || c1 == '>') {
2117 case '#': /* Comment, skip to next newline or End-of-string */
2118 while ((c = my_getc(0)) != '\0' && c != '\n');
2123 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2127 DBGPRINTF9(("YYLEX: found $\n"));
2131 c = collect(c, '}');
2150 /* If more chars process them, else return NULL char */
2168 if (multiline || cf & CONTIN) {
2169 if (interactive && e.iop <= iostack) {
2170 #if ENABLE_FEATURE_EDITING
2171 current_prompt = cprompt->value;
2173 prs(cprompt->value);
2190 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2191 if (e.linep >= elinep)
2192 err("word too long");
2199 if (any(c, "\"'`$"))
2212 yylval.cp = strsave(line, areanum);
2217 static int collect(int c, int c1)
2221 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2224 while ((c = my_getc(c1)) != c1) {
2233 if (interactive && c == '\n' && e.iop <= iostack) {
2234 #if ENABLE_FEATURE_EDITING
2235 current_prompt = cprompt->value;
2237 prs(cprompt->value);
2245 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2250 /* "multiline commands" helper func */
2251 /* see if next 2 chars form a shell multiline */
2252 static int dual(int c)
2257 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2259 *cp++ = c; /* c is the given "peek" char */
2260 *cp++ = my_getc(0); /* get next char of input */
2261 *cp = '\0'; /* add EOS marker */
2263 c = rlookup(s); /* see if 2 chars form a shell multiline */
2265 unget(*--cp); /* String is not a shell multiline, put peek char back */
2267 return c; /* String is multiline, return numeric multiline (restab) code */
2270 static void diag(int ec)
2274 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2277 if (c == '>' || c == '<') {
2280 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2283 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2284 if (c != '&' || yylval.i == IOHERE)
2290 static char *tree(unsigned size)
2296 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2297 prs("command line too complicated\n");
2307 /* -------- exec.c -------- */
2314 static int execute(struct op *t, int *pin, int *pout, int act)
2317 volatile int i, rv, a;
2318 char *cp, **wp, **wp2;
2320 struct op *outtree_save;
2324 /* Avoid longjmp clobbering */
2329 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2333 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2334 t->type, T_CMD_NAMES[t->type],
2335 ((t->words == NULL) ? "NULL" : t->words[0])));
2339 wp = (wp2 = t->words) != NULL
2340 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2345 DBGPRINTF3(("EXECUTE: TDOT\n"));
2347 outtree_save = outtree;
2349 newfile(evalstr(t->words[0], DOALL));
2351 t->left = dowholefile(TLIST, 0);
2354 outtree = outtree_save;
2357 rv = execute(t->left, pin, pout, 0);
2359 rv = execute(t->right, pin, pout, 0);
2363 rv = execute(t->left, pin, pout, 0);
2367 rv = forkexec(t, pin, pout, act, wp);
2377 pv[0] = remap(pv[0]);
2378 pv[1] = remap(pv[1]);
2379 (void) execute(t->left, pin, pv, 0);
2380 rv = execute(t->right, pv, pout, 0);
2385 (void) execute(t->left, pin, pout, 0);
2386 rv = execute(t->right, pin, pout, 0);
2391 int hinteractive = interactive;
2393 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2396 if (i == 0) { /* child */
2397 signal(SIGINT, SIG_IGN);
2398 signal(SIGQUIT, SIG_IGN);
2400 signal(SIGTERM, SIG_DFL);
2404 open(bb_dev_null, 0);
2406 _exit(execute(t->left, pin, pout, FEXEC));
2408 interactive = hinteractive;
2410 setval(lookup("!"), putn(i));
2425 rv = execute(t->left, pin, pout, 0);
2427 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2428 rv = execute(t1, pin, pout, 0);
2439 while (*wp++ != NULL);
2441 vp = lookup(t->str);
2442 while (setjmp(bc.brkpt))
2446 for (t1 = t->left; i-- && *wp != NULL;) {
2448 rv = execute(t1, pin, pout, 0);
2450 brklist = brklist->nextlev;
2455 while (setjmp(bc.brkpt))
2460 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2461 rv = execute(t->right, pin, pout, 0);
2462 brklist = brklist->nextlev;
2467 if (t->right != NULL) {
2468 rv = !execute(t->left, pin, pout, 0) ?
2469 execute(t->right->left, pin, pout, 0) :
2470 execute(t->right->right, pin, pout, 0);
2475 cp = evalstr(t->str, DOSUB | DOTRIM);
2479 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2480 ((t->str == NULL) ? "NULL" : t->str),
2481 ((cp == NULL) ? "NULL" : cp)));
2483 t1 = findcase(t->left, cp);
2485 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2486 rv = execute(t1, pin, pout, 0);
2487 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2496 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2504 rv = execute(t1, pin, pout, 0);
2517 if (interactive && intr) {
2528 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2533 forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2537 builtin_func_ptr shcom = NULL;
2540 struct ioword **iopp;
2550 struct brkcon *hbrklist;
2554 /* Avoid longjmp clobbering */
2564 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2566 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2567 ((t->words == NULL) ? "NULL" : t->words[0])));
2571 rv = -1; /* system-detected error */
2572 if (t->type == TCOM) {
2573 while ((cp = *wp++) != NULL);
2576 /* strip all initial assignments */
2577 /* not correct wrt PATH=yyy command etc */
2579 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2581 echo(cp ? wp : owp);
2584 if (cp == NULL && t->ioact == NULL) {
2585 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2587 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2588 return setstatus(0);
2591 shcom = inbuilt(cp);
2598 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2601 if (shcom == NULL && (f & FEXEC) == 0) {
2602 /* Save values in case the child process alters them */
2606 hinteractive = interactive;
2611 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2616 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2620 if (newpid > 0) { /* Parent */
2621 /* Restore values */
2625 interactive = hinteractive;
2636 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2639 /* Must be the child process, pid should be 0 */
2640 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2643 signal(SIGINT, SIG_IGN);
2644 signal(SIGQUIT, SIG_IGN);
2655 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2660 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2661 err("piping to/from shell builtins not yet done");
2679 if (shcom != NULL && shcom != doexec) {
2681 err(": cannot redirect shell command");
2687 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2695 i = setstatus((*shcom) (t));
2698 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2702 /* should use FIOCEXCL */
2703 for (i = FDBASE; i < NOFILE; i++)
2706 signal(SIGINT, SIG_DFL);
2707 signal(SIGQUIT, SIG_DFL);
2710 if (t->type == TPAREN)
2711 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2715 cp = rexecve(wp[0], wp, makenv(0, NULL));
2722 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2730 * 0< 1> are ignored as required
2733 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2736 char *cp = NULL, *msg;
2738 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2741 if (iop->io_unit == IODEFAULT) /* take default */
2742 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2744 if (pipein && iop->io_unit == 0)
2747 if (pipeout && iop->io_unit == 1)
2750 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2751 if ((iop->io_flag & IOHERE) == 0) {
2752 cp = iop->io_name; /* huh?? */
2753 cp = evalstr(cp, DOSUB | DOTRIM);
2758 if (iop->io_flag & IODUP) {
2759 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2761 err(": illegal >& argument");
2765 iop->io_flag = IOCLOSE;
2766 iop->io_flag &= ~(IOREAD | IOWRITE);
2768 switch (iop->io_flag) {
2774 case IOHERE | IOXHERE:
2775 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2779 case IOWRITE | IOCAT:
2782 lseek(u, (long) 0, SEEK_END);
2786 u = creat(cp, 0666);
2790 u = dup2(*cp - '0', iop->io_unit);
2794 close(iop->io_unit);
2803 if (u != iop->io_unit) {
2804 dup2(u, iop->io_unit);
2810 static void echo(char **wp)
2815 for (i = 0; wp[i]; i++) {
2823 static struct op **find1case(struct op *t, char *w)
2830 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2834 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2835 T_CMD_NAMES[t->type]));
2837 if (t->type == TLIST) {
2838 tp = find1case(t->left, w);
2840 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2843 t1 = t->right; /* TPAT */
2847 for (wp = t1->words; *wp;) {
2848 cp = evalstr(*wp++, DOSUB);
2849 if (cp && gmatch(w, cp)) {
2850 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2856 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2860 static struct op *findcase(struct op *t, char *w)
2864 tp = find1case(t, w);
2865 return tp != NULL ? *tp : NULL;
2869 * Enter a new loop level (marked for break/continue).
2871 static void brkset(struct brkcon *bc)
2873 bc->nextlev = brklist;
2878 * Wait for the last process created.
2879 * Print a message for each process found
2880 * that was killed by a signal.
2881 * Ignore interrupt signals while waiting
2882 * unless `canintr' is true.
2884 static int waitfor(int lastpid, int canintr)
2888 int oheedint = heedint;
2895 if (errno != EINTR || canintr)
2901 if (signame[rv] != NULL) {
2902 if (pid != lastpid) {
2909 if (pid != lastpid) {
2918 prs(" - core dumped");
2919 if (rv >= NSIGNAL || signame[rv])
2925 } while (pid != lastpid);
2940 static int setstatus(int s)
2943 setval(lookup("?"), putn(s));
2948 * PATH-searching interface to execve.
2949 * If getenv("PATH") were kept up-to-date,
2950 * execvp might be used.
2952 static char *rexecve(char *c, char **v, char **envp)
2956 int eacces = 0, asis = 0;
2959 if (ENABLE_FEATURE_SH_STANDALONE_SHELL) {
2961 if (find_applet_by_name(name)) {
2962 /* We have to exec here since we vforked. Running
2963 * run_applet_by_name() won't work and bad things
2965 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
2969 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
2971 sp = any('/', c) ? "" : path->value;
2973 while (asis || *sp != '\0') {
2976 for (; *sp != '\0'; tp++) {
2979 asis = (*sp == '\0');
2985 for (i = 0; (*tp++ = c[i++]) != '\0';);
2987 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
2989 execve(e.linep, v, envp);
2996 execve(DEFAULT_SHELL, v, envp);
3001 return (char *) bb_msg_memory_exhausted;
3004 return "argument list too long";
3011 return errno == ENOENT ? "not found" : "cannot execute";
3015 * Run the command produced by generator `f'
3016 * applied to stream `arg'.
3018 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3021 struct wdblock *swdlist;
3022 struct wdblock *siolist;
3028 /* Avoid longjmp clobbering */
3032 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3033 areanum, outtree, failpt));
3043 if (newenv(setjmp(errpt)) == 0) {
3050 if (setjmp(failpt) == 0 && yyparse() == 0)
3051 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3054 DBGPRINTF(("RUN: error from newenv()!\n"));
3061 freearea(areanum--);
3066 /* -------- do.c -------- */
3069 * built-in commands: doX
3072 static int dohelp(struct op *t)
3075 const struct builtincmd *x;
3077 puts("\nBuilt-in commands:\n"
3078 "-------------------");
3080 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3083 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3089 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
3092 const struct BB_applet *applet;
3094 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3098 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3107 return EXIT_SUCCESS;
3112 static int dolabel(struct op *t)
3117 static int dochdir(struct op *t)
3123 cp = homedir->value;
3125 er = ": no home directory";
3126 } else if (chdir(cp) < 0)
3127 er = ": bad directory";
3130 prs(cp != NULL ? cp : "cd");
3135 static int doshift(struct op *t)
3139 n = t->words[1] ? getn(t->words[1]) : 1;
3141 err("nothing to shift");
3147 setval(lookup("#"), putn(dolc));
3152 * execute login and newgrp directly
3154 static int dologin(struct op *t)
3159 signal(SIGINT, SIG_DFL);
3160 signal(SIGQUIT, SIG_DFL);
3162 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3169 static int doumask(struct op *t)
3178 for (n = 3 * 4; (n -= 3) >= 0;)
3179 putc('0' + ((i >> n) & 07), stderr);
3182 /* huh??? '8','9' are not allowed! */
3183 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3184 n = n * 8 + (*cp - '0');
3190 static int doexec(struct op *t)
3197 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3203 if (setjmp(failpt) == 0)
3204 execute(t, NOPIPE, NOPIPE, FEXEC);
3210 static int dodot(struct op *t)
3217 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)));
3221 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3224 DBGPRINTF(("DODOT: cp is %s\n", cp));
3226 sp = any('/', cp) ? ":" : path->value;
3228 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3229 ((sp == NULL) ? "NULL" : sp),
3230 ((e.linep == NULL) ? "NULL" : e.linep)));
3234 while (*sp && (*tp = *sp++) != ':')
3239 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3242 i = open(e.linep, 0);
3246 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3248 next(maltmp); /* Basically a PUSHIO */
3250 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3262 static int dowait(struct op *t)
3274 setstatus(waitfor(i, 1));
3278 static int doread(struct op *t)
3284 if (t->words[1] == NULL) {
3285 err("Usage: read name ...");
3288 for (wp = t->words + 1; *wp; wp++) {
3289 for (cp = e.linep; !nl && cp < elinep - 1; cp++) {
3290 nb = read(0, cp, sizeof(*cp));
3291 if (nb != sizeof(*cp))
3294 if (nl || (wp[1] && any(*cp, ifs->value)))
3300 setval(lookup(*wp), e.linep);
3305 static int doeval(struct op *t)
3307 return RUN(awordlist, t->words + 1, wdchar);
3310 static int dotrap(struct op *t)
3315 if (t->words[1] == NULL) {
3316 for (i = 0; i <= _NSIG; i++)
3325 resetsig = isdigit(*t->words[1]);
3326 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3327 n = getsig(t->words[i]);
3331 if (*t->words[1] != '\0') {
3332 trap[n] = strsave(t->words[1], 0);
3341 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3349 static int getsig(char *s)
3354 if (n < 0 || n > _NSIG) {
3355 err("trap: bad signal number");
3361 static void setsig(int n, sighandler_t f)
3365 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3371 static int getn(char *as)
3382 for (n = 0; isdigit(*s); s++)
3383 n = (n * 10) + (*s - '0');
3386 err(": bad number");
3391 static int dobreak(struct op *t)
3393 return brkcontin(t->words[1], 1);
3396 static int docontinue(struct op *t)
3398 return brkcontin(t->words[1], 0);
3401 static int brkcontin(char *cp, int val)
3406 nl = cp == NULL ? 1 : getn(cp);
3413 brklist = bc->nextlev;
3416 err("bad break/continue level");
3420 longjmp(bc->brkpt, 1);
3424 static int doexit(struct op *t)
3431 setstatus(getn(cp));
3433 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3440 static int doexport(struct op *t)
3442 rdexp(t->words + 1, export, EXPORT);
3446 static int doreadonly(struct op *t)
3448 rdexp(t->words + 1, ronly, RONLY);
3452 static void rdexp(char **wp, void (*f) (struct var *), int key)
3454 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3455 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3458 for (; *wp != NULL; wp++) {
3459 if (isassign(*wp)) {
3463 for (cp = *wp; *cp != '='; cp++);
3475 static void badid(char *s)
3478 err(": bad identifier");
3481 static int doset(struct op *t)
3489 for (vp = vlist; vp; vp = vp->next)
3490 varput(vp->name, 1);
3494 /* bad: t->words++; */
3495 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3497 flag['x'] = flag['v'] = 0;
3507 if (*cp >= 'a' && *cp <= 'z')
3516 t->words[0] = dolv[0];
3517 for (n = 1; t->words[n]; n++)
3518 setarea((char *) t->words[n], 0);
3521 setval(lookup("#"), putn(dolc));
3522 setarea((char *) (dolv - 1), 0);
3527 static void varput(char *s, int out)
3529 if (isalnum(*s) || *s == '_') {
3530 write(out, s, strlen(s));
3531 write(out, "\n", 1);
3537 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3538 * This file contains code for the times builtin.
3540 static int dotimes(struct op *t)
3543 long clk_tck = sysconf(_SC_CLK_TCK);
3546 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3547 (int) (buf.tms_utime / clk_tck / 60),
3548 ((double) buf.tms_utime) / clk_tck,
3549 (int) (buf.tms_stime / clk_tck / 60),
3550 ((double) buf.tms_stime) / clk_tck,
3551 (int) (buf.tms_cutime / clk_tck / 60),
3552 ((double) buf.tms_cutime) / clk_tck,
3553 (int) (buf.tms_cstime / clk_tck / 60),
3554 ((double) buf.tms_cstime) / clk_tck);
3559 static builtin_func_ptr inbuilt(char *s) {
3560 const struct builtincmd *bp;
3562 for (bp = builtincmds; bp->name != NULL; bp++)
3563 if (strcmp(bp->name, s) == 0)
3564 return bp->builtinfunc;
3569 /* -------- eval.c -------- */
3574 * blank interpretation
3579 static char **eval(char **ap, int f)
3587 /* Avoid longjmp clobbering */
3592 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3598 if (newenv(setjmp(errpt)) == 0) {
3599 while (*ap && isassign(*ap))
3600 expand(*ap++, &wb, f & ~DOGLOB);
3602 for (wf = ap; *wf; wf++) {
3604 expand(*wf, &wb, f & ~DOGLOB);
3607 for (wb = addword((char *) 0, wb); *ap; ap++) {
3608 if (!flag['k'] || !isassign(*ap))
3609 expand(*ap, &wb, f & ~DOKEY);
3611 wb = addword((char *) 0, wb);
3617 return gflg ? (char **) NULL : wp;
3621 * Make the exported environment from the exported
3622 * names in the dictionary. Keyword assignments
3623 * will already have been done.
3625 static char **makenv(int all, struct wdblock *wb)
3629 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3631 for (vp = vlist; vp; vp = vp->next)
3632 if (all || vp->status & EXPORT)
3633 wb = addword(vp->name, wb);
3634 wb = addword((char *) 0, wb);
3635 return getwords(wb);
3638 static char *evalstr(char *cp, int f)
3642 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3645 if (expand(cp, &wb, f)) {
3646 if (wb == NULL || wb->w_nword == 0
3647 || (cp = wb->w_words[0]) == NULL)
3655 static int expand(char *cp, struct wdblock **wbp, int f)
3660 /* Avoid longjmp clobbering */
3664 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3671 if (!anys("$`'\"", cp) &&
3672 !anys(ifs->value, cp) && ((f & DOGLOB) == 0 || !anys("[*?", cp))) {
3673 cp = strsave(cp, areanum);
3676 *wbp = addword(cp, *wbp);
3680 if (newenv(setjmp(errpt)) == 0) {
3681 PUSHIO(aword, cp, strchar);
3683 while ((cp = blank(f)) && gflg == 0) {
3685 cp = strsave(cp, areanum);
3686 if ((f & DOGLOB) == 0) {
3689 *wbp = addword(cp, *wbp);
3691 *wbp = glob(cp, *wbp);
3700 * Blank interpretation and quoting
3702 static char *blank(int f)
3706 int scanequals, foundequals;
3708 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3711 scanequals = f & DOKEY;
3715 c = subgetc('"', foundequals);
3724 if (f & DOBLANK && any(c, ifs->value))
3733 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3736 if (c == '\'' || !any(c, "$`\""))
3743 if (!isalpha(c) && c != '_')
3746 c = subgetc('"', foundequals);
3748 f & (DOBLANK && any(c, ifs->value)) ||
3749 (!INSUB() && any(c, "\"'"))) {
3760 } else if (!isalnum(c) && c != '_')
3770 * Get characters, substituting for ` and $
3772 static int subgetc(char ec, int quoted)
3776 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3780 if (!INSUB() && ec != '\'') {
3782 if (grave(quoted) == 0)
3784 e.iop->task = XGRAVE;
3790 e.iop->task = XDOLL;
3799 * Prepare to generate the string returned by ${} substitution.
3801 static int dollar(int quoted)
3806 char *s, c, *cp = NULL;
3809 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3815 if (isalpha(c) || c == '_') {
3816 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3817 if (e.linep < elinep)
3824 otask = e.iop->task;
3826 e.iop->task = XOTHER;
3827 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3828 if (e.linep < elinep)
3831 e.iop->task = otask;
3838 if (e.linep >= elinep) {
3839 err("string in ${} too long");
3845 for (cp = s + 1; *cp; cp++)
3846 if (any(*cp, "=-+?")) {
3851 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3853 /* currently this does not distinguish $* and $@ */
3854 /* should check dollar */
3856 PUSHIO(awordlist, dolv + 1, dolchar);
3858 } else { /* trap the nasty ${=} */
3869 err("cannot use ${...=...} with $n");
3878 dolp = strsave(cp, areanum);
3883 prs("missing value for ");
3890 } else if (c == '+')
3891 dolp = strsave(cp, areanum);
3892 if (flag['u'] && dolp == null) {
3893 prs("unset variable: ");
3898 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
3903 * Run the command in `...` and read its output.
3906 static int grave(int quoted)
3912 static char child_cmd[LINELIM];
3918 char *argument_list[4];
3919 struct wdblock *wb = NULL;
3922 /* Avoid longjmp clobbering */
3926 for (cp = e.iop->argp->aword; *cp != '`'; cp++)
3928 err("no closing `");
3932 /* string copy with dollar expansion */
3933 src = e.iop->argp->aword;
3938 while ((*src != '`') && (count < LINELIM)) {
3943 if (*src == '$' && !ignore && !ignore_once) {
3945 char var_name[LINELIM];
3946 char alt_value[LINELIM];
3959 var_name[var_index++] = *src++;
3960 while (isalnum(*src) || *src=='_')
3961 var_name[var_index++] = *src++;
3962 var_name[var_index] = 0;
3975 err("unclosed ${\n");
3980 while (*src && (*src != '}')) {
3981 alt_value[alt_index++] = *src++;
3983 alt_value[alt_index] = 0;
3985 err("unclosed ${\n");
3992 if (isalpha(*var_name)) {
3993 /* let subshell handle it instead */
3995 char *namep = var_name;
4003 char *altp = alt_value;
4011 wb = addword(lookup(var_name)->name, wb);
4015 vp = lookup(var_name);
4016 if (vp->value != null)
4017 value = (operator == '+') ?
4018 alt_value : vp->value;
4019 else if (operator == '?') {
4022 } else if (alt_index && (operator != '+')) {
4024 if (operator == '=')
4029 while (*value && (count < LINELIM)) {
4042 if (openpipe(pf) < 0)
4045 while ((i = vfork()) == -1 && errno == EAGAIN);
4047 DBGPRINTF3(("GRAVE: i is %p\n", io));
4051 err((char *) bb_msg_memory_exhausted);
4055 waitpid(i, NULL, 0);
4056 e.iop->argp->aword = ++cp;
4058 PUSHIO(afile, remap(pf[0]),
4059 (int (*)(struct ioarg *)) ((quoted) ? qgravechar :
4063 /* allow trapped signals */
4064 /* XXX - Maybe this signal stuff should go as well? */
4065 for (j = 0; j <= _NSIG; j++)
4066 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4072 argument_list[0] = (char *) DEFAULT_SHELL;
4073 argument_list[1] = "-c";
4074 argument_list[2] = child_cmd;
4075 argument_list[3] = 0;
4077 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4078 prs(argument_list[0]);
4085 static char *unquote(char *as)
4096 /* -------- glob.c -------- */
4102 #define scopy(x) strsave((x), areanum)
4104 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4106 static struct wdblock *cl, *nl;
4107 static char spcl[] = "[?*";
4109 static struct wdblock *glob(char *cp, struct wdblock *wb)
4117 for (pp = cp; *pp; pp++)
4120 else if (!any(*pp & ~QUOTE, spcl))
4123 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4124 nl = newword(cl->w_nword * 2);
4125 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4126 for (pp = cl->w_words[i]; *pp; pp++)
4127 if (any(*pp, spcl)) {
4128 globname(cl->w_words[i], pp);
4132 nl = addword(scopy(cl->w_words[i]), nl);
4134 for (i = 0; i < cl->w_nword; i++)
4135 DELETE(cl->w_words[i]);
4138 for (i = 0; i < cl->w_nword; i++)
4139 unquote(cl->w_words[i]);
4140 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4142 for (i = 0; i < cl->w_nword; i++)
4143 wb = addword(cl->w_words[i], wb);
4148 wb = addword(unquote(cp), wb);
4152 static void globname(char *we, char *pp)
4155 char *name, *gp, *dp;
4159 char dname[NAME_MAX + 1];
4162 for (np = we; np != pp; pp--)
4165 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4169 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4178 dname[NAME_MAX] = '\0';
4179 while ((de = readdir(dirp)) != NULL) {
4180 /* XXX Hmmm... What this could be? (abial) */
4182 if (ent[j].d_ino == 0)
4185 strncpy(dname, de->d_name, NAME_MAX);
4186 if (dname[0] == '.')
4189 for (k = 0; k < NAME_MAX; k++)
4190 if (any(dname[k], spcl))
4192 if (gmatch(dname, gp)) {
4193 name = generate(we, pp, dname, np);
4194 if (*np && !anys(np, spcl)) {
4195 if (stat(name, &dbuf)) {
4200 nl = addword(name, nl);
4209 * generate a pathname as below.
4210 * start..end1 / middle end
4211 * the slashes come for free
4213 static char *generate(char *start1, char *end1, char *middle, char *end)
4218 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4219 for (xp = start1; xp != end1;)
4221 for (xp = middle; (*op++ = *xp++) != '\0';);
4223 for (xp = end; (*op++ = *xp++) != '\0';);
4227 static int anyspcl(struct wdblock *wb)
4233 for (i = 0; i < wb->w_nword; i++)
4234 if (anys(spcl, *wd++))
4239 static int xstrcmp(char *p1, char *p2)
4241 return strcmp(*(char **) p1, *(char **) p2);
4244 /* -------- word.c -------- */
4246 static struct wdblock *newword(int nw)
4250 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4256 static struct wdblock *addword(char *wd, struct wdblock *wb)
4258 struct wdblock *wb2;
4262 wb = newword(NSTART);
4264 if (nw >= wb->w_bsize) {
4265 wb2 = newword(nw * 2);
4266 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4267 nw * sizeof(char *));
4272 wb->w_words[wb->w_nword++] = wd;
4277 char **getwords(struct wdblock *wb)
4284 if (wb->w_nword == 0) {
4288 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4289 memcpy((char *) wd, (char *) wb->w_words, nb);
4290 DELETE(wb); /* perhaps should done by caller */
4294 static int (*func) (char *, char *);
4297 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4301 glob1(a0, a0 + a1 * a2);
4304 static void glob1(char *base, char *lim)
4315 n = (int) (lim - base);
4318 n = v2 * (n / (2 * v2));
4319 hptr = lptr = base + n;
4324 c = (*func) (i, lptr);
4338 c = (*func) (hptr, j);
4362 if (lptr - base >= lim - hptr) {
4363 glob1(hptr + v2, lim);
4378 static void glob2(char *i, char *j)
4380 char *index1, *index2, c;
4388 *index1++ = *index2;
4393 static void glob3(char *i, char *j, char *k)
4395 char *index1, *index2, *index3;
4405 *index1++ = *index3;
4406 *index3++ = *index2;
4411 /* -------- io.c -------- */
4417 static int my_getc(int ec)
4421 if (e.linep > elinep) {
4422 while ((c = readc()) != '\n' && c);
4423 err("input line too long");
4428 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4431 if (c == '\n' && ec != '\"')
4439 static void unget(int c)
4441 if (e.iop >= e.iobase)
4445 static int eofc(void)
4447 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4450 static int readc(void)
4454 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4456 for (; e.iop >= e.iobase; e.iop--) {
4457 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4463 if (e.iop->prev != 0) {
4464 c = (*e.iop->iofn)(e.iop->argp, e.iop);
4470 if (e.iop == iostack)
4475 if (e.iop->task == XIO && e.iop->prev != '\n') {
4477 if (e.iop == iostack)
4482 if (e.iop->task == XIO) {
4487 if (interactive && e.iop == iostack + 1) {
4488 #if ENABLE_FEATURE_EDITING
4489 current_prompt = prompt->value;
4497 if (e.iop >= iostack) {
4498 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4502 DBGPRINTF(("READC: leave()...\n"));
4509 static void ioecho(char c)
4512 write(2, &c, sizeof c);
4516 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4518 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4519 argp->afid, e.iop));
4521 /* Set env ptr for io source to next array spot and check for array overflow */
4522 if (++e.iop >= &iostack[NPUSH]) {
4524 err("Shell input nested too deeply");
4529 /* We did not overflow the NPUSH array spots so setup data structs */
4531 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4533 if (argp->afid != AFID_NOBUF)
4537 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4538 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4540 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4542 if (e.iop == &iostack[0])
4543 e.iop->argp->afbuf = &mainbuf;
4545 e.iop->argp->afbuf = &sharedbuf;
4547 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4548 /* This line appears to be active when running scripts from command line */
4549 if ((isatty(e.iop->argp->afile) == 0)
4550 && (e.iop == &iostack[0]
4551 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4552 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4553 bufid = AFID_ID; /* AFID_ID = 0 */
4555 e.iop->argp->afid = bufid; /* assign buffer id */
4558 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4559 iostack, e.iop, e.iop->argp->afbuf));
4560 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4561 &mainbuf, &sharedbuf, bufid, e.iop));
4565 e.iop->prev = ~'\n';
4570 if (fn == filechar || fn == linechar)
4572 else if (fn == (int (*)(struct ioarg *)) gravechar
4573 || fn == (int (*)(struct ioarg *)) qgravechar)
4574 e.iop->task = XGRAVE;
4576 e.iop->task = XOTHER;
4579 static struct io *setbase(struct io *ip)
4589 * Input generating functions
4593 * Produce the characters of a string, then a newline, then EOF.
4595 static int nlchar(struct ioarg *ap)
4599 if (ap->aword == NULL)
4610 * Given a list of words, produce the characters
4611 * in them, with a space after each word.
4613 static int wdchar(struct ioarg *ap)
4628 ap->awordlist = NULL;
4633 * Return the characters of a list of words,
4634 * producing a space between them.
4636 static int dolchar(struct ioarg *ap)
4640 wp = *ap->awordlist++;
4642 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4648 static int xxchar(struct ioarg *ap)
4652 if (ap->aword == NULL)
4663 * Produce the characters from a single word (string).
4665 static int strchar(struct ioarg *ap)
4667 if (ap->aword == NULL)
4669 return *ap->aword++;
4673 * Produce quoted characters from a single word (string).
4675 static int qstrchar(struct ioarg *ap)
4679 if (ap->aword == NULL)
4688 * Return the characters from a file.
4690 static int filechar(struct ioarg *ap)
4694 struct iobuf *bp = ap->afbuf;
4696 if (ap->afid != AFID_NOBUF) {
4697 i = (ap->afid != bp->id);
4698 if (i || bp->bufp == bp->ebufp) {
4700 lseek(ap->afile, ap->afpos, SEEK_SET);
4702 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4710 bp->ebufp = bp->bufp + i;
4714 return *bp->bufp++ & 0177;
4716 #if ENABLE_FEATURE_EDITING
4717 if (interactive && isatty(ap->afile)) {
4718 static char mycommand[BUFSIZ];
4719 static int position = 0, size = 0;
4721 while (size == 0 || position >= size) {
4722 read_line_input(current_prompt, mycommand, BUFSIZ, line_input_state);
4723 size = strlen(mycommand);
4726 c = mycommand[position];
4731 i = safe_read(ap->afile, &c, sizeof(c));
4732 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4736 * Return the characters from a here temp file.
4738 static int herechar(struct ioarg *ap)
4742 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4750 * Return the characters produced by a process (`...`).
4751 * Quote them if required, and remove any trailing newline characters.
4753 static int gravechar(struct ioarg *ap, struct io *iop)
4757 c = qgravechar(ap, iop) & ~QUOTE;
4763 static int qgravechar(struct ioarg *ap, struct io *iop)
4767 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4772 return '\n' | QUOTE;
4776 } else if ((c = filechar(ap)) == '\n') {
4778 while ((c = filechar(ap)) == '\n')
4786 return c != 0 ? c | QUOTE : 0;
4790 * Return a single command (usually the first line) from a file.
4792 static int linechar(struct ioarg *ap)
4800 ap->afile = -1; /* illegal value */
4806 static void prs(const char *s)
4809 write(2, s, strlen(s));
4812 static void prn(unsigned u)
4817 static void closef(int i)
4823 static void closeall(void)
4827 for (u = NUFILE; u < NOFILE;)
4833 * remap fd into Shell's fd space
4835 static int remap(int fd)
4841 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
4844 for (i = 0; i < NOFILE; i++)
4851 } while (fd >= 0 && fd < e.iofd);
4853 for (i = 0; i < NOFILE; i++)
4858 err("too many files open in shell");
4864 static int openpipe(int *pv)
4870 err("can't create pipe - try again");
4874 static void closepipe(int *pv)
4882 /* -------- here.c -------- */
4888 static void markhere(char *s, struct ioword *iop)
4890 struct here *h, *lh;
4892 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4894 h = (struct here *) space(sizeof(struct here));
4898 h->h_tag = evalstr(s, DOSUB);
4908 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4909 if (lh->h_next == 0) {
4915 iop->io_flag |= IOHERE | IOXHERE;
4916 for (s = h->h_tag; *s; s++) {
4918 iop->io_flag &= ~IOXHERE;
4922 h->h_dosub = iop->io_flag & IOXHERE;
4925 static void gethere(void)
4927 struct here *h, *hp;
4929 DBGPRINTF7(("GETHERE: enter...\n"));
4931 /* Scan here files first leaving inhere list in place */
4932 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
4933 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
4935 /* Make inhere list active - keep list intact for scraphere */
4937 hp->h_next = acthere;
4943 static void readhere(char **name, char *s, int ec)
4946 char tname[30] = ".msh_XXXXXX";
4949 char myline[LINELIM + 1];
4952 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
4954 tf = mkstemp(tname);
4958 *name = strsave(tname, areanum);
4960 if (newenv(setjmp(errpt)) != 0)
4963 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
4966 if (interactive && e.iop <= iostack) {
4967 #if ENABLE_FEATURE_EDITING
4968 current_prompt = cprompt->value;
4970 prs(cprompt->value);
4974 while ((c = my_getc(ec)) != '\n' && c) {
4977 if (thenext >= &myline[LINELIM]) {
4984 if (strcmp(s, myline) == 0 || c == 0)
4987 write(tf, myline, (int) (thenext - myline));
4990 prs("here document `");
5000 * open here temp file.
5001 * if unquoted here, expand here temp file into second temp file.
5003 static int herein(char *hname, int xdoll)
5009 /* Avoid longjmp clobbering */
5015 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5017 hf = open(hname, 0);
5023 char tname[30] = ".msh_XXXXXX";
5026 tf = mkstemp(tname);
5030 if (newenv(setjmp(errpt)) == 0) {
5031 PUSHIO(afile, hf, herechar);
5033 while ((c = subgetc(0, 0)) != 0) {
5035 write(tf, &c, sizeof c);
5041 tf = open(tname, 0);
5048 static void scraphere(void)
5052 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5054 for (h = inhere; h != NULL; h = h->h_next) {
5055 if (h->h_iop && h->h_iop->io_name)
5056 unlink(h->h_iop->io_name);
5061 /* unlink here temp files before a freearea(area) */
5062 static void freehere(int area)
5064 struct here *h, *hl;
5066 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5069 for (h = acthere; h != NULL; h = h->h_next)
5070 if (getarea((char *) h) >= area) {
5071 if (h->h_iop->io_name != NULL)
5072 unlink(h->h_iop->io_name);
5074 acthere = h->h_next;
5076 hl->h_next = h->h_next;
5082 /* -------- sh.c -------- */
5087 int msh_main(int argc, char **argv)
5093 int (*iof) (struct ioarg *);
5095 #if ENABLE_FEATURE_EDITING
5096 line_input_state = new_line_input_t(FOR_SHELL);
5099 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5105 assign(*ap++, !COPYV);
5106 for (ap = environ; *ap;)
5107 export(lookup(*ap++));
5112 shell = lookup("SHELL");
5113 if (shell->value == null)
5114 setval(shell, (char *)DEFAULT_SHELL);
5117 homedir = lookup("HOME");
5118 if (homedir->value == null)
5119 setval(homedir, "/");
5122 setval(lookup("$"), putn(getpid()));
5124 path = lookup("PATH");
5125 if (path->value == null) {
5127 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
5129 setval(path, "/bin:/usr/bin");
5133 ifs = lookup("IFS");
5134 if (ifs->value == null)
5135 setval(ifs, " \t\n");
5138 mshdbg_var = lookup("MSHDEBUG");
5139 if (mshdbg_var->value == null)
5140 setval(mshdbg_var, "0");
5143 prompt = lookup("PS1");
5144 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5145 if (prompt->value == null)
5147 setval(prompt, DEFAULT_USER_PROMPT);
5148 if (geteuid() == 0) {
5149 setval(prompt, DEFAULT_ROOT_PROMPT);
5150 prompt->status &= ~EXPORT;
5152 cprompt = lookup("PS2");
5153 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5154 if (cprompt->value == null)
5156 setval(cprompt, "> ");
5162 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5163 for (s = argv[0] + 1; *s; s++)
5166 prompt->status &= ~EXPORT;
5167 cprompt->status &= ~EXPORT;
5169 setval(cprompt, "");
5172 PUSHIO(aword, *++argv, iof = nlchar);
5180 /* standard input */
5184 prompt->status &= ~EXPORT;
5192 if (*s >= 'a' && *s <= 'z')
5200 if (iof == filechar && --argc > 0) {
5202 setval(cprompt, "");
5203 prompt->status &= ~EXPORT;
5204 cprompt->status &= ~EXPORT;
5206 /* Shell is non-interactive, activate printf-based debug */
5208 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5212 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5216 exit(1); /* Exit on error */
5222 /* This won't be true if PUSHIO has been called, say from newfile() above */
5223 if (e.iop < iostack) {
5224 PUSHIO(afile, 0, iof);
5225 if (isatty(0) && isatty(1) && !cflag) {
5227 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5229 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
5231 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
5233 printf("Enter 'help' for a list of built-in commands.\n\n");
5238 signal(SIGQUIT, qflag);
5239 if (name && name[0] == '-') {
5241 f = open(".profile", 0);
5244 f = open("/etc/profile", 0);
5249 signal(SIGTERM, sig);
5251 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5252 signal(SIGINT, onintr);
5257 for (ap = ++argv; --argc > 0;) {
5259 if (assign(*ap, !COPYV)) {
5260 dolc--; /* keyword */
5266 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5268 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
5271 if (interactive && e.iop <= iostack) {
5272 #if ENABLE_FEATURE_EDITING
5273 current_prompt = prompt->value;
5279 /* Ensure that getenv("PATH") stays current */
5280 setenv("PATH", path->value, 1);
5283 DBGPRINTF(("MSH_MAIN: returning.\n"));
5288 * Copyright (c) 1987,1997, Prentice Hall
5289 * All rights reserved.
5291 * Redistribution and use of the MINIX operating system in source and
5292 * binary forms, with or without modification, are permitted provided
5293 * that the following conditions are met:
5295 * Redistributions of source code must retain the above copyright
5296 * notice, this list of conditions and the following disclaimer.
5298 * Redistributions in binary form must reproduce the above
5299 * copyright notice, this list of conditions and the following
5300 * disclaimer in the documentation and/or other materials provided
5301 * with the distribution.
5303 * Neither the name of Prentice Hall nor the names of the software
5304 * authors or contributors may be used to endorse or promote
5305 * products derived from this software without specific prior
5306 * written permission.
5308 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5309 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5310 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5311 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5312 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5313 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5314 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5315 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5316 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5317 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5318 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5319 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.