1 /* vi: set sw=4 ts=4: */
3 * Minix shell port for busybox
5 * This version of the Minix shell was adapted for use in busybox
6 * by Erik Andersen <andersen@codepoet.org>
8 * - backtick expansion did not work properly
9 * Jonas Holmberg <jonas.holmberg@axis.com>
10 * Robert Schwebel <r.schwebel@pengutronix.de>
11 * Erik Andersen <andersen@codepoet.org>
13 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
16 #include <sys/times.h>
23 # include <sys/types.h>
24 # include <sys/stat.h>
25 # include <sys/wait.h>
36 # define bb_dev_null "/dev/null"
37 # define DEFAULT_SHELL "/proc/self/exe"
38 # define CONFIG_BUSYBOX_EXEC_PATH "/proc/self/exe"
39 # define BB_BANNER "busybox standalone"
40 # define ENABLE_FEATURE_SH_STANDALONE 0
41 # define bb_msg_memory_exhausted "memory exhausted"
42 # define xmalloc(size) malloc(size)
43 # define msh_main(argc,argv) main(argc,argv)
44 # define safe_read(fd,buf,count) read(fd,buf,count)
45 # define NOT_LONE_DASH(s) ((s)[0] != '-' || (s)[1])
46 # define LONE_CHAR(s,c) ((s)[0] == (c) && !(s)[1])
47 # define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
48 static char *find_applet_by_name(const char *applet)
52 static char *utoa_to_buf(unsigned n, char *buf, unsigned buflen)
55 assert(sizeof(unsigned) == 4);
58 for (i = 1000000000; i; i /= 10) {
60 if (res || out || i == 1) {
70 static char *itoa_to_buf(int n, char *buf, unsigned buflen)
72 if (buflen && n < 0) {
77 return utoa_to_buf((unsigned)n, buf, buflen);
79 static char local_buf[12];
80 static char *itoa(int n)
82 *(itoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
87 extern char **environ;
90 /*#define MSHDEBUG 1*/
93 int mshdbg = MSHDEBUG;
95 #define DBGPRINTF(x) if (mshdbg>0) printf x
96 #define DBGPRINTF0(x) if (mshdbg>0) printf x
97 #define DBGPRINTF1(x) if (mshdbg>1) printf x
98 #define DBGPRINTF2(x) if (mshdbg>2) printf x
99 #define DBGPRINTF3(x) if (mshdbg>3) printf x
100 #define DBGPRINTF4(x) if (mshdbg>4) printf x
101 #define DBGPRINTF5(x) if (mshdbg>5) printf x
102 #define DBGPRINTF6(x) if (mshdbg>6) printf x
103 #define DBGPRINTF7(x) if (mshdbg>7) printf x
104 #define DBGPRINTF8(x) if (mshdbg>8) printf x
105 #define DBGPRINTF9(x) if (mshdbg>9) printf x
109 #define RCPRINTF(x) if (mshdbg_rc) printf x
114 #define DBGPRINTF0(x) ((void)0)
115 #define DBGPRINTF1(x) ((void)0)
116 #define DBGPRINTF2(x) ((void)0)
117 #define DBGPRINTF3(x) ((void)0)
118 #define DBGPRINTF4(x) ((void)0)
119 #define DBGPRINTF5(x) ((void)0)
120 #define DBGPRINTF6(x) ((void)0)
121 #define DBGPRINTF7(x) ((void)0)
122 #define DBGPRINTF8(x) ((void)0)
123 #define DBGPRINTF9(x) ((void)0)
125 #define RCPRINTF(x) ((void)0)
127 #endif /* MSHDEBUG */
130 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
131 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
132 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
134 # define DEFAULT_ROOT_PROMPT "# "
135 # define DEFAULT_USER_PROMPT "$ "
139 /* -------- sh.h -------- */
145 #define NPUSH 8 /* limit to input nesting */
148 #define NOFILE 20 /* Number of open files */
149 #define NUFILE 10 /* Number of user-accessible files */
150 #define FDBASE 10 /* First file usable by Shell */
153 * values returned by wait
155 #define WAITSIG(s) ((s) & 0177)
156 #define WAITVAL(s) (((s) >> 8) & 0377)
157 #define WAITCORE(s) (((s) & 0200) != 0)
160 * library and system definitions
162 typedef void xint; /* base type of jmp_buf, for not broken compilers */
167 #define NOBLOCK ((struct op *)NULL)
168 #define NOWORD ((char *)NULL)
169 #define NOWORDS ((char **)NULL)
170 #define NOPIPE ((int *)NULL)
176 short io_unit; /* unit affected */
177 short io_flag; /* action (below) */
178 char *io_name; /* file name */
181 #define IOREAD 1 /* < */
182 #define IOHERE 2 /* << (here file) */
183 #define IOWRITE 4 /* > */
184 #define IOCAT 8 /* >> */
185 #define IOXHERE 16 /* ${}, ` in << */
186 #define IODUP 32 /* >&digit */
187 #define IOCLOSE 64 /* >&- */
189 #define IODEFAULT (-1) /* token for default IO unit */
193 * Description of a command or an operation on commands.
194 * Might eventually use a union.
197 int type; /* operation type, see below */
198 char **words; /* arguments to a command */
199 struct ioword **ioact; /* IO actions (eg, < > >>) */
202 char *str; /* identifier for case and for */
205 #define TCOM 1 /* command */
206 #define TPAREN 2 /* (c-list) */
207 #define TPIPE 3 /* a | b */
208 #define TLIST 4 /* a [&;] b */
209 #define TOR 5 /* || */
210 #define TAND 6 /* && */
218 #define TPAT 14 /* pattern in case */
219 #define TBRACE 15 /* {c-list} */
220 #define TASYNC 16 /* c & */
221 /* Added to support "." file expansion */
224 /* Strings for names to make debug easier */
226 static const char *const T_CMD_NAMES[] = {
249 * actions determining the environment of a process
251 #define FEXEC 1 /* execute without forking */
253 #define AREASIZE (90000)
256 * flags to control evaluation of words
258 #define DOSUB 1 /* interpret $, `, and quotes */
259 #define DOBLANK 2 /* perform blank interpretation */
260 #define DOGLOB 4 /* interpret [?* */
261 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
262 #define DOTRIM 16 /* trim resulting string */
264 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
269 struct brkcon *nextlev;
276 * -k: look for name=value everywhere on command line
278 * -t: exit after reading and executing one command
281 * -u: unset variables net diagnostic
283 static char flags['z' - 'a' + 1];
284 /* this looks weird, but is OK ... we index FLAG with 'a'...'z' */
285 #define FLAG (flags - 'a')
287 /* moved to G: static char *trap[_NSIG + 1]; */
288 /* moved to G: static char ourtrap[_NSIG + 1]; */
289 static int trapset; /* trap pending */
291 static int yynerrs; /* yacc */
293 /* moved to G: static char line[LINELIM]; */
295 #if ENABLE_FEATURE_EDITING
296 static char *current_prompt;
297 static line_input_t *line_input_state;
304 static const char *rexecve(char *c, char **v, char **envp);
305 static char *evalstr(char *cp, int f);
306 static char *putn(int n);
307 static char *unquote(char *as);
308 static int rlookup(char *n);
309 static struct wdblock *glob(char *cp, struct wdblock *wb);
310 static int my_getc(int ec);
311 static int subgetc(char ec, int quoted);
312 static char **makenv(int all, struct wdblock *wb);
313 static char **eval(char **ap, int f);
314 static int setstatus(int s);
315 static int waitfor(int lastpid, int canintr);
317 static void onintr(int s); /* SIGINT handler */
319 static int newenv(int f);
320 static void quitenv(void);
321 static void next(int f);
322 static void setdash(void);
323 static void onecommand(void);
324 static void runtrap(int i);
327 /* -------- area stuff -------- */
329 #define REGSIZE sizeof(struct region)
331 /* #define SHRINKBY (64) */
335 #define ALIGN (sizeof(int)-1)
344 /* -------- grammar stuff -------- */
369 /* Added for "." file expansion */
372 #define YYERRCODE 300
375 #define CONTIN 01 /* skip new lines to complete command */
377 static struct op *pipeline(int cf);
378 static struct op *andor(void);
379 static struct op *c_list(void);
380 static int synio(int cf);
381 static void musthave(int c, int cf);
382 static struct op *simple(void);
383 static struct op *nested(int type, int mark);
384 static struct op *command(int cf);
385 static struct op *dogroup(int onlydone);
386 static struct op *thenpart(void);
387 static struct op *elsepart(void);
388 static struct op *caselist(void);
389 static struct op *casepart(void);
390 static char **pattern(void);
391 static char **wordlist(void);
392 static struct op *list(struct op *t1, struct op *t2);
393 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
394 static struct op *newtp(void);
395 static struct op *namelist(struct op *t);
396 static char **copyw(void);
397 static void word(char *cp);
398 static struct ioword **copyio(void);
399 static struct ioword *io(int u, int f, char *cp);
400 static int yylex(int cf);
401 static int collect(int c, int c1);
402 static int dual(int c);
403 static void diag(int ec);
404 static char *tree(unsigned size);
406 /* -------- var.h -------- */
415 #define COPYV 1 /* flag to setval, suggesting copy */
416 #define RONLY 01 /* variable is read-only */
417 #define EXPORT 02 /* variable is to be exported */
418 #define GETCELL 04 /* name & value space was got with getcell */
420 static int yyparse(void);
422 static int execute(struct op *t, int *pin, int *pout, int act);
425 #define AFID_NOBUF (~0)
429 /* -------- io.h -------- */
432 unsigned id; /* buffer id */
433 char buf[512]; /* buffer */
434 char *bufp; /* pointer into buffer */
435 char *ebufp; /* pointer to end of buffer */
438 /* possible arguments to an IO function */
442 int afile; /* file descriptor */
443 unsigned afid; /* buffer id */
444 long afpos; /* file position */
445 struct iobuf *afbuf; /* buffer for this file */
448 /* an input generator's state */
450 int (*iofn) (struct ioarg *, struct io *);
453 char prev; /* previous character read by readc() */
454 char nlcount; /* for `'s */
455 char xchar; /* for `'s */
456 char task; /* reason for pushed IO */
459 #define XOTHER 0 /* none of the below */
460 #define XDOLL 1 /* expanding ${} */
461 #define XGRAVE 2 /* expanding `'s */
462 #define XIO 3 /* file IO */
464 /* in substitution */
465 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
467 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
468 /* moved to G: static struct ioarg ioargstack[NPUSH]; */
469 static struct io iostack[NPUSH];
470 /* moved to G: static struct iobuf sharedbuf = { AFID_NOBUF }; */
471 /* moved to G: static struct iobuf mainbuf = { AFID_NOBUF }; */
472 static unsigned bufid = AFID_ID; /* buffer id counter */
474 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
478 * input generators for IO structure
480 static int nlchar(struct ioarg *ap);
481 static int strchar(struct ioarg *ap);
482 static int qstrchar(struct ioarg *ap);
483 static int filechar(struct ioarg *ap);
484 static int herechar(struct ioarg *ap);
485 static int linechar(struct ioarg *ap);
486 static int gravechar(struct ioarg *ap, struct io *iop);
487 static int qgravechar(struct ioarg *ap, struct io *iop);
488 static int dolchar(struct ioarg *ap);
489 static int wdchar(struct ioarg *ap);
490 static void scraphere(void);
491 static void freehere(int area);
492 static void gethere(void);
493 static void markhere(char *s, struct ioword *iop);
494 static int herein(char *hname, int xdoll);
495 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
498 static int eofc(void);
499 static int readc(void);
500 static void unget(int c);
501 static void ioecho(char c);
507 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
508 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
509 static int remap(int fd);
510 static int openpipe(int *pv);
511 static void closepipe(int *pv);
512 static struct io *setbase(struct io *ip);
514 /* -------- word.h -------- */
516 #define NSTART 16 /* default number of words to allow for initially */
521 /* bounds are arbitrary */
525 static struct wdblock *addword(char *wd, struct wdblock *wb);
526 static struct wdblock *newword(int nw);
527 static char **getwords(struct wdblock *wb);
529 /* -------- misc stuff -------- */
531 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
532 static int iosetup(struct ioword *iop, int pipein, int pipeout);
533 static void brkset(struct brkcon *bc);
534 static int dolabel(struct op *t);
535 static int dohelp(struct op *t);
536 static int dochdir(struct op *t);
537 static int doshift(struct op *t);
538 static int dologin(struct op *t);
539 static int doumask(struct op *t);
540 static int doexec(struct op *t);
541 static int dodot(struct op *t);
542 static int dowait(struct op *t);
543 static int doread(struct op *t);
544 static int doeval(struct op *t);
545 static int dotrap(struct op *t);
546 static int getsig(char *s);
547 static void setsig(int n, sighandler_t f);
548 static int getn(char *as);
549 static int dobreak(struct op *t);
550 static int docontinue(struct op *t);
551 static int brkcontin(char *cp, int val);
552 static int doexit(struct op *t);
553 static int doexport(struct op *t);
554 static int doreadonly(struct op *t);
555 static void rdexp(char **wp, void (*f) (struct var *), int key);
556 static void badid(char *s);
557 static int doset(struct op *t);
558 static void varput(char *s, int out);
559 static int dotimes(struct op *t);
560 static int expand(const char *cp, struct wdblock **wbp, int f);
561 static char *blank(int f);
562 static int dollar(int quoted);
563 static int grave(int quoted);
564 static void globname(char *we, char *pp);
565 static char *generate(char *start1, char *end1, char *middle, char *end);
566 static int anyspcl(struct wdblock *wb);
567 static int xstrcmp(char *p1, char *p2);
568 static void glob0(char *a0, unsigned a1, int a2,
569 int (*a3) (char *, char *));
570 static void readhere(char **name, char *s, int ec);
571 static int xxchar(struct ioarg *ap);
576 struct ioword *h_iop;
580 static const char * const signame[] = {
583 NULL, /* interrupt */
585 "Illegal instruction",
589 "Floating Point Exception",
594 NULL, /* broken pipe */
599 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
605 static const struct res restab[] = {
630 int (*builtinfunc)(struct op *t);
632 static const struct builtincmd builtincmds[] = {
635 { "break" , dobreak },
637 { "continue", docontinue },
641 { "export" , doexport },
643 { "login" , dologin },
644 { "newgrp" , dologin },
646 { "readonly", doreadonly },
648 { "shift" , doshift },
649 { "times" , dotimes },
651 { "umask" , doumask },
656 static struct op *scantree(struct op *);
657 static struct op *dowholefile(int, int);
665 static int interactive; /* Is this an interactive shell */
667 static int multiline; /* \n changed to ; */
668 static struct op *outtree; /* result from parser */
671 static struct brkcon *brklist;
673 static struct wdblock *wdlist;
674 static struct wdblock *iolist;
677 static struct var *mshdbg_var;
679 static struct var *vlist; /* dictionary */
680 static struct var *homedir; /* home directory */
681 static struct var *prompt; /* main prompt */
682 static struct var *cprompt; /* continuation prompt */
683 static struct var *path; /* search path for commands */
684 static struct var *shell; /* shell to interpret command files */
685 static struct var *ifs; /* field separators */
687 static int areanum; /* current allocation area */
688 static int intr; /* interrupt pending */
690 static char *null = (char*)""; /* null value for variable */
691 static int heedint = 1; /* heed interrupt signals */
692 static void (*qflag)(int) = SIG_IGN;
696 static int iounit = IODEFAULT;
697 static YYSTYPE yylval;
698 static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
700 static struct here *inhere; /* list of hear docs while parsing */
701 static struct here *acthere; /* list of active here documents */
702 static struct region *areabot; /* bottom of area */
703 static struct region *areatop; /* top of area */
704 static struct region *areanxt; /* starting point of scan */
706 static void *brkaddr;
709 * parsing & execution environment
715 xint *errpt; /* void * */
720 static struct env e = {
721 NULL /* set to line in main() */, /* linep: char ptr */
722 iostack, /* iobase: struct io ptr */
723 iostack - 1, /* iop: struct io ptr */
724 (xint *) NULL, /* errpt: void ptr for errors? */
725 FDBASE, /* iofd: file desc */
726 (struct env *) NULL /* oenv: struct env ptr */
731 char ourtrap[_NSIG + 1];
732 char *trap[_NSIG + 1];
733 struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
734 struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
735 struct ioarg ioargstack[NPUSH];
736 char filechar_cmdbuf[BUFSIZ];
738 char child_cmd[LINELIM];
741 #define G (*ptr_to_globals)
742 #define ourtrap (G.ourtrap )
743 #define trap (G.trap )
744 #define sharedbuf (G.sharedbuf )
745 #define mainbuf (G.mainbuf )
746 #define ioargstack (G.ioargstack )
747 #define filechar_cmdbuf (G.filechar_cmdbuf)
748 #define line (G.line )
749 #define child_cmd (G.child_cmd )
753 void print_t(struct op *t)
755 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
756 T_CMD_NAMES[t->type], t->words, t->ioact));
759 DBGPRINTF(("T: W1: %s", t->words[0]));
763 void print_tree(struct op *head)
766 DBGPRINTF(("PRINT_TREE: no tree\n"));
770 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
774 print_tree(head->left);
777 print_tree(head->right);
779 #endif /* MSHDEBUG */
785 static void prs(const char *s)
788 write(2, s, strlen(s));
791 static void prn(unsigned u)
796 static void echo(char **wp)
801 for (i = 0; wp[i]; i++) {
809 static void closef(int i)
815 static void closeall(void)
819 for (u = NUFILE; u < NOFILE;)
824 /* fail but return to process next command */
825 static void fail(void) ATTRIBUTE_NORETURN;
826 static void fail(void)
832 /* abort shell (or fail in subshell) */
833 static void leave(void) ATTRIBUTE_NORETURN;
834 static void leave(void)
836 DBGPRINTF(("LEAVE: leave called!\n"));
847 static void warn(const char *s)
858 static void err(const char *s)
868 e.iop = e.iobase = iostack;
872 /* -------- area.c -------- */
875 * All memory between (char *)areabot and (char *)(areatop+1) is
876 * exclusively administered by the area management routines.
877 * It is assumed that sbrk() and brk() manipulate the high end.
881 void * __q = (void *)-1; \
882 if (brkaddr + (int)(X) < brktop) { \
884 brkaddr += (int)(X); \
889 static void initarea(void)
891 brkaddr = xmalloc(AREASIZE);
892 brktop = brkaddr + AREASIZE;
894 while ((long) sbrk(0) & ALIGN)
896 areabot = (struct region *) sbrk(REGSIZE);
898 areabot->next = areabot;
899 areabot->area = BUSY;
904 static char *getcell(unsigned nbytes)
907 struct region *p, *q;
914 /* silly and defeats the algorithm */
916 * round upwards and add administration area
918 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
921 if (p->area > areanum) {
925 while ((q = p->next)->area > areanum && q != areanxt)
928 * exit loop if cell big enough
937 i = nregio >= GROWBY ? nregio : GROWBY;
938 p = (struct region *) sbrk(i * REGSIZE);
939 if (p == (struct region *) -1)
944 abort(); /* allocated areas are contiguous */
954 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
956 areanxt = p + nregio;
959 * split into requested area and rest
961 if (areanxt + 1 > q) {
963 abort(); /* insufficient space left for admin */
966 areanxt->area = FREE;
970 return (char *) (p + 1);
973 static void freecell(char *cp)
977 p = (struct region *) cp;
985 #define DELETE(obj) freecell((char *)obj)
987 static void freearea(int a)
989 struct region *p, *top;
992 for (p = areabot; p != top; p = p->next)
997 static void setarea(char *cp, int a)
1001 p = (struct region *) cp;
1006 static int getarea(char *cp)
1008 return ((struct region *) cp - 1)->area;
1011 static void garbage(void)
1013 struct region *p, *q, *top;
1016 for (p = areabot; p != top; p = p->next) {
1017 if (p->area > areanum) {
1018 while ((q = p->next)->area > areanum)
1024 if (areatop >= q + SHRINKBY && q->area > areanum) {
1025 brk((char *) (q + 1));
1033 static char *space(int n)
1039 err("out of string space");
1043 static char *strsave(const char *s, int a)
1047 cp = space(strlen(s) + 1);
1049 // FIXME: I highly doubt this is good.
1058 /* -------- var.c -------- */
1060 static int eqname(const char *n1, const char *n2)
1062 for (; *n1 != '=' && *n1 != '\0'; n1++)
1065 return *n2 == '\0' || *n2 == '=';
1068 static const char *findeq(const char *cp)
1070 while (*cp != '\0' && *cp != '=')
1076 * Find the given name in the dictionary
1077 * and return its value. If the name was
1078 * not previously there, enter it now and
1079 * return a null value.
1081 static struct var *lookup(const char *n)
1083 // FIXME: dirty hack
1084 static struct var dummy;
1092 dummy.name = (char*)n;
1093 for (c = 0; isdigit(*n) && c < 1000; n++)
1094 c = c * 10 + *n - '0';
1095 dummy.status = RONLY;
1096 dummy.value = (c <= dolc ? dolv[c] : null);
1100 for (vp = vlist; vp; vp = vp->next)
1101 if (eqname(vp->name, n))
1105 vp = (struct var *) space(sizeof(*vp));
1106 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1107 dummy.name = dummy.value = (char*)"";
1112 while ((*xp = *n++) != '\0' && *xp != '=')
1116 setarea((char *) vp, 0);
1117 setarea((char *) vp->name, 0);
1120 vp->status = GETCELL;
1126 * if name is not NULL, it must be
1127 * a prefix of the space `val',
1129 * this is all so that exporting
1130 * values is reasonably painless.
1132 static void nameval(struct var *vp, const char *val, const char *name)
1138 if (vp->status & RONLY) {
1140 while (*xp && *xp != '=')
1141 putc(*xp++, stderr);
1142 err(" is read-only");
1147 xp = space(strlen(vp->name) + strlen(val) + 2);
1150 /* make string: name=value */
1154 while ((*xp = *cp++) != '\0' && *xp != '=')
1161 if (vp->status & GETCELL)
1162 freecell(vp->name); /* form new string `name=value' */
1163 vp->name = (char*)name;
1164 vp->value = (char*)val;
1169 * give variable at `vp' the value `val'.
1171 static void setval(struct var *vp, const char *val)
1173 nameval(vp, val, NULL);
1176 static void export(struct var *vp)
1178 vp->status |= EXPORT;
1181 static void ronly(struct var *vp)
1183 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1184 vp->status |= RONLY;
1187 static int isassign(const char *s)
1190 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1193 /* no isalpha() - we shouldn't use locale */
1194 /* c | 0x20 - lowercase (Latin) letters */
1195 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1206 && (unsigned)(c - '0') > 9 /* not number */
1207 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1214 static int assign(const char *s, int cf)
1219 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1221 if (!isalpha(*s) && *s != '_')
1223 for (cp = s; *cp != '='; cp++)
1224 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1227 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1229 vp->status &= ~GETCELL;
1233 static int checkname(char *cp)
1235 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1237 if (!isalpha(*cp++) && *(cp - 1) != '_')
1240 if (!isalnum(*cp++) && *(cp - 1) != '_')
1245 static void putvlist(int f, int out)
1249 for (vp = vlist; vp; vp = vp->next) {
1250 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1251 if (vp->status & EXPORT)
1252 write(out, "export ", 7);
1253 if (vp->status & RONLY)
1254 write(out, "readonly ", 9);
1255 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1256 write(out, "\n", 1);
1265 static void sig(int i)
1271 static void runtrap(int i)
1276 if (trapstr == NULL)
1282 RUN(aword, trapstr, nlchar);
1286 static void setdash(void)
1290 char m['z' - 'a' + 1];
1293 for (c = 'a'; c <= 'z'; c++)
1297 setval(lookup("-"), m);
1300 static int newfile(char *s)
1304 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1307 if (NOT_LONE_DASH(s)) {
1308 DBGPRINTF(("NEWFILE: s is %s\n", s));
1309 f = open(s, O_RDONLY);
1312 err(": cannot open");
1322 struct op *scantree(struct op *head)
1329 if (head->left != NULL) {
1330 dotnode = scantree(head->left);
1335 if (head->right != NULL) {
1336 dotnode = scantree(head->right);
1341 if (head->words == NULL)
1344 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1346 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1347 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1355 static void onecommand(void)
1360 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1380 setjmp(failpt); /* Bruce Evans' fix */
1382 if (setjmp(failpt) || yyparse() || intr) {
1383 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1388 if (!interactive && intr)
1401 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1403 execute(outtree, NOPIPE, NOPIPE, 0);
1406 if (!interactive && intr) {
1418 static int newenv(int f)
1422 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1429 ep = (struct env *) space(sizeof(*ep));
1442 static void quitenv(void)
1447 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1453 /* should close `'d files */
1455 while (--fd >= e.iofd)
1461 * Is character c in s?
1463 static int any(int c, const char *s)
1472 * Is any character from s1 in s2?
1474 static int anys(const char *s1, const char *s2)
1482 static char *putn(int n)
1487 static void next(int f)
1489 PUSHIO(afile, f, filechar);
1492 static void onintr(int s) /* ANSI C requires a parameter */
1494 signal(SIGINT, onintr);
1501 } else if (heedint) {
1508 /* -------- gmatch.c -------- */
1510 * int gmatch(string, pattern)
1511 * char *string, *pattern;
1513 * Match a pattern as in sh(1).
1518 #define QMASK (CMASK & ~QUOTE)
1519 #define NOT '!' /* might use ^ */
1521 static const char *cclass(const char *p, int sub)
1523 int c, d, not, found;
1533 if (p[1] == '-' && p[2] != ']') {
1538 if (c == sub || (c <= sub && sub <= d))
1540 } while (*++p != ']');
1541 return found ? p + 1 : NULL;
1544 static int gmatch(const char *s, const char *p)
1548 if (s == NULL || p == NULL)
1551 while ((pc = *p++ & CMASK) != '\0') {
1568 if (*p == '\0' || gmatch(s, p))
1570 } while (*s++ != '\0');
1574 if (sc != (pc & ~QUOTE))
1582 /* -------- csyn.c -------- */
1584 * shell: syntax (C version)
1587 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1588 static void yyerror(const char *s)
1591 if (interactive && e.iop <= iostack) {
1593 while (eofc() == 0 && yylex(0) != '\n');
1599 static void zzerr(void) ATTRIBUTE_NORETURN;
1600 static void zzerr(void)
1602 yyerror("syntax error");
1607 DBGPRINTF7(("YYPARSE: enter...\n"));
1614 return (yynerrs != 0);
1617 static struct op *pipeline(int cf)
1622 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1626 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1629 while ((c = yylex(0)) == '|') {
1630 p = command(CONTIN);
1632 DBGPRINTF8(("PIPELINE: error!\n"));
1636 if (t->type != TPAREN && t->type != TCOM) {
1637 /* shell statement */
1638 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1641 t = block(TPIPE, t, p, NOWORDS);
1646 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1650 static struct op *andor(void)
1655 DBGPRINTF7(("ANDOR: enter...\n"));
1659 DBGPRINTF9(("ANDOR: t=%p\n", t));
1662 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1663 p = pipeline(CONTIN);
1665 DBGPRINTF8(("ANDOR: error!\n"));
1669 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1675 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1679 static struct op *c_list(void)
1684 DBGPRINTF7(("C_LIST: enter...\n"));
1691 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1693 while ((c = yylex(0)) == ';' || c == '&'
1694 || (multiline && c == '\n')) {
1702 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1710 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1714 static int synio(int cf)
1720 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1723 if (c != '<' && c != '>') {
1730 iop = io(iounit, i, yylval.cp);
1734 markhere(yylval.cp, iop);
1736 DBGPRINTF7(("SYNIO: returning 1\n"));
1740 static void musthave(int c, int cf)
1742 peeksym = yylex(cf);
1744 DBGPRINTF7(("MUSTHAVE: error!\n"));
1751 static struct op *simple(void)
1757 switch (peeksym = yylex(0)) {
1778 static struct op *nested(int type, int mark)
1782 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1788 return block(type, t, NOBLOCK, NOWORDS);
1791 static struct op *command(int cf)
1794 struct wdblock *iosave;
1797 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1823 t = nested(TPAREN, ')');
1827 t = nested(TBRACE, '}');
1837 t->words = wordlist();
1839 if (c != '\n' && c != ';')
1841 t->left = dogroup(0);
1849 t->type = c == WHILE ? TWHILE : TUNTIL;
1851 t->right = dogroup(1);
1863 musthave(IN, CONTIN);
1866 t->left = caselist();
1877 t->right = thenpart();
1886 musthave(WORD, 0); /* gets name of file */
1887 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1889 word(yylval.cp); /* add word to wdlist */
1890 word(NOWORD); /* terminate wdlist */
1891 t->words = copyw(); /* dup wdlist */
1901 DBGPRINTF(("COMMAND: returning %p\n", t));
1906 static struct op *dowholefile(int type, int mark)
1910 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1915 t = block(type, t, NOBLOCK, NOWORDS);
1916 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1920 static struct op *dogroup(int onlydone)
1926 if (c == DONE && onlydone)
1935 static struct op *thenpart(void)
1948 if (t->left == NULL)
1950 t->right = elsepart();
1954 static struct op *elsepart(void)
1959 switch (c = yylex(0)) {
1970 t->right = thenpart();
1979 static struct op *caselist(void)
1984 while ((peeksym = yylex(CONTIN)) != ESAC) {
1985 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1986 t = list(t, casepart());
1989 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1993 static struct op *casepart(void)
1997 DBGPRINTF7(("CASEPART: enter...\n"));
2001 t->words = pattern();
2004 peeksym = yylex(CONTIN);
2005 if (peeksym != ESAC)
2006 musthave(BREAK, CONTIN);
2008 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2013 static char **pattern(void)
2030 static char **wordlist(void)
2040 while ((c = yylex(0)) == WORD)
2048 * supporting functions
2050 static struct op *list(struct op *t1, struct op *t2)
2052 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2059 return block(TLIST, t1, t2, NOWORDS);
2062 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2066 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2074 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2080 /* See if given string is a shell multiline (FOR, IF, etc) */
2081 static int rlookup(char *n)
2083 const struct res *rp;
2085 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2087 for (rp = restab; rp->r_name; rp++)
2088 if (strcmp(rp->r_name, n) == 0) {
2089 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2090 return rp->r_val; /* Return numeric code for shell multiline */
2093 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2094 return 0; /* Not a shell multiline */
2097 static struct op *newtp(void)
2101 t = (struct op *) tree(sizeof(*t));
2109 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2114 static struct op *namelist(struct op *t)
2116 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2117 T_CMD_NAMES[t->type], iolist));
2120 iolist = addword((char *) NULL, iolist);
2121 t->ioact = copyio();
2125 if (t->type != TCOM) {
2126 if (t->type != TPAREN && t->ioact != NULL) {
2127 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2128 t->ioact = t->left->ioact;
2129 t->left->ioact = NULL;
2140 static char **copyw(void)
2144 wd = getwords(wdlist);
2149 static void word(char *cp)
2151 wdlist = addword(cp, wdlist);
2154 static struct ioword **copyio(void)
2156 struct ioword **iop;
2158 iop = (struct ioword **) getwords(iolist);
2163 static struct ioword *io(int u, int f, char *cp)
2167 iop = (struct ioword *) tree(sizeof(*iop));
2171 iolist = addword((char *) iop, iolist);
2175 static int yylex(int cf)
2195 line[LINELIM - 1] = '\0';
2198 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2203 if (any(c, "0123456789")) {
2206 if (c1 == '<' || c1 == '>') {
2215 case '#': /* Comment, skip to next newline or End-of-string */
2216 while ((c = my_getc(0)) != '\0' && c != '\n');
2221 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2225 DBGPRINTF9(("YYLEX: found $\n"));
2229 c = collect(c, '}');
2248 /* If more chars process them, else return NULL char */
2266 if (multiline || cf & CONTIN) {
2267 if (interactive && e.iop <= iostack) {
2268 #if ENABLE_FEATURE_EDITING
2269 current_prompt = cprompt->value;
2271 prs(cprompt->value);
2288 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2289 if (e.linep >= elinep)
2290 err("word too long");
2297 if (any(c, "\"'`$"))
2310 yylval.cp = strsave(line, areanum);
2315 static int collect(int c, int c1)
2319 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2322 while ((c = my_getc(c1)) != c1) {
2331 if (interactive && c == '\n' && e.iop <= iostack) {
2332 #if ENABLE_FEATURE_EDITING
2333 current_prompt = cprompt->value;
2335 prs(cprompt->value);
2343 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2348 /* "multiline commands" helper func */
2349 /* see if next 2 chars form a shell multiline */
2350 static int dual(int c)
2355 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2357 *cp++ = c; /* c is the given "peek" char */
2358 *cp++ = my_getc(0); /* get next char of input */
2359 *cp = '\0'; /* add EOS marker */
2361 c = rlookup(s); /* see if 2 chars form a shell multiline */
2363 unget(*--cp); /* String is not a shell multiline, put peek char back */
2365 return c; /* String is multiline, return numeric multiline (restab) code */
2368 static void diag(int ec)
2372 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2375 if (c == '>' || c == '<') {
2378 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2381 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2382 if (c != '&' || yylval.i == IOHERE)
2388 static char *tree(unsigned size)
2394 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2395 prs("command line too complicated\n");
2406 /* -------- exec.c -------- */
2408 static struct op **find1case(struct op *t, const char *w)
2416 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2420 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2421 T_CMD_NAMES[t->type]));
2423 if (t->type == TLIST) {
2424 tp = find1case(t->left, w);
2426 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2429 t1 = t->right; /* TPAT */
2433 for (wp = t1->words; *wp;) {
2434 cp = evalstr(*wp++, DOSUB);
2435 if (cp && gmatch(w, cp)) {
2436 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2442 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2446 static struct op *findcase(struct op *t, const char *w)
2450 tp = find1case(t, w);
2451 return tp != NULL ? *tp : NULL;
2458 static int execute(struct op *t, int *pin, int *pout, int act)
2461 volatile int i, rv, a;
2465 struct op *outtree_save;
2469 /* Avoid longjmp clobbering */
2474 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2478 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2479 t->type, T_CMD_NAMES[t->type],
2480 ((t->words == NULL) ? "NULL" : t->words[0])));
2484 wp = (wp2 = t->words) != NULL
2485 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2490 DBGPRINTF3(("EXECUTE: TDOT\n"));
2492 outtree_save = outtree;
2494 newfile(evalstr(t->words[0], DOALL));
2496 t->left = dowholefile(TLIST, 0);
2499 outtree = outtree_save;
2502 rv = execute(t->left, pin, pout, 0);
2504 rv = execute(t->right, pin, pout, 0);
2508 rv = execute(t->left, pin, pout, 0);
2512 rv = forkexec(t, pin, pout, act, wp);
2522 pv[0] = remap(pv[0]);
2523 pv[1] = remap(pv[1]);
2524 (void) execute(t->left, pin, pv, 0);
2525 rv = execute(t->right, pv, pout, 0);
2530 (void) execute(t->left, pin, pout, 0);
2531 rv = execute(t->right, pin, pout, 0);
2536 int hinteractive = interactive;
2538 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2541 if (i == 0) { /* child */
2542 signal(SIGINT, SIG_IGN);
2543 signal(SIGQUIT, SIG_IGN);
2545 signal(SIGTERM, SIG_DFL);
2549 xopen(bb_dev_null, O_RDONLY);
2551 _exit(execute(t->left, pin, pout, FEXEC));
2553 interactive = hinteractive;
2555 setval(lookup("!"), putn(i));
2570 rv = execute(t->left, pin, pout, 0);
2572 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2573 rv = execute(t1, pin, pout, 0);
2584 while (*wp++ != NULL);
2586 vp = lookup(t->str);
2587 while (setjmp(bc.brkpt))
2591 for (t1 = t->left; i-- && *wp != NULL;) {
2593 rv = execute(t1, pin, pout, 0);
2595 brklist = brklist->nextlev;
2600 while (setjmp(bc.brkpt))
2605 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2606 rv = execute(t->right, pin, pout, 0);
2607 brklist = brklist->nextlev;
2612 if (t->right != NULL) {
2613 rv = !execute(t->left, pin, pout, 0) ?
2614 execute(t->right->left, pin, pout, 0) :
2615 execute(t->right->right, pin, pout, 0);
2620 cp = evalstr(t->str, DOSUB | DOTRIM);
2624 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2625 ((t->str == NULL) ? "NULL" : t->str),
2626 ((cp == NULL) ? "NULL" : cp)));
2628 t1 = findcase(t->left, cp);
2630 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2631 rv = execute(t1, pin, pout, 0);
2632 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2641 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2649 rv = execute(t1, pin, pout, 0);
2662 if (interactive && intr) {
2673 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2677 typedef int (*builtin_func_ptr)(struct op *);
2679 static builtin_func_ptr inbuilt(const char *s)
2681 const struct builtincmd *bp;
2683 for (bp = builtincmds; bp->name; bp++)
2684 if (strcmp(bp->name, s) == 0)
2685 return bp->builtinfunc;
2689 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2693 builtin_func_ptr shcom = NULL;
2695 const char *cp = NULL;
2696 struct ioword **iopp;
2706 struct brkcon *hbrklist;
2710 /* Avoid longjmp clobbering */
2720 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2722 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2723 ((t->words == NULL) ? "NULL" : t->words[0])));
2727 rv = -1; /* system-detected error */
2728 if (t->type == TCOM) {
2729 while (*wp++ != NULL)
2733 /* strip all initial assignments */
2734 /* not correct wrt PATH=yyy command etc */
2736 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2738 echo(cp ? wp : owp);
2741 if (cp == NULL && t->ioact == NULL) {
2742 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2744 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2745 return setstatus(0);
2748 shcom = inbuilt(cp);
2755 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2758 if (shcom == NULL && (f & FEXEC) == 0) {
2759 /* Save values in case the child process alters them */
2763 hinteractive = interactive;
2768 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2773 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2777 if (newpid > 0) { /* Parent */
2778 /* Restore values */
2782 interactive = hinteractive;
2793 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2796 /* Must be the child process, pid should be 0 */
2797 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2800 signal(SIGINT, SIG_IGN);
2801 signal(SIGQUIT, SIG_IGN);
2812 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2817 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2818 err("piping to/from shell builtins not yet done");
2826 xmove_fd(pin[0], 0);
2827 if (pin[1] != 0) close(pin[1]);
2830 xmove_fd(pout[1], 1);
2831 if (pout[1] != 1) close(pout[0]);
2836 if (shcom != NULL && shcom != doexec) {
2838 err(": cannot redirect shell command");
2844 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2852 i = setstatus((*shcom) (t));
2855 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2859 /* should use FIOCEXCL */
2860 for (i = FDBASE; i < NOFILE; i++)
2863 signal(SIGINT, SIG_DFL);
2864 signal(SIGQUIT, SIG_DFL);
2867 if (t->type == TPAREN)
2868 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2872 cp = rexecve(wp[0], wp, makenv(0, NULL));
2879 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2887 * 0< 1> are ignored as required
2890 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2896 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2899 if (iop->io_unit == IODEFAULT) /* take default */
2900 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2902 if (pipein && iop->io_unit == 0)
2905 if (pipeout && iop->io_unit == 1)
2908 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2909 if ((iop->io_flag & IOHERE) == 0) {
2910 cp = iop->io_name; /* huh?? */
2911 cp = evalstr(cp, DOSUB | DOTRIM);
2916 if (iop->io_flag & IODUP) {
2917 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2919 err(": illegal >& argument");
2923 iop->io_flag = IOCLOSE;
2924 iop->io_flag &= ~(IOREAD | IOWRITE);
2926 switch (iop->io_flag) {
2928 u = open(cp, O_RDONLY);
2932 case IOHERE | IOXHERE:
2933 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2934 cp = (char*)"here file";
2937 case IOWRITE | IOCAT:
2938 u = open(cp, O_WRONLY);
2940 lseek(u, (long) 0, SEEK_END);
2944 u = creat(cp, 0666);
2948 u = dup2(*cp - '0', iop->io_unit);
2952 close(iop->io_unit);
2961 if (u != iop->io_unit) {
2962 dup2(u, iop->io_unit);
2969 * Enter a new loop level (marked for break/continue).
2971 static void brkset(struct brkcon *bc)
2973 bc->nextlev = brklist;
2978 * Wait for the last process created.
2979 * Print a message for each process found
2980 * that was killed by a signal.
2981 * Ignore interrupt signals while waiting
2982 * unless `canintr' is true.
2984 static int waitfor(int lastpid, int canintr)
2988 int oheedint = heedint;
2995 if (errno != EINTR || canintr)
3001 if (signame[rv] != NULL) {
3002 if (pid != lastpid) {
3009 if (pid != lastpid) {
3018 prs(" - core dumped");
3019 if (rv >= NSIGNAL || signame[rv])
3025 } while (pid != lastpid);
3040 static int setstatus(int s)
3043 setval(lookup("?"), putn(s));
3048 * PATH-searching interface to execve.
3049 * If getenv("PATH") were kept up-to-date,
3050 * execvp might be used.
3052 static const char *rexecve(char *c, char **v, char **envp)
3057 int eacces = 0, asis = 0;
3060 if (ENABLE_FEATURE_SH_STANDALONE) {
3061 if (find_applet_by_name(name)) {
3062 /* We have to exec here since we vforked. Running
3063 * run_applet_and_exit() won't work and bad things
3065 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3069 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3071 sp = any('/', c) ? "" : path->value;
3072 asis = (*sp == '\0');
3073 while (asis || *sp != '\0') {
3076 for (; *sp != '\0'; tp++) {
3079 asis = (*sp == '\0');
3085 for (i = 0; (*tp++ = c[i++]) != '\0';);
3087 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3089 execve(e.linep, v, envp);
3096 execve(DEFAULT_SHELL, v, envp);
3101 return (char *) bb_msg_memory_exhausted;
3104 return "argument list too long";
3111 return errno == ENOENT ? "not found" : "cannot execute";
3115 * Run the command produced by generator `f'
3116 * applied to stream `arg'.
3118 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3121 struct wdblock *swdlist;
3122 struct wdblock *siolist;
3128 /* Avoid longjmp clobbering */
3132 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3133 areanum, outtree, failpt));
3143 if (newenv(setjmp(errpt)) == 0) {
3150 if (setjmp(failpt) == 0 && yyparse() == 0)
3151 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3154 DBGPRINTF(("RUN: error from newenv()!\n"));
3161 freearea(areanum--);
3166 /* -------- do.c -------- */
3169 * built-in commands: doX
3172 static int dohelp(struct op *t)
3175 const struct builtincmd *x;
3177 puts("\nBuilt-in commands:\n"
3178 "-------------------");
3183 col += printf("%c%s", ((col == 0) ? '\t' : ' '), x->name);
3190 #if ENABLE_FEATURE_SH_STANDALONE
3192 const struct bb_applet *applet = applets;
3194 while (applet->name) {
3195 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applet->name);
3205 return EXIT_SUCCESS;
3208 static int dolabel(struct op *t)
3213 static int dochdir(struct op *t)
3215 const char *cp, *er;
3219 cp = homedir->value;
3222 er = ": no home directory";
3227 er = ": bad directory";
3229 prs(cp != NULL ? cp : "cd");
3234 static int doshift(struct op *t)
3238 n = t->words[1] ? getn(t->words[1]) : 1;
3240 err("nothing to shift");
3246 setval(lookup("#"), putn(dolc));
3251 * execute login and newgrp directly
3253 static int dologin(struct op *t)
3258 signal(SIGINT, SIG_DFL);
3259 signal(SIGQUIT, SIG_DFL);
3261 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3268 static int doumask(struct op *t)
3277 for (n = 3 * 4; (n -= 3) >= 0;)
3278 putc('0' + ((i >> n) & 07), stderr);
3281 /* huh??? '8','9' are not allowed! */
3282 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3283 n = n * 8 + (*cp - '0');
3289 static int doexec(struct op *t)
3296 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3302 if (setjmp(failpt) == 0)
3303 execute(t, NOPIPE, NOPIPE, FEXEC);
3309 static int dodot(struct op *t)
3317 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)));
3321 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3324 DBGPRINTF(("DODOT: cp is %s\n", cp));
3326 sp = any('/', cp) ? ":" : path->value;
3328 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3329 ((sp == NULL) ? "NULL" : sp),
3330 ((e.linep == NULL) ? "NULL" : e.linep)));
3334 while (*sp && (*tp = *sp++) != ':')
3339 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3342 i = open(e.linep, O_RDONLY);
3346 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3348 next(maltmp); /* Basically a PUSHIO */
3350 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3362 static int dowait(struct op *t)
3374 setstatus(waitfor(i, 1));
3378 static int doread(struct op *t)
3384 if (t->words[1] == NULL) {
3385 err("Usage: read name ...");
3388 for (wp = t->words + 1; *wp; wp++) {
3389 for (cp = e.linep; !nl && cp < elinep - 1; cp++) {
3390 nb = read(0, cp, sizeof(*cp));
3391 if (nb != sizeof(*cp))
3394 if (nl || (wp[1] && any(*cp, ifs->value)))
3400 setval(lookup(*wp), e.linep);
3405 static int doeval(struct op *t)
3407 return RUN(awordlist, t->words + 1, wdchar);
3410 static int dotrap(struct op *t)
3415 if (t->words[1] == NULL) {
3416 for (i = 0; i <= _NSIG; i++)
3425 resetsig = isdigit(*t->words[1]);
3426 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3427 n = getsig(t->words[i]);
3431 if (*t->words[1] != '\0') {
3432 trap[n] = strsave(t->words[1], 0);
3441 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3449 static int getsig(char *s)
3454 if (n < 0 || n > _NSIG) {
3455 err("trap: bad signal number");
3461 static void setsig(int n, sighandler_t f)
3465 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3471 static int getn(char *as)
3482 for (n = 0; isdigit(*s); s++)
3483 n = (n * 10) + (*s - '0');
3486 err(": bad number");
3491 static int dobreak(struct op *t)
3493 return brkcontin(t->words[1], 1);
3496 static int docontinue(struct op *t)
3498 return brkcontin(t->words[1], 0);
3501 static int brkcontin(char *cp, int val)
3506 nl = cp == NULL ? 1 : getn(cp);
3513 brklist = bc->nextlev;
3516 err("bad break/continue level");
3520 longjmp(bc->brkpt, 1);
3524 static int doexit(struct op *t)
3531 setstatus(getn(cp));
3533 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3540 static int doexport(struct op *t)
3542 rdexp(t->words + 1, export, EXPORT);
3546 static int doreadonly(struct op *t)
3548 rdexp(t->words + 1, ronly, RONLY);
3552 static void rdexp(char **wp, void (*f) (struct var *), int key)
3554 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3555 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3558 for (; *wp != NULL; wp++) {
3559 if (isassign(*wp)) {
3563 for (cp = *wp; *cp != '='; cp++);
3575 static void badid(char *s)
3578 err(": bad identifier");
3581 static int doset(struct op *t)
3589 for (vp = vlist; vp; vp = vp->next)
3590 varput(vp->name, 1);
3594 /* bad: t->words++; */
3595 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3597 FLAG['x'] = FLAG['v'] = 0;
3607 if (*cp >= 'a' && *cp <= 'z')
3616 t->words[0] = dolv[0];
3617 for (n = 1; t->words[n]; n++)
3618 setarea((char *) t->words[n], 0);
3621 setval(lookup("#"), putn(dolc));
3622 setarea((char *) (dolv - 1), 0);
3627 static void varput(char *s, int out)
3629 if (isalnum(*s) || *s == '_') {
3630 write(out, s, strlen(s));
3631 write(out, "\n", 1);
3637 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3638 * This file contains code for the times builtin.
3640 static int dotimes(struct op *t)
3643 long clk_tck = sysconf(_SC_CLK_TCK);
3646 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3647 (int) (buf.tms_utime / clk_tck / 60),
3648 ((double) buf.tms_utime) / clk_tck,
3649 (int) (buf.tms_stime / clk_tck / 60),
3650 ((double) buf.tms_stime) / clk_tck,
3651 (int) (buf.tms_cutime / clk_tck / 60),
3652 ((double) buf.tms_cutime) / clk_tck,
3653 (int) (buf.tms_cstime / clk_tck / 60),
3654 ((double) buf.tms_cstime) / clk_tck);
3659 /* -------- eval.c -------- */
3664 * blank interpretation
3669 static char **eval(char **ap, int f)
3677 /* Avoid longjmp clobbering */
3682 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3688 if (newenv(setjmp(errpt)) == 0) {
3689 while (*ap && isassign(*ap))
3690 expand(*ap++, &wb, f & ~DOGLOB);
3692 for (wf = ap; *wf; wf++) {
3694 expand(*wf, &wb, f & ~DOGLOB);
3697 for (wb = addword((char *) 0, wb); *ap; ap++) {
3698 if (!FLAG['k'] || !isassign(*ap))
3699 expand(*ap, &wb, f & ~DOKEY);
3701 wb = addword((char *) 0, wb);
3707 return gflg ? (char **) NULL : wp;
3712 * Make the exported environment from the exported
3713 * names in the dictionary. Keyword assignments
3714 * will already have been done.
3716 static char **makenv(int all, struct wdblock *wb)
3720 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3722 for (vp = vlist; vp; vp = vp->next)
3723 if (all || vp->status & EXPORT)
3724 wb = addword(vp->name, wb);
3725 wb = addword((char *) 0, wb);
3726 return getwords(wb);
3729 static int expand(const char *cp, struct wdblock **wbp, int f)
3735 /* Avoid longjmp clobbering */
3739 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3746 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3747 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3749 xp = strsave(cp, areanum);
3752 *wbp = addword(xp, *wbp);
3756 if (newenv(setjmp(errpt)) == 0) {
3757 PUSHIO(aword, cp, strchar);
3759 while ((xp = blank(f)) && gflg == 0) {
3761 xp = strsave(xp, areanum);
3762 if ((f & DOGLOB) == 0) {
3765 *wbp = addword(xp, *wbp);
3767 *wbp = glob(xp, *wbp);
3775 static char *evalstr(char *cp, int f)
3779 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3782 if (expand(cp, &wb, f)) {
3783 if (wb == NULL || wb->w_nword == 0
3784 || (cp = wb->w_words[0]) == NULL
3786 // TODO: I suspect that
3787 // char *evalstr(char *cp, int f) is actually
3788 // const char *evalstr(const char *cp, int f)!
3799 * Blank interpretation and quoting
3801 static char *blank(int f)
3805 int scanequals, foundequals;
3807 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3810 scanequals = f & DOKEY;
3814 c = subgetc('"', foundequals);
3823 if (f & DOBLANK && any(c, ifs->value))
3832 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3835 if (c == '\'' || !any(c, "$`\""))
3842 if (!isalpha(c) && c != '_')
3845 c = subgetc('"', foundequals);
3847 f & (DOBLANK && any(c, ifs->value)) ||
3848 (!INSUB() && any(c, "\"'"))) {
3859 } else if (!isalnum(c) && c != '_')
3869 * Get characters, substituting for ` and $
3871 static int subgetc(char ec, int quoted)
3875 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3879 if (!INSUB() && ec != '\'') {
3881 if (grave(quoted) == 0)
3883 e.iop->task = XGRAVE;
3889 e.iop->task = XDOLL;
3898 * Prepare to generate the string returned by ${} substitution.
3900 static int dollar(int quoted)
3905 char *s, c, *cp = NULL;
3908 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3914 if (isalpha(c) || c == '_') {
3915 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3916 if (e.linep < elinep)
3923 otask = e.iop->task;
3925 e.iop->task = XOTHER;
3926 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3927 if (e.linep < elinep)
3930 e.iop->task = otask;
3937 if (e.linep >= elinep) {
3938 err("string in ${} too long");
3944 for (cp = s + 1; *cp; cp++)
3945 if (any(*cp, "=-+?")) {
3950 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3952 /* currently this does not distinguish $* and $@ */
3953 /* should check dollar */
3955 PUSHIO(awordlist, dolv + 1, dolchar);
3957 } else { /* trap the nasty ${=} */
3968 err("cannot use ${...=...} with $n");
3977 dolp = strsave(cp, areanum);
3982 prs("missing value for ");
3989 } else if (c == '+')
3990 dolp = strsave(cp, areanum);
3991 if (FLAG['u'] && dolp == null) {
3992 prs("unset variable: ");
3997 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4002 * Run the command in `...` and read its output.
4005 static int grave(int quoted)
4007 /* moved to G: static char child_cmd[LINELIM]; */
4018 char *argument_list[4];
4019 struct wdblock *wb = NULL;
4022 /* Avoid longjmp clobbering */
4026 for (cp = e.iop->argp->aword; *cp != '`'; cp++) {
4028 err("no closing `");
4033 /* string copy with dollar expansion */
4034 src = e.iop->argp->aword;
4039 while ((*src != '`') && (count < LINELIM)) {
4044 if (*src == '$' && !ignore && !ignore_once) {
4046 char var_name[LINELIM];
4047 char alt_value[LINELIM];
4060 var_name[var_index++] = *src++;
4061 while (isalnum(*src) || *src=='_')
4062 var_name[var_index++] = *src++;
4063 var_name[var_index] = 0;
4076 err("unclosed ${\n");
4081 while (*src && (*src != '}')) {
4082 alt_value[alt_index++] = *src++;
4084 alt_value[alt_index] = 0;
4086 err("unclosed ${\n");
4093 if (isalpha(*var_name)) {
4094 /* let subshell handle it instead */
4096 char *namep = var_name;
4104 char *altp = alt_value;
4112 wb = addword(lookup(var_name)->name, wb);
4116 vp = lookup(var_name);
4117 if (vp->value != null)
4118 value = (operator == '+') ?
4119 alt_value : vp->value;
4120 else if (operator == '?') {
4123 } else if (alt_index && (operator != '+')) {
4125 if (operator == '=')
4130 while (*value && (count < LINELIM)) {
4143 if (openpipe(pf) < 0)
4146 while ((i = vfork()) == -1 && errno == EAGAIN);
4148 DBGPRINTF3(("GRAVE: i is %p\n", io));
4152 err((char *) bb_msg_memory_exhausted);
4156 waitpid(i, NULL, 0);
4157 e.iop->argp->aword = ++cp;
4159 PUSHIO(afile, remap(pf[0]),
4160 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4163 /* allow trapped signals */
4164 /* XXX - Maybe this signal stuff should go as well? */
4165 for (j = 0; j <= _NSIG; j++)
4166 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4169 /* Testcase where below checks are needed:
4170 * close stdout & run this script:
4175 if (pf[0] != 1) close(pf[0]);
4177 argument_list[0] = (char *) DEFAULT_SHELL;
4178 argument_list[1] = (char *) "-c";
4179 argument_list[2] = child_cmd;
4180 argument_list[3] = NULL;
4182 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4183 prs(argument_list[0]);
4190 static char *unquote(char *as)
4201 /* -------- glob.c -------- */
4207 #define scopy(x) strsave((x), areanum)
4209 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4211 static struct wdblock *cl, *nl;
4212 static char spcl[] = "[?*";
4214 static struct wdblock *glob(char *cp, struct wdblock *wb)
4222 for (pp = cp; *pp; pp++)
4225 else if (!any(*pp & ~QUOTE, spcl))
4228 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4229 nl = newword(cl->w_nword * 2);
4230 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4231 for (pp = cl->w_words[i]; *pp; pp++)
4232 if (any(*pp, spcl)) {
4233 globname(cl->w_words[i], pp);
4237 nl = addword(scopy(cl->w_words[i]), nl);
4239 for (i = 0; i < cl->w_nword; i++)
4240 DELETE(cl->w_words[i]);
4243 for (i = 0; i < cl->w_nword; i++)
4244 unquote(cl->w_words[i]);
4245 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4247 for (i = 0; i < cl->w_nword; i++)
4248 wb = addword(cl->w_words[i], wb);
4253 wb = addword(unquote(cp), wb);
4257 static void globname(char *we, char *pp)
4260 char *name, *gp, *dp;
4264 char dname[NAME_MAX + 1];
4267 for (np = we; np != pp; pp--)
4270 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4274 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4283 dname[NAME_MAX] = '\0';
4284 while ((de = readdir(dirp)) != NULL) {
4285 /* XXX Hmmm... What this could be? (abial) */
4287 if (ent[j].d_ino == 0)
4290 strncpy(dname, de->d_name, NAME_MAX);
4291 if (dname[0] == '.')
4294 for (k = 0; k < NAME_MAX; k++)
4295 if (any(dname[k], spcl))
4297 if (gmatch(dname, gp)) {
4298 name = generate(we, pp, dname, np);
4299 if (*np && !anys(np, spcl)) {
4300 if (stat(name, &dbuf)) {
4305 nl = addword(name, nl);
4314 * generate a pathname as below.
4315 * start..end1 / middle end
4316 * the slashes come for free
4318 static char *generate(char *start1, char *end1, char *middle, char *end)
4323 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4324 for (xp = start1; xp != end1;)
4326 for (xp = middle; (*op++ = *xp++) != '\0';);
4328 for (xp = end; (*op++ = *xp++) != '\0';);
4332 static int anyspcl(struct wdblock *wb)
4338 for (i = 0; i < wb->w_nword; i++)
4339 if (anys(spcl, *wd++))
4344 static int xstrcmp(char *p1, char *p2)
4346 return strcmp(*(char **) p1, *(char **) p2);
4350 /* -------- word.c -------- */
4352 static struct wdblock *newword(int nw)
4356 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4362 static struct wdblock *addword(char *wd, struct wdblock *wb)
4364 struct wdblock *wb2;
4368 wb = newword(NSTART);
4370 if (nw >= wb->w_bsize) {
4371 wb2 = newword(nw * 2);
4372 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4373 nw * sizeof(char *));
4378 wb->w_words[wb->w_nword++] = wd;
4382 static char **getwords(struct wdblock *wb)
4389 if (wb->w_nword == 0) {
4393 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4394 memcpy((char *) wd, (char *) wb->w_words, nb);
4395 DELETE(wb); /* perhaps should done by caller */
4399 static int (*func) (char *, char *);
4402 static void glob3(char *i, char *j, char *k)
4404 char *index1, *index2, *index3;
4414 *index1++ = *index3;
4415 *index3++ = *index2;
4420 static void glob2(char *i, char *j)
4422 char *index1, *index2, c;
4430 *index1++ = *index2;
4435 static void glob1(char *base, char *lim)
4446 n = (int) (lim - base);
4449 n = v2 * (n / (2 * v2));
4450 hptr = lptr = base + n;
4455 c = (*func) (i, lptr);
4469 c = (*func) (hptr, j);
4493 if (lptr - base >= lim - hptr) {
4494 glob1(hptr + v2, lim);
4509 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4513 glob1(a0, a0 + a1 * a2);
4517 /* -------- io.c -------- */
4523 static int my_getc(int ec)
4527 if (e.linep > elinep) {
4528 while ((c = readc()) != '\n' && c);
4529 err("input line too long");
4534 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4537 if (c == '\n' && ec != '\"')
4545 static void unget(int c)
4547 if (e.iop >= e.iobase)
4551 static int eofc(void)
4553 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4556 static int readc(void)
4560 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4562 for (; e.iop >= e.iobase; e.iop--) {
4563 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4569 if (e.iop->prev != 0) {
4570 c = (*e.iop->iofn)(e.iop->argp, e.iop);
4576 if (e.iop == iostack)
4581 if (e.iop->task == XIO && e.iop->prev != '\n') {
4583 if (e.iop == iostack)
4588 if (e.iop->task == XIO) {
4593 if (interactive && e.iop == iostack + 1) {
4594 #if ENABLE_FEATURE_EDITING
4595 current_prompt = prompt->value;
4603 if (e.iop >= iostack) {
4604 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4608 DBGPRINTF(("READC: leave()...\n"));
4615 static void ioecho(char c)
4618 write(2, &c, sizeof c);
4622 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4624 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4625 argp->afid, e.iop));
4627 /* Set env ptr for io source to next array spot and check for array overflow */
4628 if (++e.iop >= &iostack[NPUSH]) {
4630 err("Shell input nested too deeply");
4635 /* We did not overflow the NPUSH array spots so setup data structs */
4637 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4639 if (argp->afid != AFID_NOBUF)
4643 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4644 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4646 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4648 if (e.iop == &iostack[0])
4649 e.iop->argp->afbuf = &mainbuf;
4651 e.iop->argp->afbuf = &sharedbuf;
4653 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4654 /* This line appears to be active when running scripts from command line */
4655 if ((isatty(e.iop->argp->afile) == 0)
4656 && (e.iop == &iostack[0]
4657 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4658 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4659 bufid = AFID_ID; /* AFID_ID = 0 */
4661 e.iop->argp->afid = bufid; /* assign buffer id */
4664 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4665 iostack, e.iop, e.iop->argp->afbuf));
4666 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4667 &mainbuf, &sharedbuf, bufid, e.iop));
4671 e.iop->prev = ~'\n';
4676 if (fn == filechar || fn == linechar)
4678 else if (fn == (int (*)(struct ioarg *)) gravechar
4679 || fn == (int (*)(struct ioarg *)) qgravechar)
4680 e.iop->task = XGRAVE;
4682 e.iop->task = XOTHER;
4685 static struct io *setbase(struct io *ip)
4695 * Input generating functions
4699 * Produce the characters of a string, then a newline, then EOF.
4701 static int nlchar(struct ioarg *ap)
4705 if (ap->aword == NULL)
4716 * Given a list of words, produce the characters
4717 * in them, with a space after each word.
4719 static int wdchar(struct ioarg *ap)
4734 ap->awordlist = NULL;
4739 * Return the characters of a list of words,
4740 * producing a space between them.
4742 static int dolchar(struct ioarg *ap)
4746 wp = *ap->awordlist++;
4748 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4754 static int xxchar(struct ioarg *ap)
4758 if (ap->aword == NULL)
4769 * Produce the characters from a single word (string).
4771 static int strchar(struct ioarg *ap)
4773 if (ap->aword == NULL)
4775 return *ap->aword++;
4779 * Produce quoted characters from a single word (string).
4781 static int qstrchar(struct ioarg *ap)
4785 if (ap->aword == NULL)
4794 * Return the characters from a file.
4796 static int filechar(struct ioarg *ap)
4800 struct iobuf *bp = ap->afbuf;
4802 if (ap->afid != AFID_NOBUF) {
4803 i = (ap->afid != bp->id);
4804 if (i || bp->bufp == bp->ebufp) {
4806 lseek(ap->afile, ap->afpos, SEEK_SET);
4808 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4816 bp->ebufp = bp->bufp + i;
4820 return *bp->bufp++ & 0177;
4822 #if ENABLE_FEATURE_EDITING
4823 if (interactive && isatty(ap->afile)) {
4824 /* moved to G: static char filechar_cmdbuf[BUFSIZ]; */
4825 static int position = 0, size = 0;
4827 while (size == 0 || position >= size) {
4828 read_line_input(current_prompt, filechar_cmdbuf, BUFSIZ, line_input_state);
4829 size = strlen(filechar_cmdbuf);
4832 c = filechar_cmdbuf[position];
4837 i = safe_read(ap->afile, &c, sizeof(c));
4838 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4842 * Return the characters from a here temp file.
4844 static int herechar(struct ioarg *ap)
4848 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4856 * Return the characters produced by a process (`...`).
4857 * Quote them if required, and remove any trailing newline characters.
4859 static int gravechar(struct ioarg *ap, struct io *iop)
4863 c = qgravechar(ap, iop) & ~QUOTE;
4869 static int qgravechar(struct ioarg *ap, struct io *iop)
4873 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4878 return '\n' | QUOTE;
4882 } else if ((c = filechar(ap)) == '\n') {
4884 while ((c = filechar(ap)) == '\n')
4892 return c != 0 ? c | QUOTE : 0;
4896 * Return a single command (usually the first line) from a file.
4898 static int linechar(struct ioarg *ap)
4906 ap->afile = -1; /* illegal value */
4913 * remap fd into Shell's fd space
4915 static int remap(int fd)
4921 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
4924 for (i = 0; i < NOFILE; i++)
4931 } while (fd >= 0 && fd < e.iofd);
4933 for (i = 0; i < NOFILE; i++)
4938 err("too many files open in shell");
4944 static int openpipe(int *pv)
4950 err("can't create pipe - try again");
4954 static void closepipe(int *pv)
4963 /* -------- here.c -------- */
4969 static void markhere(char *s, struct ioword *iop)
4971 struct here *h, *lh;
4973 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4975 h = (struct here *) space(sizeof(struct here));
4979 h->h_tag = evalstr(s, DOSUB);
4989 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4990 if (lh->h_next == 0) {
4996 iop->io_flag |= IOHERE | IOXHERE;
4997 for (s = h->h_tag; *s; s++) {
4999 iop->io_flag &= ~IOXHERE;
5003 h->h_dosub = iop->io_flag & IOXHERE;
5006 static void gethere(void)
5008 struct here *h, *hp;
5010 DBGPRINTF7(("GETHERE: enter...\n"));
5012 /* Scan here files first leaving inhere list in place */
5013 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5014 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5016 /* Make inhere list active - keep list intact for scraphere */
5018 hp->h_next = acthere;
5024 static void readhere(char **name, char *s, int ec)
5027 char tname[30] = ".msh_XXXXXX";
5030 char myline[LINELIM + 1];
5033 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5035 tf = mkstemp(tname);
5039 *name = strsave(tname, areanum);
5041 if (newenv(setjmp(errpt)) != 0)
5044 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5047 if (interactive && e.iop <= iostack) {
5048 #if ENABLE_FEATURE_EDITING
5049 current_prompt = cprompt->value;
5051 prs(cprompt->value);
5055 while ((c = my_getc(ec)) != '\n' && c) {
5058 if (thenext >= &myline[LINELIM]) {
5065 if (strcmp(s, myline) == 0 || c == 0)
5068 write(tf, myline, (int) (thenext - myline));
5071 prs("here document `");
5081 * open here temp file.
5082 * if unquoted here, expand here temp file into second temp file.
5084 static int herein(char *hname, int xdoll)
5090 /* Avoid longjmp clobbering */
5096 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5098 hf = open(hname, O_RDONLY);
5104 char tname[30] = ".msh_XXXXXX";
5107 tf = mkstemp(tname);
5111 if (newenv(setjmp(errpt)) == 0) {
5112 PUSHIO(afile, hf, herechar);
5114 while ((c = subgetc(0, 0)) != 0) {
5116 write(tf, &c, sizeof c);
5122 tf = open(tname, O_RDONLY);
5129 static void scraphere(void)
5133 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5135 for (h = inhere; h != NULL; h = h->h_next) {
5136 if (h->h_iop && h->h_iop->io_name)
5137 unlink(h->h_iop->io_name);
5142 /* unlink here temp files before a freearea(area) */
5143 static void freehere(int area)
5145 struct here *h, *hl;
5147 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5150 for (h = acthere; h != NULL; h = h->h_next)
5151 if (getarea((char *) h) >= area) {
5152 if (h->h_iop->io_name != NULL)
5153 unlink(h->h_iop->io_name);
5155 acthere = h->h_next;
5157 hl->h_next = h->h_next;
5163 /* -------- sh.c -------- */
5168 int msh_main(int argc, char **argv);
5169 int msh_main(int argc, char **argv)
5175 int (*iof) (struct ioarg *);
5177 PTR_TO_GLOBALS = xzalloc(sizeof(G));
5178 sharedbuf.id = AFID_NOBUF;
5179 mainbuf.id = AFID_NOBUF;
5181 elinep = line + sizeof(line) - 5;
5183 #if ENABLE_FEATURE_EDITING
5184 line_input_state = new_line_input_t(FOR_SHELL);
5187 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5193 assign(*ap++, !COPYV);
5194 for (ap = environ; *ap;)
5195 export(lookup(*ap++));
5200 shell = lookup("SHELL");
5201 if (shell->value == null)
5202 setval(shell, (char *)DEFAULT_SHELL);
5205 homedir = lookup("HOME");
5206 if (homedir->value == null)
5207 setval(homedir, "/");
5210 setval(lookup("$"), putn(getpid()));
5212 path = lookup("PATH");
5213 if (path->value == null) {
5214 /* Can be merged with same string elsewhere in bbox */
5216 setval(path, "/sbin:/usr/sbin:/bin:/usr/bin");
5218 setval(path, "/sbin:/usr/sbin:/bin:/usr/bin" + sizeof("/sbin:/usr/sbin"));
5222 ifs = lookup("IFS");
5223 if (ifs->value == null)
5224 setval(ifs, " \t\n");
5227 mshdbg_var = lookup("MSHDEBUG");
5228 if (mshdbg_var->value == null)
5229 setval(mshdbg_var, "0");
5232 prompt = lookup("PS1");
5233 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5234 if (prompt->value == null)
5236 setval(prompt, DEFAULT_USER_PROMPT);
5237 if (geteuid() == 0) {
5238 setval(prompt, DEFAULT_ROOT_PROMPT);
5239 prompt->status &= ~EXPORT;
5241 cprompt = lookup("PS2");
5242 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5243 if (cprompt->value == null)
5245 setval(cprompt, "> ");
5251 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5252 for (s = argv[0] + 1; *s; s++)
5255 prompt->status &= ~EXPORT;
5256 cprompt->status &= ~EXPORT;
5258 setval(cprompt, "");
5261 PUSHIO(aword, *++argv, iof = nlchar);
5269 /* standard input */
5273 prompt->status &= ~EXPORT;
5281 if (*s >= 'a' && *s <= 'z')
5289 if (iof == filechar && --argc > 0) {
5291 setval(cprompt, "");
5292 prompt->status &= ~EXPORT;
5293 cprompt->status &= ~EXPORT;
5295 /* Shell is non-interactive, activate printf-based debug */
5297 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5301 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5305 exit(1); /* Exit on error */
5311 /* This won't be true if PUSHIO has been called, say from newfile() above */
5312 if (e.iop < iostack) {
5313 PUSHIO(afile, 0, iof);
5314 if (isatty(0) && isatty(1) && !cflag) {
5316 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5318 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
5320 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
5322 printf("Enter 'help' for a list of built-in commands.\n\n");
5327 signal(SIGQUIT, qflag);
5328 if (name && name[0] == '-') {
5330 f = open(".profile", O_RDONLY);
5333 f = open("/etc/profile", O_RDONLY);
5338 signal(SIGTERM, sig);
5340 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5341 signal(SIGINT, onintr);
5346 for (ap = ++argv; --argc > 0;) {
5348 if (assign(*ap, !COPYV)) {
5349 dolc--; /* keyword */
5355 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5357 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
5360 if (interactive && e.iop <= iostack) {
5361 #if ENABLE_FEATURE_EDITING
5362 current_prompt = prompt->value;
5368 /* Ensure that getenv("PATH") stays current */
5369 setenv("PATH", path->value, 1);
5372 DBGPRINTF(("MSH_MAIN: returning.\n"));
5377 * Copyright (c) 1987,1997, Prentice Hall
5378 * All rights reserved.
5380 * Redistribution and use of the MINIX operating system in source and
5381 * binary forms, with or without modification, are permitted provided
5382 * that the following conditions are met:
5384 * Redistributions of source code must retain the above copyright
5385 * notice, this list of conditions and the following disclaimer.
5387 * Redistributions in binary form must reproduce the above
5388 * copyright notice, this list of conditions and the following
5389 * disclaimer in the documentation and/or other materials provided
5390 * with the distribution.
5392 * Neither the name of Prentice Hall nor the names of the software
5393 * authors or contributors may be used to endorse or promote
5394 * products derived from this software without specific prior
5395 * written permission.
5397 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5398 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5399 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5400 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5401 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5402 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5403 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5404 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5405 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5406 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5407 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5408 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.