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)
113 short io_unit; /* unit affected */
114 short io_flag; /* action (below) */
115 char *io_name; /* file name */
118 #define IOREAD 1 /* < */
119 #define IOHERE 2 /* << (here file) */
120 #define IOWRITE 4 /* > */
121 #define IOCAT 8 /* >> */
122 #define IOXHERE 16 /* ${}, ` in << */
123 #define IODUP 32 /* >&digit */
124 #define IOCLOSE 64 /* >&- */
126 #define IODEFAULT (-1) /* token for default IO unit */
130 * Description of a command or an operation on commands.
131 * Might eventually use a union.
134 int type; /* operation type, see below */
135 char **words; /* arguments to a command */
136 struct ioword **ioact; /* IO actions (eg, < > >>) */
139 char *str; /* identifier for case and for */
142 #define TCOM 1 /* command */
143 #define TPAREN 2 /* (c-list) */
144 #define TPIPE 3 /* a | b */
145 #define TLIST 4 /* a [&;] b */
146 #define TOR 5 /* || */
147 #define TAND 6 /* && */
155 #define TPAT 14 /* pattern in case */
156 #define TBRACE 15 /* {c-list} */
157 #define TASYNC 16 /* c & */
158 /* Added to support "." file expansion */
161 /* Strings for names to make debug easier */
163 static const char *const T_CMD_NAMES[] = {
186 * actions determining the environment of a process
188 #define BIT(i) (1<<(i))
189 #define FEXEC BIT(0) /* execute without forking */
191 #define AREASIZE (90000)
194 * flags to control evaluation of words
196 #define DOSUB 1 /* interpret $, `, and quotes */
197 #define DOBLANK 2 /* perform blank interpretation */
198 #define DOGLOB 4 /* interpret [?* */
199 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
200 #define DOTRIM 16 /* trim resulting string */
202 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
206 static int newfile(char *s);
211 struct brkcon *nextlev;
218 * -k: look for name=value everywhere on command line
220 * -t: exit after reading and executing one command
223 * -u: unset variables net diagnostic
225 static char flags['z' - 'a' + 1];
226 /* this looks weird, but is OK ... we index flag with 'a'...'z' */
227 static char *flag = flags - 'a';
229 static char *null; /* null value for variable */
230 static int intr; /* interrupt pending */
232 static char *trap[_NSIG + 1];
233 static char ourtrap[_NSIG + 1];
234 static int trapset; /* trap pending */
236 static int heedint; /* heed interrupt signals */
238 static int yynerrs; /* yacc */
240 static char line[LINELIM];
243 #if ENABLE_FEATURE_EDITING
244 static char *current_prompt;
245 static line_input_t *line_input_state;
248 static int areanum; /* current allocation area */
254 static const char *rexecve(char *c, char **v, char **envp);
255 static char *evalstr(char *cp, int f);
256 static char *putn(int n);
257 static char *unquote(char *as);
258 static int rlookup(char *n);
259 static struct wdblock *glob(char *cp, struct wdblock *wb);
260 static int my_getc(int ec);
261 static int subgetc(char ec, int quoted);
262 static char **makenv(int all, struct wdblock *wb);
263 static char **eval(char **ap, int f);
264 static int setstatus(int s);
265 static int waitfor(int lastpid, int canintr);
267 static void onintr(int s); /* SIGINT handler */
269 static int newenv(int f);
270 static void quitenv(void);
271 static void next(int f);
272 static void setdash(void);
273 static void onecommand(void);
274 static void runtrap(int i);
277 /* -------- area stuff -------- */
279 #define REGSIZE sizeof(struct region)
281 /* #define SHRINKBY (64) */
285 #define ALIGN (sizeof(int)-1)
294 /* -------- grammar stuff -------- */
319 /* Added for "." file expansion */
322 #define YYERRCODE 300
325 #define CONTIN 01 /* skip new lines to complete command */
327 static struct op *pipeline(int cf);
328 static struct op *andor(void);
329 static struct op *c_list(void);
330 static int synio(int cf);
331 static void musthave(int c, int cf);
332 static struct op *simple(void);
333 static struct op *nested(int type, int mark);
334 static struct op *command(int cf);
335 static struct op *dogroup(int onlydone);
336 static struct op *thenpart(void);
337 static struct op *elsepart(void);
338 static struct op *caselist(void);
339 static struct op *casepart(void);
340 static char **pattern(void);
341 static char **wordlist(void);
342 static struct op *list(struct op *t1, struct op *t2);
343 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
344 static struct op *newtp(void);
345 static struct op *namelist(struct op *t);
346 static char **copyw(void);
347 static void word(char *cp);
348 static struct ioword **copyio(void);
349 static struct ioword *io(int u, int f, char *cp);
350 static int yylex(int cf);
351 static int collect(int c, int c1);
352 static int dual(int c);
353 static void diag(int ec);
354 static char *tree(unsigned size);
356 /* -------- var.h -------- */
365 #define COPYV 1 /* flag to setval, suggesting copy */
366 #define RONLY 01 /* variable is read-only */
367 #define EXPORT 02 /* variable is to be exported */
368 #define GETCELL 04 /* name & value space was got with getcell */
370 static int yyparse(void);
372 static int execute(struct op *t, int *pin, int *pout, int act);
375 #define AFID_NOBUF (~0)
379 /* -------- io.h -------- */
382 unsigned id; /* buffer id */
383 char buf[512]; /* buffer */
384 char *bufp; /* pointer into buffer */
385 char *ebufp; /* pointer to end of buffer */
388 /* possible arguments to an IO function */
392 int afile; /* file descriptor */
393 unsigned afid; /* buffer id */
394 long afpos; /* file position */
395 struct iobuf *afbuf; /* buffer for this file */
398 /* an input generator's state */
400 int (*iofn) (struct ioarg *, struct io *);
403 char prev; /* previous character read by readc() */
404 char nlcount; /* for `'s */
405 char xchar; /* for `'s */
406 char task; /* reason for pushed IO */
409 #define XOTHER 0 /* none of the below */
410 #define XDOLL 1 /* expanding ${} */
411 #define XGRAVE 2 /* expanding `'s */
412 #define XIO 3 /* file IO */
414 /* in substitution */
415 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
417 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
418 static struct ioarg ioargstack[NPUSH];
419 static struct io iostack[NPUSH];
420 static struct iobuf sharedbuf = { AFID_NOBUF };
421 static struct iobuf mainbuf = { AFID_NOBUF };
422 static unsigned bufid = AFID_ID; /* buffer id counter */
424 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
425 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
429 * parsing & execution environment
435 xint *errpt; /* void * */
442 * input generators for IO structure
444 static int nlchar(struct ioarg *ap);
445 static int strchar(struct ioarg *ap);
446 static int qstrchar(struct ioarg *ap);
447 static int filechar(struct ioarg *ap);
448 static int herechar(struct ioarg *ap);
449 static int linechar(struct ioarg *ap);
450 static int gravechar(struct ioarg *ap, struct io *iop);
451 static int qgravechar(struct ioarg *ap, struct io *iop);
452 static int dolchar(struct ioarg *ap);
453 static int wdchar(struct ioarg *ap);
454 static void scraphere(void);
455 static void freehere(int area);
456 static void gethere(void);
457 static void markhere(char *s, struct ioword *iop);
458 static int herein(char *hname, int xdoll);
459 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
462 static int eofc(void);
463 static int readc(void);
464 static void unget(int c);
465 static void ioecho(char c);
471 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
472 static int remap(int fd);
473 static int openpipe(int *pv);
474 static void closepipe(int *pv);
475 static struct io *setbase(struct io *ip);
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 brkset(struct brkcon *bc);
497 static int dolabel(struct op *t);
498 static int dohelp(struct op *t);
499 static int dochdir(struct op *t);
500 static int doshift(struct op *t);
501 static int dologin(struct op *t);
502 static int doumask(struct op *t);
503 static int doexec(struct op *t);
504 static int dodot(struct op *t);
505 static int dowait(struct op *t);
506 static int doread(struct op *t);
507 static int doeval(struct op *t);
508 static int dotrap(struct op *t);
509 static int getsig(char *s);
510 static void setsig(int n, sighandler_t f);
511 static int getn(char *as);
512 static int dobreak(struct op *t);
513 static int docontinue(struct op *t);
514 static int brkcontin(char *cp, int val);
515 static int doexit(struct op *t);
516 static int doexport(struct op *t);
517 static int doreadonly(struct op *t);
518 static void rdexp(char **wp, void (*f) (struct var *), int key);
519 static void badid(char *s);
520 static int doset(struct op *t);
521 static void varput(char *s, int out);
522 static int dotimes(struct op *t);
523 static int expand(const char *cp, struct wdblock **wbp, int f);
524 static char *blank(int f);
525 static int dollar(int quoted);
526 static int grave(int quoted);
527 static void globname(char *we, char *pp);
528 static char *generate(char *start1, char *end1, char *middle, char *end);
529 static int anyspcl(struct wdblock *wb);
530 static int xstrcmp(char *p1, char *p2);
531 static void glob0(char *a0, unsigned a1, int a2,
532 int (*a3) (char *, char *));
533 static void readhere(char **name, char *s, int ec);
534 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
535 static int xxchar(struct ioarg *ap);
540 struct ioword *h_iop;
544 static const char * const signame[] = {
547 NULL, /* interrupt */
549 "Illegal instruction",
553 "Floating Point Exception",
558 NULL, /* broken pipe */
563 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
569 static const struct res restab[] = {
595 int (*builtinfunc) (struct op * t);
597 static const struct builtincmd builtincmds[] = {
602 {"continue", docontinue},
606 {"export", doexport},
611 {"readonly", doreadonly},
621 static struct op *scantree(struct op *);
622 static struct op *dowholefile(int, int);
630 static int interactive; /* Is this an interactive shell */
632 static int multiline; /* \n changed to ; */
633 static struct op *outtree; /* result from parser */
636 static struct brkcon *brklist;
638 static struct wdblock *wdlist;
639 static struct wdblock *iolist;
640 static char *trap[_NSIG + 1];
641 static char ourtrap[_NSIG + 1];
642 static int trapset; /* trap pending */
645 static struct var *mshdbg_var;
647 static struct var *vlist; /* dictionary */
648 static struct var *homedir; /* home directory */
649 static struct var *prompt; /* main prompt */
650 static struct var *cprompt; /* continuation prompt */
651 static struct var *path; /* search path for commands */
652 static struct var *shell; /* shell to interpret command files */
653 static struct var *ifs; /* field separators */
655 static int areanum; /* current allocation area */
658 static char *null = (char*)"";
659 static int heedint = 1;
660 static void (*qflag) (int) = SIG_IGN;
664 static int iounit = IODEFAULT;
665 static YYSTYPE yylval;
666 static char *elinep = line + sizeof(line) - 5;
669 static struct here *inhere; /* list of hear docs while parsing */
670 static struct here *acthere; /* list of active here documents */
671 static struct region *areabot; /* bottom of area */
672 static struct region *areatop; /* top of area */
673 static struct region *areanxt; /* starting point of scan */
675 static void *brkaddr;
677 static struct env e = {
678 line, /* linep: char ptr */
679 iostack, /* iobase: struct io ptr */
680 iostack - 1, /* iop: struct io ptr */
681 (xint *) NULL, /* errpt: void ptr for errors? */
682 FDBASE, /* iofd: file desc */
683 (struct env *) NULL /* oenv: struct env ptr */
687 void print_t(struct op *t)
689 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
690 T_CMD_NAMES[t->type], t->words, t->ioact));
693 DBGPRINTF(("T: W1: %s", t->words[0]));
697 void print_tree(struct op *head)
700 DBGPRINTF(("PRINT_TREE: no tree\n"));
704 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
708 print_tree(head->left);
711 print_tree(head->right);
713 #endif /* MSHDEBUG */
719 static void prs(const char *s)
722 write(2, s, strlen(s));
725 static void prn(unsigned u)
730 static void echo(char **wp)
735 for (i = 0; wp[i]; i++) {
743 static void closef(int i)
749 static void closeall(void)
753 for (u = NUFILE; u < NOFILE;)
758 /* fail but return to process next command */
759 static void fail(void) ATTRIBUTE_NORETURN;
760 static void fail(void)
766 /* abort shell (or fail in subshell) */
767 static void leave(void) ATTRIBUTE_NORETURN;
768 static void leave(void)
770 DBGPRINTF(("LEAVE: leave called!\n"));
781 static void warn(const char *s)
792 static void err(const char *s)
802 e.iop = e.iobase = iostack;
806 /* -------- area.c -------- */
809 * All memory between (char *)areabot and (char *)(areatop+1) is
810 * exclusively administered by the area management routines.
811 * It is assumed that sbrk() and brk() manipulate the high end.
815 void * __q = (void *)-1; \
816 if (brkaddr + (int)(X) < brktop) { \
818 brkaddr += (int)(X); \
823 static void initarea(void)
825 brkaddr = xmalloc(AREASIZE);
826 brktop = brkaddr + AREASIZE;
828 while ((long) sbrk(0) & ALIGN)
830 areabot = (struct region *) sbrk(REGSIZE);
832 areabot->next = areabot;
833 areabot->area = BUSY;
838 static char *getcell(unsigned nbytes)
841 struct region *p, *q;
848 /* silly and defeats the algorithm */
850 * round upwards and add administration area
852 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
855 if (p->area > areanum) {
859 while ((q = p->next)->area > areanum && q != areanxt)
862 * exit loop if cell big enough
871 i = nregio >= GROWBY ? nregio : GROWBY;
872 p = (struct region *) sbrk(i * REGSIZE);
873 if (p == (struct region *) -1)
878 abort(); /* allocated areas are contiguous */
888 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
890 areanxt = p + nregio;
893 * split into requested area and rest
895 if (areanxt + 1 > q) {
897 abort(); /* insufficient space left for admin */
900 areanxt->area = FREE;
904 return (char *) (p + 1);
907 static void freecell(char *cp)
911 p = (struct region *) cp;
919 #define DELETE(obj) freecell((char *)obj)
921 static void freearea(int a)
923 struct region *p, *top;
926 for (p = areabot; p != top; p = p->next)
931 static void setarea(char *cp, int a)
935 p = (struct region *) cp;
940 static int getarea(char *cp)
942 return ((struct region *) cp - 1)->area;
945 static void garbage(void)
947 struct region *p, *q, *top;
950 for (p = areabot; p != top; p = p->next) {
951 if (p->area > areanum) {
952 while ((q = p->next)->area > areanum)
958 if (areatop >= q + SHRINKBY && q->area > areanum) {
959 brk((char *) (q + 1));
967 static char *space(int n)
973 err("out of string space");
977 static char *strsave(const char *s, int a)
981 cp = space(strlen(s) + 1);
983 // FIXME: I highly doubt this is good.
992 /* -------- var.c -------- */
994 static int eqname(const char *n1, const char *n2)
996 for (; *n1 != '=' && *n1 != '\0'; n1++)
999 return *n2 == '\0' || *n2 == '=';
1002 static const char *findeq(const char *cp)
1004 while (*cp != '\0' && *cp != '=')
1010 * Find the given name in the dictionary
1011 * and return its value. If the name was
1012 * not previously there, enter it now and
1013 * return a null value.
1015 static struct var *lookup(const char *n)
1017 // FIXME: dirty hack
1018 static struct var dummy;
1026 dummy.name = (char*)n;
1027 for (c = 0; isdigit(*n) && c < 1000; n++)
1028 c = c * 10 + *n - '0';
1029 dummy.status = RONLY;
1030 dummy.value = (c <= dolc ? dolv[c] : null);
1034 for (vp = vlist; vp; vp = vp->next)
1035 if (eqname(vp->name, n))
1039 vp = (struct var *) space(sizeof(*vp));
1040 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1041 dummy.name = dummy.value = (char*)"";
1046 while ((*xp = *n++) != '\0' && *xp != '=')
1050 setarea((char *) vp, 0);
1051 setarea((char *) vp->name, 0);
1054 vp->status = GETCELL;
1060 * if name is not NULL, it must be
1061 * a prefix of the space `val',
1063 * this is all so that exporting
1064 * values is reasonably painless.
1066 static void nameval(struct var *vp, const char *val, const char *name)
1072 if (vp->status & RONLY) {
1074 while (*xp && *xp != '=')
1075 putc(*xp++, stderr);
1076 err(" is read-only");
1081 xp = space(strlen(vp->name) + strlen(val) + 2);
1084 /* make string: name=value */
1088 while ((*xp = *cp++) != '\0' && *xp != '=')
1095 if (vp->status & GETCELL)
1096 freecell(vp->name); /* form new string `name=value' */
1097 vp->name = (char*)name;
1098 vp->value = (char*)val;
1103 * give variable at `vp' the value `val'.
1105 static void setval(struct var *vp, const char *val)
1107 nameval(vp, val, NULL);
1110 static void export(struct var *vp)
1112 vp->status |= EXPORT;
1115 static void ronly(struct var *vp)
1117 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1118 vp->status |= RONLY;
1121 static int isassign(const char *s)
1124 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1126 /* no isalpha() - we shouldn't use locale */
1129 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1139 c |= 0x20; /* lowercase letters, doesn't affect numbers */
1141 && (unsigned)(c - '0') > 9 /* not number */
1142 && (unsigned)(c - 'a') > 25 /* not letter */
1149 static int assign(const char *s, int cf)
1154 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1156 if (!isalpha(*s) && *s != '_')
1158 for (cp = s; *cp != '='; cp++)
1159 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1162 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1164 vp->status &= ~GETCELL;
1168 static int checkname(char *cp)
1170 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1172 if (!isalpha(*cp++) && *(cp - 1) != '_')
1175 if (!isalnum(*cp++) && *(cp - 1) != '_')
1180 static void putvlist(int f, int out)
1184 for (vp = vlist; vp; vp = vp->next) {
1185 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1186 if (vp->status & EXPORT)
1187 write(out, "export ", 7);
1188 if (vp->status & RONLY)
1189 write(out, "readonly ", 9);
1190 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1191 write(out, "\n", 1);
1200 static void sig(int i)
1206 static void runtrap(int i)
1211 if (trapstr == NULL)
1217 RUN(aword, trapstr, nlchar);
1221 static void setdash(void)
1225 char m['z' - 'a' + 1];
1228 for (c = 'a'; c <= 'z'; c++)
1232 setval(lookup("-"), m);
1235 static int newfile(char *s)
1239 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1242 if (NOT_LONE_DASH(s)) {
1243 DBGPRINTF(("NEWFILE: s is %s\n", s));
1247 err(": cannot open");
1257 struct op *scantree(struct op *head)
1264 if (head->left != NULL) {
1265 dotnode = scantree(head->left);
1270 if (head->right != NULL) {
1271 dotnode = scantree(head->right);
1276 if (head->words == NULL)
1279 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1281 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1282 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1290 static void onecommand(void)
1295 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1315 setjmp(failpt); /* Bruce Evans' fix */
1317 if (setjmp(failpt) || yyparse() || intr) {
1318 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1323 if (!interactive && intr)
1336 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1338 execute(outtree, NOPIPE, NOPIPE, 0);
1341 if (!interactive && intr) {
1353 static int newenv(int f)
1357 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1364 ep = (struct env *) space(sizeof(*ep));
1377 static void quitenv(void)
1382 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1388 /* should close `'d files */
1390 while (--fd >= e.iofd)
1396 * Is character c in s?
1398 static int any(int c, const char *s)
1407 * Is any character from s1 in s2?
1409 static int anys(const char *s1, const char *s2)
1417 static char *putn(int n)
1422 static void next(int f)
1424 PUSHIO(afile, f, filechar);
1427 static void onintr(int s) /* ANSI C requires a parameter */
1429 signal(SIGINT, onintr);
1436 } else if (heedint) {
1443 /* -------- gmatch.c -------- */
1445 * int gmatch(string, pattern)
1446 * char *string, *pattern;
1448 * Match a pattern as in sh(1).
1453 #define QMASK (CMASK&~QUOTE)
1454 #define NOT '!' /* might use ^ */
1456 static const char *cclass(const char *p, int sub)
1458 int c, d, not, found;
1468 if (p[1] == '-' && p[2] != ']') {
1473 if (c == sub || (c <= sub && sub <= d))
1475 } while (*++p != ']');
1476 return found ? p + 1 : NULL;
1479 static int gmatch(const char *s, const char *p)
1483 if (s == NULL || p == NULL)
1486 while ((pc = *p++ & CMASK) != '\0') {
1503 if (*p == '\0' || gmatch(s, p))
1505 } while (*s++ != '\0');
1509 if (sc != (pc & ~QUOTE))
1517 /* -------- csyn.c -------- */
1519 * shell: syntax (C version)
1522 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1523 static void yyerror(const char *s)
1526 if (interactive && e.iop <= iostack) {
1528 while (eofc() == 0 && yylex(0) != '\n');
1534 static void zzerr(void) ATTRIBUTE_NORETURN;
1535 static void zzerr(void)
1537 yyerror("syntax error");
1542 DBGPRINTF7(("YYPARSE: enter...\n"));
1549 return (yynerrs != 0);
1552 static struct op *pipeline(int cf)
1557 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1561 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1564 while ((c = yylex(0)) == '|') {
1565 p = command(CONTIN);
1567 DBGPRINTF8(("PIPELINE: error!\n"));
1571 if (t->type != TPAREN && t->type != TCOM) {
1572 /* shell statement */
1573 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1576 t = block(TPIPE, t, p, NOWORDS);
1581 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1585 static struct op *andor(void)
1590 DBGPRINTF7(("ANDOR: enter...\n"));
1594 DBGPRINTF9(("ANDOR: t=%p\n", t));
1597 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1598 p = pipeline(CONTIN);
1600 DBGPRINTF8(("ANDOR: error!\n"));
1604 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1610 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1614 static struct op *c_list(void)
1619 DBGPRINTF7(("C_LIST: enter...\n"));
1626 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1628 while ((c = yylex(0)) == ';' || c == '&'
1629 || (multiline && c == '\n')) {
1637 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1645 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1649 static int synio(int cf)
1655 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1658 if (c != '<' && c != '>') {
1665 iop = io(iounit, i, yylval.cp);
1669 markhere(yylval.cp, iop);
1671 DBGPRINTF7(("SYNIO: returning 1\n"));
1675 static void musthave(int c, int cf)
1677 peeksym = yylex(cf);
1679 DBGPRINTF7(("MUSTHAVE: error!\n"));
1686 static struct op *simple(void)
1692 switch (peeksym = yylex(0)) {
1713 static struct op *nested(int type, int mark)
1717 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1723 return block(type, t, NOBLOCK, NOWORDS);
1726 static struct op *command(int cf)
1729 struct wdblock *iosave;
1732 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1758 t = nested(TPAREN, ')');
1762 t = nested(TBRACE, '}');
1772 t->words = wordlist();
1774 if (c != '\n' && c != ';')
1776 t->left = dogroup(0);
1784 t->type = c == WHILE ? TWHILE : TUNTIL;
1786 t->right = dogroup(1);
1798 musthave(IN, CONTIN);
1801 t->left = caselist();
1812 t->right = thenpart();
1821 musthave(WORD, 0); /* gets name of file */
1822 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1824 word(yylval.cp); /* add word to wdlist */
1825 word(NOWORD); /* terminate wdlist */
1826 t->words = copyw(); /* dup wdlist */
1836 DBGPRINTF(("COMMAND: returning %p\n", t));
1841 static struct op *dowholefile(int type, int mark)
1845 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1850 t = block(type, t, NOBLOCK, NOWORDS);
1851 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1855 static struct op *dogroup(int onlydone)
1861 if (c == DONE && onlydone)
1870 static struct op *thenpart(void)
1883 if (t->left == NULL)
1885 t->right = elsepart();
1889 static struct op *elsepart(void)
1894 switch (c = yylex(0)) {
1905 t->right = thenpart();
1914 static struct op *caselist(void)
1919 while ((peeksym = yylex(CONTIN)) != ESAC) {
1920 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1921 t = list(t, casepart());
1924 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1928 static struct op *casepart(void)
1932 DBGPRINTF7(("CASEPART: enter...\n"));
1936 t->words = pattern();
1939 peeksym = yylex(CONTIN);
1940 if (peeksym != ESAC)
1941 musthave(BREAK, CONTIN);
1943 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
1948 static char **pattern(void)
1965 static char **wordlist(void)
1975 while ((c = yylex(0)) == WORD)
1983 * supporting functions
1985 static struct op *list(struct op *t1, struct op *t2)
1987 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
1994 return block(TLIST, t1, t2, NOWORDS);
1997 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2001 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2009 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2015 /* See if given string is a shell multiline (FOR, IF, etc) */
2016 static int rlookup(char *n)
2018 const struct res *rp;
2020 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2022 for (rp = restab; rp->r_name; rp++)
2023 if (strcmp(rp->r_name, n) == 0) {
2024 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2025 return rp->r_val; /* Return numeric code for shell multiline */
2028 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2029 return 0; /* Not a shell multiline */
2032 static struct op *newtp(void)
2036 t = (struct op *) tree(sizeof(*t));
2044 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2049 static struct op *namelist(struct op *t)
2052 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2053 T_CMD_NAMES[t->type], iolist));
2056 iolist = addword((char *) NULL, iolist);
2057 t->ioact = copyio();
2061 if (t->type != TCOM) {
2062 if (t->type != TPAREN && t->ioact != NULL) {
2063 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2064 t->ioact = t->left->ioact;
2065 t->left->ioact = NULL;
2076 static char **copyw(void)
2080 wd = getwords(wdlist);
2085 static void word(char *cp)
2087 wdlist = addword(cp, wdlist);
2090 static struct ioword **copyio(void)
2092 struct ioword **iop;
2094 iop = (struct ioword **) getwords(iolist);
2099 static struct ioword *io(int u, int f, char *cp)
2103 iop = (struct ioword *) tree(sizeof(*iop));
2107 iolist = addword((char *) iop, iolist);
2111 static int yylex(int cf)
2131 line[LINELIM - 1] = '\0';
2134 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2139 if (any(c, "0123456789")) {
2142 if (c1 == '<' || c1 == '>') {
2151 case '#': /* Comment, skip to next newline or End-of-string */
2152 while ((c = my_getc(0)) != '\0' && c != '\n');
2157 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2161 DBGPRINTF9(("YYLEX: found $\n"));
2165 c = collect(c, '}');
2184 /* If more chars process them, else return NULL char */
2202 if (multiline || cf & CONTIN) {
2203 if (interactive && e.iop <= iostack) {
2204 #if ENABLE_FEATURE_EDITING
2205 current_prompt = cprompt->value;
2207 prs(cprompt->value);
2224 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2225 if (e.linep >= elinep)
2226 err("word too long");
2233 if (any(c, "\"'`$"))
2246 yylval.cp = strsave(line, areanum);
2251 static int collect(int c, int c1)
2255 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2258 while ((c = my_getc(c1)) != c1) {
2267 if (interactive && c == '\n' && e.iop <= iostack) {
2268 #if ENABLE_FEATURE_EDITING
2269 current_prompt = cprompt->value;
2271 prs(cprompt->value);
2279 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2284 /* "multiline commands" helper func */
2285 /* see if next 2 chars form a shell multiline */
2286 static int dual(int c)
2291 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2293 *cp++ = c; /* c is the given "peek" char */
2294 *cp++ = my_getc(0); /* get next char of input */
2295 *cp = '\0'; /* add EOS marker */
2297 c = rlookup(s); /* see if 2 chars form a shell multiline */
2299 unget(*--cp); /* String is not a shell multiline, put peek char back */
2301 return c; /* String is multiline, return numeric multiline (restab) code */
2304 static void diag(int ec)
2308 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2311 if (c == '>' || c == '<') {
2314 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2317 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2318 if (c != '&' || yylval.i == IOHERE)
2324 static char *tree(unsigned size)
2330 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2331 prs("command line too complicated\n");
2342 /* -------- exec.c -------- */
2344 static struct op **find1case(struct op *t, const char *w)
2352 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2356 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2357 T_CMD_NAMES[t->type]));
2359 if (t->type == TLIST) {
2360 tp = find1case(t->left, w);
2362 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2365 t1 = t->right; /* TPAT */
2369 for (wp = t1->words; *wp;) {
2370 cp = evalstr(*wp++, DOSUB);
2371 if (cp && gmatch(w, cp)) {
2372 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2378 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2382 static struct op *findcase(struct op *t, const char *w)
2386 tp = find1case(t, w);
2387 return tp != NULL ? *tp : NULL;
2394 static int execute(struct op *t, int *pin, int *pout, int act)
2397 volatile int i, rv, a;
2401 struct op *outtree_save;
2405 /* Avoid longjmp clobbering */
2410 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2414 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2415 t->type, T_CMD_NAMES[t->type],
2416 ((t->words == NULL) ? "NULL" : t->words[0])));
2420 wp = (wp2 = t->words) != NULL
2421 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2426 DBGPRINTF3(("EXECUTE: TDOT\n"));
2428 outtree_save = outtree;
2430 newfile(evalstr(t->words[0], DOALL));
2432 t->left = dowholefile(TLIST, 0);
2435 outtree = outtree_save;
2438 rv = execute(t->left, pin, pout, 0);
2440 rv = execute(t->right, pin, pout, 0);
2444 rv = execute(t->left, pin, pout, 0);
2448 rv = forkexec(t, pin, pout, act, wp);
2458 pv[0] = remap(pv[0]);
2459 pv[1] = remap(pv[1]);
2460 (void) execute(t->left, pin, pv, 0);
2461 rv = execute(t->right, pv, pout, 0);
2466 (void) execute(t->left, pin, pout, 0);
2467 rv = execute(t->right, pin, pout, 0);
2472 int hinteractive = interactive;
2474 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2477 if (i == 0) { /* child */
2478 signal(SIGINT, SIG_IGN);
2479 signal(SIGQUIT, SIG_IGN);
2481 signal(SIGTERM, SIG_DFL);
2485 open(bb_dev_null, 0);
2487 _exit(execute(t->left, pin, pout, FEXEC));
2489 interactive = hinteractive;
2491 setval(lookup("!"), putn(i));
2506 rv = execute(t->left, pin, pout, 0);
2508 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2509 rv = execute(t1, pin, pout, 0);
2520 while (*wp++ != NULL);
2522 vp = lookup(t->str);
2523 while (setjmp(bc.brkpt))
2527 for (t1 = t->left; i-- && *wp != NULL;) {
2529 rv = execute(t1, pin, pout, 0);
2531 brklist = brklist->nextlev;
2536 while (setjmp(bc.brkpt))
2541 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2542 rv = execute(t->right, pin, pout, 0);
2543 brklist = brklist->nextlev;
2548 if (t->right != NULL) {
2549 rv = !execute(t->left, pin, pout, 0) ?
2550 execute(t->right->left, pin, pout, 0) :
2551 execute(t->right->right, pin, pout, 0);
2556 cp = evalstr(t->str, DOSUB | DOTRIM);
2560 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2561 ((t->str == NULL) ? "NULL" : t->str),
2562 ((cp == NULL) ? "NULL" : cp)));
2564 t1 = findcase(t->left, cp);
2566 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2567 rv = execute(t1, pin, pout, 0);
2568 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2577 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2585 rv = execute(t1, pin, pout, 0);
2598 if (interactive && intr) {
2609 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2613 typedef int (*builtin_func_ptr)(struct op *);
2615 static builtin_func_ptr inbuilt(const char *s) {
2616 const struct builtincmd *bp;
2618 for (bp = builtincmds; bp->name != NULL; bp++)
2619 if (strcmp(bp->name, s) == 0)
2620 return bp->builtinfunc;
2625 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2629 builtin_func_ptr shcom = NULL;
2631 const char *cp = NULL;
2632 struct ioword **iopp;
2642 struct brkcon *hbrklist;
2646 /* Avoid longjmp clobbering */
2656 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2658 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2659 ((t->words == NULL) ? "NULL" : t->words[0])));
2663 rv = -1; /* system-detected error */
2664 if (t->type == TCOM) {
2665 while (*wp++ != NULL);
2668 /* strip all initial assignments */
2669 /* not correct wrt PATH=yyy command etc */
2671 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2673 echo(cp ? wp : owp);
2676 if (cp == NULL && t->ioact == NULL) {
2677 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2679 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2680 return setstatus(0);
2683 shcom = inbuilt(cp);
2690 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2693 if (shcom == NULL && (f & FEXEC) == 0) {
2694 /* Save values in case the child process alters them */
2698 hinteractive = interactive;
2703 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2708 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2712 if (newpid > 0) { /* Parent */
2713 /* Restore values */
2717 interactive = hinteractive;
2728 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2731 /* Must be the child process, pid should be 0 */
2732 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2735 signal(SIGINT, SIG_IGN);
2736 signal(SIGQUIT, SIG_IGN);
2747 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2752 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2753 err("piping to/from shell builtins not yet done");
2771 if (shcom != NULL && shcom != doexec) {
2773 err(": cannot redirect shell command");
2779 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2787 i = setstatus((*shcom) (t));
2790 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2794 /* should use FIOCEXCL */
2795 for (i = FDBASE; i < NOFILE; i++)
2798 signal(SIGINT, SIG_DFL);
2799 signal(SIGQUIT, SIG_DFL);
2802 if (t->type == TPAREN)
2803 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2807 cp = rexecve(wp[0], wp, makenv(0, NULL));
2814 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2822 * 0< 1> are ignored as required
2825 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2831 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2834 if (iop->io_unit == IODEFAULT) /* take default */
2835 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2837 if (pipein && iop->io_unit == 0)
2840 if (pipeout && iop->io_unit == 1)
2843 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2844 if ((iop->io_flag & IOHERE) == 0) {
2845 cp = iop->io_name; /* huh?? */
2846 cp = evalstr(cp, DOSUB | DOTRIM);
2851 if (iop->io_flag & IODUP) {
2852 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2854 err(": illegal >& argument");
2858 iop->io_flag = IOCLOSE;
2859 iop->io_flag &= ~(IOREAD | IOWRITE);
2861 switch (iop->io_flag) {
2867 case IOHERE | IOXHERE:
2868 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2869 cp = (char*)"here file";
2872 case IOWRITE | IOCAT:
2875 lseek(u, (long) 0, SEEK_END);
2879 u = creat(cp, 0666);
2883 u = dup2(*cp - '0', iop->io_unit);
2887 close(iop->io_unit);
2896 if (u != iop->io_unit) {
2897 dup2(u, iop->io_unit);
2904 * Enter a new loop level (marked for break/continue).
2906 static void brkset(struct brkcon *bc)
2908 bc->nextlev = brklist;
2913 * Wait for the last process created.
2914 * Print a message for each process found
2915 * that was killed by a signal.
2916 * Ignore interrupt signals while waiting
2917 * unless `canintr' is true.
2919 static int waitfor(int lastpid, int canintr)
2923 int oheedint = heedint;
2930 if (errno != EINTR || canintr)
2936 if (signame[rv] != NULL) {
2937 if (pid != lastpid) {
2944 if (pid != lastpid) {
2953 prs(" - core dumped");
2954 if (rv >= NSIGNAL || signame[rv])
2960 } while (pid != lastpid);
2975 static int setstatus(int s)
2978 setval(lookup("?"), putn(s));
2983 * PATH-searching interface to execve.
2984 * If getenv("PATH") were kept up-to-date,
2985 * execvp might be used.
2987 static const char *rexecve(char *c, char **v, char **envp)
2992 int eacces = 0, asis = 0;
2995 if (ENABLE_FEATURE_SH_STANDALONE_SHELL) {
2997 if (find_applet_by_name(name)) {
2998 /* We have to exec here since we vforked. Running
2999 * run_applet_by_name() won't work and bad things
3001 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3005 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3007 sp = any('/', c) ? "" : path->value;
3008 asis = (*sp == '\0');
3009 while (asis || *sp != '\0') {
3012 for (; *sp != '\0'; tp++) {
3015 asis = (*sp == '\0');
3021 for (i = 0; (*tp++ = c[i++]) != '\0';);
3023 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3025 execve(e.linep, v, envp);
3032 execve(DEFAULT_SHELL, v, envp);
3037 return (char *) bb_msg_memory_exhausted;
3040 return "argument list too long";
3047 return errno == ENOENT ? "not found" : "cannot execute";
3051 * Run the command produced by generator `f'
3052 * applied to stream `arg'.
3054 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3057 struct wdblock *swdlist;
3058 struct wdblock *siolist;
3064 /* Avoid longjmp clobbering */
3068 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3069 areanum, outtree, failpt));
3079 if (newenv(setjmp(errpt)) == 0) {
3086 if (setjmp(failpt) == 0 && yyparse() == 0)
3087 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3090 DBGPRINTF(("RUN: error from newenv()!\n"));
3097 freearea(areanum--);
3102 /* -------- do.c -------- */
3105 * built-in commands: doX
3108 static int dohelp(struct op *t)
3111 const struct builtincmd *x;
3113 puts("\nBuilt-in commands:\n"
3114 "-------------------");
3116 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3119 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3125 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
3128 const struct BB_applet *applet;
3130 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3134 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3143 return EXIT_SUCCESS;
3148 static int dolabel(struct op *t)
3153 static int dochdir(struct op *t)
3155 const char *cp, *er;
3159 cp = homedir->value;
3162 er = ": no home directory";
3167 er = ": bad directory";
3169 prs(cp != NULL ? cp : "cd");
3174 static int doshift(struct op *t)
3178 n = t->words[1] ? getn(t->words[1]) : 1;
3180 err("nothing to shift");
3186 setval(lookup("#"), putn(dolc));
3191 * execute login and newgrp directly
3193 static int dologin(struct op *t)
3198 signal(SIGINT, SIG_DFL);
3199 signal(SIGQUIT, SIG_DFL);
3201 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3208 static int doumask(struct op *t)
3217 for (n = 3 * 4; (n -= 3) >= 0;)
3218 putc('0' + ((i >> n) & 07), stderr);
3221 /* huh??? '8','9' are not allowed! */
3222 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3223 n = n * 8 + (*cp - '0');
3229 static int doexec(struct op *t)
3236 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3242 if (setjmp(failpt) == 0)
3243 execute(t, NOPIPE, NOPIPE, FEXEC);
3249 static int dodot(struct op *t)
3257 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)));
3261 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3264 DBGPRINTF(("DODOT: cp is %s\n", cp));
3266 sp = any('/', cp) ? ":" : path->value;
3268 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3269 ((sp == NULL) ? "NULL" : sp),
3270 ((e.linep == NULL) ? "NULL" : e.linep)));
3274 while (*sp && (*tp = *sp++) != ':')
3279 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3282 i = open(e.linep, 0);
3286 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3288 next(maltmp); /* Basically a PUSHIO */
3290 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3302 static int dowait(struct op *t)
3314 setstatus(waitfor(i, 1));
3318 static int doread(struct op *t)
3324 if (t->words[1] == NULL) {
3325 err("Usage: read name ...");
3328 for (wp = t->words + 1; *wp; wp++) {
3329 for (cp = e.linep; !nl && cp < elinep - 1; cp++) {
3330 nb = read(0, cp, sizeof(*cp));
3331 if (nb != sizeof(*cp))
3334 if (nl || (wp[1] && any(*cp, ifs->value)))
3340 setval(lookup(*wp), e.linep);
3345 static int doeval(struct op *t)
3347 return RUN(awordlist, t->words + 1, wdchar);
3350 static int dotrap(struct op *t)
3355 if (t->words[1] == NULL) {
3356 for (i = 0; i <= _NSIG; i++)
3365 resetsig = isdigit(*t->words[1]);
3366 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3367 n = getsig(t->words[i]);
3371 if (*t->words[1] != '\0') {
3372 trap[n] = strsave(t->words[1], 0);
3381 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3389 static int getsig(char *s)
3394 if (n < 0 || n > _NSIG) {
3395 err("trap: bad signal number");
3401 static void setsig(int n, sighandler_t f)
3405 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3411 static int getn(char *as)
3422 for (n = 0; isdigit(*s); s++)
3423 n = (n * 10) + (*s - '0');
3426 err(": bad number");
3431 static int dobreak(struct op *t)
3433 return brkcontin(t->words[1], 1);
3436 static int docontinue(struct op *t)
3438 return brkcontin(t->words[1], 0);
3441 static int brkcontin(char *cp, int val)
3446 nl = cp == NULL ? 1 : getn(cp);
3453 brklist = bc->nextlev;
3456 err("bad break/continue level");
3460 longjmp(bc->brkpt, 1);
3464 static int doexit(struct op *t)
3471 setstatus(getn(cp));
3473 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3480 static int doexport(struct op *t)
3482 rdexp(t->words + 1, export, EXPORT);
3486 static int doreadonly(struct op *t)
3488 rdexp(t->words + 1, ronly, RONLY);
3492 static void rdexp(char **wp, void (*f) (struct var *), int key)
3494 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3495 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3498 for (; *wp != NULL; wp++) {
3499 if (isassign(*wp)) {
3503 for (cp = *wp; *cp != '='; cp++);
3515 static void badid(char *s)
3518 err(": bad identifier");
3521 static int doset(struct op *t)
3529 for (vp = vlist; vp; vp = vp->next)
3530 varput(vp->name, 1);
3534 /* bad: t->words++; */
3535 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3537 flag['x'] = flag['v'] = 0;
3547 if (*cp >= 'a' && *cp <= 'z')
3556 t->words[0] = dolv[0];
3557 for (n = 1; t->words[n]; n++)
3558 setarea((char *) t->words[n], 0);
3561 setval(lookup("#"), putn(dolc));
3562 setarea((char *) (dolv - 1), 0);
3567 static void varput(char *s, int out)
3569 if (isalnum(*s) || *s == '_') {
3570 write(out, s, strlen(s));
3571 write(out, "\n", 1);
3577 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3578 * This file contains code for the times builtin.
3580 static int dotimes(struct op *t)
3583 long clk_tck = sysconf(_SC_CLK_TCK);
3586 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3587 (int) (buf.tms_utime / clk_tck / 60),
3588 ((double) buf.tms_utime) / clk_tck,
3589 (int) (buf.tms_stime / clk_tck / 60),
3590 ((double) buf.tms_stime) / clk_tck,
3591 (int) (buf.tms_cutime / clk_tck / 60),
3592 ((double) buf.tms_cutime) / clk_tck,
3593 (int) (buf.tms_cstime / clk_tck / 60),
3594 ((double) buf.tms_cstime) / clk_tck);
3599 /* -------- eval.c -------- */
3604 * blank interpretation
3609 static char **eval(char **ap, int f)
3617 /* Avoid longjmp clobbering */
3622 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3628 if (newenv(setjmp(errpt)) == 0) {
3629 while (*ap && isassign(*ap))
3630 expand(*ap++, &wb, f & ~DOGLOB);
3632 for (wf = ap; *wf; wf++) {
3634 expand(*wf, &wb, f & ~DOGLOB);
3637 for (wb = addword((char *) 0, wb); *ap; ap++) {
3638 if (!flag['k'] || !isassign(*ap))
3639 expand(*ap, &wb, f & ~DOKEY);
3641 wb = addword((char *) 0, wb);
3647 return gflg ? (char **) NULL : wp;
3652 * Make the exported environment from the exported
3653 * names in the dictionary. Keyword assignments
3654 * will already have been done.
3656 static char **makenv(int all, struct wdblock *wb)
3660 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3662 for (vp = vlist; vp; vp = vp->next)
3663 if (all || vp->status & EXPORT)
3664 wb = addword(vp->name, wb);
3665 wb = addword((char *) 0, wb);
3666 return getwords(wb);
3669 static int expand(const char *cp, struct wdblock **wbp, int f)
3675 /* Avoid longjmp clobbering */
3679 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3686 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3687 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3689 xp = strsave(cp, areanum);
3692 *wbp = addword(xp, *wbp);
3696 if (newenv(setjmp(errpt)) == 0) {
3697 PUSHIO(aword, cp, strchar);
3699 while ((xp = blank(f)) && gflg == 0) {
3701 xp = strsave(xp, areanum);
3702 if ((f & DOGLOB) == 0) {
3705 *wbp = addword(xp, *wbp);
3707 *wbp = glob(xp, *wbp);
3715 static char *evalstr(char *cp, int f)
3719 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3722 if (expand(cp, &wb, f)) {
3723 if (wb == NULL || wb->w_nword == 0
3724 || (cp = wb->w_words[0]) == NULL
3726 // TODO: I suspect that
3727 // char *evalstr(char *cp, int f) is actually
3728 // const char *evalstr(const char *cp, int f)!
3739 * Blank interpretation and quoting
3741 static char *blank(int f)
3745 int scanequals, foundequals;
3747 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3750 scanequals = f & DOKEY;
3754 c = subgetc('"', foundequals);
3763 if (f & DOBLANK && any(c, ifs->value))
3772 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3775 if (c == '\'' || !any(c, "$`\""))
3782 if (!isalpha(c) && c != '_')
3785 c = subgetc('"', foundequals);
3787 f & (DOBLANK && any(c, ifs->value)) ||
3788 (!INSUB() && any(c, "\"'"))) {
3799 } else if (!isalnum(c) && c != '_')
3809 * Get characters, substituting for ` and $
3811 static int subgetc(char ec, int quoted)
3815 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3819 if (!INSUB() && ec != '\'') {
3821 if (grave(quoted) == 0)
3823 e.iop->task = XGRAVE;
3829 e.iop->task = XDOLL;
3838 * Prepare to generate the string returned by ${} substitution.
3840 static int dollar(int quoted)
3845 char *s, c, *cp = NULL;
3848 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3854 if (isalpha(c) || c == '_') {
3855 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3856 if (e.linep < elinep)
3863 otask = e.iop->task;
3865 e.iop->task = XOTHER;
3866 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3867 if (e.linep < elinep)
3870 e.iop->task = otask;
3877 if (e.linep >= elinep) {
3878 err("string in ${} too long");
3884 for (cp = s + 1; *cp; cp++)
3885 if (any(*cp, "=-+?")) {
3890 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3892 /* currently this does not distinguish $* and $@ */
3893 /* should check dollar */
3895 PUSHIO(awordlist, dolv + 1, dolchar);
3897 } else { /* trap the nasty ${=} */
3908 err("cannot use ${...=...} with $n");
3917 dolp = strsave(cp, areanum);
3922 prs("missing value for ");
3929 } else if (c == '+')
3930 dolp = strsave(cp, areanum);
3931 if (flag['u'] && dolp == null) {
3932 prs("unset variable: ");
3937 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
3942 * Run the command in `...` and read its output.
3945 static int grave(int quoted)
3951 static char child_cmd[LINELIM];
3957 char *argument_list[4];
3958 struct wdblock *wb = NULL;
3961 /* Avoid longjmp clobbering */
3965 for (cp = e.iop->argp->aword; *cp != '`'; cp++) {
3967 err("no closing `");
3972 /* string copy with dollar expansion */
3973 src = e.iop->argp->aword;
3978 while ((*src != '`') && (count < LINELIM)) {
3983 if (*src == '$' && !ignore && !ignore_once) {
3985 char var_name[LINELIM];
3986 char alt_value[LINELIM];
3999 var_name[var_index++] = *src++;
4000 while (isalnum(*src) || *src=='_')
4001 var_name[var_index++] = *src++;
4002 var_name[var_index] = 0;
4015 err("unclosed ${\n");
4020 while (*src && (*src != '}')) {
4021 alt_value[alt_index++] = *src++;
4023 alt_value[alt_index] = 0;
4025 err("unclosed ${\n");
4032 if (isalpha(*var_name)) {
4033 /* let subshell handle it instead */
4035 char *namep = var_name;
4043 char *altp = alt_value;
4051 wb = addword(lookup(var_name)->name, wb);
4055 vp = lookup(var_name);
4056 if (vp->value != null)
4057 value = (operator == '+') ?
4058 alt_value : vp->value;
4059 else if (operator == '?') {
4062 } else if (alt_index && (operator != '+')) {
4064 if (operator == '=')
4069 while (*value && (count < LINELIM)) {
4082 if (openpipe(pf) < 0)
4085 while ((i = vfork()) == -1 && errno == EAGAIN);
4087 DBGPRINTF3(("GRAVE: i is %p\n", io));
4091 err((char *) bb_msg_memory_exhausted);
4095 waitpid(i, NULL, 0);
4096 e.iop->argp->aword = ++cp;
4098 PUSHIO(afile, remap(pf[0]),
4099 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4102 /* allow trapped signals */
4103 /* XXX - Maybe this signal stuff should go as well? */
4104 for (j = 0; j <= _NSIG; j++)
4105 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4111 argument_list[0] = (char *) DEFAULT_SHELL;
4112 argument_list[1] = (char *) "-c";
4113 argument_list[2] = child_cmd;
4114 argument_list[3] = NULL;
4116 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4117 prs(argument_list[0]);
4124 static char *unquote(char *as)
4135 /* -------- glob.c -------- */
4141 #define scopy(x) strsave((x), areanum)
4143 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4145 static struct wdblock *cl, *nl;
4146 static char spcl[] = "[?*";
4148 static struct wdblock *glob(char *cp, struct wdblock *wb)
4156 for (pp = cp; *pp; pp++)
4159 else if (!any(*pp & ~QUOTE, spcl))
4162 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4163 nl = newword(cl->w_nword * 2);
4164 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4165 for (pp = cl->w_words[i]; *pp; pp++)
4166 if (any(*pp, spcl)) {
4167 globname(cl->w_words[i], pp);
4171 nl = addword(scopy(cl->w_words[i]), nl);
4173 for (i = 0; i < cl->w_nword; i++)
4174 DELETE(cl->w_words[i]);
4177 for (i = 0; i < cl->w_nword; i++)
4178 unquote(cl->w_words[i]);
4179 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4181 for (i = 0; i < cl->w_nword; i++)
4182 wb = addword(cl->w_words[i], wb);
4187 wb = addword(unquote(cp), wb);
4191 static void globname(char *we, char *pp)
4194 char *name, *gp, *dp;
4198 char dname[NAME_MAX + 1];
4201 for (np = we; np != pp; pp--)
4204 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4208 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4217 dname[NAME_MAX] = '\0';
4218 while ((de = readdir(dirp)) != NULL) {
4219 /* XXX Hmmm... What this could be? (abial) */
4221 if (ent[j].d_ino == 0)
4224 strncpy(dname, de->d_name, NAME_MAX);
4225 if (dname[0] == '.')
4228 for (k = 0; k < NAME_MAX; k++)
4229 if (any(dname[k], spcl))
4231 if (gmatch(dname, gp)) {
4232 name = generate(we, pp, dname, np);
4233 if (*np && !anys(np, spcl)) {
4234 if (stat(name, &dbuf)) {
4239 nl = addword(name, nl);
4248 * generate a pathname as below.
4249 * start..end1 / middle end
4250 * the slashes come for free
4252 static char *generate(char *start1, char *end1, char *middle, char *end)
4257 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4258 for (xp = start1; xp != end1;)
4260 for (xp = middle; (*op++ = *xp++) != '\0';);
4262 for (xp = end; (*op++ = *xp++) != '\0';);
4266 static int anyspcl(struct wdblock *wb)
4272 for (i = 0; i < wb->w_nword; i++)
4273 if (anys(spcl, *wd++))
4278 static int xstrcmp(char *p1, char *p2)
4280 return strcmp(*(char **) p1, *(char **) p2);
4284 /* -------- word.c -------- */
4286 static struct wdblock *newword(int nw)
4290 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4296 static struct wdblock *addword(char *wd, struct wdblock *wb)
4298 struct wdblock *wb2;
4302 wb = newword(NSTART);
4304 if (nw >= wb->w_bsize) {
4305 wb2 = newword(nw * 2);
4306 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4307 nw * sizeof(char *));
4312 wb->w_words[wb->w_nword++] = wd;
4317 char **getwords(struct wdblock *wb)
4324 if (wb->w_nword == 0) {
4328 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4329 memcpy((char *) wd, (char *) wb->w_words, nb);
4330 DELETE(wb); /* perhaps should done by caller */
4334 static int (*func) (char *, char *);
4337 static void glob3(char *i, char *j, char *k)
4339 char *index1, *index2, *index3;
4349 *index1++ = *index3;
4350 *index3++ = *index2;
4355 static void glob2(char *i, char *j)
4357 char *index1, *index2, c;
4365 *index1++ = *index2;
4370 static void glob1(char *base, char *lim)
4381 n = (int) (lim - base);
4384 n = v2 * (n / (2 * v2));
4385 hptr = lptr = base + n;
4390 c = (*func) (i, lptr);
4404 c = (*func) (hptr, j);
4428 if (lptr - base >= lim - hptr) {
4429 glob1(hptr + v2, lim);
4444 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4448 glob1(a0, a0 + a1 * a2);
4452 /* -------- io.c -------- */
4458 static int my_getc(int ec)
4462 if (e.linep > elinep) {
4463 while ((c = readc()) != '\n' && c);
4464 err("input line too long");
4469 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4472 if (c == '\n' && ec != '\"')
4480 static void unget(int c)
4482 if (e.iop >= e.iobase)
4486 static int eofc(void)
4488 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4491 static int readc(void)
4495 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4497 for (; e.iop >= e.iobase; e.iop--) {
4498 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4504 if (e.iop->prev != 0) {
4505 c = (*e.iop->iofn)(e.iop->argp, e.iop);
4511 if (e.iop == iostack)
4516 if (e.iop->task == XIO && e.iop->prev != '\n') {
4518 if (e.iop == iostack)
4523 if (e.iop->task == XIO) {
4528 if (interactive && e.iop == iostack + 1) {
4529 #if ENABLE_FEATURE_EDITING
4530 current_prompt = prompt->value;
4538 if (e.iop >= iostack) {
4539 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4543 DBGPRINTF(("READC: leave()...\n"));
4550 static void ioecho(char c)
4553 write(2, &c, sizeof c);
4557 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4559 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4560 argp->afid, e.iop));
4562 /* Set env ptr for io source to next array spot and check for array overflow */
4563 if (++e.iop >= &iostack[NPUSH]) {
4565 err("Shell input nested too deeply");
4570 /* We did not overflow the NPUSH array spots so setup data structs */
4572 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4574 if (argp->afid != AFID_NOBUF)
4578 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4579 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4581 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4583 if (e.iop == &iostack[0])
4584 e.iop->argp->afbuf = &mainbuf;
4586 e.iop->argp->afbuf = &sharedbuf;
4588 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4589 /* This line appears to be active when running scripts from command line */
4590 if ((isatty(e.iop->argp->afile) == 0)
4591 && (e.iop == &iostack[0]
4592 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4593 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4594 bufid = AFID_ID; /* AFID_ID = 0 */
4596 e.iop->argp->afid = bufid; /* assign buffer id */
4599 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4600 iostack, e.iop, e.iop->argp->afbuf));
4601 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4602 &mainbuf, &sharedbuf, bufid, e.iop));
4606 e.iop->prev = ~'\n';
4611 if (fn == filechar || fn == linechar)
4613 else if (fn == (int (*)(struct ioarg *)) gravechar
4614 || fn == (int (*)(struct ioarg *)) qgravechar)
4615 e.iop->task = XGRAVE;
4617 e.iop->task = XOTHER;
4620 static struct io *setbase(struct io *ip)
4630 * Input generating functions
4634 * Produce the characters of a string, then a newline, then EOF.
4636 static int nlchar(struct ioarg *ap)
4640 if (ap->aword == NULL)
4651 * Given a list of words, produce the characters
4652 * in them, with a space after each word.
4654 static int wdchar(struct ioarg *ap)
4669 ap->awordlist = NULL;
4674 * Return the characters of a list of words,
4675 * producing a space between them.
4677 static int dolchar(struct ioarg *ap)
4681 wp = *ap->awordlist++;
4683 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4689 static int xxchar(struct ioarg *ap)
4693 if (ap->aword == NULL)
4704 * Produce the characters from a single word (string).
4706 static int strchar(struct ioarg *ap)
4708 if (ap->aword == NULL)
4710 return *ap->aword++;
4714 * Produce quoted characters from a single word (string).
4716 static int qstrchar(struct ioarg *ap)
4720 if (ap->aword == NULL)
4729 * Return the characters from a file.
4731 static int filechar(struct ioarg *ap)
4735 struct iobuf *bp = ap->afbuf;
4737 if (ap->afid != AFID_NOBUF) {
4738 i = (ap->afid != bp->id);
4739 if (i || bp->bufp == bp->ebufp) {
4741 lseek(ap->afile, ap->afpos, SEEK_SET);
4743 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4751 bp->ebufp = bp->bufp + i;
4755 return *bp->bufp++ & 0177;
4757 #if ENABLE_FEATURE_EDITING
4758 if (interactive && isatty(ap->afile)) {
4759 static char mycommand[BUFSIZ];
4760 static int position = 0, size = 0;
4762 while (size == 0 || position >= size) {
4763 read_line_input(current_prompt, mycommand, BUFSIZ, line_input_state);
4764 size = strlen(mycommand);
4767 c = mycommand[position];
4772 i = safe_read(ap->afile, &c, sizeof(c));
4773 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4777 * Return the characters from a here temp file.
4779 static int herechar(struct ioarg *ap)
4783 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4791 * Return the characters produced by a process (`...`).
4792 * Quote them if required, and remove any trailing newline characters.
4794 static int gravechar(struct ioarg *ap, struct io *iop)
4798 c = qgravechar(ap, iop) & ~QUOTE;
4804 static int qgravechar(struct ioarg *ap, struct io *iop)
4808 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4813 return '\n' | QUOTE;
4817 } else if ((c = filechar(ap)) == '\n') {
4819 while ((c = filechar(ap)) == '\n')
4827 return c != 0 ? c | QUOTE : 0;
4831 * Return a single command (usually the first line) from a file.
4833 static int linechar(struct ioarg *ap)
4841 ap->afile = -1; /* illegal value */
4848 * remap fd into Shell's fd space
4850 static int remap(int fd)
4856 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
4859 for (i = 0; i < NOFILE; i++)
4866 } while (fd >= 0 && fd < e.iofd);
4868 for (i = 0; i < NOFILE; i++)
4873 err("too many files open in shell");
4879 static int openpipe(int *pv)
4885 err("can't create pipe - try again");
4889 static void closepipe(int *pv)
4898 /* -------- here.c -------- */
4904 static void markhere(char *s, struct ioword *iop)
4906 struct here *h, *lh;
4908 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4910 h = (struct here *) space(sizeof(struct here));
4914 h->h_tag = evalstr(s, DOSUB);
4924 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4925 if (lh->h_next == 0) {
4931 iop->io_flag |= IOHERE | IOXHERE;
4932 for (s = h->h_tag; *s; s++) {
4934 iop->io_flag &= ~IOXHERE;
4938 h->h_dosub = iop->io_flag & IOXHERE;
4941 static void gethere(void)
4943 struct here *h, *hp;
4945 DBGPRINTF7(("GETHERE: enter...\n"));
4947 /* Scan here files first leaving inhere list in place */
4948 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
4949 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
4951 /* Make inhere list active - keep list intact for scraphere */
4953 hp->h_next = acthere;
4959 static void readhere(char **name, char *s, int ec)
4962 char tname[30] = ".msh_XXXXXX";
4965 char myline[LINELIM + 1];
4968 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
4970 tf = mkstemp(tname);
4974 *name = strsave(tname, areanum);
4976 if (newenv(setjmp(errpt)) != 0)
4979 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
4982 if (interactive && e.iop <= iostack) {
4983 #if ENABLE_FEATURE_EDITING
4984 current_prompt = cprompt->value;
4986 prs(cprompt->value);
4990 while ((c = my_getc(ec)) != '\n' && c) {
4993 if (thenext >= &myline[LINELIM]) {
5000 if (strcmp(s, myline) == 0 || c == 0)
5003 write(tf, myline, (int) (thenext - myline));
5006 prs("here document `");
5016 * open here temp file.
5017 * if unquoted here, expand here temp file into second temp file.
5019 static int herein(char *hname, int xdoll)
5025 /* Avoid longjmp clobbering */
5031 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5033 hf = open(hname, 0);
5039 char tname[30] = ".msh_XXXXXX";
5042 tf = mkstemp(tname);
5046 if (newenv(setjmp(errpt)) == 0) {
5047 PUSHIO(afile, hf, herechar);
5049 while ((c = subgetc(0, 0)) != 0) {
5051 write(tf, &c, sizeof c);
5057 tf = open(tname, 0);
5064 static void scraphere(void)
5068 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5070 for (h = inhere; h != NULL; h = h->h_next) {
5071 if (h->h_iop && h->h_iop->io_name)
5072 unlink(h->h_iop->io_name);
5077 /* unlink here temp files before a freearea(area) */
5078 static void freehere(int area)
5080 struct here *h, *hl;
5082 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5085 for (h = acthere; h != NULL; h = h->h_next)
5086 if (getarea((char *) h) >= area) {
5087 if (h->h_iop->io_name != NULL)
5088 unlink(h->h_iop->io_name);
5090 acthere = h->h_next;
5092 hl->h_next = h->h_next;
5098 /* -------- sh.c -------- */
5103 int msh_main(int argc, char **argv);
5104 int msh_main(int argc, char **argv)
5110 int (*iof) (struct ioarg *);
5112 #if ENABLE_FEATURE_EDITING
5113 line_input_state = new_line_input_t(FOR_SHELL);
5116 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5122 assign(*ap++, !COPYV);
5123 for (ap = environ; *ap;)
5124 export(lookup(*ap++));
5129 shell = lookup("SHELL");
5130 if (shell->value == null)
5131 setval(shell, (char *)DEFAULT_SHELL);
5134 homedir = lookup("HOME");
5135 if (homedir->value == null)
5136 setval(homedir, "/");
5139 setval(lookup("$"), putn(getpid()));
5141 path = lookup("PATH");
5142 if (path->value == null) {
5144 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
5146 setval(path, "/bin:/usr/bin");
5150 ifs = lookup("IFS");
5151 if (ifs->value == null)
5152 setval(ifs, " \t\n");
5155 mshdbg_var = lookup("MSHDEBUG");
5156 if (mshdbg_var->value == null)
5157 setval(mshdbg_var, "0");
5160 prompt = lookup("PS1");
5161 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5162 if (prompt->value == null)
5164 setval(prompt, DEFAULT_USER_PROMPT);
5165 if (geteuid() == 0) {
5166 setval(prompt, DEFAULT_ROOT_PROMPT);
5167 prompt->status &= ~EXPORT;
5169 cprompt = lookup("PS2");
5170 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5171 if (cprompt->value == null)
5173 setval(cprompt, "> ");
5179 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5180 for (s = argv[0] + 1; *s; s++)
5183 prompt->status &= ~EXPORT;
5184 cprompt->status &= ~EXPORT;
5186 setval(cprompt, "");
5189 PUSHIO(aword, *++argv, iof = nlchar);
5197 /* standard input */
5201 prompt->status &= ~EXPORT;
5209 if (*s >= 'a' && *s <= 'z')
5217 if (iof == filechar && --argc > 0) {
5219 setval(cprompt, "");
5220 prompt->status &= ~EXPORT;
5221 cprompt->status &= ~EXPORT;
5223 /* Shell is non-interactive, activate printf-based debug */
5225 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5229 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5233 exit(1); /* Exit on error */
5239 /* This won't be true if PUSHIO has been called, say from newfile() above */
5240 if (e.iop < iostack) {
5241 PUSHIO(afile, 0, iof);
5242 if (isatty(0) && isatty(1) && !cflag) {
5244 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5246 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
5248 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
5250 printf("Enter 'help' for a list of built-in commands.\n\n");
5255 signal(SIGQUIT, qflag);
5256 if (name && name[0] == '-') {
5258 f = open(".profile", 0);
5261 f = open("/etc/profile", 0);
5266 signal(SIGTERM, sig);
5268 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5269 signal(SIGINT, onintr);
5274 for (ap = ++argv; --argc > 0;) {
5276 if (assign(*ap, !COPYV)) {
5277 dolc--; /* keyword */
5283 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5285 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
5288 if (interactive && e.iop <= iostack) {
5289 #if ENABLE_FEATURE_EDITING
5290 current_prompt = prompt->value;
5296 /* Ensure that getenv("PATH") stays current */
5297 setenv("PATH", path->value, 1);
5300 DBGPRINTF(("MSH_MAIN: returning.\n"));
5305 * Copyright (c) 1987,1997, Prentice Hall
5306 * All rights reserved.
5308 * Redistribution and use of the MINIX operating system in source and
5309 * binary forms, with or without modification, are permitted provided
5310 * that the following conditions are met:
5312 * Redistributions of source code must retain the above copyright
5313 * notice, this list of conditions and the following disclaimer.
5315 * Redistributions in binary form must reproduce the above
5316 * copyright notice, this list of conditions and the following
5317 * disclaimer in the documentation and/or other materials provided
5318 * with the distribution.
5320 * Neither the name of Prentice Hall nor the names of the software
5321 * authors or contributors may be used to endorse or promote
5322 * products derived from this software without specific prior
5323 * written permission.
5325 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5326 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5327 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5328 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5329 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5330 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5331 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5332 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5333 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5334 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5335 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5336 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.