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_SHELL 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 void 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 void itoa_to_buf(int n, char *buf, unsigned buflen)
72 if (buflen && n < 0) {
77 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));
87 extern char **environ;
90 /*#define MSHDEBUG 1*/
93 int mshdbg = MSHDEBUG;
95 #define DBGPRINTF(x) if(mshdbg>0)printf x
96 #define DBGPRINTF0(x) if(mshdbg>0)printf x
97 #define DBGPRINTF1(x) if(mshdbg>1)printf x
98 #define DBGPRINTF2(x) if(mshdbg>2)printf x
99 #define DBGPRINTF3(x) if(mshdbg>3)printf x
100 #define DBGPRINTF4(x) if(mshdbg>4)printf x
101 #define DBGPRINTF5(x) if(mshdbg>5)printf x
102 #define DBGPRINTF6(x) if(mshdbg>6)printf x
103 #define DBGPRINTF7(x) if(mshdbg>7)printf x
104 #define DBGPRINTF8(x) if(mshdbg>8)printf x
105 #define DBGPRINTF9(x) if(mshdbg>9)printf x
109 #define RCPRINTF(x) if(mshdbg_rc)printf x
114 #define DBGPRINTF0(x) ((void)0)
115 #define DBGPRINTF1(x) ((void)0)
116 #define DBGPRINTF2(x) ((void)0)
117 #define DBGPRINTF3(x) ((void)0)
118 #define DBGPRINTF4(x) ((void)0)
119 #define DBGPRINTF5(x) ((void)0)
120 #define DBGPRINTF6(x) ((void)0)
121 #define DBGPRINTF7(x) ((void)0)
122 #define DBGPRINTF8(x) ((void)0)
123 #define DBGPRINTF9(x) ((void)0)
125 #define RCPRINTF(x) ((void)0)
127 #endif /* MSHDEBUG */
130 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
131 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
132 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
134 # define DEFAULT_ROOT_PROMPT "# "
135 # define DEFAULT_USER_PROMPT "$ "
139 /* -------- sh.h -------- */
145 #define NPUSH 8 /* limit to input nesting */
148 #define NOFILE 20 /* Number of open files */
149 #define NUFILE 10 /* Number of user-accessible files */
150 #define FDBASE 10 /* First file usable by Shell */
153 * values returned by wait
155 #define WAITSIG(s) ((s)&0177)
156 #define WAITVAL(s) (((s)>>8)&0377)
157 #define WAITCORE(s) (((s)&0200)!=0)
160 * library and system definitions
162 typedef void xint; /* base type of jmp_buf, for not broken compilers */
168 #define NOBLOCK ((struct op *)NULL)
169 #define NOWORD ((char *)NULL)
170 #define NOWORDS ((char **)NULL)
171 #define NOPIPE ((int *)NULL)
178 short io_unit; /* unit affected */
179 short io_flag; /* action (below) */
180 char *io_name; /* file name */
183 #define IOREAD 1 /* < */
184 #define IOHERE 2 /* << (here file) */
185 #define IOWRITE 4 /* > */
186 #define IOCAT 8 /* >> */
187 #define IOXHERE 16 /* ${}, ` in << */
188 #define IODUP 32 /* >&digit */
189 #define IOCLOSE 64 /* >&- */
191 #define IODEFAULT (-1) /* token for default IO unit */
195 * Description of a command or an operation on commands.
196 * Might eventually use a union.
199 int type; /* operation type, see below */
200 char **words; /* arguments to a command */
201 struct ioword **ioact; /* IO actions (eg, < > >>) */
204 char *str; /* identifier for case and for */
207 #define TCOM 1 /* command */
208 #define TPAREN 2 /* (c-list) */
209 #define TPIPE 3 /* a | b */
210 #define TLIST 4 /* a [&;] b */
211 #define TOR 5 /* || */
212 #define TAND 6 /* && */
220 #define TPAT 14 /* pattern in case */
221 #define TBRACE 15 /* {c-list} */
222 #define TASYNC 16 /* c & */
223 /* Added to support "." file expansion */
226 /* Strings for names to make debug easier */
228 static const char *const T_CMD_NAMES[] = {
251 * actions determining the environment of a process
253 #define BIT(i) (1<<(i))
254 #define FEXEC BIT(0) /* execute without forking */
256 #define AREASIZE (90000)
259 * flags to control evaluation of words
261 #define DOSUB 1 /* interpret $, `, and quotes */
262 #define DOBLANK 2 /* perform blank interpretation */
263 #define DOGLOB 4 /* interpret [?* */
264 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
265 #define DOTRIM 16 /* trim resulting string */
267 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
271 static int newfile(char *s);
276 struct brkcon *nextlev;
283 * -k: look for name=value everywhere on command line
285 * -t: exit after reading and executing one command
288 * -u: unset variables net diagnostic
290 static char flags['z' - 'a' + 1];
291 /* this looks weird, but is OK ... we index flag with 'a'...'z' */
292 static char *flag = flags - 'a';
294 static char *null; /* null value for variable */
295 static int intr; /* interrupt pending */
297 /* moved to G: static char *trap[_NSIG + 1]; */
298 /* moved to G: static char ourtrap[_NSIG + 1]; */
299 static int trapset; /* trap pending */
301 static int heedint; /* heed interrupt signals */
303 static int yynerrs; /* yacc */
305 /* moved to G: static char line[LINELIM]; */
307 #if ENABLE_FEATURE_EDITING
308 static char *current_prompt;
309 static line_input_t *line_input_state;
316 static const char *rexecve(char *c, char **v, char **envp);
317 static char *evalstr(char *cp, int f);
318 static char *putn(int n);
319 static char *unquote(char *as);
320 static int rlookup(char *n);
321 static struct wdblock *glob(char *cp, struct wdblock *wb);
322 static int my_getc(int ec);
323 static int subgetc(char ec, int quoted);
324 static char **makenv(int all, struct wdblock *wb);
325 static char **eval(char **ap, int f);
326 static int setstatus(int s);
327 static int waitfor(int lastpid, int canintr);
329 static void onintr(int s); /* SIGINT handler */
331 static int newenv(int f);
332 static void quitenv(void);
333 static void next(int f);
334 static void setdash(void);
335 static void onecommand(void);
336 static void runtrap(int i);
339 /* -------- area stuff -------- */
341 #define REGSIZE sizeof(struct region)
343 /* #define SHRINKBY (64) */
347 #define ALIGN (sizeof(int)-1)
356 /* -------- grammar stuff -------- */
381 /* Added for "." file expansion */
384 #define YYERRCODE 300
387 #define CONTIN 01 /* skip new lines to complete command */
389 static struct op *pipeline(int cf);
390 static struct op *andor(void);
391 static struct op *c_list(void);
392 static int synio(int cf);
393 static void musthave(int c, int cf);
394 static struct op *simple(void);
395 static struct op *nested(int type, int mark);
396 static struct op *command(int cf);
397 static struct op *dogroup(int onlydone);
398 static struct op *thenpart(void);
399 static struct op *elsepart(void);
400 static struct op *caselist(void);
401 static struct op *casepart(void);
402 static char **pattern(void);
403 static char **wordlist(void);
404 static struct op *list(struct op *t1, struct op *t2);
405 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
406 static struct op *newtp(void);
407 static struct op *namelist(struct op *t);
408 static char **copyw(void);
409 static void word(char *cp);
410 static struct ioword **copyio(void);
411 static struct ioword *io(int u, int f, char *cp);
412 static int yylex(int cf);
413 static int collect(int c, int c1);
414 static int dual(int c);
415 static void diag(int ec);
416 static char *tree(unsigned size);
418 /* -------- var.h -------- */
427 #define COPYV 1 /* flag to setval, suggesting copy */
428 #define RONLY 01 /* variable is read-only */
429 #define EXPORT 02 /* variable is to be exported */
430 #define GETCELL 04 /* name & value space was got with getcell */
432 static int yyparse(void);
434 static int execute(struct op *t, int *pin, int *pout, int act);
437 #define AFID_NOBUF (~0)
441 /* -------- io.h -------- */
444 unsigned id; /* buffer id */
445 char buf[512]; /* buffer */
446 char *bufp; /* pointer into buffer */
447 char *ebufp; /* pointer to end of buffer */
450 /* possible arguments to an IO function */
454 int afile; /* file descriptor */
455 unsigned afid; /* buffer id */
456 long afpos; /* file position */
457 struct iobuf *afbuf; /* buffer for this file */
460 /* an input generator's state */
462 int (*iofn) (struct ioarg *, struct io *);
465 char prev; /* previous character read by readc() */
466 char nlcount; /* for `'s */
467 char xchar; /* for `'s */
468 char task; /* reason for pushed IO */
471 #define XOTHER 0 /* none of the below */
472 #define XDOLL 1 /* expanding ${} */
473 #define XGRAVE 2 /* expanding `'s */
474 #define XIO 3 /* file IO */
476 /* in substitution */
477 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
479 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
480 /* moved to G: static struct ioarg ioargstack[NPUSH]; */
481 static struct io iostack[NPUSH];
482 /* moved to G: static struct iobuf sharedbuf = { AFID_NOBUF }; */
483 /* moved to G: static struct iobuf mainbuf = { AFID_NOBUF }; */
484 static unsigned bufid = AFID_ID; /* buffer id counter */
486 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
490 * input generators for IO structure
492 static int nlchar(struct ioarg *ap);
493 static int strchar(struct ioarg *ap);
494 static int qstrchar(struct ioarg *ap);
495 static int filechar(struct ioarg *ap);
496 static int herechar(struct ioarg *ap);
497 static int linechar(struct ioarg *ap);
498 static int gravechar(struct ioarg *ap, struct io *iop);
499 static int qgravechar(struct ioarg *ap, struct io *iop);
500 static int dolchar(struct ioarg *ap);
501 static int wdchar(struct ioarg *ap);
502 static void scraphere(void);
503 static void freehere(int area);
504 static void gethere(void);
505 static void markhere(char *s, struct ioword *iop);
506 static int herein(char *hname, int xdoll);
507 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
510 static int eofc(void);
511 static int readc(void);
512 static void unget(int c);
513 static void ioecho(char c);
519 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
520 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
521 static int remap(int fd);
522 static int openpipe(int *pv);
523 static void closepipe(int *pv);
524 static struct io *setbase(struct io *ip);
526 /* -------- word.h -------- */
528 #define NSTART 16 /* default number of words to allow for initially */
533 /* bounds are arbitrary */
537 static struct wdblock *addword(char *wd, struct wdblock *wb);
538 static struct wdblock *newword(int nw);
539 static char **getwords(struct wdblock *wb);
541 /* -------- misc stuff -------- */
543 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
544 static int iosetup(struct ioword *iop, int pipein, int pipeout);
545 static void brkset(struct brkcon *bc);
546 static int dolabel(struct op *t);
547 static int dohelp(struct op *t);
548 static int dochdir(struct op *t);
549 static int doshift(struct op *t);
550 static int dologin(struct op *t);
551 static int doumask(struct op *t);
552 static int doexec(struct op *t);
553 static int dodot(struct op *t);
554 static int dowait(struct op *t);
555 static int doread(struct op *t);
556 static int doeval(struct op *t);
557 static int dotrap(struct op *t);
558 static int getsig(char *s);
559 static void setsig(int n, sighandler_t f);
560 static int getn(char *as);
561 static int dobreak(struct op *t);
562 static int docontinue(struct op *t);
563 static int brkcontin(char *cp, int val);
564 static int doexit(struct op *t);
565 static int doexport(struct op *t);
566 static int doreadonly(struct op *t);
567 static void rdexp(char **wp, void (*f) (struct var *), int key);
568 static void badid(char *s);
569 static int doset(struct op *t);
570 static void varput(char *s, int out);
571 static int dotimes(struct op *t);
572 static int expand(const char *cp, struct wdblock **wbp, int f);
573 static char *blank(int f);
574 static int dollar(int quoted);
575 static int grave(int quoted);
576 static void globname(char *we, char *pp);
577 static char *generate(char *start1, char *end1, char *middle, char *end);
578 static int anyspcl(struct wdblock *wb);
579 static int xstrcmp(char *p1, char *p2);
580 static void glob0(char *a0, unsigned a1, int a2,
581 int (*a3) (char *, char *));
582 static void readhere(char **name, char *s, int ec);
583 static int xxchar(struct ioarg *ap);
588 struct ioword *h_iop;
592 static const char * const signame[] = {
595 NULL, /* interrupt */
597 "Illegal instruction",
601 "Floating Point Exception",
606 NULL, /* broken pipe */
611 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
617 static const struct res restab[] = {
643 int (*builtinfunc) (struct op * t);
645 static const struct builtincmd builtincmds[] = {
650 {"continue", docontinue},
654 {"export", doexport},
659 {"readonly", doreadonly},
669 static struct op *scantree(struct op *);
670 static struct op *dowholefile(int, int);
678 static int interactive; /* Is this an interactive shell */
680 static int multiline; /* \n changed to ; */
681 static struct op *outtree; /* result from parser */
684 static struct brkcon *brklist;
686 static struct wdblock *wdlist;
687 static struct wdblock *iolist;
690 static struct var *mshdbg_var;
692 static struct var *vlist; /* dictionary */
693 static struct var *homedir; /* home directory */
694 static struct var *prompt; /* main prompt */
695 static struct var *cprompt; /* continuation prompt */
696 static struct var *path; /* search path for commands */
697 static struct var *shell; /* shell to interpret command files */
698 static struct var *ifs; /* field separators */
700 static int areanum; /* current allocation area */
703 static char *null = (char*)"";
704 static int heedint = 1;
705 static void (*qflag) (int) = SIG_IGN;
709 static int iounit = IODEFAULT;
710 static YYSTYPE yylval;
711 static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
713 static struct here *inhere; /* list of hear docs while parsing */
714 static struct here *acthere; /* list of active here documents */
715 static struct region *areabot; /* bottom of area */
716 static struct region *areatop; /* top of area */
717 static struct region *areanxt; /* starting point of scan */
719 static void *brkaddr;
722 * parsing & execution environment
728 xint *errpt; /* void * */
733 static struct env e = {
734 NULL /* set to line in main() */, /* linep: char ptr */
735 iostack, /* iobase: struct io ptr */
736 iostack - 1, /* iop: struct io ptr */
737 (xint *) NULL, /* errpt: void ptr for errors? */
738 FDBASE, /* iofd: file desc */
739 (struct env *) NULL /* oenv: struct env ptr */
744 char ourtrap[_NSIG + 1];
745 char *trap[_NSIG + 1];
746 struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
747 struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
748 struct ioarg ioargstack[NPUSH];
749 char filechar_cmdbuf[BUFSIZ];
751 char child_cmd[LINELIM];
754 #define G (*ptr_to_globals)
755 #define ourtrap (G.ourtrap )
756 #define trap (G.trap )
757 #define sharedbuf (G.sharedbuf )
758 #define mainbuf (G.mainbuf )
759 #define ioargstack (G.ioargstack )
760 #define filechar_cmdbuf (G.filechar_cmdbuf)
761 #define line (G.line )
762 #define child_cmd (G.child_cmd )
766 void print_t(struct op *t)
768 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
769 T_CMD_NAMES[t->type], t->words, t->ioact));
772 DBGPRINTF(("T: W1: %s", t->words[0]));
776 void print_tree(struct op *head)
779 DBGPRINTF(("PRINT_TREE: no tree\n"));
783 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
787 print_tree(head->left);
790 print_tree(head->right);
792 #endif /* MSHDEBUG */
798 static void prs(const char *s)
801 write(2, s, strlen(s));
804 static void prn(unsigned u)
809 static void echo(char **wp)
814 for (i = 0; wp[i]; i++) {
822 static void closef(int i)
828 static void closeall(void)
832 for (u = NUFILE; u < NOFILE;)
837 /* fail but return to process next command */
838 static void fail(void) ATTRIBUTE_NORETURN;
839 static void fail(void)
845 /* abort shell (or fail in subshell) */
846 static void leave(void) ATTRIBUTE_NORETURN;
847 static void leave(void)
849 DBGPRINTF(("LEAVE: leave called!\n"));
860 static void warn(const char *s)
871 static void err(const char *s)
881 e.iop = e.iobase = iostack;
885 /* -------- area.c -------- */
888 * All memory between (char *)areabot and (char *)(areatop+1) is
889 * exclusively administered by the area management routines.
890 * It is assumed that sbrk() and brk() manipulate the high end.
894 void * __q = (void *)-1; \
895 if (brkaddr + (int)(X) < brktop) { \
897 brkaddr += (int)(X); \
902 static void initarea(void)
904 brkaddr = xmalloc(AREASIZE);
905 brktop = brkaddr + AREASIZE;
907 while ((long) sbrk(0) & ALIGN)
909 areabot = (struct region *) sbrk(REGSIZE);
911 areabot->next = areabot;
912 areabot->area = BUSY;
917 static char *getcell(unsigned nbytes)
920 struct region *p, *q;
927 /* silly and defeats the algorithm */
929 * round upwards and add administration area
931 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
934 if (p->area > areanum) {
938 while ((q = p->next)->area > areanum && q != areanxt)
941 * exit loop if cell big enough
950 i = nregio >= GROWBY ? nregio : GROWBY;
951 p = (struct region *) sbrk(i * REGSIZE);
952 if (p == (struct region *) -1)
957 abort(); /* allocated areas are contiguous */
967 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
969 areanxt = p + nregio;
972 * split into requested area and rest
974 if (areanxt + 1 > q) {
976 abort(); /* insufficient space left for admin */
979 areanxt->area = FREE;
983 return (char *) (p + 1);
986 static void freecell(char *cp)
990 p = (struct region *) cp;
998 #define DELETE(obj) freecell((char *)obj)
1000 static void freearea(int a)
1002 struct region *p, *top;
1005 for (p = areabot; p != top; p = p->next)
1010 static void setarea(char *cp, int a)
1014 p = (struct region *) cp;
1019 static int getarea(char *cp)
1021 return ((struct region *) cp - 1)->area;
1024 static void garbage(void)
1026 struct region *p, *q, *top;
1029 for (p = areabot; p != top; p = p->next) {
1030 if (p->area > areanum) {
1031 while ((q = p->next)->area > areanum)
1037 if (areatop >= q + SHRINKBY && q->area > areanum) {
1038 brk((char *) (q + 1));
1046 static char *space(int n)
1052 err("out of string space");
1056 static char *strsave(const char *s, int a)
1060 cp = space(strlen(s) + 1);
1062 // FIXME: I highly doubt this is good.
1071 /* -------- var.c -------- */
1073 static int eqname(const char *n1, const char *n2)
1075 for (; *n1 != '=' && *n1 != '\0'; n1++)
1078 return *n2 == '\0' || *n2 == '=';
1081 static const char *findeq(const char *cp)
1083 while (*cp != '\0' && *cp != '=')
1089 * Find the given name in the dictionary
1090 * and return its value. If the name was
1091 * not previously there, enter it now and
1092 * return a null value.
1094 static struct var *lookup(const char *n)
1096 // FIXME: dirty hack
1097 static struct var dummy;
1105 dummy.name = (char*)n;
1106 for (c = 0; isdigit(*n) && c < 1000; n++)
1107 c = c * 10 + *n - '0';
1108 dummy.status = RONLY;
1109 dummy.value = (c <= dolc ? dolv[c] : null);
1113 for (vp = vlist; vp; vp = vp->next)
1114 if (eqname(vp->name, n))
1118 vp = (struct var *) space(sizeof(*vp));
1119 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1120 dummy.name = dummy.value = (char*)"";
1125 while ((*xp = *n++) != '\0' && *xp != '=')
1129 setarea((char *) vp, 0);
1130 setarea((char *) vp->name, 0);
1133 vp->status = GETCELL;
1139 * if name is not NULL, it must be
1140 * a prefix of the space `val',
1142 * this is all so that exporting
1143 * values is reasonably painless.
1145 static void nameval(struct var *vp, const char *val, const char *name)
1151 if (vp->status & RONLY) {
1153 while (*xp && *xp != '=')
1154 putc(*xp++, stderr);
1155 err(" is read-only");
1160 xp = space(strlen(vp->name) + strlen(val) + 2);
1163 /* make string: name=value */
1167 while ((*xp = *cp++) != '\0' && *xp != '=')
1174 if (vp->status & GETCELL)
1175 freecell(vp->name); /* form new string `name=value' */
1176 vp->name = (char*)name;
1177 vp->value = (char*)val;
1182 * give variable at `vp' the value `val'.
1184 static void setval(struct var *vp, const char *val)
1186 nameval(vp, val, NULL);
1189 static void export(struct var *vp)
1191 vp->status |= EXPORT;
1194 static void ronly(struct var *vp)
1196 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1197 vp->status |= RONLY;
1200 static int isassign(const char *s)
1203 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1206 /* no isalpha() - we shouldn't use locale */
1207 /* c | 0x20 - lowercase (Latin) letters */
1208 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1219 && (unsigned)(c - '0') > 9 /* not number */
1220 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1227 static int assign(const char *s, int cf)
1232 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1234 if (!isalpha(*s) && *s != '_')
1236 for (cp = s; *cp != '='; cp++)
1237 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1240 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1242 vp->status &= ~GETCELL;
1246 static int checkname(char *cp)
1248 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1250 if (!isalpha(*cp++) && *(cp - 1) != '_')
1253 if (!isalnum(*cp++) && *(cp - 1) != '_')
1258 static void putvlist(int f, int out)
1262 for (vp = vlist; vp; vp = vp->next) {
1263 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1264 if (vp->status & EXPORT)
1265 write(out, "export ", 7);
1266 if (vp->status & RONLY)
1267 write(out, "readonly ", 9);
1268 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1269 write(out, "\n", 1);
1278 static void sig(int i)
1284 static void runtrap(int i)
1289 if (trapstr == NULL)
1295 RUN(aword, trapstr, nlchar);
1299 static void setdash(void)
1303 char m['z' - 'a' + 1];
1306 for (c = 'a'; c <= 'z'; c++)
1310 setval(lookup("-"), m);
1313 static int newfile(char *s)
1317 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1320 if (NOT_LONE_DASH(s)) {
1321 DBGPRINTF(("NEWFILE: s is %s\n", s));
1325 err(": cannot open");
1335 struct op *scantree(struct op *head)
1342 if (head->left != NULL) {
1343 dotnode = scantree(head->left);
1348 if (head->right != NULL) {
1349 dotnode = scantree(head->right);
1354 if (head->words == NULL)
1357 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1359 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1360 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1368 static void onecommand(void)
1373 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1393 setjmp(failpt); /* Bruce Evans' fix */
1395 if (setjmp(failpt) || yyparse() || intr) {
1396 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1401 if (!interactive && intr)
1414 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1416 execute(outtree, NOPIPE, NOPIPE, 0);
1419 if (!interactive && intr) {
1431 static int newenv(int f)
1435 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1442 ep = (struct env *) space(sizeof(*ep));
1455 static void quitenv(void)
1460 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1466 /* should close `'d files */
1468 while (--fd >= e.iofd)
1474 * Is character c in s?
1476 static int any(int c, const char *s)
1485 * Is any character from s1 in s2?
1487 static int anys(const char *s1, const char *s2)
1495 static char *putn(int n)
1500 static void next(int f)
1502 PUSHIO(afile, f, filechar);
1505 static void onintr(int s) /* ANSI C requires a parameter */
1507 signal(SIGINT, onintr);
1514 } else if (heedint) {
1521 /* -------- gmatch.c -------- */
1523 * int gmatch(string, pattern)
1524 * char *string, *pattern;
1526 * Match a pattern as in sh(1).
1531 #define QMASK (CMASK & ~QUOTE)
1532 #define NOT '!' /* might use ^ */
1534 static const char *cclass(const char *p, int sub)
1536 int c, d, not, found;
1546 if (p[1] == '-' && p[2] != ']') {
1551 if (c == sub || (c <= sub && sub <= d))
1553 } while (*++p != ']');
1554 return found ? p + 1 : NULL;
1557 static int gmatch(const char *s, const char *p)
1561 if (s == NULL || p == NULL)
1564 while ((pc = *p++ & CMASK) != '\0') {
1581 if (*p == '\0' || gmatch(s, p))
1583 } while (*s++ != '\0');
1587 if (sc != (pc & ~QUOTE))
1595 /* -------- csyn.c -------- */
1597 * shell: syntax (C version)
1600 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1601 static void yyerror(const char *s)
1604 if (interactive && e.iop <= iostack) {
1606 while (eofc() == 0 && yylex(0) != '\n');
1612 static void zzerr(void) ATTRIBUTE_NORETURN;
1613 static void zzerr(void)
1615 yyerror("syntax error");
1620 DBGPRINTF7(("YYPARSE: enter...\n"));
1627 return (yynerrs != 0);
1630 static struct op *pipeline(int cf)
1635 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1639 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1642 while ((c = yylex(0)) == '|') {
1643 p = command(CONTIN);
1645 DBGPRINTF8(("PIPELINE: error!\n"));
1649 if (t->type != TPAREN && t->type != TCOM) {
1650 /* shell statement */
1651 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1654 t = block(TPIPE, t, p, NOWORDS);
1659 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1663 static struct op *andor(void)
1668 DBGPRINTF7(("ANDOR: enter...\n"));
1672 DBGPRINTF9(("ANDOR: t=%p\n", t));
1675 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1676 p = pipeline(CONTIN);
1678 DBGPRINTF8(("ANDOR: error!\n"));
1682 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1688 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1692 static struct op *c_list(void)
1697 DBGPRINTF7(("C_LIST: enter...\n"));
1704 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1706 while ((c = yylex(0)) == ';' || c == '&'
1707 || (multiline && c == '\n')) {
1715 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1723 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1727 static int synio(int cf)
1733 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1736 if (c != '<' && c != '>') {
1743 iop = io(iounit, i, yylval.cp);
1747 markhere(yylval.cp, iop);
1749 DBGPRINTF7(("SYNIO: returning 1\n"));
1753 static void musthave(int c, int cf)
1755 peeksym = yylex(cf);
1757 DBGPRINTF7(("MUSTHAVE: error!\n"));
1764 static struct op *simple(void)
1770 switch (peeksym = yylex(0)) {
1791 static struct op *nested(int type, int mark)
1795 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1801 return block(type, t, NOBLOCK, NOWORDS);
1804 static struct op *command(int cf)
1807 struct wdblock *iosave;
1810 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1836 t = nested(TPAREN, ')');
1840 t = nested(TBRACE, '}');
1850 t->words = wordlist();
1852 if (c != '\n' && c != ';')
1854 t->left = dogroup(0);
1862 t->type = c == WHILE ? TWHILE : TUNTIL;
1864 t->right = dogroup(1);
1876 musthave(IN, CONTIN);
1879 t->left = caselist();
1890 t->right = thenpart();
1899 musthave(WORD, 0); /* gets name of file */
1900 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1902 word(yylval.cp); /* add word to wdlist */
1903 word(NOWORD); /* terminate wdlist */
1904 t->words = copyw(); /* dup wdlist */
1914 DBGPRINTF(("COMMAND: returning %p\n", t));
1919 static struct op *dowholefile(int type, int mark)
1923 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1928 t = block(type, t, NOBLOCK, NOWORDS);
1929 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1933 static struct op *dogroup(int onlydone)
1939 if (c == DONE && onlydone)
1948 static struct op *thenpart(void)
1961 if (t->left == NULL)
1963 t->right = elsepart();
1967 static struct op *elsepart(void)
1972 switch (c = yylex(0)) {
1983 t->right = thenpart();
1992 static struct op *caselist(void)
1997 while ((peeksym = yylex(CONTIN)) != ESAC) {
1998 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1999 t = list(t, casepart());
2002 DBGPRINTF(("CASELIST, returning t=%p\n", t));
2006 static struct op *casepart(void)
2010 DBGPRINTF7(("CASEPART: enter...\n"));
2014 t->words = pattern();
2017 peeksym = yylex(CONTIN);
2018 if (peeksym != ESAC)
2019 musthave(BREAK, CONTIN);
2021 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2026 static char **pattern(void)
2043 static char **wordlist(void)
2053 while ((c = yylex(0)) == WORD)
2061 * supporting functions
2063 static struct op *list(struct op *t1, struct op *t2)
2065 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2072 return block(TLIST, t1, t2, NOWORDS);
2075 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2079 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2087 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2093 /* See if given string is a shell multiline (FOR, IF, etc) */
2094 static int rlookup(char *n)
2096 const struct res *rp;
2098 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2100 for (rp = restab; rp->r_name; rp++)
2101 if (strcmp(rp->r_name, n) == 0) {
2102 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2103 return rp->r_val; /* Return numeric code for shell multiline */
2106 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2107 return 0; /* Not a shell multiline */
2110 static struct op *newtp(void)
2114 t = (struct op *) tree(sizeof(*t));
2122 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2127 static struct op *namelist(struct op *t)
2130 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2131 T_CMD_NAMES[t->type], iolist));
2134 iolist = addword((char *) NULL, iolist);
2135 t->ioact = copyio();
2139 if (t->type != TCOM) {
2140 if (t->type != TPAREN && t->ioact != NULL) {
2141 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2142 t->ioact = t->left->ioact;
2143 t->left->ioact = NULL;
2154 static char **copyw(void)
2158 wd = getwords(wdlist);
2163 static void word(char *cp)
2165 wdlist = addword(cp, wdlist);
2168 static struct ioword **copyio(void)
2170 struct ioword **iop;
2172 iop = (struct ioword **) getwords(iolist);
2177 static struct ioword *io(int u, int f, char *cp)
2181 iop = (struct ioword *) tree(sizeof(*iop));
2185 iolist = addword((char *) iop, iolist);
2189 static int yylex(int cf)
2209 line[LINELIM - 1] = '\0';
2212 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2217 if (any(c, "0123456789")) {
2220 if (c1 == '<' || c1 == '>') {
2229 case '#': /* Comment, skip to next newline or End-of-string */
2230 while ((c = my_getc(0)) != '\0' && c != '\n');
2235 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2239 DBGPRINTF9(("YYLEX: found $\n"));
2243 c = collect(c, '}');
2262 /* If more chars process them, else return NULL char */
2280 if (multiline || cf & CONTIN) {
2281 if (interactive && e.iop <= iostack) {
2282 #if ENABLE_FEATURE_EDITING
2283 current_prompt = cprompt->value;
2285 prs(cprompt->value);
2302 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2303 if (e.linep >= elinep)
2304 err("word too long");
2311 if (any(c, "\"'`$"))
2324 yylval.cp = strsave(line, areanum);
2329 static int collect(int c, int c1)
2333 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2336 while ((c = my_getc(c1)) != c1) {
2345 if (interactive && c == '\n' && e.iop <= iostack) {
2346 #if ENABLE_FEATURE_EDITING
2347 current_prompt = cprompt->value;
2349 prs(cprompt->value);
2357 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2362 /* "multiline commands" helper func */
2363 /* see if next 2 chars form a shell multiline */
2364 static int dual(int c)
2369 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2371 *cp++ = c; /* c is the given "peek" char */
2372 *cp++ = my_getc(0); /* get next char of input */
2373 *cp = '\0'; /* add EOS marker */
2375 c = rlookup(s); /* see if 2 chars form a shell multiline */
2377 unget(*--cp); /* String is not a shell multiline, put peek char back */
2379 return c; /* String is multiline, return numeric multiline (restab) code */
2382 static void diag(int ec)
2386 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2389 if (c == '>' || c == '<') {
2392 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2395 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2396 if (c != '&' || yylval.i == IOHERE)
2402 static char *tree(unsigned size)
2408 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2409 prs("command line too complicated\n");
2420 /* -------- exec.c -------- */
2422 static struct op **find1case(struct op *t, const char *w)
2430 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2434 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2435 T_CMD_NAMES[t->type]));
2437 if (t->type == TLIST) {
2438 tp = find1case(t->left, w);
2440 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2443 t1 = t->right; /* TPAT */
2447 for (wp = t1->words; *wp;) {
2448 cp = evalstr(*wp++, DOSUB);
2449 if (cp && gmatch(w, cp)) {
2450 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2456 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2460 static struct op *findcase(struct op *t, const char *w)
2464 tp = find1case(t, w);
2465 return tp != NULL ? *tp : NULL;
2472 static int execute(struct op *t, int *pin, int *pout, int act)
2475 volatile int i, rv, a;
2479 struct op *outtree_save;
2483 /* Avoid longjmp clobbering */
2488 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2492 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2493 t->type, T_CMD_NAMES[t->type],
2494 ((t->words == NULL) ? "NULL" : t->words[0])));
2498 wp = (wp2 = t->words) != NULL
2499 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2504 DBGPRINTF3(("EXECUTE: TDOT\n"));
2506 outtree_save = outtree;
2508 newfile(evalstr(t->words[0], DOALL));
2510 t->left = dowholefile(TLIST, 0);
2513 outtree = outtree_save;
2516 rv = execute(t->left, pin, pout, 0);
2518 rv = execute(t->right, pin, pout, 0);
2522 rv = execute(t->left, pin, pout, 0);
2526 rv = forkexec(t, pin, pout, act, wp);
2536 pv[0] = remap(pv[0]);
2537 pv[1] = remap(pv[1]);
2538 (void) execute(t->left, pin, pv, 0);
2539 rv = execute(t->right, pv, pout, 0);
2544 (void) execute(t->left, pin, pout, 0);
2545 rv = execute(t->right, pin, pout, 0);
2550 int hinteractive = interactive;
2552 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2555 if (i == 0) { /* child */
2556 signal(SIGINT, SIG_IGN);
2557 signal(SIGQUIT, SIG_IGN);
2559 signal(SIGTERM, SIG_DFL);
2563 open(bb_dev_null, 0);
2565 _exit(execute(t->left, pin, pout, FEXEC));
2567 interactive = hinteractive;
2569 setval(lookup("!"), putn(i));
2584 rv = execute(t->left, pin, pout, 0);
2586 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2587 rv = execute(t1, pin, pout, 0);
2598 while (*wp++ != NULL);
2600 vp = lookup(t->str);
2601 while (setjmp(bc.brkpt))
2605 for (t1 = t->left; i-- && *wp != NULL;) {
2607 rv = execute(t1, pin, pout, 0);
2609 brklist = brklist->nextlev;
2614 while (setjmp(bc.brkpt))
2619 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2620 rv = execute(t->right, pin, pout, 0);
2621 brklist = brklist->nextlev;
2626 if (t->right != NULL) {
2627 rv = !execute(t->left, pin, pout, 0) ?
2628 execute(t->right->left, pin, pout, 0) :
2629 execute(t->right->right, pin, pout, 0);
2634 cp = evalstr(t->str, DOSUB | DOTRIM);
2638 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2639 ((t->str == NULL) ? "NULL" : t->str),
2640 ((cp == NULL) ? "NULL" : cp)));
2642 t1 = findcase(t->left, cp);
2644 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2645 rv = execute(t1, pin, pout, 0);
2646 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2655 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2663 rv = execute(t1, pin, pout, 0);
2676 if (interactive && intr) {
2687 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2691 typedef int (*builtin_func_ptr)(struct op *);
2693 static builtin_func_ptr inbuilt(const char *s) {
2694 const struct builtincmd *bp;
2696 for (bp = builtincmds; bp->name != NULL; bp++)
2697 if (strcmp(bp->name, s) == 0)
2698 return bp->builtinfunc;
2703 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2707 builtin_func_ptr shcom = NULL;
2709 const char *cp = NULL;
2710 struct ioword **iopp;
2720 struct brkcon *hbrklist;
2724 /* Avoid longjmp clobbering */
2734 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2736 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2737 ((t->words == NULL) ? "NULL" : t->words[0])));
2741 rv = -1; /* system-detected error */
2742 if (t->type == TCOM) {
2743 while (*wp++ != NULL);
2746 /* strip all initial assignments */
2747 /* not correct wrt PATH=yyy command etc */
2749 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2751 echo(cp ? wp : owp);
2754 if (cp == NULL && t->ioact == NULL) {
2755 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2757 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2758 return setstatus(0);
2761 shcom = inbuilt(cp);
2768 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2771 if (shcom == NULL && (f & FEXEC) == 0) {
2772 /* Save values in case the child process alters them */
2776 hinteractive = interactive;
2781 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2786 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2790 if (newpid > 0) { /* Parent */
2791 /* Restore values */
2795 interactive = hinteractive;
2806 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2809 /* Must be the child process, pid should be 0 */
2810 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2813 signal(SIGINT, SIG_IGN);
2814 signal(SIGQUIT, SIG_IGN);
2825 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2830 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2831 err("piping to/from shell builtins not yet done");
2849 if (shcom != NULL && shcom != doexec) {
2851 err(": cannot redirect shell command");
2857 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2865 i = setstatus((*shcom) (t));
2868 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2872 /* should use FIOCEXCL */
2873 for (i = FDBASE; i < NOFILE; i++)
2876 signal(SIGINT, SIG_DFL);
2877 signal(SIGQUIT, SIG_DFL);
2880 if (t->type == TPAREN)
2881 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2885 cp = rexecve(wp[0], wp, makenv(0, NULL));
2892 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2900 * 0< 1> are ignored as required
2903 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2909 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2912 if (iop->io_unit == IODEFAULT) /* take default */
2913 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2915 if (pipein && iop->io_unit == 0)
2918 if (pipeout && iop->io_unit == 1)
2921 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2922 if ((iop->io_flag & IOHERE) == 0) {
2923 cp = iop->io_name; /* huh?? */
2924 cp = evalstr(cp, DOSUB | DOTRIM);
2929 if (iop->io_flag & IODUP) {
2930 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2932 err(": illegal >& argument");
2936 iop->io_flag = IOCLOSE;
2937 iop->io_flag &= ~(IOREAD | IOWRITE);
2939 switch (iop->io_flag) {
2945 case IOHERE | IOXHERE:
2946 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2947 cp = (char*)"here file";
2950 case IOWRITE | IOCAT:
2953 lseek(u, (long) 0, SEEK_END);
2957 u = creat(cp, 0666);
2961 u = dup2(*cp - '0', iop->io_unit);
2965 close(iop->io_unit);
2974 if (u != iop->io_unit) {
2975 dup2(u, iop->io_unit);
2982 * Enter a new loop level (marked for break/continue).
2984 static void brkset(struct brkcon *bc)
2986 bc->nextlev = brklist;
2991 * Wait for the last process created.
2992 * Print a message for each process found
2993 * that was killed by a signal.
2994 * Ignore interrupt signals while waiting
2995 * unless `canintr' is true.
2997 static int waitfor(int lastpid, int canintr)
3001 int oheedint = heedint;
3008 if (errno != EINTR || canintr)
3014 if (signame[rv] != NULL) {
3015 if (pid != lastpid) {
3022 if (pid != lastpid) {
3031 prs(" - core dumped");
3032 if (rv >= NSIGNAL || signame[rv])
3038 } while (pid != lastpid);
3053 static int setstatus(int s)
3056 setval(lookup("?"), putn(s));
3061 * PATH-searching interface to execve.
3062 * If getenv("PATH") were kept up-to-date,
3063 * execvp might be used.
3065 static const char *rexecve(char *c, char **v, char **envp)
3070 int eacces = 0, asis = 0;
3073 if (ENABLE_FEATURE_SH_STANDALONE_SHELL) {
3075 if (find_applet_by_name(name)) {
3076 /* We have to exec here since we vforked. Running
3077 * run_applet_by_name() won't work and bad things
3079 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3083 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3085 sp = any('/', c) ? "" : path->value;
3086 asis = (*sp == '\0');
3087 while (asis || *sp != '\0') {
3090 for (; *sp != '\0'; tp++) {
3093 asis = (*sp == '\0');
3099 for (i = 0; (*tp++ = c[i++]) != '\0';);
3101 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3103 execve(e.linep, v, envp);
3110 execve(DEFAULT_SHELL, v, envp);
3115 return (char *) bb_msg_memory_exhausted;
3118 return "argument list too long";
3125 return errno == ENOENT ? "not found" : "cannot execute";
3129 * Run the command produced by generator `f'
3130 * applied to stream `arg'.
3132 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3135 struct wdblock *swdlist;
3136 struct wdblock *siolist;
3142 /* Avoid longjmp clobbering */
3146 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3147 areanum, outtree, failpt));
3157 if (newenv(setjmp(errpt)) == 0) {
3164 if (setjmp(failpt) == 0 && yyparse() == 0)
3165 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3168 DBGPRINTF(("RUN: error from newenv()!\n"));
3175 freearea(areanum--);
3180 /* -------- do.c -------- */
3183 * built-in commands: doX
3186 static int dohelp(struct op *t)
3189 const struct builtincmd *x;
3191 puts("\nBuilt-in commands:\n"
3192 "-------------------");
3194 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3197 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3203 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
3206 const struct BB_applet *applet;
3208 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3212 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3221 return EXIT_SUCCESS;
3226 static int dolabel(struct op *t)
3231 static int dochdir(struct op *t)
3233 const char *cp, *er;
3237 cp = homedir->value;
3240 er = ": no home directory";
3245 er = ": bad directory";
3247 prs(cp != NULL ? cp : "cd");
3252 static int doshift(struct op *t)
3256 n = t->words[1] ? getn(t->words[1]) : 1;
3258 err("nothing to shift");
3264 setval(lookup("#"), putn(dolc));
3269 * execute login and newgrp directly
3271 static int dologin(struct op *t)
3276 signal(SIGINT, SIG_DFL);
3277 signal(SIGQUIT, SIG_DFL);
3279 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3286 static int doumask(struct op *t)
3295 for (n = 3 * 4; (n -= 3) >= 0;)
3296 putc('0' + ((i >> n) & 07), stderr);
3299 /* huh??? '8','9' are not allowed! */
3300 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3301 n = n * 8 + (*cp - '0');
3307 static int doexec(struct op *t)
3314 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3320 if (setjmp(failpt) == 0)
3321 execute(t, NOPIPE, NOPIPE, FEXEC);
3327 static int dodot(struct op *t)
3335 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)));
3339 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3342 DBGPRINTF(("DODOT: cp is %s\n", cp));
3344 sp = any('/', cp) ? ":" : path->value;
3346 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3347 ((sp == NULL) ? "NULL" : sp),
3348 ((e.linep == NULL) ? "NULL" : e.linep)));
3352 while (*sp && (*tp = *sp++) != ':')
3357 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3360 i = open(e.linep, 0);
3364 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3366 next(maltmp); /* Basically a PUSHIO */
3368 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3380 static int dowait(struct op *t)
3392 setstatus(waitfor(i, 1));
3396 static int doread(struct op *t)
3402 if (t->words[1] == NULL) {
3403 err("Usage: read name ...");
3406 for (wp = t->words + 1; *wp; wp++) {
3407 for (cp = e.linep; !nl && cp < elinep - 1; cp++) {
3408 nb = read(0, cp, sizeof(*cp));
3409 if (nb != sizeof(*cp))
3412 if (nl || (wp[1] && any(*cp, ifs->value)))
3418 setval(lookup(*wp), e.linep);
3423 static int doeval(struct op *t)
3425 return RUN(awordlist, t->words + 1, wdchar);
3428 static int dotrap(struct op *t)
3433 if (t->words[1] == NULL) {
3434 for (i = 0; i <= _NSIG; i++)
3443 resetsig = isdigit(*t->words[1]);
3444 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3445 n = getsig(t->words[i]);
3449 if (*t->words[1] != '\0') {
3450 trap[n] = strsave(t->words[1], 0);
3459 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3467 static int getsig(char *s)
3472 if (n < 0 || n > _NSIG) {
3473 err("trap: bad signal number");
3479 static void setsig(int n, sighandler_t f)
3483 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3489 static int getn(char *as)
3500 for (n = 0; isdigit(*s); s++)
3501 n = (n * 10) + (*s - '0');
3504 err(": bad number");
3509 static int dobreak(struct op *t)
3511 return brkcontin(t->words[1], 1);
3514 static int docontinue(struct op *t)
3516 return brkcontin(t->words[1], 0);
3519 static int brkcontin(char *cp, int val)
3524 nl = cp == NULL ? 1 : getn(cp);
3531 brklist = bc->nextlev;
3534 err("bad break/continue level");
3538 longjmp(bc->brkpt, 1);
3542 static int doexit(struct op *t)
3549 setstatus(getn(cp));
3551 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3558 static int doexport(struct op *t)
3560 rdexp(t->words + 1, export, EXPORT);
3564 static int doreadonly(struct op *t)
3566 rdexp(t->words + 1, ronly, RONLY);
3570 static void rdexp(char **wp, void (*f) (struct var *), int key)
3572 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3573 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3576 for (; *wp != NULL; wp++) {
3577 if (isassign(*wp)) {
3581 for (cp = *wp; *cp != '='; cp++);
3593 static void badid(char *s)
3596 err(": bad identifier");
3599 static int doset(struct op *t)
3607 for (vp = vlist; vp; vp = vp->next)
3608 varput(vp->name, 1);
3612 /* bad: t->words++; */
3613 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3615 flag['x'] = flag['v'] = 0;
3625 if (*cp >= 'a' && *cp <= 'z')
3634 t->words[0] = dolv[0];
3635 for (n = 1; t->words[n]; n++)
3636 setarea((char *) t->words[n], 0);
3639 setval(lookup("#"), putn(dolc));
3640 setarea((char *) (dolv - 1), 0);
3645 static void varput(char *s, int out)
3647 if (isalnum(*s) || *s == '_') {
3648 write(out, s, strlen(s));
3649 write(out, "\n", 1);
3655 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3656 * This file contains code for the times builtin.
3658 static int dotimes(struct op *t)
3661 long clk_tck = sysconf(_SC_CLK_TCK);
3664 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3665 (int) (buf.tms_utime / clk_tck / 60),
3666 ((double) buf.tms_utime) / clk_tck,
3667 (int) (buf.tms_stime / clk_tck / 60),
3668 ((double) buf.tms_stime) / clk_tck,
3669 (int) (buf.tms_cutime / clk_tck / 60),
3670 ((double) buf.tms_cutime) / clk_tck,
3671 (int) (buf.tms_cstime / clk_tck / 60),
3672 ((double) buf.tms_cstime) / clk_tck);
3677 /* -------- eval.c -------- */
3682 * blank interpretation
3687 static char **eval(char **ap, int f)
3695 /* Avoid longjmp clobbering */
3700 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3706 if (newenv(setjmp(errpt)) == 0) {
3707 while (*ap && isassign(*ap))
3708 expand(*ap++, &wb, f & ~DOGLOB);
3710 for (wf = ap; *wf; wf++) {
3712 expand(*wf, &wb, f & ~DOGLOB);
3715 for (wb = addword((char *) 0, wb); *ap; ap++) {
3716 if (!flag['k'] || !isassign(*ap))
3717 expand(*ap, &wb, f & ~DOKEY);
3719 wb = addword((char *) 0, wb);
3725 return gflg ? (char **) NULL : wp;
3730 * Make the exported environment from the exported
3731 * names in the dictionary. Keyword assignments
3732 * will already have been done.
3734 static char **makenv(int all, struct wdblock *wb)
3738 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3740 for (vp = vlist; vp; vp = vp->next)
3741 if (all || vp->status & EXPORT)
3742 wb = addword(vp->name, wb);
3743 wb = addword((char *) 0, wb);
3744 return getwords(wb);
3747 static int expand(const char *cp, struct wdblock **wbp, int f)
3753 /* Avoid longjmp clobbering */
3757 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3764 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3765 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3767 xp = strsave(cp, areanum);
3770 *wbp = addword(xp, *wbp);
3774 if (newenv(setjmp(errpt)) == 0) {
3775 PUSHIO(aword, cp, strchar);
3777 while ((xp = blank(f)) && gflg == 0) {
3779 xp = strsave(xp, areanum);
3780 if ((f & DOGLOB) == 0) {
3783 *wbp = addword(xp, *wbp);
3785 *wbp = glob(xp, *wbp);
3793 static char *evalstr(char *cp, int f)
3797 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3800 if (expand(cp, &wb, f)) {
3801 if (wb == NULL || wb->w_nword == 0
3802 || (cp = wb->w_words[0]) == NULL
3804 // TODO: I suspect that
3805 // char *evalstr(char *cp, int f) is actually
3806 // const char *evalstr(const char *cp, int f)!
3817 * Blank interpretation and quoting
3819 static char *blank(int f)
3823 int scanequals, foundequals;
3825 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3828 scanequals = f & DOKEY;
3832 c = subgetc('"', foundequals);
3841 if (f & DOBLANK && any(c, ifs->value))
3850 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3853 if (c == '\'' || !any(c, "$`\""))
3860 if (!isalpha(c) && c != '_')
3863 c = subgetc('"', foundequals);
3865 f & (DOBLANK && any(c, ifs->value)) ||
3866 (!INSUB() && any(c, "\"'"))) {
3877 } else if (!isalnum(c) && c != '_')
3887 * Get characters, substituting for ` and $
3889 static int subgetc(char ec, int quoted)
3893 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3897 if (!INSUB() && ec != '\'') {
3899 if (grave(quoted) == 0)
3901 e.iop->task = XGRAVE;
3907 e.iop->task = XDOLL;
3916 * Prepare to generate the string returned by ${} substitution.
3918 static int dollar(int quoted)
3923 char *s, c, *cp = NULL;
3926 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3932 if (isalpha(c) || c == '_') {
3933 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3934 if (e.linep < elinep)
3941 otask = e.iop->task;
3943 e.iop->task = XOTHER;
3944 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3945 if (e.linep < elinep)
3948 e.iop->task = otask;
3955 if (e.linep >= elinep) {
3956 err("string in ${} too long");
3962 for (cp = s + 1; *cp; cp++)
3963 if (any(*cp, "=-+?")) {
3968 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3970 /* currently this does not distinguish $* and $@ */
3971 /* should check dollar */
3973 PUSHIO(awordlist, dolv + 1, dolchar);
3975 } else { /* trap the nasty ${=} */
3986 err("cannot use ${...=...} with $n");
3995 dolp = strsave(cp, areanum);
4000 prs("missing value for ");
4007 } else if (c == '+')
4008 dolp = strsave(cp, areanum);
4009 if (flag['u'] && dolp == null) {
4010 prs("unset variable: ");
4015 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4020 * Run the command in `...` and read its output.
4023 static int grave(int quoted)
4025 /* moved to G: static char child_cmd[LINELIM]; */
4036 char *argument_list[4];
4037 struct wdblock *wb = NULL;
4040 /* Avoid longjmp clobbering */
4044 for (cp = e.iop->argp->aword; *cp != '`'; cp++) {
4046 err("no closing `");
4051 /* string copy with dollar expansion */
4052 src = e.iop->argp->aword;
4057 while ((*src != '`') && (count < LINELIM)) {
4062 if (*src == '$' && !ignore && !ignore_once) {
4064 char var_name[LINELIM];
4065 char alt_value[LINELIM];
4078 var_name[var_index++] = *src++;
4079 while (isalnum(*src) || *src=='_')
4080 var_name[var_index++] = *src++;
4081 var_name[var_index] = 0;
4094 err("unclosed ${\n");
4099 while (*src && (*src != '}')) {
4100 alt_value[alt_index++] = *src++;
4102 alt_value[alt_index] = 0;
4104 err("unclosed ${\n");
4111 if (isalpha(*var_name)) {
4112 /* let subshell handle it instead */
4114 char *namep = var_name;
4122 char *altp = alt_value;
4130 wb = addword(lookup(var_name)->name, wb);
4134 vp = lookup(var_name);
4135 if (vp->value != null)
4136 value = (operator == '+') ?
4137 alt_value : vp->value;
4138 else if (operator == '?') {
4141 } else if (alt_index && (operator != '+')) {
4143 if (operator == '=')
4148 while (*value && (count < LINELIM)) {
4161 if (openpipe(pf) < 0)
4164 while ((i = vfork()) == -1 && errno == EAGAIN);
4166 DBGPRINTF3(("GRAVE: i is %p\n", io));
4170 err((char *) bb_msg_memory_exhausted);
4174 waitpid(i, NULL, 0);
4175 e.iop->argp->aword = ++cp;
4177 PUSHIO(afile, remap(pf[0]),
4178 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4181 /* allow trapped signals */
4182 /* XXX - Maybe this signal stuff should go as well? */
4183 for (j = 0; j <= _NSIG; j++)
4184 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4190 argument_list[0] = (char *) DEFAULT_SHELL;
4191 argument_list[1] = (char *) "-c";
4192 argument_list[2] = child_cmd;
4193 argument_list[3] = NULL;
4195 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4196 prs(argument_list[0]);
4203 static char *unquote(char *as)
4214 /* -------- glob.c -------- */
4220 #define scopy(x) strsave((x), areanum)
4222 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4224 static struct wdblock *cl, *nl;
4225 static char spcl[] = "[?*";
4227 static struct wdblock *glob(char *cp, struct wdblock *wb)
4235 for (pp = cp; *pp; pp++)
4238 else if (!any(*pp & ~QUOTE, spcl))
4241 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4242 nl = newword(cl->w_nword * 2);
4243 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4244 for (pp = cl->w_words[i]; *pp; pp++)
4245 if (any(*pp, spcl)) {
4246 globname(cl->w_words[i], pp);
4250 nl = addword(scopy(cl->w_words[i]), nl);
4252 for (i = 0; i < cl->w_nword; i++)
4253 DELETE(cl->w_words[i]);
4256 for (i = 0; i < cl->w_nword; i++)
4257 unquote(cl->w_words[i]);
4258 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4260 for (i = 0; i < cl->w_nword; i++)
4261 wb = addword(cl->w_words[i], wb);
4266 wb = addword(unquote(cp), wb);
4270 static void globname(char *we, char *pp)
4273 char *name, *gp, *dp;
4277 char dname[NAME_MAX + 1];
4280 for (np = we; np != pp; pp--)
4283 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4287 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4296 dname[NAME_MAX] = '\0';
4297 while ((de = readdir(dirp)) != NULL) {
4298 /* XXX Hmmm... What this could be? (abial) */
4300 if (ent[j].d_ino == 0)
4303 strncpy(dname, de->d_name, NAME_MAX);
4304 if (dname[0] == '.')
4307 for (k = 0; k < NAME_MAX; k++)
4308 if (any(dname[k], spcl))
4310 if (gmatch(dname, gp)) {
4311 name = generate(we, pp, dname, np);
4312 if (*np && !anys(np, spcl)) {
4313 if (stat(name, &dbuf)) {
4318 nl = addword(name, nl);
4327 * generate a pathname as below.
4328 * start..end1 / middle end
4329 * the slashes come for free
4331 static char *generate(char *start1, char *end1, char *middle, char *end)
4336 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4337 for (xp = start1; xp != end1;)
4339 for (xp = middle; (*op++ = *xp++) != '\0';);
4341 for (xp = end; (*op++ = *xp++) != '\0';);
4345 static int anyspcl(struct wdblock *wb)
4351 for (i = 0; i < wb->w_nword; i++)
4352 if (anys(spcl, *wd++))
4357 static int xstrcmp(char *p1, char *p2)
4359 return strcmp(*(char **) p1, *(char **) p2);
4363 /* -------- word.c -------- */
4365 static struct wdblock *newword(int nw)
4369 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4375 static struct wdblock *addword(char *wd, struct wdblock *wb)
4377 struct wdblock *wb2;
4381 wb = newword(NSTART);
4383 if (nw >= wb->w_bsize) {
4384 wb2 = newword(nw * 2);
4385 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4386 nw * sizeof(char *));
4391 wb->w_words[wb->w_nword++] = wd;
4396 char **getwords(struct wdblock *wb)
4403 if (wb->w_nword == 0) {
4407 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4408 memcpy((char *) wd, (char *) wb->w_words, nb);
4409 DELETE(wb); /* perhaps should done by caller */
4413 static int (*func) (char *, char *);
4416 static void glob3(char *i, char *j, char *k)
4418 char *index1, *index2, *index3;
4428 *index1++ = *index3;
4429 *index3++ = *index2;
4434 static void glob2(char *i, char *j)
4436 char *index1, *index2, c;
4444 *index1++ = *index2;
4449 static void glob1(char *base, char *lim)
4460 n = (int) (lim - base);
4463 n = v2 * (n / (2 * v2));
4464 hptr = lptr = base + n;
4469 c = (*func) (i, lptr);
4483 c = (*func) (hptr, j);
4507 if (lptr - base >= lim - hptr) {
4508 glob1(hptr + v2, lim);
4523 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4527 glob1(a0, a0 + a1 * a2);
4531 /* -------- io.c -------- */
4537 static int my_getc(int ec)
4541 if (e.linep > elinep) {
4542 while ((c = readc()) != '\n' && c);
4543 err("input line too long");
4548 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4551 if (c == '\n' && ec != '\"')
4559 static void unget(int c)
4561 if (e.iop >= e.iobase)
4565 static int eofc(void)
4567 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4570 static int readc(void)
4574 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4576 for (; e.iop >= e.iobase; e.iop--) {
4577 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4583 if (e.iop->prev != 0) {
4584 c = (*e.iop->iofn)(e.iop->argp, e.iop);
4590 if (e.iop == iostack)
4595 if (e.iop->task == XIO && e.iop->prev != '\n') {
4597 if (e.iop == iostack)
4602 if (e.iop->task == XIO) {
4607 if (interactive && e.iop == iostack + 1) {
4608 #if ENABLE_FEATURE_EDITING
4609 current_prompt = prompt->value;
4617 if (e.iop >= iostack) {
4618 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4622 DBGPRINTF(("READC: leave()...\n"));
4629 static void ioecho(char c)
4632 write(2, &c, sizeof c);
4636 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4638 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4639 argp->afid, e.iop));
4641 /* Set env ptr for io source to next array spot and check for array overflow */
4642 if (++e.iop >= &iostack[NPUSH]) {
4644 err("Shell input nested too deeply");
4649 /* We did not overflow the NPUSH array spots so setup data structs */
4651 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4653 if (argp->afid != AFID_NOBUF)
4657 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4658 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4660 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4662 if (e.iop == &iostack[0])
4663 e.iop->argp->afbuf = &mainbuf;
4665 e.iop->argp->afbuf = &sharedbuf;
4667 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4668 /* This line appears to be active when running scripts from command line */
4669 if ((isatty(e.iop->argp->afile) == 0)
4670 && (e.iop == &iostack[0]
4671 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4672 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4673 bufid = AFID_ID; /* AFID_ID = 0 */
4675 e.iop->argp->afid = bufid; /* assign buffer id */
4678 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4679 iostack, e.iop, e.iop->argp->afbuf));
4680 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4681 &mainbuf, &sharedbuf, bufid, e.iop));
4685 e.iop->prev = ~'\n';
4690 if (fn == filechar || fn == linechar)
4692 else if (fn == (int (*)(struct ioarg *)) gravechar
4693 || fn == (int (*)(struct ioarg *)) qgravechar)
4694 e.iop->task = XGRAVE;
4696 e.iop->task = XOTHER;
4699 static struct io *setbase(struct io *ip)
4709 * Input generating functions
4713 * Produce the characters of a string, then a newline, then EOF.
4715 static int nlchar(struct ioarg *ap)
4719 if (ap->aword == NULL)
4730 * Given a list of words, produce the characters
4731 * in them, with a space after each word.
4733 static int wdchar(struct ioarg *ap)
4748 ap->awordlist = NULL;
4753 * Return the characters of a list of words,
4754 * producing a space between them.
4756 static int dolchar(struct ioarg *ap)
4760 wp = *ap->awordlist++;
4762 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4768 static int xxchar(struct ioarg *ap)
4772 if (ap->aword == NULL)
4783 * Produce the characters from a single word (string).
4785 static int strchar(struct ioarg *ap)
4787 if (ap->aword == NULL)
4789 return *ap->aword++;
4793 * Produce quoted characters from a single word (string).
4795 static int qstrchar(struct ioarg *ap)
4799 if (ap->aword == NULL)
4808 * Return the characters from a file.
4810 static int filechar(struct ioarg *ap)
4814 struct iobuf *bp = ap->afbuf;
4816 if (ap->afid != AFID_NOBUF) {
4817 i = (ap->afid != bp->id);
4818 if (i || bp->bufp == bp->ebufp) {
4820 lseek(ap->afile, ap->afpos, SEEK_SET);
4822 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4830 bp->ebufp = bp->bufp + i;
4834 return *bp->bufp++ & 0177;
4836 #if ENABLE_FEATURE_EDITING
4837 if (interactive && isatty(ap->afile)) {
4838 /* moved to G: static char filechar_cmdbuf[BUFSIZ]; */
4839 static int position = 0, size = 0;
4841 while (size == 0 || position >= size) {
4842 read_line_input(current_prompt, filechar_cmdbuf, BUFSIZ, line_input_state);
4843 size = strlen(filechar_cmdbuf);
4846 c = filechar_cmdbuf[position];
4851 i = safe_read(ap->afile, &c, sizeof(c));
4852 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4856 * Return the characters from a here temp file.
4858 static int herechar(struct ioarg *ap)
4862 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4870 * Return the characters produced by a process (`...`).
4871 * Quote them if required, and remove any trailing newline characters.
4873 static int gravechar(struct ioarg *ap, struct io *iop)
4877 c = qgravechar(ap, iop) & ~QUOTE;
4883 static int qgravechar(struct ioarg *ap, struct io *iop)
4887 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4892 return '\n' | QUOTE;
4896 } else if ((c = filechar(ap)) == '\n') {
4898 while ((c = filechar(ap)) == '\n')
4906 return c != 0 ? c | QUOTE : 0;
4910 * Return a single command (usually the first line) from a file.
4912 static int linechar(struct ioarg *ap)
4920 ap->afile = -1; /* illegal value */
4927 * remap fd into Shell's fd space
4929 static int remap(int fd)
4935 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
4938 for (i = 0; i < NOFILE; i++)
4945 } while (fd >= 0 && fd < e.iofd);
4947 for (i = 0; i < NOFILE; i++)
4952 err("too many files open in shell");
4958 static int openpipe(int *pv)
4964 err("can't create pipe - try again");
4968 static void closepipe(int *pv)
4977 /* -------- here.c -------- */
4983 static void markhere(char *s, struct ioword *iop)
4985 struct here *h, *lh;
4987 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4989 h = (struct here *) space(sizeof(struct here));
4993 h->h_tag = evalstr(s, DOSUB);
5003 for (lh = inhere; lh != NULL; lh = lh->h_next) {
5004 if (lh->h_next == 0) {
5010 iop->io_flag |= IOHERE | IOXHERE;
5011 for (s = h->h_tag; *s; s++) {
5013 iop->io_flag &= ~IOXHERE;
5017 h->h_dosub = iop->io_flag & IOXHERE;
5020 static void gethere(void)
5022 struct here *h, *hp;
5024 DBGPRINTF7(("GETHERE: enter...\n"));
5026 /* Scan here files first leaving inhere list in place */
5027 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5028 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5030 /* Make inhere list active - keep list intact for scraphere */
5032 hp->h_next = acthere;
5038 static void readhere(char **name, char *s, int ec)
5041 char tname[30] = ".msh_XXXXXX";
5044 char myline[LINELIM + 1];
5047 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5049 tf = mkstemp(tname);
5053 *name = strsave(tname, areanum);
5055 if (newenv(setjmp(errpt)) != 0)
5058 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5061 if (interactive && e.iop <= iostack) {
5062 #if ENABLE_FEATURE_EDITING
5063 current_prompt = cprompt->value;
5065 prs(cprompt->value);
5069 while ((c = my_getc(ec)) != '\n' && c) {
5072 if (thenext >= &myline[LINELIM]) {
5079 if (strcmp(s, myline) == 0 || c == 0)
5082 write(tf, myline, (int) (thenext - myline));
5085 prs("here document `");
5095 * open here temp file.
5096 * if unquoted here, expand here temp file into second temp file.
5098 static int herein(char *hname, int xdoll)
5104 /* Avoid longjmp clobbering */
5110 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5112 hf = open(hname, 0);
5118 char tname[30] = ".msh_XXXXXX";
5121 tf = mkstemp(tname);
5125 if (newenv(setjmp(errpt)) == 0) {
5126 PUSHIO(afile, hf, herechar);
5128 while ((c = subgetc(0, 0)) != 0) {
5130 write(tf, &c, sizeof c);
5136 tf = open(tname, 0);
5143 static void scraphere(void)
5147 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5149 for (h = inhere; h != NULL; h = h->h_next) {
5150 if (h->h_iop && h->h_iop->io_name)
5151 unlink(h->h_iop->io_name);
5156 /* unlink here temp files before a freearea(area) */
5157 static void freehere(int area)
5159 struct here *h, *hl;
5161 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5164 for (h = acthere; h != NULL; h = h->h_next)
5165 if (getarea((char *) h) >= area) {
5166 if (h->h_iop->io_name != NULL)
5167 unlink(h->h_iop->io_name);
5169 acthere = h->h_next;
5171 hl->h_next = h->h_next;
5177 /* -------- sh.c -------- */
5182 int msh_main(int argc, char **argv);
5183 int msh_main(int argc, char **argv)
5189 int (*iof) (struct ioarg *);
5191 PTR_TO_GLOBALS = xzalloc(sizeof(G));
5192 sharedbuf.id = AFID_NOBUF;
5193 mainbuf.id = AFID_NOBUF;
5195 elinep = line + sizeof(line) - 5;
5197 #if ENABLE_FEATURE_EDITING
5198 line_input_state = new_line_input_t(FOR_SHELL);
5201 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5207 assign(*ap++, !COPYV);
5208 for (ap = environ; *ap;)
5209 export(lookup(*ap++));
5214 shell = lookup("SHELL");
5215 if (shell->value == null)
5216 setval(shell, (char *)DEFAULT_SHELL);
5219 homedir = lookup("HOME");
5220 if (homedir->value == null)
5221 setval(homedir, "/");
5224 setval(lookup("$"), putn(getpid()));
5226 path = lookup("PATH");
5227 if (path->value == null) {
5229 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
5231 setval(path, "/bin:/usr/bin");
5235 ifs = lookup("IFS");
5236 if (ifs->value == null)
5237 setval(ifs, " \t\n");
5240 mshdbg_var = lookup("MSHDEBUG");
5241 if (mshdbg_var->value == null)
5242 setval(mshdbg_var, "0");
5245 prompt = lookup("PS1");
5246 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5247 if (prompt->value == null)
5249 setval(prompt, DEFAULT_USER_PROMPT);
5250 if (geteuid() == 0) {
5251 setval(prompt, DEFAULT_ROOT_PROMPT);
5252 prompt->status &= ~EXPORT;
5254 cprompt = lookup("PS2");
5255 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5256 if (cprompt->value == null)
5258 setval(cprompt, "> ");
5264 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5265 for (s = argv[0] + 1; *s; s++)
5268 prompt->status &= ~EXPORT;
5269 cprompt->status &= ~EXPORT;
5271 setval(cprompt, "");
5274 PUSHIO(aword, *++argv, iof = nlchar);
5282 /* standard input */
5286 prompt->status &= ~EXPORT;
5294 if (*s >= 'a' && *s <= 'z')
5302 if (iof == filechar && --argc > 0) {
5304 setval(cprompt, "");
5305 prompt->status &= ~EXPORT;
5306 cprompt->status &= ~EXPORT;
5308 /* Shell is non-interactive, activate printf-based debug */
5310 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5314 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5318 exit(1); /* Exit on error */
5324 /* This won't be true if PUSHIO has been called, say from newfile() above */
5325 if (e.iop < iostack) {
5326 PUSHIO(afile, 0, iof);
5327 if (isatty(0) && isatty(1) && !cflag) {
5329 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5331 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
5333 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
5335 printf("Enter 'help' for a list of built-in commands.\n\n");
5340 signal(SIGQUIT, qflag);
5341 if (name && name[0] == '-') {
5343 f = open(".profile", 0);
5346 f = open("/etc/profile", 0);
5351 signal(SIGTERM, sig);
5353 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5354 signal(SIGINT, onintr);
5359 for (ap = ++argv; --argc > 0;) {
5361 if (assign(*ap, !COPYV)) {
5362 dolc--; /* keyword */
5368 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5370 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
5373 if (interactive && e.iop <= iostack) {
5374 #if ENABLE_FEATURE_EDITING
5375 current_prompt = prompt->value;
5381 /* Ensure that getenv("PATH") stays current */
5382 setenv("PATH", path->value, 1);
5385 DBGPRINTF(("MSH_MAIN: returning.\n"));
5390 * Copyright (c) 1987,1997, Prentice Hall
5391 * All rights reserved.
5393 * Redistribution and use of the MINIX operating system in source and
5394 * binary forms, with or without modification, are permitted provided
5395 * that the following conditions are met:
5397 * Redistributions of source code must retain the above copyright
5398 * notice, this list of conditions and the following disclaimer.
5400 * Redistributions in binary form must reproduce the above
5401 * copyright notice, this list of conditions and the following
5402 * disclaimer in the documentation and/or other materials provided
5403 * with the distribution.
5405 * Neither the name of Prentice Hall nor the names of the software
5406 * authors or contributors may be used to endorse or promote
5407 * products derived from this software without specific prior
5408 * written permission.
5410 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5411 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5412 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5413 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5414 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5415 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5416 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5417 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5418 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5419 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5420 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5421 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.