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.
15 #include <sys/times.h>
22 # include <sys/types.h>
23 # include <sys/stat.h>
24 # include <sys/wait.h>
35 # define bb_dev_null "/dev/null"
36 # define DEFAULT_SHELL "/proc/self/exe"
37 # define bb_banner "busybox standalone"
38 # define ENABLE_FEATURE_SH_STANDALONE 0
39 # define bb_msg_memory_exhausted "memory exhausted"
40 # define xmalloc(size) malloc(size)
41 # define msh_main(argc,argv) main(argc,argv)
42 # define safe_read(fd,buf,count) read(fd,buf,count)
43 # define nonblock_safe_read(fd,buf,count) read(fd,buf,count)
44 # define NOT_LONE_DASH(s) ((s)[0] != '-' || (s)[1])
45 # define LONE_CHAR(s,c) ((s)[0] == (c) && !(s)[1])
46 # define NORETURN __attribute__ ((__noreturn__))
47 static int find_applet_by_name(const char *applet)
51 static char *utoa_to_buf(unsigned n, char *buf, unsigned buflen)
54 assert(sizeof(unsigned) == 4);
57 for (i = 1000000000; i; i /= 10) {
59 if (res || out || i == 1) {
69 static char *itoa_to_buf(int n, char *buf, unsigned buflen)
71 if (buflen && n < 0) {
76 return utoa_to_buf((unsigned)n, buf, buflen);
78 static char local_buf[12];
79 static char *itoa(int n)
81 *(itoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
85 # include "busybox.h" /* for applet_names */
91 static int mshdbg = MSHDEBUG;
93 #define DBGPRINTF(x) if (mshdbg > 0) printf x
94 #define DBGPRINTF0(x) if (mshdbg > 0) printf x
95 #define DBGPRINTF1(x) if (mshdbg > 1) printf x
96 #define DBGPRINTF2(x) if (mshdbg > 2) printf x
97 #define DBGPRINTF3(x) if (mshdbg > 3) printf x
98 #define DBGPRINTF4(x) if (mshdbg > 4) printf x
99 #define DBGPRINTF5(x) if (mshdbg > 5) printf x
100 #define DBGPRINTF6(x) if (mshdbg > 6) printf x
101 #define DBGPRINTF7(x) if (mshdbg > 7) printf x
102 #define DBGPRINTF8(x) if (mshdbg > 8) printf x
103 #define DBGPRINTF9(x) if (mshdbg > 9) printf x
105 static int mshdbg_rc = 0;
107 #define RCPRINTF(x) if (mshdbg_rc) printf x
112 #define DBGPRINTF0(x) ((void)0)
113 #define DBGPRINTF1(x) ((void)0)
114 #define DBGPRINTF2(x) ((void)0)
115 #define DBGPRINTF3(x) ((void)0)
116 #define DBGPRINTF4(x) ((void)0)
117 #define DBGPRINTF5(x) ((void)0)
118 #define DBGPRINTF6(x) ((void)0)
119 #define DBGPRINTF7(x) ((void)0)
120 #define DBGPRINTF8(x) ((void)0)
121 #define DBGPRINTF9(x) ((void)0)
123 #define RCPRINTF(x) ((void)0)
125 #endif /* MSHDEBUG */
128 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
129 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
130 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
132 # define DEFAULT_ROOT_PROMPT "# "
133 # define DEFAULT_USER_PROMPT "$ "
137 /* -------- sh.h -------- */
143 #define NPUSH 8 /* limit to input nesting */
146 #define NOFILE 20 /* Number of open files */
147 #define NUFILE 10 /* Number of user-accessible files */
148 #define FDBASE 10 /* First file usable by Shell */
151 * values returned by wait
153 #define WAITSIG(s) ((s) & 0177)
154 #define WAITVAL(s) (((s) >> 8) & 0377)
155 #define WAITCORE(s) (((s) & 0200) != 0)
158 * library and system definitions
160 typedef void xint; /* base type of jmp_buf, for not broken compilers */
165 #define NOBLOCK ((struct op *)NULL)
166 #define NOWORD ((char *)NULL)
167 #define NOWORDS ((char **)NULL)
168 #define NOPIPE ((int *)NULL)
174 smallint io_flag; /* action (below) */
175 int io_fd; /* fd affected */
176 char *io_name; /* file name */
179 #define IOREAD 1 /* < */
180 #define IOHERE 2 /* << (here file) */
181 #define IOWRITE 4 /* > */
182 #define IOCAT 8 /* >> */
183 #define IOXHERE 16 /* ${}, ` in << */
184 #define IODUP 32 /* >&digit */
185 #define IOCLOSE 64 /* >&- */
187 #define IODEFAULT (-1) /* "default" IO fd */
191 * Description of a command or an operation on commands.
192 * Might eventually use a union.
195 smallint op_type; /* operation type, see Txxxx below */
196 char **op_words; /* arguments to a command */
197 struct ioword **ioact; /* IO actions (eg, < > >>) */
200 char *str; /* identifier for case and for */
203 #define TCOM 1 /* command */
204 #define TPAREN 2 /* (c-list) */
205 #define TPIPE 3 /* a | b */
206 #define TLIST 4 /* a [&;] b */
207 #define TOR 5 /* || */
208 #define TAND 6 /* && */
216 #define TPAT 14 /* pattern in case */
217 #define TBRACE 15 /* {c-list} */
218 #define TASYNC 16 /* c & */
219 /* Added to support "." file expansion */
222 /* Strings for names to make debug easier */
224 static const char *const T_CMD_NAMES[] = {
246 #define AREASIZE (90000)
249 * flags to control evaluation of words
251 #define DOSUB 1 /* interpret $, `, and quotes */
252 #define DOBLANK 2 /* perform blank interpretation */
253 #define DOGLOB 4 /* interpret [?* */
254 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
255 #define DOTRIM 16 /* trim resulting string */
257 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
262 struct brkcon *nextlev;
266 static smallint trapset; /* trap pending (signal number) */
268 static smallint yynerrs; /* yacc (flag) */
270 /* moved to G: static char line[LINELIM]; */
272 #if ENABLE_FEATURE_EDITING
273 static char *current_prompt;
274 static line_input_t *line_input_state;
281 static const char *rexecve(char *c, char **v, char **envp);
282 static char *evalstr(char *cp, int f);
283 static char *putn(int n);
284 static char *unquote(char *as);
285 static int rlookup(char *n);
286 static struct wdblock *glob(char *cp, struct wdblock *wb);
287 static int my_getc(int ec);
288 static int subgetc(char ec, int quoted);
289 static char **makenv(int all, struct wdblock *wb);
290 static char **eval(char **ap, int f);
291 static int setstatus(int s);
292 static int waitfor(int lastpid, int canintr);
294 static void onintr(int s); /* SIGINT handler */
296 static int newenv(int f);
297 static void quitenv(void);
298 static void next(int f);
299 static void setdash(void);
300 static void onecommand(void);
301 static void runtrap(int i);
304 /* -------- area stuff -------- */
306 #define REGSIZE sizeof(struct region)
308 /* #define SHRINKBY (64) */
312 #define ALIGN (sizeof(int)-1)
321 /* -------- grammar stuff -------- */
346 /* Added for "." file expansion */
349 #define YYERRCODE 300
352 #define CONTIN 01 /* skip new lines to complete command */
354 static struct op *pipeline(int cf);
355 static struct op *andor(void);
356 static struct op *c_list(void);
357 static int synio(int cf);
358 static void musthave(int c, int cf);
359 static struct op *simple(void);
360 static struct op *nested(int type, int mark);
361 static struct op *command(int cf);
362 static struct op *dogroup(int onlydone);
363 static struct op *thenpart(void);
364 static struct op *elsepart(void);
365 static struct op *caselist(void);
366 static struct op *casepart(void);
367 static char **pattern(void);
368 static char **wordlist(void);
369 static struct op *list(struct op *t1, struct op *t2);
370 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
371 static struct op *newtp(void);
372 static struct op *namelist(struct op *t);
373 static char **copyw(void);
374 static void word(char *cp);
375 static struct ioword **copyio(void);
376 static struct ioword *io(int u, int f, char *cp);
377 static int yylex(int cf);
378 static int collect(int c, int c1);
379 static int dual(int c);
380 static void diag(int ec);
381 static char *tree(unsigned size);
383 /* -------- var.h -------- */
392 #define COPYV 1 /* flag to setval, suggesting copy */
393 #define RONLY 01 /* variable is read-only */
394 #define EXPORT 02 /* variable is to be exported */
395 #define GETCELL 04 /* name & value space was got with getcell */
397 static int yyparse(void);
400 /* -------- io.h -------- */
403 unsigned id; /* buffer id */
404 char buf[512]; /* buffer */
405 char *bufp; /* pointer into buffer */
406 char *ebufp; /* pointer to end of buffer */
409 /* possible arguments to an IO function */
413 int afile; /* file descriptor */
414 unsigned afid; /* buffer id */
415 off_t afpos; /* file position */
416 struct iobuf *afbuf; /* buffer for this file */
419 /* an input generator's state */
421 int (*iofn) (struct ioarg *, struct io *);
424 char prev; /* previous character read by readc() */
425 char nlcount; /* for `'s */
426 char xchar; /* for `'s */
427 char task; /* reason for pushed IO */
430 #define XOTHER 0 /* none of the below */
431 #define XDOLL 1 /* expanding ${} */
432 #define XGRAVE 2 /* expanding `'s */
433 #define XIO 3 /* file IO */
437 * input generators for IO structure
439 static int nlchar(struct ioarg *ap);
440 static int strchar(struct ioarg *ap);
441 static int qstrchar(struct ioarg *ap);
442 static int filechar(struct ioarg *ap);
443 static int herechar(struct ioarg *ap);
444 static int linechar(struct ioarg *ap);
445 static int gravechar(struct ioarg *ap, struct io *iop);
446 static int qgravechar(struct ioarg *ap, struct io *iop);
447 static int dolchar(struct ioarg *ap);
448 static int wdchar(struct ioarg *ap);
449 static void scraphere(void);
450 static void freehere(int area);
451 static void gethere(void);
452 static void markhere(char *s, struct ioword *iop);
453 static int herein(char *hname, int xdoll);
454 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
457 static int eofc(void);
458 static int readc(void);
459 static void unget(int c);
460 static void ioecho(char c);
466 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
467 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
468 static int remap(int fd);
469 static int openpipe(int *pv);
470 static void closepipe(int *pv);
471 static struct io *setbase(struct io *ip);
473 /* -------- word.h -------- */
475 #define NSTART 16 /* default number of words to allow for initially */
480 /* bounds are arbitrary */
484 static struct wdblock *addword(char *wd, struct wdblock *wb);
485 static struct wdblock *newword(int nw);
486 static char **getwords(struct wdblock *wb);
488 /* -------- misc stuff -------- */
490 static int dolabel(struct op *t, char **args);
491 static int dohelp(struct op *t, char **args);
492 static int dochdir(struct op *t, char **args);
493 static int doshift(struct op *t, char **args);
494 static int dologin(struct op *t, char **args);
495 static int doumask(struct op *t, char **args);
496 static int doexec(struct op *t, char **args);
497 static int dodot(struct op *t, char **args);
498 static int dowait(struct op *t, char **args);
499 static int doread(struct op *t, char **args);
500 static int doeval(struct op *t, char **args);
501 static int dotrap(struct op *t, char **args);
502 static int dobreak(struct op *t, char **args);
503 static int doexit(struct op *t, char **args);
504 static int doexport(struct op *t, char **args);
505 static int doreadonly(struct op *t, char **args);
506 static int doset(struct op *t, char **args);
507 static int dotimes(struct op *t, char **args);
508 static int docontinue(struct op *t, char **args);
510 static int forkexec(struct op *t, int *pin, int *pout, int no_fork, char **wp);
511 static int execute(struct op *t, int *pin, int *pout, int no_fork);
512 static int iosetup(struct ioword *iop, int pipein, int pipeout);
513 static void brkset(struct brkcon *bc);
514 static int getsig(char *s);
515 static void setsig(int n, sighandler_t f);
516 static int getn(char *as);
517 static int brkcontin(char *cp, int val);
518 static void rdexp(char **wp, void (*f) (struct var *), int key);
519 static void badid(char *s);
520 static void varput(char *s, int out);
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 void readhere(char **name, char *s, int ec);
529 static int xxchar(struct ioarg *ap);
534 struct ioword *h_iop;
538 static const char *const signame[] = {
541 NULL, /* interrupt */
543 "Illegal instruction",
547 "Floating Point Exception",
552 NULL, /* broken pipe */
558 typedef int (*builtin_func_ptr)(struct op *, char **);
562 builtin_func_ptr builtinfunc;
565 static const struct builtincmd builtincmds[] = {
568 { "break" , dobreak },
570 { "continue", docontinue },
574 { "export" , doexport },
576 { "login" , dologin },
577 { "newgrp" , dologin },
579 { "readonly", doreadonly },
581 { "shift" , doshift },
582 { "times" , dotimes },
584 { "umask" , doumask },
589 static struct op *dowholefile(int /*, int*/);
595 static uint8_t exstat;
596 static smallint gflg; /* (seems to be a parse error indicator) */
597 static smallint interactive; /* Is this an interactive shell */
598 static smallint execflg;
599 static smallint isbreak; /* "break" statement was seen */
600 static int multiline; /* '\n' changed to ';' (counter) */
601 static struct op *outtree; /* result from parser */
604 static struct brkcon *brklist;
605 static struct wdblock *wdlist;
606 static struct wdblock *iolist;
609 static struct var *mshdbg_var;
611 static struct var *vlist; /* dictionary */
612 static struct var *homedir; /* home directory */
613 static struct var *prompt; /* main prompt */
614 static struct var *cprompt; /* continuation prompt */
615 static struct var *path; /* search path for commands */
616 static struct var *shell; /* shell to interpret command files */
617 static struct var *ifs; /* field separators */
619 static int areanum; /* current allocation area */
620 static smallint intr; /* interrupt pending (bool) */
621 static smallint heedint = 1; /* heed interrupt signals (bool) */
623 static char *null = (char*)""; /* null value for variable */
624 static void (*qflag)(int) = SIG_IGN;
628 static int iounit = IODEFAULT;
629 static YYSTYPE yylval;
630 static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
632 static struct here *inhere; /* list of hear docs while parsing */
633 static struct here *acthere; /* list of active here documents */
634 static struct region *areabot; /* bottom of area */
635 static struct region *areatop; /* top of area */
636 static struct region *areanxt; /* starting point of scan */
638 static void *brkaddr;
640 #define AFID_NOBUF (~0)
645 * parsing & execution environment
651 xint *errpt; /* void * */
658 struct env global_env;
659 struct ioarg temparg; // = { .afid = AFID_NOBUF }; /* temporary for PUSHIO */
660 unsigned bufid; // = AFID_ID; /* buffer id counter */
661 char ourtrap[_NSIG + 1];
662 char *trap[_NSIG + 1];
663 struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
664 struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
665 struct ioarg ioargstack[NPUSH];
669 * -k: look for name=value everywhere on command line
671 * -t: exit after reading and executing one command
674 * -u: unset variables net diagnostic
676 char flags['z' - 'a' + 1];
677 char filechar_cmdbuf[BUFSIZ];
679 char child_cmd[LINELIM];
681 struct io iostack[NPUSH];
683 char grave__var_name[LINELIM];
684 char grave__alt_value[LINELIM];
687 #define G (*ptr_to_globals)
688 #define global_env (G.global_env )
689 #define temparg (G.temparg )
690 #define bufid (G.bufid )
691 #define ourtrap (G.ourtrap )
692 #define trap (G.trap )
693 #define sharedbuf (G.sharedbuf )
694 #define mainbuf (G.mainbuf )
695 #define ioargstack (G.ioargstack )
696 /* this looks weird, but is OK ... we index FLAG with 'a'...'z' */
697 #define FLAG (G.flags - 'a' )
698 #define filechar_cmdbuf (G.filechar_cmdbuf)
699 #define line (G.line )
700 #define child_cmd (G.child_cmd )
701 #define iostack (G.iostack )
702 #define INIT_G() do { \
703 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
704 global_env.linep = line; \
705 global_env.iobase = iostack; \
706 global_env.iop = iostack - 1; \
707 global_env.iofd = FDBASE; \
708 temparg.afid = AFID_NOBUF; \
713 /* in substitution */
714 #define INSUB() (global_env.iop->task == XGRAVE || global_env.iop->task == XDOLL)
716 #define RUN(what, arg, gen) ((temparg.what = (arg)), run(&temparg, (gen)))
719 static void print_tree(struct op *head)
722 DBGPRINTF(("PRINT_TREE: no tree\n"));
726 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
730 print_tree(head->left);
733 print_tree(head->right);
735 #endif /* MSHDEBUG */
741 static void prs(const char *s)
744 xwrite_str(STDERR_FILENO, s);
747 static void prn(unsigned u)
752 static void echo(char **wp)
757 for (i = 0; wp[i]; i++) {
765 static void closef(int i)
771 static void closeall(void)
775 for (u = NUFILE; u < NOFILE;)
780 /* fail but return to process next command */
781 static void fail(void) NORETURN;
782 static void fail(void)
788 /* abort shell (or fail in subshell) */
789 static void leave(void) NORETURN;
790 static void leave(void)
792 DBGPRINTF(("LEAVE: leave called!\n"));
803 static void warn(const char *s)
815 static void err(const char *s)
822 if (global_env.errpt)
823 longjmp(global_env.errpt, 1);
825 global_env.iop = global_env.iobase = iostack;
829 /* -------- area.c -------- */
832 * All memory between (char *)areabot and (char *)(areatop+1) is
833 * exclusively administered by the area management routines.
834 * It is assumed that sbrk() and brk() manipulate the high end.
838 void * __q = (void *)-1; \
839 if (brkaddr + (int)(X) < brktop) { \
841 brkaddr += (int)(X); \
846 static void initarea(void)
848 brkaddr = xmalloc(AREASIZE);
849 brktop = brkaddr + AREASIZE;
851 while ((long) sbrk(0) & ALIGN)
853 areabot = (struct region *) sbrk(REGSIZE);
855 areabot->next = areabot;
856 areabot->area = BUSY;
861 static char *getcell(unsigned nbytes)
864 struct region *p, *q;
871 /* silly and defeats the algorithm */
873 * round upwards and add administration area
875 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
878 if (p->area > areanum) {
882 while ((q = p->next)->area > areanum && q != areanxt)
885 * exit loop if cell big enough
894 i = nregio >= GROWBY ? nregio : GROWBY;
895 p = (struct region *) sbrk(i * REGSIZE);
896 if (p == (struct region *) -1)
901 abort(); /* allocated areas are contiguous */
911 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
913 areanxt = p + nregio;
916 * split into requested area and rest
918 if (areanxt + 1 > q) {
920 abort(); /* insufficient space left for admin */
923 areanxt->area = FREE;
927 return (char *) (p + 1);
930 static void freecell(char *cp)
934 p = (struct region *) cp;
942 #define DELETE(obj) freecell((char *)obj)
944 static void freearea(int a)
946 struct region *p, *top;
949 for (p = areabot; p != top; p = p->next)
954 static void setarea(char *cp, int a)
958 p = (struct region *) cp;
963 static int getarea(char *cp)
965 return ((struct region *) cp - 1)->area;
968 static void garbage(void)
970 struct region *p, *q, *top;
973 for (p = areabot; p != top; p = p->next) {
974 if (p->area > areanum) {
975 while ((q = p->next)->area > areanum)
981 if (areatop >= q + SHRINKBY && q->area > areanum) {
982 brk((char *) (q + 1));
990 static void *get_space(int n)
996 err("out of string space");
1000 static char *strsave(const char *s, int a)
1004 cp = get_space(strlen(s) + 1);
1006 // FIXME: I highly doubt this is good.
1015 /* -------- var.c -------- */
1017 static int eqname(const char *n1, const char *n2)
1019 for (; *n1 != '=' && *n1 != '\0'; n1++)
1022 return *n2 == '\0' || *n2 == '=';
1025 static const char *findeq(const char *cp)
1027 while (*cp != '\0' && *cp != '=')
1033 * Find the given name in the dictionary
1034 * and return its value. If the name was
1035 * not previously there, enter it now and
1036 * return a null value.
1038 static struct var *lookup(const char *n)
1040 // FIXME: dirty hack
1041 static struct var dummy;
1049 dummy.name = (char*)n;
1050 for (c = 0; isdigit(*n) && c < 1000; n++)
1051 c = c * 10 + *n - '0';
1052 dummy.status = RONLY;
1053 dummy.value = (c <= dolc ? dolv[c] : null);
1057 for (vp = vlist; vp; vp = vp->next)
1058 if (eqname(vp->name, n))
1062 vp = get_space(sizeof(*vp));
1063 if (vp == 0 || (vp->name = get_space((int) (cp - n) + 2)) == NULL) {
1064 dummy.name = dummy.value = (char*)"";
1069 while ((*xp = *n++) != '\0' && *xp != '=')
1073 setarea((char *) vp, 0);
1074 setarea((char *) vp->name, 0);
1077 vp->status = GETCELL;
1083 * if name is not NULL, it must be
1084 * a prefix of the space `val',
1086 * this is all so that exporting
1087 * values is reasonably painless.
1089 static void nameval(struct var *vp, const char *val, const char *name)
1095 if (vp->status & RONLY) {
1097 while (*xp && *xp != '=')
1098 fputc(*xp++, stderr);
1099 err(" is read-only");
1104 xp = get_space(strlen(vp->name) + strlen(val) + 2);
1107 /* make string: name=value */
1111 while ((*xp = *cp++) != '\0' && *xp != '=')
1118 if (vp->status & GETCELL)
1119 freecell(vp->name); /* form new string `name=value' */
1120 vp->name = (char*)name;
1121 vp->value = (char*)val;
1126 * give variable at `vp' the value `val'.
1128 static void setval(struct var *vp, const char *val)
1130 nameval(vp, val, NULL);
1133 static void export(struct var *vp)
1135 vp->status |= EXPORT;
1138 static void ronly(struct var *vp)
1140 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1141 vp->status |= RONLY;
1144 static int isassign(const char *s)
1147 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1150 /* no isalpha() - we shouldn't use locale */
1151 /* c | 0x20 - lowercase (Latin) letters */
1152 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1163 && (unsigned)(c - '0') > 9 /* not number */
1164 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1171 static int assign(const char *s, int cf)
1176 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1178 if (!isalpha(*s) && *s != '_')
1180 for (cp = s; *cp != '='; cp++)
1181 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1184 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1186 vp->status &= ~GETCELL;
1190 static int checkname(char *cp)
1192 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1194 if (!isalpha(*cp++) && *(cp - 1) != '_')
1197 if (!isalnum(*cp++) && *(cp - 1) != '_')
1202 static void putvlist(int f, int out)
1206 for (vp = vlist; vp; vp = vp->next) {
1207 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1208 if (vp->status & EXPORT)
1209 write(out, "export ", 7);
1210 if (vp->status & RONLY)
1211 write(out, "readonly ", 9);
1212 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1213 write(out, "\n", 1);
1222 static void sig(int i)
1228 static void runtrap(int i)
1233 if (trapstr == NULL)
1239 RUN(aword, trapstr, nlchar);
1243 static void setdash(void)
1247 char m['z' - 'a' + 1];
1250 for (c = 'a'; c <= 'z'; c++)
1254 setval(lookup("-"), m);
1257 static int newfile(char *s)
1261 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1264 if (NOT_LONE_DASH(s)) {
1265 DBGPRINTF(("NEWFILE: s is %s\n", s));
1266 f = open(s, O_RDONLY);
1269 err(": can't open");
1280 struct op *scantree(struct op *head)
1287 if (head->left != NULL) {
1288 dotnode = scantree(head->left);
1293 if (head->right != NULL) {
1294 dotnode = scantree(head->right);
1299 if (head->op_words == NULL)
1302 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1304 if ((head->op_type != TDOT) && LONE_CHAR(head->op_words[0], '.')) {
1305 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1314 static void onecommand(void)
1319 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1321 while (global_env.oenv)
1330 global_env.errpt = NULL;
1331 global_env.linep = line;
1339 setjmp(failpt); /* Bruce Evans' fix */
1341 if (setjmp(failpt) || yyparse() || intr) {
1342 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1344 while (global_env.oenv)
1347 if (!interactive && intr)
1360 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1362 execute(outtree, NOPIPE, NOPIPE, /* no_fork: */ 0);
1365 if (!interactive && intr) {
1377 static int newenv(int f)
1381 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1388 ep = get_space(sizeof(*ep));
1390 while (global_env.oenv)
1395 global_env.oenv = ep;
1396 global_env.errpt = errpt;
1401 static void quitenv(void)
1406 DBGPRINTF(("QUITENV: global_env.oenv=%p\n", global_env.oenv));
1408 ep = global_env.oenv;
1410 fd = global_env.iofd;
1412 /* should close `'d files */
1414 while (--fd >= global_env.iofd)
1420 * Is character c in s?
1422 static int any(int c, const char *s)
1431 * Is any character from s1 in s2?
1433 static int anys(const char *s1, const char *s2)
1441 static char *putn(int n)
1446 static void next(int f)
1448 PUSHIO(afile, f, filechar);
1451 static void onintr(int s UNUSED_PARAM) /* ANSI C requires a parameter */
1453 signal(SIGINT, onintr);
1460 } else if (heedint) {
1467 /* -------- gmatch.c -------- */
1469 * int gmatch(string, pattern)
1470 * char *string, *pattern;
1472 * Match a pattern as in sh(1).
1477 #define QMASK (CMASK & ~QUOTE)
1478 #define NOT '!' /* might use ^ */
1480 static const char *cclass(const char *p, int sub)
1482 int c, d, not, found;
1492 if (p[1] == '-' && p[2] != ']') {
1497 if (c == sub || (c <= sub && sub <= d))
1499 } while (*++p != ']');
1500 return found ? p + 1 : NULL;
1503 static int gmatch(const char *s, const char *p)
1507 if (s == NULL || p == NULL)
1510 while ((pc = *p++ & CMASK) != '\0') {
1527 if (*p == '\0' || gmatch(s, p))
1529 } while (*s++ != '\0');
1533 if (sc != (pc & ~QUOTE))
1541 /* -------- csyn.c -------- */
1543 * shell: syntax (C version)
1546 static void yyerror(const char *s) NORETURN;
1547 static void yyerror(const char *s)
1550 if (interactive && global_env.iop <= iostack) {
1552 while (eofc() == 0 && yylex(0) != '\n')
1559 static void zzerr(void) NORETURN;
1560 static void zzerr(void)
1562 yyerror("syntax error");
1567 DBGPRINTF7(("YYPARSE: enter...\n"));
1574 return yynerrs; /* 0/1 */
1577 static struct op *pipeline(int cf)
1582 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1586 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1589 while ((c = yylex(0)) == '|') {
1590 p = command(CONTIN);
1592 DBGPRINTF8(("PIPELINE: error!\n"));
1596 if (t->op_type != TPAREN && t->op_type != TCOM) {
1597 /* shell statement */
1598 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1601 t = block(TPIPE, t, p, NOWORDS);
1606 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1610 static struct op *andor(void)
1615 DBGPRINTF7(("ANDOR: enter...\n"));
1619 DBGPRINTF9(("ANDOR: t=%p\n", t));
1622 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1623 p = pipeline(CONTIN);
1625 DBGPRINTF8(("ANDOR: error!\n"));
1629 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1635 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1639 static struct op *c_list(void)
1644 DBGPRINTF7(("C_LIST: enter...\n"));
1651 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1653 while ((c = yylex(0)) == ';' || c == '&'
1654 || (multiline && c == '\n')
1662 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1670 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1674 static int synio(int cf)
1680 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1683 if (c != '<' && c != '>') {
1690 iop = io(iounit, i, yylval.cp);
1694 markhere(yylval.cp, iop);
1696 DBGPRINTF7(("SYNIO: returning 1\n"));
1700 static void musthave(int c, int cf)
1702 peeksym = yylex(cf);
1704 DBGPRINTF7(("MUSTHAVE: error!\n"));
1711 static struct op *simple(void)
1717 switch (peeksym = yylex(0)) {
1738 static struct op *nested(int type, int mark)
1742 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1748 return block(type, t, NOBLOCK, NOWORDS);
1751 static struct op *command(int cf)
1754 struct wdblock *iosave;
1757 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1783 t = nested(TPAREN, ')');
1787 t = nested(TBRACE, '}');
1797 t->op_words = wordlist();
1799 if (c != '\n' && c != ';')
1801 t->left = dogroup(0);
1809 t->op_type = (c == WHILE ? TWHILE : TUNTIL);
1811 t->right = dogroup(1);
1812 /* t->op_words = NULL; - newtp() did this */
1823 musthave(IN, CONTIN);
1826 t->left = caselist();
1837 t->right = thenpart();
1846 musthave(WORD, 0); /* gets name of file */
1847 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1849 word(yylval.cp); /* add word to wdlist */
1850 word(NOWORD); /* terminate wdlist */
1851 t->op_words = copyw(); /* dup wdlist */
1862 DBGPRINTF(("COMMAND: returning %p\n", t));
1867 static struct op *dowholefile(int type /*, int mark*/)
1871 DBGPRINTF(("DOWHOLEFILE: enter, type=%d\n", type /*, mark*/));
1876 t = block(type, t, NOBLOCK, NOWORDS);
1877 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1881 static struct op *dogroup(int onlydone)
1887 if (c == DONE && onlydone)
1896 static struct op *thenpart(void)
1907 /*t->op_type = 0; - newtp() did this */
1909 if (t->left == NULL)
1911 t->right = elsepart();
1915 static struct op *elsepart(void)
1920 switch (c = yylex(0)) {
1931 t->right = thenpart();
1940 static struct op *caselist(void)
1945 while ((peeksym = yylex(CONTIN)) != ESAC) {
1946 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1947 t = list(t, casepart());
1950 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1954 static struct op *casepart(void)
1958 DBGPRINTF7(("CASEPART: enter...\n"));
1962 t->op_words = pattern();
1965 peeksym = yylex(CONTIN);
1966 if (peeksym != ESAC)
1967 musthave(BREAK, CONTIN);
1969 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
1974 static char **pattern(void)
1991 static char **wordlist(void)
2001 while ((c = yylex(0)) == WORD)
2009 * supporting functions
2011 static struct op *list(struct op *t1, struct op *t2)
2013 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2020 return block(TLIST, t1, t2, NOWORDS);
2023 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2027 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2035 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1, t2));
2040 /* See if given string is a shell multiline (FOR, IF, etc) */
2041 static int rlookup(char *n)
2047 static const struct res restab[] = {
2070 const struct res *rp;
2072 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2074 for (rp = restab; rp->r_name[0]; rp++)
2075 if (strcmp(rp->r_name, n) == 0) {
2076 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2077 return rp->r_val; /* Return numeric code for shell multiline */
2080 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2081 return 0; /* Not a shell multiline */
2084 static struct op *newtp(void)
2088 t = (struct op *) tree(sizeof(*t));
2089 memset(t, 0, sizeof(*t));
2091 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2096 static struct op *namelist(struct op *t)
2098 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2099 T_CMD_NAMES[t->op_type], iolist));
2102 iolist = addword((char *) NULL, iolist);
2103 t->ioact = copyio();
2107 if (t->op_type != TCOM) {
2108 if (t->op_type != TPAREN && t->ioact != NULL) {
2109 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2110 t->ioact = t->left->ioact;
2111 t->left->ioact = NULL;
2117 t->op_words = copyw();
2122 static char **copyw(void)
2126 wd = getwords(wdlist);
2131 static void word(char *cp)
2133 wdlist = addword(cp, wdlist);
2136 static struct ioword **copyio(void)
2138 struct ioword **iop;
2140 iop = (struct ioword **) getwords(iolist);
2145 static struct ioword *io(int u, int f, char *cp)
2149 iop = (struct ioword *) tree(sizeof(*iop));
2153 iolist = addword((char *) iop, iolist);
2157 static int yylex(int cf)
2174 global_env.linep = line;
2177 line[LINELIM - 1] = '\0';
2180 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2185 if (any(c, "0123456789")) {
2188 if (c1 == '<' || c1 == '>') {
2192 *global_env.linep++ = c;
2197 case '#': /* Comment, skip to next newline or End-of-string */
2198 while ((c = my_getc(0)) != '\0' && c != '\n')
2204 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2208 DBGPRINTF9(("YYLEX: found $\n"));
2209 *global_env.linep++ = c;
2212 c = collect(c, '}');
2231 /* If more chars process them, else return NULL char */
2249 if (multiline || cf & CONTIN) {
2250 if (interactive && global_env.iop <= iostack) {
2251 #if ENABLE_FEATURE_EDITING
2252 current_prompt = cprompt->value;
2254 prs(cprompt->value);
2271 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2272 if (global_env.linep >= elinep)
2273 err("word too long");
2275 *global_env.linep++ = c;
2280 if (any(c, "\"'`$"))
2283 *global_env.linep++ = '\0';
2293 yylval.cp = strsave(line, areanum);
2298 static int collect(int c, int c1)
2302 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2304 *global_env.linep++ = c;
2305 while ((c = my_getc(c1)) != c1) {
2314 if (interactive && c == '\n' && global_env.iop <= iostack) {
2315 #if ENABLE_FEATURE_EDITING
2316 current_prompt = cprompt->value;
2318 prs(cprompt->value);
2321 *global_env.linep++ = c;
2324 *global_env.linep++ = c;
2326 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2331 /* "multiline commands" helper func */
2332 /* see if next 2 chars form a shell multiline */
2333 static int dual(int c)
2338 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2340 *cp++ = c; /* c is the given "peek" char */
2341 *cp++ = my_getc(0); /* get next char of input */
2342 *cp = '\0'; /* add EOS marker */
2344 c = rlookup(s); /* see if 2 chars form a shell multiline */
2346 unget(*--cp); /* String is not a shell multiline, put peek char back */
2348 return c; /* String is multiline, return numeric multiline (restab) code */
2351 static void diag(int ec)
2355 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2358 if (c == '>' || c == '<') {
2361 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2364 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2365 if (c != '&' || yylval.i == IOHERE)
2371 static char *tree(unsigned size)
2377 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2378 prs("command line too complicated\n");
2389 /* -------- exec.c -------- */
2391 static struct op **find1case(struct op *t, const char *w)
2399 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2403 DBGPRINTF3(("FIND1CASE: enter, t->op_type=%d (%s)\n", t->op_type,
2404 T_CMD_NAMES[t->op_type]));
2406 if (t->op_type == TLIST) {
2407 tp = find1case(t->left, w);
2409 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2412 t1 = t->right; /* TPAT */
2416 for (wp = t1->op_words; *wp;) {
2417 cp = evalstr(*wp++, DOSUB);
2418 if (cp && gmatch(w, cp)) {
2419 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2425 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2429 static struct op *findcase(struct op *t, const char *w)
2433 tp = find1case(t, w);
2434 return tp != NULL ? *tp : NULL;
2441 static int execute(struct op *t, int *pin, int *pout, int no_fork)
2444 volatile int i, rv, a;
2448 struct op *outtree_save;
2452 /* Avoid longjmp clobbering */
2457 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2461 DBGPRINTF(("EXECUTE: t=%p, t->op_type=%d (%s), t->op_words is %s\n", t,
2462 t->op_type, T_CMD_NAMES[t->op_type],
2463 ((t->op_words == NULL) ? "NULL" : t->op_words[0])));
2469 ? eval(wp2, t->op_type == TCOM ? DOALL : DOALL & ~DOKEY)
2472 switch (t->op_type) {
2474 DBGPRINTF3(("EXECUTE: TDOT\n"));
2476 outtree_save = outtree;
2478 newfile(evalstr(t->op_words[0], DOALL));
2480 t->left = dowholefile(TLIST /*, 0*/);
2483 outtree = outtree_save;
2486 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2488 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2492 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2496 rv = forkexec(t, pin, pout, no_fork, wp);
2506 pv[0] = remap(pv[0]);
2507 pv[1] = remap(pv[1]);
2508 (void) execute(t->left, pin, pv, /* no_fork: */ 0);
2509 rv = execute(t->right, pv, pout, /* no_fork: */ 0);
2514 (void) execute(t->left, pin, pout, /* no_fork: */ 0);
2515 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2520 smallint hinteractive = interactive;
2522 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2525 if (i == 0) { /* child */
2526 signal(SIGINT, SIG_IGN);
2527 signal(SIGQUIT, SIG_IGN);
2529 signal(SIGTERM, SIG_DFL);
2533 xopen(bb_dev_null, O_RDONLY);
2535 _exit(execute(t->left, pin, pout, /* no_fork: */ 1));
2537 interactive = hinteractive;
2539 setval(lookup("!"), putn(i));
2553 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2555 if (t1 != NULL && (rv == 0) == (t->op_type == TAND))
2556 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2567 while (*wp++ != NULL)
2570 vp = lookup(t->str);
2571 while (setjmp(bc.brkpt))
2574 /* Restore areanum value. It may be incremented by execute()
2575 * below, and then "continue" may jump back to setjmp above */
2577 freearea(areanum + 1);
2579 for (t1 = t->left; i-- && *wp != NULL;) {
2581 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2583 brklist = brklist->nextlev;
2588 while (setjmp(bc.brkpt))
2591 /* Restore areanum value. It may be incremented by execute()
2592 * below, and then "continue" may jump back to setjmp above */
2594 freearea(areanum + 1);
2597 while ((execute(t1, pin, pout, /* no_fork: */ 0) == 0) == (t->op_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);
2649 // Restoring op_words is most likely not needed now: see comment in forkexec()
2650 // (also take a look at exec builtin (doexec) - it touches t->op_words)
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->op_words is %s\n",
2715 ((t->op_words == NULL) ? "NULL" : t->op_words[0])));
2718 if (t->op_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->op_words to temporary (expanded) arg list:
2746 // t->op_words = wp;
2747 // and restored it later (in execute()), but "break"
2748 // longjmps away (at "Run builtin" below), leaving t->op_words clobbered!
2749 // See http://bugs.busybox.net/view.php?id=846.
2750 // Now we do not touch t->op_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, can't 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(": can't 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(": can't 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->op_type == TPAREN)
2863 _exit(execute(t->left, NOPIPE, NOPIPE, /* no_fork: */ 1));
2865 _exit(EXIT_SUCCESS);
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_fd == IODEFAULT) /* take default */
2895 iop->io_fd = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2897 if (pipein && iop->io_fd == 0)
2900 if (pipeout && iop->io_fd == 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_fd);
2960 xmove_fd(u, iop->io_fd);
2965 * Enter a new loop level (marked for break/continue).
2967 static void brkset(struct brkcon *bc)
2969 bc->nextlev = brklist;
2974 * Wait for the last process created.
2975 * Print a message for each process found
2976 * that was killed by a signal.
2977 * Ignore interrupt signals while waiting
2978 * unless `canintr' is true.
2980 static int waitfor(int lastpid, int canintr)
2984 smallint oheedint = heedint;
2991 if (errno != EINTR || canintr)
2996 if (rv < ARRAY_SIZE(signame)) {
2997 if (signame[rv] != NULL) {
2998 if (pid != lastpid) {
3005 if (pid != lastpid) {
3014 prs(" - core dumped");
3015 if (rv >= ARRAY_SIZE(signame) || signame[rv])
3021 } while (pid != lastpid);
3036 static int setstatus(int s)
3039 setval(lookup("?"), putn(s));
3044 * PATH-searching interface to execve.
3045 * If getenv("PATH") were kept up-to-date,
3046 * execvp might be used.
3048 static const char *rexecve(char *c, char **v, char **envp)
3055 if (ENABLE_FEATURE_SH_STANDALONE) {
3056 if (find_applet_by_name(name) >= 0) {
3057 /* We have to exec here since we vforked. Running
3058 * run_applet_and_exit() won't work and bad things
3060 execve(bb_busybox_exec_path, v, envp);
3064 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3066 sp = any('/', c) ? "" : path->value;
3067 asis = (*sp == '\0');
3068 while (asis || *sp != '\0') {
3070 tp = global_env.linep;
3071 for (; *sp != '\0'; tp++) {
3074 asis = (*sp == '\0');
3078 if (tp != global_env.linep)
3082 DBGPRINTF3(("REXECVE: global_env.linep is %s\n", global_env.linep));
3084 execve(global_env.linep, v, envp);
3088 /* File is executable but file format isnt recognized */
3089 /* Run it as a shell script */
3090 /* (execve above didnt do it itself, unlike execvp) */
3091 *v = global_env.linep;
3094 *v = (char*)DEFAULT_SHELL;
3095 execve(DEFAULT_SHELL, v, envp);
3100 return (char *) bb_msg_memory_exhausted;
3103 return "argument list too long";
3106 if (errno == ENOENT) {
3107 exstat = 127; /* standards require this */
3110 exstat = 126; /* mimic bash */
3111 return "can't execute";
3115 * Run the command produced by generator `f'
3116 * applied to stream `arg'.
3118 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3121 struct wdblock *swdlist;
3122 struct wdblock *siolist;
3128 /* Avoid longjmp clobbering */
3132 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3133 areanum, outtree, failpt));
3143 if (newenv(setjmp(errpt)) == 0) {
3147 global_env.iobase = global_env.iop;
3150 if (setjmp(failpt) == 0 && yyparse() == 0)
3151 rv = execute(outtree, NOPIPE, NOPIPE, /* no_fork: */ 0);
3154 DBGPRINTF(("RUN: error from newenv()!\n"));
3161 freearea(areanum--);
3166 /* -------- do.c -------- */
3169 * built-in commands: doX
3172 static int dohelp(struct op *t UNUSED_PARAM, char **args UNUSED_PARAM)
3175 const struct builtincmd *x;
3178 "Built-in commands:\n"
3179 "------------------\n");
3184 col += printf("%c%s", ((col == 0) ? '\t' : ' '), x->name);
3191 #if ENABLE_FEATURE_SH_STANDALONE
3193 const char *applet = applet_names;
3196 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applet);
3201 applet += strlen(applet) + 1;
3206 return EXIT_SUCCESS;
3209 static int dolabel(struct op *t UNUSED_PARAM, char **args UNUSED_PARAM)
3214 static int dochdir(struct op *t UNUSED_PARAM, char **args)
3216 const char *cp, *er;
3220 cp = homedir->value;
3223 er = ": no home directory";
3228 er = ": bad directory";
3230 prs(cp != NULL ? cp : "cd");
3235 static int doshift(struct op *t UNUSED_PARAM, char **args)
3239 n = args[1] ? getn(args[1]) : 1;
3241 err("nothing to shift");
3247 setval(lookup("#"), putn(dolc));
3252 * execute login and newgrp directly
3254 static int dologin(struct op *t UNUSED_PARAM, char **args)
3259 signal(SIGINT, SIG_DFL);
3260 signal(SIGQUIT, SIG_DFL);
3262 cp = rexecve(args[0], args, makenv(0, NULL));
3269 static int doumask(struct op *t UNUSED_PARAM, char **args)
3278 printf("%04o\n", i);
3280 i = bb_strtou(cp, NULL, 8);
3282 err("umask: bad octal number");
3290 static int doexec(struct op *t, char **args)
3304 sv_words = t->op_words;
3305 t->op_words = args + 1;
3306 // TODO: test what will happen with "exec break" -
3307 // will it leave t->op_words pointing to garbage?
3308 // (see http://bugs.busybox.net/view.php?id=846)
3309 if (setjmp(failpt) == 0)
3310 execute(t, NOPIPE, NOPIPE, /* no_fork: */ 1);
3311 t->op_words = sv_words;
3319 static int dodot(struct op *t UNUSED_PARAM, char **args)
3327 DBGPRINTF(("DODOT: enter, t=%p, tleft %p, tright %p, global_env.linep is %s\n",
3328 t, t->left, t->right, ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3332 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3335 DBGPRINTF(("DODOT: cp is %s\n", cp));
3337 sp = any('/', cp) ? ":" : path->value;
3339 DBGPRINTF(("DODOT: sp is %s, global_env.linep is %s\n",
3340 ((sp == NULL) ? "NULL" : sp),
3341 ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3344 tp = global_env.linep;
3345 while (*sp && (*tp = *sp++) != ':')
3347 if (tp != global_env.linep)
3352 i = open(global_env.linep, O_RDONLY);
3356 DBGPRINTF(("DODOT: remap=%d, exstat=%d, global_env.iofd %d, i %d, global_env.linep is %s\n",
3357 maltmp, exstat, global_env.iofd, i, global_env.linep));
3359 next(maltmp); /* Basically a PUSHIO */
3361 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3373 static int dowait(struct op *t UNUSED_PARAM, char **args)
3385 setstatus(waitfor(i, 1));
3389 static int doread(struct op *t UNUSED_PARAM, char **args)
3395 if (args[1] == NULL) {
3396 err("Usage: read name ...");
3399 for (wp = args + 1; *wp; wp++) {
3400 for (cp = global_env.linep; !nl && cp < elinep - 1; cp++) {
3401 nb = nonblock_safe_read(STDIN_FILENO, cp, sizeof(*cp));
3402 if (nb != sizeof(*cp))
3405 if (nl || (wp[1] && any(*cp, ifs->value)))
3411 setval(lookup(*wp), global_env.linep);
3416 static int doeval(struct op *t UNUSED_PARAM, char **args)
3418 return RUN(awordlist, args + 1, wdchar);
3421 static int dotrap(struct op *t UNUSED_PARAM, char **args)
3426 if (args[1] == NULL) {
3427 for (i = 0; i <= _NSIG; i++)
3436 resetsig = isdigit(args[1][0]);
3437 for (i = resetsig ? 1 : 2; args[i] != NULL; ++i) {
3438 n = getsig(args[i]);
3442 if (args[1][0] != '\0') {
3443 trap[n] = strsave(args[1], 0);
3452 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3460 static int getsig(char *s)
3465 if (n < 0 || n > _NSIG) {
3466 err("trap: bad signal number");
3472 static void setsig(int n, sighandler_t f)
3476 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3482 static int getn(char *as)
3493 for (n = 0; isdigit(*s); s++)
3494 n = (n * 10) + (*s - '0');
3497 err(": bad number");
3502 static int dobreak(struct op *t UNUSED_PARAM, char **args)
3504 return brkcontin(args[1], 1);
3507 static int docontinue(struct op *t UNUSED_PARAM, char **args)
3509 return brkcontin(args[1], 0);
3512 static int brkcontin(char *cp, int val)
3517 nl = cp == NULL ? 1 : getn(cp);
3524 brklist = bc->nextlev;
3527 err("bad break/continue level");
3530 isbreak = (val != 0);
3531 longjmp(bc->brkpt, 1);
3535 static int doexit(struct op *t UNUSED_PARAM, char **args)
3542 setstatus(getn(cp));
3544 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3551 static int doexport(struct op *t UNUSED_PARAM, char **args)
3553 rdexp(args + 1, export, EXPORT);
3557 static int doreadonly(struct op *t UNUSED_PARAM, char **args)
3559 rdexp(args + 1, ronly, RONLY);
3563 static void rdexp(char **wp, void (*f) (struct var *), int key)
3565 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3566 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3569 for (; *wp != NULL; wp++) {
3570 if (isassign(*wp)) {
3574 for (cp = *wp; *cp != '='; cp++)
3587 static void badid(char *s)
3590 err(": bad identifier");
3593 static int doset(struct op *t UNUSED_PARAM, char **args)
3601 for (vp = vlist; vp; vp = vp->next)
3602 varput(vp->name, STDOUT_FILENO);
3608 FLAG['x'] = FLAG['v'] = 0;
3618 if (*cp >= 'a' && *cp <= 'z')
3628 for (n = 1; args[n]; n++)
3629 setarea((char *) args[n], 0);
3632 setval(lookup("#"), putn(dolc));
3633 setarea((char *) (dolv - 1), 0);
3638 static void varput(char *s, int out)
3640 if (isalnum(*s) || *s == '_') {
3642 xwrite(out, "\n", 1);
3648 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3649 * This file contains code for the times builtin.
3651 static void times_fmt(char *buf, clock_t val, unsigned clk_tck)
3654 if (sizeof(val) > sizeof(int))
3655 sec = ((unsigned long)val) / clk_tck;
3657 sec = ((unsigned)val) / clk_tck;
3660 sprintf(buf, "%um%u.%03us", min, (sec - min * 60),
3661 /* msec: */ ((unsigned)(val - (clock_t)sec * clk_tck)) * 1000 / clk_tck
3664 sprintf(buf, "%um%us", min, (sec - min * 60));
3668 static int dotimes(struct op *t UNUSED_PARAM, char **args UNUSED_PARAM)
3671 unsigned clk_tck = sysconf(_SC_CLK_TCK);
3672 /* How much do we need for "NmN.NNNs" ? */
3673 enum { TIMEBUF_SIZE = sizeof(int)*3 + sizeof(int)*3 + 6 };
3674 char u[TIMEBUF_SIZE], s[TIMEBUF_SIZE];
3675 char cu[TIMEBUF_SIZE], cs[TIMEBUF_SIZE];
3679 times_fmt(u, buf.tms_utime, clk_tck);
3680 times_fmt(s, buf.tms_stime, clk_tck);
3681 times_fmt(cu, buf.tms_cutime, clk_tck);
3682 times_fmt(cs, buf.tms_cstime, clk_tck);
3684 printf("%s %s\n%s %s\n", u, s, cu, cs);
3689 /* -------- eval.c -------- */
3694 * blank interpretation
3699 static char **eval(char **ap, int f)
3707 /* Avoid longjmp clobbering */
3712 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3718 if (newenv(setjmp(errpt)) == 0) {
3719 while (*ap && isassign(*ap))
3720 expand(*ap++, &wb, f & ~DOGLOB);
3722 for (wf = ap; *wf; wf++) {
3724 expand(*wf, &wb, f & ~DOGLOB);
3727 for (wb = addword((char *) NULL, wb); *ap; ap++) {
3728 if (!FLAG['k'] || !isassign(*ap))
3729 expand(*ap, &wb, f & ~DOKEY);
3731 wb = addword((char *) 0, wb);
3737 return gflg ? (char **) NULL : wp;
3742 * Make the exported environment from the exported
3743 * names in the dictionary. Keyword assignments
3744 * will already have been done.
3746 static char **makenv(int all, struct wdblock *wb)
3750 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3752 for (vp = vlist; vp; vp = vp->next)
3753 if (all || vp->status & EXPORT)
3754 wb = addword(vp->name, wb);
3755 wb = addword((char *) 0, wb);
3756 return getwords(wb);
3759 static int expand(const char *cp, struct wdblock **wbp, int f)
3765 /* Avoid longjmp clobbering */
3769 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3776 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3777 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3779 xp = strsave(cp, areanum);
3782 *wbp = addword(xp, *wbp);
3786 if (newenv(setjmp(errpt)) == 0) {
3787 PUSHIO(aword, cp, strchar);
3788 global_env.iobase = global_env.iop;
3789 while ((xp = blank(f)) && gflg == 0) {
3790 global_env.linep = xp;
3791 xp = strsave(xp, areanum);
3792 if ((f & DOGLOB) == 0) {
3795 *wbp = addword(xp, *wbp);
3797 *wbp = glob(xp, *wbp);
3805 static char *evalstr(char *cp, int f)
3809 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3812 if (expand(cp, &wb, f)) {
3813 if (wb == NULL || wb->w_nword == 0
3814 || (cp = wb->w_words[0]) == NULL
3816 // TODO: I suspect that
3817 // char *evalstr(char *cp, int f) is actually
3818 // const char *evalstr(const char *cp, int f)!
3829 * Blank interpretation and quoting
3831 static char *blank(int f)
3835 int scanequals, foundequals;
3837 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3839 sp = global_env.linep;
3840 scanequals = f & DOKEY;
3844 c = subgetc('"', foundequals);
3847 if (sp == global_env.linep)
3849 *global_env.linep++ = 0;
3853 if (f & DOBLANK && any(c, ifs->value))
3862 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3865 if (c == '\'' || !any(c, "$`\""))
3867 *global_env.linep++ = c;
3872 if (!isalpha(c) && c != '_')
3875 c = subgetc('"', foundequals);
3877 f & (DOBLANK && any(c, ifs->value)) ||
3878 (!INSUB() && any(c, "\"'"))) {
3889 } else if (!isalnum(c) && c != '_')
3892 *global_env.linep++ = c;
3894 *global_env.linep++ = 0;
3899 * Get characters, substituting for ` and $
3901 static int subgetc(char ec, int quoted)
3905 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3909 if (!INSUB() && ec != '\'') {
3911 if (grave(quoted) == 0)
3913 global_env.iop->task = XGRAVE;
3919 global_env.iop->task = XDOLL;
3928 * Prepare to generate the string returned by ${} substitution.
3930 static int dollar(int quoted)
3935 char *s, c, *cp = NULL;
3938 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3941 s = global_env.linep;
3943 *global_env.linep++ = c;
3944 if (isalpha(c) || c == '_') {
3945 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3946 if (global_env.linep < elinep)
3947 *global_env.linep++ = c;
3952 oiop = global_env.iop;
3953 otask = global_env.iop->task;
3955 global_env.iop->task = XOTHER;
3956 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3957 if (global_env.linep < elinep)
3958 *global_env.linep++ = c;
3959 if (oiop == global_env.iop)
3960 global_env.iop->task = otask;
3967 if (global_env.linep >= elinep) {
3968 err("string in ${} too long");
3970 global_env.linep -= 10;
3972 *global_env.linep = 0;
3974 for (cp = s + 1; *cp; cp++)
3975 if (any(*cp, "=-+?")) {
3980 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3982 /* currently this does not distinguish $* and $@ */
3983 /* should check dollar */
3984 global_env.linep = s;
3985 PUSHIO(awordlist, dolv + 1, dolchar);
3987 } else { /* trap the nasty ${=} */
3998 err("can't use ${...=...} with $n");
4007 dolp = strsave(cp, areanum);
4012 prs("missing value for ");
4019 } else if (c == '+')
4020 dolp = strsave(cp, areanum);
4021 if (FLAG['u'] && dolp == null) {
4022 prs("unset variable: ");
4026 global_env.linep = s;
4027 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4032 * Run the command in `...` and read its output.
4035 static int grave(int quoted)
4037 /* moved to G: static char child_cmd[LINELIM]; */
4048 char *argument_list[4];
4049 struct wdblock *wb = NULL;
4052 /* Avoid longjmp clobbering */
4056 for (cp = global_env.iop->argp->aword; *cp != '`'; cp++) {
4058 err("no closing `");
4063 /* string copy with dollar expansion */
4064 src = global_env.iop->argp->aword;
4069 while ((*src != '`') && (count < LINELIM)) {
4074 if (*src == '$' && !ignore && !ignore_once) {
4076 /* moved to G to reduce stack usage
4077 char var_name[LINELIM];
4078 char alt_value[LINELIM];
4080 #define var_name (G.grave__var_name)
4081 #define alt_value (G.grave__alt_value)
4094 var_name[var_index++] = *src++;
4095 while (isalnum(*src) || *src=='_')
4096 var_name[var_index++] = *src++;
4097 var_name[var_index] = 0;
4110 err("unclosed ${\n");
4115 while (*src && (*src != '}')) {
4116 alt_value[alt_index++] = *src++;
4118 alt_value[alt_index] = 0;
4120 err("unclosed ${\n");
4127 if (isalpha(*var_name)) {
4128 /* let subshell handle it instead */
4130 char *namep = var_name;
4138 char *altp = alt_value;
4146 wb = addword(lookup(var_name)->name, wb);
4150 vp = lookup(var_name);
4151 if (vp->value != null)
4152 value = (operator == '+') ?
4153 alt_value : vp->value;
4154 else if (operator == '?') {
4157 } else if (alt_index && (operator != '+')) {
4159 if (operator == '=')
4164 while (*value && (count < LINELIM)) {
4179 if (openpipe(pf) < 0)
4182 while ((i = vfork()) == -1 && errno == EAGAIN)
4185 DBGPRINTF3(("GRAVE: i is %p\n", io));
4189 err((char *) bb_msg_memory_exhausted);
4193 waitpid(i, NULL, 0); // safe_waitpid?
4194 global_env.iop->argp->aword = ++cp;
4196 PUSHIO(afile, remap(pf[0]),
4197 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4200 /* allow trapped signals */
4201 /* XXX - Maybe this signal stuff should go as well? */
4202 for (j = 0; j <= _NSIG; j++)
4203 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4206 /* Testcase where below checks are needed:
4207 * close stdout & run this script:
4215 argument_list[0] = (char *) DEFAULT_SHELL;
4216 argument_list[1] = (char *) "-c";
4217 argument_list[2] = child_cmd;
4218 argument_list[3] = NULL;
4220 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4221 prs(argument_list[0]);
4224 _exit(EXIT_FAILURE);
4228 static char *unquote(char *as)
4239 /* -------- glob.c -------- */
4245 #define scopy(x) strsave((x), areanum)
4247 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4249 static struct wdblock *cl, *nl;
4250 static const char spcl[] ALIGN1= "[?*";
4252 static struct wdblock *glob(char *cp, struct wdblock *wb)
4260 for (pp = cp; *pp; pp++)
4263 else if (!any(*pp & ~QUOTE, spcl))
4266 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4267 nl = newword(cl->w_nword * 2);
4268 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4269 for (pp = cl->w_words[i]; *pp; pp++)
4270 if (any(*pp, spcl)) {
4271 globname(cl->w_words[i], pp);
4275 nl = addword(scopy(cl->w_words[i]), nl);
4277 for (i = 0; i < cl->w_nword; i++)
4278 DELETE(cl->w_words[i]);
4282 for (i = 0; i < cl->w_nword; i++)
4283 unquote(cl->w_words[i]);
4284 qsort_string_vector(cl->w_words, cl->w_nword);
4285 for (i = 0; i < cl->w_nword; i++)
4286 wb = addword(cl->w_words[i], wb);
4291 wb = addword(unquote(cp), wb);
4295 static void globname(char *we, char *pp)
4298 char *name, *gp, *dp;
4302 char dname[NAME_MAX + 1];
4305 for (np = we; np != pp; pp--)
4308 dp = cp = get_space((int) (pp - np) + 3);
4313 gp = cp = get_space(strlen(pp) + 1);
4314 while (*np && *np != '/')
4323 dname[NAME_MAX] = '\0';
4324 while ((de = readdir(dirp)) != NULL) {
4325 /* XXX Hmmm... What this could be? (abial) */
4326 /* if (ent[j].d_ino == 0) continue;
4328 strncpy(dname, de->d_name, NAME_MAX);
4329 if (dname[0] == '.')
4332 for (k = 0; k < NAME_MAX; k++)
4333 if (any(dname[k], spcl))
4335 if (gmatch(dname, gp)) {
4336 name = generate(we, pp, dname, np);
4337 if (*np && !anys(np, spcl)) {
4338 if (stat(name, &dbuf)) {
4343 nl = addword(name, nl);
4352 * generate a pathname as below.
4353 * start..end1 / middle end
4354 * the slashes come for free
4356 static char *generate(char *start1, char *end1, char *middle, char *end)
4361 p = op = get_space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4372 static int anyspcl(struct wdblock *wb)
4378 for (i = 0; i < wb->w_nword; i++)
4379 if (anys(spcl, *wd++))
4385 /* -------- word.c -------- */
4387 static struct wdblock *newword(int nw)
4391 wb = get_space(sizeof(*wb) + nw * sizeof(char *));
4397 static struct wdblock *addword(char *wd, struct wdblock *wb)
4399 struct wdblock *wb2;
4403 wb = newword(NSTART);
4405 if (nw >= wb->w_bsize) {
4406 wb2 = newword(nw * 2);
4407 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4408 nw * sizeof(char *));
4413 wb->w_words[wb->w_nword++] = wd;
4417 static char **getwords(struct wdblock *wb)
4424 if (wb->w_nword == 0) {
4428 nb = sizeof(*wd) * wb->w_nword;
4430 memcpy(wd, wb->w_words, nb);
4431 DELETE(wb); /* perhaps should done by caller */
4436 /* -------- io.c -------- */
4442 static int my_getc(int ec)
4446 if (global_env.linep > elinep) {
4447 while ((c = readc()) != '\n' && c)
4449 err("input line too long");
4454 if ((ec != '\'') && (ec != '`') && (global_env.iop->task != XGRAVE)) {
4457 if (c == '\n' && ec != '\"')
4465 static void unget(int c)
4467 if (global_env.iop >= global_env.iobase)
4468 global_env.iop->peekc = c;
4471 static int eofc(void)
4473 return global_env.iop < global_env.iobase || (global_env.iop->peekc == 0 && global_env.iop->prev == 0);
4476 static int readc(void)
4480 RCPRINTF(("READC: global_env.iop %p, global_env.iobase %p\n", global_env.iop, global_env.iobase));
4482 for (; global_env.iop >= global_env.iobase; global_env.iop--) {
4483 RCPRINTF(("READC: global_env.iop %p, peekc 0x%x\n", global_env.iop, global_env.iop->peekc));
4484 c = global_env.iop->peekc;
4486 global_env.iop->peekc = 0;
4489 if (global_env.iop->prev != 0) {
4490 c = (*global_env.iop->iofn)(global_env.iop->argp, global_env.iop);
4496 if (global_env.iop == iostack)
4498 global_env.iop->prev = c;
4501 if (global_env.iop->task == XIO && global_env.iop->prev != '\n') {
4502 global_env.iop->prev = 0;
4503 if (global_env.iop == iostack)
4508 if (global_env.iop->task == XIO) {
4510 global_env.iop->prev = 0;
4513 if (interactive && global_env.iop == iostack + 1) {
4514 #if ENABLE_FEATURE_EDITING
4515 current_prompt = prompt->value;
4523 if (global_env.iop >= iostack) {
4524 RCPRINTF(("READC: return 0, global_env.iop %p\n", global_env.iop));
4528 DBGPRINTF(("READC: leave()...\n"));
4534 static void ioecho(char c)
4537 write(STDERR_FILENO, &c, sizeof c);
4540 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4542 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, global_env.iop %p\n", argp,
4543 argp->afid, global_env.iop));
4545 /* Set env ptr for io source to next array spot and check for array overflow */
4546 if (++global_env.iop >= &iostack[NPUSH]) {
4548 err("Shell input nested too deeply");
4553 /* We did not overflow the NPUSH array spots so setup data structs */
4555 global_env.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4557 if (argp->afid != AFID_NOBUF)
4558 global_env.iop->argp = argp;
4561 global_env.iop->argp = ioargstack + (global_env.iop - iostack); /* MAL - index into stack */
4562 *global_env.iop->argp = *argp; /* copy data from temp area into stack spot */
4564 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4566 if (global_env.iop == &iostack[0])
4567 global_env.iop->argp->afbuf = &mainbuf;
4569 global_env.iop->argp->afbuf = &sharedbuf;
4571 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4572 /* This line appears to be active when running scripts from command line */
4573 if ((isatty(global_env.iop->argp->afile) == 0)
4574 && (global_env.iop == &iostack[0]
4575 || lseek(global_env.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4576 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4577 bufid = AFID_ID; /* AFID_ID = 0 */
4579 global_env.iop->argp->afid = bufid; /* assign buffer id */
4582 DBGPRINTF(("PUSHIO: iostack %p, global_env.iop %p, afbuf %p\n",
4583 iostack, global_env.iop, global_env.iop->argp->afbuf));
4584 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, global_env.iop %p\n",
4585 &mainbuf, &sharedbuf, bufid, global_env.iop));
4589 global_env.iop->prev = ~'\n';
4590 global_env.iop->peekc = 0;
4591 global_env.iop->xchar = 0;
4592 global_env.iop->nlcount = 0;
4594 if (fn == filechar || fn == linechar)
4595 global_env.iop->task = XIO;
4596 else if (fn == (int (*)(struct ioarg *)) gravechar
4597 || fn == (int (*)(struct ioarg *)) qgravechar)
4598 global_env.iop->task = XGRAVE;
4600 global_env.iop->task = XOTHER;
4603 static struct io *setbase(struct io *ip)
4607 xp = global_env.iobase;
4608 global_env.iobase = ip;
4613 * Input generating functions
4617 * Produce the characters of a string, then a newline, then NUL.
4619 static int nlchar(struct ioarg *ap)
4623 if (ap->aword == NULL)
4634 * Given a list of words, produce the characters
4635 * in them, with a space after each word.
4637 static int wdchar(struct ioarg *ap)
4652 ap->awordlist = NULL;
4657 * Return the characters of a list of words,
4658 * producing a space between them.
4660 static int dolchar(struct ioarg *ap)
4664 wp = *ap->awordlist++;
4666 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4672 static int xxchar(struct ioarg *ap)
4676 if (ap->aword == NULL)
4687 * Produce the characters from a single word (string).
4689 static int strchar(struct ioarg *ap)
4691 if (ap->aword == NULL)
4693 return *ap->aword++;
4697 * Produce quoted characters from a single word (string).
4699 static int qstrchar(struct ioarg *ap)
4703 if (ap->aword == NULL)
4712 * Return the characters from a file.
4714 static int filechar(struct ioarg *ap)
4718 struct iobuf *bp = ap->afbuf;
4720 if (ap->afid != AFID_NOBUF) {
4721 i = (ap->afid != bp->id);
4722 if (i || bp->bufp == bp->ebufp) {
4724 lseek(ap->afile, ap->afpos, SEEK_SET);
4726 i = nonblock_safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4734 bp->ebufp = bp->bufp + i;
4738 return *bp->bufp++ & 0177;
4740 #if ENABLE_FEATURE_EDITING
4741 if (interactive && isatty(ap->afile)) {
4742 /* moved to G: static char filechar_cmdbuf[BUFSIZ]; */
4743 static int position = 0, size = 0;
4745 while (size == 0 || position >= size) {
4746 size = read_line_input(current_prompt, filechar_cmdbuf, BUFSIZ, line_input_state);
4747 if (size < 0) /* Error/EOF */
4750 /* if Ctrl-C, size == 0 and loop will repeat */
4752 c = filechar_cmdbuf[position];
4757 i = nonblock_safe_read(ap->afile, &c, sizeof(c));
4758 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4762 * Return the characters from a here temp file.
4764 static int herechar(struct ioarg *ap)
4768 if (nonblock_safe_read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4776 * Return the characters produced by a process (`...`).
4777 * Quote them if required, and remove any trailing newline characters.
4779 static int gravechar(struct ioarg *ap, struct io *iop)
4783 c = qgravechar(ap, iop) & ~QUOTE;
4789 static int qgravechar(struct ioarg *ap, struct io *iop)
4793 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4798 return '\n' | QUOTE;
4802 } else if ((c = filechar(ap)) == '\n') {
4804 while ((c = filechar(ap)) == '\n')
4812 return c != 0 ? c | QUOTE : 0;
4816 * Return a single command (usually the first line) from a file.
4818 static int linechar(struct ioarg *ap)
4826 ap->afile = -1; /* illegal value */
4833 * Remap fd into shell's fd space
4835 static int remap(int fd)
4841 DBGPRINTF(("REMAP: fd=%d, global_env.iofd=%d\n", fd, global_env.iofd));
4843 if (fd < global_env.iofd) {
4844 for (i = 0; i < NOFILE; i++)
4851 } while (fd >= 0 && fd < global_env.iofd);
4853 for (i = 0; i < NOFILE; i++)
4858 err("too many files open in shell");
4864 static int openpipe(int *pv)
4870 err("can't create pipe - try again");
4874 static void closepipe(int *pv)
4883 /* -------- here.c -------- */
4889 static void markhere(char *s, struct ioword *iop)
4891 struct here *h, *lh;
4893 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4895 h = get_space(sizeof(struct here));
4899 h->h_tag = evalstr(s, DOSUB);
4909 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4910 if (lh->h_next == 0) {
4916 iop->io_flag |= IOHERE | IOXHERE;
4917 for (s = h->h_tag; *s; s++) {
4919 iop->io_flag &= ~IOXHERE;
4923 h->h_dosub = ((iop->io_flag & IOXHERE) ? '\0' : '\'');
4926 static void gethere(void)
4928 struct here *h, *hp;
4930 DBGPRINTF7(("GETHERE: enter...\n"));
4932 /* Scan here files first leaving inhere list in place */
4933 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
4934 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub /* NUL or ' */);
4936 /* Make inhere list active - keep list intact for scraphere */
4938 hp->h_next = acthere;
4944 static void readhere(char **name, char *s, int ec)
4947 char tname[30] = ".msh_XXXXXX";
4950 char myline[LINELIM + 1];
4953 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
4955 tf = mkstemp(tname);
4959 *name = strsave(tname, areanum);
4961 if (newenv(setjmp(errpt)) != 0)
4964 pushio(global_env.iop->argp, (int (*)(struct ioarg *)) global_env.iop->iofn);
4965 global_env.iobase = global_env.iop;
4967 if (interactive && global_env.iop <= iostack) {
4968 #if ENABLE_FEATURE_EDITING
4969 current_prompt = cprompt->value;
4971 prs(cprompt->value);
4975 while ((c = my_getc(ec)) != '\n' && c) {
4978 if (thenext >= &myline[LINELIM]) {
4985 if (strcmp(s, myline) == 0 || c == 0)
4988 write(tf, myline, (int) (thenext - myline));
4991 prs("here document `");
5001 * open here temp file.
5002 * if unquoted here, expand here temp file into second temp file.
5004 static int herein(char *hname, int xdoll)
5010 /* Avoid longjmp clobbering */
5016 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5018 hf = open(hname, O_RDONLY);
5024 char tname[30] = ".msh_XXXXXX";
5027 tf = mkstemp(tname);
5031 if (newenv(setjmp(errpt)) == 0) {
5032 PUSHIO(afile, hf, herechar);
5033 setbase(global_env.iop);
5034 while ((c = subgetc(0, 0)) != 0) {
5036 write(tf, &c, sizeof c);
5042 tf = open(tname, O_RDONLY);
5049 static void scraphere(void)
5053 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5055 for (h = inhere; h != NULL; h = h->h_next) {
5056 if (h->h_iop && h->h_iop->io_name)
5057 unlink(h->h_iop->io_name);
5062 /* unlink here temp files before a freearea(area) */
5063 static void freehere(int area)
5065 struct here *h, *hl;
5067 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5070 for (h = acthere; h != NULL; h = h->h_next) {
5071 if (getarea((char *) h) >= area) {
5072 if (h->h_iop->io_name != NULL)
5073 unlink(h->h_iop->io_name);
5075 acthere = h->h_next;
5077 hl->h_next = h->h_next;
5085 /* -------- sh.c -------- */
5090 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5091 int msh_main(int argc, char **argv)
5097 int (*iof) (struct ioarg *);
5101 sharedbuf.id = AFID_NOBUF;
5102 mainbuf.id = AFID_NOBUF;
5103 elinep = line + sizeof(line) - 5;
5105 #if ENABLE_FEATURE_EDITING
5106 line_input_state = new_line_input_t(FOR_SHELL);
5109 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5115 assign(*ap++, !COPYV);
5116 for (ap = environ; *ap;)
5117 export(lookup(*ap++));
5122 shell = lookup("SHELL");
5123 if (shell->value == null)
5124 setval(shell, (char *)DEFAULT_SHELL);
5127 homedir = lookup("HOME");
5128 if (homedir->value == null)
5129 setval(homedir, "/");
5132 setval(lookup("$"), putn(getpid()));
5134 path = lookup("PATH");
5135 if (path->value == null) {
5136 /* Can be merged with same string elsewhere in bbox */
5138 setval(path, bb_default_root_path);
5140 setval(path, bb_default_path);
5144 ifs = lookup("IFS");
5145 if (ifs->value == null)
5146 setval(ifs, " \t\n");
5149 mshdbg_var = lookup("MSHDEBUG");
5150 if (mshdbg_var->value == null)
5151 setval(mshdbg_var, "0");
5154 prompt = lookup("PS1");
5155 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5156 if (prompt->value == null)
5158 setval(prompt, DEFAULT_USER_PROMPT);
5159 if (geteuid() == 0) {
5160 setval(prompt, DEFAULT_ROOT_PROMPT);
5161 prompt->status &= ~EXPORT;
5163 cprompt = lookup("PS2");
5164 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5165 if (cprompt->value == null)
5167 setval(cprompt, "> ");
5173 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5174 for (s = argv[0] + 1; *s; s++)
5177 prompt->status &= ~EXPORT;
5178 cprompt->status &= ~EXPORT;
5180 setval(cprompt, "");
5183 PUSHIO(aword, *++argv, iof = nlchar);
5191 /* standard input */
5195 prompt->status &= ~EXPORT;
5203 if (*s >= 'a' && *s <= 'z')
5211 if (iof == filechar && --argc > 0) {
5213 setval(cprompt, "");
5214 prompt->status &= ~EXPORT;
5215 cprompt->status &= ~EXPORT;
5217 /* Shell is non-interactive, activate printf-based debug */
5219 mshdbg = mshdbg_var->value[0] - '0';
5223 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5227 exit(EXIT_FAILURE); /* Exit on error */
5233 /* This won't be true if PUSHIO has been called, say from newfile() above */
5234 if (global_env.iop < iostack) {
5235 PUSHIO(afile, 0, iof);
5236 if (isatty(0) && isatty(1) && !cflag) {
5238 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5240 printf("\n\n%s built-in shell (msh with debug)\n", bb_banner);
5242 printf("\n\n%s built-in shell (msh)\n", bb_banner);
5244 printf("Enter 'help' for a list of built-in commands.\n\n");
5249 signal(SIGQUIT, qflag);
5250 if (name && name[0] == '-') {
5252 f = open(".profile", O_RDONLY);
5255 f = open("/etc/profile", O_RDONLY);
5260 signal(SIGTERM, sig);
5262 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5263 signal(SIGINT, onintr);
5265 /* Handle "msh SCRIPT VAR=val params..." */
5266 /* Disabled: bash does not do it! */
5269 /* skip leading args of the form VAR=val */
5270 while (*argv && assign(*argv, !COPYV)) {
5280 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5282 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, global_env.iop %p, iostack %p\n", interactive, global_env.iop, iostack));
5285 if (interactive && global_env.iop <= iostack) {
5286 #if ENABLE_FEATURE_EDITING
5287 current_prompt = prompt->value;
5293 /* Ensure that getenv("PATH") stays current */
5294 setenv("PATH", path->value, 1);
5297 DBGPRINTF(("MSH_MAIN: returning.\n"));
5302 * Copyright (c) 1987,1997, Prentice Hall
5303 * All rights reserved.
5305 * Redistribution and use of the MINIX operating system in source and
5306 * binary forms, with or without modification, are permitted provided
5307 * that the following conditions are met:
5309 * Redistributions of source code must retain the above copyright
5310 * notice, this list of conditions and the following disclaimer.
5312 * Redistributions in binary form must reproduce the above
5313 * copyright notice, this list of conditions and the following
5314 * disclaimer in the documentation and/or other materials provided
5315 * with the distribution.
5317 * Neither the name of Prentice Hall nor the names of the software
5318 * authors or contributors may be used to endorse or promote
5319 * products derived from this software without specific prior
5320 * written permission.
5322 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5323 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5324 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5325 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5326 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5327 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5328 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5329 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5330 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5331 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5332 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5333 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.