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.
16 #include <sys/times.h>
23 # include <sys/types.h>
24 # include <sys/stat.h>
25 # include <sys/wait.h>
36 # define bb_dev_null "/dev/null"
37 # define DEFAULT_SHELL "/proc/self/exe"
38 # define CONFIG_BUSYBOX_EXEC_PATH "/proc/self/exe"
39 # define BB_BANNER "busybox standalone"
40 # define ENABLE_FEATURE_SH_STANDALONE 0
41 # define bb_msg_memory_exhausted "memory exhausted"
42 # define xmalloc(size) malloc(size)
43 # define msh_main(argc,argv) main(argc,argv)
44 # define safe_read(fd,buf,count) read(fd,buf,count)
45 # define NOT_LONE_DASH(s) ((s)[0] != '-' || (s)[1])
46 # define LONE_CHAR(s,c) ((s)[0] == (c) && !(s)[1])
47 # define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
48 static char *find_applet_by_name(const char *applet)
52 static char *utoa_to_buf(unsigned n, char *buf, unsigned buflen)
55 assert(sizeof(unsigned) == 4);
58 for (i = 1000000000; i; i /= 10) {
60 if (res || out || i == 1) {
70 static char *itoa_to_buf(int n, char *buf, unsigned buflen)
72 if (buflen && n < 0) {
77 return utoa_to_buf((unsigned)n, buf, buflen);
79 static char local_buf[12];
80 static char *itoa(int n)
82 *(itoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
87 extern char **environ;
90 /*#define MSHDEBUG 1*/
93 int mshdbg = MSHDEBUG;
95 #define DBGPRINTF(x) if (mshdbg>0) printf x
96 #define DBGPRINTF0(x) if (mshdbg>0) printf x
97 #define DBGPRINTF1(x) if (mshdbg>1) printf x
98 #define DBGPRINTF2(x) if (mshdbg>2) printf x
99 #define DBGPRINTF3(x) if (mshdbg>3) printf x
100 #define DBGPRINTF4(x) if (mshdbg>4) printf x
101 #define DBGPRINTF5(x) if (mshdbg>5) printf x
102 #define DBGPRINTF6(x) if (mshdbg>6) printf x
103 #define DBGPRINTF7(x) if (mshdbg>7) printf x
104 #define DBGPRINTF8(x) if (mshdbg>8) printf x
105 #define DBGPRINTF9(x) if (mshdbg>9) printf x
109 #define RCPRINTF(x) if (mshdbg_rc) printf x
114 #define DBGPRINTF0(x) ((void)0)
115 #define DBGPRINTF1(x) ((void)0)
116 #define DBGPRINTF2(x) ((void)0)
117 #define DBGPRINTF3(x) ((void)0)
118 #define DBGPRINTF4(x) ((void)0)
119 #define DBGPRINTF5(x) ((void)0)
120 #define DBGPRINTF6(x) ((void)0)
121 #define DBGPRINTF7(x) ((void)0)
122 #define DBGPRINTF8(x) ((void)0)
123 #define DBGPRINTF9(x) ((void)0)
125 #define RCPRINTF(x) ((void)0)
127 #endif /* MSHDEBUG */
130 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
131 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
132 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
134 # define DEFAULT_ROOT_PROMPT "# "
135 # define DEFAULT_USER_PROMPT "$ "
139 /* -------- sh.h -------- */
145 #define NPUSH 8 /* limit to input nesting */
148 #define NOFILE 20 /* Number of open files */
149 #define NUFILE 10 /* Number of user-accessible files */
150 #define FDBASE 10 /* First file usable by Shell */
153 * values returned by wait
155 #define WAITSIG(s) ((s)&0177)
156 #define WAITVAL(s) (((s)>>8)&0377)
157 #define WAITCORE(s) (((s)&0200)!=0)
160 * library and system definitions
162 typedef void xint; /* base type of jmp_buf, for not broken compilers */
168 #define NOBLOCK ((struct op *)NULL)
169 #define NOWORD ((char *)NULL)
170 #define NOWORDS ((char **)NULL)
171 #define NOPIPE ((int *)NULL)
178 short io_unit; /* unit affected */
179 short io_flag; /* action (below) */
180 char *io_name; /* file name */
183 #define IOREAD 1 /* < */
184 #define IOHERE 2 /* << (here file) */
185 #define IOWRITE 4 /* > */
186 #define IOCAT 8 /* >> */
187 #define IOXHERE 16 /* ${}, ` in << */
188 #define IODUP 32 /* >&digit */
189 #define IOCLOSE 64 /* >&- */
191 #define IODEFAULT (-1) /* token for default IO unit */
195 * Description of a command or an operation on commands.
196 * Might eventually use a union.
199 int type; /* operation type, see below */
200 char **words; /* arguments to a command */
201 struct ioword **ioact; /* IO actions (eg, < > >>) */
204 char *str; /* identifier for case and for */
207 #define TCOM 1 /* command */
208 #define TPAREN 2 /* (c-list) */
209 #define TPIPE 3 /* a | b */
210 #define TLIST 4 /* a [&;] b */
211 #define TOR 5 /* || */
212 #define TAND 6 /* && */
220 #define TPAT 14 /* pattern in case */
221 #define TBRACE 15 /* {c-list} */
222 #define TASYNC 16 /* c & */
223 /* Added to support "." file expansion */
226 /* Strings for names to make debug easier */
228 static const char *const T_CMD_NAMES[] = {
251 * actions determining the environment of a process
253 #define BIT(i) (1<<(i))
254 #define FEXEC BIT(0) /* execute without forking */
256 #define AREASIZE (90000)
259 * flags to control evaluation of words
261 #define DOSUB 1 /* interpret $, `, and quotes */
262 #define DOBLANK 2 /* perform blank interpretation */
263 #define DOGLOB 4 /* interpret [?* */
264 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
265 #define DOTRIM 16 /* trim resulting string */
267 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
271 static int newfile(char *s);
276 struct brkcon *nextlev;
283 * -k: look for name=value everywhere on command line
285 * -t: exit after reading and executing one command
288 * -u: unset variables net diagnostic
290 static char flags['z' - 'a' + 1];
291 /* this looks weird, but is OK ... we index flag with 'a'...'z' */
292 static char *flag = flags - 'a';
294 /* moved to G: static char *trap[_NSIG + 1]; */
295 /* moved to G: static char ourtrap[_NSIG + 1]; */
296 static int trapset; /* trap pending */
298 static int yynerrs; /* yacc */
300 /* moved to G: static char line[LINELIM]; */
302 #if ENABLE_FEATURE_EDITING
303 static char *current_prompt;
304 static line_input_t *line_input_state;
311 static const char *rexecve(char *c, char **v, char **envp);
312 static char *evalstr(char *cp, int f);
313 static char *putn(int n);
314 static char *unquote(char *as);
315 static int rlookup(char *n);
316 static struct wdblock *glob(char *cp, struct wdblock *wb);
317 static int my_getc(int ec);
318 static int subgetc(char ec, int quoted);
319 static char **makenv(int all, struct wdblock *wb);
320 static char **eval(char **ap, int f);
321 static int setstatus(int s);
322 static int waitfor(int lastpid, int canintr);
324 static void onintr(int s); /* SIGINT handler */
326 static int newenv(int f);
327 static void quitenv(void);
328 static void next(int f);
329 static void setdash(void);
330 static void onecommand(void);
331 static void runtrap(int i);
334 /* -------- area stuff -------- */
336 #define REGSIZE sizeof(struct region)
338 /* #define SHRINKBY (64) */
342 #define ALIGN (sizeof(int)-1)
351 /* -------- grammar stuff -------- */
376 /* Added for "." file expansion */
379 #define YYERRCODE 300
382 #define CONTIN 01 /* skip new lines to complete command */
384 static struct op *pipeline(int cf);
385 static struct op *andor(void);
386 static struct op *c_list(void);
387 static int synio(int cf);
388 static void musthave(int c, int cf);
389 static struct op *simple(void);
390 static struct op *nested(int type, int mark);
391 static struct op *command(int cf);
392 static struct op *dogroup(int onlydone);
393 static struct op *thenpart(void);
394 static struct op *elsepart(void);
395 static struct op *caselist(void);
396 static struct op *casepart(void);
397 static char **pattern(void);
398 static char **wordlist(void);
399 static struct op *list(struct op *t1, struct op *t2);
400 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
401 static struct op *newtp(void);
402 static struct op *namelist(struct op *t);
403 static char **copyw(void);
404 static void word(char *cp);
405 static struct ioword **copyio(void);
406 static struct ioword *io(int u, int f, char *cp);
407 static int yylex(int cf);
408 static int collect(int c, int c1);
409 static int dual(int c);
410 static void diag(int ec);
411 static char *tree(unsigned size);
413 /* -------- var.h -------- */
422 #define COPYV 1 /* flag to setval, suggesting copy */
423 #define RONLY 01 /* variable is read-only */
424 #define EXPORT 02 /* variable is to be exported */
425 #define GETCELL 04 /* name & value space was got with getcell */
427 static int yyparse(void);
429 static int execute(struct op *t, int *pin, int *pout, int act);
432 #define AFID_NOBUF (~0)
436 /* -------- io.h -------- */
439 unsigned id; /* buffer id */
440 char buf[512]; /* buffer */
441 char *bufp; /* pointer into buffer */
442 char *ebufp; /* pointer to end of buffer */
445 /* possible arguments to an IO function */
449 int afile; /* file descriptor */
450 unsigned afid; /* buffer id */
451 long afpos; /* file position */
452 struct iobuf *afbuf; /* buffer for this file */
455 /* an input generator's state */
457 int (*iofn) (struct ioarg *, struct io *);
460 char prev; /* previous character read by readc() */
461 char nlcount; /* for `'s */
462 char xchar; /* for `'s */
463 char task; /* reason for pushed IO */
466 #define XOTHER 0 /* none of the below */
467 #define XDOLL 1 /* expanding ${} */
468 #define XGRAVE 2 /* expanding `'s */
469 #define XIO 3 /* file IO */
471 /* in substitution */
472 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
474 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
475 /* moved to G: static struct ioarg ioargstack[NPUSH]; */
476 static struct io iostack[NPUSH];
477 /* moved to G: static struct iobuf sharedbuf = { AFID_NOBUF }; */
478 /* moved to G: static struct iobuf mainbuf = { AFID_NOBUF }; */
479 static unsigned bufid = AFID_ID; /* buffer id counter */
481 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
485 * input generators for IO structure
487 static int nlchar(struct ioarg *ap);
488 static int strchar(struct ioarg *ap);
489 static int qstrchar(struct ioarg *ap);
490 static int filechar(struct ioarg *ap);
491 static int herechar(struct ioarg *ap);
492 static int linechar(struct ioarg *ap);
493 static int gravechar(struct ioarg *ap, struct io *iop);
494 static int qgravechar(struct ioarg *ap, struct io *iop);
495 static int dolchar(struct ioarg *ap);
496 static int wdchar(struct ioarg *ap);
497 static void scraphere(void);
498 static void freehere(int area);
499 static void gethere(void);
500 static void markhere(char *s, struct ioword *iop);
501 static int herein(char *hname, int xdoll);
502 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
505 static int eofc(void);
506 static int readc(void);
507 static void unget(int c);
508 static void ioecho(char c);
514 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
515 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
516 static int remap(int fd);
517 static int openpipe(int *pv);
518 static void closepipe(int *pv);
519 static struct io *setbase(struct io *ip);
521 /* -------- word.h -------- */
523 #define NSTART 16 /* default number of words to allow for initially */
528 /* bounds are arbitrary */
532 static struct wdblock *addword(char *wd, struct wdblock *wb);
533 static struct wdblock *newword(int nw);
534 static char **getwords(struct wdblock *wb);
536 /* -------- misc stuff -------- */
538 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
539 static int iosetup(struct ioword *iop, int pipein, int pipeout);
540 static void brkset(struct brkcon *bc);
541 static int dolabel(struct op *t);
542 static int dohelp(struct op *t);
543 static int dochdir(struct op *t);
544 static int doshift(struct op *t);
545 static int dologin(struct op *t);
546 static int doumask(struct op *t);
547 static int doexec(struct op *t);
548 static int dodot(struct op *t);
549 static int dowait(struct op *t);
550 static int doread(struct op *t);
551 static int doeval(struct op *t);
552 static int dotrap(struct op *t);
553 static int getsig(char *s);
554 static void setsig(int n, sighandler_t f);
555 static int getn(char *as);
556 static int dobreak(struct op *t);
557 static int docontinue(struct op *t);
558 static int brkcontin(char *cp, int val);
559 static int doexit(struct op *t);
560 static int doexport(struct op *t);
561 static int doreadonly(struct op *t);
562 static void rdexp(char **wp, void (*f) (struct var *), int key);
563 static void badid(char *s);
564 static int doset(struct op *t);
565 static void varput(char *s, int out);
566 static int dotimes(struct op *t);
567 static int expand(const char *cp, struct wdblock **wbp, int f);
568 static char *blank(int f);
569 static int dollar(int quoted);
570 static int grave(int quoted);
571 static void globname(char *we, char *pp);
572 static char *generate(char *start1, char *end1, char *middle, char *end);
573 static int anyspcl(struct wdblock *wb);
574 static int xstrcmp(char *p1, char *p2);
575 static void glob0(char *a0, unsigned a1, int a2,
576 int (*a3) (char *, char *));
577 static void readhere(char **name, char *s, int ec);
578 static int xxchar(struct ioarg *ap);
583 struct ioword *h_iop;
587 static const char * const signame[] = {
590 NULL, /* interrupt */
592 "Illegal instruction",
596 "Floating Point Exception",
601 NULL, /* broken pipe */
606 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
612 static const struct res restab[] = {
637 int (*builtinfunc)(struct op *t);
639 static const struct builtincmd builtincmds[] = {
642 { "break" , dobreak },
644 { "continue", docontinue },
648 { "export" , doexport },
650 { "login" , dologin },
651 { "newgrp" , dologin },
653 { "readonly", doreadonly },
655 { "shift" , doshift },
656 { "times" , dotimes },
658 { "umask" , doumask },
663 static struct op *scantree(struct op *);
664 static struct op *dowholefile(int, int);
672 static int interactive; /* Is this an interactive shell */
674 static int multiline; /* \n changed to ; */
675 static struct op *outtree; /* result from parser */
678 static struct brkcon *brklist;
680 static struct wdblock *wdlist;
681 static struct wdblock *iolist;
684 static struct var *mshdbg_var;
686 static struct var *vlist; /* dictionary */
687 static struct var *homedir; /* home directory */
688 static struct var *prompt; /* main prompt */
689 static struct var *cprompt; /* continuation prompt */
690 static struct var *path; /* search path for commands */
691 static struct var *shell; /* shell to interpret command files */
692 static struct var *ifs; /* field separators */
694 static int areanum; /* current allocation area */
695 static int intr; /* interrupt pending */
697 static char *null = (char*)""; /* null value for variable */
698 static int heedint = 1; /* heed interrupt signals */
699 static void (*qflag) (int) = SIG_IGN;
703 static int iounit = IODEFAULT;
704 static YYSTYPE yylval;
705 static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
707 static struct here *inhere; /* list of hear docs while parsing */
708 static struct here *acthere; /* list of active here documents */
709 static struct region *areabot; /* bottom of area */
710 static struct region *areatop; /* top of area */
711 static struct region *areanxt; /* starting point of scan */
713 static void *brkaddr;
716 * parsing & execution environment
722 xint *errpt; /* void * */
727 static struct env e = {
728 NULL /* set to line in main() */, /* linep: char ptr */
729 iostack, /* iobase: struct io ptr */
730 iostack - 1, /* iop: struct io ptr */
731 (xint *) NULL, /* errpt: void ptr for errors? */
732 FDBASE, /* iofd: file desc */
733 (struct env *) NULL /* oenv: struct env ptr */
738 char ourtrap[_NSIG + 1];
739 char *trap[_NSIG + 1];
740 struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
741 struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
742 struct ioarg ioargstack[NPUSH];
743 char filechar_cmdbuf[BUFSIZ];
745 char child_cmd[LINELIM];
748 #define G (*ptr_to_globals)
749 #define ourtrap (G.ourtrap )
750 #define trap (G.trap )
751 #define sharedbuf (G.sharedbuf )
752 #define mainbuf (G.mainbuf )
753 #define ioargstack (G.ioargstack )
754 #define filechar_cmdbuf (G.filechar_cmdbuf)
755 #define line (G.line )
756 #define child_cmd (G.child_cmd )
760 void print_t(struct op *t)
762 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
763 T_CMD_NAMES[t->type], t->words, t->ioact));
766 DBGPRINTF(("T: W1: %s", t->words[0]));
770 void print_tree(struct op *head)
773 DBGPRINTF(("PRINT_TREE: no tree\n"));
777 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
781 print_tree(head->left);
784 print_tree(head->right);
786 #endif /* MSHDEBUG */
792 static void prs(const char *s)
795 write(2, s, strlen(s));
798 static void prn(unsigned u)
803 static void echo(char **wp)
808 for (i = 0; wp[i]; i++) {
816 static void closef(int i)
822 static void closeall(void)
826 for (u = NUFILE; u < NOFILE;)
831 /* fail but return to process next command */
832 static void fail(void) ATTRIBUTE_NORETURN;
833 static void fail(void)
839 /* abort shell (or fail in subshell) */
840 static void leave(void) ATTRIBUTE_NORETURN;
841 static void leave(void)
843 DBGPRINTF(("LEAVE: leave called!\n"));
854 static void warn(const char *s)
865 static void err(const char *s)
875 e.iop = e.iobase = iostack;
879 /* -------- area.c -------- */
882 * All memory between (char *)areabot and (char *)(areatop+1) is
883 * exclusively administered by the area management routines.
884 * It is assumed that sbrk() and brk() manipulate the high end.
888 void * __q = (void *)-1; \
889 if (brkaddr + (int)(X) < brktop) { \
891 brkaddr += (int)(X); \
896 static void initarea(void)
898 brkaddr = xmalloc(AREASIZE);
899 brktop = brkaddr + AREASIZE;
901 while ((long) sbrk(0) & ALIGN)
903 areabot = (struct region *) sbrk(REGSIZE);
905 areabot->next = areabot;
906 areabot->area = BUSY;
911 static char *getcell(unsigned nbytes)
914 struct region *p, *q;
921 /* silly and defeats the algorithm */
923 * round upwards and add administration area
925 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
928 if (p->area > areanum) {
932 while ((q = p->next)->area > areanum && q != areanxt)
935 * exit loop if cell big enough
944 i = nregio >= GROWBY ? nregio : GROWBY;
945 p = (struct region *) sbrk(i * REGSIZE);
946 if (p == (struct region *) -1)
951 abort(); /* allocated areas are contiguous */
961 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
963 areanxt = p + nregio;
966 * split into requested area and rest
968 if (areanxt + 1 > q) {
970 abort(); /* insufficient space left for admin */
973 areanxt->area = FREE;
977 return (char *) (p + 1);
980 static void freecell(char *cp)
984 p = (struct region *) cp;
992 #define DELETE(obj) freecell((char *)obj)
994 static void freearea(int a)
996 struct region *p, *top;
999 for (p = areabot; p != top; p = p->next)
1004 static void setarea(char *cp, int a)
1008 p = (struct region *) cp;
1013 static int getarea(char *cp)
1015 return ((struct region *) cp - 1)->area;
1018 static void garbage(void)
1020 struct region *p, *q, *top;
1023 for (p = areabot; p != top; p = p->next) {
1024 if (p->area > areanum) {
1025 while ((q = p->next)->area > areanum)
1031 if (areatop >= q + SHRINKBY && q->area > areanum) {
1032 brk((char *) (q + 1));
1040 static char *space(int n)
1046 err("out of string space");
1050 static char *strsave(const char *s, int a)
1054 cp = space(strlen(s) + 1);
1056 // FIXME: I highly doubt this is good.
1065 /* -------- var.c -------- */
1067 static int eqname(const char *n1, const char *n2)
1069 for (; *n1 != '=' && *n1 != '\0'; n1++)
1072 return *n2 == '\0' || *n2 == '=';
1075 static const char *findeq(const char *cp)
1077 while (*cp != '\0' && *cp != '=')
1083 * Find the given name in the dictionary
1084 * and return its value. If the name was
1085 * not previously there, enter it now and
1086 * return a null value.
1088 static struct var *lookup(const char *n)
1090 // FIXME: dirty hack
1091 static struct var dummy;
1099 dummy.name = (char*)n;
1100 for (c = 0; isdigit(*n) && c < 1000; n++)
1101 c = c * 10 + *n - '0';
1102 dummy.status = RONLY;
1103 dummy.value = (c <= dolc ? dolv[c] : null);
1107 for (vp = vlist; vp; vp = vp->next)
1108 if (eqname(vp->name, n))
1112 vp = (struct var *) space(sizeof(*vp));
1113 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1114 dummy.name = dummy.value = (char*)"";
1119 while ((*xp = *n++) != '\0' && *xp != '=')
1123 setarea((char *) vp, 0);
1124 setarea((char *) vp->name, 0);
1127 vp->status = GETCELL;
1133 * if name is not NULL, it must be
1134 * a prefix of the space `val',
1136 * this is all so that exporting
1137 * values is reasonably painless.
1139 static void nameval(struct var *vp, const char *val, const char *name)
1145 if (vp->status & RONLY) {
1147 while (*xp && *xp != '=')
1148 putc(*xp++, stderr);
1149 err(" is read-only");
1154 xp = space(strlen(vp->name) + strlen(val) + 2);
1157 /* make string: name=value */
1161 while ((*xp = *cp++) != '\0' && *xp != '=')
1168 if (vp->status & GETCELL)
1169 freecell(vp->name); /* form new string `name=value' */
1170 vp->name = (char*)name;
1171 vp->value = (char*)val;
1176 * give variable at `vp' the value `val'.
1178 static void setval(struct var *vp, const char *val)
1180 nameval(vp, val, NULL);
1183 static void export(struct var *vp)
1185 vp->status |= EXPORT;
1188 static void ronly(struct var *vp)
1190 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1191 vp->status |= RONLY;
1194 static int isassign(const char *s)
1197 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1200 /* no isalpha() - we shouldn't use locale */
1201 /* c | 0x20 - lowercase (Latin) letters */
1202 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1213 && (unsigned)(c - '0') > 9 /* not number */
1214 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1221 static int assign(const char *s, int cf)
1226 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1228 if (!isalpha(*s) && *s != '_')
1230 for (cp = s; *cp != '='; cp++)
1231 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1234 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1236 vp->status &= ~GETCELL;
1240 static int checkname(char *cp)
1242 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1244 if (!isalpha(*cp++) && *(cp - 1) != '_')
1247 if (!isalnum(*cp++) && *(cp - 1) != '_')
1252 static void putvlist(int f, int out)
1256 for (vp = vlist; vp; vp = vp->next) {
1257 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1258 if (vp->status & EXPORT)
1259 write(out, "export ", 7);
1260 if (vp->status & RONLY)
1261 write(out, "readonly ", 9);
1262 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1263 write(out, "\n", 1);
1272 static void sig(int i)
1278 static void runtrap(int i)
1283 if (trapstr == NULL)
1289 RUN(aword, trapstr, nlchar);
1293 static void setdash(void)
1297 char m['z' - 'a' + 1];
1300 for (c = 'a'; c <= 'z'; c++)
1304 setval(lookup("-"), m);
1307 static int newfile(char *s)
1311 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1314 if (NOT_LONE_DASH(s)) {
1315 DBGPRINTF(("NEWFILE: s is %s\n", s));
1319 err(": cannot open");
1329 struct op *scantree(struct op *head)
1336 if (head->left != NULL) {
1337 dotnode = scantree(head->left);
1342 if (head->right != NULL) {
1343 dotnode = scantree(head->right);
1348 if (head->words == NULL)
1351 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1353 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1354 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1362 static void onecommand(void)
1367 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1387 setjmp(failpt); /* Bruce Evans' fix */
1389 if (setjmp(failpt) || yyparse() || intr) {
1390 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1395 if (!interactive && intr)
1408 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1410 execute(outtree, NOPIPE, NOPIPE, 0);
1413 if (!interactive && intr) {
1425 static int newenv(int f)
1429 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1436 ep = (struct env *) space(sizeof(*ep));
1449 static void quitenv(void)
1454 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1460 /* should close `'d files */
1462 while (--fd >= e.iofd)
1468 * Is character c in s?
1470 static int any(int c, const char *s)
1479 * Is any character from s1 in s2?
1481 static int anys(const char *s1, const char *s2)
1489 static char *putn(int n)
1494 static void next(int f)
1496 PUSHIO(afile, f, filechar);
1499 static void onintr(int s) /* ANSI C requires a parameter */
1501 signal(SIGINT, onintr);
1508 } else if (heedint) {
1515 /* -------- gmatch.c -------- */
1517 * int gmatch(string, pattern)
1518 * char *string, *pattern;
1520 * Match a pattern as in sh(1).
1525 #define QMASK (CMASK & ~QUOTE)
1526 #define NOT '!' /* might use ^ */
1528 static const char *cclass(const char *p, int sub)
1530 int c, d, not, found;
1540 if (p[1] == '-' && p[2] != ']') {
1545 if (c == sub || (c <= sub && sub <= d))
1547 } while (*++p != ']');
1548 return found ? p + 1 : NULL;
1551 static int gmatch(const char *s, const char *p)
1555 if (s == NULL || p == NULL)
1558 while ((pc = *p++ & CMASK) != '\0') {
1575 if (*p == '\0' || gmatch(s, p))
1577 } while (*s++ != '\0');
1581 if (sc != (pc & ~QUOTE))
1589 /* -------- csyn.c -------- */
1591 * shell: syntax (C version)
1594 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1595 static void yyerror(const char *s)
1598 if (interactive && e.iop <= iostack) {
1600 while (eofc() == 0 && yylex(0) != '\n');
1606 static void zzerr(void) ATTRIBUTE_NORETURN;
1607 static void zzerr(void)
1609 yyerror("syntax error");
1614 DBGPRINTF7(("YYPARSE: enter...\n"));
1621 return (yynerrs != 0);
1624 static struct op *pipeline(int cf)
1629 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1633 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1636 while ((c = yylex(0)) == '|') {
1637 p = command(CONTIN);
1639 DBGPRINTF8(("PIPELINE: error!\n"));
1643 if (t->type != TPAREN && t->type != TCOM) {
1644 /* shell statement */
1645 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1648 t = block(TPIPE, t, p, NOWORDS);
1653 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1657 static struct op *andor(void)
1662 DBGPRINTF7(("ANDOR: enter...\n"));
1666 DBGPRINTF9(("ANDOR: t=%p\n", t));
1669 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1670 p = pipeline(CONTIN);
1672 DBGPRINTF8(("ANDOR: error!\n"));
1676 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1682 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1686 static struct op *c_list(void)
1691 DBGPRINTF7(("C_LIST: enter...\n"));
1698 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1700 while ((c = yylex(0)) == ';' || c == '&'
1701 || (multiline && c == '\n')) {
1709 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1717 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1721 static int synio(int cf)
1727 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1730 if (c != '<' && c != '>') {
1737 iop = io(iounit, i, yylval.cp);
1741 markhere(yylval.cp, iop);
1743 DBGPRINTF7(("SYNIO: returning 1\n"));
1747 static void musthave(int c, int cf)
1749 peeksym = yylex(cf);
1751 DBGPRINTF7(("MUSTHAVE: error!\n"));
1758 static struct op *simple(void)
1764 switch (peeksym = yylex(0)) {
1785 static struct op *nested(int type, int mark)
1789 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1795 return block(type, t, NOBLOCK, NOWORDS);
1798 static struct op *command(int cf)
1801 struct wdblock *iosave;
1804 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1830 t = nested(TPAREN, ')');
1834 t = nested(TBRACE, '}');
1844 t->words = wordlist();
1846 if (c != '\n' && c != ';')
1848 t->left = dogroup(0);
1856 t->type = c == WHILE ? TWHILE : TUNTIL;
1858 t->right = dogroup(1);
1870 musthave(IN, CONTIN);
1873 t->left = caselist();
1884 t->right = thenpart();
1893 musthave(WORD, 0); /* gets name of file */
1894 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1896 word(yylval.cp); /* add word to wdlist */
1897 word(NOWORD); /* terminate wdlist */
1898 t->words = copyw(); /* dup wdlist */
1908 DBGPRINTF(("COMMAND: returning %p\n", t));
1913 static struct op *dowholefile(int type, int mark)
1917 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1922 t = block(type, t, NOBLOCK, NOWORDS);
1923 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1927 static struct op *dogroup(int onlydone)
1933 if (c == DONE && onlydone)
1942 static struct op *thenpart(void)
1955 if (t->left == NULL)
1957 t->right = elsepart();
1961 static struct op *elsepart(void)
1966 switch (c = yylex(0)) {
1977 t->right = thenpart();
1986 static struct op *caselist(void)
1991 while ((peeksym = yylex(CONTIN)) != ESAC) {
1992 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1993 t = list(t, casepart());
1996 DBGPRINTF(("CASELIST, returning t=%p\n", t));
2000 static struct op *casepart(void)
2004 DBGPRINTF7(("CASEPART: enter...\n"));
2008 t->words = pattern();
2011 peeksym = yylex(CONTIN);
2012 if (peeksym != ESAC)
2013 musthave(BREAK, CONTIN);
2015 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2020 static char **pattern(void)
2037 static char **wordlist(void)
2047 while ((c = yylex(0)) == WORD)
2055 * supporting functions
2057 static struct op *list(struct op *t1, struct op *t2)
2059 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2066 return block(TLIST, t1, t2, NOWORDS);
2069 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2073 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2081 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2087 /* See if given string is a shell multiline (FOR, IF, etc) */
2088 static int rlookup(char *n)
2090 const struct res *rp;
2092 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2094 for (rp = restab; rp->r_name; rp++)
2095 if (strcmp(rp->r_name, n) == 0) {
2096 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2097 return rp->r_val; /* Return numeric code for shell multiline */
2100 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2101 return 0; /* Not a shell multiline */
2104 static struct op *newtp(void)
2108 t = (struct op *) tree(sizeof(*t));
2116 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2121 static struct op *namelist(struct op *t)
2124 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2125 T_CMD_NAMES[t->type], iolist));
2128 iolist = addword((char *) NULL, iolist);
2129 t->ioact = copyio();
2133 if (t->type != TCOM) {
2134 if (t->type != TPAREN && t->ioact != NULL) {
2135 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2136 t->ioact = t->left->ioact;
2137 t->left->ioact = NULL;
2148 static char **copyw(void)
2152 wd = getwords(wdlist);
2157 static void word(char *cp)
2159 wdlist = addword(cp, wdlist);
2162 static struct ioword **copyio(void)
2164 struct ioword **iop;
2166 iop = (struct ioword **) getwords(iolist);
2171 static struct ioword *io(int u, int f, char *cp)
2175 iop = (struct ioword *) tree(sizeof(*iop));
2179 iolist = addword((char *) iop, iolist);
2183 static int yylex(int cf)
2203 line[LINELIM - 1] = '\0';
2206 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2211 if (any(c, "0123456789")) {
2214 if (c1 == '<' || c1 == '>') {
2223 case '#': /* Comment, skip to next newline or End-of-string */
2224 while ((c = my_getc(0)) != '\0' && c != '\n');
2229 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2233 DBGPRINTF9(("YYLEX: found $\n"));
2237 c = collect(c, '}');
2256 /* If more chars process them, else return NULL char */
2274 if (multiline || cf & CONTIN) {
2275 if (interactive && e.iop <= iostack) {
2276 #if ENABLE_FEATURE_EDITING
2277 current_prompt = cprompt->value;
2279 prs(cprompt->value);
2296 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2297 if (e.linep >= elinep)
2298 err("word too long");
2305 if (any(c, "\"'`$"))
2318 yylval.cp = strsave(line, areanum);
2323 static int collect(int c, int c1)
2327 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2330 while ((c = my_getc(c1)) != c1) {
2339 if (interactive && c == '\n' && e.iop <= iostack) {
2340 #if ENABLE_FEATURE_EDITING
2341 current_prompt = cprompt->value;
2343 prs(cprompt->value);
2351 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2356 /* "multiline commands" helper func */
2357 /* see if next 2 chars form a shell multiline */
2358 static int dual(int c)
2363 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2365 *cp++ = c; /* c is the given "peek" char */
2366 *cp++ = my_getc(0); /* get next char of input */
2367 *cp = '\0'; /* add EOS marker */
2369 c = rlookup(s); /* see if 2 chars form a shell multiline */
2371 unget(*--cp); /* String is not a shell multiline, put peek char back */
2373 return c; /* String is multiline, return numeric multiline (restab) code */
2376 static void diag(int ec)
2380 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2383 if (c == '>' || c == '<') {
2386 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2389 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2390 if (c != '&' || yylval.i == IOHERE)
2396 static char *tree(unsigned size)
2402 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2403 prs("command line too complicated\n");
2414 /* -------- exec.c -------- */
2416 static struct op **find1case(struct op *t, const char *w)
2424 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2428 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2429 T_CMD_NAMES[t->type]));
2431 if (t->type == TLIST) {
2432 tp = find1case(t->left, w);
2434 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2437 t1 = t->right; /* TPAT */
2441 for (wp = t1->words; *wp;) {
2442 cp = evalstr(*wp++, DOSUB);
2443 if (cp && gmatch(w, cp)) {
2444 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2450 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2454 static struct op *findcase(struct op *t, const char *w)
2458 tp = find1case(t, w);
2459 return tp != NULL ? *tp : NULL;
2466 static int execute(struct op *t, int *pin, int *pout, int act)
2469 volatile int i, rv, a;
2473 struct op *outtree_save;
2477 /* Avoid longjmp clobbering */
2482 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2486 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2487 t->type, T_CMD_NAMES[t->type],
2488 ((t->words == NULL) ? "NULL" : t->words[0])));
2492 wp = (wp2 = t->words) != NULL
2493 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2498 DBGPRINTF3(("EXECUTE: TDOT\n"));
2500 outtree_save = outtree;
2502 newfile(evalstr(t->words[0], DOALL));
2504 t->left = dowholefile(TLIST, 0);
2507 outtree = outtree_save;
2510 rv = execute(t->left, pin, pout, 0);
2512 rv = execute(t->right, pin, pout, 0);
2516 rv = execute(t->left, pin, pout, 0);
2520 rv = forkexec(t, pin, pout, act, wp);
2530 pv[0] = remap(pv[0]);
2531 pv[1] = remap(pv[1]);
2532 (void) execute(t->left, pin, pv, 0);
2533 rv = execute(t->right, pv, pout, 0);
2538 (void) execute(t->left, pin, pout, 0);
2539 rv = execute(t->right, pin, pout, 0);
2544 int hinteractive = interactive;
2546 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2549 if (i == 0) { /* child */
2550 signal(SIGINT, SIG_IGN);
2551 signal(SIGQUIT, SIG_IGN);
2553 signal(SIGTERM, SIG_DFL);
2557 open(bb_dev_null, 0);
2559 _exit(execute(t->left, pin, pout, FEXEC));
2561 interactive = hinteractive;
2563 setval(lookup("!"), putn(i));
2578 rv = execute(t->left, pin, pout, 0);
2580 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2581 rv = execute(t1, pin, pout, 0);
2592 while (*wp++ != NULL);
2594 vp = lookup(t->str);
2595 while (setjmp(bc.brkpt))
2599 for (t1 = t->left; i-- && *wp != NULL;) {
2601 rv = execute(t1, pin, pout, 0);
2603 brklist = brklist->nextlev;
2608 while (setjmp(bc.brkpt))
2613 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2614 rv = execute(t->right, pin, pout, 0);
2615 brklist = brklist->nextlev;
2620 if (t->right != NULL) {
2621 rv = !execute(t->left, pin, pout, 0) ?
2622 execute(t->right->left, pin, pout, 0) :
2623 execute(t->right->right, pin, pout, 0);
2628 cp = evalstr(t->str, DOSUB | DOTRIM);
2632 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2633 ((t->str == NULL) ? "NULL" : t->str),
2634 ((cp == NULL) ? "NULL" : cp)));
2636 t1 = findcase(t->left, cp);
2638 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2639 rv = execute(t1, pin, pout, 0);
2640 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2649 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2657 rv = execute(t1, pin, pout, 0);
2670 if (interactive && intr) {
2681 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2685 typedef int (*builtin_func_ptr)(struct op *);
2687 static builtin_func_ptr inbuilt(const char *s) {
2688 const struct builtincmd *bp;
2690 for (bp = builtincmds; bp->name; bp++)
2691 if (strcmp(bp->name, s) == 0)
2692 return bp->builtinfunc;
2697 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2701 builtin_func_ptr shcom = NULL;
2703 const char *cp = NULL;
2704 struct ioword **iopp;
2714 struct brkcon *hbrklist;
2718 /* Avoid longjmp clobbering */
2728 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2730 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2731 ((t->words == NULL) ? "NULL" : t->words[0])));
2735 rv = -1; /* system-detected error */
2736 if (t->type == TCOM) {
2737 while (*wp++ != NULL);
2740 /* strip all initial assignments */
2741 /* not correct wrt PATH=yyy command etc */
2743 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2745 echo(cp ? wp : owp);
2748 if (cp == NULL && t->ioact == NULL) {
2749 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2751 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2752 return setstatus(0);
2755 shcom = inbuilt(cp);
2762 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2765 if (shcom == NULL && (f & FEXEC) == 0) {
2766 /* Save values in case the child process alters them */
2770 hinteractive = interactive;
2775 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2780 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2784 if (newpid > 0) { /* Parent */
2785 /* Restore values */
2789 interactive = hinteractive;
2800 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2803 /* Must be the child process, pid should be 0 */
2804 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2807 signal(SIGINT, SIG_IGN);
2808 signal(SIGQUIT, SIG_IGN);
2819 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2824 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2825 err("piping to/from shell builtins not yet done");
2843 if (shcom != NULL && shcom != doexec) {
2845 err(": cannot redirect shell command");
2851 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2859 i = setstatus((*shcom) (t));
2862 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2866 /* should use FIOCEXCL */
2867 for (i = FDBASE; i < NOFILE; i++)
2870 signal(SIGINT, SIG_DFL);
2871 signal(SIGQUIT, SIG_DFL);
2874 if (t->type == TPAREN)
2875 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2879 cp = rexecve(wp[0], wp, makenv(0, NULL));
2886 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2894 * 0< 1> are ignored as required
2897 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2903 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2906 if (iop->io_unit == IODEFAULT) /* take default */
2907 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2909 if (pipein && iop->io_unit == 0)
2912 if (pipeout && iop->io_unit == 1)
2915 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2916 if ((iop->io_flag & IOHERE) == 0) {
2917 cp = iop->io_name; /* huh?? */
2918 cp = evalstr(cp, DOSUB | DOTRIM);
2923 if (iop->io_flag & IODUP) {
2924 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2926 err(": illegal >& argument");
2930 iop->io_flag = IOCLOSE;
2931 iop->io_flag &= ~(IOREAD | IOWRITE);
2933 switch (iop->io_flag) {
2939 case IOHERE | IOXHERE:
2940 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2941 cp = (char*)"here file";
2944 case IOWRITE | IOCAT:
2947 lseek(u, (long) 0, SEEK_END);
2951 u = creat(cp, 0666);
2955 u = dup2(*cp - '0', iop->io_unit);
2959 close(iop->io_unit);
2968 if (u != iop->io_unit) {
2969 dup2(u, iop->io_unit);
2976 * Enter a new loop level (marked for break/continue).
2978 static void brkset(struct brkcon *bc)
2980 bc->nextlev = brklist;
2985 * Wait for the last process created.
2986 * Print a message for each process found
2987 * that was killed by a signal.
2988 * Ignore interrupt signals while waiting
2989 * unless `canintr' is true.
2991 static int waitfor(int lastpid, int canintr)
2995 int oheedint = heedint;
3002 if (errno != EINTR || canintr)
3008 if (signame[rv] != NULL) {
3009 if (pid != lastpid) {
3016 if (pid != lastpid) {
3025 prs(" - core dumped");
3026 if (rv >= NSIGNAL || signame[rv])
3032 } while (pid != lastpid);
3047 static int setstatus(int s)
3050 setval(lookup("?"), putn(s));
3055 * PATH-searching interface to execve.
3056 * If getenv("PATH") were kept up-to-date,
3057 * execvp might be used.
3059 static const char *rexecve(char *c, char **v, char **envp)
3064 int eacces = 0, asis = 0;
3067 if (ENABLE_FEATURE_SH_STANDALONE) {
3069 if (find_applet_by_name(name)) {
3070 /* We have to exec here since we vforked. Running
3071 * run_applet_and_exit() won't work and bad things
3073 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3077 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3079 sp = any('/', c) ? "" : path->value;
3080 asis = (*sp == '\0');
3081 while (asis || *sp != '\0') {
3084 for (; *sp != '\0'; tp++) {
3087 asis = (*sp == '\0');
3093 for (i = 0; (*tp++ = c[i++]) != '\0';);
3095 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3097 execve(e.linep, v, envp);
3104 execve(DEFAULT_SHELL, v, envp);
3109 return (char *) bb_msg_memory_exhausted;
3112 return "argument list too long";
3119 return errno == ENOENT ? "not found" : "cannot execute";
3123 * Run the command produced by generator `f'
3124 * applied to stream `arg'.
3126 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3129 struct wdblock *swdlist;
3130 struct wdblock *siolist;
3136 /* Avoid longjmp clobbering */
3140 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3141 areanum, outtree, failpt));
3151 if (newenv(setjmp(errpt)) == 0) {
3158 if (setjmp(failpt) == 0 && yyparse() == 0)
3159 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3162 DBGPRINTF(("RUN: error from newenv()!\n"));
3169 freearea(areanum--);
3174 /* -------- do.c -------- */
3177 * built-in commands: doX
3180 static int dohelp(struct op *t)
3183 const struct builtincmd *x;
3185 puts("\nBuilt-in commands:\n"
3186 "-------------------");
3191 col += printf("%c%s", ((col == 0) ? '\t' : ' '), x->name);
3198 #if ENABLE_FEATURE_SH_STANDALONE
3200 const struct bb_applet *applet = applets;
3202 while (applet->name) {
3203 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applet->name);
3213 return EXIT_SUCCESS;
3216 static int dolabel(struct op *t)
3221 static int dochdir(struct op *t)
3223 const char *cp, *er;
3227 cp = homedir->value;
3230 er = ": no home directory";
3235 er = ": bad directory";
3237 prs(cp != NULL ? cp : "cd");
3242 static int doshift(struct op *t)
3246 n = t->words[1] ? getn(t->words[1]) : 1;
3248 err("nothing to shift");
3254 setval(lookup("#"), putn(dolc));
3259 * execute login and newgrp directly
3261 static int dologin(struct op *t)
3266 signal(SIGINT, SIG_DFL);
3267 signal(SIGQUIT, SIG_DFL);
3269 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3276 static int doumask(struct op *t)
3285 for (n = 3 * 4; (n -= 3) >= 0;)
3286 putc('0' + ((i >> n) & 07), stderr);
3289 /* huh??? '8','9' are not allowed! */
3290 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3291 n = n * 8 + (*cp - '0');
3297 static int doexec(struct op *t)
3304 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3310 if (setjmp(failpt) == 0)
3311 execute(t, NOPIPE, NOPIPE, FEXEC);
3317 static int dodot(struct op *t)
3325 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)));
3329 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3332 DBGPRINTF(("DODOT: cp is %s\n", cp));
3334 sp = any('/', cp) ? ":" : path->value;
3336 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3337 ((sp == NULL) ? "NULL" : sp),
3338 ((e.linep == NULL) ? "NULL" : e.linep)));
3342 while (*sp && (*tp = *sp++) != ':')
3347 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3350 i = open(e.linep, 0);
3354 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3356 next(maltmp); /* Basically a PUSHIO */
3358 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3370 static int dowait(struct op *t)
3382 setstatus(waitfor(i, 1));
3386 static int doread(struct op *t)
3392 if (t->words[1] == NULL) {
3393 err("Usage: read name ...");
3396 for (wp = t->words + 1; *wp; wp++) {
3397 for (cp = e.linep; !nl && cp < elinep - 1; cp++) {
3398 nb = read(0, cp, sizeof(*cp));
3399 if (nb != sizeof(*cp))
3402 if (nl || (wp[1] && any(*cp, ifs->value)))
3408 setval(lookup(*wp), e.linep);
3413 static int doeval(struct op *t)
3415 return RUN(awordlist, t->words + 1, wdchar);
3418 static int dotrap(struct op *t)
3423 if (t->words[1] == NULL) {
3424 for (i = 0; i <= _NSIG; i++)
3433 resetsig = isdigit(*t->words[1]);
3434 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3435 n = getsig(t->words[i]);
3439 if (*t->words[1] != '\0') {
3440 trap[n] = strsave(t->words[1], 0);
3449 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3457 static int getsig(char *s)
3462 if (n < 0 || n > _NSIG) {
3463 err("trap: bad signal number");
3469 static void setsig(int n, sighandler_t f)
3473 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3479 static int getn(char *as)
3490 for (n = 0; isdigit(*s); s++)
3491 n = (n * 10) + (*s - '0');
3494 err(": bad number");
3499 static int dobreak(struct op *t)
3501 return brkcontin(t->words[1], 1);
3504 static int docontinue(struct op *t)
3506 return brkcontin(t->words[1], 0);
3509 static int brkcontin(char *cp, int val)
3514 nl = cp == NULL ? 1 : getn(cp);
3521 brklist = bc->nextlev;
3524 err("bad break/continue level");
3528 longjmp(bc->brkpt, 1);
3532 static int doexit(struct op *t)
3539 setstatus(getn(cp));
3541 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3548 static int doexport(struct op *t)
3550 rdexp(t->words + 1, export, EXPORT);
3554 static int doreadonly(struct op *t)
3556 rdexp(t->words + 1, ronly, RONLY);
3560 static void rdexp(char **wp, void (*f) (struct var *), int key)
3562 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3563 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3566 for (; *wp != NULL; wp++) {
3567 if (isassign(*wp)) {
3571 for (cp = *wp; *cp != '='; cp++);
3583 static void badid(char *s)
3586 err(": bad identifier");
3589 static int doset(struct op *t)
3597 for (vp = vlist; vp; vp = vp->next)
3598 varput(vp->name, 1);
3602 /* bad: t->words++; */
3603 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3605 flag['x'] = flag['v'] = 0;
3615 if (*cp >= 'a' && *cp <= 'z')
3624 t->words[0] = dolv[0];
3625 for (n = 1; t->words[n]; n++)
3626 setarea((char *) t->words[n], 0);
3629 setval(lookup("#"), putn(dolc));
3630 setarea((char *) (dolv - 1), 0);
3635 static void varput(char *s, int out)
3637 if (isalnum(*s) || *s == '_') {
3638 write(out, s, strlen(s));
3639 write(out, "\n", 1);
3645 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3646 * This file contains code for the times builtin.
3648 static int dotimes(struct op *t)
3651 long clk_tck = sysconf(_SC_CLK_TCK);
3654 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3655 (int) (buf.tms_utime / clk_tck / 60),
3656 ((double) buf.tms_utime) / clk_tck,
3657 (int) (buf.tms_stime / clk_tck / 60),
3658 ((double) buf.tms_stime) / clk_tck,
3659 (int) (buf.tms_cutime / clk_tck / 60),
3660 ((double) buf.tms_cutime) / clk_tck,
3661 (int) (buf.tms_cstime / clk_tck / 60),
3662 ((double) buf.tms_cstime) / clk_tck);
3667 /* -------- eval.c -------- */
3672 * blank interpretation
3677 static char **eval(char **ap, int f)
3685 /* Avoid longjmp clobbering */
3690 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3696 if (newenv(setjmp(errpt)) == 0) {
3697 while (*ap && isassign(*ap))
3698 expand(*ap++, &wb, f & ~DOGLOB);
3700 for (wf = ap; *wf; wf++) {
3702 expand(*wf, &wb, f & ~DOGLOB);
3705 for (wb = addword((char *) 0, wb); *ap; ap++) {
3706 if (!flag['k'] || !isassign(*ap))
3707 expand(*ap, &wb, f & ~DOKEY);
3709 wb = addword((char *) 0, wb);
3715 return gflg ? (char **) NULL : wp;
3720 * Make the exported environment from the exported
3721 * names in the dictionary. Keyword assignments
3722 * will already have been done.
3724 static char **makenv(int all, struct wdblock *wb)
3728 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3730 for (vp = vlist; vp; vp = vp->next)
3731 if (all || vp->status & EXPORT)
3732 wb = addword(vp->name, wb);
3733 wb = addword((char *) 0, wb);
3734 return getwords(wb);
3737 static int expand(const char *cp, struct wdblock **wbp, int f)
3743 /* Avoid longjmp clobbering */
3747 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3754 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3755 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3757 xp = strsave(cp, areanum);
3760 *wbp = addword(xp, *wbp);
3764 if (newenv(setjmp(errpt)) == 0) {
3765 PUSHIO(aword, cp, strchar);
3767 while ((xp = blank(f)) && gflg == 0) {
3769 xp = strsave(xp, areanum);
3770 if ((f & DOGLOB) == 0) {
3773 *wbp = addword(xp, *wbp);
3775 *wbp = glob(xp, *wbp);
3783 static char *evalstr(char *cp, int f)
3787 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3790 if (expand(cp, &wb, f)) {
3791 if (wb == NULL || wb->w_nword == 0
3792 || (cp = wb->w_words[0]) == NULL
3794 // TODO: I suspect that
3795 // char *evalstr(char *cp, int f) is actually
3796 // const char *evalstr(const char *cp, int f)!
3807 * Blank interpretation and quoting
3809 static char *blank(int f)
3813 int scanequals, foundequals;
3815 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3818 scanequals = f & DOKEY;
3822 c = subgetc('"', foundequals);
3831 if (f & DOBLANK && any(c, ifs->value))
3840 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3843 if (c == '\'' || !any(c, "$`\""))
3850 if (!isalpha(c) && c != '_')
3853 c = subgetc('"', foundequals);
3855 f & (DOBLANK && any(c, ifs->value)) ||
3856 (!INSUB() && any(c, "\"'"))) {
3867 } else if (!isalnum(c) && c != '_')
3877 * Get characters, substituting for ` and $
3879 static int subgetc(char ec, int quoted)
3883 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3887 if (!INSUB() && ec != '\'') {
3889 if (grave(quoted) == 0)
3891 e.iop->task = XGRAVE;
3897 e.iop->task = XDOLL;
3906 * Prepare to generate the string returned by ${} substitution.
3908 static int dollar(int quoted)
3913 char *s, c, *cp = NULL;
3916 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3922 if (isalpha(c) || c == '_') {
3923 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3924 if (e.linep < elinep)
3931 otask = e.iop->task;
3933 e.iop->task = XOTHER;
3934 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3935 if (e.linep < elinep)
3938 e.iop->task = otask;
3945 if (e.linep >= elinep) {
3946 err("string in ${} too long");
3952 for (cp = s + 1; *cp; cp++)
3953 if (any(*cp, "=-+?")) {
3958 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3960 /* currently this does not distinguish $* and $@ */
3961 /* should check dollar */
3963 PUSHIO(awordlist, dolv + 1, dolchar);
3965 } else { /* trap the nasty ${=} */
3976 err("cannot use ${...=...} with $n");
3985 dolp = strsave(cp, areanum);
3990 prs("missing value for ");
3997 } else if (c == '+')
3998 dolp = strsave(cp, areanum);
3999 if (flag['u'] && dolp == null) {
4000 prs("unset variable: ");
4005 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4010 * Run the command in `...` and read its output.
4013 static int grave(int quoted)
4015 /* moved to G: static char child_cmd[LINELIM]; */
4026 char *argument_list[4];
4027 struct wdblock *wb = NULL;
4030 /* Avoid longjmp clobbering */
4034 for (cp = e.iop->argp->aword; *cp != '`'; cp++) {
4036 err("no closing `");
4041 /* string copy with dollar expansion */
4042 src = e.iop->argp->aword;
4047 while ((*src != '`') && (count < LINELIM)) {
4052 if (*src == '$' && !ignore && !ignore_once) {
4054 char var_name[LINELIM];
4055 char alt_value[LINELIM];
4068 var_name[var_index++] = *src++;
4069 while (isalnum(*src) || *src=='_')
4070 var_name[var_index++] = *src++;
4071 var_name[var_index] = 0;
4084 err("unclosed ${\n");
4089 while (*src && (*src != '}')) {
4090 alt_value[alt_index++] = *src++;
4092 alt_value[alt_index] = 0;
4094 err("unclosed ${\n");
4101 if (isalpha(*var_name)) {
4102 /* let subshell handle it instead */
4104 char *namep = var_name;
4112 char *altp = alt_value;
4120 wb = addword(lookup(var_name)->name, wb);
4124 vp = lookup(var_name);
4125 if (vp->value != null)
4126 value = (operator == '+') ?
4127 alt_value : vp->value;
4128 else if (operator == '?') {
4131 } else if (alt_index && (operator != '+')) {
4133 if (operator == '=')
4138 while (*value && (count < LINELIM)) {
4151 if (openpipe(pf) < 0)
4154 while ((i = vfork()) == -1 && errno == EAGAIN);
4156 DBGPRINTF3(("GRAVE: i is %p\n", io));
4160 err((char *) bb_msg_memory_exhausted);
4164 waitpid(i, NULL, 0);
4165 e.iop->argp->aword = ++cp;
4167 PUSHIO(afile, remap(pf[0]),
4168 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4171 /* allow trapped signals */
4172 /* XXX - Maybe this signal stuff should go as well? */
4173 for (j = 0; j <= _NSIG; j++)
4174 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4180 argument_list[0] = (char *) DEFAULT_SHELL;
4181 argument_list[1] = (char *) "-c";
4182 argument_list[2] = child_cmd;
4183 argument_list[3] = NULL;
4185 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4186 prs(argument_list[0]);
4193 static char *unquote(char *as)
4204 /* -------- glob.c -------- */
4210 #define scopy(x) strsave((x), areanum)
4212 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4214 static struct wdblock *cl, *nl;
4215 static char spcl[] = "[?*";
4217 static struct wdblock *glob(char *cp, struct wdblock *wb)
4225 for (pp = cp; *pp; pp++)
4228 else if (!any(*pp & ~QUOTE, spcl))
4231 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4232 nl = newword(cl->w_nword * 2);
4233 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4234 for (pp = cl->w_words[i]; *pp; pp++)
4235 if (any(*pp, spcl)) {
4236 globname(cl->w_words[i], pp);
4240 nl = addword(scopy(cl->w_words[i]), nl);
4242 for (i = 0; i < cl->w_nword; i++)
4243 DELETE(cl->w_words[i]);
4246 for (i = 0; i < cl->w_nword; i++)
4247 unquote(cl->w_words[i]);
4248 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4250 for (i = 0; i < cl->w_nword; i++)
4251 wb = addword(cl->w_words[i], wb);
4256 wb = addword(unquote(cp), wb);
4260 static void globname(char *we, char *pp)
4263 char *name, *gp, *dp;
4267 char dname[NAME_MAX + 1];
4270 for (np = we; np != pp; pp--)
4273 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4277 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4286 dname[NAME_MAX] = '\0';
4287 while ((de = readdir(dirp)) != NULL) {
4288 /* XXX Hmmm... What this could be? (abial) */
4290 if (ent[j].d_ino == 0)
4293 strncpy(dname, de->d_name, NAME_MAX);
4294 if (dname[0] == '.')
4297 for (k = 0; k < NAME_MAX; k++)
4298 if (any(dname[k], spcl))
4300 if (gmatch(dname, gp)) {
4301 name = generate(we, pp, dname, np);
4302 if (*np && !anys(np, spcl)) {
4303 if (stat(name, &dbuf)) {
4308 nl = addword(name, nl);
4317 * generate a pathname as below.
4318 * start..end1 / middle end
4319 * the slashes come for free
4321 static char *generate(char *start1, char *end1, char *middle, char *end)
4326 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4327 for (xp = start1; xp != end1;)
4329 for (xp = middle; (*op++ = *xp++) != '\0';);
4331 for (xp = end; (*op++ = *xp++) != '\0';);
4335 static int anyspcl(struct wdblock *wb)
4341 for (i = 0; i < wb->w_nword; i++)
4342 if (anys(spcl, *wd++))
4347 static int xstrcmp(char *p1, char *p2)
4349 return strcmp(*(char **) p1, *(char **) p2);
4353 /* -------- word.c -------- */
4355 static struct wdblock *newword(int nw)
4359 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4365 static struct wdblock *addword(char *wd, struct wdblock *wb)
4367 struct wdblock *wb2;
4371 wb = newword(NSTART);
4373 if (nw >= wb->w_bsize) {
4374 wb2 = newword(nw * 2);
4375 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4376 nw * sizeof(char *));
4381 wb->w_words[wb->w_nword++] = wd;
4386 char **getwords(struct wdblock *wb)
4393 if (wb->w_nword == 0) {
4397 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4398 memcpy((char *) wd, (char *) wb->w_words, nb);
4399 DELETE(wb); /* perhaps should done by caller */
4403 static int (*func) (char *, char *);
4406 static void glob3(char *i, char *j, char *k)
4408 char *index1, *index2, *index3;
4418 *index1++ = *index3;
4419 *index3++ = *index2;
4424 static void glob2(char *i, char *j)
4426 char *index1, *index2, c;
4434 *index1++ = *index2;
4439 static void glob1(char *base, char *lim)
4450 n = (int) (lim - base);
4453 n = v2 * (n / (2 * v2));
4454 hptr = lptr = base + n;
4459 c = (*func) (i, lptr);
4473 c = (*func) (hptr, j);
4497 if (lptr - base >= lim - hptr) {
4498 glob1(hptr + v2, lim);
4513 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4517 glob1(a0, a0 + a1 * a2);
4521 /* -------- io.c -------- */
4527 static int my_getc(int ec)
4531 if (e.linep > elinep) {
4532 while ((c = readc()) != '\n' && c);
4533 err("input line too long");
4538 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4541 if (c == '\n' && ec != '\"')
4549 static void unget(int c)
4551 if (e.iop >= e.iobase)
4555 static int eofc(void)
4557 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4560 static int readc(void)
4564 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4566 for (; e.iop >= e.iobase; e.iop--) {
4567 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4573 if (e.iop->prev != 0) {
4574 c = (*e.iop->iofn)(e.iop->argp, e.iop);
4580 if (e.iop == iostack)
4585 if (e.iop->task == XIO && e.iop->prev != '\n') {
4587 if (e.iop == iostack)
4592 if (e.iop->task == XIO) {
4597 if (interactive && e.iop == iostack + 1) {
4598 #if ENABLE_FEATURE_EDITING
4599 current_prompt = prompt->value;
4607 if (e.iop >= iostack) {
4608 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4612 DBGPRINTF(("READC: leave()...\n"));
4619 static void ioecho(char c)
4622 write(2, &c, sizeof c);
4626 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4628 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4629 argp->afid, e.iop));
4631 /* Set env ptr for io source to next array spot and check for array overflow */
4632 if (++e.iop >= &iostack[NPUSH]) {
4634 err("Shell input nested too deeply");
4639 /* We did not overflow the NPUSH array spots so setup data structs */
4641 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4643 if (argp->afid != AFID_NOBUF)
4647 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4648 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4650 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4652 if (e.iop == &iostack[0])
4653 e.iop->argp->afbuf = &mainbuf;
4655 e.iop->argp->afbuf = &sharedbuf;
4657 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4658 /* This line appears to be active when running scripts from command line */
4659 if ((isatty(e.iop->argp->afile) == 0)
4660 && (e.iop == &iostack[0]
4661 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4662 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4663 bufid = AFID_ID; /* AFID_ID = 0 */
4665 e.iop->argp->afid = bufid; /* assign buffer id */
4668 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4669 iostack, e.iop, e.iop->argp->afbuf));
4670 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4671 &mainbuf, &sharedbuf, bufid, e.iop));
4675 e.iop->prev = ~'\n';
4680 if (fn == filechar || fn == linechar)
4682 else if (fn == (int (*)(struct ioarg *)) gravechar
4683 || fn == (int (*)(struct ioarg *)) qgravechar)
4684 e.iop->task = XGRAVE;
4686 e.iop->task = XOTHER;
4689 static struct io *setbase(struct io *ip)
4699 * Input generating functions
4703 * Produce the characters of a string, then a newline, then EOF.
4705 static int nlchar(struct ioarg *ap)
4709 if (ap->aword == NULL)
4720 * Given a list of words, produce the characters
4721 * in them, with a space after each word.
4723 static int wdchar(struct ioarg *ap)
4738 ap->awordlist = NULL;
4743 * Return the characters of a list of words,
4744 * producing a space between them.
4746 static int dolchar(struct ioarg *ap)
4750 wp = *ap->awordlist++;
4752 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4758 static int xxchar(struct ioarg *ap)
4762 if (ap->aword == NULL)
4773 * Produce the characters from a single word (string).
4775 static int strchar(struct ioarg *ap)
4777 if (ap->aword == NULL)
4779 return *ap->aword++;
4783 * Produce quoted characters from a single word (string).
4785 static int qstrchar(struct ioarg *ap)
4789 if (ap->aword == NULL)
4798 * Return the characters from a file.
4800 static int filechar(struct ioarg *ap)
4804 struct iobuf *bp = ap->afbuf;
4806 if (ap->afid != AFID_NOBUF) {
4807 i = (ap->afid != bp->id);
4808 if (i || bp->bufp == bp->ebufp) {
4810 lseek(ap->afile, ap->afpos, SEEK_SET);
4812 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4820 bp->ebufp = bp->bufp + i;
4824 return *bp->bufp++ & 0177;
4826 #if ENABLE_FEATURE_EDITING
4827 if (interactive && isatty(ap->afile)) {
4828 /* moved to G: static char filechar_cmdbuf[BUFSIZ]; */
4829 static int position = 0, size = 0;
4831 while (size == 0 || position >= size) {
4832 read_line_input(current_prompt, filechar_cmdbuf, BUFSIZ, line_input_state);
4833 size = strlen(filechar_cmdbuf);
4836 c = filechar_cmdbuf[position];
4841 i = safe_read(ap->afile, &c, sizeof(c));
4842 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4846 * Return the characters from a here temp file.
4848 static int herechar(struct ioarg *ap)
4852 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4860 * Return the characters produced by a process (`...`).
4861 * Quote them if required, and remove any trailing newline characters.
4863 static int gravechar(struct ioarg *ap, struct io *iop)
4867 c = qgravechar(ap, iop) & ~QUOTE;
4873 static int qgravechar(struct ioarg *ap, struct io *iop)
4877 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4882 return '\n' | QUOTE;
4886 } else if ((c = filechar(ap)) == '\n') {
4888 while ((c = filechar(ap)) == '\n')
4896 return c != 0 ? c | QUOTE : 0;
4900 * Return a single command (usually the first line) from a file.
4902 static int linechar(struct ioarg *ap)
4910 ap->afile = -1; /* illegal value */
4917 * remap fd into Shell's fd space
4919 static int remap(int fd)
4925 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
4928 for (i = 0; i < NOFILE; i++)
4935 } while (fd >= 0 && fd < e.iofd);
4937 for (i = 0; i < NOFILE; i++)
4942 err("too many files open in shell");
4948 static int openpipe(int *pv)
4954 err("can't create pipe - try again");
4958 static void closepipe(int *pv)
4967 /* -------- here.c -------- */
4973 static void markhere(char *s, struct ioword *iop)
4975 struct here *h, *lh;
4977 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4979 h = (struct here *) space(sizeof(struct here));
4983 h->h_tag = evalstr(s, DOSUB);
4993 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4994 if (lh->h_next == 0) {
5000 iop->io_flag |= IOHERE | IOXHERE;
5001 for (s = h->h_tag; *s; s++) {
5003 iop->io_flag &= ~IOXHERE;
5007 h->h_dosub = iop->io_flag & IOXHERE;
5010 static void gethere(void)
5012 struct here *h, *hp;
5014 DBGPRINTF7(("GETHERE: enter...\n"));
5016 /* Scan here files first leaving inhere list in place */
5017 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5018 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5020 /* Make inhere list active - keep list intact for scraphere */
5022 hp->h_next = acthere;
5028 static void readhere(char **name, char *s, int ec)
5031 char tname[30] = ".msh_XXXXXX";
5034 char myline[LINELIM + 1];
5037 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5039 tf = mkstemp(tname);
5043 *name = strsave(tname, areanum);
5045 if (newenv(setjmp(errpt)) != 0)
5048 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5051 if (interactive && e.iop <= iostack) {
5052 #if ENABLE_FEATURE_EDITING
5053 current_prompt = cprompt->value;
5055 prs(cprompt->value);
5059 while ((c = my_getc(ec)) != '\n' && c) {
5062 if (thenext >= &myline[LINELIM]) {
5069 if (strcmp(s, myline) == 0 || c == 0)
5072 write(tf, myline, (int) (thenext - myline));
5075 prs("here document `");
5085 * open here temp file.
5086 * if unquoted here, expand here temp file into second temp file.
5088 static int herein(char *hname, int xdoll)
5094 /* Avoid longjmp clobbering */
5100 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5102 hf = open(hname, 0);
5108 char tname[30] = ".msh_XXXXXX";
5111 tf = mkstemp(tname);
5115 if (newenv(setjmp(errpt)) == 0) {
5116 PUSHIO(afile, hf, herechar);
5118 while ((c = subgetc(0, 0)) != 0) {
5120 write(tf, &c, sizeof c);
5126 tf = open(tname, 0);
5133 static void scraphere(void)
5137 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5139 for (h = inhere; h != NULL; h = h->h_next) {
5140 if (h->h_iop && h->h_iop->io_name)
5141 unlink(h->h_iop->io_name);
5146 /* unlink here temp files before a freearea(area) */
5147 static void freehere(int area)
5149 struct here *h, *hl;
5151 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5154 for (h = acthere; h != NULL; h = h->h_next)
5155 if (getarea((char *) h) >= area) {
5156 if (h->h_iop->io_name != NULL)
5157 unlink(h->h_iop->io_name);
5159 acthere = h->h_next;
5161 hl->h_next = h->h_next;
5167 /* -------- sh.c -------- */
5172 int msh_main(int argc, char **argv);
5173 int msh_main(int argc, char **argv)
5179 int (*iof) (struct ioarg *);
5181 PTR_TO_GLOBALS = xzalloc(sizeof(G));
5182 sharedbuf.id = AFID_NOBUF;
5183 mainbuf.id = AFID_NOBUF;
5185 elinep = line + sizeof(line) - 5;
5187 #if ENABLE_FEATURE_EDITING
5188 line_input_state = new_line_input_t(FOR_SHELL);
5191 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5197 assign(*ap++, !COPYV);
5198 for (ap = environ; *ap;)
5199 export(lookup(*ap++));
5204 shell = lookup("SHELL");
5205 if (shell->value == null)
5206 setval(shell, (char *)DEFAULT_SHELL);
5209 homedir = lookup("HOME");
5210 if (homedir->value == null)
5211 setval(homedir, "/");
5214 setval(lookup("$"), putn(getpid()));
5216 path = lookup("PATH");
5217 if (path->value == null) {
5219 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
5221 setval(path, "/bin:/usr/bin");
5225 ifs = lookup("IFS");
5226 if (ifs->value == null)
5227 setval(ifs, " \t\n");
5230 mshdbg_var = lookup("MSHDEBUG");
5231 if (mshdbg_var->value == null)
5232 setval(mshdbg_var, "0");
5235 prompt = lookup("PS1");
5236 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5237 if (prompt->value == null)
5239 setval(prompt, DEFAULT_USER_PROMPT);
5240 if (geteuid() == 0) {
5241 setval(prompt, DEFAULT_ROOT_PROMPT);
5242 prompt->status &= ~EXPORT;
5244 cprompt = lookup("PS2");
5245 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5246 if (cprompt->value == null)
5248 setval(cprompt, "> ");
5254 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5255 for (s = argv[0] + 1; *s; s++)
5258 prompt->status &= ~EXPORT;
5259 cprompt->status &= ~EXPORT;
5261 setval(cprompt, "");
5264 PUSHIO(aword, *++argv, iof = nlchar);
5272 /* standard input */
5276 prompt->status &= ~EXPORT;
5284 if (*s >= 'a' && *s <= 'z')
5292 if (iof == filechar && --argc > 0) {
5294 setval(cprompt, "");
5295 prompt->status &= ~EXPORT;
5296 cprompt->status &= ~EXPORT;
5298 /* Shell is non-interactive, activate printf-based debug */
5300 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5304 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5308 exit(1); /* Exit on error */
5314 /* This won't be true if PUSHIO has been called, say from newfile() above */
5315 if (e.iop < iostack) {
5316 PUSHIO(afile, 0, iof);
5317 if (isatty(0) && isatty(1) && !cflag) {
5319 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5321 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
5323 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
5325 printf("Enter 'help' for a list of built-in commands.\n\n");
5330 signal(SIGQUIT, qflag);
5331 if (name && name[0] == '-') {
5333 f = open(".profile", 0);
5336 f = open("/etc/profile", 0);
5341 signal(SIGTERM, sig);
5343 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5344 signal(SIGINT, onintr);
5349 for (ap = ++argv; --argc > 0;) {
5351 if (assign(*ap, !COPYV)) {
5352 dolc--; /* keyword */
5358 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5360 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
5363 if (interactive && e.iop <= iostack) {
5364 #if ENABLE_FEATURE_EDITING
5365 current_prompt = prompt->value;
5371 /* Ensure that getenv("PATH") stays current */
5372 setenv("PATH", path->value, 1);
5375 DBGPRINTF(("MSH_MAIN: returning.\n"));
5380 * Copyright (c) 1987,1997, Prentice Hall
5381 * All rights reserved.
5383 * Redistribution and use of the MINIX operating system in source and
5384 * binary forms, with or without modification, are permitted provided
5385 * that the following conditions are met:
5387 * Redistributions of source code must retain the above copyright
5388 * notice, this list of conditions and the following disclaimer.
5390 * Redistributions in binary form must reproduce the above
5391 * copyright notice, this list of conditions and the following
5392 * disclaimer in the documentation and/or other materials provided
5393 * with the distribution.
5395 * Neither the name of Prentice Hall nor the names of the software
5396 * authors or contributors may be used to endorse or promote
5397 * products derived from this software without specific prior
5398 * written permission.
5400 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5401 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5402 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5403 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5404 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5405 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5406 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5407 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5408 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5409 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5410 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5411 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.