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)
71 if (buflen && n < 0) {
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));
1195 /* no isalpha() - we shouldn't use locale */
1196 /* c | 0x20 - lowercase (Latin) letters */
1197 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1208 && (unsigned)(c - '0') > 9 /* not number */
1209 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1216 static int assign(const char *s, int cf)
1221 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1223 if (!isalpha(*s) && *s != '_')
1225 for (cp = s; *cp != '='; cp++)
1226 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1229 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1231 vp->status &= ~GETCELL;
1235 static int checkname(char *cp)
1237 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1239 if (!isalpha(*cp++) && *(cp - 1) != '_')
1242 if (!isalnum(*cp++) && *(cp - 1) != '_')
1247 static void putvlist(int f, int out)
1251 for (vp = vlist; vp; vp = vp->next) {
1252 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1253 if (vp->status & EXPORT)
1254 write(out, "export ", 7);
1255 if (vp->status & RONLY)
1256 write(out, "readonly ", 9);
1257 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1258 write(out, "\n", 1);
1267 static void sig(int i)
1273 static void runtrap(int i)
1278 if (trapstr == NULL)
1284 RUN(aword, trapstr, nlchar);
1288 static void setdash(void)
1292 char m['z' - 'a' + 1];
1295 for (c = 'a'; c <= 'z'; c++)
1299 setval(lookup("-"), m);
1302 static int newfile(char *s)
1306 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1309 if (NOT_LONE_DASH(s)) {
1310 DBGPRINTF(("NEWFILE: s is %s\n", s));
1314 err(": cannot open");
1324 struct op *scantree(struct op *head)
1331 if (head->left != NULL) {
1332 dotnode = scantree(head->left);
1337 if (head->right != NULL) {
1338 dotnode = scantree(head->right);
1343 if (head->words == NULL)
1346 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1348 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1349 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1357 static void onecommand(void)
1362 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1382 setjmp(failpt); /* Bruce Evans' fix */
1384 if (setjmp(failpt) || yyparse() || intr) {
1385 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1390 if (!interactive && intr)
1403 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1405 execute(outtree, NOPIPE, NOPIPE, 0);
1408 if (!interactive && intr) {
1420 static int newenv(int f)
1424 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1431 ep = (struct env *) space(sizeof(*ep));
1444 static void quitenv(void)
1449 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1455 /* should close `'d files */
1457 while (--fd >= e.iofd)
1463 * Is character c in s?
1465 static int any(int c, const char *s)
1474 * Is any character from s1 in s2?
1476 static int anys(const char *s1, const char *s2)
1484 static char *putn(int n)
1489 static void next(int f)
1491 PUSHIO(afile, f, filechar);
1494 static void onintr(int s) /* ANSI C requires a parameter */
1496 signal(SIGINT, onintr);
1503 } else if (heedint) {
1510 /* -------- gmatch.c -------- */
1512 * int gmatch(string, pattern)
1513 * char *string, *pattern;
1515 * Match a pattern as in sh(1).
1520 #define QMASK (CMASK&~QUOTE)
1521 #define NOT '!' /* might use ^ */
1523 static const char *cclass(const char *p, int sub)
1525 int c, d, not, found;
1535 if (p[1] == '-' && p[2] != ']') {
1540 if (c == sub || (c <= sub && sub <= d))
1542 } while (*++p != ']');
1543 return found ? p + 1 : NULL;
1546 static int gmatch(const char *s, const char *p)
1550 if (s == NULL || p == NULL)
1553 while ((pc = *p++ & CMASK) != '\0') {
1570 if (*p == '\0' || gmatch(s, p))
1572 } while (*s++ != '\0');
1576 if (sc != (pc & ~QUOTE))
1584 /* -------- csyn.c -------- */
1586 * shell: syntax (C version)
1589 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1590 static void yyerror(const char *s)
1593 if (interactive && e.iop <= iostack) {
1595 while (eofc() == 0 && yylex(0) != '\n');
1601 static void zzerr(void) ATTRIBUTE_NORETURN;
1602 static void zzerr(void)
1604 yyerror("syntax error");
1609 DBGPRINTF7(("YYPARSE: enter...\n"));
1616 return (yynerrs != 0);
1619 static struct op *pipeline(int cf)
1624 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1628 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1631 while ((c = yylex(0)) == '|') {
1632 p = command(CONTIN);
1634 DBGPRINTF8(("PIPELINE: error!\n"));
1638 if (t->type != TPAREN && t->type != TCOM) {
1639 /* shell statement */
1640 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1643 t = block(TPIPE, t, p, NOWORDS);
1648 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1652 static struct op *andor(void)
1657 DBGPRINTF7(("ANDOR: enter...\n"));
1661 DBGPRINTF9(("ANDOR: t=%p\n", t));
1664 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1665 p = pipeline(CONTIN);
1667 DBGPRINTF8(("ANDOR: error!\n"));
1671 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1677 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1681 static struct op *c_list(void)
1686 DBGPRINTF7(("C_LIST: enter...\n"));
1693 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1695 while ((c = yylex(0)) == ';' || c == '&'
1696 || (multiline && c == '\n')) {
1704 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1712 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1716 static int synio(int cf)
1722 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1725 if (c != '<' && c != '>') {
1732 iop = io(iounit, i, yylval.cp);
1736 markhere(yylval.cp, iop);
1738 DBGPRINTF7(("SYNIO: returning 1\n"));
1742 static void musthave(int c, int cf)
1744 peeksym = yylex(cf);
1746 DBGPRINTF7(("MUSTHAVE: error!\n"));
1753 static struct op *simple(void)
1759 switch (peeksym = yylex(0)) {
1780 static struct op *nested(int type, int mark)
1784 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1790 return block(type, t, NOBLOCK, NOWORDS);
1793 static struct op *command(int cf)
1796 struct wdblock *iosave;
1799 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1825 t = nested(TPAREN, ')');
1829 t = nested(TBRACE, '}');
1839 t->words = wordlist();
1841 if (c != '\n' && c != ';')
1843 t->left = dogroup(0);
1851 t->type = c == WHILE ? TWHILE : TUNTIL;
1853 t->right = dogroup(1);
1865 musthave(IN, CONTIN);
1868 t->left = caselist();
1879 t->right = thenpart();
1888 musthave(WORD, 0); /* gets name of file */
1889 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1891 word(yylval.cp); /* add word to wdlist */
1892 word(NOWORD); /* terminate wdlist */
1893 t->words = copyw(); /* dup wdlist */
1903 DBGPRINTF(("COMMAND: returning %p\n", t));
1908 static struct op *dowholefile(int type, int mark)
1912 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1917 t = block(type, t, NOBLOCK, NOWORDS);
1918 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1922 static struct op *dogroup(int onlydone)
1928 if (c == DONE && onlydone)
1937 static struct op *thenpart(void)
1950 if (t->left == NULL)
1952 t->right = elsepart();
1956 static struct op *elsepart(void)
1961 switch (c = yylex(0)) {
1972 t->right = thenpart();
1981 static struct op *caselist(void)
1986 while ((peeksym = yylex(CONTIN)) != ESAC) {
1987 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1988 t = list(t, casepart());
1991 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1995 static struct op *casepart(void)
1999 DBGPRINTF7(("CASEPART: enter...\n"));
2003 t->words = pattern();
2006 peeksym = yylex(CONTIN);
2007 if (peeksym != ESAC)
2008 musthave(BREAK, CONTIN);
2010 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2015 static char **pattern(void)
2032 static char **wordlist(void)
2042 while ((c = yylex(0)) == WORD)
2050 * supporting functions
2052 static struct op *list(struct op *t1, struct op *t2)
2054 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2061 return block(TLIST, t1, t2, NOWORDS);
2064 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2068 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2076 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2082 /* See if given string is a shell multiline (FOR, IF, etc) */
2083 static int rlookup(char *n)
2085 const struct res *rp;
2087 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2089 for (rp = restab; rp->r_name; rp++)
2090 if (strcmp(rp->r_name, n) == 0) {
2091 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2092 return rp->r_val; /* Return numeric code for shell multiline */
2095 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2096 return 0; /* Not a shell multiline */
2099 static struct op *newtp(void)
2103 t = (struct op *) tree(sizeof(*t));
2111 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2116 static struct op *namelist(struct op *t)
2119 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2120 T_CMD_NAMES[t->type], iolist));
2123 iolist = addword((char *) NULL, iolist);
2124 t->ioact = copyio();
2128 if (t->type != TCOM) {
2129 if (t->type != TPAREN && t->ioact != NULL) {
2130 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2131 t->ioact = t->left->ioact;
2132 t->left->ioact = NULL;
2143 static char **copyw(void)
2147 wd = getwords(wdlist);
2152 static void word(char *cp)
2154 wdlist = addword(cp, wdlist);
2157 static struct ioword **copyio(void)
2159 struct ioword **iop;
2161 iop = (struct ioword **) getwords(iolist);
2166 static struct ioword *io(int u, int f, char *cp)
2170 iop = (struct ioword *) tree(sizeof(*iop));
2174 iolist = addword((char *) iop, iolist);
2178 static int yylex(int cf)
2198 line[LINELIM - 1] = '\0';
2201 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2206 if (any(c, "0123456789")) {
2209 if (c1 == '<' || c1 == '>') {
2218 case '#': /* Comment, skip to next newline or End-of-string */
2219 while ((c = my_getc(0)) != '\0' && c != '\n');
2224 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2228 DBGPRINTF9(("YYLEX: found $\n"));
2232 c = collect(c, '}');
2251 /* If more chars process them, else return NULL char */
2269 if (multiline || cf & CONTIN) {
2270 if (interactive && e.iop <= iostack) {
2271 #if ENABLE_FEATURE_EDITING
2272 current_prompt = cprompt->value;
2274 prs(cprompt->value);
2291 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2292 if (e.linep >= elinep)
2293 err("word too long");
2300 if (any(c, "\"'`$"))
2313 yylval.cp = strsave(line, areanum);
2318 static int collect(int c, int c1)
2322 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2325 while ((c = my_getc(c1)) != c1) {
2334 if (interactive && c == '\n' && e.iop <= iostack) {
2335 #if ENABLE_FEATURE_EDITING
2336 current_prompt = cprompt->value;
2338 prs(cprompt->value);
2346 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2351 /* "multiline commands" helper func */
2352 /* see if next 2 chars form a shell multiline */
2353 static int dual(int c)
2358 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2360 *cp++ = c; /* c is the given "peek" char */
2361 *cp++ = my_getc(0); /* get next char of input */
2362 *cp = '\0'; /* add EOS marker */
2364 c = rlookup(s); /* see if 2 chars form a shell multiline */
2366 unget(*--cp); /* String is not a shell multiline, put peek char back */
2368 return c; /* String is multiline, return numeric multiline (restab) code */
2371 static void diag(int ec)
2375 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2378 if (c == '>' || c == '<') {
2381 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2384 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2385 if (c != '&' || yylval.i == IOHERE)
2391 static char *tree(unsigned size)
2397 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2398 prs("command line too complicated\n");
2409 /* -------- exec.c -------- */
2411 static struct op **find1case(struct op *t, const char *w)
2419 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2423 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2424 T_CMD_NAMES[t->type]));
2426 if (t->type == TLIST) {
2427 tp = find1case(t->left, w);
2429 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2432 t1 = t->right; /* TPAT */
2436 for (wp = t1->words; *wp;) {
2437 cp = evalstr(*wp++, DOSUB);
2438 if (cp && gmatch(w, cp)) {
2439 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2445 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2449 static struct op *findcase(struct op *t, const char *w)
2453 tp = find1case(t, w);
2454 return tp != NULL ? *tp : NULL;
2461 static int execute(struct op *t, int *pin, int *pout, int act)
2464 volatile int i, rv, a;
2468 struct op *outtree_save;
2472 /* Avoid longjmp clobbering */
2477 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2481 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2482 t->type, T_CMD_NAMES[t->type],
2483 ((t->words == NULL) ? "NULL" : t->words[0])));
2487 wp = (wp2 = t->words) != NULL
2488 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2493 DBGPRINTF3(("EXECUTE: TDOT\n"));
2495 outtree_save = outtree;
2497 newfile(evalstr(t->words[0], DOALL));
2499 t->left = dowholefile(TLIST, 0);
2502 outtree = outtree_save;
2505 rv = execute(t->left, pin, pout, 0);
2507 rv = execute(t->right, pin, pout, 0);
2511 rv = execute(t->left, pin, pout, 0);
2515 rv = forkexec(t, pin, pout, act, wp);
2525 pv[0] = remap(pv[0]);
2526 pv[1] = remap(pv[1]);
2527 (void) execute(t->left, pin, pv, 0);
2528 rv = execute(t->right, pv, pout, 0);
2533 (void) execute(t->left, pin, pout, 0);
2534 rv = execute(t->right, pin, pout, 0);
2539 int hinteractive = interactive;
2541 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2544 if (i == 0) { /* child */
2545 signal(SIGINT, SIG_IGN);
2546 signal(SIGQUIT, SIG_IGN);
2548 signal(SIGTERM, SIG_DFL);
2552 open(bb_dev_null, 0);
2554 _exit(execute(t->left, pin, pout, FEXEC));
2556 interactive = hinteractive;
2558 setval(lookup("!"), putn(i));
2573 rv = execute(t->left, pin, pout, 0);
2575 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2576 rv = execute(t1, pin, pout, 0);
2587 while (*wp++ != NULL);
2589 vp = lookup(t->str);
2590 while (setjmp(bc.brkpt))
2594 for (t1 = t->left; i-- && *wp != NULL;) {
2596 rv = execute(t1, pin, pout, 0);
2598 brklist = brklist->nextlev;
2603 while (setjmp(bc.brkpt))
2608 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2609 rv = execute(t->right, pin, pout, 0);
2610 brklist = brklist->nextlev;
2615 if (t->right != NULL) {
2616 rv = !execute(t->left, pin, pout, 0) ?
2617 execute(t->right->left, pin, pout, 0) :
2618 execute(t->right->right, pin, pout, 0);
2623 cp = evalstr(t->str, DOSUB | DOTRIM);
2627 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2628 ((t->str == NULL) ? "NULL" : t->str),
2629 ((cp == NULL) ? "NULL" : cp)));
2631 t1 = findcase(t->left, cp);
2633 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2634 rv = execute(t1, pin, pout, 0);
2635 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2644 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2652 rv = execute(t1, pin, pout, 0);
2665 if (interactive && intr) {
2676 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2680 typedef int (*builtin_func_ptr)(struct op *);
2682 static builtin_func_ptr inbuilt(const char *s) {
2683 const struct builtincmd *bp;
2685 for (bp = builtincmds; bp->name != NULL; bp++)
2686 if (strcmp(bp->name, s) == 0)
2687 return bp->builtinfunc;
2692 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2696 builtin_func_ptr shcom = NULL;
2698 const char *cp = NULL;
2699 struct ioword **iopp;
2709 struct brkcon *hbrklist;
2713 /* Avoid longjmp clobbering */
2723 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2725 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2726 ((t->words == NULL) ? "NULL" : t->words[0])));
2730 rv = -1; /* system-detected error */
2731 if (t->type == TCOM) {
2732 while (*wp++ != NULL);
2735 /* strip all initial assignments */
2736 /* not correct wrt PATH=yyy command etc */
2738 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2740 echo(cp ? wp : owp);
2743 if (cp == NULL && t->ioact == NULL) {
2744 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2746 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2747 return setstatus(0);
2750 shcom = inbuilt(cp);
2757 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2760 if (shcom == NULL && (f & FEXEC) == 0) {
2761 /* Save values in case the child process alters them */
2765 hinteractive = interactive;
2770 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2775 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2779 if (newpid > 0) { /* Parent */
2780 /* Restore values */
2784 interactive = hinteractive;
2795 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2798 /* Must be the child process, pid should be 0 */
2799 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2802 signal(SIGINT, SIG_IGN);
2803 signal(SIGQUIT, SIG_IGN);
2814 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2819 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2820 err("piping to/from shell builtins not yet done");
2838 if (shcom != NULL && shcom != doexec) {
2840 err(": cannot redirect shell command");
2846 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2854 i = setstatus((*shcom) (t));
2857 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2861 /* should use FIOCEXCL */
2862 for (i = FDBASE; i < NOFILE; i++)
2865 signal(SIGINT, SIG_DFL);
2866 signal(SIGQUIT, SIG_DFL);
2869 if (t->type == TPAREN)
2870 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2874 cp = rexecve(wp[0], wp, makenv(0, NULL));
2881 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2889 * 0< 1> are ignored as required
2892 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2898 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2901 if (iop->io_unit == IODEFAULT) /* take default */
2902 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2904 if (pipein && iop->io_unit == 0)
2907 if (pipeout && iop->io_unit == 1)
2910 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2911 if ((iop->io_flag & IOHERE) == 0) {
2912 cp = iop->io_name; /* huh?? */
2913 cp = evalstr(cp, DOSUB | DOTRIM);
2918 if (iop->io_flag & IODUP) {
2919 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2921 err(": illegal >& argument");
2925 iop->io_flag = IOCLOSE;
2926 iop->io_flag &= ~(IOREAD | IOWRITE);
2928 switch (iop->io_flag) {
2934 case IOHERE | IOXHERE:
2935 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2936 cp = (char*)"here file";
2939 case IOWRITE | IOCAT:
2942 lseek(u, (long) 0, SEEK_END);
2946 u = creat(cp, 0666);
2950 u = dup2(*cp - '0', iop->io_unit);
2954 close(iop->io_unit);
2963 if (u != iop->io_unit) {
2964 dup2(u, iop->io_unit);
2971 * Enter a new loop level (marked for break/continue).
2973 static void brkset(struct brkcon *bc)
2975 bc->nextlev = brklist;
2980 * Wait for the last process created.
2981 * Print a message for each process found
2982 * that was killed by a signal.
2983 * Ignore interrupt signals while waiting
2984 * unless `canintr' is true.
2986 static int waitfor(int lastpid, int canintr)
2990 int oheedint = heedint;
2997 if (errno != EINTR || canintr)
3003 if (signame[rv] != NULL) {
3004 if (pid != lastpid) {
3011 if (pid != lastpid) {
3020 prs(" - core dumped");
3021 if (rv >= NSIGNAL || signame[rv])
3027 } while (pid != lastpid);
3042 static int setstatus(int s)
3045 setval(lookup("?"), putn(s));
3050 * PATH-searching interface to execve.
3051 * If getenv("PATH") were kept up-to-date,
3052 * execvp might be used.
3054 static const char *rexecve(char *c, char **v, char **envp)
3059 int eacces = 0, asis = 0;
3062 if (ENABLE_FEATURE_SH_STANDALONE_SHELL) {
3064 if (find_applet_by_name(name)) {
3065 /* We have to exec here since we vforked. Running
3066 * run_applet_by_name() won't work and bad things
3068 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3072 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3074 sp = any('/', c) ? "" : path->value;
3075 asis = (*sp == '\0');
3076 while (asis || *sp != '\0') {
3079 for (; *sp != '\0'; tp++) {
3082 asis = (*sp == '\0');
3088 for (i = 0; (*tp++ = c[i++]) != '\0';);
3090 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3092 execve(e.linep, v, envp);
3099 execve(DEFAULT_SHELL, v, envp);
3104 return (char *) bb_msg_memory_exhausted;
3107 return "argument list too long";
3114 return errno == ENOENT ? "not found" : "cannot execute";
3118 * Run the command produced by generator `f'
3119 * applied to stream `arg'.
3121 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3124 struct wdblock *swdlist;
3125 struct wdblock *siolist;
3131 /* Avoid longjmp clobbering */
3135 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3136 areanum, outtree, failpt));
3146 if (newenv(setjmp(errpt)) == 0) {
3153 if (setjmp(failpt) == 0 && yyparse() == 0)
3154 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3157 DBGPRINTF(("RUN: error from newenv()!\n"));
3164 freearea(areanum--);
3169 /* -------- do.c -------- */
3172 * built-in commands: doX
3175 static int dohelp(struct op *t)
3178 const struct builtincmd *x;
3180 puts("\nBuilt-in commands:\n"
3181 "-------------------");
3183 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3186 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3192 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
3195 const struct BB_applet *applet;
3197 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3201 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3210 return EXIT_SUCCESS;
3215 static int dolabel(struct op *t)
3220 static int dochdir(struct op *t)
3222 const char *cp, *er;
3226 cp = homedir->value;
3229 er = ": no home directory";
3234 er = ": bad directory";
3236 prs(cp != NULL ? cp : "cd");
3241 static int doshift(struct op *t)
3245 n = t->words[1] ? getn(t->words[1]) : 1;
3247 err("nothing to shift");
3253 setval(lookup("#"), putn(dolc));
3258 * execute login and newgrp directly
3260 static int dologin(struct op *t)
3265 signal(SIGINT, SIG_DFL);
3266 signal(SIGQUIT, SIG_DFL);
3268 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3275 static int doumask(struct op *t)
3284 for (n = 3 * 4; (n -= 3) >= 0;)
3285 putc('0' + ((i >> n) & 07), stderr);
3288 /* huh??? '8','9' are not allowed! */
3289 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3290 n = n * 8 + (*cp - '0');
3296 static int doexec(struct op *t)
3303 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3309 if (setjmp(failpt) == 0)
3310 execute(t, NOPIPE, NOPIPE, FEXEC);
3316 static int dodot(struct op *t)
3324 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)));
3328 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3331 DBGPRINTF(("DODOT: cp is %s\n", cp));
3333 sp = any('/', cp) ? ":" : path->value;
3335 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3336 ((sp == NULL) ? "NULL" : sp),
3337 ((e.linep == NULL) ? "NULL" : e.linep)));
3341 while (*sp && (*tp = *sp++) != ':')
3346 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3349 i = open(e.linep, 0);
3353 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3355 next(maltmp); /* Basically a PUSHIO */
3357 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3369 static int dowait(struct op *t)
3381 setstatus(waitfor(i, 1));
3385 static int doread(struct op *t)
3391 if (t->words[1] == NULL) {
3392 err("Usage: read name ...");
3395 for (wp = t->words + 1; *wp; wp++) {
3396 for (cp = e.linep; !nl && cp < elinep - 1; cp++) {
3397 nb = read(0, cp, sizeof(*cp));
3398 if (nb != sizeof(*cp))
3401 if (nl || (wp[1] && any(*cp, ifs->value)))
3407 setval(lookup(*wp), e.linep);
3412 static int doeval(struct op *t)
3414 return RUN(awordlist, t->words + 1, wdchar);
3417 static int dotrap(struct op *t)
3422 if (t->words[1] == NULL) {
3423 for (i = 0; i <= _NSIG; i++)
3432 resetsig = isdigit(*t->words[1]);
3433 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3434 n = getsig(t->words[i]);
3438 if (*t->words[1] != '\0') {
3439 trap[n] = strsave(t->words[1], 0);
3448 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3456 static int getsig(char *s)
3461 if (n < 0 || n > _NSIG) {
3462 err("trap: bad signal number");
3468 static void setsig(int n, sighandler_t f)
3472 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3478 static int getn(char *as)
3489 for (n = 0; isdigit(*s); s++)
3490 n = (n * 10) + (*s - '0');
3493 err(": bad number");
3498 static int dobreak(struct op *t)
3500 return brkcontin(t->words[1], 1);
3503 static int docontinue(struct op *t)
3505 return brkcontin(t->words[1], 0);
3508 static int brkcontin(char *cp, int val)
3513 nl = cp == NULL ? 1 : getn(cp);
3520 brklist = bc->nextlev;
3523 err("bad break/continue level");
3527 longjmp(bc->brkpt, 1);
3531 static int doexit(struct op *t)
3538 setstatus(getn(cp));
3540 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3547 static int doexport(struct op *t)
3549 rdexp(t->words + 1, export, EXPORT);
3553 static int doreadonly(struct op *t)
3555 rdexp(t->words + 1, ronly, RONLY);
3559 static void rdexp(char **wp, void (*f) (struct var *), int key)
3561 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3562 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3565 for (; *wp != NULL; wp++) {
3566 if (isassign(*wp)) {
3570 for (cp = *wp; *cp != '='; cp++);
3582 static void badid(char *s)
3585 err(": bad identifier");
3588 static int doset(struct op *t)
3596 for (vp = vlist; vp; vp = vp->next)
3597 varput(vp->name, 1);
3601 /* bad: t->words++; */
3602 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3604 flag['x'] = flag['v'] = 0;
3614 if (*cp >= 'a' && *cp <= 'z')
3623 t->words[0] = dolv[0];
3624 for (n = 1; t->words[n]; n++)
3625 setarea((char *) t->words[n], 0);
3628 setval(lookup("#"), putn(dolc));
3629 setarea((char *) (dolv - 1), 0);
3634 static void varput(char *s, int out)
3636 if (isalnum(*s) || *s == '_') {
3637 write(out, s, strlen(s));
3638 write(out, "\n", 1);
3644 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3645 * This file contains code for the times builtin.
3647 static int dotimes(struct op *t)
3650 long clk_tck = sysconf(_SC_CLK_TCK);
3653 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3654 (int) (buf.tms_utime / clk_tck / 60),
3655 ((double) buf.tms_utime) / clk_tck,
3656 (int) (buf.tms_stime / clk_tck / 60),
3657 ((double) buf.tms_stime) / clk_tck,
3658 (int) (buf.tms_cutime / clk_tck / 60),
3659 ((double) buf.tms_cutime) / clk_tck,
3660 (int) (buf.tms_cstime / clk_tck / 60),
3661 ((double) buf.tms_cstime) / clk_tck);
3666 /* -------- eval.c -------- */
3671 * blank interpretation
3676 static char **eval(char **ap, int f)
3684 /* Avoid longjmp clobbering */
3689 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3695 if (newenv(setjmp(errpt)) == 0) {
3696 while (*ap && isassign(*ap))
3697 expand(*ap++, &wb, f & ~DOGLOB);
3699 for (wf = ap; *wf; wf++) {
3701 expand(*wf, &wb, f & ~DOGLOB);
3704 for (wb = addword((char *) 0, wb); *ap; ap++) {
3705 if (!flag['k'] || !isassign(*ap))
3706 expand(*ap, &wb, f & ~DOKEY);
3708 wb = addword((char *) 0, wb);
3714 return gflg ? (char **) NULL : wp;
3719 * Make the exported environment from the exported
3720 * names in the dictionary. Keyword assignments
3721 * will already have been done.
3723 static char **makenv(int all, struct wdblock *wb)
3727 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3729 for (vp = vlist; vp; vp = vp->next)
3730 if (all || vp->status & EXPORT)
3731 wb = addword(vp->name, wb);
3732 wb = addword((char *) 0, wb);
3733 return getwords(wb);
3736 static int expand(const char *cp, struct wdblock **wbp, int f)
3742 /* Avoid longjmp clobbering */
3746 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3753 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3754 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3756 xp = strsave(cp, areanum);
3759 *wbp = addword(xp, *wbp);
3763 if (newenv(setjmp(errpt)) == 0) {
3764 PUSHIO(aword, cp, strchar);
3766 while ((xp = blank(f)) && gflg == 0) {
3768 xp = strsave(xp, areanum);
3769 if ((f & DOGLOB) == 0) {
3772 *wbp = addword(xp, *wbp);
3774 *wbp = glob(xp, *wbp);
3782 static char *evalstr(char *cp, int f)
3786 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3789 if (expand(cp, &wb, f)) {
3790 if (wb == NULL || wb->w_nword == 0
3791 || (cp = wb->w_words[0]) == NULL
3793 // TODO: I suspect that
3794 // char *evalstr(char *cp, int f) is actually
3795 // const char *evalstr(const char *cp, int f)!
3806 * Blank interpretation and quoting
3808 static char *blank(int f)
3812 int scanequals, foundequals;
3814 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3817 scanequals = f & DOKEY;
3821 c = subgetc('"', foundequals);
3830 if (f & DOBLANK && any(c, ifs->value))
3839 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3842 if (c == '\'' || !any(c, "$`\""))
3849 if (!isalpha(c) && c != '_')
3852 c = subgetc('"', foundequals);
3854 f & (DOBLANK && any(c, ifs->value)) ||
3855 (!INSUB() && any(c, "\"'"))) {
3866 } else if (!isalnum(c) && c != '_')
3876 * Get characters, substituting for ` and $
3878 static int subgetc(char ec, int quoted)
3882 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3886 if (!INSUB() && ec != '\'') {
3888 if (grave(quoted) == 0)
3890 e.iop->task = XGRAVE;
3896 e.iop->task = XDOLL;
3905 * Prepare to generate the string returned by ${} substitution.
3907 static int dollar(int quoted)
3912 char *s, c, *cp = NULL;
3915 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3921 if (isalpha(c) || c == '_') {
3922 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3923 if (e.linep < elinep)
3930 otask = e.iop->task;
3932 e.iop->task = XOTHER;
3933 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3934 if (e.linep < elinep)
3937 e.iop->task = otask;
3944 if (e.linep >= elinep) {
3945 err("string in ${} too long");
3951 for (cp = s + 1; *cp; cp++)
3952 if (any(*cp, "=-+?")) {
3957 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3959 /* currently this does not distinguish $* and $@ */
3960 /* should check dollar */
3962 PUSHIO(awordlist, dolv + 1, dolchar);
3964 } else { /* trap the nasty ${=} */
3975 err("cannot use ${...=...} with $n");
3984 dolp = strsave(cp, areanum);
3989 prs("missing value for ");
3996 } else if (c == '+')
3997 dolp = strsave(cp, areanum);
3998 if (flag['u'] && dolp == null) {
3999 prs("unset variable: ");
4004 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4009 * Run the command in `...` and read its output.
4012 static int grave(int quoted)
4018 static char child_cmd[LINELIM];
4024 char *argument_list[4];
4025 struct wdblock *wb = NULL;
4028 /* Avoid longjmp clobbering */
4032 for (cp = e.iop->argp->aword; *cp != '`'; cp++) {
4034 err("no closing `");
4039 /* string copy with dollar expansion */
4040 src = e.iop->argp->aword;
4045 while ((*src != '`') && (count < LINELIM)) {
4050 if (*src == '$' && !ignore && !ignore_once) {
4052 char var_name[LINELIM];
4053 char alt_value[LINELIM];
4066 var_name[var_index++] = *src++;
4067 while (isalnum(*src) || *src=='_')
4068 var_name[var_index++] = *src++;
4069 var_name[var_index] = 0;
4082 err("unclosed ${\n");
4087 while (*src && (*src != '}')) {
4088 alt_value[alt_index++] = *src++;
4090 alt_value[alt_index] = 0;
4092 err("unclosed ${\n");
4099 if (isalpha(*var_name)) {
4100 /* let subshell handle it instead */
4102 char *namep = var_name;
4110 char *altp = alt_value;
4118 wb = addword(lookup(var_name)->name, wb);
4122 vp = lookup(var_name);
4123 if (vp->value != null)
4124 value = (operator == '+') ?
4125 alt_value : vp->value;
4126 else if (operator == '?') {
4129 } else if (alt_index && (operator != '+')) {
4131 if (operator == '=')
4136 while (*value && (count < LINELIM)) {
4149 if (openpipe(pf) < 0)
4152 while ((i = vfork()) == -1 && errno == EAGAIN);
4154 DBGPRINTF3(("GRAVE: i is %p\n", io));
4158 err((char *) bb_msg_memory_exhausted);
4162 waitpid(i, NULL, 0);
4163 e.iop->argp->aword = ++cp;
4165 PUSHIO(afile, remap(pf[0]),
4166 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4169 /* allow trapped signals */
4170 /* XXX - Maybe this signal stuff should go as well? */
4171 for (j = 0; j <= _NSIG; j++)
4172 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4178 argument_list[0] = (char *) DEFAULT_SHELL;
4179 argument_list[1] = (char *) "-c";
4180 argument_list[2] = child_cmd;
4181 argument_list[3] = NULL;
4183 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4184 prs(argument_list[0]);
4191 static char *unquote(char *as)
4202 /* -------- glob.c -------- */
4208 #define scopy(x) strsave((x), areanum)
4210 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4212 static struct wdblock *cl, *nl;
4213 static char spcl[] = "[?*";
4215 static struct wdblock *glob(char *cp, struct wdblock *wb)
4223 for (pp = cp; *pp; pp++)
4226 else if (!any(*pp & ~QUOTE, spcl))
4229 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4230 nl = newword(cl->w_nword * 2);
4231 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4232 for (pp = cl->w_words[i]; *pp; pp++)
4233 if (any(*pp, spcl)) {
4234 globname(cl->w_words[i], pp);
4238 nl = addword(scopy(cl->w_words[i]), nl);
4240 for (i = 0; i < cl->w_nword; i++)
4241 DELETE(cl->w_words[i]);
4244 for (i = 0; i < cl->w_nword; i++)
4245 unquote(cl->w_words[i]);
4246 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4248 for (i = 0; i < cl->w_nword; i++)
4249 wb = addword(cl->w_words[i], wb);
4254 wb = addword(unquote(cp), wb);
4258 static void globname(char *we, char *pp)
4261 char *name, *gp, *dp;
4265 char dname[NAME_MAX + 1];
4268 for (np = we; np != pp; pp--)
4271 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4275 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4284 dname[NAME_MAX] = '\0';
4285 while ((de = readdir(dirp)) != NULL) {
4286 /* XXX Hmmm... What this could be? (abial) */
4288 if (ent[j].d_ino == 0)
4291 strncpy(dname, de->d_name, NAME_MAX);
4292 if (dname[0] == '.')
4295 for (k = 0; k < NAME_MAX; k++)
4296 if (any(dname[k], spcl))
4298 if (gmatch(dname, gp)) {
4299 name = generate(we, pp, dname, np);
4300 if (*np && !anys(np, spcl)) {
4301 if (stat(name, &dbuf)) {
4306 nl = addword(name, nl);
4315 * generate a pathname as below.
4316 * start..end1 / middle end
4317 * the slashes come for free
4319 static char *generate(char *start1, char *end1, char *middle, char *end)
4324 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4325 for (xp = start1; xp != end1;)
4327 for (xp = middle; (*op++ = *xp++) != '\0';);
4329 for (xp = end; (*op++ = *xp++) != '\0';);
4333 static int anyspcl(struct wdblock *wb)
4339 for (i = 0; i < wb->w_nword; i++)
4340 if (anys(spcl, *wd++))
4345 static int xstrcmp(char *p1, char *p2)
4347 return strcmp(*(char **) p1, *(char **) p2);
4351 /* -------- word.c -------- */
4353 static struct wdblock *newword(int nw)
4357 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4363 static struct wdblock *addword(char *wd, struct wdblock *wb)
4365 struct wdblock *wb2;
4369 wb = newword(NSTART);
4371 if (nw >= wb->w_bsize) {
4372 wb2 = newword(nw * 2);
4373 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4374 nw * sizeof(char *));
4379 wb->w_words[wb->w_nword++] = wd;
4384 char **getwords(struct wdblock *wb)
4391 if (wb->w_nword == 0) {
4395 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4396 memcpy((char *) wd, (char *) wb->w_words, nb);
4397 DELETE(wb); /* perhaps should done by caller */
4401 static int (*func) (char *, char *);
4404 static void glob3(char *i, char *j, char *k)
4406 char *index1, *index2, *index3;
4416 *index1++ = *index3;
4417 *index3++ = *index2;
4422 static void glob2(char *i, char *j)
4424 char *index1, *index2, c;
4432 *index1++ = *index2;
4437 static void glob1(char *base, char *lim)
4448 n = (int) (lim - base);
4451 n = v2 * (n / (2 * v2));
4452 hptr = lptr = base + n;
4457 c = (*func) (i, lptr);
4471 c = (*func) (hptr, j);
4495 if (lptr - base >= lim - hptr) {
4496 glob1(hptr + v2, lim);
4511 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4515 glob1(a0, a0 + a1 * a2);
4519 /* -------- io.c -------- */
4525 static int my_getc(int ec)
4529 if (e.linep > elinep) {
4530 while ((c = readc()) != '\n' && c);
4531 err("input line too long");
4536 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4539 if (c == '\n' && ec != '\"')
4547 static void unget(int c)
4549 if (e.iop >= e.iobase)
4553 static int eofc(void)
4555 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4558 static int readc(void)
4562 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4564 for (; e.iop >= e.iobase; e.iop--) {
4565 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4571 if (e.iop->prev != 0) {
4572 c = (*e.iop->iofn)(e.iop->argp, e.iop);
4578 if (e.iop == iostack)
4583 if (e.iop->task == XIO && e.iop->prev != '\n') {
4585 if (e.iop == iostack)
4590 if (e.iop->task == XIO) {
4595 if (interactive && e.iop == iostack + 1) {
4596 #if ENABLE_FEATURE_EDITING
4597 current_prompt = prompt->value;
4605 if (e.iop >= iostack) {
4606 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4610 DBGPRINTF(("READC: leave()...\n"));
4617 static void ioecho(char c)
4620 write(2, &c, sizeof c);
4624 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4626 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4627 argp->afid, e.iop));
4629 /* Set env ptr for io source to next array spot and check for array overflow */
4630 if (++e.iop >= &iostack[NPUSH]) {
4632 err("Shell input nested too deeply");
4637 /* We did not overflow the NPUSH array spots so setup data structs */
4639 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4641 if (argp->afid != AFID_NOBUF)
4645 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4646 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4648 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4650 if (e.iop == &iostack[0])
4651 e.iop->argp->afbuf = &mainbuf;
4653 e.iop->argp->afbuf = &sharedbuf;
4655 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4656 /* This line appears to be active when running scripts from command line */
4657 if ((isatty(e.iop->argp->afile) == 0)
4658 && (e.iop == &iostack[0]
4659 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4660 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4661 bufid = AFID_ID; /* AFID_ID = 0 */
4663 e.iop->argp->afid = bufid; /* assign buffer id */
4666 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4667 iostack, e.iop, e.iop->argp->afbuf));
4668 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4669 &mainbuf, &sharedbuf, bufid, e.iop));
4673 e.iop->prev = ~'\n';
4678 if (fn == filechar || fn == linechar)
4680 else if (fn == (int (*)(struct ioarg *)) gravechar
4681 || fn == (int (*)(struct ioarg *)) qgravechar)
4682 e.iop->task = XGRAVE;
4684 e.iop->task = XOTHER;
4687 static struct io *setbase(struct io *ip)
4697 * Input generating functions
4701 * Produce the characters of a string, then a newline, then EOF.
4703 static int nlchar(struct ioarg *ap)
4707 if (ap->aword == NULL)
4718 * Given a list of words, produce the characters
4719 * in them, with a space after each word.
4721 static int wdchar(struct ioarg *ap)
4736 ap->awordlist = NULL;
4741 * Return the characters of a list of words,
4742 * producing a space between them.
4744 static int dolchar(struct ioarg *ap)
4748 wp = *ap->awordlist++;
4750 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4756 static int xxchar(struct ioarg *ap)
4760 if (ap->aword == NULL)
4771 * Produce the characters from a single word (string).
4773 static int strchar(struct ioarg *ap)
4775 if (ap->aword == NULL)
4777 return *ap->aword++;
4781 * Produce quoted characters from a single word (string).
4783 static int qstrchar(struct ioarg *ap)
4787 if (ap->aword == NULL)
4796 * Return the characters from a file.
4798 static int filechar(struct ioarg *ap)
4802 struct iobuf *bp = ap->afbuf;
4804 if (ap->afid != AFID_NOBUF) {
4805 i = (ap->afid != bp->id);
4806 if (i || bp->bufp == bp->ebufp) {
4808 lseek(ap->afile, ap->afpos, SEEK_SET);
4810 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4818 bp->ebufp = bp->bufp + i;
4822 return *bp->bufp++ & 0177;
4824 #if ENABLE_FEATURE_EDITING
4825 if (interactive && isatty(ap->afile)) {
4826 static char mycommand[BUFSIZ];
4827 static int position = 0, size = 0;
4829 while (size == 0 || position >= size) {
4830 read_line_input(current_prompt, mycommand, BUFSIZ, line_input_state);
4831 size = strlen(mycommand);
4834 c = mycommand[position];
4839 i = safe_read(ap->afile, &c, sizeof(c));
4840 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4844 * Return the characters from a here temp file.
4846 static int herechar(struct ioarg *ap)
4850 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4858 * Return the characters produced by a process (`...`).
4859 * Quote them if required, and remove any trailing newline characters.
4861 static int gravechar(struct ioarg *ap, struct io *iop)
4865 c = qgravechar(ap, iop) & ~QUOTE;
4871 static int qgravechar(struct ioarg *ap, struct io *iop)
4875 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4880 return '\n' | QUOTE;
4884 } else if ((c = filechar(ap)) == '\n') {
4886 while ((c = filechar(ap)) == '\n')
4894 return c != 0 ? c | QUOTE : 0;
4898 * Return a single command (usually the first line) from a file.
4900 static int linechar(struct ioarg *ap)
4908 ap->afile = -1; /* illegal value */
4915 * remap fd into Shell's fd space
4917 static int remap(int fd)
4923 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
4926 for (i = 0; i < NOFILE; i++)
4933 } while (fd >= 0 && fd < e.iofd);
4935 for (i = 0; i < NOFILE; i++)
4940 err("too many files open in shell");
4946 static int openpipe(int *pv)
4952 err("can't create pipe - try again");
4956 static void closepipe(int *pv)
4965 /* -------- here.c -------- */
4971 static void markhere(char *s, struct ioword *iop)
4973 struct here *h, *lh;
4975 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4977 h = (struct here *) space(sizeof(struct here));
4981 h->h_tag = evalstr(s, DOSUB);
4991 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4992 if (lh->h_next == 0) {
4998 iop->io_flag |= IOHERE | IOXHERE;
4999 for (s = h->h_tag; *s; s++) {
5001 iop->io_flag &= ~IOXHERE;
5005 h->h_dosub = iop->io_flag & IOXHERE;
5008 static void gethere(void)
5010 struct here *h, *hp;
5012 DBGPRINTF7(("GETHERE: enter...\n"));
5014 /* Scan here files first leaving inhere list in place */
5015 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5016 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5018 /* Make inhere list active - keep list intact for scraphere */
5020 hp->h_next = acthere;
5026 static void readhere(char **name, char *s, int ec)
5029 char tname[30] = ".msh_XXXXXX";
5032 char myline[LINELIM + 1];
5035 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5037 tf = mkstemp(tname);
5041 *name = strsave(tname, areanum);
5043 if (newenv(setjmp(errpt)) != 0)
5046 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5049 if (interactive && e.iop <= iostack) {
5050 #if ENABLE_FEATURE_EDITING
5051 current_prompt = cprompt->value;
5053 prs(cprompt->value);
5057 while ((c = my_getc(ec)) != '\n' && c) {
5060 if (thenext >= &myline[LINELIM]) {
5067 if (strcmp(s, myline) == 0 || c == 0)
5070 write(tf, myline, (int) (thenext - myline));
5073 prs("here document `");
5083 * open here temp file.
5084 * if unquoted here, expand here temp file into second temp file.
5086 static int herein(char *hname, int xdoll)
5092 /* Avoid longjmp clobbering */
5098 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5100 hf = open(hname, 0);
5106 char tname[30] = ".msh_XXXXXX";
5109 tf = mkstemp(tname);
5113 if (newenv(setjmp(errpt)) == 0) {
5114 PUSHIO(afile, hf, herechar);
5116 while ((c = subgetc(0, 0)) != 0) {
5118 write(tf, &c, sizeof c);
5124 tf = open(tname, 0);
5131 static void scraphere(void)
5135 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5137 for (h = inhere; h != NULL; h = h->h_next) {
5138 if (h->h_iop && h->h_iop->io_name)
5139 unlink(h->h_iop->io_name);
5144 /* unlink here temp files before a freearea(area) */
5145 static void freehere(int area)
5147 struct here *h, *hl;
5149 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5152 for (h = acthere; h != NULL; h = h->h_next)
5153 if (getarea((char *) h) >= area) {
5154 if (h->h_iop->io_name != NULL)
5155 unlink(h->h_iop->io_name);
5157 acthere = h->h_next;
5159 hl->h_next = h->h_next;
5165 /* -------- sh.c -------- */
5170 int msh_main(int argc, char **argv);
5171 int msh_main(int argc, char **argv)
5177 int (*iof) (struct ioarg *);
5179 #if ENABLE_FEATURE_EDITING
5180 line_input_state = new_line_input_t(FOR_SHELL);
5183 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5189 assign(*ap++, !COPYV);
5190 for (ap = environ; *ap;)
5191 export(lookup(*ap++));
5196 shell = lookup("SHELL");
5197 if (shell->value == null)
5198 setval(shell, (char *)DEFAULT_SHELL);
5201 homedir = lookup("HOME");
5202 if (homedir->value == null)
5203 setval(homedir, "/");
5206 setval(lookup("$"), putn(getpid()));
5208 path = lookup("PATH");
5209 if (path->value == null) {
5211 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
5213 setval(path, "/bin:/usr/bin");
5217 ifs = lookup("IFS");
5218 if (ifs->value == null)
5219 setval(ifs, " \t\n");
5222 mshdbg_var = lookup("MSHDEBUG");
5223 if (mshdbg_var->value == null)
5224 setval(mshdbg_var, "0");
5227 prompt = lookup("PS1");
5228 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5229 if (prompt->value == null)
5231 setval(prompt, DEFAULT_USER_PROMPT);
5232 if (geteuid() == 0) {
5233 setval(prompt, DEFAULT_ROOT_PROMPT);
5234 prompt->status &= ~EXPORT;
5236 cprompt = lookup("PS2");
5237 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5238 if (cprompt->value == null)
5240 setval(cprompt, "> ");
5246 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5247 for (s = argv[0] + 1; *s; s++)
5250 prompt->status &= ~EXPORT;
5251 cprompt->status &= ~EXPORT;
5253 setval(cprompt, "");
5256 PUSHIO(aword, *++argv, iof = nlchar);
5264 /* standard input */
5268 prompt->status &= ~EXPORT;
5276 if (*s >= 'a' && *s <= 'z')
5284 if (iof == filechar && --argc > 0) {
5286 setval(cprompt, "");
5287 prompt->status &= ~EXPORT;
5288 cprompt->status &= ~EXPORT;
5290 /* Shell is non-interactive, activate printf-based debug */
5292 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5296 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5300 exit(1); /* Exit on error */
5306 /* This won't be true if PUSHIO has been called, say from newfile() above */
5307 if (e.iop < iostack) {
5308 PUSHIO(afile, 0, iof);
5309 if (isatty(0) && isatty(1) && !cflag) {
5311 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5313 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
5315 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
5317 printf("Enter 'help' for a list of built-in commands.\n\n");
5322 signal(SIGQUIT, qflag);
5323 if (name && name[0] == '-') {
5325 f = open(".profile", 0);
5328 f = open("/etc/profile", 0);
5333 signal(SIGTERM, sig);
5335 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5336 signal(SIGINT, onintr);
5341 for (ap = ++argv; --argc > 0;) {
5343 if (assign(*ap, !COPYV)) {
5344 dolc--; /* keyword */
5350 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5352 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
5355 if (interactive && e.iop <= iostack) {
5356 #if ENABLE_FEATURE_EDITING
5357 current_prompt = prompt->value;
5363 /* Ensure that getenv("PATH") stays current */
5364 setenv("PATH", path->value, 1);
5367 DBGPRINTF(("MSH_MAIN: returning.\n"));
5372 * Copyright (c) 1987,1997, Prentice Hall
5373 * All rights reserved.
5375 * Redistribution and use of the MINIX operating system in source and
5376 * binary forms, with or without modification, are permitted provided
5377 * that the following conditions are met:
5379 * Redistributions of source code must retain the above copyright
5380 * notice, this list of conditions and the following disclaimer.
5382 * Redistributions in binary form must reproduce the above
5383 * copyright notice, this list of conditions and the following
5384 * disclaimer in the documentation and/or other materials provided
5385 * with the distribution.
5387 * Neither the name of Prentice Hall nor the names of the software
5388 * authors or contributors may be used to endorse or promote
5389 * products derived from this software without specific prior
5390 * written permission.
5392 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5393 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5394 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5395 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5396 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5397 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5398 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5399 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5400 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5401 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5402 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5403 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.