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.
21 # include <sys/times.h>
22 # include <sys/types.h>
23 # include <sys/stat.h>
24 # include <sys/wait.h>
35 # define bb_dev_null "/dev/null"
36 # define DEFAULT_SHELL "/proc/self/exe"
37 # define CONFIG_BUSYBOX_EXEC_PATH "/proc/self/exe"
38 # define BB_BANNER "busybox standalone"
39 # define ENABLE_FEATURE_SH_STANDALONE_SHELL 0
40 # define bb_msg_memory_exhausted "memory exhausted"
41 # define xmalloc(size) malloc(size)
42 # define msh_main(argc,argv) main(argc,argv)
43 # define safe_read(fd,buf,count) read(fd,buf,count)
44 # define NOT_LONE_DASH(s) ((s)[0] != '-' || (s)[1])
45 # define LONE_CHAR(s,c) ((s)[0] == (c) && !(s)[1])
46 # define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
47 static char *find_applet_by_name(const char *applet)
51 static void utoa_to_buf(unsigned n, char *buf, unsigned buflen)
54 assert(sizeof(unsigned) == 4);
57 for (i = 1000000000; i; i /= 10) {
59 if (res || out || i == 1) {
69 static void itoa_to_buf(int n, char *buf, unsigned buflen)
76 utoa_to_buf((unsigned)n, buf, buflen);
78 static char local_buf[12];
79 static char *itoa(int n)
81 itoa_to_buf(n, local_buf, sizeof(local_buf));
86 # include <sys/times.h>
88 extern char **environ;
91 /*#define MSHDEBUG 1*/
94 int mshdbg = MSHDEBUG;
96 #define DBGPRINTF(x) if(mshdbg>0)printf x
97 #define DBGPRINTF0(x) if(mshdbg>0)printf x
98 #define DBGPRINTF1(x) if(mshdbg>1)printf x
99 #define DBGPRINTF2(x) if(mshdbg>2)printf x
100 #define DBGPRINTF3(x) if(mshdbg>3)printf x
101 #define DBGPRINTF4(x) if(mshdbg>4)printf x
102 #define DBGPRINTF5(x) if(mshdbg>5)printf x
103 #define DBGPRINTF6(x) if(mshdbg>6)printf x
104 #define DBGPRINTF7(x) if(mshdbg>7)printf x
105 #define DBGPRINTF8(x) if(mshdbg>8)printf x
106 #define DBGPRINTF9(x) if(mshdbg>9)printf x
110 #define RCPRINTF(x) if(mshdbg_rc)printf x
115 #define DBGPRINTF0(x) ((void)0)
116 #define DBGPRINTF1(x) ((void)0)
117 #define DBGPRINTF2(x) ((void)0)
118 #define DBGPRINTF3(x) ((void)0)
119 #define DBGPRINTF4(x) ((void)0)
120 #define DBGPRINTF5(x) ((void)0)
121 #define DBGPRINTF6(x) ((void)0)
122 #define DBGPRINTF7(x) ((void)0)
123 #define DBGPRINTF8(x) ((void)0)
124 #define DBGPRINTF9(x) ((void)0)
126 #define RCPRINTF(x) ((void)0)
128 #endif /* MSHDEBUG */
131 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
132 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
133 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
135 # define DEFAULT_ROOT_PROMPT "# "
136 # define DEFAULT_USER_PROMPT "$ "
140 /* -------- sh.h -------- */
146 #define NPUSH 8 /* limit to input nesting */
149 #define NOFILE 20 /* Number of open files */
150 #define NUFILE 10 /* Number of user-accessible files */
151 #define FDBASE 10 /* First file usable by Shell */
154 * values returned by wait
156 #define WAITSIG(s) ((s)&0177)
157 #define WAITVAL(s) (((s)>>8)&0377)
158 #define WAITCORE(s) (((s)&0200)!=0)
161 * library and system definitions
163 typedef void xint; /* base type of jmp_buf, for not broken compilers */
171 #define NOBLOCK ((struct op *)NULL)
172 #define NOWORD ((char *)NULL)
173 #define NOWORDS ((char **)NULL)
174 #define NOPIPE ((int *)NULL)
181 short io_unit; /* unit affected */
182 short io_flag; /* action (below) */
183 char *io_name; /* file name */
186 #define IOREAD 1 /* < */
187 #define IOHERE 2 /* << (here file) */
188 #define IOWRITE 4 /* > */
189 #define IOCAT 8 /* >> */
190 #define IOXHERE 16 /* ${}, ` in << */
191 #define IODUP 32 /* >&digit */
192 #define IOCLOSE 64 /* >&- */
194 #define IODEFAULT (-1) /* token for default IO unit */
198 * Description of a command or an operation on commands.
199 * Might eventually use a union.
202 int type; /* operation type, see below */
203 char **words; /* arguments to a command */
204 struct ioword **ioact; /* IO actions (eg, < > >>) */
207 char *str; /* identifier for case and for */
210 #define TCOM 1 /* command */
211 #define TPAREN 2 /* (c-list) */
212 #define TPIPE 3 /* a | b */
213 #define TLIST 4 /* a [&;] b */
214 #define TOR 5 /* || */
215 #define TAND 6 /* && */
223 #define TPAT 14 /* pattern in case */
224 #define TBRACE 15 /* {c-list} */
225 #define TASYNC 16 /* c & */
226 /* Added to support "." file expansion */
229 /* Strings for names to make debug easier */
231 static const char *const T_CMD_NAMES[] = {
254 * actions determining the environment of a process
256 #define BIT(i) (1<<(i))
257 #define FEXEC BIT(0) /* execute without forking */
259 #define AREASIZE (90000)
262 * flags to control evaluation of words
264 #define DOSUB 1 /* interpret $, `, and quotes */
265 #define DOBLANK 2 /* perform blank interpretation */
266 #define DOGLOB 4 /* interpret [?* */
267 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
268 #define DOTRIM 16 /* trim resulting string */
270 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
274 static int newfile(char *s);
279 struct brkcon *nextlev;
286 * -k: look for name=value everywhere on command line
288 * -t: exit after reading and executing one command
291 * -u: unset variables net diagnostic
293 static char flags['z' - 'a' + 1];
294 /* this looks weird, but is OK ... we index flag with 'a'...'z' */
295 static char *flag = flags - 'a';
297 static char *null; /* null value for variable */
298 static int intr; /* interrupt pending */
300 static char *trap[_NSIG + 1];
301 static char ourtrap[_NSIG + 1];
302 static int trapset; /* trap pending */
304 static int heedint; /* heed interrupt signals */
306 static int yynerrs; /* yacc */
308 static char line[LINELIM];
311 #if ENABLE_FEATURE_EDITING
312 static char *current_prompt;
313 static line_input_t *line_input_state;
316 static int areanum; /* current allocation area */
322 static const char *rexecve(char *c, char **v, char **envp);
323 static char *evalstr(char *cp, int f);
324 static char *putn(int n);
325 static char *unquote(char *as);
326 static int rlookup(char *n);
327 static struct wdblock *glob(char *cp, struct wdblock *wb);
328 static int my_getc(int ec);
329 static int subgetc(char ec, int quoted);
330 static char **makenv(int all, struct wdblock *wb);
331 static char **eval(char **ap, int f);
332 static int setstatus(int s);
333 static int waitfor(int lastpid, int canintr);
335 static void onintr(int s); /* SIGINT handler */
337 static int newenv(int f);
338 static void quitenv(void);
339 static void next(int f);
340 static void setdash(void);
341 static void onecommand(void);
342 static void runtrap(int i);
345 /* -------- area stuff -------- */
347 #define REGSIZE sizeof(struct region)
349 /* #define SHRINKBY (64) */
353 #define ALIGN (sizeof(int)-1)
362 /* -------- grammar stuff -------- */
387 /* Added for "." file expansion */
390 #define YYERRCODE 300
393 #define CONTIN 01 /* skip new lines to complete command */
395 static struct op *pipeline(int cf);
396 static struct op *andor(void);
397 static struct op *c_list(void);
398 static int synio(int cf);
399 static void musthave(int c, int cf);
400 static struct op *simple(void);
401 static struct op *nested(int type, int mark);
402 static struct op *command(int cf);
403 static struct op *dogroup(int onlydone);
404 static struct op *thenpart(void);
405 static struct op *elsepart(void);
406 static struct op *caselist(void);
407 static struct op *casepart(void);
408 static char **pattern(void);
409 static char **wordlist(void);
410 static struct op *list(struct op *t1, struct op *t2);
411 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
412 static struct op *newtp(void);
413 static struct op *namelist(struct op *t);
414 static char **copyw(void);
415 static void word(char *cp);
416 static struct ioword **copyio(void);
417 static struct ioword *io(int u, int f, char *cp);
418 static int yylex(int cf);
419 static int collect(int c, int c1);
420 static int dual(int c);
421 static void diag(int ec);
422 static char *tree(unsigned size);
424 /* -------- var.h -------- */
433 #define COPYV 1 /* flag to setval, suggesting copy */
434 #define RONLY 01 /* variable is read-only */
435 #define EXPORT 02 /* variable is to be exported */
436 #define GETCELL 04 /* name & value space was got with getcell */
438 static int yyparse(void);
440 static int execute(struct op *t, int *pin, int *pout, int act);
443 #define AFID_NOBUF (~0)
447 /* -------- io.h -------- */
450 unsigned id; /* buffer id */
451 char buf[512]; /* buffer */
452 char *bufp; /* pointer into buffer */
453 char *ebufp; /* pointer to end of buffer */
456 /* possible arguments to an IO function */
460 int afile; /* file descriptor */
461 unsigned afid; /* buffer id */
462 long afpos; /* file position */
463 struct iobuf *afbuf; /* buffer for this file */
466 /* an input generator's state */
468 int (*iofn) (struct ioarg *, struct io *);
471 char prev; /* previous character read by readc() */
472 char nlcount; /* for `'s */
473 char xchar; /* for `'s */
474 char task; /* reason for pushed IO */
477 #define XOTHER 0 /* none of the below */
478 #define XDOLL 1 /* expanding ${} */
479 #define XGRAVE 2 /* expanding `'s */
480 #define XIO 3 /* file IO */
482 /* in substitution */
483 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
485 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
486 static struct ioarg ioargstack[NPUSH];
487 static struct io iostack[NPUSH];
488 static struct iobuf sharedbuf = { AFID_NOBUF };
489 static struct iobuf mainbuf = { AFID_NOBUF };
490 static unsigned bufid = AFID_ID; /* buffer id counter */
492 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
493 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
497 * parsing & execution environment
503 xint *errpt; /* void * */
510 * input generators for IO structure
512 static int nlchar(struct ioarg *ap);
513 static int strchar(struct ioarg *ap);
514 static int qstrchar(struct ioarg *ap);
515 static int filechar(struct ioarg *ap);
516 static int herechar(struct ioarg *ap);
517 static int linechar(struct ioarg *ap);
518 static int gravechar(struct ioarg *ap, struct io *iop);
519 static int qgravechar(struct ioarg *ap, struct io *iop);
520 static int dolchar(struct ioarg *ap);
521 static int wdchar(struct ioarg *ap);
522 static void scraphere(void);
523 static void freehere(int area);
524 static void gethere(void);
525 static void markhere(char *s, struct ioword *iop);
526 static int herein(char *hname, int xdoll);
527 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
530 static int eofc(void);
531 static int readc(void);
532 static void unget(int c);
533 static void ioecho(char c);
539 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
540 static int remap(int fd);
541 static int openpipe(int *pv);
542 static void closepipe(int *pv);
543 static struct io *setbase(struct io *ip);
545 /* -------- word.h -------- */
547 #define NSTART 16 /* default number of words to allow for initially */
552 /* bounds are arbitrary */
556 static struct wdblock *addword(char *wd, struct wdblock *wb);
557 static struct wdblock *newword(int nw);
558 static char **getwords(struct wdblock *wb);
560 /* -------- misc stuff -------- */
562 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
563 static int iosetup(struct ioword *iop, int pipein, int pipeout);
564 static void brkset(struct brkcon *bc);
565 static int dolabel(struct op *t);
566 static int dohelp(struct op *t);
567 static int dochdir(struct op *t);
568 static int doshift(struct op *t);
569 static int dologin(struct op *t);
570 static int doumask(struct op *t);
571 static int doexec(struct op *t);
572 static int dodot(struct op *t);
573 static int dowait(struct op *t);
574 static int doread(struct op *t);
575 static int doeval(struct op *t);
576 static int dotrap(struct op *t);
577 static int getsig(char *s);
578 static void setsig(int n, sighandler_t f);
579 static int getn(char *as);
580 static int dobreak(struct op *t);
581 static int docontinue(struct op *t);
582 static int brkcontin(char *cp, int val);
583 static int doexit(struct op *t);
584 static int doexport(struct op *t);
585 static int doreadonly(struct op *t);
586 static void rdexp(char **wp, void (*f) (struct var *), int key);
587 static void badid(char *s);
588 static int doset(struct op *t);
589 static void varput(char *s, int out);
590 static int dotimes(struct op *t);
591 static int expand(const char *cp, struct wdblock **wbp, int f);
592 static char *blank(int f);
593 static int dollar(int quoted);
594 static int grave(int quoted);
595 static void globname(char *we, char *pp);
596 static char *generate(char *start1, char *end1, char *middle, char *end);
597 static int anyspcl(struct wdblock *wb);
598 static int xstrcmp(char *p1, char *p2);
599 static void glob0(char *a0, unsigned a1, int a2,
600 int (*a3) (char *, char *));
601 static void readhere(char **name, char *s, int ec);
602 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
603 static int xxchar(struct ioarg *ap);
608 struct ioword *h_iop;
612 static const char * const signame[] = {
615 NULL, /* interrupt */
617 "Illegal instruction",
621 "Floating Point Exception",
626 NULL, /* broken pipe */
631 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
637 static const struct res restab[] = {
663 int (*builtinfunc) (struct op * t);
665 static const struct builtincmd builtincmds[] = {
670 {"continue", docontinue},
674 {"export", doexport},
679 {"readonly", doreadonly},
689 static struct op *scantree(struct op *);
690 static struct op *dowholefile(int, int);
698 static int interactive; /* Is this an interactive shell */
700 static int multiline; /* \n changed to ; */
701 static struct op *outtree; /* result from parser */
704 static struct brkcon *brklist;
706 static struct wdblock *wdlist;
707 static struct wdblock *iolist;
708 static char *trap[_NSIG + 1];
709 static char ourtrap[_NSIG + 1];
710 static int trapset; /* trap pending */
713 static struct var *mshdbg_var;
715 static struct var *vlist; /* dictionary */
716 static struct var *homedir; /* home directory */
717 static struct var *prompt; /* main prompt */
718 static struct var *cprompt; /* continuation prompt */
719 static struct var *path; /* search path for commands */
720 static struct var *shell; /* shell to interpret command files */
721 static struct var *ifs; /* field separators */
723 static int areanum; /* current allocation area */
726 static char *null = (char*)"";
727 static int heedint = 1;
728 static void (*qflag) (int) = SIG_IGN;
732 static int iounit = IODEFAULT;
733 static YYSTYPE yylval;
734 static char *elinep = line + sizeof(line) - 5;
737 static struct here *inhere; /* list of hear docs while parsing */
738 static struct here *acthere; /* list of active here documents */
739 static struct region *areabot; /* bottom of area */
740 static struct region *areatop; /* top of area */
741 static struct region *areanxt; /* starting point of scan */
743 static void *brkaddr;
745 static struct env e = {
746 line, /* linep: char ptr */
747 iostack, /* iobase: struct io ptr */
748 iostack - 1, /* iop: struct io ptr */
749 (xint *) NULL, /* errpt: void ptr for errors? */
750 FDBASE, /* iofd: file desc */
751 (struct env *) NULL /* oenv: struct env ptr */
755 void print_t(struct op *t)
757 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
758 T_CMD_NAMES[t->type], t->words, t->ioact));
761 DBGPRINTF(("T: W1: %s", t->words[0]));
765 void print_tree(struct op *head)
768 DBGPRINTF(("PRINT_TREE: no tree\n"));
772 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
776 print_tree(head->left);
779 print_tree(head->right);
781 #endif /* MSHDEBUG */
787 static void prs(const char *s)
790 write(2, s, strlen(s));
793 static void prn(unsigned u)
798 static void echo(char **wp)
803 for (i = 0; wp[i]; i++) {
811 static void closef(int i)
817 static void closeall(void)
821 for (u = NUFILE; u < NOFILE;)
826 /* fail but return to process next command */
827 static void fail(void) ATTRIBUTE_NORETURN;
828 static void fail(void)
834 /* abort shell (or fail in subshell) */
835 static void leave(void) ATTRIBUTE_NORETURN;
836 static void leave(void)
838 DBGPRINTF(("LEAVE: leave called!\n"));
849 static void warn(const char *s)
860 static void err(const char *s)
870 e.iop = e.iobase = iostack;
874 /* -------- area.c -------- */
877 * All memory between (char *)areabot and (char *)(areatop+1) is
878 * exclusively administered by the area management routines.
879 * It is assumed that sbrk() and brk() manipulate the high end.
883 void * __q = (void *)-1; \
884 if (brkaddr + (int)(X) < brktop) { \
886 brkaddr += (int)(X); \
891 static void initarea(void)
893 brkaddr = xmalloc(AREASIZE);
894 brktop = brkaddr + AREASIZE;
896 while ((long) sbrk(0) & ALIGN)
898 areabot = (struct region *) sbrk(REGSIZE);
900 areabot->next = areabot;
901 areabot->area = BUSY;
906 static char *getcell(unsigned nbytes)
909 struct region *p, *q;
916 /* silly and defeats the algorithm */
918 * round upwards and add administration area
920 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
923 if (p->area > areanum) {
927 while ((q = p->next)->area > areanum && q != areanxt)
930 * exit loop if cell big enough
939 i = nregio >= GROWBY ? nregio : GROWBY;
940 p = (struct region *) sbrk(i * REGSIZE);
941 if (p == (struct region *) -1)
946 abort(); /* allocated areas are contiguous */
956 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
958 areanxt = p + nregio;
961 * split into requested area and rest
963 if (areanxt + 1 > q) {
965 abort(); /* insufficient space left for admin */
968 areanxt->area = FREE;
972 return (char *) (p + 1);
975 static void freecell(char *cp)
979 p = (struct region *) cp;
987 #define DELETE(obj) freecell((char *)obj)
989 static void freearea(int a)
991 struct region *p, *top;
994 for (p = areabot; p != top; p = p->next)
999 static void setarea(char *cp, int a)
1003 p = (struct region *) cp;
1008 static int getarea(char *cp)
1010 return ((struct region *) cp - 1)->area;
1013 static void garbage(void)
1015 struct region *p, *q, *top;
1018 for (p = areabot; p != top; p = p->next) {
1019 if (p->area > areanum) {
1020 while ((q = p->next)->area > areanum)
1026 if (areatop >= q + SHRINKBY && q->area > areanum) {
1027 brk((char *) (q + 1));
1035 static char *space(int n)
1041 err("out of string space");
1045 static char *strsave(const char *s, int a)
1049 cp = space(strlen(s) + 1);
1051 // FIXME: I highly doubt this is good.
1060 /* -------- var.c -------- */
1062 static int eqname(const char *n1, const char *n2)
1064 for (; *n1 != '=' && *n1 != '\0'; n1++)
1067 return *n2 == '\0' || *n2 == '=';
1070 static const char *findeq(const char *cp)
1072 while (*cp != '\0' && *cp != '=')
1078 * Find the given name in the dictionary
1079 * and return its value. If the name was
1080 * not previously there, enter it now and
1081 * return a null value.
1083 static struct var *lookup(const char *n)
1085 // FIXME: dirty hack
1086 static struct var dummy;
1094 dummy.name = (char*)n;
1095 for (c = 0; isdigit(*n) && c < 1000; n++)
1096 c = c * 10 + *n - '0';
1097 dummy.status = RONLY;
1098 dummy.value = (c <= dolc ? dolv[c] : null);
1102 for (vp = vlist; vp; vp = vp->next)
1103 if (eqname(vp->name, n))
1107 vp = (struct var *) space(sizeof(*vp));
1108 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1109 dummy.name = dummy.value = (char*)"";
1114 while ((*xp = *n++) != '\0' && *xp != '=')
1118 setarea((char *) vp, 0);
1119 setarea((char *) vp->name, 0);
1122 vp->status = GETCELL;
1128 * if name is not NULL, it must be
1129 * a prefix of the space `val',
1131 * this is all so that exporting
1132 * values is reasonably painless.
1134 static void nameval(struct var *vp, const char *val, const char *name)
1140 if (vp->status & RONLY) {
1142 while (*xp && *xp != '=')
1143 putc(*xp++, stderr);
1144 err(" is read-only");
1149 xp = space(strlen(vp->name) + strlen(val) + 2);
1152 /* make string: name=value */
1156 while ((*xp = *cp++) != '\0' && *xp != '=')
1163 if (vp->status & GETCELL)
1164 freecell(vp->name); /* form new string `name=value' */
1165 vp->name = (char*)name;
1166 vp->value = (char*)val;
1171 * give variable at `vp' the value `val'.
1173 static void setval(struct var *vp, const char *val)
1175 nameval(vp, val, NULL);
1178 static void export(struct var *vp)
1180 vp->status |= EXPORT;
1183 static void ronly(struct var *vp)
1185 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1186 vp->status |= RONLY;
1189 static int isassign(const char *s)
1192 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1194 /* no isalpha() - we shouldn't use locale */
1197 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1207 c |= 0x20; /* lowercase letters, doesn't affect numbers */
1209 && (unsigned)(c - '0') > 9 /* not number */
1210 && (unsigned)(c - 'a') > 25 /* not letter */
1217 static int assign(const char *s, int cf)
1222 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1224 if (!isalpha(*s) && *s != '_')
1226 for (cp = s; *cp != '='; cp++)
1227 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1230 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1232 vp->status &= ~GETCELL;
1236 static int checkname(char *cp)
1238 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1240 if (!isalpha(*cp++) && *(cp - 1) != '_')
1243 if (!isalnum(*cp++) && *(cp - 1) != '_')
1248 static void putvlist(int f, int out)
1252 for (vp = vlist; vp; vp = vp->next) {
1253 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1254 if (vp->status & EXPORT)
1255 write(out, "export ", 7);
1256 if (vp->status & RONLY)
1257 write(out, "readonly ", 9);
1258 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1259 write(out, "\n", 1);
1268 static void sig(int i)
1274 static void runtrap(int i)
1279 if (trapstr == NULL)
1285 RUN(aword, trapstr, nlchar);
1289 static void setdash(void)
1293 char m['z' - 'a' + 1];
1296 for (c = 'a'; c <= 'z'; c++)
1300 setval(lookup("-"), m);
1303 static int newfile(char *s)
1307 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1310 if (NOT_LONE_DASH(s)) {
1311 DBGPRINTF(("NEWFILE: s is %s\n", s));
1315 err(": cannot open");
1325 struct op *scantree(struct op *head)
1332 if (head->left != NULL) {
1333 dotnode = scantree(head->left);
1338 if (head->right != NULL) {
1339 dotnode = scantree(head->right);
1344 if (head->words == NULL)
1347 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1349 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1350 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1358 static void onecommand(void)
1363 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1383 setjmp(failpt); /* Bruce Evans' fix */
1385 if (setjmp(failpt) || yyparse() || intr) {
1386 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1391 if (!interactive && intr)
1404 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1406 execute(outtree, NOPIPE, NOPIPE, 0);
1409 if (!interactive && intr) {
1421 static int newenv(int f)
1425 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1432 ep = (struct env *) space(sizeof(*ep));
1445 static void quitenv(void)
1450 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1456 /* should close `'d files */
1458 while (--fd >= e.iofd)
1464 * Is character c in s?
1466 static int any(int c, const char *s)
1475 * Is any character from s1 in s2?
1477 static int anys(const char *s1, const char *s2)
1485 static char *putn(int n)
1490 static void next(int f)
1492 PUSHIO(afile, f, filechar);
1495 static void onintr(int s) /* ANSI C requires a parameter */
1497 signal(SIGINT, onintr);
1504 } else if (heedint) {
1511 /* -------- gmatch.c -------- */
1513 * int gmatch(string, pattern)
1514 * char *string, *pattern;
1516 * Match a pattern as in sh(1).
1521 #define QMASK (CMASK&~QUOTE)
1522 #define NOT '!' /* might use ^ */
1524 static const char *cclass(const char *p, int sub)
1526 int c, d, not, found;
1536 if (p[1] == '-' && p[2] != ']') {
1541 if (c == sub || (c <= sub && sub <= d))
1543 } while (*++p != ']');
1544 return found ? p + 1 : NULL;
1547 static int gmatch(const char *s, const char *p)
1551 if (s == NULL || p == NULL)
1554 while ((pc = *p++ & CMASK) != '\0') {
1571 if (*p == '\0' || gmatch(s, p))
1573 } while (*s++ != '\0');
1577 if (sc != (pc & ~QUOTE))
1585 /* -------- csyn.c -------- */
1587 * shell: syntax (C version)
1590 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1591 static void yyerror(const char *s)
1594 if (interactive && e.iop <= iostack) {
1596 while (eofc() == 0 && yylex(0) != '\n');
1602 static void zzerr(void) ATTRIBUTE_NORETURN;
1603 static void zzerr(void)
1605 yyerror("syntax error");
1610 DBGPRINTF7(("YYPARSE: enter...\n"));
1617 return (yynerrs != 0);
1620 static struct op *pipeline(int cf)
1625 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1629 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1632 while ((c = yylex(0)) == '|') {
1633 p = command(CONTIN);
1635 DBGPRINTF8(("PIPELINE: error!\n"));
1639 if (t->type != TPAREN && t->type != TCOM) {
1640 /* shell statement */
1641 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1644 t = block(TPIPE, t, p, NOWORDS);
1649 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1653 static struct op *andor(void)
1658 DBGPRINTF7(("ANDOR: enter...\n"));
1662 DBGPRINTF9(("ANDOR: t=%p\n", t));
1665 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1666 p = pipeline(CONTIN);
1668 DBGPRINTF8(("ANDOR: error!\n"));
1672 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1678 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1682 static struct op *c_list(void)
1687 DBGPRINTF7(("C_LIST: enter...\n"));
1694 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1696 while ((c = yylex(0)) == ';' || c == '&'
1697 || (multiline && c == '\n')) {
1705 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1713 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1717 static int synio(int cf)
1723 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1726 if (c != '<' && c != '>') {
1733 iop = io(iounit, i, yylval.cp);
1737 markhere(yylval.cp, iop);
1739 DBGPRINTF7(("SYNIO: returning 1\n"));
1743 static void musthave(int c, int cf)
1745 peeksym = yylex(cf);
1747 DBGPRINTF7(("MUSTHAVE: error!\n"));
1754 static struct op *simple(void)
1760 switch (peeksym = yylex(0)) {
1781 static struct op *nested(int type, int mark)
1785 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1791 return block(type, t, NOBLOCK, NOWORDS);
1794 static struct op *command(int cf)
1797 struct wdblock *iosave;
1800 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1826 t = nested(TPAREN, ')');
1830 t = nested(TBRACE, '}');
1840 t->words = wordlist();
1842 if (c != '\n' && c != ';')
1844 t->left = dogroup(0);
1852 t->type = c == WHILE ? TWHILE : TUNTIL;
1854 t->right = dogroup(1);
1866 musthave(IN, CONTIN);
1869 t->left = caselist();
1880 t->right = thenpart();
1889 musthave(WORD, 0); /* gets name of file */
1890 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1892 word(yylval.cp); /* add word to wdlist */
1893 word(NOWORD); /* terminate wdlist */
1894 t->words = copyw(); /* dup wdlist */
1904 DBGPRINTF(("COMMAND: returning %p\n", t));
1909 static struct op *dowholefile(int type, int mark)
1913 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1918 t = block(type, t, NOBLOCK, NOWORDS);
1919 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1923 static struct op *dogroup(int onlydone)
1929 if (c == DONE && onlydone)
1938 static struct op *thenpart(void)
1951 if (t->left == NULL)
1953 t->right = elsepart();
1957 static struct op *elsepart(void)
1962 switch (c = yylex(0)) {
1973 t->right = thenpart();
1982 static struct op *caselist(void)
1987 while ((peeksym = yylex(CONTIN)) != ESAC) {
1988 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1989 t = list(t, casepart());
1992 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1996 static struct op *casepart(void)
2000 DBGPRINTF7(("CASEPART: enter...\n"));
2004 t->words = pattern();
2007 peeksym = yylex(CONTIN);
2008 if (peeksym != ESAC)
2009 musthave(BREAK, CONTIN);
2011 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2016 static char **pattern(void)
2033 static char **wordlist(void)
2043 while ((c = yylex(0)) == WORD)
2051 * supporting functions
2053 static struct op *list(struct op *t1, struct op *t2)
2055 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2062 return block(TLIST, t1, t2, NOWORDS);
2065 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2069 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2077 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2083 /* See if given string is a shell multiline (FOR, IF, etc) */
2084 static int rlookup(char *n)
2086 const struct res *rp;
2088 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2090 for (rp = restab; rp->r_name; rp++)
2091 if (strcmp(rp->r_name, n) == 0) {
2092 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2093 return rp->r_val; /* Return numeric code for shell multiline */
2096 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2097 return 0; /* Not a shell multiline */
2100 static struct op *newtp(void)
2104 t = (struct op *) tree(sizeof(*t));
2112 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2117 static struct op *namelist(struct op *t)
2120 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2121 T_CMD_NAMES[t->type], iolist));
2124 iolist = addword((char *) NULL, iolist);
2125 t->ioact = copyio();
2129 if (t->type != TCOM) {
2130 if (t->type != TPAREN && t->ioact != NULL) {
2131 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2132 t->ioact = t->left->ioact;
2133 t->left->ioact = NULL;
2144 static char **copyw(void)
2148 wd = getwords(wdlist);
2153 static void word(char *cp)
2155 wdlist = addword(cp, wdlist);
2158 static struct ioword **copyio(void)
2160 struct ioword **iop;
2162 iop = (struct ioword **) getwords(iolist);
2167 static struct ioword *io(int u, int f, char *cp)
2171 iop = (struct ioword *) tree(sizeof(*iop));
2175 iolist = addword((char *) iop, iolist);
2179 static int yylex(int cf)
2199 line[LINELIM - 1] = '\0';
2202 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2207 if (any(c, "0123456789")) {
2210 if (c1 == '<' || c1 == '>') {
2219 case '#': /* Comment, skip to next newline or End-of-string */
2220 while ((c = my_getc(0)) != '\0' && c != '\n');
2225 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2229 DBGPRINTF9(("YYLEX: found $\n"));
2233 c = collect(c, '}');
2252 /* If more chars process them, else return NULL char */
2270 if (multiline || cf & CONTIN) {
2271 if (interactive && e.iop <= iostack) {
2272 #if ENABLE_FEATURE_EDITING
2273 current_prompt = cprompt->value;
2275 prs(cprompt->value);
2292 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2293 if (e.linep >= elinep)
2294 err("word too long");
2301 if (any(c, "\"'`$"))
2314 yylval.cp = strsave(line, areanum);
2319 static int collect(int c, int c1)
2323 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2326 while ((c = my_getc(c1)) != c1) {
2335 if (interactive && c == '\n' && e.iop <= iostack) {
2336 #if ENABLE_FEATURE_EDITING
2337 current_prompt = cprompt->value;
2339 prs(cprompt->value);
2347 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2352 /* "multiline commands" helper func */
2353 /* see if next 2 chars form a shell multiline */
2354 static int dual(int c)
2359 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2361 *cp++ = c; /* c is the given "peek" char */
2362 *cp++ = my_getc(0); /* get next char of input */
2363 *cp = '\0'; /* add EOS marker */
2365 c = rlookup(s); /* see if 2 chars form a shell multiline */
2367 unget(*--cp); /* String is not a shell multiline, put peek char back */
2369 return c; /* String is multiline, return numeric multiline (restab) code */
2372 static void diag(int ec)
2376 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2379 if (c == '>' || c == '<') {
2382 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2385 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2386 if (c != '&' || yylval.i == IOHERE)
2392 static char *tree(unsigned size)
2398 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2399 prs("command line too complicated\n");
2410 /* -------- exec.c -------- */
2412 static struct op **find1case(struct op *t, const char *w)
2420 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2424 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2425 T_CMD_NAMES[t->type]));
2427 if (t->type == TLIST) {
2428 tp = find1case(t->left, w);
2430 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2433 t1 = t->right; /* TPAT */
2437 for (wp = t1->words; *wp;) {
2438 cp = evalstr(*wp++, DOSUB);
2439 if (cp && gmatch(w, cp)) {
2440 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2446 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2450 static struct op *findcase(struct op *t, const char *w)
2454 tp = find1case(t, w);
2455 return tp != NULL ? *tp : NULL;
2462 static int execute(struct op *t, int *pin, int *pout, int act)
2465 volatile int i, rv, a;
2469 struct op *outtree_save;
2473 /* Avoid longjmp clobbering */
2478 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2482 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2483 t->type, T_CMD_NAMES[t->type],
2484 ((t->words == NULL) ? "NULL" : t->words[0])));
2488 wp = (wp2 = t->words) != NULL
2489 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2494 DBGPRINTF3(("EXECUTE: TDOT\n"));
2496 outtree_save = outtree;
2498 newfile(evalstr(t->words[0], DOALL));
2500 t->left = dowholefile(TLIST, 0);
2503 outtree = outtree_save;
2506 rv = execute(t->left, pin, pout, 0);
2508 rv = execute(t->right, pin, pout, 0);
2512 rv = execute(t->left, pin, pout, 0);
2516 rv = forkexec(t, pin, pout, act, wp);
2526 pv[0] = remap(pv[0]);
2527 pv[1] = remap(pv[1]);
2528 (void) execute(t->left, pin, pv, 0);
2529 rv = execute(t->right, pv, pout, 0);
2534 (void) execute(t->left, pin, pout, 0);
2535 rv = execute(t->right, pin, pout, 0);
2540 int hinteractive = interactive;
2542 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2545 if (i == 0) { /* child */
2546 signal(SIGINT, SIG_IGN);
2547 signal(SIGQUIT, SIG_IGN);
2549 signal(SIGTERM, SIG_DFL);
2553 open(bb_dev_null, 0);
2555 _exit(execute(t->left, pin, pout, FEXEC));
2557 interactive = hinteractive;
2559 setval(lookup("!"), putn(i));
2574 rv = execute(t->left, pin, pout, 0);
2576 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2577 rv = execute(t1, pin, pout, 0);
2588 while (*wp++ != NULL);
2590 vp = lookup(t->str);
2591 while (setjmp(bc.brkpt))
2595 for (t1 = t->left; i-- && *wp != NULL;) {
2597 rv = execute(t1, pin, pout, 0);
2599 brklist = brklist->nextlev;
2604 while (setjmp(bc.brkpt))
2609 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2610 rv = execute(t->right, pin, pout, 0);
2611 brklist = brklist->nextlev;
2616 if (t->right != NULL) {
2617 rv = !execute(t->left, pin, pout, 0) ?
2618 execute(t->right->left, pin, pout, 0) :
2619 execute(t->right->right, pin, pout, 0);
2624 cp = evalstr(t->str, DOSUB | DOTRIM);
2628 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2629 ((t->str == NULL) ? "NULL" : t->str),
2630 ((cp == NULL) ? "NULL" : cp)));
2632 t1 = findcase(t->left, cp);
2634 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2635 rv = execute(t1, pin, pout, 0);
2636 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2645 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2653 rv = execute(t1, pin, pout, 0);
2666 if (interactive && intr) {
2677 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2681 typedef int (*builtin_func_ptr)(struct op *);
2683 static builtin_func_ptr inbuilt(const char *s) {
2684 const struct builtincmd *bp;
2686 for (bp = builtincmds; bp->name != NULL; bp++)
2687 if (strcmp(bp->name, s) == 0)
2688 return bp->builtinfunc;
2693 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2697 builtin_func_ptr shcom = NULL;
2699 const char *cp = NULL;
2700 struct ioword **iopp;
2710 struct brkcon *hbrklist;
2714 /* Avoid longjmp clobbering */
2724 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2726 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2727 ((t->words == NULL) ? "NULL" : t->words[0])));
2731 rv = -1; /* system-detected error */
2732 if (t->type == TCOM) {
2733 while (*wp++ != NULL);
2736 /* strip all initial assignments */
2737 /* not correct wrt PATH=yyy command etc */
2739 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2741 echo(cp ? wp : owp);
2744 if (cp == NULL && t->ioact == NULL) {
2745 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2747 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2748 return setstatus(0);
2751 shcom = inbuilt(cp);
2758 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2761 if (shcom == NULL && (f & FEXEC) == 0) {
2762 /* Save values in case the child process alters them */
2766 hinteractive = interactive;
2771 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2776 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2780 if (newpid > 0) { /* Parent */
2781 /* Restore values */
2785 interactive = hinteractive;
2796 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2799 /* Must be the child process, pid should be 0 */
2800 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2803 signal(SIGINT, SIG_IGN);
2804 signal(SIGQUIT, SIG_IGN);
2815 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2820 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2821 err("piping to/from shell builtins not yet done");
2839 if (shcom != NULL && shcom != doexec) {
2841 err(": cannot redirect shell command");
2847 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2855 i = setstatus((*shcom) (t));
2858 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2862 /* should use FIOCEXCL */
2863 for (i = FDBASE; i < NOFILE; i++)
2866 signal(SIGINT, SIG_DFL);
2867 signal(SIGQUIT, SIG_DFL);
2870 if (t->type == TPAREN)
2871 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2875 cp = rexecve(wp[0], wp, makenv(0, NULL));
2882 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2890 * 0< 1> are ignored as required
2893 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2899 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2902 if (iop->io_unit == IODEFAULT) /* take default */
2903 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2905 if (pipein && iop->io_unit == 0)
2908 if (pipeout && iop->io_unit == 1)
2911 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2912 if ((iop->io_flag & IOHERE) == 0) {
2913 cp = iop->io_name; /* huh?? */
2914 cp = evalstr(cp, DOSUB | DOTRIM);
2919 if (iop->io_flag & IODUP) {
2920 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2922 err(": illegal >& argument");
2926 iop->io_flag = IOCLOSE;
2927 iop->io_flag &= ~(IOREAD | IOWRITE);
2929 switch (iop->io_flag) {
2935 case IOHERE | IOXHERE:
2936 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2937 cp = (char*)"here file";
2940 case IOWRITE | IOCAT:
2943 lseek(u, (long) 0, SEEK_END);
2947 u = creat(cp, 0666);
2951 u = dup2(*cp - '0', iop->io_unit);
2955 close(iop->io_unit);
2964 if (u != iop->io_unit) {
2965 dup2(u, iop->io_unit);
2972 * Enter a new loop level (marked for break/continue).
2974 static void brkset(struct brkcon *bc)
2976 bc->nextlev = brklist;
2981 * Wait for the last process created.
2982 * Print a message for each process found
2983 * that was killed by a signal.
2984 * Ignore interrupt signals while waiting
2985 * unless `canintr' is true.
2987 static int waitfor(int lastpid, int canintr)
2991 int oheedint = heedint;
2998 if (errno != EINTR || canintr)
3004 if (signame[rv] != NULL) {
3005 if (pid != lastpid) {
3012 if (pid != lastpid) {
3021 prs(" - core dumped");
3022 if (rv >= NSIGNAL || signame[rv])
3028 } while (pid != lastpid);
3043 static int setstatus(int s)
3046 setval(lookup("?"), putn(s));
3051 * PATH-searching interface to execve.
3052 * If getenv("PATH") were kept up-to-date,
3053 * execvp might be used.
3055 static const char *rexecve(char *c, char **v, char **envp)
3060 int eacces = 0, asis = 0;
3063 if (ENABLE_FEATURE_SH_STANDALONE_SHELL) {
3065 if (find_applet_by_name(name)) {
3066 /* We have to exec here since we vforked. Running
3067 * run_applet_by_name() won't work and bad things
3069 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3073 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3075 sp = any('/', c) ? "" : path->value;
3076 asis = (*sp == '\0');
3077 while (asis || *sp != '\0') {
3080 for (; *sp != '\0'; tp++) {
3083 asis = (*sp == '\0');
3089 for (i = 0; (*tp++ = c[i++]) != '\0';);
3091 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3093 execve(e.linep, v, envp);
3100 execve(DEFAULT_SHELL, v, envp);
3105 return (char *) bb_msg_memory_exhausted;
3108 return "argument list too long";
3115 return errno == ENOENT ? "not found" : "cannot execute";
3119 * Run the command produced by generator `f'
3120 * applied to stream `arg'.
3122 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3125 struct wdblock *swdlist;
3126 struct wdblock *siolist;
3132 /* Avoid longjmp clobbering */
3136 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3137 areanum, outtree, failpt));
3147 if (newenv(setjmp(errpt)) == 0) {
3154 if (setjmp(failpt) == 0 && yyparse() == 0)
3155 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3158 DBGPRINTF(("RUN: error from newenv()!\n"));
3165 freearea(areanum--);
3170 /* -------- do.c -------- */
3173 * built-in commands: doX
3176 static int dohelp(struct op *t)
3179 const struct builtincmd *x;
3181 puts("\nBuilt-in commands:\n"
3182 "-------------------");
3184 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3187 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3193 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
3196 const struct BB_applet *applet;
3198 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3202 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3211 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)
4019 static char child_cmd[LINELIM];
4025 char *argument_list[4];
4026 struct wdblock *wb = NULL;
4029 /* Avoid longjmp clobbering */
4033 for (cp = e.iop->argp->aword; *cp != '`'; cp++) {
4035 err("no closing `");
4040 /* string copy with dollar expansion */
4041 src = e.iop->argp->aword;
4046 while ((*src != '`') && (count < LINELIM)) {
4051 if (*src == '$' && !ignore && !ignore_once) {
4053 char var_name[LINELIM];
4054 char alt_value[LINELIM];
4067 var_name[var_index++] = *src++;
4068 while (isalnum(*src) || *src=='_')
4069 var_name[var_index++] = *src++;
4070 var_name[var_index] = 0;
4083 err("unclosed ${\n");
4088 while (*src && (*src != '}')) {
4089 alt_value[alt_index++] = *src++;
4091 alt_value[alt_index] = 0;
4093 err("unclosed ${\n");
4100 if (isalpha(*var_name)) {
4101 /* let subshell handle it instead */
4103 char *namep = var_name;
4111 char *altp = alt_value;
4119 wb = addword(lookup(var_name)->name, wb);
4123 vp = lookup(var_name);
4124 if (vp->value != null)
4125 value = (operator == '+') ?
4126 alt_value : vp->value;
4127 else if (operator == '?') {
4130 } else if (alt_index && (operator != '+')) {
4132 if (operator == '=')
4137 while (*value && (count < LINELIM)) {
4150 if (openpipe(pf) < 0)
4153 while ((i = vfork()) == -1 && errno == EAGAIN);
4155 DBGPRINTF3(("GRAVE: i is %p\n", io));
4159 err((char *) bb_msg_memory_exhausted);
4163 waitpid(i, NULL, 0);
4164 e.iop->argp->aword = ++cp;
4166 PUSHIO(afile, remap(pf[0]),
4167 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4170 /* allow trapped signals */
4171 /* XXX - Maybe this signal stuff should go as well? */
4172 for (j = 0; j <= _NSIG; j++)
4173 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4179 argument_list[0] = (char *) DEFAULT_SHELL;
4180 argument_list[1] = (char *) "-c";
4181 argument_list[2] = child_cmd;
4182 argument_list[3] = NULL;
4184 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4185 prs(argument_list[0]);
4192 static char *unquote(char *as)
4203 /* -------- glob.c -------- */
4209 #define scopy(x) strsave((x), areanum)
4211 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4213 static struct wdblock *cl, *nl;
4214 static char spcl[] = "[?*";
4216 static struct wdblock *glob(char *cp, struct wdblock *wb)
4224 for (pp = cp; *pp; pp++)
4227 else if (!any(*pp & ~QUOTE, spcl))
4230 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4231 nl = newword(cl->w_nword * 2);
4232 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4233 for (pp = cl->w_words[i]; *pp; pp++)
4234 if (any(*pp, spcl)) {
4235 globname(cl->w_words[i], pp);
4239 nl = addword(scopy(cl->w_words[i]), nl);
4241 for (i = 0; i < cl->w_nword; i++)
4242 DELETE(cl->w_words[i]);
4245 for (i = 0; i < cl->w_nword; i++)
4246 unquote(cl->w_words[i]);
4247 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4249 for (i = 0; i < cl->w_nword; i++)
4250 wb = addword(cl->w_words[i], wb);
4255 wb = addword(unquote(cp), wb);
4259 static void globname(char *we, char *pp)
4262 char *name, *gp, *dp;
4266 char dname[NAME_MAX + 1];
4269 for (np = we; np != pp; pp--)
4272 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4276 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4285 dname[NAME_MAX] = '\0';
4286 while ((de = readdir(dirp)) != NULL) {
4287 /* XXX Hmmm... What this could be? (abial) */
4289 if (ent[j].d_ino == 0)
4292 strncpy(dname, de->d_name, NAME_MAX);
4293 if (dname[0] == '.')
4296 for (k = 0; k < NAME_MAX; k++)
4297 if (any(dname[k], spcl))
4299 if (gmatch(dname, gp)) {
4300 name = generate(we, pp, dname, np);
4301 if (*np && !anys(np, spcl)) {
4302 if (stat(name, &dbuf)) {
4307 nl = addword(name, nl);
4316 * generate a pathname as below.
4317 * start..end1 / middle end
4318 * the slashes come for free
4320 static char *generate(char *start1, char *end1, char *middle, char *end)
4325 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4326 for (xp = start1; xp != end1;)
4328 for (xp = middle; (*op++ = *xp++) != '\0';);
4330 for (xp = end; (*op++ = *xp++) != '\0';);
4334 static int anyspcl(struct wdblock *wb)
4340 for (i = 0; i < wb->w_nword; i++)
4341 if (anys(spcl, *wd++))
4346 static int xstrcmp(char *p1, char *p2)
4348 return strcmp(*(char **) p1, *(char **) p2);
4352 /* -------- word.c -------- */
4354 static struct wdblock *newword(int nw)
4358 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4364 static struct wdblock *addword(char *wd, struct wdblock *wb)
4366 struct wdblock *wb2;
4370 wb = newword(NSTART);
4372 if (nw >= wb->w_bsize) {
4373 wb2 = newword(nw * 2);
4374 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4375 nw * sizeof(char *));
4380 wb->w_words[wb->w_nword++] = wd;
4385 char **getwords(struct wdblock *wb)
4392 if (wb->w_nword == 0) {
4396 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4397 memcpy((char *) wd, (char *) wb->w_words, nb);
4398 DELETE(wb); /* perhaps should done by caller */
4402 static int (*func) (char *, char *);
4405 static void glob3(char *i, char *j, char *k)
4407 char *index1, *index2, *index3;
4417 *index1++ = *index3;
4418 *index3++ = *index2;
4423 static void glob2(char *i, char *j)
4425 char *index1, *index2, c;
4433 *index1++ = *index2;
4438 static void glob1(char *base, char *lim)
4449 n = (int) (lim - base);
4452 n = v2 * (n / (2 * v2));
4453 hptr = lptr = base + n;
4458 c = (*func) (i, lptr);
4472 c = (*func) (hptr, j);
4496 if (lptr - base >= lim - hptr) {
4497 glob1(hptr + v2, lim);
4512 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4516 glob1(a0, a0 + a1 * a2);
4520 /* -------- io.c -------- */
4526 static int my_getc(int ec)
4530 if (e.linep > elinep) {
4531 while ((c = readc()) != '\n' && c);
4532 err("input line too long");
4537 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4540 if (c == '\n' && ec != '\"')
4548 static void unget(int c)
4550 if (e.iop >= e.iobase)
4554 static int eofc(void)
4556 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4559 static int readc(void)
4563 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4565 for (; e.iop >= e.iobase; e.iop--) {
4566 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4572 if (e.iop->prev != 0) {
4573 c = (*e.iop->iofn)(e.iop->argp, e.iop);
4579 if (e.iop == iostack)
4584 if (e.iop->task == XIO && e.iop->prev != '\n') {
4586 if (e.iop == iostack)
4591 if (e.iop->task == XIO) {
4596 if (interactive && e.iop == iostack + 1) {
4597 #if ENABLE_FEATURE_EDITING
4598 current_prompt = prompt->value;
4606 if (e.iop >= iostack) {
4607 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4611 DBGPRINTF(("READC: leave()...\n"));
4618 static void ioecho(char c)
4621 write(2, &c, sizeof c);
4625 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4627 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4628 argp->afid, e.iop));
4630 /* Set env ptr for io source to next array spot and check for array overflow */
4631 if (++e.iop >= &iostack[NPUSH]) {
4633 err("Shell input nested too deeply");
4638 /* We did not overflow the NPUSH array spots so setup data structs */
4640 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4642 if (argp->afid != AFID_NOBUF)
4646 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4647 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4649 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4651 if (e.iop == &iostack[0])
4652 e.iop->argp->afbuf = &mainbuf;
4654 e.iop->argp->afbuf = &sharedbuf;
4656 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4657 /* This line appears to be active when running scripts from command line */
4658 if ((isatty(e.iop->argp->afile) == 0)
4659 && (e.iop == &iostack[0]
4660 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4661 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4662 bufid = AFID_ID; /* AFID_ID = 0 */
4664 e.iop->argp->afid = bufid; /* assign buffer id */
4667 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4668 iostack, e.iop, e.iop->argp->afbuf));
4669 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4670 &mainbuf, &sharedbuf, bufid, e.iop));
4674 e.iop->prev = ~'\n';
4679 if (fn == filechar || fn == linechar)
4681 else if (fn == (int (*)(struct ioarg *)) gravechar
4682 || fn == (int (*)(struct ioarg *)) qgravechar)
4683 e.iop->task = XGRAVE;
4685 e.iop->task = XOTHER;
4688 static struct io *setbase(struct io *ip)
4698 * Input generating functions
4702 * Produce the characters of a string, then a newline, then EOF.
4704 static int nlchar(struct ioarg *ap)
4708 if (ap->aword == NULL)
4719 * Given a list of words, produce the characters
4720 * in them, with a space after each word.
4722 static int wdchar(struct ioarg *ap)
4737 ap->awordlist = NULL;
4742 * Return the characters of a list of words,
4743 * producing a space between them.
4745 static int dolchar(struct ioarg *ap)
4749 wp = *ap->awordlist++;
4751 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4757 static int xxchar(struct ioarg *ap)
4761 if (ap->aword == NULL)
4772 * Produce the characters from a single word (string).
4774 static int strchar(struct ioarg *ap)
4776 if (ap->aword == NULL)
4778 return *ap->aword++;
4782 * Produce quoted characters from a single word (string).
4784 static int qstrchar(struct ioarg *ap)
4788 if (ap->aword == NULL)
4797 * Return the characters from a file.
4799 static int filechar(struct ioarg *ap)
4803 struct iobuf *bp = ap->afbuf;
4805 if (ap->afid != AFID_NOBUF) {
4806 i = (ap->afid != bp->id);
4807 if (i || bp->bufp == bp->ebufp) {
4809 lseek(ap->afile, ap->afpos, SEEK_SET);
4811 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4819 bp->ebufp = bp->bufp + i;
4823 return *bp->bufp++ & 0177;
4825 #if ENABLE_FEATURE_EDITING
4826 if (interactive && isatty(ap->afile)) {
4827 static char mycommand[BUFSIZ];
4828 static int position = 0, size = 0;
4830 while (size == 0 || position >= size) {
4831 read_line_input(current_prompt, mycommand, BUFSIZ, line_input_state);
4832 size = strlen(mycommand);
4835 c = mycommand[position];
4840 i = safe_read(ap->afile, &c, sizeof(c));
4841 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4845 * Return the characters from a here temp file.
4847 static int herechar(struct ioarg *ap)
4851 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4859 * Return the characters produced by a process (`...`).
4860 * Quote them if required, and remove any trailing newline characters.
4862 static int gravechar(struct ioarg *ap, struct io *iop)
4866 c = qgravechar(ap, iop) & ~QUOTE;
4872 static int qgravechar(struct ioarg *ap, struct io *iop)
4876 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4881 return '\n' | QUOTE;
4885 } else if ((c = filechar(ap)) == '\n') {
4887 while ((c = filechar(ap)) == '\n')
4895 return c != 0 ? c | QUOTE : 0;
4899 * Return a single command (usually the first line) from a file.
4901 static int linechar(struct ioarg *ap)
4909 ap->afile = -1; /* illegal value */
4916 * remap fd into Shell's fd space
4918 static int remap(int fd)
4924 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
4927 for (i = 0; i < NOFILE; i++)
4934 } while (fd >= 0 && fd < e.iofd);
4936 for (i = 0; i < NOFILE; i++)
4941 err("too many files open in shell");
4947 static int openpipe(int *pv)
4953 err("can't create pipe - try again");
4957 static void closepipe(int *pv)
4966 /* -------- here.c -------- */
4972 static void markhere(char *s, struct ioword *iop)
4974 struct here *h, *lh;
4976 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4978 h = (struct here *) space(sizeof(struct here));
4982 h->h_tag = evalstr(s, DOSUB);
4992 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4993 if (lh->h_next == 0) {
4999 iop->io_flag |= IOHERE | IOXHERE;
5000 for (s = h->h_tag; *s; s++) {
5002 iop->io_flag &= ~IOXHERE;
5006 h->h_dosub = iop->io_flag & IOXHERE;
5009 static void gethere(void)
5011 struct here *h, *hp;
5013 DBGPRINTF7(("GETHERE: enter...\n"));
5015 /* Scan here files first leaving inhere list in place */
5016 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5017 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5019 /* Make inhere list active - keep list intact for scraphere */
5021 hp->h_next = acthere;
5027 static void readhere(char **name, char *s, int ec)
5030 char tname[30] = ".msh_XXXXXX";
5033 char myline[LINELIM + 1];
5036 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5038 tf = mkstemp(tname);
5042 *name = strsave(tname, areanum);
5044 if (newenv(setjmp(errpt)) != 0)
5047 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5050 if (interactive && e.iop <= iostack) {
5051 #if ENABLE_FEATURE_EDITING
5052 current_prompt = cprompt->value;
5054 prs(cprompt->value);
5058 while ((c = my_getc(ec)) != '\n' && c) {
5061 if (thenext >= &myline[LINELIM]) {
5068 if (strcmp(s, myline) == 0 || c == 0)
5071 write(tf, myline, (int) (thenext - myline));
5074 prs("here document `");
5084 * open here temp file.
5085 * if unquoted here, expand here temp file into second temp file.
5087 static int herein(char *hname, int xdoll)
5093 /* Avoid longjmp clobbering */
5099 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5101 hf = open(hname, 0);
5107 char tname[30] = ".msh_XXXXXX";
5110 tf = mkstemp(tname);
5114 if (newenv(setjmp(errpt)) == 0) {
5115 PUSHIO(afile, hf, herechar);
5117 while ((c = subgetc(0, 0)) != 0) {
5119 write(tf, &c, sizeof c);
5125 tf = open(tname, 0);
5132 static void scraphere(void)
5136 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5138 for (h = inhere; h != NULL; h = h->h_next) {
5139 if (h->h_iop && h->h_iop->io_name)
5140 unlink(h->h_iop->io_name);
5145 /* unlink here temp files before a freearea(area) */
5146 static void freehere(int area)
5148 struct here *h, *hl;
5150 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5153 for (h = acthere; h != NULL; h = h->h_next)
5154 if (getarea((char *) h) >= area) {
5155 if (h->h_iop->io_name != NULL)
5156 unlink(h->h_iop->io_name);
5158 acthere = h->h_next;
5160 hl->h_next = h->h_next;
5166 /* -------- sh.c -------- */
5171 int msh_main(int argc, char **argv);
5172 int msh_main(int argc, char **argv)
5178 int (*iof) (struct ioarg *);
5180 #if ENABLE_FEATURE_EDITING
5181 line_input_state = new_line_input_t(FOR_SHELL);
5184 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5190 assign(*ap++, !COPYV);
5191 for (ap = environ; *ap;)
5192 export(lookup(*ap++));
5197 shell = lookup("SHELL");
5198 if (shell->value == null)
5199 setval(shell, (char *)DEFAULT_SHELL);
5202 homedir = lookup("HOME");
5203 if (homedir->value == null)
5204 setval(homedir, "/");
5207 setval(lookup("$"), putn(getpid()));
5209 path = lookup("PATH");
5210 if (path->value == null) {
5212 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
5214 setval(path, "/bin:/usr/bin");
5218 ifs = lookup("IFS");
5219 if (ifs->value == null)
5220 setval(ifs, " \t\n");
5223 mshdbg_var = lookup("MSHDEBUG");
5224 if (mshdbg_var->value == null)
5225 setval(mshdbg_var, "0");
5228 prompt = lookup("PS1");
5229 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5230 if (prompt->value == null)
5232 setval(prompt, DEFAULT_USER_PROMPT);
5233 if (geteuid() == 0) {
5234 setval(prompt, DEFAULT_ROOT_PROMPT);
5235 prompt->status &= ~EXPORT;
5237 cprompt = lookup("PS2");
5238 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5239 if (cprompt->value == null)
5241 setval(cprompt, "> ");
5247 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5248 for (s = argv[0] + 1; *s; s++)
5251 prompt->status &= ~EXPORT;
5252 cprompt->status &= ~EXPORT;
5254 setval(cprompt, "");
5257 PUSHIO(aword, *++argv, iof = nlchar);
5265 /* standard input */
5269 prompt->status &= ~EXPORT;
5277 if (*s >= 'a' && *s <= 'z')
5285 if (iof == filechar && --argc > 0) {
5287 setval(cprompt, "");
5288 prompt->status &= ~EXPORT;
5289 cprompt->status &= ~EXPORT;
5291 /* Shell is non-interactive, activate printf-based debug */
5293 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5297 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5301 exit(1); /* Exit on error */
5307 /* This won't be true if PUSHIO has been called, say from newfile() above */
5308 if (e.iop < iostack) {
5309 PUSHIO(afile, 0, iof);
5310 if (isatty(0) && isatty(1) && !cflag) {
5312 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5314 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
5316 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
5318 printf("Enter 'help' for a list of built-in commands.\n\n");
5323 signal(SIGQUIT, qflag);
5324 if (name && name[0] == '-') {
5326 f = open(".profile", 0);
5329 f = open("/etc/profile", 0);
5334 signal(SIGTERM, sig);
5336 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5337 signal(SIGINT, onintr);
5342 for (ap = ++argv; --argc > 0;) {
5344 if (assign(*ap, !COPYV)) {
5345 dolc--; /* keyword */
5351 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5353 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
5356 if (interactive && e.iop <= iostack) {
5357 #if ENABLE_FEATURE_EDITING
5358 current_prompt = prompt->value;
5364 /* Ensure that getenv("PATH") stays current */
5365 setenv("PATH", path->value, 1);
5368 DBGPRINTF(("MSH_MAIN: returning.\n"));
5373 * Copyright (c) 1987,1997, Prentice Hall
5374 * All rights reserved.
5376 * Redistribution and use of the MINIX operating system in source and
5377 * binary forms, with or without modification, are permitted provided
5378 * that the following conditions are met:
5380 * Redistributions of source code must retain the above copyright
5381 * notice, this list of conditions and the following disclaimer.
5383 * Redistributions in binary form must reproduce the above
5384 * copyright notice, this list of conditions and the following
5385 * disclaimer in the documentation and/or other materials provided
5386 * with the distribution.
5388 * Neither the name of Prentice Hall nor the names of the software
5389 * authors or contributors may be used to endorse or promote
5390 * products derived from this software without specific prior
5391 * written permission.
5393 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5394 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5395 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5396 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5397 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5398 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5399 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5400 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5401 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5402 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5403 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5404 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.