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 nonblock_safe_read(fd,buf,count) read(fd,buf,count)
46 # define NOT_LONE_DASH(s) ((s)[0] != '-' || (s)[1])
47 # define LONE_CHAR(s,c) ((s)[0] == (c) && !(s)[1])
48 # define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
49 static int find_applet_by_name(const char *applet)
53 static char *utoa_to_buf(unsigned n, char *buf, unsigned buflen)
56 assert(sizeof(unsigned) == 4);
59 for (i = 1000000000; i; i /= 10) {
61 if (res || out || i == 1) {
71 static char *itoa_to_buf(int n, char *buf, unsigned buflen)
73 if (buflen && n < 0) {
78 return utoa_to_buf((unsigned)n, buf, buflen);
80 static char local_buf[12];
81 static char *itoa(int n)
83 *(itoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
87 # include "busybox.h" /* for applet_names */
93 int mshdbg = MSHDEBUG;
95 #define DBGPRINTF(x) if (mshdbg>0) printf x
96 #define DBGPRINTF0(x) if (mshdbg>0) printf x
97 #define DBGPRINTF1(x) if (mshdbg>1) printf x
98 #define DBGPRINTF2(x) if (mshdbg>2) printf x
99 #define DBGPRINTF3(x) if (mshdbg>3) printf x
100 #define DBGPRINTF4(x) if (mshdbg>4) printf x
101 #define DBGPRINTF5(x) if (mshdbg>5) printf x
102 #define DBGPRINTF6(x) if (mshdbg>6) printf x
103 #define DBGPRINTF7(x) if (mshdbg>7) printf x
104 #define DBGPRINTF8(x) if (mshdbg>8) printf x
105 #define DBGPRINTF9(x) if (mshdbg>9) printf x
109 #define RCPRINTF(x) if (mshdbg_rc) printf x
114 #define DBGPRINTF0(x) ((void)0)
115 #define DBGPRINTF1(x) ((void)0)
116 #define DBGPRINTF2(x) ((void)0)
117 #define DBGPRINTF3(x) ((void)0)
118 #define DBGPRINTF4(x) ((void)0)
119 #define DBGPRINTF5(x) ((void)0)
120 #define DBGPRINTF6(x) ((void)0)
121 #define DBGPRINTF7(x) ((void)0)
122 #define DBGPRINTF8(x) ((void)0)
123 #define DBGPRINTF9(x) ((void)0)
125 #define RCPRINTF(x) ((void)0)
127 #endif /* MSHDEBUG */
130 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
131 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
132 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
134 # define DEFAULT_ROOT_PROMPT "# "
135 # define DEFAULT_USER_PROMPT "$ "
139 /* -------- sh.h -------- */
145 #define NPUSH 8 /* limit to input nesting */
148 #define NOFILE 20 /* Number of open files */
149 #define NUFILE 10 /* Number of user-accessible files */
150 #define FDBASE 10 /* First file usable by Shell */
153 * values returned by wait
155 #define WAITSIG(s) ((s) & 0177)
156 #define WAITVAL(s) (((s) >> 8) & 0377)
157 #define WAITCORE(s) (((s) & 0200) != 0)
160 * library and system definitions
162 typedef void xint; /* base type of jmp_buf, for not broken compilers */
167 #define NOBLOCK ((struct op *)NULL)
168 #define NOWORD ((char *)NULL)
169 #define NOWORDS ((char **)NULL)
170 #define NOPIPE ((int *)NULL)
176 short io_unit; /* unit affected */
177 short io_flag; /* action (below) */
178 char *io_name; /* file name */
181 #define IOREAD 1 /* < */
182 #define IOHERE 2 /* << (here file) */
183 #define IOWRITE 4 /* > */
184 #define IOCAT 8 /* >> */
185 #define IOXHERE 16 /* ${}, ` in << */
186 #define IODUP 32 /* >&digit */
187 #define IOCLOSE 64 /* >&- */
189 #define IODEFAULT (-1) /* token for default IO unit */
193 * Description of a command or an operation on commands.
194 * Might eventually use a union.
197 smallint type; /* operation type, see Txxxx below */
198 char **words; /* arguments to a command */
199 struct ioword **ioact; /* IO actions (eg, < > >>) */
202 char *str; /* identifier for case and for */
205 #define TCOM 1 /* command */
206 #define TPAREN 2 /* (c-list) */
207 #define TPIPE 3 /* a | b */
208 #define TLIST 4 /* a [&;] b */
209 #define TOR 5 /* || */
210 #define TAND 6 /* && */
218 #define TPAT 14 /* pattern in case */
219 #define TBRACE 15 /* {c-list} */
220 #define TASYNC 16 /* c & */
221 /* Added to support "." file expansion */
224 /* Strings for names to make debug easier */
226 static const char *const T_CMD_NAMES[] = {
248 #define AREASIZE (90000)
251 * flags to control evaluation of words
253 #define DOSUB 1 /* interpret $, `, and quotes */
254 #define DOBLANK 2 /* perform blank interpretation */
255 #define DOGLOB 4 /* interpret [?* */
256 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
257 #define DOTRIM 16 /* trim resulting string */
259 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
264 struct brkcon *nextlev;
268 static smallint trapset; /* trap pending (signal number) */
270 static smallint yynerrs; /* yacc (flag) */
272 /* moved to G: static char line[LINELIM]; */
274 #if ENABLE_FEATURE_EDITING
275 static char *current_prompt;
276 static line_input_t *line_input_state;
283 static const char *rexecve(char *c, char **v, char **envp);
284 static char *evalstr(char *cp, int f);
285 static char *putn(int n);
286 static char *unquote(char *as);
287 static int rlookup(char *n);
288 static struct wdblock *glob(char *cp, struct wdblock *wb);
289 static int my_getc(int ec);
290 static int subgetc(char ec, int quoted);
291 static char **makenv(int all, struct wdblock *wb);
292 static char **eval(char **ap, int f);
293 static int setstatus(int s);
294 static int waitfor(int lastpid, int canintr);
296 static void onintr(int s); /* SIGINT handler */
298 static int newenv(int f);
299 static void quitenv(void);
300 static void next(int f);
301 static void setdash(void);
302 static void onecommand(void);
303 static void runtrap(int i);
306 /* -------- area stuff -------- */
308 #define REGSIZE sizeof(struct region)
310 /* #define SHRINKBY (64) */
314 #define ALIGN (sizeof(int)-1)
323 /* -------- grammar stuff -------- */
348 /* Added for "." file expansion */
351 #define YYERRCODE 300
354 #define CONTIN 01 /* skip new lines to complete command */
356 static struct op *pipeline(int cf);
357 static struct op *andor(void);
358 static struct op *c_list(void);
359 static int synio(int cf);
360 static void musthave(int c, int cf);
361 static struct op *simple(void);
362 static struct op *nested(int type, int mark);
363 static struct op *command(int cf);
364 static struct op *dogroup(int onlydone);
365 static struct op *thenpart(void);
366 static struct op *elsepart(void);
367 static struct op *caselist(void);
368 static struct op *casepart(void);
369 static char **pattern(void);
370 static char **wordlist(void);
371 static struct op *list(struct op *t1, struct op *t2);
372 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
373 static struct op *newtp(void);
374 static struct op *namelist(struct op *t);
375 static char **copyw(void);
376 static void word(char *cp);
377 static struct ioword **copyio(void);
378 static struct ioword *io(int u, int f, char *cp);
379 static int yylex(int cf);
380 static int collect(int c, int c1);
381 static int dual(int c);
382 static void diag(int ec);
383 static char *tree(unsigned size);
385 /* -------- var.h -------- */
394 #define COPYV 1 /* flag to setval, suggesting copy */
395 #define RONLY 01 /* variable is read-only */
396 #define EXPORT 02 /* variable is to be exported */
397 #define GETCELL 04 /* name & value space was got with getcell */
399 static int yyparse(void);
402 /* -------- io.h -------- */
405 unsigned id; /* buffer id */
406 char buf[512]; /* buffer */
407 char *bufp; /* pointer into buffer */
408 char *ebufp; /* pointer to end of buffer */
411 /* possible arguments to an IO function */
415 int afile; /* file descriptor */
416 unsigned afid; /* buffer id */
417 off_t afpos; /* file position */
418 struct iobuf *afbuf; /* buffer for this file */
421 /* an input generator's state */
423 int (*iofn) (struct ioarg *, struct io *);
426 char prev; /* previous character read by readc() */
427 char nlcount; /* for `'s */
428 char xchar; /* for `'s */
429 char task; /* reason for pushed IO */
432 #define XOTHER 0 /* none of the below */
433 #define XDOLL 1 /* expanding ${} */
434 #define XGRAVE 2 /* expanding `'s */
435 #define XIO 3 /* file IO */
439 * input generators for IO structure
441 static int nlchar(struct ioarg *ap);
442 static int strchar(struct ioarg *ap);
443 static int qstrchar(struct ioarg *ap);
444 static int filechar(struct ioarg *ap);
445 static int herechar(struct ioarg *ap);
446 static int linechar(struct ioarg *ap);
447 static int gravechar(struct ioarg *ap, struct io *iop);
448 static int qgravechar(struct ioarg *ap, struct io *iop);
449 static int dolchar(struct ioarg *ap);
450 static int wdchar(struct ioarg *ap);
451 static void scraphere(void);
452 static void freehere(int area);
453 static void gethere(void);
454 static void markhere(char *s, struct ioword *iop);
455 static int herein(char *hname, int xdoll);
456 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
459 static int eofc(void);
460 static int readc(void);
461 static void unget(int c);
462 static void ioecho(char c);
468 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
469 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
470 static int remap(int fd);
471 static int openpipe(int *pv);
472 static void closepipe(int *pv);
473 static struct io *setbase(struct io *ip);
475 /* -------- word.h -------- */
477 #define NSTART 16 /* default number of words to allow for initially */
482 /* bounds are arbitrary */
486 static struct wdblock *addword(char *wd, struct wdblock *wb);
487 static struct wdblock *newword(int nw);
488 static char **getwords(struct wdblock *wb);
490 /* -------- misc stuff -------- */
492 static int dolabel(struct op *t, char **args);
493 static int dohelp(struct op *t, char **args);
494 static int dochdir(struct op *t, char **args);
495 static int doshift(struct op *t, char **args);
496 static int dologin(struct op *t, char **args);
497 static int doumask(struct op *t, char **args);
498 static int doexec(struct op *t, char **args);
499 static int dodot(struct op *t, char **args);
500 static int dowait(struct op *t, char **args);
501 static int doread(struct op *t, char **args);
502 static int doeval(struct op *t, char **args);
503 static int dotrap(struct op *t, char **args);
504 static int dobreak(struct op *t, char **args);
505 static int doexit(struct op *t, char **args);
506 static int doexport(struct op *t, char **args);
507 static int doreadonly(struct op *t, char **args);
508 static int doset(struct op *t, char **args);
509 static int dotimes(struct op *t, char **args);
510 static int docontinue(struct op *t, char **args);
512 static int forkexec(struct op *t, int *pin, int *pout, int no_fork, char **wp);
513 static int execute(struct op *t, int *pin, int *pout, int no_fork);
514 static int iosetup(struct ioword *iop, int pipein, int pipeout);
515 static void brkset(struct brkcon *bc);
516 static int getsig(char *s);
517 static void setsig(int n, sighandler_t f);
518 static int getn(char *as);
519 static int brkcontin(char *cp, int val);
520 static void rdexp(char **wp, void (*f) (struct var *), int key);
521 static void badid(char *s);
522 static void varput(char *s, int out);
523 static int expand(const char *cp, struct wdblock **wbp, int f);
524 static char *blank(int f);
525 static int dollar(int quoted);
526 static int grave(int quoted);
527 static void globname(char *we, char *pp);
528 static char *generate(char *start1, char *end1, char *middle, char *end);
529 static int anyspcl(struct wdblock *wb);
530 static int xstrcmp(char *p1, char *p2);
531 static void glob0(char *a0, unsigned a1, int a2,
532 int (*a3) (char *, char *));
533 static void readhere(char **name, char *s, int ec);
534 static int xxchar(struct ioarg *ap);
539 struct ioword *h_iop;
543 static const char *const signame[] = {
546 NULL, /* interrupt */
548 "Illegal instruction",
552 "Floating Point Exception",
557 NULL, /* broken pipe */
563 typedef int (*builtin_func_ptr)(struct op *, char **);
567 builtin_func_ptr builtinfunc;
570 static const struct builtincmd builtincmds[] = {
573 { "break" , dobreak },
575 { "continue", docontinue },
579 { "export" , doexport },
581 { "login" , dologin },
582 { "newgrp" , dologin },
584 { "readonly", doreadonly },
586 { "shift" , doshift },
587 { "times" , dotimes },
589 { "umask" , doumask },
594 static struct op *scantree(struct op *);
595 static struct op *dowholefile(int, int);
602 static smallint gflg; /* (seems to be a parse error indicator) */
603 static smallint interactive; /* Is this an interactive shell */
604 static smallint execflg;
605 static smallint isbreak; /* "break" statement was seen */
606 static int multiline; /* '\n' changed to ';' (counter) */
607 static struct op *outtree; /* result from parser */
610 static struct brkcon *brklist;
611 static struct wdblock *wdlist;
612 static struct wdblock *iolist;
615 static struct var *mshdbg_var;
617 static struct var *vlist; /* dictionary */
618 static struct var *homedir; /* home directory */
619 static struct var *prompt; /* main prompt */
620 static struct var *cprompt; /* continuation prompt */
621 static struct var *path; /* search path for commands */
622 static struct var *shell; /* shell to interpret command files */
623 static struct var *ifs; /* field separators */
625 static int areanum; /* current allocation area */
626 static smallint intr; /* interrupt pending (bool) */
627 static smallint heedint = 1; /* heed interrupt signals (bool) */
629 static char *null = (char*)""; /* null value for variable */
630 static void (*qflag)(int) = SIG_IGN;
634 static int iounit = IODEFAULT;
635 static YYSTYPE yylval;
636 static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
638 static struct here *inhere; /* list of hear docs while parsing */
639 static struct here *acthere; /* list of active here documents */
640 static struct region *areabot; /* bottom of area */
641 static struct region *areatop; /* top of area */
642 static struct region *areanxt; /* starting point of scan */
644 static void *brkaddr;
646 #define AFID_NOBUF (~0)
651 * parsing & execution environment
657 xint *errpt; /* void * */
664 struct env global_env;
665 struct ioarg temparg; // = { .afid = AFID_NOBUF }; /* temporary for PUSHIO */
666 unsigned bufid; // = AFID_ID; /* buffer id counter */
667 char ourtrap[_NSIG + 1];
668 char *trap[_NSIG + 1];
669 struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
670 struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
671 struct ioarg ioargstack[NPUSH];
675 * -k: look for name=value everywhere on command line
677 * -t: exit after reading and executing one command
680 * -u: unset variables net diagnostic
682 char flags['z' - 'a' + 1];
683 char filechar_cmdbuf[BUFSIZ];
685 char child_cmd[LINELIM];
687 struct io iostack[NPUSH];
689 char grave__var_name[LINELIM];
690 char grave__alt_value[LINELIM];
693 #define G (*ptr_to_globals)
694 #define global_env (G.global_env )
695 #define temparg (G.temparg )
696 #define bufid (G.bufid )
697 #define ourtrap (G.ourtrap )
698 #define trap (G.trap )
699 #define sharedbuf (G.sharedbuf )
700 #define mainbuf (G.mainbuf )
701 #define ioargstack (G.ioargstack )
702 /* this looks weird, but is OK ... we index FLAG with 'a'...'z' */
703 #define FLAG (G.flags - 'a' )
704 #define filechar_cmdbuf (G.filechar_cmdbuf)
705 #define line (G.line )
706 #define child_cmd (G.child_cmd )
707 #define iostack (G.iostack )
708 #define INIT_G() do { \
709 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
710 global_env.linep = line; \
711 global_env.iobase = iostack; \
712 global_env.iop = iostack - 1; \
713 global_env.iofd = FDBASE; \
714 temparg.afid = AFID_NOBUF; \
719 /* in substitution */
720 #define INSUB() (global_env.iop->task == XGRAVE || global_env.iop->task == XDOLL)
722 #define RUN(what, arg, gen) ((temparg.what = (arg)), run(&temparg, (gen)))
725 void print_t(struct op *t)
727 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
728 T_CMD_NAMES[t->type], t->words, t->ioact));
731 DBGPRINTF(("T: W1: %s", t->words[0]));
735 void print_tree(struct op *head)
738 DBGPRINTF(("PRINT_TREE: no tree\n"));
742 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
746 print_tree(head->left);
749 print_tree(head->right);
751 #endif /* MSHDEBUG */
757 static void prs(const char *s)
760 write(2, s, strlen(s));
763 static void prn(unsigned u)
768 static void echo(char **wp)
773 for (i = 0; wp[i]; i++) {
781 static void closef(int i)
787 static void closeall(void)
791 for (u = NUFILE; u < NOFILE;)
796 /* fail but return to process next command */
797 static void fail(void) ATTRIBUTE_NORETURN;
798 static void fail(void)
804 /* abort shell (or fail in subshell) */
805 static void leave(void) ATTRIBUTE_NORETURN;
806 static void leave(void)
808 DBGPRINTF(("LEAVE: leave called!\n"));
819 static void warn(const char *s)
830 static void err(const char *s)
837 if (global_env.errpt)
838 longjmp(global_env.errpt, 1);
840 global_env.iop = global_env.iobase = iostack;
844 /* -------- area.c -------- */
847 * All memory between (char *)areabot and (char *)(areatop+1) is
848 * exclusively administered by the area management routines.
849 * It is assumed that sbrk() and brk() manipulate the high end.
853 void * __q = (void *)-1; \
854 if (brkaddr + (int)(X) < brktop) { \
856 brkaddr += (int)(X); \
861 static void initarea(void)
863 brkaddr = xmalloc(AREASIZE);
864 brktop = brkaddr + AREASIZE;
866 while ((long) sbrk(0) & ALIGN)
868 areabot = (struct region *) sbrk(REGSIZE);
870 areabot->next = areabot;
871 areabot->area = BUSY;
876 static char *getcell(unsigned nbytes)
879 struct region *p, *q;
886 /* silly and defeats the algorithm */
888 * round upwards and add administration area
890 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
893 if (p->area > areanum) {
897 while ((q = p->next)->area > areanum && q != areanxt)
900 * exit loop if cell big enough
909 i = nregio >= GROWBY ? nregio : GROWBY;
910 p = (struct region *) sbrk(i * REGSIZE);
911 if (p == (struct region *) -1)
916 abort(); /* allocated areas are contiguous */
926 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
928 areanxt = p + nregio;
931 * split into requested area and rest
933 if (areanxt + 1 > q) {
935 abort(); /* insufficient space left for admin */
938 areanxt->area = FREE;
942 return (char *) (p + 1);
945 static void freecell(char *cp)
949 p = (struct region *) cp;
957 #define DELETE(obj) freecell((char *)obj)
959 static void freearea(int a)
961 struct region *p, *top;
964 for (p = areabot; p != top; p = p->next)
969 static void setarea(char *cp, int a)
973 p = (struct region *) cp;
978 static int getarea(char *cp)
980 return ((struct region *) cp - 1)->area;
983 static void garbage(void)
985 struct region *p, *q, *top;
988 for (p = areabot; p != top; p = p->next) {
989 if (p->area > areanum) {
990 while ((q = p->next)->area > areanum)
996 if (areatop >= q + SHRINKBY && q->area > areanum) {
997 brk((char *) (q + 1));
1005 static char *space(int n)
1011 err("out of string space");
1015 static char *strsave(const char *s, int a)
1019 cp = space(strlen(s) + 1);
1021 // FIXME: I highly doubt this is good.
1030 /* -------- var.c -------- */
1032 static int eqname(const char *n1, const char *n2)
1034 for (; *n1 != '=' && *n1 != '\0'; n1++)
1037 return *n2 == '\0' || *n2 == '=';
1040 static const char *findeq(const char *cp)
1042 while (*cp != '\0' && *cp != '=')
1048 * Find the given name in the dictionary
1049 * and return its value. If the name was
1050 * not previously there, enter it now and
1051 * return a null value.
1053 static struct var *lookup(const char *n)
1055 // FIXME: dirty hack
1056 static struct var dummy;
1064 dummy.name = (char*)n;
1065 for (c = 0; isdigit(*n) && c < 1000; n++)
1066 c = c * 10 + *n - '0';
1067 dummy.status = RONLY;
1068 dummy.value = (c <= dolc ? dolv[c] : null);
1072 for (vp = vlist; vp; vp = vp->next)
1073 if (eqname(vp->name, n))
1077 vp = (struct var *) space(sizeof(*vp));
1078 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1079 dummy.name = dummy.value = (char*)"";
1084 while ((*xp = *n++) != '\0' && *xp != '=')
1088 setarea((char *) vp, 0);
1089 setarea((char *) vp->name, 0);
1092 vp->status = GETCELL;
1098 * if name is not NULL, it must be
1099 * a prefix of the space `val',
1101 * this is all so that exporting
1102 * values is reasonably painless.
1104 static void nameval(struct var *vp, const char *val, const char *name)
1110 if (vp->status & RONLY) {
1112 while (*xp && *xp != '=')
1113 fputc(*xp++, stderr);
1114 err(" is read-only");
1119 xp = space(strlen(vp->name) + strlen(val) + 2);
1122 /* make string: name=value */
1126 while ((*xp = *cp++) != '\0' && *xp != '=')
1133 if (vp->status & GETCELL)
1134 freecell(vp->name); /* form new string `name=value' */
1135 vp->name = (char*)name;
1136 vp->value = (char*)val;
1141 * give variable at `vp' the value `val'.
1143 static void setval(struct var *vp, const char *val)
1145 nameval(vp, val, NULL);
1148 static void export(struct var *vp)
1150 vp->status |= EXPORT;
1153 static void ronly(struct var *vp)
1155 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1156 vp->status |= RONLY;
1159 static int isassign(const char *s)
1162 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1165 /* no isalpha() - we shouldn't use locale */
1166 /* c | 0x20 - lowercase (Latin) letters */
1167 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1178 && (unsigned)(c - '0') > 9 /* not number */
1179 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1186 static int assign(const char *s, int cf)
1191 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1193 if (!isalpha(*s) && *s != '_')
1195 for (cp = s; *cp != '='; cp++)
1196 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1199 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1201 vp->status &= ~GETCELL;
1205 static int checkname(char *cp)
1207 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1209 if (!isalpha(*cp++) && *(cp - 1) != '_')
1212 if (!isalnum(*cp++) && *(cp - 1) != '_')
1217 static void putvlist(int f, int out)
1221 for (vp = vlist; vp; vp = vp->next) {
1222 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1223 if (vp->status & EXPORT)
1224 write(out, "export ", 7);
1225 if (vp->status & RONLY)
1226 write(out, "readonly ", 9);
1227 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1228 write(out, "\n", 1);
1237 static void sig(int i)
1243 static void runtrap(int i)
1248 if (trapstr == NULL)
1254 RUN(aword, trapstr, nlchar);
1258 static void setdash(void)
1262 char m['z' - 'a' + 1];
1265 for (c = 'a'; c <= 'z'; c++)
1269 setval(lookup("-"), m);
1272 static int newfile(char *s)
1276 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1279 if (NOT_LONE_DASH(s)) {
1280 DBGPRINTF(("NEWFILE: s is %s\n", s));
1281 f = open(s, O_RDONLY);
1284 err(": cannot open");
1294 struct op *scantree(struct op *head)
1301 if (head->left != NULL) {
1302 dotnode = scantree(head->left);
1307 if (head->right != NULL) {
1308 dotnode = scantree(head->right);
1313 if (head->words == NULL)
1316 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1318 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1319 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1327 static void onecommand(void)
1332 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1334 while (global_env.oenv)
1343 global_env.errpt = 0;
1344 global_env.linep = line;
1352 setjmp(failpt); /* Bruce Evans' fix */
1354 if (setjmp(failpt) || yyparse() || intr) {
1355 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1357 while (global_env.oenv)
1360 if (!interactive && intr)
1373 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1375 execute(outtree, NOPIPE, NOPIPE, /* no_fork: */ 0);
1378 if (!interactive && intr) {
1390 static int newenv(int f)
1394 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1401 ep = (struct env *) space(sizeof(*ep));
1403 while (global_env.oenv)
1408 global_env.oenv = ep;
1409 global_env.errpt = errpt;
1414 static void quitenv(void)
1419 DBGPRINTF(("QUITENV: global_env.oenv=%p\n", global_env.oenv));
1421 ep = global_env.oenv;
1423 fd = global_env.iofd;
1425 /* should close `'d files */
1427 while (--fd >= global_env.iofd)
1433 * Is character c in s?
1435 static int any(int c, const char *s)
1444 * Is any character from s1 in s2?
1446 static int anys(const char *s1, const char *s2)
1454 static char *putn(int n)
1459 static void next(int f)
1461 PUSHIO(afile, f, filechar);
1464 static void onintr(int s) /* ANSI C requires a parameter */
1466 signal(SIGINT, onintr);
1473 } else if (heedint) {
1480 /* -------- gmatch.c -------- */
1482 * int gmatch(string, pattern)
1483 * char *string, *pattern;
1485 * Match a pattern as in sh(1).
1490 #define QMASK (CMASK & ~QUOTE)
1491 #define NOT '!' /* might use ^ */
1493 static const char *cclass(const char *p, int sub)
1495 int c, d, not, found;
1505 if (p[1] == '-' && p[2] != ']') {
1510 if (c == sub || (c <= sub && sub <= d))
1512 } while (*++p != ']');
1513 return found ? p + 1 : NULL;
1516 static int gmatch(const char *s, const char *p)
1520 if (s == NULL || p == NULL)
1523 while ((pc = *p++ & CMASK) != '\0') {
1540 if (*p == '\0' || gmatch(s, p))
1542 } while (*s++ != '\0');
1546 if (sc != (pc & ~QUOTE))
1554 /* -------- csyn.c -------- */
1556 * shell: syntax (C version)
1559 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1560 static void yyerror(const char *s)
1563 if (interactive && global_env.iop <= iostack) {
1565 while (eofc() == 0 && yylex(0) != '\n')
1572 static void zzerr(void) ATTRIBUTE_NORETURN;
1573 static void zzerr(void)
1575 yyerror("syntax error");
1580 DBGPRINTF7(("YYPARSE: enter...\n"));
1587 return yynerrs; /* 0/1 */
1590 static struct op *pipeline(int cf)
1595 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1599 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1602 while ((c = yylex(0)) == '|') {
1603 p = command(CONTIN);
1605 DBGPRINTF8(("PIPELINE: error!\n"));
1609 if (t->type != TPAREN && t->type != TCOM) {
1610 /* shell statement */
1611 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1614 t = block(TPIPE, t, p, NOWORDS);
1619 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1623 static struct op *andor(void)
1628 DBGPRINTF7(("ANDOR: enter...\n"));
1632 DBGPRINTF9(("ANDOR: t=%p\n", t));
1635 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1636 p = pipeline(CONTIN);
1638 DBGPRINTF8(("ANDOR: error!\n"));
1642 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1648 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1652 static struct op *c_list(void)
1657 DBGPRINTF7(("C_LIST: enter...\n"));
1664 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1666 while ((c = yylex(0)) == ';' || c == '&'
1667 || (multiline && c == '\n')) {
1675 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1683 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1687 static int synio(int cf)
1693 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1696 if (c != '<' && c != '>') {
1703 iop = io(iounit, i, yylval.cp);
1707 markhere(yylval.cp, iop);
1709 DBGPRINTF7(("SYNIO: returning 1\n"));
1713 static void musthave(int c, int cf)
1715 peeksym = yylex(cf);
1717 DBGPRINTF7(("MUSTHAVE: error!\n"));
1724 static struct op *simple(void)
1730 switch (peeksym = yylex(0)) {
1751 static struct op *nested(int type, int mark)
1755 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1761 return block(type, t, NOBLOCK, NOWORDS);
1764 static struct op *command(int cf)
1767 struct wdblock *iosave;
1770 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1796 t = nested(TPAREN, ')');
1800 t = nested(TBRACE, '}');
1810 t->words = wordlist();
1812 if (c != '\n' && c != ';')
1814 t->left = dogroup(0);
1822 t->type = (c == WHILE ? TWHILE : TUNTIL);
1824 t->right = dogroup(1);
1825 /* t->words = NULL; - newtp() did this */
1836 musthave(IN, CONTIN);
1839 t->left = caselist();
1850 t->right = thenpart();
1859 musthave(WORD, 0); /* gets name of file */
1860 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1862 word(yylval.cp); /* add word to wdlist */
1863 word(NOWORD); /* terminate wdlist */
1864 t->words = copyw(); /* dup wdlist */
1874 DBGPRINTF(("COMMAND: returning %p\n", t));
1879 static struct op *dowholefile(int type, int mark)
1883 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1888 t = block(type, t, NOBLOCK, NOWORDS);
1889 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1893 static struct op *dogroup(int onlydone)
1899 if (c == DONE && onlydone)
1908 static struct op *thenpart(void)
1919 /*t->type = 0; - newtp() did this */
1921 if (t->left == NULL)
1923 t->right = elsepart();
1927 static struct op *elsepart(void)
1932 switch (c = yylex(0)) {
1943 t->right = thenpart();
1952 static struct op *caselist(void)
1957 while ((peeksym = yylex(CONTIN)) != ESAC) {
1958 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1959 t = list(t, casepart());
1962 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1966 static struct op *casepart(void)
1970 DBGPRINTF7(("CASEPART: enter...\n"));
1974 t->words = pattern();
1977 peeksym = yylex(CONTIN);
1978 if (peeksym != ESAC)
1979 musthave(BREAK, CONTIN);
1981 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
1986 static char **pattern(void)
2003 static char **wordlist(void)
2013 while ((c = yylex(0)) == WORD)
2021 * supporting functions
2023 static struct op *list(struct op *t1, struct op *t2)
2025 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2032 return block(TLIST, t1, t2, NOWORDS);
2035 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2039 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2047 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1, t2));
2052 /* See if given string is a shell multiline (FOR, IF, etc) */
2053 static int rlookup(char *n)
2059 static const struct res restab[] = {
2082 const struct res *rp;
2084 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2086 for (rp = restab; rp->r_name[0]; rp++)
2087 if (strcmp(rp->r_name, n) == 0) {
2088 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2089 return rp->r_val; /* Return numeric code for shell multiline */
2092 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2093 return 0; /* Not a shell multiline */
2096 static struct op *newtp(void)
2100 t = (struct op *) tree(sizeof(*t));
2101 memset(t, 0, sizeof(*t));
2103 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2108 static struct op *namelist(struct op *t)
2110 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2111 T_CMD_NAMES[t->type], iolist));
2114 iolist = addword((char *) NULL, iolist);
2115 t->ioact = copyio();
2119 if (t->type != TCOM) {
2120 if (t->type != TPAREN && t->ioact != NULL) {
2121 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2122 t->ioact = t->left->ioact;
2123 t->left->ioact = NULL;
2134 static char **copyw(void)
2138 wd = getwords(wdlist);
2143 static void word(char *cp)
2145 wdlist = addword(cp, wdlist);
2148 static struct ioword **copyio(void)
2150 struct ioword **iop;
2152 iop = (struct ioword **) getwords(iolist);
2157 static struct ioword *io(int u, int f, char *cp)
2161 iop = (struct ioword *) tree(sizeof(*iop));
2165 iolist = addword((char *) iop, iolist);
2169 static int yylex(int cf)
2186 global_env.linep = line;
2189 line[LINELIM - 1] = '\0';
2192 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2197 if (any(c, "0123456789")) {
2200 if (c1 == '<' || c1 == '>') {
2204 *global_env.linep++ = c;
2209 case '#': /* Comment, skip to next newline or End-of-string */
2210 while ((c = my_getc(0)) != '\0' && c != '\n');
2215 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2219 DBGPRINTF9(("YYLEX: found $\n"));
2220 *global_env.linep++ = c;
2223 c = collect(c, '}');
2242 /* If more chars process them, else return NULL char */
2260 if (multiline || cf & CONTIN) {
2261 if (interactive && global_env.iop <= iostack) {
2262 #if ENABLE_FEATURE_EDITING
2263 current_prompt = cprompt->value;
2265 prs(cprompt->value);
2282 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2283 if (global_env.linep >= elinep)
2284 err("word too long");
2286 *global_env.linep++ = c;
2291 if (any(c, "\"'`$"))
2294 *global_env.linep++ = '\0';
2304 yylval.cp = strsave(line, areanum);
2309 static int collect(int c, int c1)
2313 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2315 *global_env.linep++ = c;
2316 while ((c = my_getc(c1)) != c1) {
2325 if (interactive && c == '\n' && global_env.iop <= iostack) {
2326 #if ENABLE_FEATURE_EDITING
2327 current_prompt = cprompt->value;
2329 prs(cprompt->value);
2332 *global_env.linep++ = c;
2335 *global_env.linep++ = c;
2337 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2342 /* "multiline commands" helper func */
2343 /* see if next 2 chars form a shell multiline */
2344 static int dual(int c)
2349 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2351 *cp++ = c; /* c is the given "peek" char */
2352 *cp++ = my_getc(0); /* get next char of input */
2353 *cp = '\0'; /* add EOS marker */
2355 c = rlookup(s); /* see if 2 chars form a shell multiline */
2357 unget(*--cp); /* String is not a shell multiline, put peek char back */
2359 return c; /* String is multiline, return numeric multiline (restab) code */
2362 static void diag(int ec)
2366 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2369 if (c == '>' || c == '<') {
2372 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2375 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2376 if (c != '&' || yylval.i == IOHERE)
2382 static char *tree(unsigned size)
2388 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2389 prs("command line too complicated\n");
2400 /* -------- exec.c -------- */
2402 static struct op **find1case(struct op *t, const char *w)
2410 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2414 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2415 T_CMD_NAMES[t->type]));
2417 if (t->type == TLIST) {
2418 tp = find1case(t->left, w);
2420 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2423 t1 = t->right; /* TPAT */
2427 for (wp = t1->words; *wp;) {
2428 cp = evalstr(*wp++, DOSUB);
2429 if (cp && gmatch(w, cp)) {
2430 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2436 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2440 static struct op *findcase(struct op *t, const char *w)
2444 tp = find1case(t, w);
2445 return tp != NULL ? *tp : NULL;
2452 static int execute(struct op *t, int *pin, int *pout, int no_fork)
2455 volatile int i, rv, a;
2459 struct op *outtree_save;
2463 /* Avoid longjmp clobbering */
2468 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2472 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2473 t->type, T_CMD_NAMES[t->type],
2474 ((t->words == NULL) ? "NULL" : t->words[0])));
2480 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2485 DBGPRINTF3(("EXECUTE: TDOT\n"));
2487 outtree_save = outtree;
2489 newfile(evalstr(t->words[0], DOALL));
2491 t->left = dowholefile(TLIST, 0);
2494 outtree = outtree_save;
2497 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2499 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2503 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2507 rv = forkexec(t, pin, pout, no_fork, wp);
2517 pv[0] = remap(pv[0]);
2518 pv[1] = remap(pv[1]);
2519 (void) execute(t->left, pin, pv, /* no_fork: */ 0);
2520 rv = execute(t->right, pv, pout, /* no_fork: */ 0);
2525 (void) execute(t->left, pin, pout, /* no_fork: */ 0);
2526 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2531 smallint hinteractive = interactive;
2533 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2536 if (i == 0) { /* child */
2537 signal(SIGINT, SIG_IGN);
2538 signal(SIGQUIT, SIG_IGN);
2540 signal(SIGTERM, SIG_DFL);
2544 xopen(bb_dev_null, O_RDONLY);
2546 _exit(execute(t->left, pin, pout, /* no_fork: */ 1));
2548 interactive = hinteractive;
2550 setval(lookup("!"), putn(i));
2564 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2566 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2567 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2578 while (*wp++ != NULL);
2580 vp = lookup(t->str);
2581 while (setjmp(bc.brkpt))
2585 for (t1 = t->left; i-- && *wp != NULL;) {
2587 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2589 brklist = brklist->nextlev;
2594 while (setjmp(bc.brkpt))
2599 while ((execute(t1, pin, pout, /* no_fork: */ 0) == 0) == (t->type == TWHILE))
2600 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2601 brklist = brklist->nextlev;
2606 if (t->right != NULL) {
2607 rv = !execute(t->left, pin, pout, /* no_fork: */ 0) ?
2608 execute(t->right->left, pin, pout, /* no_fork: */ 0) :
2609 execute(t->right->right, pin, pout, /* no_fork: */ 0);
2614 cp = evalstr(t->str, DOSUB | DOTRIM);
2618 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2619 ((t->str == NULL) ? "NULL" : t->str),
2620 ((cp == NULL) ? "NULL" : cp)));
2622 t1 = findcase(t->left, cp);
2624 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2625 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2626 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2635 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2643 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2656 if (interactive && intr) {
2667 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2671 static builtin_func_ptr inbuilt(const char *s)
2673 const struct builtincmd *bp;
2675 for (bp = builtincmds; bp->name; bp++)
2676 if (strcmp(bp->name, s) == 0)
2677 return bp->builtinfunc;
2681 static int forkexec(struct op *t, int *pin, int *pout, int no_fork, char **wp)
2685 builtin_func_ptr bltin = NULL;
2686 const char *bltin_name = NULL;
2688 struct ioword **iopp;
2696 smallint hinteractive;
2699 struct brkcon *hbrklist;
2702 /* Avoid longjmp clobbering */
2712 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, no_fork %d\n", t, pin,
2714 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2715 ((t->words == NULL) ? "NULL" : t->words[0])));
2718 if (t->type == TCOM) {
2719 while (*wp++ != NULL)
2723 /* strip all initial assignments */
2724 /* FIXME: not correct wrt PATH=yyy command etc */
2726 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2728 echo(cp ? wp : owp);
2732 if (t->ioact == NULL) {
2733 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2735 DBGPRINTF(("FORKEXEC: returning setstatus(0)\n"));
2736 return setstatus(0);
2738 } else { /* cp != NULL */
2740 bltin = inbuilt(cp);
2745 // We were pointing t->words to temporary (expanded) arg list:
2747 // and restored it later (in execute()), but "break"
2748 // longjmps away (at "Run builtin" below), leaving t->words clobbered!
2749 // See http://bugs.busybox.net/view.php?id=846.
2750 // Now we do not touch t->words, but separately pass wp as param list
2752 DBGPRINTF(("FORKEXEC: bltin %p, no_fork %d, owp %p\n", bltin,
2754 /* Don't fork if it is a lone builtin (not in pipe)
2755 * OR we are told to _not_ fork */
2756 if ((!bltin || pin || pout) /* not lone bltin AND */
2757 && !no_fork /* not told to avoid fork */
2759 /* Save values in case child alters them after vfork */
2763 hinteractive = interactive;
2768 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2771 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2775 if (newpid > 0) { /* Parent */
2776 /* Restore values */
2780 interactive = hinteractive;
2786 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2790 DBGPRINTF(("FORKEXEC: child process, bltin=%p (%s)\n", bltin, bltin_name));
2792 signal(SIGINT, SIG_IGN);
2793 signal(SIGQUIT, SIG_IGN);
2804 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2808 if (pin) { /* NB: close _first_, then move fds! */
2810 xmove_fd(pin[0], 0);
2814 xmove_fd(pout[1], 1);
2819 if (bltin && bltin != doexec) {
2821 err(": cannot redirect shell command");
2827 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2828 /* system-detected error */
2837 if (forked || pin || pout) {
2838 /* Builtin in pipe: disallowed */
2839 /* TODO: allow "exec"? */
2841 err(": cannot run builtin as part of pipe");
2847 i = setstatus(bltin(t, wp));
2850 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2854 /* should use FIOCEXCL */
2855 for (i = FDBASE; i < NOFILE; i++)
2858 signal(SIGINT, SIG_DFL);
2859 signal(SIGQUIT, SIG_DFL);
2862 if (t->type == TPAREN)
2863 _exit(execute(t->left, NOPIPE, NOPIPE, /* no_fork: */ 1));
2867 cp = rexecve(wp[0], wp, makenv(0, NULL));
2874 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", getpid()));
2882 * 0< 1> are ignored as required
2885 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2891 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2894 if (iop->io_unit == IODEFAULT) /* take default */
2895 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2897 if (pipein && iop->io_unit == 0)
2900 if (pipeout && iop->io_unit == 1)
2903 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2904 if ((iop->io_flag & IOHERE) == 0) {
2905 cp = iop->io_name; /* huh?? */
2906 cp = evalstr(cp, DOSUB | DOTRIM);
2911 if (iop->io_flag & IODUP) {
2912 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2914 err(": illegal >& argument");
2918 iop->io_flag = IOCLOSE;
2919 iop->io_flag &= ~(IOREAD | IOWRITE);
2922 switch (iop->io_flag) {
2924 u = open(cp, O_RDONLY);
2928 case IOHERE | IOXHERE:
2929 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2930 cp = (char*)"here file";
2933 case IOWRITE | IOCAT:
2934 u = open(cp, O_WRONLY);
2936 lseek(u, (long) 0, SEEK_END);
2939 /* fall through to creation if >>file doesn't exist */
2942 u = creat(cp, 0666);
2946 u = dup2(*cp - '0', iop->io_unit);
2950 close(iop->io_unit);
2960 if (u != iop->io_unit) {
2961 dup2(u, iop->io_unit);
2968 * Enter a new loop level (marked for break/continue).
2970 static void brkset(struct brkcon *bc)
2972 bc->nextlev = brklist;
2977 * Wait for the last process created.
2978 * Print a message for each process found
2979 * that was killed by a signal.
2980 * Ignore interrupt signals while waiting
2981 * unless `canintr' is true.
2983 static int waitfor(int lastpid, int canintr)
2987 smallint oheedint = heedint;
2994 if (errno != EINTR || canintr)
2999 if (rv < ARRAY_SIZE(signame)) {
3000 if (signame[rv] != NULL) {
3001 if (pid != lastpid) {
3008 if (pid != lastpid) {
3017 prs(" - core dumped");
3018 if (rv >= ARRAY_SIZE(signame) || signame[rv])
3024 } while (pid != lastpid);
3039 static int setstatus(int s)
3042 setval(lookup("?"), putn(s));
3047 * PATH-searching interface to execve.
3048 * If getenv("PATH") were kept up-to-date,
3049 * execvp might be used.
3051 static const char *rexecve(char *c, char **v, char **envp)
3059 if (ENABLE_FEATURE_SH_STANDALONE) {
3060 if (find_applet_by_name(name) >= 0) {
3061 /* We have to exec here since we vforked. Running
3062 * run_applet_and_exit() won't work and bad things
3064 execve(bb_busybox_exec_path, v, envp);
3068 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3070 sp = any('/', c) ? "" : path->value;
3071 asis = (*sp == '\0');
3072 while (asis || *sp != '\0') {
3074 tp = global_env.linep;
3075 for (; *sp != '\0'; tp++) {
3078 asis = (*sp == '\0');
3082 if (tp != global_env.linep)
3084 for (i = 0; (*tp++ = c[i++]) != '\0';);
3086 DBGPRINTF3(("REXECVE: global_env.linep is %s\n", global_env.linep));
3088 execve(global_env.linep, v, envp);
3092 *v = global_env.linep;
3094 *v = global_env.linep;
3095 execve(DEFAULT_SHELL, v, envp);
3100 return (char *) bb_msg_memory_exhausted;
3103 return "argument list too long";
3106 return errno == ENOENT ? "not found" : "cannot execute";
3110 * Run the command produced by generator `f'
3111 * applied to stream `arg'.
3113 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3116 struct wdblock *swdlist;
3117 struct wdblock *siolist;
3123 /* Avoid longjmp clobbering */
3127 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3128 areanum, outtree, failpt));
3138 if (newenv(setjmp(errpt)) == 0) {
3142 global_env.iobase = global_env.iop;
3145 if (setjmp(failpt) == 0 && yyparse() == 0)
3146 rv = execute(outtree, NOPIPE, NOPIPE, /* no_fork: */ 0);
3149 DBGPRINTF(("RUN: error from newenv()!\n"));
3156 freearea(areanum--);
3161 /* -------- do.c -------- */
3164 * built-in commands: doX
3167 static int dohelp(struct op *t, char **args)
3170 const struct builtincmd *x;
3172 puts("\nBuilt-in commands:\n"
3173 "-------------------");
3178 col += printf("%c%s", ((col == 0) ? '\t' : ' '), x->name);
3185 #if ENABLE_FEATURE_SH_STANDALONE
3187 const char *applet = applet_names;
3190 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applet);
3195 applet += strlen(applet) + 1;
3200 return EXIT_SUCCESS;
3203 static int dolabel(struct op *t, char **args)
3208 static int dochdir(struct op *t, char **args)
3210 const char *cp, *er;
3214 cp = homedir->value;
3217 er = ": no home directory";
3222 er = ": bad directory";
3224 prs(cp != NULL ? cp : "cd");
3229 static int doshift(struct op *t, char **args)
3233 n = args[1] ? getn(args[1]) : 1;
3235 err("nothing to shift");
3241 setval(lookup("#"), putn(dolc));
3246 * execute login and newgrp directly
3248 static int dologin(struct op *t, char **args)
3253 signal(SIGINT, SIG_DFL);
3254 signal(SIGQUIT, SIG_DFL);
3256 cp = rexecve(args[0], args, makenv(0, NULL));
3263 static int doumask(struct op *t, char **args)
3272 printf("%04o\n", i);
3274 i = bb_strtou(cp, NULL, 8);
3276 err("umask: bad octal number");
3284 static int doexec(struct op *t, char **args)
3298 sv_words = t->words;
3299 t->words = args + 1;
3300 // TODO: test what will happen with "exec break" -
3301 // will it leave t->words pointing to garbage?
3302 // (see http://bugs.busybox.net/view.php?id=846)
3303 if (setjmp(failpt) == 0)
3304 execute(t, NOPIPE, NOPIPE, /* no_fork: */ 1);
3305 t->words = sv_words;
3313 static int dodot(struct op *t, char **args)
3321 DBGPRINTF(("DODOT: enter, t=%p, tleft %p, tright %p, global_env.linep is %s\n",
3322 t, t->left, t->right, ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3326 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3329 DBGPRINTF(("DODOT: cp is %s\n", cp));
3331 sp = any('/', cp) ? ":" : path->value;
3333 DBGPRINTF(("DODOT: sp is %s, global_env.linep is %s\n",
3334 ((sp == NULL) ? "NULL" : sp),
3335 ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3338 tp = global_env.linep;
3339 while (*sp && (*tp = *sp++) != ':')
3341 if (tp != global_env.linep)
3344 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3347 i = open(global_env.linep, O_RDONLY);
3351 DBGPRINTF(("DODOT: remap=%d, exstat=%d, global_env.iofd %d, i %d, global_env.linep is %s\n",
3352 maltmp, exstat, global_env.iofd, i, global_env.linep));
3354 next(maltmp); /* Basically a PUSHIO */
3356 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3368 static int dowait(struct op *t, char **args)
3380 setstatus(waitfor(i, 1));
3384 static int doread(struct op *t, char **args)
3390 if (args[1] == NULL) {
3391 err("Usage: read name ...");
3394 for (wp = args + 1; *wp; wp++) {
3395 for (cp = global_env.linep; !nl && cp < elinep - 1; cp++) {
3396 nb = nonblock_safe_read(0, cp, sizeof(*cp));
3397 if (nb != sizeof(*cp))
3400 if (nl || (wp[1] && any(*cp, ifs->value)))
3406 setval(lookup(*wp), global_env.linep);
3411 static int doeval(struct op *t, char **args)
3413 return RUN(awordlist, args + 1, wdchar);
3416 static int dotrap(struct op *t, char **args)
3421 if (args[1] == NULL) {
3422 for (i = 0; i <= _NSIG; i++)
3431 resetsig = isdigit(args[1][0]);
3432 for (i = resetsig ? 1 : 2; args[i] != NULL; ++i) {
3433 n = getsig(args[i]);
3437 if (args[1][0] != '\0') {
3438 trap[n] = strsave(args[1], 0);
3447 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3455 static int getsig(char *s)
3460 if (n < 0 || n > _NSIG) {
3461 err("trap: bad signal number");
3467 static void setsig(int n, sighandler_t f)
3471 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3477 static int getn(char *as)
3488 for (n = 0; isdigit(*s); s++)
3489 n = (n * 10) + (*s - '0');
3492 err(": bad number");
3497 static int dobreak(struct op *t, char **args)
3499 return brkcontin(args[1], 1);
3502 static int docontinue(struct op *t, char **args)
3504 return brkcontin(args[1], 0);
3507 static int brkcontin(char *cp, int val)
3512 nl = cp == NULL ? 1 : getn(cp);
3519 brklist = bc->nextlev;
3522 err("bad break/continue level");
3525 isbreak = (val != 0);
3526 longjmp(bc->brkpt, 1);
3530 static int doexit(struct op *t, char **args)
3537 setstatus(getn(cp));
3539 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3546 static int doexport(struct op *t, char **args)
3548 rdexp(args + 1, export, EXPORT);
3552 static int doreadonly(struct op *t, char **args)
3554 rdexp(args + 1, ronly, RONLY);
3558 static void rdexp(char **wp, void (*f) (struct var *), int key)
3560 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3561 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3564 for (; *wp != NULL; wp++) {
3565 if (isassign(*wp)) {
3569 for (cp = *wp; *cp != '='; cp++);
3581 static void badid(char *s)
3584 err(": bad identifier");
3587 static int doset(struct op *t, char **args)
3595 for (vp = vlist; vp; vp = vp->next)
3596 varput(vp->name, 1);
3602 FLAG['x'] = FLAG['v'] = 0;
3612 if (*cp >= 'a' && *cp <= 'z')
3622 for (n = 1; args[n]; n++)
3623 setarea((char *) args[n], 0);
3626 setval(lookup("#"), putn(dolc));
3627 setarea((char *) (dolv - 1), 0);
3632 static void varput(char *s, int out)
3634 if (isalnum(*s) || *s == '_') {
3635 write(out, s, strlen(s));
3636 write(out, "\n", 1);
3642 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3643 * This file contains code for the times builtin.
3645 static void times_fmt(char *buf, clock_t val, unsigned clk_tck)
3648 if (sizeof(val) > sizeof(int))
3649 sec = ((unsigned long)val) / clk_tck;
3651 sec = ((unsigned)val) / clk_tck;
3654 sprintf(buf, "%um%u.%03us", min, (sec - min * 60),
3655 /* msec: */ ((unsigned)(val - (clock_t)sec * clk_tck)) * 1000 / clk_tck
3658 sprintf(buf, "%um%us", min, (sec - min * 60));
3662 static int dotimes(struct op *t, char **args)
3665 unsigned clk_tck = sysconf(_SC_CLK_TCK);
3666 /* How much do we need for "NmN.NNNs" ? */
3667 enum { TIMEBUF_SIZE = sizeof(int)*3 + sizeof(int)*3 + 6 };
3668 char u[TIMEBUF_SIZE], s[TIMEBUF_SIZE];
3669 char cu[TIMEBUF_SIZE], cs[TIMEBUF_SIZE];
3673 times_fmt(u, buf.tms_utime, clk_tck);
3674 times_fmt(s, buf.tms_stime, clk_tck);
3675 times_fmt(cu, buf.tms_cutime, clk_tck);
3676 times_fmt(cs, buf.tms_cstime, clk_tck);
3678 printf("%s %s\n%s %s\n", u, s, cu, cs);
3683 /* -------- eval.c -------- */
3688 * blank interpretation
3693 static char **eval(char **ap, int f)
3701 /* Avoid longjmp clobbering */
3706 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3712 if (newenv(setjmp(errpt)) == 0) {
3713 while (*ap && isassign(*ap))
3714 expand(*ap++, &wb, f & ~DOGLOB);
3716 for (wf = ap; *wf; wf++) {
3718 expand(*wf, &wb, f & ~DOGLOB);
3721 for (wb = addword((char *) NULL, wb); *ap; ap++) {
3722 if (!FLAG['k'] || !isassign(*ap))
3723 expand(*ap, &wb, f & ~DOKEY);
3725 wb = addword((char *) 0, wb);
3731 return gflg ? (char **) NULL : wp;
3736 * Make the exported environment from the exported
3737 * names in the dictionary. Keyword assignments
3738 * will already have been done.
3740 static char **makenv(int all, struct wdblock *wb)
3744 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3746 for (vp = vlist; vp; vp = vp->next)
3747 if (all || vp->status & EXPORT)
3748 wb = addword(vp->name, wb);
3749 wb = addword((char *) 0, wb);
3750 return getwords(wb);
3753 static int expand(const char *cp, struct wdblock **wbp, int f)
3759 /* Avoid longjmp clobbering */
3763 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3770 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3771 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3773 xp = strsave(cp, areanum);
3776 *wbp = addword(xp, *wbp);
3780 if (newenv(setjmp(errpt)) == 0) {
3781 PUSHIO(aword, cp, strchar);
3782 global_env.iobase = global_env.iop;
3783 while ((xp = blank(f)) && gflg == 0) {
3784 global_env.linep = xp;
3785 xp = strsave(xp, areanum);
3786 if ((f & DOGLOB) == 0) {
3789 *wbp = addword(xp, *wbp);
3791 *wbp = glob(xp, *wbp);
3799 static char *evalstr(char *cp, int f)
3803 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3806 if (expand(cp, &wb, f)) {
3807 if (wb == NULL || wb->w_nword == 0
3808 || (cp = wb->w_words[0]) == NULL
3810 // TODO: I suspect that
3811 // char *evalstr(char *cp, int f) is actually
3812 // const char *evalstr(const char *cp, int f)!
3823 * Blank interpretation and quoting
3825 static char *blank(int f)
3829 int scanequals, foundequals;
3831 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3833 sp = global_env.linep;
3834 scanequals = f & DOKEY;
3838 c = subgetc('"', foundequals);
3841 if (sp == global_env.linep)
3843 *global_env.linep++ = 0;
3847 if (f & DOBLANK && any(c, ifs->value))
3856 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3859 if (c == '\'' || !any(c, "$`\""))
3861 *global_env.linep++ = c;
3866 if (!isalpha(c) && c != '_')
3869 c = subgetc('"', foundequals);
3871 f & (DOBLANK && any(c, ifs->value)) ||
3872 (!INSUB() && any(c, "\"'"))) {
3883 } else if (!isalnum(c) && c != '_')
3886 *global_env.linep++ = c;
3888 *global_env.linep++ = 0;
3893 * Get characters, substituting for ` and $
3895 static int subgetc(char ec, int quoted)
3899 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3903 if (!INSUB() && ec != '\'') {
3905 if (grave(quoted) == 0)
3907 global_env.iop->task = XGRAVE;
3913 global_env.iop->task = XDOLL;
3922 * Prepare to generate the string returned by ${} substitution.
3924 static int dollar(int quoted)
3929 char *s, c, *cp = NULL;
3932 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3935 s = global_env.linep;
3937 *global_env.linep++ = c;
3938 if (isalpha(c) || c == '_') {
3939 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3940 if (global_env.linep < elinep)
3941 *global_env.linep++ = c;
3946 oiop = global_env.iop;
3947 otask = global_env.iop->task;
3949 global_env.iop->task = XOTHER;
3950 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3951 if (global_env.linep < elinep)
3952 *global_env.linep++ = c;
3953 if (oiop == global_env.iop)
3954 global_env.iop->task = otask;
3961 if (global_env.linep >= elinep) {
3962 err("string in ${} too long");
3964 global_env.linep -= 10;
3966 *global_env.linep = 0;
3968 for (cp = s + 1; *cp; cp++)
3969 if (any(*cp, "=-+?")) {
3974 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3976 /* currently this does not distinguish $* and $@ */
3977 /* should check dollar */
3978 global_env.linep = s;
3979 PUSHIO(awordlist, dolv + 1, dolchar);
3981 } else { /* trap the nasty ${=} */
3992 err("cannot use ${...=...} with $n");
4001 dolp = strsave(cp, areanum);
4006 prs("missing value for ");
4013 } else if (c == '+')
4014 dolp = strsave(cp, areanum);
4015 if (FLAG['u'] && dolp == null) {
4016 prs("unset variable: ");
4020 global_env.linep = s;
4021 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4026 * Run the command in `...` and read its output.
4029 static int grave(int quoted)
4031 /* moved to G: static char child_cmd[LINELIM]; */
4042 char *argument_list[4];
4043 struct wdblock *wb = NULL;
4046 /* Avoid longjmp clobbering */
4050 for (cp = global_env.iop->argp->aword; *cp != '`'; cp++) {
4052 err("no closing `");
4057 /* string copy with dollar expansion */
4058 src = global_env.iop->argp->aword;
4063 while ((*src != '`') && (count < LINELIM)) {
4068 if (*src == '$' && !ignore && !ignore_once) {
4070 /* moved to G to reduce stack usage
4071 char var_name[LINELIM];
4072 char alt_value[LINELIM];
4074 #define var_name (G.grave__var_name)
4075 #define alt_value (G.grave__alt_value)
4088 var_name[var_index++] = *src++;
4089 while (isalnum(*src) || *src=='_')
4090 var_name[var_index++] = *src++;
4091 var_name[var_index] = 0;
4104 err("unclosed ${\n");
4109 while (*src && (*src != '}')) {
4110 alt_value[alt_index++] = *src++;
4112 alt_value[alt_index] = 0;
4114 err("unclosed ${\n");
4121 if (isalpha(*var_name)) {
4122 /* let subshell handle it instead */
4124 char *namep = var_name;
4132 char *altp = alt_value;
4140 wb = addword(lookup(var_name)->name, wb);
4144 vp = lookup(var_name);
4145 if (vp->value != null)
4146 value = (operator == '+') ?
4147 alt_value : vp->value;
4148 else if (operator == '?') {
4151 } else if (alt_index && (operator != '+')) {
4153 if (operator == '=')
4158 while (*value && (count < LINELIM)) {
4173 if (openpipe(pf) < 0)
4176 while ((i = vfork()) == -1 && errno == EAGAIN);
4178 DBGPRINTF3(("GRAVE: i is %p\n", io));
4182 err((char *) bb_msg_memory_exhausted);
4186 waitpid(i, NULL, 0); // safe_waitpid?
4187 global_env.iop->argp->aword = ++cp;
4189 PUSHIO(afile, remap(pf[0]),
4190 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4193 /* allow trapped signals */
4194 /* XXX - Maybe this signal stuff should go as well? */
4195 for (j = 0; j <= _NSIG; j++)
4196 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4199 /* Testcase where below checks are needed:
4200 * close stdout & run this script:
4208 argument_list[0] = (char *) DEFAULT_SHELL;
4209 argument_list[1] = (char *) "-c";
4210 argument_list[2] = child_cmd;
4211 argument_list[3] = NULL;
4213 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4214 prs(argument_list[0]);
4221 static char *unquote(char *as)
4232 /* -------- glob.c -------- */
4238 #define scopy(x) strsave((x), areanum)
4240 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4242 static struct wdblock *cl, *nl;
4243 static const char spcl[] ALIGN1= "[?*";
4245 static struct wdblock *glob(char *cp, struct wdblock *wb)
4253 for (pp = cp; *pp; pp++)
4256 else if (!any(*pp & ~QUOTE, spcl))
4259 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4260 nl = newword(cl->w_nword * 2);
4261 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4262 for (pp = cl->w_words[i]; *pp; pp++)
4263 if (any(*pp, spcl)) {
4264 globname(cl->w_words[i], pp);
4268 nl = addword(scopy(cl->w_words[i]), nl);
4270 for (i = 0; i < cl->w_nword; i++)
4271 DELETE(cl->w_words[i]);
4274 for (i = 0; i < cl->w_nword; i++)
4275 unquote(cl->w_words[i]);
4276 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4278 for (i = 0; i < cl->w_nword; i++)
4279 wb = addword(cl->w_words[i], wb);
4284 wb = addword(unquote(cp), wb);
4288 static void globname(char *we, char *pp)
4291 char *name, *gp, *dp;
4295 char dname[NAME_MAX + 1];
4298 for (np = we; np != pp; pp--)
4301 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4305 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4314 dname[NAME_MAX] = '\0';
4315 while ((de = readdir(dirp)) != NULL) {
4316 /* XXX Hmmm... What this could be? (abial) */
4318 if (ent[j].d_ino == 0)
4321 strncpy(dname, de->d_name, NAME_MAX);
4322 if (dname[0] == '.')
4325 for (k = 0; k < NAME_MAX; k++)
4326 if (any(dname[k], spcl))
4328 if (gmatch(dname, gp)) {
4329 name = generate(we, pp, dname, np);
4330 if (*np && !anys(np, spcl)) {
4331 if (stat(name, &dbuf)) {
4336 nl = addword(name, nl);
4345 * generate a pathname as below.
4346 * start..end1 / middle end
4347 * the slashes come for free
4349 static char *generate(char *start1, char *end1, char *middle, char *end)
4354 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4355 for (xp = start1; xp != end1;)
4357 for (xp = middle; (*op++ = *xp++) != '\0';);
4359 for (xp = end; (*op++ = *xp++) != '\0';);
4363 static int anyspcl(struct wdblock *wb)
4369 for (i = 0; i < wb->w_nword; i++)
4370 if (anys(spcl, *wd++))
4375 static int xstrcmp(char *p1, char *p2)
4377 return strcmp(*(char **) p1, *(char **) p2);
4381 /* -------- word.c -------- */
4383 static struct wdblock *newword(int nw)
4387 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4393 static struct wdblock *addword(char *wd, struct wdblock *wb)
4395 struct wdblock *wb2;
4399 wb = newword(NSTART);
4401 if (nw >= wb->w_bsize) {
4402 wb2 = newword(nw * 2);
4403 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4404 nw * sizeof(char *));
4409 wb->w_words[wb->w_nword++] = wd;
4413 static char **getwords(struct wdblock *wb)
4420 if (wb->w_nword == 0) {
4424 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4425 memcpy((char *) wd, (char *) wb->w_words, nb);
4426 DELETE(wb); /* perhaps should done by caller */
4430 static int (*func) (char *, char *);
4433 static void glob3(char *i, char *j, char *k)
4435 char *index1, *index2, *index3;
4445 *index1++ = *index3;
4446 *index3++ = *index2;
4451 static void glob2(char *i, char *j)
4453 char *index1, *index2, c;
4461 *index1++ = *index2;
4466 static void glob1(char *base, char *lim)
4477 n = (int) (lim - base);
4480 n = v2 * (n / (2 * v2));
4481 hptr = lptr = base + n;
4486 c = (*func) (i, lptr);
4500 c = (*func) (hptr, j);
4524 if (lptr - base >= lim - hptr) {
4525 glob1(hptr + v2, lim);
4540 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4544 glob1(a0, a0 + a1 * a2);
4548 /* -------- io.c -------- */
4554 static int my_getc(int ec)
4558 if (global_env.linep > elinep) {
4559 while ((c = readc()) != '\n' && c);
4560 err("input line too long");
4565 if ((ec != '\'') && (ec != '`') && (global_env.iop->task != XGRAVE)) {
4568 if (c == '\n' && ec != '\"')
4576 static void unget(int c)
4578 if (global_env.iop >= global_env.iobase)
4579 global_env.iop->peekc = c;
4582 static int eofc(void)
4584 return global_env.iop < global_env.iobase || (global_env.iop->peekc == 0 && global_env.iop->prev == 0);
4587 static int readc(void)
4591 RCPRINTF(("READC: global_env.iop %p, global_env.iobase %p\n", global_env.iop, global_env.iobase));
4593 for (; global_env.iop >= global_env.iobase; global_env.iop--) {
4594 RCPRINTF(("READC: global_env.iop %p, peekc 0x%x\n", global_env.iop, global_env.iop->peekc));
4595 c = global_env.iop->peekc;
4597 global_env.iop->peekc = 0;
4600 if (global_env.iop->prev != 0) {
4601 c = (*global_env.iop->iofn)(global_env.iop->argp, global_env.iop);
4607 if (global_env.iop == iostack)
4609 global_env.iop->prev = c;
4610 return global_env.iop->prev;
4612 if (global_env.iop->task == XIO && global_env.iop->prev != '\n') {
4613 global_env.iop->prev = 0;
4614 if (global_env.iop == iostack)
4619 if (global_env.iop->task == XIO) {
4621 global_env.iop->prev = 0;
4622 return global_env.iop->prev;
4624 if (interactive && global_env.iop == iostack + 1) {
4625 #if ENABLE_FEATURE_EDITING
4626 current_prompt = prompt->value;
4634 if (global_env.iop >= iostack) {
4635 RCPRINTF(("READC: return 0, global_env.iop %p\n", global_env.iop));
4639 DBGPRINTF(("READC: leave()...\n"));
4645 static void ioecho(char c)
4648 write(2, &c, sizeof c);
4651 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4653 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, global_env.iop %p\n", argp,
4654 argp->afid, global_env.iop));
4656 /* Set env ptr for io source to next array spot and check for array overflow */
4657 if (++global_env.iop >= &iostack[NPUSH]) {
4659 err("Shell input nested too deeply");
4664 /* We did not overflow the NPUSH array spots so setup data structs */
4666 global_env.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4668 if (argp->afid != AFID_NOBUF)
4669 global_env.iop->argp = argp;
4672 global_env.iop->argp = ioargstack + (global_env.iop - iostack); /* MAL - index into stack */
4673 *global_env.iop->argp = *argp; /* copy data from temp area into stack spot */
4675 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4677 if (global_env.iop == &iostack[0])
4678 global_env.iop->argp->afbuf = &mainbuf;
4680 global_env.iop->argp->afbuf = &sharedbuf;
4682 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4683 /* This line appears to be active when running scripts from command line */
4684 if ((isatty(global_env.iop->argp->afile) == 0)
4685 && (global_env.iop == &iostack[0]
4686 || lseek(global_env.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4687 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4688 bufid = AFID_ID; /* AFID_ID = 0 */
4690 global_env.iop->argp->afid = bufid; /* assign buffer id */
4693 DBGPRINTF(("PUSHIO: iostack %p, global_env.iop %p, afbuf %p\n",
4694 iostack, global_env.iop, global_env.iop->argp->afbuf));
4695 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, global_env.iop %p\n",
4696 &mainbuf, &sharedbuf, bufid, global_env.iop));
4700 global_env.iop->prev = ~'\n';
4701 global_env.iop->peekc = 0;
4702 global_env.iop->xchar = 0;
4703 global_env.iop->nlcount = 0;
4705 if (fn == filechar || fn == linechar)
4706 global_env.iop->task = XIO;
4707 else if (fn == (int (*)(struct ioarg *)) gravechar
4708 || fn == (int (*)(struct ioarg *)) qgravechar)
4709 global_env.iop->task = XGRAVE;
4711 global_env.iop->task = XOTHER;
4714 static struct io *setbase(struct io *ip)
4718 xp = global_env.iobase;
4719 global_env.iobase = ip;
4724 * Input generating functions
4728 * Produce the characters of a string, then a newline, then EOF.
4730 static int nlchar(struct ioarg *ap)
4734 if (ap->aword == NULL)
4745 * Given a list of words, produce the characters
4746 * in them, with a space after each word.
4748 static int wdchar(struct ioarg *ap)
4763 ap->awordlist = NULL;
4768 * Return the characters of a list of words,
4769 * producing a space between them.
4771 static int dolchar(struct ioarg *ap)
4775 wp = *ap->awordlist++;
4777 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4783 static int xxchar(struct ioarg *ap)
4787 if (ap->aword == NULL)
4798 * Produce the characters from a single word (string).
4800 static int strchar(struct ioarg *ap)
4802 if (ap->aword == NULL)
4804 return *ap->aword++;
4808 * Produce quoted characters from a single word (string).
4810 static int qstrchar(struct ioarg *ap)
4814 if (ap->aword == NULL)
4823 * Return the characters from a file.
4825 static int filechar(struct ioarg *ap)
4829 struct iobuf *bp = ap->afbuf;
4831 if (ap->afid != AFID_NOBUF) {
4832 i = (ap->afid != bp->id);
4833 if (i || bp->bufp == bp->ebufp) {
4835 lseek(ap->afile, ap->afpos, SEEK_SET);
4837 i = nonblock_safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4845 bp->ebufp = bp->bufp + i;
4849 return *bp->bufp++ & 0177;
4851 #if ENABLE_FEATURE_EDITING
4852 if (interactive && isatty(ap->afile)) {
4853 /* moved to G: static char filechar_cmdbuf[BUFSIZ]; */
4854 static int position = 0, size = 0;
4856 while (size == 0 || position >= size) {
4857 size = read_line_input(current_prompt, filechar_cmdbuf, BUFSIZ, line_input_state);
4858 if (size < 0) /* Error/EOF */
4861 /* if Ctrl-C, size == 0 and loop will repeat */
4863 c = filechar_cmdbuf[position];
4868 i = nonblock_safe_read(ap->afile, &c, sizeof(c));
4869 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4873 * Return the characters from a here temp file.
4875 static int herechar(struct ioarg *ap)
4879 if (nonblock_safe_read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4887 * Return the characters produced by a process (`...`).
4888 * Quote them if required, and remove any trailing newline characters.
4890 static int gravechar(struct ioarg *ap, struct io *iop)
4894 c = qgravechar(ap, iop) & ~QUOTE;
4900 static int qgravechar(struct ioarg *ap, struct io *iop)
4904 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4909 return '\n' | QUOTE;
4913 } else if ((c = filechar(ap)) == '\n') {
4915 while ((c = filechar(ap)) == '\n')
4923 return c != 0 ? c | QUOTE : 0;
4927 * Return a single command (usually the first line) from a file.
4929 static int linechar(struct ioarg *ap)
4937 ap->afile = -1; /* illegal value */
4944 * remap fd into Shell's fd space
4946 static int remap(int fd)
4952 DBGPRINTF(("REMAP: fd=%d, global_env.iofd=%d\n", fd, global_env.iofd));
4954 if (fd < global_env.iofd) {
4955 for (i = 0; i < NOFILE; i++)
4962 } while (fd >= 0 && fd < global_env.iofd);
4964 for (i = 0; i < NOFILE; i++)
4969 err("too many files open in shell");
4975 static int openpipe(int *pv)
4981 err("can't create pipe - try again");
4985 static void closepipe(int *pv)
4994 /* -------- here.c -------- */
5000 static void markhere(char *s, struct ioword *iop)
5002 struct here *h, *lh;
5004 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
5006 h = (struct here *) space(sizeof(struct here));
5010 h->h_tag = evalstr(s, DOSUB);
5020 for (lh = inhere; lh != NULL; lh = lh->h_next) {
5021 if (lh->h_next == 0) {
5027 iop->io_flag |= IOHERE | IOXHERE;
5028 for (s = h->h_tag; *s; s++) {
5030 iop->io_flag &= ~IOXHERE;
5034 h->h_dosub = ((iop->io_flag & IOXHERE) ? '\0' : '\'');
5037 static void gethere(void)
5039 struct here *h, *hp;
5041 DBGPRINTF7(("GETHERE: enter...\n"));
5043 /* Scan here files first leaving inhere list in place */
5044 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5045 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub /* NUL or ' */);
5047 /* Make inhere list active - keep list intact for scraphere */
5049 hp->h_next = acthere;
5055 static void readhere(char **name, char *s, int ec)
5058 char tname[30] = ".msh_XXXXXX";
5061 char myline[LINELIM + 1];
5064 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5066 tf = mkstemp(tname);
5070 *name = strsave(tname, areanum);
5072 if (newenv(setjmp(errpt)) != 0)
5075 pushio(global_env.iop->argp, (int (*)(struct ioarg *)) global_env.iop->iofn);
5076 global_env.iobase = global_env.iop;
5078 if (interactive && global_env.iop <= iostack) {
5079 #if ENABLE_FEATURE_EDITING
5080 current_prompt = cprompt->value;
5082 prs(cprompt->value);
5086 while ((c = my_getc(ec)) != '\n' && c) {
5089 if (thenext >= &myline[LINELIM]) {
5096 if (strcmp(s, myline) == 0 || c == 0)
5099 write(tf, myline, (int) (thenext - myline));
5102 prs("here document `");
5112 * open here temp file.
5113 * if unquoted here, expand here temp file into second temp file.
5115 static int herein(char *hname, int xdoll)
5121 /* Avoid longjmp clobbering */
5127 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5129 hf = open(hname, O_RDONLY);
5135 char tname[30] = ".msh_XXXXXX";
5138 tf = mkstemp(tname);
5142 if (newenv(setjmp(errpt)) == 0) {
5143 PUSHIO(afile, hf, herechar);
5144 setbase(global_env.iop);
5145 while ((c = subgetc(0, 0)) != 0) {
5147 write(tf, &c, sizeof c);
5153 tf = open(tname, O_RDONLY);
5160 static void scraphere(void)
5164 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5166 for (h = inhere; h != NULL; h = h->h_next) {
5167 if (h->h_iop && h->h_iop->io_name)
5168 unlink(h->h_iop->io_name);
5173 /* unlink here temp files before a freearea(area) */
5174 static void freehere(int area)
5176 struct here *h, *hl;
5178 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5181 for (h = acthere; h != NULL; h = h->h_next)
5182 if (getarea((char *) h) >= area) {
5183 if (h->h_iop->io_name != NULL)
5184 unlink(h->h_iop->io_name);
5186 acthere = h->h_next;
5188 hl->h_next = h->h_next;
5194 /* -------- sh.c -------- */
5199 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5200 int msh_main(int argc, char **argv)
5206 int (*iof) (struct ioarg *);
5210 sharedbuf.id = AFID_NOBUF;
5211 mainbuf.id = AFID_NOBUF;
5212 elinep = line + sizeof(line) - 5;
5214 #if ENABLE_FEATURE_EDITING
5215 line_input_state = new_line_input_t(FOR_SHELL);
5218 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5224 assign(*ap++, !COPYV);
5225 for (ap = environ; *ap;)
5226 export(lookup(*ap++));
5231 shell = lookup("SHELL");
5232 if (shell->value == null)
5233 setval(shell, (char *)DEFAULT_SHELL);
5236 homedir = lookup("HOME");
5237 if (homedir->value == null)
5238 setval(homedir, "/");
5241 setval(lookup("$"), putn(getpid()));
5243 path = lookup("PATH");
5244 if (path->value == null) {
5245 /* Can be merged with same string elsewhere in bbox */
5247 setval(path, bb_default_root_path);
5249 setval(path, bb_default_path);
5253 ifs = lookup("IFS");
5254 if (ifs->value == null)
5255 setval(ifs, " \t\n");
5258 mshdbg_var = lookup("MSHDEBUG");
5259 if (mshdbg_var->value == null)
5260 setval(mshdbg_var, "0");
5263 prompt = lookup("PS1");
5264 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5265 if (prompt->value == null)
5267 setval(prompt, DEFAULT_USER_PROMPT);
5268 if (geteuid() == 0) {
5269 setval(prompt, DEFAULT_ROOT_PROMPT);
5270 prompt->status &= ~EXPORT;
5272 cprompt = lookup("PS2");
5273 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5274 if (cprompt->value == null)
5276 setval(cprompt, "> ");
5282 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5283 for (s = argv[0] + 1; *s; s++)
5286 prompt->status &= ~EXPORT;
5287 cprompt->status &= ~EXPORT;
5289 setval(cprompt, "");
5292 PUSHIO(aword, *++argv, iof = nlchar);
5300 /* standard input */
5304 prompt->status &= ~EXPORT;
5312 if (*s >= 'a' && *s <= 'z')
5320 if (iof == filechar && --argc > 0) {
5322 setval(cprompt, "");
5323 prompt->status &= ~EXPORT;
5324 cprompt->status &= ~EXPORT;
5326 /* Shell is non-interactive, activate printf-based debug */
5328 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5332 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5336 exit(1); /* Exit on error */
5342 /* This won't be true if PUSHIO has been called, say from newfile() above */
5343 if (global_env.iop < iostack) {
5344 PUSHIO(afile, 0, iof);
5345 if (isatty(0) && isatty(1) && !cflag) {
5347 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5349 printf("\n\n%s built-in shell (msh with debug)\n", bb_banner);
5351 printf("\n\n%s built-in shell (msh)\n", bb_banner);
5353 printf("Enter 'help' for a list of built-in commands.\n\n");
5358 signal(SIGQUIT, qflag);
5359 if (name && name[0] == '-') {
5361 f = open(".profile", O_RDONLY);
5364 f = open("/etc/profile", O_RDONLY);
5369 signal(SIGTERM, sig);
5371 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5372 signal(SIGINT, onintr);
5374 /* Handle "msh SCRIPT VAR=val params..." */
5375 /* Disabled: bash does not do it! */
5378 /* skip leading args of the form VAR=val */
5379 while (*argv && assign(*argv, !COPYV)) {
5389 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5391 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, global_env.iop %p, iostack %p\n", interactive, global_env.iop, iostack));
5394 if (interactive && global_env.iop <= iostack) {
5395 #if ENABLE_FEATURE_EDITING
5396 current_prompt = prompt->value;
5402 /* Ensure that getenv("PATH") stays current */
5403 setenv("PATH", path->value, 1);
5406 DBGPRINTF(("MSH_MAIN: returning.\n"));
5411 * Copyright (c) 1987,1997, Prentice Hall
5412 * All rights reserved.
5414 * Redistribution and use of the MINIX operating system in source and
5415 * binary forms, with or without modification, are permitted provided
5416 * that the following conditions are met:
5418 * Redistributions of source code must retain the above copyright
5419 * notice, this list of conditions and the following disclaimer.
5421 * Redistributions in binary form must reproduce the above
5422 * copyright notice, this list of conditions and the following
5423 * disclaimer in the documentation and/or other materials provided
5424 * with the distribution.
5426 * Neither the name of Prentice Hall nor the names of the software
5427 * authors or contributors may be used to endorse or promote
5428 * products derived from this software without specific prior
5429 * written permission.
5431 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5432 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5433 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5434 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5435 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5436 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5437 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5438 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5439 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5440 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5441 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5442 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.