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 int 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';
86 # include "busybox.h" /* for applet_names */
92 int mshdbg = MSHDEBUG;
94 #define DBGPRINTF(x) if (mshdbg>0) printf x
95 #define DBGPRINTF0(x) if (mshdbg>0) printf x
96 #define DBGPRINTF1(x) if (mshdbg>1) printf x
97 #define DBGPRINTF2(x) if (mshdbg>2) printf x
98 #define DBGPRINTF3(x) if (mshdbg>3) printf x
99 #define DBGPRINTF4(x) if (mshdbg>4) printf x
100 #define DBGPRINTF5(x) if (mshdbg>5) printf x
101 #define DBGPRINTF6(x) if (mshdbg>6) printf x
102 #define DBGPRINTF7(x) if (mshdbg>7) printf x
103 #define DBGPRINTF8(x) if (mshdbg>8) printf x
104 #define DBGPRINTF9(x) if (mshdbg>9) printf x
108 #define RCPRINTF(x) if (mshdbg_rc) printf x
113 #define DBGPRINTF0(x) ((void)0)
114 #define DBGPRINTF1(x) ((void)0)
115 #define DBGPRINTF2(x) ((void)0)
116 #define DBGPRINTF3(x) ((void)0)
117 #define DBGPRINTF4(x) ((void)0)
118 #define DBGPRINTF5(x) ((void)0)
119 #define DBGPRINTF6(x) ((void)0)
120 #define DBGPRINTF7(x) ((void)0)
121 #define DBGPRINTF8(x) ((void)0)
122 #define DBGPRINTF9(x) ((void)0)
124 #define RCPRINTF(x) ((void)0)
126 #endif /* MSHDEBUG */
129 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
130 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
131 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
133 # define DEFAULT_ROOT_PROMPT "# "
134 # define DEFAULT_USER_PROMPT "$ "
138 /* -------- sh.h -------- */
144 #define NPUSH 8 /* limit to input nesting */
147 #define NOFILE 20 /* Number of open files */
148 #define NUFILE 10 /* Number of user-accessible files */
149 #define FDBASE 10 /* First file usable by Shell */
152 * values returned by wait
154 #define WAITSIG(s) ((s) & 0177)
155 #define WAITVAL(s) (((s) >> 8) & 0377)
156 #define WAITCORE(s) (((s) & 0200) != 0)
159 * library and system definitions
161 typedef void xint; /* base type of jmp_buf, for not broken compilers */
166 #define NOBLOCK ((struct op *)NULL)
167 #define NOWORD ((char *)NULL)
168 #define NOWORDS ((char **)NULL)
169 #define NOPIPE ((int *)NULL)
175 short io_unit; /* unit affected */
176 short io_flag; /* action (below) */
177 char *io_name; /* file name */
180 #define IOREAD 1 /* < */
181 #define IOHERE 2 /* << (here file) */
182 #define IOWRITE 4 /* > */
183 #define IOCAT 8 /* >> */
184 #define IOXHERE 16 /* ${}, ` in << */
185 #define IODUP 32 /* >&digit */
186 #define IOCLOSE 64 /* >&- */
188 #define IODEFAULT (-1) /* token for default IO unit */
192 * Description of a command or an operation on commands.
193 * Might eventually use a union.
196 smallint type; /* operation type, see Txxxx below */
197 char **words; /* arguments to a command */
198 struct ioword **ioact; /* IO actions (eg, < > >>) */
201 char *str; /* identifier for case and for */
204 #define TCOM 1 /* command */
205 #define TPAREN 2 /* (c-list) */
206 #define TPIPE 3 /* a | b */
207 #define TLIST 4 /* a [&;] b */
208 #define TOR 5 /* || */
209 #define TAND 6 /* && */
217 #define TPAT 14 /* pattern in case */
218 #define TBRACE 15 /* {c-list} */
219 #define TASYNC 16 /* c & */
220 /* Added to support "." file expansion */
223 /* Strings for names to make debug easier */
225 static const char *const T_CMD_NAMES[] = {
247 #define AREASIZE (90000)
250 * flags to control evaluation of words
252 #define DOSUB 1 /* interpret $, `, and quotes */
253 #define DOBLANK 2 /* perform blank interpretation */
254 #define DOGLOB 4 /* interpret [?* */
255 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
256 #define DOTRIM 16 /* trim resulting string */
258 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
263 struct brkcon *nextlev;
267 static smallint trapset; /* trap pending (signal number) */
269 static smallint yynerrs; /* yacc (flag) */
271 /* moved to G: static char line[LINELIM]; */
273 #if ENABLE_FEATURE_EDITING
274 static char *current_prompt;
275 static line_input_t *line_input_state;
282 static const char *rexecve(char *c, char **v, char **envp);
283 static char *evalstr(char *cp, int f);
284 static char *putn(int n);
285 static char *unquote(char *as);
286 static int rlookup(char *n);
287 static struct wdblock *glob(char *cp, struct wdblock *wb);
288 static int my_getc(int ec);
289 static int subgetc(char ec, int quoted);
290 static char **makenv(int all, struct wdblock *wb);
291 static char **eval(char **ap, int f);
292 static int setstatus(int s);
293 static int waitfor(int lastpid, int canintr);
295 static void onintr(int s); /* SIGINT handler */
297 static int newenv(int f);
298 static void quitenv(void);
299 static void next(int f);
300 static void setdash(void);
301 static void onecommand(void);
302 static void runtrap(int i);
305 /* -------- area stuff -------- */
307 #define REGSIZE sizeof(struct region)
309 /* #define SHRINKBY (64) */
313 #define ALIGN (sizeof(int)-1)
322 /* -------- grammar stuff -------- */
347 /* Added for "." file expansion */
350 #define YYERRCODE 300
353 #define CONTIN 01 /* skip new lines to complete command */
355 static struct op *pipeline(int cf);
356 static struct op *andor(void);
357 static struct op *c_list(void);
358 static int synio(int cf);
359 static void musthave(int c, int cf);
360 static struct op *simple(void);
361 static struct op *nested(int type, int mark);
362 static struct op *command(int cf);
363 static struct op *dogroup(int onlydone);
364 static struct op *thenpart(void);
365 static struct op *elsepart(void);
366 static struct op *caselist(void);
367 static struct op *casepart(void);
368 static char **pattern(void);
369 static char **wordlist(void);
370 static struct op *list(struct op *t1, struct op *t2);
371 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
372 static struct op *newtp(void);
373 static struct op *namelist(struct op *t);
374 static char **copyw(void);
375 static void word(char *cp);
376 static struct ioword **copyio(void);
377 static struct ioword *io(int u, int f, char *cp);
378 static int yylex(int cf);
379 static int collect(int c, int c1);
380 static int dual(int c);
381 static void diag(int ec);
382 static char *tree(unsigned size);
384 /* -------- var.h -------- */
393 #define COPYV 1 /* flag to setval, suggesting copy */
394 #define RONLY 01 /* variable is read-only */
395 #define EXPORT 02 /* variable is to be exported */
396 #define GETCELL 04 /* name & value space was got with getcell */
398 static int yyparse(void);
401 /* -------- io.h -------- */
404 unsigned id; /* buffer id */
405 char buf[512]; /* buffer */
406 char *bufp; /* pointer into buffer */
407 char *ebufp; /* pointer to end of buffer */
410 /* possible arguments to an IO function */
414 int afile; /* file descriptor */
415 unsigned afid; /* buffer id */
416 off_t afpos; /* file position */
417 struct iobuf *afbuf; /* buffer for this file */
420 /* an input generator's state */
422 int (*iofn) (struct ioarg *, struct io *);
425 char prev; /* previous character read by readc() */
426 char nlcount; /* for `'s */
427 char xchar; /* for `'s */
428 char task; /* reason for pushed IO */
431 #define XOTHER 0 /* none of the below */
432 #define XDOLL 1 /* expanding ${} */
433 #define XGRAVE 2 /* expanding `'s */
434 #define XIO 3 /* file IO */
438 * input generators for IO structure
440 static int nlchar(struct ioarg *ap);
441 static int strchar(struct ioarg *ap);
442 static int qstrchar(struct ioarg *ap);
443 static int filechar(struct ioarg *ap);
444 static int herechar(struct ioarg *ap);
445 static int linechar(struct ioarg *ap);
446 static int gravechar(struct ioarg *ap, struct io *iop);
447 static int qgravechar(struct ioarg *ap, struct io *iop);
448 static int dolchar(struct ioarg *ap);
449 static int wdchar(struct ioarg *ap);
450 static void scraphere(void);
451 static void freehere(int area);
452 static void gethere(void);
453 static void markhere(char *s, struct ioword *iop);
454 static int herein(char *hname, int xdoll);
455 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
458 static int eofc(void);
459 static int readc(void);
460 static void unget(int c);
461 static void ioecho(char c);
467 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
468 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
469 static int remap(int fd);
470 static int openpipe(int *pv);
471 static void closepipe(int *pv);
472 static struct io *setbase(struct io *ip);
474 /* -------- word.h -------- */
476 #define NSTART 16 /* default number of words to allow for initially */
481 /* bounds are arbitrary */
485 static struct wdblock *addword(char *wd, struct wdblock *wb);
486 static struct wdblock *newword(int nw);
487 static char **getwords(struct wdblock *wb);
489 /* -------- misc stuff -------- */
491 static int forkexec(struct op *t, int *pin, int *pout, int no_fork, char **wp);
492 static int execute(struct op *t, int *pin, int *pout, int no_fork);
493 static int iosetup(struct ioword *iop, int pipein, int pipeout);
494 static void brkset(struct brkcon *bc);
495 static int dolabel(struct op *t);
496 static int dohelp(struct op *t);
497 static int dochdir(struct op *t);
498 static int doshift(struct op *t);
499 static int dologin(struct op *t);
500 static int doumask(struct op *t);
501 static int doexec(struct op *t);
502 static int dodot(struct op *t);
503 static int dowait(struct op *t);
504 static int doread(struct op *t);
505 static int doeval(struct op *t);
506 static int dotrap(struct op *t);
507 static int getsig(char *s);
508 static void setsig(int n, sighandler_t f);
509 static int getn(char *as);
510 static int dobreak(struct op *t);
511 static int docontinue(struct op *t);
512 static int brkcontin(char *cp, int val);
513 static int doexit(struct op *t);
514 static int doexport(struct op *t);
515 static int doreadonly(struct op *t);
516 static void rdexp(char **wp, void (*f) (struct var *), int key);
517 static void badid(char *s);
518 static int doset(struct op *t);
519 static void varput(char *s, int out);
520 static int dotimes(struct op *t);
521 static int expand(const char *cp, struct wdblock **wbp, int f);
522 static char *blank(int f);
523 static int dollar(int quoted);
524 static int grave(int quoted);
525 static void globname(char *we, char *pp);
526 static char *generate(char *start1, char *end1, char *middle, char *end);
527 static int anyspcl(struct wdblock *wb);
528 static int xstrcmp(char *p1, char *p2);
529 static void glob0(char *a0, unsigned a1, int a2,
530 int (*a3) (char *, char *));
531 static void readhere(char **name, char *s, int ec);
532 static int xxchar(struct ioarg *ap);
537 struct ioword *h_iop;
541 static const char *const signame[] = {
544 NULL, /* interrupt */
546 "Illegal instruction",
550 "Floating Point Exception",
555 NULL, /* broken pipe */
561 typedef int (*builtin_func_ptr)(struct op *);
565 builtin_func_ptr builtinfunc;
568 static const struct builtincmd builtincmds[] = {
571 { "break" , dobreak },
573 { "continue", docontinue },
577 { "export" , doexport },
579 { "login" , dologin },
580 { "newgrp" , dologin },
582 { "readonly", doreadonly },
584 { "shift" , doshift },
585 { "times" , dotimes },
587 { "umask" , doumask },
592 static struct op *scantree(struct op *);
593 static struct op *dowholefile(int, int);
600 static smallint gflg; /* (seems to be a parse error indicator) */
601 static smallint interactive; /* Is this an interactive shell */
602 static smallint execflg;
603 static smallint isbreak; /* "break" statement was seen */
604 static int multiline; /* '\n' changed to ';' (counter) */
605 static struct op *outtree; /* result from parser */
608 static struct brkcon *brklist;
609 static struct wdblock *wdlist;
610 static struct wdblock *iolist;
613 static struct var *mshdbg_var;
615 static struct var *vlist; /* dictionary */
616 static struct var *homedir; /* home directory */
617 static struct var *prompt; /* main prompt */
618 static struct var *cprompt; /* continuation prompt */
619 static struct var *path; /* search path for commands */
620 static struct var *shell; /* shell to interpret command files */
621 static struct var *ifs; /* field separators */
623 static int areanum; /* current allocation area */
624 static smallint intr; /* interrupt pending (bool) */
625 static smallint heedint = 1; /* heed interrupt signals (bool) */
627 static char *null = (char*)""; /* null value for variable */
628 static void (*qflag)(int) = SIG_IGN;
632 static int iounit = IODEFAULT;
633 static YYSTYPE yylval;
634 static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
636 static struct here *inhere; /* list of hear docs while parsing */
637 static struct here *acthere; /* list of active here documents */
638 static struct region *areabot; /* bottom of area */
639 static struct region *areatop; /* top of area */
640 static struct region *areanxt; /* starting point of scan */
642 static void *brkaddr;
644 #define AFID_NOBUF (~0)
649 * parsing & execution environment
655 xint *errpt; /* void * */
662 struct env global_env;
663 struct ioarg temparg; // = { .afid = AFID_NOBUF }; /* temporary for PUSHIO */
664 unsigned bufid; // = AFID_ID; /* buffer id counter */
665 char ourtrap[_NSIG + 1];
666 char *trap[_NSIG + 1];
667 struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
668 struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
669 struct ioarg ioargstack[NPUSH];
673 * -k: look for name=value everywhere on command line
675 * -t: exit after reading and executing one command
678 * -u: unset variables net diagnostic
680 char flags['z' - 'a' + 1];
681 char filechar_cmdbuf[BUFSIZ];
683 char child_cmd[LINELIM];
685 struct io iostack[NPUSH];
687 char grave__var_name[LINELIM];
688 char grave__alt_value[LINELIM];
691 #define G (*ptr_to_globals)
692 #define global_env (G.global_env )
693 #define temparg (G.temparg )
694 #define bufid (G.bufid )
695 #define ourtrap (G.ourtrap )
696 #define trap (G.trap )
697 #define sharedbuf (G.sharedbuf )
698 #define mainbuf (G.mainbuf )
699 #define ioargstack (G.ioargstack )
700 /* this looks weird, but is OK ... we index FLAG with 'a'...'z' */
701 #define FLAG (G.flags - 'a' )
702 #define filechar_cmdbuf (G.filechar_cmdbuf)
703 #define line (G.line )
704 #define child_cmd (G.child_cmd )
705 #define iostack (G.iostack )
706 #define INIT_G() do { \
707 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
708 global_env.linep = line; \
709 global_env.iobase = iostack; \
710 global_env.iop = iostack - 1; \
711 global_env.iofd = FDBASE; \
712 temparg.afid = AFID_NOBUF; \
717 /* in substitution */
718 #define INSUB() (global_env.iop->task == XGRAVE || global_env.iop->task == XDOLL)
720 #define RUN(what, arg, gen) ((temparg.what = (arg)), run(&temparg, (gen)))
723 void print_t(struct op *t)
725 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
726 T_CMD_NAMES[t->type], t->words, t->ioact));
729 DBGPRINTF(("T: W1: %s", t->words[0]));
733 void print_tree(struct op *head)
736 DBGPRINTF(("PRINT_TREE: no tree\n"));
740 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
744 print_tree(head->left);
747 print_tree(head->right);
749 #endif /* MSHDEBUG */
755 static void prs(const char *s)
758 write(2, s, strlen(s));
761 static void prn(unsigned u)
766 static void echo(char **wp)
771 for (i = 0; wp[i]; i++) {
779 static void closef(int i)
785 static void closeall(void)
789 for (u = NUFILE; u < NOFILE;)
794 /* fail but return to process next command */
795 static void fail(void) ATTRIBUTE_NORETURN;
796 static void fail(void)
802 /* abort shell (or fail in subshell) */
803 static void leave(void) ATTRIBUTE_NORETURN;
804 static void leave(void)
806 DBGPRINTF(("LEAVE: leave called!\n"));
817 static void warn(const char *s)
828 static void err(const char *s)
835 if (global_env.errpt)
836 longjmp(global_env.errpt, 1);
838 global_env.iop = global_env.iobase = iostack;
842 /* -------- area.c -------- */
845 * All memory between (char *)areabot and (char *)(areatop+1) is
846 * exclusively administered by the area management routines.
847 * It is assumed that sbrk() and brk() manipulate the high end.
851 void * __q = (void *)-1; \
852 if (brkaddr + (int)(X) < brktop) { \
854 brkaddr += (int)(X); \
859 static void initarea(void)
861 brkaddr = xmalloc(AREASIZE);
862 brktop = brkaddr + AREASIZE;
864 while ((long) sbrk(0) & ALIGN)
866 areabot = (struct region *) sbrk(REGSIZE);
868 areabot->next = areabot;
869 areabot->area = BUSY;
874 static char *getcell(unsigned nbytes)
877 struct region *p, *q;
884 /* silly and defeats the algorithm */
886 * round upwards and add administration area
888 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
891 if (p->area > areanum) {
895 while ((q = p->next)->area > areanum && q != areanxt)
898 * exit loop if cell big enough
907 i = nregio >= GROWBY ? nregio : GROWBY;
908 p = (struct region *) sbrk(i * REGSIZE);
909 if (p == (struct region *) -1)
914 abort(); /* allocated areas are contiguous */
924 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
926 areanxt = p + nregio;
929 * split into requested area and rest
931 if (areanxt + 1 > q) {
933 abort(); /* insufficient space left for admin */
936 areanxt->area = FREE;
940 return (char *) (p + 1);
943 static void freecell(char *cp)
947 p = (struct region *) cp;
955 #define DELETE(obj) freecell((char *)obj)
957 static void freearea(int a)
959 struct region *p, *top;
962 for (p = areabot; p != top; p = p->next)
967 static void setarea(char *cp, int a)
971 p = (struct region *) cp;
976 static int getarea(char *cp)
978 return ((struct region *) cp - 1)->area;
981 static void garbage(void)
983 struct region *p, *q, *top;
986 for (p = areabot; p != top; p = p->next) {
987 if (p->area > areanum) {
988 while ((q = p->next)->area > areanum)
994 if (areatop >= q + SHRINKBY && q->area > areanum) {
995 brk((char *) (q + 1));
1003 static char *space(int n)
1009 err("out of string space");
1013 static char *strsave(const char *s, int a)
1017 cp = space(strlen(s) + 1);
1019 // FIXME: I highly doubt this is good.
1028 /* -------- var.c -------- */
1030 static int eqname(const char *n1, const char *n2)
1032 for (; *n1 != '=' && *n1 != '\0'; n1++)
1035 return *n2 == '\0' || *n2 == '=';
1038 static const char *findeq(const char *cp)
1040 while (*cp != '\0' && *cp != '=')
1046 * Find the given name in the dictionary
1047 * and return its value. If the name was
1048 * not previously there, enter it now and
1049 * return a null value.
1051 static struct var *lookup(const char *n)
1053 // FIXME: dirty hack
1054 static struct var dummy;
1062 dummy.name = (char*)n;
1063 for (c = 0; isdigit(*n) && c < 1000; n++)
1064 c = c * 10 + *n - '0';
1065 dummy.status = RONLY;
1066 dummy.value = (c <= dolc ? dolv[c] : null);
1070 for (vp = vlist; vp; vp = vp->next)
1071 if (eqname(vp->name, n))
1075 vp = (struct var *) space(sizeof(*vp));
1076 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1077 dummy.name = dummy.value = (char*)"";
1082 while ((*xp = *n++) != '\0' && *xp != '=')
1086 setarea((char *) vp, 0);
1087 setarea((char *) vp->name, 0);
1090 vp->status = GETCELL;
1096 * if name is not NULL, it must be
1097 * a prefix of the space `val',
1099 * this is all so that exporting
1100 * values is reasonably painless.
1102 static void nameval(struct var *vp, const char *val, const char *name)
1108 if (vp->status & RONLY) {
1110 while (*xp && *xp != '=')
1111 fputc(*xp++, stderr);
1112 err(" is read-only");
1117 xp = space(strlen(vp->name) + strlen(val) + 2);
1120 /* make string: name=value */
1124 while ((*xp = *cp++) != '\0' && *xp != '=')
1131 if (vp->status & GETCELL)
1132 freecell(vp->name); /* form new string `name=value' */
1133 vp->name = (char*)name;
1134 vp->value = (char*)val;
1139 * give variable at `vp' the value `val'.
1141 static void setval(struct var *vp, const char *val)
1143 nameval(vp, val, NULL);
1146 static void export(struct var *vp)
1148 vp->status |= EXPORT;
1151 static void ronly(struct var *vp)
1153 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1154 vp->status |= RONLY;
1157 static int isassign(const char *s)
1160 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1163 /* no isalpha() - we shouldn't use locale */
1164 /* c | 0x20 - lowercase (Latin) letters */
1165 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1176 && (unsigned)(c - '0') > 9 /* not number */
1177 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1184 static int assign(const char *s, int cf)
1189 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1191 if (!isalpha(*s) && *s != '_')
1193 for (cp = s; *cp != '='; cp++)
1194 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1197 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1199 vp->status &= ~GETCELL;
1203 static int checkname(char *cp)
1205 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1207 if (!isalpha(*cp++) && *(cp - 1) != '_')
1210 if (!isalnum(*cp++) && *(cp - 1) != '_')
1215 static void putvlist(int f, int out)
1219 for (vp = vlist; vp; vp = vp->next) {
1220 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1221 if (vp->status & EXPORT)
1222 write(out, "export ", 7);
1223 if (vp->status & RONLY)
1224 write(out, "readonly ", 9);
1225 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1226 write(out, "\n", 1);
1235 static void sig(int i)
1241 static void runtrap(int i)
1246 if (trapstr == NULL)
1252 RUN(aword, trapstr, nlchar);
1256 static void setdash(void)
1260 char m['z' - 'a' + 1];
1263 for (c = 'a'; c <= 'z'; c++)
1267 setval(lookup("-"), m);
1270 static int newfile(char *s)
1274 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1277 if (NOT_LONE_DASH(s)) {
1278 DBGPRINTF(("NEWFILE: s is %s\n", s));
1279 f = open(s, O_RDONLY);
1282 err(": cannot open");
1292 struct op *scantree(struct op *head)
1299 if (head->left != NULL) {
1300 dotnode = scantree(head->left);
1305 if (head->right != NULL) {
1306 dotnode = scantree(head->right);
1311 if (head->words == NULL)
1314 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1316 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1317 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1325 static void onecommand(void)
1330 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1332 while (global_env.oenv)
1341 global_env.errpt = 0;
1342 global_env.linep = line;
1350 setjmp(failpt); /* Bruce Evans' fix */
1352 if (setjmp(failpt) || yyparse() || intr) {
1353 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1355 while (global_env.oenv)
1358 if (!interactive && intr)
1371 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1373 execute(outtree, NOPIPE, NOPIPE, /* no_fork: */ 0);
1376 if (!interactive && intr) {
1388 static int newenv(int f)
1392 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1399 ep = (struct env *) space(sizeof(*ep));
1401 while (global_env.oenv)
1406 global_env.oenv = ep;
1407 global_env.errpt = errpt;
1412 static void quitenv(void)
1417 DBGPRINTF(("QUITENV: global_env.oenv=%p\n", global_env.oenv));
1419 ep = global_env.oenv;
1421 fd = global_env.iofd;
1423 /* should close `'d files */
1425 while (--fd >= global_env.iofd)
1431 * Is character c in s?
1433 static int any(int c, const char *s)
1442 * Is any character from s1 in s2?
1444 static int anys(const char *s1, const char *s2)
1452 static char *putn(int n)
1457 static void next(int f)
1459 PUSHIO(afile, f, filechar);
1462 static void onintr(int s) /* ANSI C requires a parameter */
1464 signal(SIGINT, onintr);
1471 } else if (heedint) {
1478 /* -------- gmatch.c -------- */
1480 * int gmatch(string, pattern)
1481 * char *string, *pattern;
1483 * Match a pattern as in sh(1).
1488 #define QMASK (CMASK & ~QUOTE)
1489 #define NOT '!' /* might use ^ */
1491 static const char *cclass(const char *p, int sub)
1493 int c, d, not, found;
1503 if (p[1] == '-' && p[2] != ']') {
1508 if (c == sub || (c <= sub && sub <= d))
1510 } while (*++p != ']');
1511 return found ? p + 1 : NULL;
1514 static int gmatch(const char *s, const char *p)
1518 if (s == NULL || p == NULL)
1521 while ((pc = *p++ & CMASK) != '\0') {
1538 if (*p == '\0' || gmatch(s, p))
1540 } while (*s++ != '\0');
1544 if (sc != (pc & ~QUOTE))
1552 /* -------- csyn.c -------- */
1554 * shell: syntax (C version)
1557 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1558 static void yyerror(const char *s)
1561 if (interactive && global_env.iop <= iostack) {
1563 while (eofc() == 0 && yylex(0) != '\n')
1570 static void zzerr(void) ATTRIBUTE_NORETURN;
1571 static void zzerr(void)
1573 yyerror("syntax error");
1578 DBGPRINTF7(("YYPARSE: enter...\n"));
1585 return yynerrs; /* 0/1 */
1588 static struct op *pipeline(int cf)
1593 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1597 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1600 while ((c = yylex(0)) == '|') {
1601 p = command(CONTIN);
1603 DBGPRINTF8(("PIPELINE: error!\n"));
1607 if (t->type != TPAREN && t->type != TCOM) {
1608 /* shell statement */
1609 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1612 t = block(TPIPE, t, p, NOWORDS);
1617 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1621 static struct op *andor(void)
1626 DBGPRINTF7(("ANDOR: enter...\n"));
1630 DBGPRINTF9(("ANDOR: t=%p\n", t));
1633 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1634 p = pipeline(CONTIN);
1636 DBGPRINTF8(("ANDOR: error!\n"));
1640 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1646 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1650 static struct op *c_list(void)
1655 DBGPRINTF7(("C_LIST: enter...\n"));
1662 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1664 while ((c = yylex(0)) == ';' || c == '&'
1665 || (multiline && c == '\n')) {
1673 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1681 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1685 static int synio(int cf)
1691 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1694 if (c != '<' && c != '>') {
1701 iop = io(iounit, i, yylval.cp);
1705 markhere(yylval.cp, iop);
1707 DBGPRINTF7(("SYNIO: returning 1\n"));
1711 static void musthave(int c, int cf)
1713 peeksym = yylex(cf);
1715 DBGPRINTF7(("MUSTHAVE: error!\n"));
1722 static struct op *simple(void)
1728 switch (peeksym = yylex(0)) {
1749 static struct op *nested(int type, int mark)
1753 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1759 return block(type, t, NOBLOCK, NOWORDS);
1762 static struct op *command(int cf)
1765 struct wdblock *iosave;
1768 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1794 t = nested(TPAREN, ')');
1798 t = nested(TBRACE, '}');
1808 t->words = wordlist();
1810 if (c != '\n' && c != ';')
1812 t->left = dogroup(0);
1820 t->type = (c == WHILE ? TWHILE : TUNTIL);
1822 t->right = dogroup(1);
1834 musthave(IN, CONTIN);
1837 t->left = caselist();
1848 t->right = thenpart();
1857 musthave(WORD, 0); /* gets name of file */
1858 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1860 word(yylval.cp); /* add word to wdlist */
1861 word(NOWORD); /* terminate wdlist */
1862 t->words = copyw(); /* dup wdlist */
1872 DBGPRINTF(("COMMAND: returning %p\n", t));
1877 static struct op *dowholefile(int type, int mark)
1881 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1886 t = block(type, t, NOBLOCK, NOWORDS);
1887 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1891 static struct op *dogroup(int onlydone)
1897 if (c == DONE && onlydone)
1906 static struct op *thenpart(void)
1917 /*t->type = 0; - newtp() did this */
1919 if (t->left == NULL)
1921 t->right = elsepart();
1925 static struct op *elsepart(void)
1930 switch (c = yylex(0)) {
1941 t->right = thenpart();
1950 static struct op *caselist(void)
1955 while ((peeksym = yylex(CONTIN)) != ESAC) {
1956 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1957 t = list(t, casepart());
1960 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1964 static struct op *casepart(void)
1968 DBGPRINTF7(("CASEPART: enter...\n"));
1972 t->words = pattern();
1975 peeksym = yylex(CONTIN);
1976 if (peeksym != ESAC)
1977 musthave(BREAK, CONTIN);
1979 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
1984 static char **pattern(void)
2001 static char **wordlist(void)
2011 while ((c = yylex(0)) == WORD)
2019 * supporting functions
2021 static struct op *list(struct op *t1, struct op *t2)
2023 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2030 return block(TLIST, t1, t2, NOWORDS);
2033 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2037 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2045 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1, t2));
2050 /* See if given string is a shell multiline (FOR, IF, etc) */
2051 static int rlookup(char *n)
2057 static const struct res restab[] = {
2080 const struct res *rp;
2082 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2084 for (rp = restab; rp->r_name[0]; rp++)
2085 if (strcmp(rp->r_name, n) == 0) {
2086 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2087 return rp->r_val; /* Return numeric code for shell multiline */
2090 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2091 return 0; /* Not a shell multiline */
2094 static struct op *newtp(void)
2098 t = (struct op *) tree(sizeof(*t));
2099 memset(t, 0, sizeof(*t));
2101 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2106 static struct op *namelist(struct op *t)
2108 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2109 T_CMD_NAMES[t->type], iolist));
2112 iolist = addword((char *) NULL, iolist);
2113 t->ioact = copyio();
2117 if (t->type != TCOM) {
2118 if (t->type != TPAREN && t->ioact != NULL) {
2119 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2120 t->ioact = t->left->ioact;
2121 t->left->ioact = NULL;
2132 static char **copyw(void)
2136 wd = getwords(wdlist);
2141 static void word(char *cp)
2143 wdlist = addword(cp, wdlist);
2146 static struct ioword **copyio(void)
2148 struct ioword **iop;
2150 iop = (struct ioword **) getwords(iolist);
2155 static struct ioword *io(int u, int f, char *cp)
2159 iop = (struct ioword *) tree(sizeof(*iop));
2163 iolist = addword((char *) iop, iolist);
2167 static int yylex(int cf)
2184 global_env.linep = line;
2187 line[LINELIM - 1] = '\0';
2190 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2195 if (any(c, "0123456789")) {
2198 if (c1 == '<' || c1 == '>') {
2202 *global_env.linep++ = c;
2207 case '#': /* Comment, skip to next newline or End-of-string */
2208 while ((c = my_getc(0)) != '\0' && c != '\n');
2213 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2217 DBGPRINTF9(("YYLEX: found $\n"));
2218 *global_env.linep++ = c;
2221 c = collect(c, '}');
2240 /* If more chars process them, else return NULL char */
2258 if (multiline || cf & CONTIN) {
2259 if (interactive && global_env.iop <= iostack) {
2260 #if ENABLE_FEATURE_EDITING
2261 current_prompt = cprompt->value;
2263 prs(cprompt->value);
2280 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2281 if (global_env.linep >= elinep)
2282 err("word too long");
2284 *global_env.linep++ = c;
2289 if (any(c, "\"'`$"))
2292 *global_env.linep++ = '\0';
2302 yylval.cp = strsave(line, areanum);
2307 static int collect(int c, int c1)
2311 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2313 *global_env.linep++ = c;
2314 while ((c = my_getc(c1)) != c1) {
2323 if (interactive && c == '\n' && global_env.iop <= iostack) {
2324 #if ENABLE_FEATURE_EDITING
2325 current_prompt = cprompt->value;
2327 prs(cprompt->value);
2330 *global_env.linep++ = c;
2333 *global_env.linep++ = c;
2335 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2340 /* "multiline commands" helper func */
2341 /* see if next 2 chars form a shell multiline */
2342 static int dual(int c)
2347 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2349 *cp++ = c; /* c is the given "peek" char */
2350 *cp++ = my_getc(0); /* get next char of input */
2351 *cp = '\0'; /* add EOS marker */
2353 c = rlookup(s); /* see if 2 chars form a shell multiline */
2355 unget(*--cp); /* String is not a shell multiline, put peek char back */
2357 return c; /* String is multiline, return numeric multiline (restab) code */
2360 static void diag(int ec)
2364 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2367 if (c == '>' || c == '<') {
2370 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2373 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2374 if (c != '&' || yylval.i == IOHERE)
2380 static char *tree(unsigned size)
2386 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2387 prs("command line too complicated\n");
2398 /* -------- exec.c -------- */
2400 static struct op **find1case(struct op *t, const char *w)
2408 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2412 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2413 T_CMD_NAMES[t->type]));
2415 if (t->type == TLIST) {
2416 tp = find1case(t->left, w);
2418 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2421 t1 = t->right; /* TPAT */
2425 for (wp = t1->words; *wp;) {
2426 cp = evalstr(*wp++, DOSUB);
2427 if (cp && gmatch(w, cp)) {
2428 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2434 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2438 static struct op *findcase(struct op *t, const char *w)
2442 tp = find1case(t, w);
2443 return tp != NULL ? *tp : NULL;
2450 static int execute(struct op *t, int *pin, int *pout, int no_fork)
2453 volatile int i, rv, a;
2457 struct op *outtree_save;
2461 /* Avoid longjmp clobbering */
2466 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2470 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2471 t->type, T_CMD_NAMES[t->type],
2472 ((t->words == NULL) ? "NULL" : t->words[0])));
2478 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2483 DBGPRINTF3(("EXECUTE: TDOT\n"));
2485 outtree_save = outtree;
2487 newfile(evalstr(t->words[0], DOALL));
2489 t->left = dowholefile(TLIST, 0);
2492 outtree = outtree_save;
2495 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2497 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2501 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2505 rv = forkexec(t, pin, pout, no_fork, wp);
2515 pv[0] = remap(pv[0]);
2516 pv[1] = remap(pv[1]);
2517 (void) execute(t->left, pin, pv, /* no_fork: */ 0);
2518 rv = execute(t->right, pv, pout, /* no_fork: */ 0);
2523 (void) execute(t->left, pin, pout, /* no_fork: */ 0);
2524 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2529 smallint hinteractive = interactive;
2531 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2534 if (i == 0) { /* child */
2535 signal(SIGINT, SIG_IGN);
2536 signal(SIGQUIT, SIG_IGN);
2538 signal(SIGTERM, SIG_DFL);
2542 xopen(bb_dev_null, O_RDONLY);
2544 _exit(execute(t->left, pin, pout, /* no_fork: */ 1));
2546 interactive = hinteractive;
2548 setval(lookup("!"), putn(i));
2562 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2564 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2565 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2576 while (*wp++ != NULL);
2578 vp = lookup(t->str);
2579 while (setjmp(bc.brkpt))
2583 for (t1 = t->left; i-- && *wp != NULL;) {
2585 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2587 brklist = brklist->nextlev;
2592 while (setjmp(bc.brkpt))
2597 while ((execute(t1, pin, pout, /* no_fork: */ 0) == 0) == (t->type == TWHILE))
2598 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2599 brklist = brklist->nextlev;
2604 if (t->right != NULL) {
2605 rv = !execute(t->left, pin, pout, /* no_fork: */ 0) ?
2606 execute(t->right->left, pin, pout, /* no_fork: */ 0) :
2607 execute(t->right->right, pin, pout, /* no_fork: */ 0);
2612 cp = evalstr(t->str, DOSUB | DOTRIM);
2616 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2617 ((t->str == NULL) ? "NULL" : t->str),
2618 ((cp == NULL) ? "NULL" : cp)));
2620 t1 = findcase(t->left, cp);
2622 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2623 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2624 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2633 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2641 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2654 if (interactive && intr) {
2665 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2669 static builtin_func_ptr inbuilt(const char *s)
2671 const struct builtincmd *bp;
2673 for (bp = builtincmds; bp->name; bp++)
2674 if (strcmp(bp->name, s) == 0)
2675 return bp->builtinfunc;
2679 static int forkexec(struct op *t, int *pin, int *pout, int no_fork, char **wp)
2683 builtin_func_ptr bltin = NULL;
2684 const char *bltin_name = NULL;
2686 struct ioword **iopp;
2694 smallint hinteractive;
2697 struct brkcon *hbrklist;
2700 /* Avoid longjmp clobbering */
2710 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, no_fork %d\n", t, pin,
2712 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2713 ((t->words == NULL) ? "NULL" : t->words[0])));
2716 if (t->type == TCOM) {
2717 while (*wp++ != NULL)
2721 /* strip all initial assignments */
2722 /* FIXME: not correct wrt PATH=yyy command etc */
2724 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2726 echo(cp ? wp : owp);
2730 if (t->ioact == NULL) {
2731 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2733 DBGPRINTF(("FORKEXEC: returning setstatus(0)\n"));
2734 return setstatus(0);
2736 } else { /* cp != NULL */
2738 bltin = inbuilt(cp);
2744 DBGPRINTF(("FORKEXEC: bltin %p, no_fork %d, owp %p\n", bltin,
2746 /* Don't fork if it is a lone builtin (not in pipe)
2747 * OR we are told to _not_ fork */
2748 if ((!bltin || pin || pout) /* not lone bltin AND */
2749 && !no_fork /* not told to avoid fork */
2751 /* Save values in case child alters them after vfork */
2755 hinteractive = interactive;
2760 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2763 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2767 if (newpid > 0) { /* Parent */
2768 /* Restore values */
2772 interactive = hinteractive;
2778 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2782 DBGPRINTF(("FORKEXEC: child process, bltin=%p (%s)\n", bltin, bltin_name));
2784 signal(SIGINT, SIG_IGN);
2785 signal(SIGQUIT, SIG_IGN);
2796 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2801 xmove_fd(pin[0], 0);
2806 xmove_fd(pout[1], 1);
2813 if (bltin && bltin != doexec) {
2815 err(": cannot redirect shell command");
2821 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2822 /* system-detected error */
2831 if (forked || pin || pout) {
2832 /* Builtin in pipe: disallowed */
2833 /* TODO: allow "exec"? */
2835 err(": cannot run builtin as part of pipe");
2840 i = setstatus(bltin(t));
2843 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2847 /* should use FIOCEXCL */
2848 for (i = FDBASE; i < NOFILE; i++)
2851 signal(SIGINT, SIG_DFL);
2852 signal(SIGQUIT, SIG_DFL);
2855 if (t->type == TPAREN)
2856 _exit(execute(t->left, NOPIPE, NOPIPE, /* no_fork: */ 1));
2860 cp = rexecve(wp[0], wp, makenv(0, NULL));
2867 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", getpid()));
2875 * 0< 1> are ignored as required
2878 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2884 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2887 if (iop->io_unit == IODEFAULT) /* take default */
2888 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2890 if (pipein && iop->io_unit == 0)
2893 if (pipeout && iop->io_unit == 1)
2896 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2897 if ((iop->io_flag & IOHERE) == 0) {
2898 cp = iop->io_name; /* huh?? */
2899 cp = evalstr(cp, DOSUB | DOTRIM);
2904 if (iop->io_flag & IODUP) {
2905 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2907 err(": illegal >& argument");
2911 iop->io_flag = IOCLOSE;
2912 iop->io_flag &= ~(IOREAD | IOWRITE);
2915 switch (iop->io_flag) {
2917 u = open(cp, O_RDONLY);
2921 case IOHERE | IOXHERE:
2922 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2923 cp = (char*)"here file";
2926 case IOWRITE | IOCAT:
2927 u = open(cp, O_WRONLY);
2929 lseek(u, (long) 0, SEEK_END);
2932 /* fall through to creation if >>file doesn't exist */
2935 u = creat(cp, 0666);
2939 u = dup2(*cp - '0', iop->io_unit);
2943 close(iop->io_unit);
2953 if (u != iop->io_unit) {
2954 dup2(u, iop->io_unit);
2961 * Enter a new loop level (marked for break/continue).
2963 static void brkset(struct brkcon *bc)
2965 bc->nextlev = brklist;
2970 * Wait for the last process created.
2971 * Print a message for each process found
2972 * that was killed by a signal.
2973 * Ignore interrupt signals while waiting
2974 * unless `canintr' is true.
2976 static int waitfor(int lastpid, int canintr)
2980 smallint oheedint = heedint;
2987 if (errno != EINTR || canintr)
2992 if (rv < ARRAY_SIZE(signame)) {
2993 if (signame[rv] != NULL) {
2994 if (pid != lastpid) {
3001 if (pid != lastpid) {
3010 prs(" - core dumped");
3011 if (rv >= ARRAY_SIZE(signame) || signame[rv])
3017 } while (pid != lastpid);
3032 static int setstatus(int s)
3035 setval(lookup("?"), putn(s));
3040 * PATH-searching interface to execve.
3041 * If getenv("PATH") were kept up-to-date,
3042 * execvp might be used.
3044 static const char *rexecve(char *c, char **v, char **envp)
3052 if (ENABLE_FEATURE_SH_STANDALONE) {
3053 if (find_applet_by_name(name) >= 0) {
3054 /* We have to exec here since we vforked. Running
3055 * run_applet_and_exit() won't work and bad things
3057 execve(bb_busybox_exec_path, v, envp);
3061 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3063 sp = any('/', c) ? "" : path->value;
3064 asis = (*sp == '\0');
3065 while (asis || *sp != '\0') {
3067 tp = global_env.linep;
3068 for (; *sp != '\0'; tp++) {
3071 asis = (*sp == '\0');
3075 if (tp != global_env.linep)
3077 for (i = 0; (*tp++ = c[i++]) != '\0';);
3079 DBGPRINTF3(("REXECVE: global_env.linep is %s\n", global_env.linep));
3081 execve(global_env.linep, v, envp);
3085 *v = global_env.linep;
3087 *v = global_env.linep;
3088 execve(DEFAULT_SHELL, v, envp);
3093 return (char *) bb_msg_memory_exhausted;
3096 return "argument list too long";
3099 return errno == ENOENT ? "not found" : "cannot execute";
3103 * Run the command produced by generator `f'
3104 * applied to stream `arg'.
3106 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3109 struct wdblock *swdlist;
3110 struct wdblock *siolist;
3116 /* Avoid longjmp clobbering */
3120 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3121 areanum, outtree, failpt));
3131 if (newenv(setjmp(errpt)) == 0) {
3135 global_env.iobase = global_env.iop;
3138 if (setjmp(failpt) == 0 && yyparse() == 0)
3139 rv = execute(outtree, NOPIPE, NOPIPE, /* no_fork: */ 0);
3142 DBGPRINTF(("RUN: error from newenv()!\n"));
3149 freearea(areanum--);
3154 /* -------- do.c -------- */
3157 * built-in commands: doX
3160 static int dohelp(struct op *t)
3163 const struct builtincmd *x;
3165 puts("\nBuilt-in commands:\n"
3166 "-------------------");
3171 col += printf("%c%s", ((col == 0) ? '\t' : ' '), x->name);
3178 #if ENABLE_FEATURE_SH_STANDALONE
3180 const char *applet = applet_names;
3183 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applet);
3188 applet += strlen(applet) + 1;
3193 return EXIT_SUCCESS;
3196 static int dolabel(struct op *t)
3201 static int dochdir(struct op *t)
3203 const char *cp, *er;
3207 cp = homedir->value;
3210 er = ": no home directory";
3215 er = ": bad directory";
3217 prs(cp != NULL ? cp : "cd");
3222 static int doshift(struct op *t)
3226 n = t->words[1] ? getn(t->words[1]) : 1;
3228 err("nothing to shift");
3234 setval(lookup("#"), putn(dolc));
3239 * execute login and newgrp directly
3241 static int dologin(struct op *t)
3246 signal(SIGINT, SIG_DFL);
3247 signal(SIGQUIT, SIG_DFL);
3249 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3256 static int doumask(struct op *t)
3265 printf("%04o\n", i);
3267 i = bb_strtou(cp, NULL, 8);
3269 err("umask: bad octal number");
3277 static int doexec(struct op *t)
3284 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++)
3291 if (setjmp(failpt) == 0)
3292 execute(t, NOPIPE, NOPIPE, /* no_fork: */ 1);
3298 static int dodot(struct op *t)
3306 DBGPRINTF(("DODOT: enter, t=%p, tleft %p, tright %p, global_env.linep is %s\n",
3307 t, t->left, t->right, ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3311 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3314 DBGPRINTF(("DODOT: cp is %s\n", cp));
3316 sp = any('/', cp) ? ":" : path->value;
3318 DBGPRINTF(("DODOT: sp is %s, global_env.linep is %s\n",
3319 ((sp == NULL) ? "NULL" : sp),
3320 ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3323 tp = global_env.linep;
3324 while (*sp && (*tp = *sp++) != ':')
3326 if (tp != global_env.linep)
3329 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3332 i = open(global_env.linep, O_RDONLY);
3336 DBGPRINTF(("DODOT: remap=%d, exstat=%d, global_env.iofd %d, i %d, global_env.linep is %s\n",
3337 maltmp, exstat, global_env.iofd, i, global_env.linep));
3339 next(maltmp); /* Basically a PUSHIO */
3341 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3353 static int dowait(struct op *t)
3365 setstatus(waitfor(i, 1));
3369 static int doread(struct op *t)
3375 if (t->words[1] == NULL) {
3376 err("Usage: read name ...");
3379 for (wp = t->words + 1; *wp; wp++) {
3380 for (cp = global_env.linep; !nl && cp < elinep - 1; cp++) {
3381 nb = read(0, cp, sizeof(*cp));
3382 if (nb != sizeof(*cp))
3385 if (nl || (wp[1] && any(*cp, ifs->value)))
3391 setval(lookup(*wp), global_env.linep);
3396 static int doeval(struct op *t)
3398 return RUN(awordlist, t->words + 1, wdchar);
3401 static int dotrap(struct op *t)
3406 if (t->words[1] == NULL) {
3407 for (i = 0; i <= _NSIG; i++)
3416 resetsig = isdigit(*t->words[1]);
3417 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3418 n = getsig(t->words[i]);
3422 if (*t->words[1] != '\0') {
3423 trap[n] = strsave(t->words[1], 0);
3432 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3440 static int getsig(char *s)
3445 if (n < 0 || n > _NSIG) {
3446 err("trap: bad signal number");
3452 static void setsig(int n, sighandler_t f)
3456 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3462 static int getn(char *as)
3473 for (n = 0; isdigit(*s); s++)
3474 n = (n * 10) + (*s - '0');
3477 err(": bad number");
3482 static int dobreak(struct op *t)
3484 return brkcontin(t->words[1], 1);
3487 static int docontinue(struct op *t)
3489 return brkcontin(t->words[1], 0);
3492 static int brkcontin(char *cp, int val)
3497 nl = cp == NULL ? 1 : getn(cp);
3504 brklist = bc->nextlev;
3507 err("bad break/continue level");
3510 isbreak = (val != 0);
3511 longjmp(bc->brkpt, 1);
3515 static int doexit(struct op *t)
3522 setstatus(getn(cp));
3524 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3531 static int doexport(struct op *t)
3533 rdexp(t->words + 1, export, EXPORT);
3537 static int doreadonly(struct op *t)
3539 rdexp(t->words + 1, ronly, RONLY);
3543 static void rdexp(char **wp, void (*f) (struct var *), int key)
3545 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3546 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3549 for (; *wp != NULL; wp++) {
3550 if (isassign(*wp)) {
3554 for (cp = *wp; *cp != '='; cp++);
3566 static void badid(char *s)
3569 err(": bad identifier");
3572 static int doset(struct op *t)
3580 for (vp = vlist; vp; vp = vp->next)
3581 varput(vp->name, 1);
3585 /* bad: t->words++; */
3586 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3588 FLAG['x'] = FLAG['v'] = 0;
3598 if (*cp >= 'a' && *cp <= 'z')
3607 t->words[0] = dolv[0];
3608 for (n = 1; t->words[n]; n++)
3609 setarea((char *) t->words[n], 0);
3612 setval(lookup("#"), putn(dolc));
3613 setarea((char *) (dolv - 1), 0);
3618 static void varput(char *s, int out)
3620 if (isalnum(*s) || *s == '_') {
3621 write(out, s, strlen(s));
3622 write(out, "\n", 1);
3628 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3629 * This file contains code for the times builtin.
3631 static int dotimes(struct op *t)
3634 long clk_tck = sysconf(_SC_CLK_TCK);
3637 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3638 (int) (buf.tms_utime / clk_tck / 60),
3639 ((double) buf.tms_utime) / clk_tck,
3640 (int) (buf.tms_stime / clk_tck / 60),
3641 ((double) buf.tms_stime) / clk_tck,
3642 (int) (buf.tms_cutime / clk_tck / 60),
3643 ((double) buf.tms_cutime) / clk_tck,
3644 (int) (buf.tms_cstime / clk_tck / 60),
3645 ((double) buf.tms_cstime) / clk_tck);
3650 /* -------- eval.c -------- */
3655 * blank interpretation
3660 static char **eval(char **ap, int f)
3668 /* Avoid longjmp clobbering */
3673 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3679 if (newenv(setjmp(errpt)) == 0) {
3680 while (*ap && isassign(*ap))
3681 expand(*ap++, &wb, f & ~DOGLOB);
3683 for (wf = ap; *wf; wf++) {
3685 expand(*wf, &wb, f & ~DOGLOB);
3688 for (wb = addword((char *) NULL, wb); *ap; ap++) {
3689 if (!FLAG['k'] || !isassign(*ap))
3690 expand(*ap, &wb, f & ~DOKEY);
3692 wb = addword((char *) 0, wb);
3698 return gflg ? (char **) NULL : wp;
3703 * Make the exported environment from the exported
3704 * names in the dictionary. Keyword assignments
3705 * will already have been done.
3707 static char **makenv(int all, struct wdblock *wb)
3711 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3713 for (vp = vlist; vp; vp = vp->next)
3714 if (all || vp->status & EXPORT)
3715 wb = addword(vp->name, wb);
3716 wb = addword((char *) 0, wb);
3717 return getwords(wb);
3720 static int expand(const char *cp, struct wdblock **wbp, int f)
3726 /* Avoid longjmp clobbering */
3730 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3737 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3738 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3740 xp = strsave(cp, areanum);
3743 *wbp = addword(xp, *wbp);
3747 if (newenv(setjmp(errpt)) == 0) {
3748 PUSHIO(aword, cp, strchar);
3749 global_env.iobase = global_env.iop;
3750 while ((xp = blank(f)) && gflg == 0) {
3751 global_env.linep = xp;
3752 xp = strsave(xp, areanum);
3753 if ((f & DOGLOB) == 0) {
3756 *wbp = addword(xp, *wbp);
3758 *wbp = glob(xp, *wbp);
3766 static char *evalstr(char *cp, int f)
3770 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3773 if (expand(cp, &wb, f)) {
3774 if (wb == NULL || wb->w_nword == 0
3775 || (cp = wb->w_words[0]) == NULL
3777 // TODO: I suspect that
3778 // char *evalstr(char *cp, int f) is actually
3779 // const char *evalstr(const char *cp, int f)!
3790 * Blank interpretation and quoting
3792 static char *blank(int f)
3796 int scanequals, foundequals;
3798 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3800 sp = global_env.linep;
3801 scanequals = f & DOKEY;
3805 c = subgetc('"', foundequals);
3808 if (sp == global_env.linep)
3810 *global_env.linep++ = 0;
3814 if (f & DOBLANK && any(c, ifs->value))
3823 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3826 if (c == '\'' || !any(c, "$`\""))
3828 *global_env.linep++ = c;
3833 if (!isalpha(c) && c != '_')
3836 c = subgetc('"', foundequals);
3838 f & (DOBLANK && any(c, ifs->value)) ||
3839 (!INSUB() && any(c, "\"'"))) {
3850 } else if (!isalnum(c) && c != '_')
3853 *global_env.linep++ = c;
3855 *global_env.linep++ = 0;
3860 * Get characters, substituting for ` and $
3862 static int subgetc(char ec, int quoted)
3866 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3870 if (!INSUB() && ec != '\'') {
3872 if (grave(quoted) == 0)
3874 global_env.iop->task = XGRAVE;
3880 global_env.iop->task = XDOLL;
3889 * Prepare to generate the string returned by ${} substitution.
3891 static int dollar(int quoted)
3896 char *s, c, *cp = NULL;
3899 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3902 s = global_env.linep;
3904 *global_env.linep++ = c;
3905 if (isalpha(c) || c == '_') {
3906 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3907 if (global_env.linep < elinep)
3908 *global_env.linep++ = c;
3913 oiop = global_env.iop;
3914 otask = global_env.iop->task;
3916 global_env.iop->task = XOTHER;
3917 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3918 if (global_env.linep < elinep)
3919 *global_env.linep++ = c;
3920 if (oiop == global_env.iop)
3921 global_env.iop->task = otask;
3928 if (global_env.linep >= elinep) {
3929 err("string in ${} too long");
3931 global_env.linep -= 10;
3933 *global_env.linep = 0;
3935 for (cp = s + 1; *cp; cp++)
3936 if (any(*cp, "=-+?")) {
3941 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3943 /* currently this does not distinguish $* and $@ */
3944 /* should check dollar */
3945 global_env.linep = s;
3946 PUSHIO(awordlist, dolv + 1, dolchar);
3948 } else { /* trap the nasty ${=} */
3959 err("cannot use ${...=...} with $n");
3968 dolp = strsave(cp, areanum);
3973 prs("missing value for ");
3980 } else if (c == '+')
3981 dolp = strsave(cp, areanum);
3982 if (FLAG['u'] && dolp == null) {
3983 prs("unset variable: ");
3987 global_env.linep = s;
3988 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
3993 * Run the command in `...` and read its output.
3996 static int grave(int quoted)
3998 /* moved to G: static char child_cmd[LINELIM]; */
4009 char *argument_list[4];
4010 struct wdblock *wb = NULL;
4013 /* Avoid longjmp clobbering */
4017 for (cp = global_env.iop->argp->aword; *cp != '`'; cp++) {
4019 err("no closing `");
4024 /* string copy with dollar expansion */
4025 src = global_env.iop->argp->aword;
4030 while ((*src != '`') && (count < LINELIM)) {
4035 if (*src == '$' && !ignore && !ignore_once) {
4037 /* moved to G to reduce stack usage
4038 char var_name[LINELIM];
4039 char alt_value[LINELIM];
4041 #define var_name (G.grave__var_name)
4042 #define alt_value (G.grave__alt_value)
4055 var_name[var_index++] = *src++;
4056 while (isalnum(*src) || *src=='_')
4057 var_name[var_index++] = *src++;
4058 var_name[var_index] = 0;
4071 err("unclosed ${\n");
4076 while (*src && (*src != '}')) {
4077 alt_value[alt_index++] = *src++;
4079 alt_value[alt_index] = 0;
4081 err("unclosed ${\n");
4088 if (isalpha(*var_name)) {
4089 /* let subshell handle it instead */
4091 char *namep = var_name;
4099 char *altp = alt_value;
4107 wb = addword(lookup(var_name)->name, wb);
4111 vp = lookup(var_name);
4112 if (vp->value != null)
4113 value = (operator == '+') ?
4114 alt_value : vp->value;
4115 else if (operator == '?') {
4118 } else if (alt_index && (operator != '+')) {
4120 if (operator == '=')
4125 while (*value && (count < LINELIM)) {
4140 if (openpipe(pf) < 0)
4143 while ((i = vfork()) == -1 && errno == EAGAIN);
4145 DBGPRINTF3(("GRAVE: i is %p\n", io));
4149 err((char *) bb_msg_memory_exhausted);
4153 waitpid(i, NULL, 0); // safe_waitpid?
4154 global_env.iop->argp->aword = ++cp;
4156 PUSHIO(afile, remap(pf[0]),
4157 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4160 /* allow trapped signals */
4161 /* XXX - Maybe this signal stuff should go as well? */
4162 for (j = 0; j <= _NSIG; j++)
4163 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4166 /* Testcase where below checks are needed:
4167 * close stdout & run this script:
4175 argument_list[0] = (char *) DEFAULT_SHELL;
4176 argument_list[1] = (char *) "-c";
4177 argument_list[2] = child_cmd;
4178 argument_list[3] = NULL;
4180 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4181 prs(argument_list[0]);
4188 static char *unquote(char *as)
4199 /* -------- glob.c -------- */
4205 #define scopy(x) strsave((x), areanum)
4207 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4209 static struct wdblock *cl, *nl;
4210 static const char spcl[] ALIGN1= "[?*";
4212 static struct wdblock *glob(char *cp, struct wdblock *wb)
4220 for (pp = cp; *pp; pp++)
4223 else if (!any(*pp & ~QUOTE, spcl))
4226 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4227 nl = newword(cl->w_nword * 2);
4228 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4229 for (pp = cl->w_words[i]; *pp; pp++)
4230 if (any(*pp, spcl)) {
4231 globname(cl->w_words[i], pp);
4235 nl = addword(scopy(cl->w_words[i]), nl);
4237 for (i = 0; i < cl->w_nword; i++)
4238 DELETE(cl->w_words[i]);
4241 for (i = 0; i < cl->w_nword; i++)
4242 unquote(cl->w_words[i]);
4243 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4245 for (i = 0; i < cl->w_nword; i++)
4246 wb = addword(cl->w_words[i], wb);
4251 wb = addword(unquote(cp), wb);
4255 static void globname(char *we, char *pp)
4258 char *name, *gp, *dp;
4262 char dname[NAME_MAX + 1];
4265 for (np = we; np != pp; pp--)
4268 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4272 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4281 dname[NAME_MAX] = '\0';
4282 while ((de = readdir(dirp)) != NULL) {
4283 /* XXX Hmmm... What this could be? (abial) */
4285 if (ent[j].d_ino == 0)
4288 strncpy(dname, de->d_name, NAME_MAX);
4289 if (dname[0] == '.')
4292 for (k = 0; k < NAME_MAX; k++)
4293 if (any(dname[k], spcl))
4295 if (gmatch(dname, gp)) {
4296 name = generate(we, pp, dname, np);
4297 if (*np && !anys(np, spcl)) {
4298 if (stat(name, &dbuf)) {
4303 nl = addword(name, nl);
4312 * generate a pathname as below.
4313 * start..end1 / middle end
4314 * the slashes come for free
4316 static char *generate(char *start1, char *end1, char *middle, char *end)
4321 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4322 for (xp = start1; xp != end1;)
4324 for (xp = middle; (*op++ = *xp++) != '\0';);
4326 for (xp = end; (*op++ = *xp++) != '\0';);
4330 static int anyspcl(struct wdblock *wb)
4336 for (i = 0; i < wb->w_nword; i++)
4337 if (anys(spcl, *wd++))
4342 static int xstrcmp(char *p1, char *p2)
4344 return strcmp(*(char **) p1, *(char **) p2);
4348 /* -------- word.c -------- */
4350 static struct wdblock *newword(int nw)
4354 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4360 static struct wdblock *addword(char *wd, struct wdblock *wb)
4362 struct wdblock *wb2;
4366 wb = newword(NSTART);
4368 if (nw >= wb->w_bsize) {
4369 wb2 = newword(nw * 2);
4370 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4371 nw * sizeof(char *));
4376 wb->w_words[wb->w_nword++] = wd;
4380 static char **getwords(struct wdblock *wb)
4387 if (wb->w_nword == 0) {
4391 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4392 memcpy((char *) wd, (char *) wb->w_words, nb);
4393 DELETE(wb); /* perhaps should done by caller */
4397 static int (*func) (char *, char *);
4400 static void glob3(char *i, char *j, char *k)
4402 char *index1, *index2, *index3;
4412 *index1++ = *index3;
4413 *index3++ = *index2;
4418 static void glob2(char *i, char *j)
4420 char *index1, *index2, c;
4428 *index1++ = *index2;
4433 static void glob1(char *base, char *lim)
4444 n = (int) (lim - base);
4447 n = v2 * (n / (2 * v2));
4448 hptr = lptr = base + n;
4453 c = (*func) (i, lptr);
4467 c = (*func) (hptr, j);
4491 if (lptr - base >= lim - hptr) {
4492 glob1(hptr + v2, lim);
4507 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4511 glob1(a0, a0 + a1 * a2);
4515 /* -------- io.c -------- */
4521 static int my_getc(int ec)
4525 if (global_env.linep > elinep) {
4526 while ((c = readc()) != '\n' && c);
4527 err("input line too long");
4532 if ((ec != '\'') && (ec != '`') && (global_env.iop->task != XGRAVE)) {
4535 if (c == '\n' && ec != '\"')
4543 static void unget(int c)
4545 if (global_env.iop >= global_env.iobase)
4546 global_env.iop->peekc = c;
4549 static int eofc(void)
4551 return global_env.iop < global_env.iobase || (global_env.iop->peekc == 0 && global_env.iop->prev == 0);
4554 static int readc(void)
4558 RCPRINTF(("READC: global_env.iop %p, global_env.iobase %p\n", global_env.iop, global_env.iobase));
4560 for (; global_env.iop >= global_env.iobase; global_env.iop--) {
4561 RCPRINTF(("READC: global_env.iop %p, peekc 0x%x\n", global_env.iop, global_env.iop->peekc));
4562 c = global_env.iop->peekc;
4564 global_env.iop->peekc = 0;
4567 if (global_env.iop->prev != 0) {
4568 c = (*global_env.iop->iofn)(global_env.iop->argp, global_env.iop);
4574 if (global_env.iop == iostack)
4576 global_env.iop->prev = c;
4577 return global_env.iop->prev;
4579 if (global_env.iop->task == XIO && global_env.iop->prev != '\n') {
4580 global_env.iop->prev = 0;
4581 if (global_env.iop == iostack)
4586 if (global_env.iop->task == XIO) {
4588 global_env.iop->prev = 0;
4589 return global_env.iop->prev;
4591 if (interactive && global_env.iop == iostack + 1) {
4592 #if ENABLE_FEATURE_EDITING
4593 current_prompt = prompt->value;
4601 if (global_env.iop >= iostack) {
4602 RCPRINTF(("READC: return 0, global_env.iop %p\n", global_env.iop));
4606 DBGPRINTF(("READC: leave()...\n"));
4612 static void ioecho(char c)
4615 write(2, &c, sizeof c);
4618 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4620 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, global_env.iop %p\n", argp,
4621 argp->afid, global_env.iop));
4623 /* Set env ptr for io source to next array spot and check for array overflow */
4624 if (++global_env.iop >= &iostack[NPUSH]) {
4626 err("Shell input nested too deeply");
4631 /* We did not overflow the NPUSH array spots so setup data structs */
4633 global_env.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4635 if (argp->afid != AFID_NOBUF)
4636 global_env.iop->argp = argp;
4639 global_env.iop->argp = ioargstack + (global_env.iop - iostack); /* MAL - index into stack */
4640 *global_env.iop->argp = *argp; /* copy data from temp area into stack spot */
4642 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4644 if (global_env.iop == &iostack[0])
4645 global_env.iop->argp->afbuf = &mainbuf;
4647 global_env.iop->argp->afbuf = &sharedbuf;
4649 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4650 /* This line appears to be active when running scripts from command line */
4651 if ((isatty(global_env.iop->argp->afile) == 0)
4652 && (global_env.iop == &iostack[0]
4653 || lseek(global_env.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4654 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4655 bufid = AFID_ID; /* AFID_ID = 0 */
4657 global_env.iop->argp->afid = bufid; /* assign buffer id */
4660 DBGPRINTF(("PUSHIO: iostack %p, global_env.iop %p, afbuf %p\n",
4661 iostack, global_env.iop, global_env.iop->argp->afbuf));
4662 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, global_env.iop %p\n",
4663 &mainbuf, &sharedbuf, bufid, global_env.iop));
4667 global_env.iop->prev = ~'\n';
4668 global_env.iop->peekc = 0;
4669 global_env.iop->xchar = 0;
4670 global_env.iop->nlcount = 0;
4672 if (fn == filechar || fn == linechar)
4673 global_env.iop->task = XIO;
4674 else if (fn == (int (*)(struct ioarg *)) gravechar
4675 || fn == (int (*)(struct ioarg *)) qgravechar)
4676 global_env.iop->task = XGRAVE;
4678 global_env.iop->task = XOTHER;
4681 static struct io *setbase(struct io *ip)
4685 xp = global_env.iobase;
4686 global_env.iobase = ip;
4691 * Input generating functions
4695 * Produce the characters of a string, then a newline, then EOF.
4697 static int nlchar(struct ioarg *ap)
4701 if (ap->aword == NULL)
4712 * Given a list of words, produce the characters
4713 * in them, with a space after each word.
4715 static int wdchar(struct ioarg *ap)
4730 ap->awordlist = NULL;
4735 * Return the characters of a list of words,
4736 * producing a space between them.
4738 static int dolchar(struct ioarg *ap)
4742 wp = *ap->awordlist++;
4744 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4750 static int xxchar(struct ioarg *ap)
4754 if (ap->aword == NULL)
4765 * Produce the characters from a single word (string).
4767 static int strchar(struct ioarg *ap)
4769 if (ap->aword == NULL)
4771 return *ap->aword++;
4775 * Produce quoted characters from a single word (string).
4777 static int qstrchar(struct ioarg *ap)
4781 if (ap->aword == NULL)
4790 * Return the characters from a file.
4792 static int filechar(struct ioarg *ap)
4796 struct iobuf *bp = ap->afbuf;
4798 if (ap->afid != AFID_NOBUF) {
4799 i = (ap->afid != bp->id);
4800 if (i || bp->bufp == bp->ebufp) {
4802 lseek(ap->afile, ap->afpos, SEEK_SET);
4804 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4812 bp->ebufp = bp->bufp + i;
4816 return *bp->bufp++ & 0177;
4818 #if ENABLE_FEATURE_EDITING
4819 if (interactive && isatty(ap->afile)) {
4820 /* moved to G: static char filechar_cmdbuf[BUFSIZ]; */
4821 static int position = 0, size = 0;
4823 while (size == 0 || position >= size) {
4824 size = read_line_input(current_prompt, filechar_cmdbuf, BUFSIZ, line_input_state);
4825 if (size < 0) /* Error/EOF */
4828 /* if Ctrl-C, size == 0 and loop will repeat */
4830 c = filechar_cmdbuf[position];
4835 i = safe_read(ap->afile, &c, sizeof(c));
4836 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4840 * Return the characters from a here temp file.
4842 static int herechar(struct ioarg *ap)
4846 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4854 * Return the characters produced by a process (`...`).
4855 * Quote them if required, and remove any trailing newline characters.
4857 static int gravechar(struct ioarg *ap, struct io *iop)
4861 c = qgravechar(ap, iop) & ~QUOTE;
4867 static int qgravechar(struct ioarg *ap, struct io *iop)
4871 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4876 return '\n' | QUOTE;
4880 } else if ((c = filechar(ap)) == '\n') {
4882 while ((c = filechar(ap)) == '\n')
4890 return c != 0 ? c | QUOTE : 0;
4894 * Return a single command (usually the first line) from a file.
4896 static int linechar(struct ioarg *ap)
4904 ap->afile = -1; /* illegal value */
4911 * remap fd into Shell's fd space
4913 static int remap(int fd)
4919 DBGPRINTF(("REMAP: fd=%d, global_env.iofd=%d\n", fd, global_env.iofd));
4921 if (fd < global_env.iofd) {
4922 for (i = 0; i < NOFILE; i++)
4929 } while (fd >= 0 && fd < global_env.iofd);
4931 for (i = 0; i < NOFILE; i++)
4936 err("too many files open in shell");
4942 static int openpipe(int *pv)
4948 err("can't create pipe - try again");
4952 static void closepipe(int *pv)
4961 /* -------- here.c -------- */
4967 static void markhere(char *s, struct ioword *iop)
4969 struct here *h, *lh;
4971 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4973 h = (struct here *) space(sizeof(struct here));
4977 h->h_tag = evalstr(s, DOSUB);
4987 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4988 if (lh->h_next == 0) {
4994 iop->io_flag |= IOHERE | IOXHERE;
4995 for (s = h->h_tag; *s; s++) {
4997 iop->io_flag &= ~IOXHERE;
5001 h->h_dosub = ((iop->io_flag & IOXHERE) ? '\0' : '\'');
5004 static void gethere(void)
5006 struct here *h, *hp;
5008 DBGPRINTF7(("GETHERE: enter...\n"));
5010 /* Scan here files first leaving inhere list in place */
5011 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5012 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub /* NUL or ' */);
5014 /* Make inhere list active - keep list intact for scraphere */
5016 hp->h_next = acthere;
5022 static void readhere(char **name, char *s, int ec)
5025 char tname[30] = ".msh_XXXXXX";
5028 char myline[LINELIM + 1];
5031 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5033 tf = mkstemp(tname);
5037 *name = strsave(tname, areanum);
5039 if (newenv(setjmp(errpt)) != 0)
5042 pushio(global_env.iop->argp, (int (*)(struct ioarg *)) global_env.iop->iofn);
5043 global_env.iobase = global_env.iop;
5045 if (interactive && global_env.iop <= iostack) {
5046 #if ENABLE_FEATURE_EDITING
5047 current_prompt = cprompt->value;
5049 prs(cprompt->value);
5053 while ((c = my_getc(ec)) != '\n' && c) {
5056 if (thenext >= &myline[LINELIM]) {
5063 if (strcmp(s, myline) == 0 || c == 0)
5066 write(tf, myline, (int) (thenext - myline));
5069 prs("here document `");
5079 * open here temp file.
5080 * if unquoted here, expand here temp file into second temp file.
5082 static int herein(char *hname, int xdoll)
5088 /* Avoid longjmp clobbering */
5094 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5096 hf = open(hname, O_RDONLY);
5102 char tname[30] = ".msh_XXXXXX";
5105 tf = mkstemp(tname);
5109 if (newenv(setjmp(errpt)) == 0) {
5110 PUSHIO(afile, hf, herechar);
5111 setbase(global_env.iop);
5112 while ((c = subgetc(0, 0)) != 0) {
5114 write(tf, &c, sizeof c);
5120 tf = open(tname, O_RDONLY);
5127 static void scraphere(void)
5131 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5133 for (h = inhere; h != NULL; h = h->h_next) {
5134 if (h->h_iop && h->h_iop->io_name)
5135 unlink(h->h_iop->io_name);
5140 /* unlink here temp files before a freearea(area) */
5141 static void freehere(int area)
5143 struct here *h, *hl;
5145 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5148 for (h = acthere; h != NULL; h = h->h_next)
5149 if (getarea((char *) h) >= area) {
5150 if (h->h_iop->io_name != NULL)
5151 unlink(h->h_iop->io_name);
5153 acthere = h->h_next;
5155 hl->h_next = h->h_next;
5161 /* -------- sh.c -------- */
5166 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5167 int msh_main(int argc, char **argv)
5173 int (*iof) (struct ioarg *);
5177 sharedbuf.id = AFID_NOBUF;
5178 mainbuf.id = AFID_NOBUF;
5179 elinep = line + sizeof(line) - 5;
5181 #if ENABLE_FEATURE_EDITING
5182 line_input_state = new_line_input_t(FOR_SHELL);
5185 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5191 assign(*ap++, !COPYV);
5192 for (ap = environ; *ap;)
5193 export(lookup(*ap++));
5198 shell = lookup("SHELL");
5199 if (shell->value == null)
5200 setval(shell, (char *)DEFAULT_SHELL);
5203 homedir = lookup("HOME");
5204 if (homedir->value == null)
5205 setval(homedir, "/");
5208 setval(lookup("$"), putn(getpid()));
5210 path = lookup("PATH");
5211 if (path->value == null) {
5212 /* Can be merged with same string elsewhere in bbox */
5214 setval(path, bb_default_root_path);
5216 setval(path, bb_default_path);
5220 ifs = lookup("IFS");
5221 if (ifs->value == null)
5222 setval(ifs, " \t\n");
5225 mshdbg_var = lookup("MSHDEBUG");
5226 if (mshdbg_var->value == null)
5227 setval(mshdbg_var, "0");
5230 prompt = lookup("PS1");
5231 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5232 if (prompt->value == null)
5234 setval(prompt, DEFAULT_USER_PROMPT);
5235 if (geteuid() == 0) {
5236 setval(prompt, DEFAULT_ROOT_PROMPT);
5237 prompt->status &= ~EXPORT;
5239 cprompt = lookup("PS2");
5240 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5241 if (cprompt->value == null)
5243 setval(cprompt, "> ");
5249 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5250 for (s = argv[0] + 1; *s; s++)
5253 prompt->status &= ~EXPORT;
5254 cprompt->status &= ~EXPORT;
5256 setval(cprompt, "");
5259 PUSHIO(aword, *++argv, iof = nlchar);
5267 /* standard input */
5271 prompt->status &= ~EXPORT;
5279 if (*s >= 'a' && *s <= 'z')
5287 if (iof == filechar && --argc > 0) {
5289 setval(cprompt, "");
5290 prompt->status &= ~EXPORT;
5291 cprompt->status &= ~EXPORT;
5293 /* Shell is non-interactive, activate printf-based debug */
5295 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5299 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5303 exit(1); /* Exit on error */
5309 /* This won't be true if PUSHIO has been called, say from newfile() above */
5310 if (global_env.iop < iostack) {
5311 PUSHIO(afile, 0, iof);
5312 if (isatty(0) && isatty(1) && !cflag) {
5314 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5316 printf("\n\n%s built-in shell (msh with debug)\n", bb_banner);
5318 printf("\n\n%s built-in shell (msh)\n", bb_banner);
5320 printf("Enter 'help' for a list of built-in commands.\n\n");
5325 signal(SIGQUIT, qflag);
5326 if (name && name[0] == '-') {
5328 f = open(".profile", O_RDONLY);
5331 f = open("/etc/profile", O_RDONLY);
5336 signal(SIGTERM, sig);
5338 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5339 signal(SIGINT, onintr);
5341 /* Handle "msh SCRIPT VAR=val params..." */
5342 /* Disabled: bash does not do it! */
5345 /* skip leading args of the form VAR=val */
5346 while (*argv && assign(*argv, !COPYV)) {
5356 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5358 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, global_env.iop %p, iostack %p\n", interactive, global_env.iop, iostack));
5361 if (interactive && global_env.iop <= iostack) {
5362 #if ENABLE_FEATURE_EDITING
5363 current_prompt = prompt->value;
5369 /* Ensure that getenv("PATH") stays current */
5370 setenv("PATH", path->value, 1);
5373 DBGPRINTF(("MSH_MAIN: returning.\n"));
5378 * Copyright (c) 1987,1997, Prentice Hall
5379 * All rights reserved.
5381 * Redistribution and use of the MINIX operating system in source and
5382 * binary forms, with or without modification, are permitted provided
5383 * that the following conditions are met:
5385 * Redistributions of source code must retain the above copyright
5386 * notice, this list of conditions and the following disclaimer.
5388 * Redistributions in binary form must reproduce the above
5389 * copyright notice, this list of conditions and the following
5390 * disclaimer in the documentation and/or other materials provided
5391 * with the distribution.
5393 * Neither the name of Prentice Hall nor the names of the software
5394 * authors or contributors may be used to endorse or promote
5395 * products derived from this software without specific prior
5396 * written permission.
5398 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5399 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5400 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5401 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5402 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5403 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5404 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5405 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5406 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5407 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5408 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5409 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.