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 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 static 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
107 static int mshdbg_rc = 0;
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 smallint io_flag; /* action (below) */
177 int io_fd; /* fd affected */
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) /* "default" IO fd */
193 * Description of a command or an operation on commands.
194 * Might eventually use a union.
197 smallint op_type; /* operation type, see Txxxx below */
198 char **op_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 void readhere(char **name, char *s, int ec);
531 static int xxchar(struct ioarg *ap);
536 struct ioword *h_iop;
540 static const char *const signame[] = {
543 NULL, /* interrupt */
545 "Illegal instruction",
549 "Floating Point Exception",
554 NULL, /* broken pipe */
560 typedef int (*builtin_func_ptr)(struct op *, char **);
564 builtin_func_ptr builtinfunc;
567 static const struct builtincmd builtincmds[] = {
570 { "break" , dobreak },
572 { "continue", docontinue },
576 { "export" , doexport },
578 { "login" , dologin },
579 { "newgrp" , dologin },
581 { "readonly", doreadonly },
583 { "shift" , doshift },
584 { "times" , dotimes },
586 { "umask" , doumask },
591 static struct op *dowholefile(int /*, int*/);
597 static uint8_t exstat;
598 static smallint gflg; /* (seems to be a parse error indicator) */
599 static smallint interactive; /* Is this an interactive shell */
600 static smallint execflg;
601 static smallint isbreak; /* "break" statement was seen */
602 static int multiline; /* '\n' changed to ';' (counter) */
603 static struct op *outtree; /* result from parser */
606 static struct brkcon *brklist;
607 static struct wdblock *wdlist;
608 static struct wdblock *iolist;
611 static struct var *mshdbg_var;
613 static struct var *vlist; /* dictionary */
614 static struct var *homedir; /* home directory */
615 static struct var *prompt; /* main prompt */
616 static struct var *cprompt; /* continuation prompt */
617 static struct var *path; /* search path for commands */
618 static struct var *shell; /* shell to interpret command files */
619 static struct var *ifs; /* field separators */
621 static int areanum; /* current allocation area */
622 static smallint intr; /* interrupt pending (bool) */
623 static smallint heedint = 1; /* heed interrupt signals (bool) */
625 static char *null = (char*)""; /* null value for variable */
626 static void (*qflag)(int) = SIG_IGN;
630 static int iounit = IODEFAULT;
631 static YYSTYPE yylval;
632 static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
634 static struct here *inhere; /* list of hear docs while parsing */
635 static struct here *acthere; /* list of active here documents */
636 static struct region *areabot; /* bottom of area */
637 static struct region *areatop; /* top of area */
638 static struct region *areanxt; /* starting point of scan */
640 static void *brkaddr;
642 #define AFID_NOBUF (~0)
647 * parsing & execution environment
653 xint *errpt; /* void * */
660 struct env global_env;
661 struct ioarg temparg; // = { .afid = AFID_NOBUF }; /* temporary for PUSHIO */
662 unsigned bufid; // = AFID_ID; /* buffer id counter */
663 char ourtrap[_NSIG + 1];
664 char *trap[_NSIG + 1];
665 struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
666 struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
667 struct ioarg ioargstack[NPUSH];
671 * -k: look for name=value everywhere on command line
673 * -t: exit after reading and executing one command
676 * -u: unset variables net diagnostic
678 char flags['z' - 'a' + 1];
679 char filechar_cmdbuf[BUFSIZ];
681 char child_cmd[LINELIM];
683 struct io iostack[NPUSH];
685 char grave__var_name[LINELIM];
686 char grave__alt_value[LINELIM];
689 #define G (*ptr_to_globals)
690 #define global_env (G.global_env )
691 #define temparg (G.temparg )
692 #define bufid (G.bufid )
693 #define ourtrap (G.ourtrap )
694 #define trap (G.trap )
695 #define sharedbuf (G.sharedbuf )
696 #define mainbuf (G.mainbuf )
697 #define ioargstack (G.ioargstack )
698 /* this looks weird, but is OK ... we index FLAG with 'a'...'z' */
699 #define FLAG (G.flags - 'a' )
700 #define filechar_cmdbuf (G.filechar_cmdbuf)
701 #define line (G.line )
702 #define child_cmd (G.child_cmd )
703 #define iostack (G.iostack )
704 #define INIT_G() do { \
705 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
706 global_env.linep = line; \
707 global_env.iobase = iostack; \
708 global_env.iop = iostack - 1; \
709 global_env.iofd = FDBASE; \
710 temparg.afid = AFID_NOBUF; \
715 /* in substitution */
716 #define INSUB() (global_env.iop->task == XGRAVE || global_env.iop->task == XDOLL)
718 #define RUN(what, arg, gen) ((temparg.what = (arg)), run(&temparg, (gen)))
721 static void print_tree(struct op *head)
724 DBGPRINTF(("PRINT_TREE: no tree\n"));
728 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
732 print_tree(head->left);
735 print_tree(head->right);
737 #endif /* MSHDEBUG */
743 static void prs(const char *s)
746 xwrite_str(STDERR_FILENO, s);
749 static void prn(unsigned u)
754 static void echo(char **wp)
759 for (i = 0; wp[i]; i++) {
767 static void closef(int i)
773 static void closeall(void)
777 for (u = NUFILE; u < NOFILE;)
782 /* fail but return to process next command */
783 static void fail(void) NORETURN;
784 static void fail(void)
790 /* abort shell (or fail in subshell) */
791 static void leave(void) NORETURN;
792 static void leave(void)
794 DBGPRINTF(("LEAVE: leave called!\n"));
805 static void warn(const char *s)
817 static void err(const char *s)
824 if (global_env.errpt)
825 longjmp(global_env.errpt, 1);
827 global_env.iop = global_env.iobase = iostack;
831 /* -------- area.c -------- */
834 * All memory between (char *)areabot and (char *)(areatop+1) is
835 * exclusively administered by the area management routines.
836 * It is assumed that sbrk() and brk() manipulate the high end.
840 void * __q = (void *)-1; \
841 if (brkaddr + (int)(X) < brktop) { \
843 brkaddr += (int)(X); \
848 static void initarea(void)
850 brkaddr = xmalloc(AREASIZE);
851 brktop = brkaddr + AREASIZE;
853 while ((long) sbrk(0) & ALIGN)
855 areabot = (struct region *) sbrk(REGSIZE);
857 areabot->next = areabot;
858 areabot->area = BUSY;
863 static char *getcell(unsigned nbytes)
866 struct region *p, *q;
873 /* silly and defeats the algorithm */
875 * round upwards and add administration area
877 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
880 if (p->area > areanum) {
884 while ((q = p->next)->area > areanum && q != areanxt)
887 * exit loop if cell big enough
896 i = nregio >= GROWBY ? nregio : GROWBY;
897 p = (struct region *) sbrk(i * REGSIZE);
898 if (p == (struct region *) -1)
903 abort(); /* allocated areas are contiguous */
913 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
915 areanxt = p + nregio;
918 * split into requested area and rest
920 if (areanxt + 1 > q) {
922 abort(); /* insufficient space left for admin */
925 areanxt->area = FREE;
929 return (char *) (p + 1);
932 static void freecell(char *cp)
936 p = (struct region *) cp;
944 #define DELETE(obj) freecell((char *)obj)
946 static void freearea(int a)
948 struct region *p, *top;
951 for (p = areabot; p != top; p = p->next)
956 static void setarea(char *cp, int a)
960 p = (struct region *) cp;
965 static int getarea(char *cp)
967 return ((struct region *) cp - 1)->area;
970 static void garbage(void)
972 struct region *p, *q, *top;
975 for (p = areabot; p != top; p = p->next) {
976 if (p->area > areanum) {
977 while ((q = p->next)->area > areanum)
983 if (areatop >= q + SHRINKBY && q->area > areanum) {
984 brk((char *) (q + 1));
992 static void *get_space(int n)
998 err("out of string space");
1002 static char *strsave(const char *s, int a)
1006 cp = get_space(strlen(s) + 1);
1008 // FIXME: I highly doubt this is good.
1017 /* -------- var.c -------- */
1019 static int eqname(const char *n1, const char *n2)
1021 for (; *n1 != '=' && *n1 != '\0'; n1++)
1024 return *n2 == '\0' || *n2 == '=';
1027 static const char *findeq(const char *cp)
1029 while (*cp != '\0' && *cp != '=')
1035 * Find the given name in the dictionary
1036 * and return its value. If the name was
1037 * not previously there, enter it now and
1038 * return a null value.
1040 static struct var *lookup(const char *n)
1042 // FIXME: dirty hack
1043 static struct var dummy;
1051 dummy.name = (char*)n;
1052 for (c = 0; isdigit(*n) && c < 1000; n++)
1053 c = c * 10 + *n - '0';
1054 dummy.status = RONLY;
1055 dummy.value = (c <= dolc ? dolv[c] : null);
1059 for (vp = vlist; vp; vp = vp->next)
1060 if (eqname(vp->name, n))
1064 vp = get_space(sizeof(*vp));
1065 if (vp == 0 || (vp->name = get_space((int) (cp - n) + 2)) == NULL) {
1066 dummy.name = dummy.value = (char*)"";
1071 while ((*xp = *n++) != '\0' && *xp != '=')
1075 setarea((char *) vp, 0);
1076 setarea((char *) vp->name, 0);
1079 vp->status = GETCELL;
1085 * if name is not NULL, it must be
1086 * a prefix of the space `val',
1088 * this is all so that exporting
1089 * values is reasonably painless.
1091 static void nameval(struct var *vp, const char *val, const char *name)
1097 if (vp->status & RONLY) {
1099 while (*xp && *xp != '=')
1100 fputc(*xp++, stderr);
1101 err(" is read-only");
1106 xp = get_space(strlen(vp->name) + strlen(val) + 2);
1109 /* make string: name=value */
1113 while ((*xp = *cp++) != '\0' && *xp != '=')
1120 if (vp->status & GETCELL)
1121 freecell(vp->name); /* form new string `name=value' */
1122 vp->name = (char*)name;
1123 vp->value = (char*)val;
1128 * give variable at `vp' the value `val'.
1130 static void setval(struct var *vp, const char *val)
1132 nameval(vp, val, NULL);
1135 static void export(struct var *vp)
1137 vp->status |= EXPORT;
1140 static void ronly(struct var *vp)
1142 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1143 vp->status |= RONLY;
1146 static int isassign(const char *s)
1149 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1152 /* no isalpha() - we shouldn't use locale */
1153 /* c | 0x20 - lowercase (Latin) letters */
1154 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1165 && (unsigned)(c - '0') > 9 /* not number */
1166 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1173 static int assign(const char *s, int cf)
1178 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1180 if (!isalpha(*s) && *s != '_')
1182 for (cp = s; *cp != '='; cp++)
1183 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1186 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1188 vp->status &= ~GETCELL;
1192 static int checkname(char *cp)
1194 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1196 if (!isalpha(*cp++) && *(cp - 1) != '_')
1199 if (!isalnum(*cp++) && *(cp - 1) != '_')
1204 static void putvlist(int f, int out)
1208 for (vp = vlist; vp; vp = vp->next) {
1209 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1210 if (vp->status & EXPORT)
1211 write(out, "export ", 7);
1212 if (vp->status & RONLY)
1213 write(out, "readonly ", 9);
1214 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1215 write(out, "\n", 1);
1224 static void sig(int i)
1230 static void runtrap(int i)
1235 if (trapstr == NULL)
1241 RUN(aword, trapstr, nlchar);
1245 static void setdash(void)
1249 char m['z' - 'a' + 1];
1252 for (c = 'a'; c <= 'z'; c++)
1256 setval(lookup("-"), m);
1259 static int newfile(char *s)
1263 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1266 if (NOT_LONE_DASH(s)) {
1267 DBGPRINTF(("NEWFILE: s is %s\n", s));
1268 f = open(s, O_RDONLY);
1271 err(": can't open");
1282 struct op *scantree(struct op *head)
1289 if (head->left != NULL) {
1290 dotnode = scantree(head->left);
1295 if (head->right != NULL) {
1296 dotnode = scantree(head->right);
1301 if (head->op_words == NULL)
1304 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1306 if ((head->op_type != TDOT) && LONE_CHAR(head->op_words[0], '.')) {
1307 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1316 static void onecommand(void)
1321 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1323 while (global_env.oenv)
1332 global_env.errpt = NULL;
1333 global_env.linep = line;
1341 setjmp(failpt); /* Bruce Evans' fix */
1343 if (setjmp(failpt) || yyparse() || intr) {
1344 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1346 while (global_env.oenv)
1349 if (!interactive && intr)
1362 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1364 execute(outtree, NOPIPE, NOPIPE, /* no_fork: */ 0);
1367 if (!interactive && intr) {
1379 static int newenv(int f)
1383 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1390 ep = get_space(sizeof(*ep));
1392 while (global_env.oenv)
1397 global_env.oenv = ep;
1398 global_env.errpt = errpt;
1403 static void quitenv(void)
1408 DBGPRINTF(("QUITENV: global_env.oenv=%p\n", global_env.oenv));
1410 ep = global_env.oenv;
1412 fd = global_env.iofd;
1414 /* should close `'d files */
1416 while (--fd >= global_env.iofd)
1422 * Is character c in s?
1424 static int any(int c, const char *s)
1433 * Is any character from s1 in s2?
1435 static int anys(const char *s1, const char *s2)
1443 static char *putn(int n)
1448 static void next(int f)
1450 PUSHIO(afile, f, filechar);
1453 static void onintr(int s UNUSED_PARAM) /* ANSI C requires a parameter */
1455 signal(SIGINT, onintr);
1462 } else if (heedint) {
1469 /* -------- gmatch.c -------- */
1471 * int gmatch(string, pattern)
1472 * char *string, *pattern;
1474 * Match a pattern as in sh(1).
1479 #define QMASK (CMASK & ~QUOTE)
1480 #define NOT '!' /* might use ^ */
1482 static const char *cclass(const char *p, int sub)
1484 int c, d, not, found;
1494 if (p[1] == '-' && p[2] != ']') {
1499 if (c == sub || (c <= sub && sub <= d))
1501 } while (*++p != ']');
1502 return found ? p + 1 : NULL;
1505 static int gmatch(const char *s, const char *p)
1509 if (s == NULL || p == NULL)
1512 while ((pc = *p++ & CMASK) != '\0') {
1529 if (*p == '\0' || gmatch(s, p))
1531 } while (*s++ != '\0');
1535 if (sc != (pc & ~QUOTE))
1543 /* -------- csyn.c -------- */
1545 * shell: syntax (C version)
1548 static void yyerror(const char *s) NORETURN;
1549 static void yyerror(const char *s)
1552 if (interactive && global_env.iop <= iostack) {
1554 while (eofc() == 0 && yylex(0) != '\n')
1561 static void zzerr(void) NORETURN;
1562 static void zzerr(void)
1564 yyerror("syntax error");
1569 DBGPRINTF7(("YYPARSE: enter...\n"));
1576 return yynerrs; /* 0/1 */
1579 static struct op *pipeline(int cf)
1584 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1588 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1591 while ((c = yylex(0)) == '|') {
1592 p = command(CONTIN);
1594 DBGPRINTF8(("PIPELINE: error!\n"));
1598 if (t->op_type != TPAREN && t->op_type != TCOM) {
1599 /* shell statement */
1600 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1603 t = block(TPIPE, t, p, NOWORDS);
1608 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1612 static struct op *andor(void)
1617 DBGPRINTF7(("ANDOR: enter...\n"));
1621 DBGPRINTF9(("ANDOR: t=%p\n", t));
1624 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1625 p = pipeline(CONTIN);
1627 DBGPRINTF8(("ANDOR: error!\n"));
1631 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1637 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1641 static struct op *c_list(void)
1646 DBGPRINTF7(("C_LIST: enter...\n"));
1653 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1655 while ((c = yylex(0)) == ';' || c == '&'
1656 || (multiline && c == '\n')
1664 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1672 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1676 static int synio(int cf)
1682 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1685 if (c != '<' && c != '>') {
1692 iop = io(iounit, i, yylval.cp);
1696 markhere(yylval.cp, iop);
1698 DBGPRINTF7(("SYNIO: returning 1\n"));
1702 static void musthave(int c, int cf)
1704 peeksym = yylex(cf);
1706 DBGPRINTF7(("MUSTHAVE: error!\n"));
1713 static struct op *simple(void)
1719 switch (peeksym = yylex(0)) {
1740 static struct op *nested(int type, int mark)
1744 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1750 return block(type, t, NOBLOCK, NOWORDS);
1753 static struct op *command(int cf)
1756 struct wdblock *iosave;
1759 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1785 t = nested(TPAREN, ')');
1789 t = nested(TBRACE, '}');
1799 t->op_words = wordlist();
1801 if (c != '\n' && c != ';')
1803 t->left = dogroup(0);
1811 t->op_type = (c == WHILE ? TWHILE : TUNTIL);
1813 t->right = dogroup(1);
1814 /* t->op_words = NULL; - newtp() did this */
1825 musthave(IN, CONTIN);
1828 t->left = caselist();
1839 t->right = thenpart();
1848 musthave(WORD, 0); /* gets name of file */
1849 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1851 word(yylval.cp); /* add word to wdlist */
1852 word(NOWORD); /* terminate wdlist */
1853 t->op_words = copyw(); /* dup wdlist */
1864 DBGPRINTF(("COMMAND: returning %p\n", t));
1869 static struct op *dowholefile(int type /*, int mark*/)
1873 DBGPRINTF(("DOWHOLEFILE: enter, type=%d\n", type /*, mark*/));
1878 t = block(type, t, NOBLOCK, NOWORDS);
1879 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1883 static struct op *dogroup(int onlydone)
1889 if (c == DONE && onlydone)
1898 static struct op *thenpart(void)
1909 /*t->op_type = 0; - newtp() did this */
1911 if (t->left == NULL)
1913 t->right = elsepart();
1917 static struct op *elsepart(void)
1922 switch (c = yylex(0)) {
1933 t->right = thenpart();
1942 static struct op *caselist(void)
1947 while ((peeksym = yylex(CONTIN)) != ESAC) {
1948 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1949 t = list(t, casepart());
1952 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1956 static struct op *casepart(void)
1960 DBGPRINTF7(("CASEPART: enter...\n"));
1964 t->op_words = pattern();
1967 peeksym = yylex(CONTIN);
1968 if (peeksym != ESAC)
1969 musthave(BREAK, CONTIN);
1971 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
1976 static char **pattern(void)
1993 static char **wordlist(void)
2003 while ((c = yylex(0)) == WORD)
2011 * supporting functions
2013 static struct op *list(struct op *t1, struct op *t2)
2015 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2022 return block(TLIST, t1, t2, NOWORDS);
2025 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2029 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2037 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1, t2));
2042 /* See if given string is a shell multiline (FOR, IF, etc) */
2043 static int rlookup(char *n)
2049 static const struct res restab[] = {
2072 const struct res *rp;
2074 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2076 for (rp = restab; rp->r_name[0]; rp++)
2077 if (strcmp(rp->r_name, n) == 0) {
2078 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2079 return rp->r_val; /* Return numeric code for shell multiline */
2082 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2083 return 0; /* Not a shell multiline */
2086 static struct op *newtp(void)
2090 t = (struct op *) tree(sizeof(*t));
2091 memset(t, 0, sizeof(*t));
2093 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2098 static struct op *namelist(struct op *t)
2100 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2101 T_CMD_NAMES[t->op_type], iolist));
2104 iolist = addword((char *) NULL, iolist);
2105 t->ioact = copyio();
2109 if (t->op_type != TCOM) {
2110 if (t->op_type != TPAREN && t->ioact != NULL) {
2111 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2112 t->ioact = t->left->ioact;
2113 t->left->ioact = NULL;
2119 t->op_words = copyw();
2124 static char **copyw(void)
2128 wd = getwords(wdlist);
2133 static void word(char *cp)
2135 wdlist = addword(cp, wdlist);
2138 static struct ioword **copyio(void)
2140 struct ioword **iop;
2142 iop = (struct ioword **) getwords(iolist);
2147 static struct ioword *io(int u, int f, char *cp)
2151 iop = (struct ioword *) tree(sizeof(*iop));
2155 iolist = addword((char *) iop, iolist);
2159 static int yylex(int cf)
2176 global_env.linep = line;
2179 line[LINELIM - 1] = '\0';
2182 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2187 if (any(c, "0123456789")) {
2190 if (c1 == '<' || c1 == '>') {
2194 *global_env.linep++ = c;
2199 case '#': /* Comment, skip to next newline or End-of-string */
2200 while ((c = my_getc(0)) != '\0' && c != '\n')
2206 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2210 DBGPRINTF9(("YYLEX: found $\n"));
2211 *global_env.linep++ = c;
2214 c = collect(c, '}');
2233 /* If more chars process them, else return NULL char */
2251 if (multiline || cf & CONTIN) {
2252 if (interactive && global_env.iop <= iostack) {
2253 #if ENABLE_FEATURE_EDITING
2254 current_prompt = cprompt->value;
2256 prs(cprompt->value);
2273 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2274 if (global_env.linep >= elinep)
2275 err("word too long");
2277 *global_env.linep++ = c;
2282 if (any(c, "\"'`$"))
2285 *global_env.linep++ = '\0';
2295 yylval.cp = strsave(line, areanum);
2300 static int collect(int c, int c1)
2304 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2306 *global_env.linep++ = c;
2307 while ((c = my_getc(c1)) != c1) {
2316 if (interactive && c == '\n' && global_env.iop <= iostack) {
2317 #if ENABLE_FEATURE_EDITING
2318 current_prompt = cprompt->value;
2320 prs(cprompt->value);
2323 *global_env.linep++ = c;
2326 *global_env.linep++ = c;
2328 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2333 /* "multiline commands" helper func */
2334 /* see if next 2 chars form a shell multiline */
2335 static int dual(int c)
2340 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2342 *cp++ = c; /* c is the given "peek" char */
2343 *cp++ = my_getc(0); /* get next char of input */
2344 *cp = '\0'; /* add EOS marker */
2346 c = rlookup(s); /* see if 2 chars form a shell multiline */
2348 unget(*--cp); /* String is not a shell multiline, put peek char back */
2350 return c; /* String is multiline, return numeric multiline (restab) code */
2353 static void diag(int ec)
2357 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2360 if (c == '>' || c == '<') {
2363 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2366 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2367 if (c != '&' || yylval.i == IOHERE)
2373 static char *tree(unsigned size)
2379 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2380 prs("command line too complicated\n");
2391 /* -------- exec.c -------- */
2393 static struct op **find1case(struct op *t, const char *w)
2401 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2405 DBGPRINTF3(("FIND1CASE: enter, t->op_type=%d (%s)\n", t->op_type,
2406 T_CMD_NAMES[t->op_type]));
2408 if (t->op_type == TLIST) {
2409 tp = find1case(t->left, w);
2411 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2414 t1 = t->right; /* TPAT */
2418 for (wp = t1->op_words; *wp;) {
2419 cp = evalstr(*wp++, DOSUB);
2420 if (cp && gmatch(w, cp)) {
2421 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2427 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2431 static struct op *findcase(struct op *t, const char *w)
2435 tp = find1case(t, w);
2436 return tp != NULL ? *tp : NULL;
2443 static int execute(struct op *t, int *pin, int *pout, int no_fork)
2446 volatile int i, rv, a;
2450 struct op *outtree_save;
2454 /* Avoid longjmp clobbering */
2459 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2463 DBGPRINTF(("EXECUTE: t=%p, t->op_type=%d (%s), t->op_words is %s\n", t,
2464 t->op_type, T_CMD_NAMES[t->op_type],
2465 ((t->op_words == NULL) ? "NULL" : t->op_words[0])));
2471 ? eval(wp2, t->op_type == TCOM ? DOALL : DOALL & ~DOKEY)
2474 switch (t->op_type) {
2476 DBGPRINTF3(("EXECUTE: TDOT\n"));
2478 outtree_save = outtree;
2480 newfile(evalstr(t->op_words[0], DOALL));
2482 t->left = dowholefile(TLIST /*, 0*/);
2485 outtree = outtree_save;
2488 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2490 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2494 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2498 rv = forkexec(t, pin, pout, no_fork, wp);
2508 pv[0] = remap(pv[0]);
2509 pv[1] = remap(pv[1]);
2510 (void) execute(t->left, pin, pv, /* no_fork: */ 0);
2511 rv = execute(t->right, pv, pout, /* no_fork: */ 0);
2516 (void) execute(t->left, pin, pout, /* no_fork: */ 0);
2517 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2522 smallint hinteractive = interactive;
2524 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2527 if (i == 0) { /* child */
2528 signal(SIGINT, SIG_IGN);
2529 signal(SIGQUIT, SIG_IGN);
2531 signal(SIGTERM, SIG_DFL);
2535 xopen(bb_dev_null, O_RDONLY);
2537 _exit(execute(t->left, pin, pout, /* no_fork: */ 1));
2539 interactive = hinteractive;
2541 setval(lookup("!"), putn(i));
2555 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2557 if (t1 != NULL && (rv == 0) == (t->op_type == TAND))
2558 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2569 while (*wp++ != NULL)
2572 vp = lookup(t->str);
2573 while (setjmp(bc.brkpt))
2576 /* Restore areanum value. It may be incremented by execute()
2577 * below, and then "continue" may jump back to setjmp above */
2579 freearea(areanum + 1);
2581 for (t1 = t->left; i-- && *wp != NULL;) {
2583 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2585 brklist = brklist->nextlev;
2590 while (setjmp(bc.brkpt))
2593 /* Restore areanum value. It may be incremented by execute()
2594 * below, and then "continue" may jump back to setjmp above */
2596 freearea(areanum + 1);
2599 while ((execute(t1, pin, pout, /* no_fork: */ 0) == 0) == (t->op_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);
2651 // Restoring op_words is most likely not needed now: see comment in forkexec()
2652 // (also take a look at exec builtin (doexec) - it touches t->op_words)
2658 if (interactive && intr) {
2669 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2673 static builtin_func_ptr inbuilt(const char *s)
2675 const struct builtincmd *bp;
2677 for (bp = builtincmds; bp->name; bp++)
2678 if (strcmp(bp->name, s) == 0)
2679 return bp->builtinfunc;
2683 static int forkexec(struct op *t, int *pin, int *pout, int no_fork, char **wp)
2687 builtin_func_ptr bltin = NULL;
2688 const char *bltin_name = NULL;
2690 struct ioword **iopp;
2698 smallint hinteractive;
2701 struct brkcon *hbrklist;
2704 /* Avoid longjmp clobbering */
2714 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, no_fork %d\n", t, pin,
2716 DBGPRINTF7(("FORKEXEC: t->op_words is %s\n",
2717 ((t->op_words == NULL) ? "NULL" : t->op_words[0])));
2720 if (t->op_type == TCOM) {
2721 while (*wp++ != NULL)
2725 /* strip all initial assignments */
2726 /* FIXME: not correct wrt PATH=yyy command etc */
2728 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2730 echo(cp ? wp : owp);
2734 if (t->ioact == NULL) {
2735 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2737 DBGPRINTF(("FORKEXEC: returning setstatus(0)\n"));
2738 return setstatus(0);
2740 } else { /* cp != NULL */
2742 bltin = inbuilt(cp);
2747 // We were pointing t->op_words to temporary (expanded) arg list:
2748 // t->op_words = wp;
2749 // and restored it later (in execute()), but "break"
2750 // longjmps away (at "Run builtin" below), leaving t->op_words clobbered!
2751 // See http://bugs.busybox.net/view.php?id=846.
2752 // Now we do not touch t->op_words, but separately pass wp as param list
2754 DBGPRINTF(("FORKEXEC: bltin %p, no_fork %d, owp %p\n", bltin,
2756 /* Don't fork if it is a lone builtin (not in pipe)
2757 * OR we are told to _not_ fork */
2758 if ((!bltin || pin || pout) /* not lone bltin AND */
2759 && !no_fork /* not told to avoid fork */
2761 /* Save values in case child alters them after vfork */
2765 hinteractive = interactive;
2770 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2773 DBGPRINTF(("FORKEXEC: ERROR, can't vfork()!\n"));
2777 if (newpid > 0) { /* Parent */
2778 /* Restore values */
2782 interactive = hinteractive;
2788 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2792 DBGPRINTF(("FORKEXEC: child process, bltin=%p (%s)\n", bltin, bltin_name));
2794 signal(SIGINT, SIG_IGN);
2795 signal(SIGQUIT, SIG_IGN);
2806 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2810 if (pin) { /* NB: close _first_, then move fds! */
2812 xmove_fd(pin[0], 0);
2816 xmove_fd(pout[1], 1);
2821 if (bltin && bltin != doexec) {
2823 err(": can't redirect shell command");
2829 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2830 /* system-detected error */
2839 if (forked || pin || pout) {
2840 /* Builtin in pipe: disallowed */
2841 /* TODO: allow "exec"? */
2843 err(": can't run builtin as part of pipe");
2849 i = setstatus(bltin(t, wp));
2852 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2856 /* should use FIOCEXCL */
2857 for (i = FDBASE; i < NOFILE; i++)
2860 signal(SIGINT, SIG_DFL);
2861 signal(SIGQUIT, SIG_DFL);
2864 if (t->op_type == TPAREN)
2865 _exit(execute(t->left, NOPIPE, NOPIPE, /* no_fork: */ 1));
2867 _exit(EXIT_SUCCESS);
2869 cp = rexecve(wp[0], wp, makenv(0, NULL));
2876 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", getpid()));
2884 * 0< 1> are ignored as required
2887 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2893 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2896 if (iop->io_fd == IODEFAULT) /* take default */
2897 iop->io_fd = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2899 if (pipein && iop->io_fd == 0)
2902 if (pipeout && iop->io_fd == 1)
2905 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2906 if ((iop->io_flag & IOHERE) == 0) {
2907 cp = iop->io_name; /* huh?? */
2908 cp = evalstr(cp, DOSUB | DOTRIM);
2913 if (iop->io_flag & IODUP) {
2914 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2916 err(": illegal >& argument");
2920 iop->io_flag = IOCLOSE;
2921 iop->io_flag &= ~(IOREAD | IOWRITE);
2924 switch (iop->io_flag) {
2926 u = open(cp, O_RDONLY);
2930 case IOHERE | IOXHERE:
2931 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2932 cp = (char*)"here file";
2935 case IOWRITE | IOCAT:
2936 u = open(cp, O_WRONLY);
2938 lseek(u, (long) 0, SEEK_END);
2941 /* fall through to creation if >>file doesn't exist */
2944 u = creat(cp, 0666);
2948 u = dup2(*cp - '0', iop->io_fd);
2962 xmove_fd(u, iop->io_fd);
2967 * Enter a new loop level (marked for break/continue).
2969 static void brkset(struct brkcon *bc)
2971 bc->nextlev = brklist;
2976 * Wait for the last process created.
2977 * Print a message for each process found
2978 * that was killed by a signal.
2979 * Ignore interrupt signals while waiting
2980 * unless `canintr' is true.
2982 static int waitfor(int lastpid, int canintr)
2986 smallint oheedint = heedint;
2993 if (errno != EINTR || canintr)
2998 if (rv < ARRAY_SIZE(signame)) {
2999 if (signame[rv] != NULL) {
3000 if (pid != lastpid) {
3007 if (pid != lastpid) {
3016 prs(" - core dumped");
3017 if (rv >= ARRAY_SIZE(signame) || signame[rv])
3023 } while (pid != lastpid);
3038 static int setstatus(int s)
3041 setval(lookup("?"), putn(s));
3046 * PATH-searching interface to execve.
3047 * If getenv("PATH") were kept up-to-date,
3048 * execvp might be used.
3050 static const char *rexecve(char *c, char **v, char **envp)
3057 if (ENABLE_FEATURE_SH_STANDALONE) {
3058 if (find_applet_by_name(name) >= 0) {
3059 /* We have to exec here since we vforked. Running
3060 * run_applet_and_exit() won't work and bad things
3062 execve(bb_busybox_exec_path, v, envp);
3066 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3068 sp = any('/', c) ? "" : path->value;
3069 asis = (*sp == '\0');
3070 while (asis || *sp != '\0') {
3072 tp = global_env.linep;
3073 for (; *sp != '\0'; tp++) {
3076 asis = (*sp == '\0');
3080 if (tp != global_env.linep)
3084 DBGPRINTF3(("REXECVE: global_env.linep is %s\n", global_env.linep));
3086 execve(global_env.linep, v, envp);
3090 /* File is executable but file format isnt recognized */
3091 /* Run it as a shell script */
3092 /* (execve above didnt do it itself, unlike execvp) */
3093 *v = global_env.linep;
3096 *v = (char*)DEFAULT_SHELL;
3097 execve(DEFAULT_SHELL, v, envp);
3102 return (char *) bb_msg_memory_exhausted;
3105 return "argument list too long";
3108 if (errno == ENOENT) {
3109 exstat = 127; /* standards require this */
3112 exstat = 126; /* mimic bash */
3113 return "can't execute";
3117 * Run the command produced by generator `f'
3118 * applied to stream `arg'.
3120 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3123 struct wdblock *swdlist;
3124 struct wdblock *siolist;
3130 /* Avoid longjmp clobbering */
3134 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3135 areanum, outtree, failpt));
3145 if (newenv(setjmp(errpt)) == 0) {
3149 global_env.iobase = global_env.iop;
3152 if (setjmp(failpt) == 0 && yyparse() == 0)
3153 rv = execute(outtree, NOPIPE, NOPIPE, /* no_fork: */ 0);
3156 DBGPRINTF(("RUN: error from newenv()!\n"));
3163 freearea(areanum--);
3168 /* -------- do.c -------- */
3171 * built-in commands: doX
3174 static int dohelp(struct op *t UNUSED_PARAM, char **args UNUSED_PARAM)
3177 const struct builtincmd *x;
3179 puts("\nBuilt-in commands:\n"
3180 "-------------------");
3185 col += printf("%c%s", ((col == 0) ? '\t' : ' '), x->name);
3192 #if ENABLE_FEATURE_SH_STANDALONE
3194 const char *applet = applet_names;
3197 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applet);
3202 applet += strlen(applet) + 1;
3207 return EXIT_SUCCESS;
3210 static int dolabel(struct op *t UNUSED_PARAM, char **args UNUSED_PARAM)
3215 static int dochdir(struct op *t UNUSED_PARAM, char **args)
3217 const char *cp, *er;
3221 cp = homedir->value;
3224 er = ": no home directory";
3229 er = ": bad directory";
3231 prs(cp != NULL ? cp : "cd");
3236 static int doshift(struct op *t UNUSED_PARAM, char **args)
3240 n = args[1] ? getn(args[1]) : 1;
3242 err("nothing to shift");
3248 setval(lookup("#"), putn(dolc));
3253 * execute login and newgrp directly
3255 static int dologin(struct op *t UNUSED_PARAM, char **args)
3260 signal(SIGINT, SIG_DFL);
3261 signal(SIGQUIT, SIG_DFL);
3263 cp = rexecve(args[0], args, makenv(0, NULL));
3270 static int doumask(struct op *t UNUSED_PARAM, char **args)
3279 printf("%04o\n", i);
3281 i = bb_strtou(cp, NULL, 8);
3283 err("umask: bad octal number");
3291 static int doexec(struct op *t, char **args)
3305 sv_words = t->op_words;
3306 t->op_words = args + 1;
3307 // TODO: test what will happen with "exec break" -
3308 // will it leave t->op_words pointing to garbage?
3309 // (see http://bugs.busybox.net/view.php?id=846)
3310 if (setjmp(failpt) == 0)
3311 execute(t, NOPIPE, NOPIPE, /* no_fork: */ 1);
3312 t->op_words = sv_words;
3320 static int dodot(struct op *t UNUSED_PARAM, char **args)
3328 DBGPRINTF(("DODOT: enter, t=%p, tleft %p, tright %p, global_env.linep is %s\n",
3329 t, t->left, t->right, ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3333 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3336 DBGPRINTF(("DODOT: cp is %s\n", cp));
3338 sp = any('/', cp) ? ":" : path->value;
3340 DBGPRINTF(("DODOT: sp is %s, global_env.linep is %s\n",
3341 ((sp == NULL) ? "NULL" : sp),
3342 ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3345 tp = global_env.linep;
3346 while (*sp && (*tp = *sp++) != ':')
3348 if (tp != global_env.linep)
3353 i = open(global_env.linep, O_RDONLY);
3357 DBGPRINTF(("DODOT: remap=%d, exstat=%d, global_env.iofd %d, i %d, global_env.linep is %s\n",
3358 maltmp, exstat, global_env.iofd, i, global_env.linep));
3360 next(maltmp); /* Basically a PUSHIO */
3362 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3374 static int dowait(struct op *t UNUSED_PARAM, char **args)
3386 setstatus(waitfor(i, 1));
3390 static int doread(struct op *t UNUSED_PARAM, char **args)
3396 if (args[1] == NULL) {
3397 err("Usage: read name ...");
3400 for (wp = args + 1; *wp; wp++) {
3401 for (cp = global_env.linep; !nl && cp < elinep - 1; cp++) {
3402 nb = nonblock_safe_read(STDIN_FILENO, cp, sizeof(*cp));
3403 if (nb != sizeof(*cp))
3406 if (nl || (wp[1] && any(*cp, ifs->value)))
3412 setval(lookup(*wp), global_env.linep);
3417 static int doeval(struct op *t UNUSED_PARAM, char **args)
3419 return RUN(awordlist, args + 1, wdchar);
3422 static int dotrap(struct op *t UNUSED_PARAM, char **args)
3427 if (args[1] == NULL) {
3428 for (i = 0; i <= _NSIG; i++)
3437 resetsig = isdigit(args[1][0]);
3438 for (i = resetsig ? 1 : 2; args[i] != NULL; ++i) {
3439 n = getsig(args[i]);
3443 if (args[1][0] != '\0') {
3444 trap[n] = strsave(args[1], 0);
3453 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3461 static int getsig(char *s)
3466 if (n < 0 || n > _NSIG) {
3467 err("trap: bad signal number");
3473 static void setsig(int n, sighandler_t f)
3477 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3483 static int getn(char *as)
3494 for (n = 0; isdigit(*s); s++)
3495 n = (n * 10) + (*s - '0');
3498 err(": bad number");
3503 static int dobreak(struct op *t UNUSED_PARAM, char **args)
3505 return brkcontin(args[1], 1);
3508 static int docontinue(struct op *t UNUSED_PARAM, char **args)
3510 return brkcontin(args[1], 0);
3513 static int brkcontin(char *cp, int val)
3518 nl = cp == NULL ? 1 : getn(cp);
3525 brklist = bc->nextlev;
3528 err("bad break/continue level");
3531 isbreak = (val != 0);
3532 longjmp(bc->brkpt, 1);
3536 static int doexit(struct op *t UNUSED_PARAM, char **args)
3543 setstatus(getn(cp));
3545 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3552 static int doexport(struct op *t UNUSED_PARAM, char **args)
3554 rdexp(args + 1, export, EXPORT);
3558 static int doreadonly(struct op *t UNUSED_PARAM, char **args)
3560 rdexp(args + 1, ronly, RONLY);
3564 static void rdexp(char **wp, void (*f) (struct var *), int key)
3566 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3567 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3570 for (; *wp != NULL; wp++) {
3571 if (isassign(*wp)) {
3575 for (cp = *wp; *cp != '='; cp++)
3588 static void badid(char *s)
3591 err(": bad identifier");
3594 static int doset(struct op *t UNUSED_PARAM, char **args)
3602 for (vp = vlist; vp; vp = vp->next)
3603 varput(vp->name, STDOUT_FILENO);
3609 FLAG['x'] = FLAG['v'] = 0;
3619 if (*cp >= 'a' && *cp <= 'z')
3629 for (n = 1; args[n]; n++)
3630 setarea((char *) args[n], 0);
3633 setval(lookup("#"), putn(dolc));
3634 setarea((char *) (dolv - 1), 0);
3639 static void varput(char *s, int out)
3641 if (isalnum(*s) || *s == '_') {
3643 xwrite(out, "\n", 1);
3649 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3650 * This file contains code for the times builtin.
3652 static void times_fmt(char *buf, clock_t val, unsigned clk_tck)
3655 if (sizeof(val) > sizeof(int))
3656 sec = ((unsigned long)val) / clk_tck;
3658 sec = ((unsigned)val) / clk_tck;
3661 sprintf(buf, "%um%u.%03us", min, (sec - min * 60),
3662 /* msec: */ ((unsigned)(val - (clock_t)sec * clk_tck)) * 1000 / clk_tck
3665 sprintf(buf, "%um%us", min, (sec - min * 60));
3669 static int dotimes(struct op *t UNUSED_PARAM, char **args UNUSED_PARAM)
3672 unsigned clk_tck = sysconf(_SC_CLK_TCK);
3673 /* How much do we need for "NmN.NNNs" ? */
3674 enum { TIMEBUF_SIZE = sizeof(int)*3 + sizeof(int)*3 + 6 };
3675 char u[TIMEBUF_SIZE], s[TIMEBUF_SIZE];
3676 char cu[TIMEBUF_SIZE], cs[TIMEBUF_SIZE];
3680 times_fmt(u, buf.tms_utime, clk_tck);
3681 times_fmt(s, buf.tms_stime, clk_tck);
3682 times_fmt(cu, buf.tms_cutime, clk_tck);
3683 times_fmt(cs, buf.tms_cstime, clk_tck);
3685 printf("%s %s\n%s %s\n", u, s, cu, cs);
3690 /* -------- eval.c -------- */
3695 * blank interpretation
3700 static char **eval(char **ap, int f)
3708 /* Avoid longjmp clobbering */
3713 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3719 if (newenv(setjmp(errpt)) == 0) {
3720 while (*ap && isassign(*ap))
3721 expand(*ap++, &wb, f & ~DOGLOB);
3723 for (wf = ap; *wf; wf++) {
3725 expand(*wf, &wb, f & ~DOGLOB);
3728 for (wb = addword((char *) NULL, wb); *ap; ap++) {
3729 if (!FLAG['k'] || !isassign(*ap))
3730 expand(*ap, &wb, f & ~DOKEY);
3732 wb = addword((char *) 0, wb);
3738 return gflg ? (char **) NULL : wp;
3743 * Make the exported environment from the exported
3744 * names in the dictionary. Keyword assignments
3745 * will already have been done.
3747 static char **makenv(int all, struct wdblock *wb)
3751 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3753 for (vp = vlist; vp; vp = vp->next)
3754 if (all || vp->status & EXPORT)
3755 wb = addword(vp->name, wb);
3756 wb = addword((char *) 0, wb);
3757 return getwords(wb);
3760 static int expand(const char *cp, struct wdblock **wbp, int f)
3766 /* Avoid longjmp clobbering */
3770 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3777 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3778 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3780 xp = strsave(cp, areanum);
3783 *wbp = addword(xp, *wbp);
3787 if (newenv(setjmp(errpt)) == 0) {
3788 PUSHIO(aword, cp, strchar);
3789 global_env.iobase = global_env.iop;
3790 while ((xp = blank(f)) && gflg == 0) {
3791 global_env.linep = xp;
3792 xp = strsave(xp, areanum);
3793 if ((f & DOGLOB) == 0) {
3796 *wbp = addword(xp, *wbp);
3798 *wbp = glob(xp, *wbp);
3806 static char *evalstr(char *cp, int f)
3810 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3813 if (expand(cp, &wb, f)) {
3814 if (wb == NULL || wb->w_nword == 0
3815 || (cp = wb->w_words[0]) == NULL
3817 // TODO: I suspect that
3818 // char *evalstr(char *cp, int f) is actually
3819 // const char *evalstr(const char *cp, int f)!
3830 * Blank interpretation and quoting
3832 static char *blank(int f)
3836 int scanequals, foundequals;
3838 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3840 sp = global_env.linep;
3841 scanequals = f & DOKEY;
3845 c = subgetc('"', foundequals);
3848 if (sp == global_env.linep)
3850 *global_env.linep++ = 0;
3854 if (f & DOBLANK && any(c, ifs->value))
3863 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3866 if (c == '\'' || !any(c, "$`\""))
3868 *global_env.linep++ = c;
3873 if (!isalpha(c) && c != '_')
3876 c = subgetc('"', foundequals);
3878 f & (DOBLANK && any(c, ifs->value)) ||
3879 (!INSUB() && any(c, "\"'"))) {
3890 } else if (!isalnum(c) && c != '_')
3893 *global_env.linep++ = c;
3895 *global_env.linep++ = 0;
3900 * Get characters, substituting for ` and $
3902 static int subgetc(char ec, int quoted)
3906 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3910 if (!INSUB() && ec != '\'') {
3912 if (grave(quoted) == 0)
3914 global_env.iop->task = XGRAVE;
3920 global_env.iop->task = XDOLL;
3929 * Prepare to generate the string returned by ${} substitution.
3931 static int dollar(int quoted)
3936 char *s, c, *cp = NULL;
3939 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3942 s = global_env.linep;
3944 *global_env.linep++ = c;
3945 if (isalpha(c) || c == '_') {
3946 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3947 if (global_env.linep < elinep)
3948 *global_env.linep++ = c;
3953 oiop = global_env.iop;
3954 otask = global_env.iop->task;
3956 global_env.iop->task = XOTHER;
3957 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3958 if (global_env.linep < elinep)
3959 *global_env.linep++ = c;
3960 if (oiop == global_env.iop)
3961 global_env.iop->task = otask;
3968 if (global_env.linep >= elinep) {
3969 err("string in ${} too long");
3971 global_env.linep -= 10;
3973 *global_env.linep = 0;
3975 for (cp = s + 1; *cp; cp++)
3976 if (any(*cp, "=-+?")) {
3981 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3983 /* currently this does not distinguish $* and $@ */
3984 /* should check dollar */
3985 global_env.linep = s;
3986 PUSHIO(awordlist, dolv + 1, dolchar);
3988 } else { /* trap the nasty ${=} */
3999 err("can't use ${...=...} with $n");
4008 dolp = strsave(cp, areanum);
4013 prs("missing value for ");
4020 } else if (c == '+')
4021 dolp = strsave(cp, areanum);
4022 if (FLAG['u'] && dolp == null) {
4023 prs("unset variable: ");
4027 global_env.linep = s;
4028 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4033 * Run the command in `...` and read its output.
4036 static int grave(int quoted)
4038 /* moved to G: static char child_cmd[LINELIM]; */
4049 char *argument_list[4];
4050 struct wdblock *wb = NULL;
4053 /* Avoid longjmp clobbering */
4057 for (cp = global_env.iop->argp->aword; *cp != '`'; cp++) {
4059 err("no closing `");
4064 /* string copy with dollar expansion */
4065 src = global_env.iop->argp->aword;
4070 while ((*src != '`') && (count < LINELIM)) {
4075 if (*src == '$' && !ignore && !ignore_once) {
4077 /* moved to G to reduce stack usage
4078 char var_name[LINELIM];
4079 char alt_value[LINELIM];
4081 #define var_name (G.grave__var_name)
4082 #define alt_value (G.grave__alt_value)
4095 var_name[var_index++] = *src++;
4096 while (isalnum(*src) || *src=='_')
4097 var_name[var_index++] = *src++;
4098 var_name[var_index] = 0;
4111 err("unclosed ${\n");
4116 while (*src && (*src != '}')) {
4117 alt_value[alt_index++] = *src++;
4119 alt_value[alt_index] = 0;
4121 err("unclosed ${\n");
4128 if (isalpha(*var_name)) {
4129 /* let subshell handle it instead */
4131 char *namep = var_name;
4139 char *altp = alt_value;
4147 wb = addword(lookup(var_name)->name, wb);
4151 vp = lookup(var_name);
4152 if (vp->value != null)
4153 value = (operator == '+') ?
4154 alt_value : vp->value;
4155 else if (operator == '?') {
4158 } else if (alt_index && (operator != '+')) {
4160 if (operator == '=')
4165 while (*value && (count < LINELIM)) {
4180 if (openpipe(pf) < 0)
4183 while ((i = vfork()) == -1 && errno == EAGAIN)
4186 DBGPRINTF3(("GRAVE: i is %p\n", io));
4190 err((char *) bb_msg_memory_exhausted);
4194 waitpid(i, NULL, 0); // safe_waitpid?
4195 global_env.iop->argp->aword = ++cp;
4197 PUSHIO(afile, remap(pf[0]),
4198 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4201 /* allow trapped signals */
4202 /* XXX - Maybe this signal stuff should go as well? */
4203 for (j = 0; j <= _NSIG; j++)
4204 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4207 /* Testcase where below checks are needed:
4208 * close stdout & run this script:
4216 argument_list[0] = (char *) DEFAULT_SHELL;
4217 argument_list[1] = (char *) "-c";
4218 argument_list[2] = child_cmd;
4219 argument_list[3] = NULL;
4221 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4222 prs(argument_list[0]);
4225 _exit(EXIT_FAILURE);
4229 static char *unquote(char *as)
4240 /* -------- glob.c -------- */
4246 #define scopy(x) strsave((x), areanum)
4248 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4250 static struct wdblock *cl, *nl;
4251 static const char spcl[] ALIGN1= "[?*";
4253 static struct wdblock *glob(char *cp, struct wdblock *wb)
4261 for (pp = cp; *pp; pp++)
4264 else if (!any(*pp & ~QUOTE, spcl))
4267 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4268 nl = newword(cl->w_nword * 2);
4269 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4270 for (pp = cl->w_words[i]; *pp; pp++)
4271 if (any(*pp, spcl)) {
4272 globname(cl->w_words[i], pp);
4276 nl = addword(scopy(cl->w_words[i]), nl);
4278 for (i = 0; i < cl->w_nword; i++)
4279 DELETE(cl->w_words[i]);
4283 for (i = 0; i < cl->w_nword; i++)
4284 unquote(cl->w_words[i]);
4285 qsort_string_vector(cl->w_words, cl->w_nword);
4286 for (i = 0; i < cl->w_nword; i++)
4287 wb = addword(cl->w_words[i], wb);
4292 wb = addword(unquote(cp), wb);
4296 static void globname(char *we, char *pp)
4299 char *name, *gp, *dp;
4303 char dname[NAME_MAX + 1];
4306 for (np = we; np != pp; pp--)
4309 dp = cp = get_space((int) (pp - np) + 3);
4314 gp = cp = get_space(strlen(pp) + 1);
4315 while (*np && *np != '/')
4324 dname[NAME_MAX] = '\0';
4325 while ((de = readdir(dirp)) != NULL) {
4326 /* XXX Hmmm... What this could be? (abial) */
4327 /* if (ent[j].d_ino == 0) continue;
4329 strncpy(dname, de->d_name, NAME_MAX);
4330 if (dname[0] == '.')
4333 for (k = 0; k < NAME_MAX; k++)
4334 if (any(dname[k], spcl))
4336 if (gmatch(dname, gp)) {
4337 name = generate(we, pp, dname, np);
4338 if (*np && !anys(np, spcl)) {
4339 if (stat(name, &dbuf)) {
4344 nl = addword(name, nl);
4353 * generate a pathname as below.
4354 * start..end1 / middle end
4355 * the slashes come for free
4357 static char *generate(char *start1, char *end1, char *middle, char *end)
4362 p = op = get_space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4373 static int anyspcl(struct wdblock *wb)
4379 for (i = 0; i < wb->w_nword; i++)
4380 if (anys(spcl, *wd++))
4386 /* -------- word.c -------- */
4388 static struct wdblock *newword(int nw)
4392 wb = get_space(sizeof(*wb) + nw * sizeof(char *));
4398 static struct wdblock *addword(char *wd, struct wdblock *wb)
4400 struct wdblock *wb2;
4404 wb = newword(NSTART);
4406 if (nw >= wb->w_bsize) {
4407 wb2 = newword(nw * 2);
4408 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4409 nw * sizeof(char *));
4414 wb->w_words[wb->w_nword++] = wd;
4418 static char **getwords(struct wdblock *wb)
4425 if (wb->w_nword == 0) {
4429 nb = sizeof(*wd) * wb->w_nword;
4431 memcpy(wd, wb->w_words, nb);
4432 DELETE(wb); /* perhaps should done by caller */
4437 /* -------- io.c -------- */
4443 static int my_getc(int ec)
4447 if (global_env.linep > elinep) {
4448 while ((c = readc()) != '\n' && c)
4450 err("input line too long");
4455 if ((ec != '\'') && (ec != '`') && (global_env.iop->task != XGRAVE)) {
4458 if (c == '\n' && ec != '\"')
4466 static void unget(int c)
4468 if (global_env.iop >= global_env.iobase)
4469 global_env.iop->peekc = c;
4472 static int eofc(void)
4474 return global_env.iop < global_env.iobase || (global_env.iop->peekc == 0 && global_env.iop->prev == 0);
4477 static int readc(void)
4481 RCPRINTF(("READC: global_env.iop %p, global_env.iobase %p\n", global_env.iop, global_env.iobase));
4483 for (; global_env.iop >= global_env.iobase; global_env.iop--) {
4484 RCPRINTF(("READC: global_env.iop %p, peekc 0x%x\n", global_env.iop, global_env.iop->peekc));
4485 c = global_env.iop->peekc;
4487 global_env.iop->peekc = 0;
4490 if (global_env.iop->prev != 0) {
4491 c = (*global_env.iop->iofn)(global_env.iop->argp, global_env.iop);
4497 if (global_env.iop == iostack)
4499 global_env.iop->prev = c;
4502 if (global_env.iop->task == XIO && global_env.iop->prev != '\n') {
4503 global_env.iop->prev = 0;
4504 if (global_env.iop == iostack)
4509 if (global_env.iop->task == XIO) {
4511 global_env.iop->prev = 0;
4514 if (interactive && global_env.iop == iostack + 1) {
4515 #if ENABLE_FEATURE_EDITING
4516 current_prompt = prompt->value;
4524 if (global_env.iop >= iostack) {
4525 RCPRINTF(("READC: return 0, global_env.iop %p\n", global_env.iop));
4529 DBGPRINTF(("READC: leave()...\n"));
4535 static void ioecho(char c)
4538 write(STDERR_FILENO, &c, sizeof c);
4541 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4543 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, global_env.iop %p\n", argp,
4544 argp->afid, global_env.iop));
4546 /* Set env ptr for io source to next array spot and check for array overflow */
4547 if (++global_env.iop >= &iostack[NPUSH]) {
4549 err("Shell input nested too deeply");
4554 /* We did not overflow the NPUSH array spots so setup data structs */
4556 global_env.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4558 if (argp->afid != AFID_NOBUF)
4559 global_env.iop->argp = argp;
4562 global_env.iop->argp = ioargstack + (global_env.iop - iostack); /* MAL - index into stack */
4563 *global_env.iop->argp = *argp; /* copy data from temp area into stack spot */
4565 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4567 if (global_env.iop == &iostack[0])
4568 global_env.iop->argp->afbuf = &mainbuf;
4570 global_env.iop->argp->afbuf = &sharedbuf;
4572 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4573 /* This line appears to be active when running scripts from command line */
4574 if ((isatty(global_env.iop->argp->afile) == 0)
4575 && (global_env.iop == &iostack[0]
4576 || lseek(global_env.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4577 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4578 bufid = AFID_ID; /* AFID_ID = 0 */
4580 global_env.iop->argp->afid = bufid; /* assign buffer id */
4583 DBGPRINTF(("PUSHIO: iostack %p, global_env.iop %p, afbuf %p\n",
4584 iostack, global_env.iop, global_env.iop->argp->afbuf));
4585 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, global_env.iop %p\n",
4586 &mainbuf, &sharedbuf, bufid, global_env.iop));
4590 global_env.iop->prev = ~'\n';
4591 global_env.iop->peekc = 0;
4592 global_env.iop->xchar = 0;
4593 global_env.iop->nlcount = 0;
4595 if (fn == filechar || fn == linechar)
4596 global_env.iop->task = XIO;
4597 else if (fn == (int (*)(struct ioarg *)) gravechar
4598 || fn == (int (*)(struct ioarg *)) qgravechar)
4599 global_env.iop->task = XGRAVE;
4601 global_env.iop->task = XOTHER;
4604 static struct io *setbase(struct io *ip)
4608 xp = global_env.iobase;
4609 global_env.iobase = ip;
4614 * Input generating functions
4618 * Produce the characters of a string, then a newline, then NUL.
4620 static int nlchar(struct ioarg *ap)
4624 if (ap->aword == NULL)
4635 * Given a list of words, produce the characters
4636 * in them, with a space after each word.
4638 static int wdchar(struct ioarg *ap)
4653 ap->awordlist = NULL;
4658 * Return the characters of a list of words,
4659 * producing a space between them.
4661 static int dolchar(struct ioarg *ap)
4665 wp = *ap->awordlist++;
4667 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4673 static int xxchar(struct ioarg *ap)
4677 if (ap->aword == NULL)
4688 * Produce the characters from a single word (string).
4690 static int strchar(struct ioarg *ap)
4692 if (ap->aword == NULL)
4694 return *ap->aword++;
4698 * Produce quoted characters from a single word (string).
4700 static int qstrchar(struct ioarg *ap)
4704 if (ap->aword == NULL)
4713 * Return the characters from a file.
4715 static int filechar(struct ioarg *ap)
4719 struct iobuf *bp = ap->afbuf;
4721 if (ap->afid != AFID_NOBUF) {
4722 i = (ap->afid != bp->id);
4723 if (i || bp->bufp == bp->ebufp) {
4725 lseek(ap->afile, ap->afpos, SEEK_SET);
4727 i = nonblock_safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4735 bp->ebufp = bp->bufp + i;
4739 return *bp->bufp++ & 0177;
4741 #if ENABLE_FEATURE_EDITING
4742 if (interactive && isatty(ap->afile)) {
4743 /* moved to G: static char filechar_cmdbuf[BUFSIZ]; */
4744 static int position = 0, size = 0;
4746 while (size == 0 || position >= size) {
4747 size = read_line_input(current_prompt, filechar_cmdbuf, BUFSIZ, line_input_state);
4748 if (size < 0) /* Error/EOF */
4751 /* if Ctrl-C, size == 0 and loop will repeat */
4753 c = filechar_cmdbuf[position];
4758 i = nonblock_safe_read(ap->afile, &c, sizeof(c));
4759 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4763 * Return the characters from a here temp file.
4765 static int herechar(struct ioarg *ap)
4769 if (nonblock_safe_read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4777 * Return the characters produced by a process (`...`).
4778 * Quote them if required, and remove any trailing newline characters.
4780 static int gravechar(struct ioarg *ap, struct io *iop)
4784 c = qgravechar(ap, iop) & ~QUOTE;
4790 static int qgravechar(struct ioarg *ap, struct io *iop)
4794 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4799 return '\n' | QUOTE;
4803 } else if ((c = filechar(ap)) == '\n') {
4805 while ((c = filechar(ap)) == '\n')
4813 return c != 0 ? c | QUOTE : 0;
4817 * Return a single command (usually the first line) from a file.
4819 static int linechar(struct ioarg *ap)
4827 ap->afile = -1; /* illegal value */
4834 * Remap fd into shell's fd space
4836 static int remap(int fd)
4842 DBGPRINTF(("REMAP: fd=%d, global_env.iofd=%d\n", fd, global_env.iofd));
4844 if (fd < global_env.iofd) {
4845 for (i = 0; i < NOFILE; i++)
4852 } while (fd >= 0 && fd < global_env.iofd);
4854 for (i = 0; i < NOFILE; i++)
4859 err("too many files open in shell");
4865 static int openpipe(int *pv)
4871 err("can't create pipe - try again");
4875 static void closepipe(int *pv)
4884 /* -------- here.c -------- */
4890 static void markhere(char *s, struct ioword *iop)
4892 struct here *h, *lh;
4894 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4896 h = get_space(sizeof(struct here));
4900 h->h_tag = evalstr(s, DOSUB);
4910 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4911 if (lh->h_next == 0) {
4917 iop->io_flag |= IOHERE | IOXHERE;
4918 for (s = h->h_tag; *s; s++) {
4920 iop->io_flag &= ~IOXHERE;
4924 h->h_dosub = ((iop->io_flag & IOXHERE) ? '\0' : '\'');
4927 static void gethere(void)
4929 struct here *h, *hp;
4931 DBGPRINTF7(("GETHERE: enter...\n"));
4933 /* Scan here files first leaving inhere list in place */
4934 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
4935 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub /* NUL or ' */);
4937 /* Make inhere list active - keep list intact for scraphere */
4939 hp->h_next = acthere;
4945 static void readhere(char **name, char *s, int ec)
4948 char tname[30] = ".msh_XXXXXX";
4951 char myline[LINELIM + 1];
4954 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
4956 tf = mkstemp(tname);
4960 *name = strsave(tname, areanum);
4962 if (newenv(setjmp(errpt)) != 0)
4965 pushio(global_env.iop->argp, (int (*)(struct ioarg *)) global_env.iop->iofn);
4966 global_env.iobase = global_env.iop;
4968 if (interactive && global_env.iop <= iostack) {
4969 #if ENABLE_FEATURE_EDITING
4970 current_prompt = cprompt->value;
4972 prs(cprompt->value);
4976 while ((c = my_getc(ec)) != '\n' && c) {
4979 if (thenext >= &myline[LINELIM]) {
4986 if (strcmp(s, myline) == 0 || c == 0)
4989 write(tf, myline, (int) (thenext - myline));
4992 prs("here document `");
5002 * open here temp file.
5003 * if unquoted here, expand here temp file into second temp file.
5005 static int herein(char *hname, int xdoll)
5011 /* Avoid longjmp clobbering */
5017 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5019 hf = open(hname, O_RDONLY);
5025 char tname[30] = ".msh_XXXXXX";
5028 tf = mkstemp(tname);
5032 if (newenv(setjmp(errpt)) == 0) {
5033 PUSHIO(afile, hf, herechar);
5034 setbase(global_env.iop);
5035 while ((c = subgetc(0, 0)) != 0) {
5037 write(tf, &c, sizeof c);
5043 tf = open(tname, O_RDONLY);
5050 static void scraphere(void)
5054 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5056 for (h = inhere; h != NULL; h = h->h_next) {
5057 if (h->h_iop && h->h_iop->io_name)
5058 unlink(h->h_iop->io_name);
5063 /* unlink here temp files before a freearea(area) */
5064 static void freehere(int area)
5066 struct here *h, *hl;
5068 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5071 for (h = acthere; h != NULL; h = h->h_next) {
5072 if (getarea((char *) h) >= area) {
5073 if (h->h_iop->io_name != NULL)
5074 unlink(h->h_iop->io_name);
5076 acthere = h->h_next;
5078 hl->h_next = h->h_next;
5086 /* -------- sh.c -------- */
5091 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5092 int msh_main(int argc, char **argv)
5098 int (*iof) (struct ioarg *);
5102 sharedbuf.id = AFID_NOBUF;
5103 mainbuf.id = AFID_NOBUF;
5104 elinep = line + sizeof(line) - 5;
5106 #if ENABLE_FEATURE_EDITING
5107 line_input_state = new_line_input_t(FOR_SHELL);
5110 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5116 assign(*ap++, !COPYV);
5117 for (ap = environ; *ap;)
5118 export(lookup(*ap++));
5123 shell = lookup("SHELL");
5124 if (shell->value == null)
5125 setval(shell, (char *)DEFAULT_SHELL);
5128 homedir = lookup("HOME");
5129 if (homedir->value == null)
5130 setval(homedir, "/");
5133 setval(lookup("$"), putn(getpid()));
5135 path = lookup("PATH");
5136 if (path->value == null) {
5137 /* Can be merged with same string elsewhere in bbox */
5139 setval(path, bb_default_root_path);
5141 setval(path, bb_default_path);
5145 ifs = lookup("IFS");
5146 if (ifs->value == null)
5147 setval(ifs, " \t\n");
5150 mshdbg_var = lookup("MSHDEBUG");
5151 if (mshdbg_var->value == null)
5152 setval(mshdbg_var, "0");
5155 prompt = lookup("PS1");
5156 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5157 if (prompt->value == null)
5159 setval(prompt, DEFAULT_USER_PROMPT);
5160 if (geteuid() == 0) {
5161 setval(prompt, DEFAULT_ROOT_PROMPT);
5162 prompt->status &= ~EXPORT;
5164 cprompt = lookup("PS2");
5165 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5166 if (cprompt->value == null)
5168 setval(cprompt, "> ");
5174 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5175 for (s = argv[0] + 1; *s; s++)
5178 prompt->status &= ~EXPORT;
5179 cprompt->status &= ~EXPORT;
5181 setval(cprompt, "");
5184 PUSHIO(aword, *++argv, iof = nlchar);
5192 /* standard input */
5196 prompt->status &= ~EXPORT;
5204 if (*s >= 'a' && *s <= 'z')
5212 if (iof == filechar && --argc > 0) {
5214 setval(cprompt, "");
5215 prompt->status &= ~EXPORT;
5216 cprompt->status &= ~EXPORT;
5218 /* Shell is non-interactive, activate printf-based debug */
5220 mshdbg = mshdbg_var->value[0] - '0';
5224 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5228 exit(EXIT_FAILURE); /* Exit on error */
5234 /* This won't be true if PUSHIO has been called, say from newfile() above */
5235 if (global_env.iop < iostack) {
5236 PUSHIO(afile, 0, iof);
5237 if (isatty(0) && isatty(1) && !cflag) {
5239 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5241 printf("\n\n%s built-in shell (msh with debug)\n", bb_banner);
5243 printf("\n\n%s built-in shell (msh)\n", bb_banner);
5245 printf("Enter 'help' for a list of built-in commands.\n\n");
5250 signal(SIGQUIT, qflag);
5251 if (name && name[0] == '-') {
5253 f = open(".profile", O_RDONLY);
5256 f = open("/etc/profile", O_RDONLY);
5261 signal(SIGTERM, sig);
5263 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5264 signal(SIGINT, onintr);
5266 /* Handle "msh SCRIPT VAR=val params..." */
5267 /* Disabled: bash does not do it! */
5270 /* skip leading args of the form VAR=val */
5271 while (*argv && assign(*argv, !COPYV)) {
5281 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5283 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, global_env.iop %p, iostack %p\n", interactive, global_env.iop, iostack));
5286 if (interactive && global_env.iop <= iostack) {
5287 #if ENABLE_FEATURE_EDITING
5288 current_prompt = prompt->value;
5294 /* Ensure that getenv("PATH") stays current */
5295 setenv("PATH", path->value, 1);
5298 DBGPRINTF(("MSH_MAIN: returning.\n"));
5303 * Copyright (c) 1987,1997, Prentice Hall
5304 * All rights reserved.
5306 * Redistribution and use of the MINIX operating system in source and
5307 * binary forms, with or without modification, are permitted provided
5308 * that the following conditions are met:
5310 * Redistributions of source code must retain the above copyright
5311 * notice, this list of conditions and the following disclaimer.
5313 * Redistributions in binary form must reproduce the above
5314 * copyright notice, this list of conditions and the following
5315 * disclaimer in the documentation and/or other materials provided
5316 * with the distribution.
5318 * Neither the name of Prentice Hall nor the names of the software
5319 * authors or contributors may be used to endorse or promote
5320 * products derived from this software without specific prior
5321 * written permission.
5323 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5324 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5325 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5326 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5327 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5328 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5329 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5330 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5331 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5332 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5333 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5334 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.