1 /* vi: set sw=4 ts=4: */
3 * Minix shell port for busybox
5 * This version of the Minix shell was adapted for use in busybox
6 * by Erik Andersen <andersen@codepoet.org>
8 * - backtick expansion did not work properly
9 * Jonas Holmberg <jonas.holmberg@axis.com>
10 * Robert Schwebel <r.schwebel@pengutronix.de>
11 * Erik Andersen <andersen@codepoet.org>
13 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
16 #include <sys/times.h>
23 # include <sys/types.h>
24 # include <sys/stat.h>
25 # include <sys/wait.h>
36 # define bb_dev_null "/dev/null"
37 # define DEFAULT_SHELL "/proc/self/exe"
38 # define CONFIG_BUSYBOX_EXEC_PATH "/proc/self/exe"
39 # define bb_banner "busybox standalone"
40 # define ENABLE_FEATURE_SH_STANDALONE 0
41 # define bb_msg_memory_exhausted "memory exhausted"
42 # define xmalloc(size) malloc(size)
43 # define msh_main(argc,argv) main(argc,argv)
44 # define safe_read(fd,buf,count) read(fd,buf,count)
45 # define nonblock_safe_read(fd,buf,count) read(fd,buf,count)
46 # define NOT_LONE_DASH(s) ((s)[0] != '-' || (s)[1])
47 # define LONE_CHAR(s,c) ((s)[0] == (c) && !(s)[1])
48 # define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
49 static int find_applet_by_name(const char *applet)
53 static char *utoa_to_buf(unsigned n, char *buf, unsigned buflen)
56 assert(sizeof(unsigned) == 4);
59 for (i = 1000000000; i; i /= 10) {
61 if (res || out || i == 1) {
71 static char *itoa_to_buf(int n, char *buf, unsigned buflen)
73 if (buflen && n < 0) {
78 return utoa_to_buf((unsigned)n, buf, buflen);
80 static char local_buf[12];
81 static char *itoa(int n)
83 *(itoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
87 # include "busybox.h" /* for applet_names */
93 int mshdbg = MSHDEBUG;
95 #define DBGPRINTF(x) if (mshdbg>0) printf x
96 #define DBGPRINTF0(x) if (mshdbg>0) printf x
97 #define DBGPRINTF1(x) if (mshdbg>1) printf x
98 #define DBGPRINTF2(x) if (mshdbg>2) printf x
99 #define DBGPRINTF3(x) if (mshdbg>3) printf x
100 #define DBGPRINTF4(x) if (mshdbg>4) printf x
101 #define DBGPRINTF5(x) if (mshdbg>5) printf x
102 #define DBGPRINTF6(x) if (mshdbg>6) printf x
103 #define DBGPRINTF7(x) if (mshdbg>7) printf x
104 #define DBGPRINTF8(x) if (mshdbg>8) printf x
105 #define DBGPRINTF9(x) if (mshdbg>9) printf x
109 #define RCPRINTF(x) if (mshdbg_rc) printf x
114 #define DBGPRINTF0(x) ((void)0)
115 #define DBGPRINTF1(x) ((void)0)
116 #define DBGPRINTF2(x) ((void)0)
117 #define DBGPRINTF3(x) ((void)0)
118 #define DBGPRINTF4(x) ((void)0)
119 #define DBGPRINTF5(x) ((void)0)
120 #define DBGPRINTF6(x) ((void)0)
121 #define DBGPRINTF7(x) ((void)0)
122 #define DBGPRINTF8(x) ((void)0)
123 #define DBGPRINTF9(x) ((void)0)
125 #define RCPRINTF(x) ((void)0)
127 #endif /* MSHDEBUG */
130 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
131 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
132 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
134 # define DEFAULT_ROOT_PROMPT "# "
135 # define DEFAULT_USER_PROMPT "$ "
139 /* -------- sh.h -------- */
145 #define NPUSH 8 /* limit to input nesting */
148 #define NOFILE 20 /* Number of open files */
149 #define NUFILE 10 /* Number of user-accessible files */
150 #define FDBASE 10 /* First file usable by Shell */
153 * values returned by wait
155 #define WAITSIG(s) ((s) & 0177)
156 #define WAITVAL(s) (((s) >> 8) & 0377)
157 #define WAITCORE(s) (((s) & 0200) != 0)
160 * library and system definitions
162 typedef void xint; /* base type of jmp_buf, for not broken compilers */
167 #define NOBLOCK ((struct op *)NULL)
168 #define NOWORD ((char *)NULL)
169 #define NOWORDS ((char **)NULL)
170 #define NOPIPE ((int *)NULL)
176 short io_unit; /* unit affected */
177 short io_flag; /* action (below) */
178 char *io_name; /* file name */
181 #define IOREAD 1 /* < */
182 #define IOHERE 2 /* << (here file) */
183 #define IOWRITE 4 /* > */
184 #define IOCAT 8 /* >> */
185 #define IOXHERE 16 /* ${}, ` in << */
186 #define IODUP 32 /* >&digit */
187 #define IOCLOSE 64 /* >&- */
189 #define IODEFAULT (-1) /* token for default IO unit */
193 * Description of a command or an operation on commands.
194 * Might eventually use a union.
197 smallint type; /* operation type, see Txxxx below */
198 char **words; /* arguments to a command */
199 struct ioword **ioact; /* IO actions (eg, < > >>) */
202 char *str; /* identifier for case and for */
205 #define TCOM 1 /* command */
206 #define TPAREN 2 /* (c-list) */
207 #define TPIPE 3 /* a | b */
208 #define TLIST 4 /* a [&;] b */
209 #define TOR 5 /* || */
210 #define TAND 6 /* && */
218 #define TPAT 14 /* pattern in case */
219 #define TBRACE 15 /* {c-list} */
220 #define TASYNC 16 /* c & */
221 /* Added to support "." file expansion */
224 /* Strings for names to make debug easier */
226 static const char *const T_CMD_NAMES[] = {
248 #define AREASIZE (90000)
251 * flags to control evaluation of words
253 #define DOSUB 1 /* interpret $, `, and quotes */
254 #define DOBLANK 2 /* perform blank interpretation */
255 #define DOGLOB 4 /* interpret [?* */
256 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
257 #define DOTRIM 16 /* trim resulting string */
259 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
264 struct brkcon *nextlev;
268 static smallint trapset; /* trap pending (signal number) */
270 static smallint yynerrs; /* yacc (flag) */
272 /* moved to G: static char line[LINELIM]; */
274 #if ENABLE_FEATURE_EDITING
275 static char *current_prompt;
276 static line_input_t *line_input_state;
283 static const char *rexecve(char *c, char **v, char **envp);
284 static char *evalstr(char *cp, int f);
285 static char *putn(int n);
286 static char *unquote(char *as);
287 static int rlookup(char *n);
288 static struct wdblock *glob(char *cp, struct wdblock *wb);
289 static int my_getc(int ec);
290 static int subgetc(char ec, int quoted);
291 static char **makenv(int all, struct wdblock *wb);
292 static char **eval(char **ap, int f);
293 static int setstatus(int s);
294 static int waitfor(int lastpid, int canintr);
296 static void onintr(int s); /* SIGINT handler */
298 static int newenv(int f);
299 static void quitenv(void);
300 static void next(int f);
301 static void setdash(void);
302 static void onecommand(void);
303 static void runtrap(int i);
306 /* -------- area stuff -------- */
308 #define REGSIZE sizeof(struct region)
310 /* #define SHRINKBY (64) */
314 #define ALIGN (sizeof(int)-1)
323 /* -------- grammar stuff -------- */
348 /* Added for "." file expansion */
351 #define YYERRCODE 300
354 #define CONTIN 01 /* skip new lines to complete command */
356 static struct op *pipeline(int cf);
357 static struct op *andor(void);
358 static struct op *c_list(void);
359 static int synio(int cf);
360 static void musthave(int c, int cf);
361 static struct op *simple(void);
362 static struct op *nested(int type, int mark);
363 static struct op *command(int cf);
364 static struct op *dogroup(int onlydone);
365 static struct op *thenpart(void);
366 static struct op *elsepart(void);
367 static struct op *caselist(void);
368 static struct op *casepart(void);
369 static char **pattern(void);
370 static char **wordlist(void);
371 static struct op *list(struct op *t1, struct op *t2);
372 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
373 static struct op *newtp(void);
374 static struct op *namelist(struct op *t);
375 static char **copyw(void);
376 static void word(char *cp);
377 static struct ioword **copyio(void);
378 static struct ioword *io(int u, int f, char *cp);
379 static int yylex(int cf);
380 static int collect(int c, int c1);
381 static int dual(int c);
382 static void diag(int ec);
383 static char *tree(unsigned size);
385 /* -------- var.h -------- */
394 #define COPYV 1 /* flag to setval, suggesting copy */
395 #define RONLY 01 /* variable is read-only */
396 #define EXPORT 02 /* variable is to be exported */
397 #define GETCELL 04 /* name & value space was got with getcell */
399 static int yyparse(void);
402 /* -------- io.h -------- */
405 unsigned id; /* buffer id */
406 char buf[512]; /* buffer */
407 char *bufp; /* pointer into buffer */
408 char *ebufp; /* pointer to end of buffer */
411 /* possible arguments to an IO function */
415 int afile; /* file descriptor */
416 unsigned afid; /* buffer id */
417 off_t afpos; /* file position */
418 struct iobuf *afbuf; /* buffer for this file */
421 /* an input generator's state */
423 int (*iofn) (struct ioarg *, struct io *);
426 char prev; /* previous character read by readc() */
427 char nlcount; /* for `'s */
428 char xchar; /* for `'s */
429 char task; /* reason for pushed IO */
432 #define XOTHER 0 /* none of the below */
433 #define XDOLL 1 /* expanding ${} */
434 #define XGRAVE 2 /* expanding `'s */
435 #define XIO 3 /* file IO */
439 * input generators for IO structure
441 static int nlchar(struct ioarg *ap);
442 static int strchar(struct ioarg *ap);
443 static int qstrchar(struct ioarg *ap);
444 static int filechar(struct ioarg *ap);
445 static int herechar(struct ioarg *ap);
446 static int linechar(struct ioarg *ap);
447 static int gravechar(struct ioarg *ap, struct io *iop);
448 static int qgravechar(struct ioarg *ap, struct io *iop);
449 static int dolchar(struct ioarg *ap);
450 static int wdchar(struct ioarg *ap);
451 static void scraphere(void);
452 static void freehere(int area);
453 static void gethere(void);
454 static void markhere(char *s, struct ioword *iop);
455 static int herein(char *hname, int xdoll);
456 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
459 static int eofc(void);
460 static int readc(void);
461 static void unget(int c);
462 static void ioecho(char c);
468 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
469 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
470 static int remap(int fd);
471 static int openpipe(int *pv);
472 static void closepipe(int *pv);
473 static struct io *setbase(struct io *ip);
475 /* -------- word.h -------- */
477 #define NSTART 16 /* default number of words to allow for initially */
482 /* bounds are arbitrary */
486 static struct wdblock *addword(char *wd, struct wdblock *wb);
487 static struct wdblock *newword(int nw);
488 static char **getwords(struct wdblock *wb);
490 /* -------- misc stuff -------- */
492 static int forkexec(struct op *t, int *pin, int *pout, int no_fork, char **wp);
493 static int execute(struct op *t, int *pin, int *pout, int no_fork);
494 static int iosetup(struct ioword *iop, int pipein, int pipeout);
495 static void brkset(struct brkcon *bc);
496 static int dolabel(struct op *t);
497 static int dohelp(struct op *t);
498 static int dochdir(struct op *t);
499 static int doshift(struct op *t);
500 static int dologin(struct op *t);
501 static int doumask(struct op *t);
502 static int doexec(struct op *t);
503 static int dodot(struct op *t);
504 static int dowait(struct op *t);
505 static int doread(struct op *t);
506 static int doeval(struct op *t);
507 static int dotrap(struct op *t);
508 static int getsig(char *s);
509 static void setsig(int n, sighandler_t f);
510 static int getn(char *as);
511 static int dobreak(struct op *t);
512 static int docontinue(struct op *t);
513 static int brkcontin(char *cp, int val);
514 static int doexit(struct op *t);
515 static int doexport(struct op *t);
516 static int doreadonly(struct op *t);
517 static void rdexp(char **wp, void (*f) (struct var *), int key);
518 static void badid(char *s);
519 static int doset(struct op *t);
520 static void varput(char *s, int out);
521 static int dotimes(struct op *t);
522 static int expand(const char *cp, struct wdblock **wbp, int f);
523 static char *blank(int f);
524 static int dollar(int quoted);
525 static int grave(int quoted);
526 static void globname(char *we, char *pp);
527 static char *generate(char *start1, char *end1, char *middle, char *end);
528 static int anyspcl(struct wdblock *wb);
529 static int xstrcmp(char *p1, char *p2);
530 static void glob0(char *a0, unsigned a1, int a2,
531 int (*a3) (char *, char *));
532 static void readhere(char **name, char *s, int ec);
533 static int xxchar(struct ioarg *ap);
538 struct ioword *h_iop;
542 static const char *const signame[] = {
545 NULL, /* interrupt */
547 "Illegal instruction",
551 "Floating Point Exception",
556 NULL, /* broken pipe */
562 typedef int (*builtin_func_ptr)(struct op *);
566 builtin_func_ptr builtinfunc;
569 static const struct builtincmd builtincmds[] = {
572 { "break" , dobreak },
574 { "continue", docontinue },
578 { "export" , doexport },
580 { "login" , dologin },
581 { "newgrp" , dologin },
583 { "readonly", doreadonly },
585 { "shift" , doshift },
586 { "times" , dotimes },
588 { "umask" , doumask },
593 static struct op *scantree(struct op *);
594 static struct op *dowholefile(int, int);
601 static smallint gflg; /* (seems to be a parse error indicator) */
602 static smallint interactive; /* Is this an interactive shell */
603 static smallint execflg;
604 static smallint isbreak; /* "break" statement was seen */
605 static int multiline; /* '\n' changed to ';' (counter) */
606 static struct op *outtree; /* result from parser */
609 static struct brkcon *brklist;
610 static struct wdblock *wdlist;
611 static struct wdblock *iolist;
614 static struct var *mshdbg_var;
616 static struct var *vlist; /* dictionary */
617 static struct var *homedir; /* home directory */
618 static struct var *prompt; /* main prompt */
619 static struct var *cprompt; /* continuation prompt */
620 static struct var *path; /* search path for commands */
621 static struct var *shell; /* shell to interpret command files */
622 static struct var *ifs; /* field separators */
624 static int areanum; /* current allocation area */
625 static smallint intr; /* interrupt pending (bool) */
626 static smallint heedint = 1; /* heed interrupt signals (bool) */
628 static char *null = (char*)""; /* null value for variable */
629 static void (*qflag)(int) = SIG_IGN;
633 static int iounit = IODEFAULT;
634 static YYSTYPE yylval;
635 static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
637 static struct here *inhere; /* list of hear docs while parsing */
638 static struct here *acthere; /* list of active here documents */
639 static struct region *areabot; /* bottom of area */
640 static struct region *areatop; /* top of area */
641 static struct region *areanxt; /* starting point of scan */
643 static void *brkaddr;
645 #define AFID_NOBUF (~0)
650 * parsing & execution environment
656 xint *errpt; /* void * */
663 struct env global_env;
664 struct ioarg temparg; // = { .afid = AFID_NOBUF }; /* temporary for PUSHIO */
665 unsigned bufid; // = AFID_ID; /* buffer id counter */
666 char ourtrap[_NSIG + 1];
667 char *trap[_NSIG + 1];
668 struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
669 struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
670 struct ioarg ioargstack[NPUSH];
674 * -k: look for name=value everywhere on command line
676 * -t: exit after reading and executing one command
679 * -u: unset variables net diagnostic
681 char flags['z' - 'a' + 1];
682 char filechar_cmdbuf[BUFSIZ];
684 char child_cmd[LINELIM];
686 struct io iostack[NPUSH];
688 char grave__var_name[LINELIM];
689 char grave__alt_value[LINELIM];
692 #define G (*ptr_to_globals)
693 #define global_env (G.global_env )
694 #define temparg (G.temparg )
695 #define bufid (G.bufid )
696 #define ourtrap (G.ourtrap )
697 #define trap (G.trap )
698 #define sharedbuf (G.sharedbuf )
699 #define mainbuf (G.mainbuf )
700 #define ioargstack (G.ioargstack )
701 /* this looks weird, but is OK ... we index FLAG with 'a'...'z' */
702 #define FLAG (G.flags - 'a' )
703 #define filechar_cmdbuf (G.filechar_cmdbuf)
704 #define line (G.line )
705 #define child_cmd (G.child_cmd )
706 #define iostack (G.iostack )
707 #define INIT_G() do { \
708 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
709 global_env.linep = line; \
710 global_env.iobase = iostack; \
711 global_env.iop = iostack - 1; \
712 global_env.iofd = FDBASE; \
713 temparg.afid = AFID_NOBUF; \
718 /* in substitution */
719 #define INSUB() (global_env.iop->task == XGRAVE || global_env.iop->task == XDOLL)
721 #define RUN(what, arg, gen) ((temparg.what = (arg)), run(&temparg, (gen)))
724 void print_t(struct op *t)
726 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
727 T_CMD_NAMES[t->type], t->words, t->ioact));
730 DBGPRINTF(("T: W1: %s", t->words[0]));
734 void print_tree(struct op *head)
737 DBGPRINTF(("PRINT_TREE: no tree\n"));
741 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
745 print_tree(head->left);
748 print_tree(head->right);
750 #endif /* MSHDEBUG */
756 static void prs(const char *s)
759 write(2, s, strlen(s));
762 static void prn(unsigned u)
767 static void echo(char **wp)
772 for (i = 0; wp[i]; i++) {
780 static void closef(int i)
786 static void closeall(void)
790 for (u = NUFILE; u < NOFILE;)
795 /* fail but return to process next command */
796 static void fail(void) ATTRIBUTE_NORETURN;
797 static void fail(void)
803 /* abort shell (or fail in subshell) */
804 static void leave(void) ATTRIBUTE_NORETURN;
805 static void leave(void)
807 DBGPRINTF(("LEAVE: leave called!\n"));
818 static void warn(const char *s)
829 static void err(const char *s)
836 if (global_env.errpt)
837 longjmp(global_env.errpt, 1);
839 global_env.iop = global_env.iobase = iostack;
843 /* -------- area.c -------- */
846 * All memory between (char *)areabot and (char *)(areatop+1) is
847 * exclusively administered by the area management routines.
848 * It is assumed that sbrk() and brk() manipulate the high end.
852 void * __q = (void *)-1; \
853 if (brkaddr + (int)(X) < brktop) { \
855 brkaddr += (int)(X); \
860 static void initarea(void)
862 brkaddr = xmalloc(AREASIZE);
863 brktop = brkaddr + AREASIZE;
865 while ((long) sbrk(0) & ALIGN)
867 areabot = (struct region *) sbrk(REGSIZE);
869 areabot->next = areabot;
870 areabot->area = BUSY;
875 static char *getcell(unsigned nbytes)
878 struct region *p, *q;
885 /* silly and defeats the algorithm */
887 * round upwards and add administration area
889 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
892 if (p->area > areanum) {
896 while ((q = p->next)->area > areanum && q != areanxt)
899 * exit loop if cell big enough
908 i = nregio >= GROWBY ? nregio : GROWBY;
909 p = (struct region *) sbrk(i * REGSIZE);
910 if (p == (struct region *) -1)
915 abort(); /* allocated areas are contiguous */
925 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
927 areanxt = p + nregio;
930 * split into requested area and rest
932 if (areanxt + 1 > q) {
934 abort(); /* insufficient space left for admin */
937 areanxt->area = FREE;
941 return (char *) (p + 1);
944 static void freecell(char *cp)
948 p = (struct region *) cp;
956 #define DELETE(obj) freecell((char *)obj)
958 static void freearea(int a)
960 struct region *p, *top;
963 for (p = areabot; p != top; p = p->next)
968 static void setarea(char *cp, int a)
972 p = (struct region *) cp;
977 static int getarea(char *cp)
979 return ((struct region *) cp - 1)->area;
982 static void garbage(void)
984 struct region *p, *q, *top;
987 for (p = areabot; p != top; p = p->next) {
988 if (p->area > areanum) {
989 while ((q = p->next)->area > areanum)
995 if (areatop >= q + SHRINKBY && q->area > areanum) {
996 brk((char *) (q + 1));
1004 static char *space(int n)
1010 err("out of string space");
1014 static char *strsave(const char *s, int a)
1018 cp = space(strlen(s) + 1);
1020 // FIXME: I highly doubt this is good.
1029 /* -------- var.c -------- */
1031 static int eqname(const char *n1, const char *n2)
1033 for (; *n1 != '=' && *n1 != '\0'; n1++)
1036 return *n2 == '\0' || *n2 == '=';
1039 static const char *findeq(const char *cp)
1041 while (*cp != '\0' && *cp != '=')
1047 * Find the given name in the dictionary
1048 * and return its value. If the name was
1049 * not previously there, enter it now and
1050 * return a null value.
1052 static struct var *lookup(const char *n)
1054 // FIXME: dirty hack
1055 static struct var dummy;
1063 dummy.name = (char*)n;
1064 for (c = 0; isdigit(*n) && c < 1000; n++)
1065 c = c * 10 + *n - '0';
1066 dummy.status = RONLY;
1067 dummy.value = (c <= dolc ? dolv[c] : null);
1071 for (vp = vlist; vp; vp = vp->next)
1072 if (eqname(vp->name, n))
1076 vp = (struct var *) space(sizeof(*vp));
1077 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1078 dummy.name = dummy.value = (char*)"";
1083 while ((*xp = *n++) != '\0' && *xp != '=')
1087 setarea((char *) vp, 0);
1088 setarea((char *) vp->name, 0);
1091 vp->status = GETCELL;
1097 * if name is not NULL, it must be
1098 * a prefix of the space `val',
1100 * this is all so that exporting
1101 * values is reasonably painless.
1103 static void nameval(struct var *vp, const char *val, const char *name)
1109 if (vp->status & RONLY) {
1111 while (*xp && *xp != '=')
1112 fputc(*xp++, stderr);
1113 err(" is read-only");
1118 xp = space(strlen(vp->name) + strlen(val) + 2);
1121 /* make string: name=value */
1125 while ((*xp = *cp++) != '\0' && *xp != '=')
1132 if (vp->status & GETCELL)
1133 freecell(vp->name); /* form new string `name=value' */
1134 vp->name = (char*)name;
1135 vp->value = (char*)val;
1140 * give variable at `vp' the value `val'.
1142 static void setval(struct var *vp, const char *val)
1144 nameval(vp, val, NULL);
1147 static void export(struct var *vp)
1149 vp->status |= EXPORT;
1152 static void ronly(struct var *vp)
1154 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1155 vp->status |= RONLY;
1158 static int isassign(const char *s)
1161 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1164 /* no isalpha() - we shouldn't use locale */
1165 /* c | 0x20 - lowercase (Latin) letters */
1166 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1177 && (unsigned)(c - '0') > 9 /* not number */
1178 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1185 static int assign(const char *s, int cf)
1190 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1192 if (!isalpha(*s) && *s != '_')
1194 for (cp = s; *cp != '='; cp++)
1195 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1198 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1200 vp->status &= ~GETCELL;
1204 static int checkname(char *cp)
1206 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1208 if (!isalpha(*cp++) && *(cp - 1) != '_')
1211 if (!isalnum(*cp++) && *(cp - 1) != '_')
1216 static void putvlist(int f, int out)
1220 for (vp = vlist; vp; vp = vp->next) {
1221 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1222 if (vp->status & EXPORT)
1223 write(out, "export ", 7);
1224 if (vp->status & RONLY)
1225 write(out, "readonly ", 9);
1226 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1227 write(out, "\n", 1);
1236 static void sig(int i)
1242 static void runtrap(int i)
1247 if (trapstr == NULL)
1253 RUN(aword, trapstr, nlchar);
1257 static void setdash(void)
1261 char m['z' - 'a' + 1];
1264 for (c = 'a'; c <= 'z'; c++)
1268 setval(lookup("-"), m);
1271 static int newfile(char *s)
1275 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1278 if (NOT_LONE_DASH(s)) {
1279 DBGPRINTF(("NEWFILE: s is %s\n", s));
1280 f = open(s, O_RDONLY);
1283 err(": cannot open");
1293 struct op *scantree(struct op *head)
1300 if (head->left != NULL) {
1301 dotnode = scantree(head->left);
1306 if (head->right != NULL) {
1307 dotnode = scantree(head->right);
1312 if (head->words == NULL)
1315 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1317 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1318 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1326 static void onecommand(void)
1331 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1333 while (global_env.oenv)
1342 global_env.errpt = 0;
1343 global_env.linep = line;
1351 setjmp(failpt); /* Bruce Evans' fix */
1353 if (setjmp(failpt) || yyparse() || intr) {
1354 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1356 while (global_env.oenv)
1359 if (!interactive && intr)
1372 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1374 execute(outtree, NOPIPE, NOPIPE, /* no_fork: */ 0);
1377 if (!interactive && intr) {
1389 static int newenv(int f)
1393 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1400 ep = (struct env *) space(sizeof(*ep));
1402 while (global_env.oenv)
1407 global_env.oenv = ep;
1408 global_env.errpt = errpt;
1413 static void quitenv(void)
1418 DBGPRINTF(("QUITENV: global_env.oenv=%p\n", global_env.oenv));
1420 ep = global_env.oenv;
1422 fd = global_env.iofd;
1424 /* should close `'d files */
1426 while (--fd >= global_env.iofd)
1432 * Is character c in s?
1434 static int any(int c, const char *s)
1443 * Is any character from s1 in s2?
1445 static int anys(const char *s1, const char *s2)
1453 static char *putn(int n)
1458 static void next(int f)
1460 PUSHIO(afile, f, filechar);
1463 static void onintr(int s) /* ANSI C requires a parameter */
1465 signal(SIGINT, onintr);
1472 } else if (heedint) {
1479 /* -------- gmatch.c -------- */
1481 * int gmatch(string, pattern)
1482 * char *string, *pattern;
1484 * Match a pattern as in sh(1).
1489 #define QMASK (CMASK & ~QUOTE)
1490 #define NOT '!' /* might use ^ */
1492 static const char *cclass(const char *p, int sub)
1494 int c, d, not, found;
1504 if (p[1] == '-' && p[2] != ']') {
1509 if (c == sub || (c <= sub && sub <= d))
1511 } while (*++p != ']');
1512 return found ? p + 1 : NULL;
1515 static int gmatch(const char *s, const char *p)
1519 if (s == NULL || p == NULL)
1522 while ((pc = *p++ & CMASK) != '\0') {
1539 if (*p == '\0' || gmatch(s, p))
1541 } while (*s++ != '\0');
1545 if (sc != (pc & ~QUOTE))
1553 /* -------- csyn.c -------- */
1555 * shell: syntax (C version)
1558 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1559 static void yyerror(const char *s)
1562 if (interactive && global_env.iop <= iostack) {
1564 while (eofc() == 0 && yylex(0) != '\n')
1571 static void zzerr(void) ATTRIBUTE_NORETURN;
1572 static void zzerr(void)
1574 yyerror("syntax error");
1579 DBGPRINTF7(("YYPARSE: enter...\n"));
1586 return yynerrs; /* 0/1 */
1589 static struct op *pipeline(int cf)
1594 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1598 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1601 while ((c = yylex(0)) == '|') {
1602 p = command(CONTIN);
1604 DBGPRINTF8(("PIPELINE: error!\n"));
1608 if (t->type != TPAREN && t->type != TCOM) {
1609 /* shell statement */
1610 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1613 t = block(TPIPE, t, p, NOWORDS);
1618 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1622 static struct op *andor(void)
1627 DBGPRINTF7(("ANDOR: enter...\n"));
1631 DBGPRINTF9(("ANDOR: t=%p\n", t));
1634 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1635 p = pipeline(CONTIN);
1637 DBGPRINTF8(("ANDOR: error!\n"));
1641 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1647 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1651 static struct op *c_list(void)
1656 DBGPRINTF7(("C_LIST: enter...\n"));
1663 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1665 while ((c = yylex(0)) == ';' || c == '&'
1666 || (multiline && c == '\n')) {
1674 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1682 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1686 static int synio(int cf)
1692 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1695 if (c != '<' && c != '>') {
1702 iop = io(iounit, i, yylval.cp);
1706 markhere(yylval.cp, iop);
1708 DBGPRINTF7(("SYNIO: returning 1\n"));
1712 static void musthave(int c, int cf)
1714 peeksym = yylex(cf);
1716 DBGPRINTF7(("MUSTHAVE: error!\n"));
1723 static struct op *simple(void)
1729 switch (peeksym = yylex(0)) {
1750 static struct op *nested(int type, int mark)
1754 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1760 return block(type, t, NOBLOCK, NOWORDS);
1763 static struct op *command(int cf)
1766 struct wdblock *iosave;
1769 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1795 t = nested(TPAREN, ')');
1799 t = nested(TBRACE, '}');
1809 t->words = wordlist();
1811 if (c != '\n' && c != ';')
1813 t->left = dogroup(0);
1821 t->type = (c == WHILE ? TWHILE : TUNTIL);
1823 t->right = dogroup(1);
1835 musthave(IN, CONTIN);
1838 t->left = caselist();
1849 t->right = thenpart();
1858 musthave(WORD, 0); /* gets name of file */
1859 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1861 word(yylval.cp); /* add word to wdlist */
1862 word(NOWORD); /* terminate wdlist */
1863 t->words = copyw(); /* dup wdlist */
1873 DBGPRINTF(("COMMAND: returning %p\n", t));
1878 static struct op *dowholefile(int type, int mark)
1882 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1887 t = block(type, t, NOBLOCK, NOWORDS);
1888 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1892 static struct op *dogroup(int onlydone)
1898 if (c == DONE && onlydone)
1907 static struct op *thenpart(void)
1918 /*t->type = 0; - newtp() did this */
1920 if (t->left == NULL)
1922 t->right = elsepart();
1926 static struct op *elsepart(void)
1931 switch (c = yylex(0)) {
1942 t->right = thenpart();
1951 static struct op *caselist(void)
1956 while ((peeksym = yylex(CONTIN)) != ESAC) {
1957 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1958 t = list(t, casepart());
1961 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1965 static struct op *casepart(void)
1969 DBGPRINTF7(("CASEPART: enter...\n"));
1973 t->words = pattern();
1976 peeksym = yylex(CONTIN);
1977 if (peeksym != ESAC)
1978 musthave(BREAK, CONTIN);
1980 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
1985 static char **pattern(void)
2002 static char **wordlist(void)
2012 while ((c = yylex(0)) == WORD)
2020 * supporting functions
2022 static struct op *list(struct op *t1, struct op *t2)
2024 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2031 return block(TLIST, t1, t2, NOWORDS);
2034 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2038 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2046 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1, t2));
2051 /* See if given string is a shell multiline (FOR, IF, etc) */
2052 static int rlookup(char *n)
2058 static const struct res restab[] = {
2081 const struct res *rp;
2083 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2085 for (rp = restab; rp->r_name[0]; rp++)
2086 if (strcmp(rp->r_name, n) == 0) {
2087 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2088 return rp->r_val; /* Return numeric code for shell multiline */
2091 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2092 return 0; /* Not a shell multiline */
2095 static struct op *newtp(void)
2099 t = (struct op *) tree(sizeof(*t));
2100 memset(t, 0, sizeof(*t));
2102 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2107 static struct op *namelist(struct op *t)
2109 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2110 T_CMD_NAMES[t->type], iolist));
2113 iolist = addword((char *) NULL, iolist);
2114 t->ioact = copyio();
2118 if (t->type != TCOM) {
2119 if (t->type != TPAREN && t->ioact != NULL) {
2120 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2121 t->ioact = t->left->ioact;
2122 t->left->ioact = NULL;
2133 static char **copyw(void)
2137 wd = getwords(wdlist);
2142 static void word(char *cp)
2144 wdlist = addword(cp, wdlist);
2147 static struct ioword **copyio(void)
2149 struct ioword **iop;
2151 iop = (struct ioword **) getwords(iolist);
2156 static struct ioword *io(int u, int f, char *cp)
2160 iop = (struct ioword *) tree(sizeof(*iop));
2164 iolist = addword((char *) iop, iolist);
2168 static int yylex(int cf)
2185 global_env.linep = line;
2188 line[LINELIM - 1] = '\0';
2191 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2196 if (any(c, "0123456789")) {
2199 if (c1 == '<' || c1 == '>') {
2203 *global_env.linep++ = c;
2208 case '#': /* Comment, skip to next newline or End-of-string */
2209 while ((c = my_getc(0)) != '\0' && c != '\n');
2214 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2218 DBGPRINTF9(("YYLEX: found $\n"));
2219 *global_env.linep++ = c;
2222 c = collect(c, '}');
2241 /* If more chars process them, else return NULL char */
2259 if (multiline || cf & CONTIN) {
2260 if (interactive && global_env.iop <= iostack) {
2261 #if ENABLE_FEATURE_EDITING
2262 current_prompt = cprompt->value;
2264 prs(cprompt->value);
2281 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2282 if (global_env.linep >= elinep)
2283 err("word too long");
2285 *global_env.linep++ = c;
2290 if (any(c, "\"'`$"))
2293 *global_env.linep++ = '\0';
2303 yylval.cp = strsave(line, areanum);
2308 static int collect(int c, int c1)
2312 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2314 *global_env.linep++ = c;
2315 while ((c = my_getc(c1)) != c1) {
2324 if (interactive && c == '\n' && global_env.iop <= iostack) {
2325 #if ENABLE_FEATURE_EDITING
2326 current_prompt = cprompt->value;
2328 prs(cprompt->value);
2331 *global_env.linep++ = c;
2334 *global_env.linep++ = c;
2336 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2341 /* "multiline commands" helper func */
2342 /* see if next 2 chars form a shell multiline */
2343 static int dual(int c)
2348 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2350 *cp++ = c; /* c is the given "peek" char */
2351 *cp++ = my_getc(0); /* get next char of input */
2352 *cp = '\0'; /* add EOS marker */
2354 c = rlookup(s); /* see if 2 chars form a shell multiline */
2356 unget(*--cp); /* String is not a shell multiline, put peek char back */
2358 return c; /* String is multiline, return numeric multiline (restab) code */
2361 static void diag(int ec)
2365 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2368 if (c == '>' || c == '<') {
2371 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2374 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2375 if (c != '&' || yylval.i == IOHERE)
2381 static char *tree(unsigned size)
2387 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2388 prs("command line too complicated\n");
2399 /* -------- exec.c -------- */
2401 static struct op **find1case(struct op *t, const char *w)
2409 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2413 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2414 T_CMD_NAMES[t->type]));
2416 if (t->type == TLIST) {
2417 tp = find1case(t->left, w);
2419 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2422 t1 = t->right; /* TPAT */
2426 for (wp = t1->words; *wp;) {
2427 cp = evalstr(*wp++, DOSUB);
2428 if (cp && gmatch(w, cp)) {
2429 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2435 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2439 static struct op *findcase(struct op *t, const char *w)
2443 tp = find1case(t, w);
2444 return tp != NULL ? *tp : NULL;
2451 static int execute(struct op *t, int *pin, int *pout, int no_fork)
2454 volatile int i, rv, a;
2458 struct op *outtree_save;
2462 /* Avoid longjmp clobbering */
2467 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2471 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2472 t->type, T_CMD_NAMES[t->type],
2473 ((t->words == NULL) ? "NULL" : t->words[0])));
2479 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2484 DBGPRINTF3(("EXECUTE: TDOT\n"));
2486 outtree_save = outtree;
2488 newfile(evalstr(t->words[0], DOALL));
2490 t->left = dowholefile(TLIST, 0);
2493 outtree = outtree_save;
2496 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2498 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2502 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2506 rv = forkexec(t, pin, pout, no_fork, wp);
2516 pv[0] = remap(pv[0]);
2517 pv[1] = remap(pv[1]);
2518 (void) execute(t->left, pin, pv, /* no_fork: */ 0);
2519 rv = execute(t->right, pv, pout, /* no_fork: */ 0);
2524 (void) execute(t->left, pin, pout, /* no_fork: */ 0);
2525 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2530 smallint hinteractive = interactive;
2532 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2535 if (i == 0) { /* child */
2536 signal(SIGINT, SIG_IGN);
2537 signal(SIGQUIT, SIG_IGN);
2539 signal(SIGTERM, SIG_DFL);
2543 xopen(bb_dev_null, O_RDONLY);
2545 _exit(execute(t->left, pin, pout, /* no_fork: */ 1));
2547 interactive = hinteractive;
2549 setval(lookup("!"), putn(i));
2563 rv = execute(t->left, pin, pout, /* no_fork: */ 0);
2565 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2566 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2577 while (*wp++ != NULL);
2579 vp = lookup(t->str);
2580 while (setjmp(bc.brkpt))
2584 for (t1 = t->left; i-- && *wp != NULL;) {
2586 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2588 brklist = brklist->nextlev;
2593 while (setjmp(bc.brkpt))
2598 while ((execute(t1, pin, pout, /* no_fork: */ 0) == 0) == (t->type == TWHILE))
2599 rv = execute(t->right, pin, pout, /* no_fork: */ 0);
2600 brklist = brklist->nextlev;
2605 if (t->right != NULL) {
2606 rv = !execute(t->left, pin, pout, /* no_fork: */ 0) ?
2607 execute(t->right->left, pin, pout, /* no_fork: */ 0) :
2608 execute(t->right->right, pin, pout, /* no_fork: */ 0);
2613 cp = evalstr(t->str, DOSUB | DOTRIM);
2617 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2618 ((t->str == NULL) ? "NULL" : t->str),
2619 ((cp == NULL) ? "NULL" : cp)));
2621 t1 = findcase(t->left, cp);
2623 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2624 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2625 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2634 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2642 rv = execute(t1, pin, pout, /* no_fork: */ 0);
2655 if (interactive && intr) {
2666 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2670 static builtin_func_ptr inbuilt(const char *s)
2672 const struct builtincmd *bp;
2674 for (bp = builtincmds; bp->name; bp++)
2675 if (strcmp(bp->name, s) == 0)
2676 return bp->builtinfunc;
2680 static int forkexec(struct op *t, int *pin, int *pout, int no_fork, char **wp)
2684 builtin_func_ptr bltin = NULL;
2685 const char *bltin_name = NULL;
2687 struct ioword **iopp;
2695 smallint hinteractive;
2698 struct brkcon *hbrklist;
2701 /* Avoid longjmp clobbering */
2711 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, no_fork %d\n", t, pin,
2713 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2714 ((t->words == NULL) ? "NULL" : t->words[0])));
2717 if (t->type == TCOM) {
2718 while (*wp++ != NULL)
2722 /* strip all initial assignments */
2723 /* FIXME: not correct wrt PATH=yyy command etc */
2725 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2727 echo(cp ? wp : owp);
2731 if (t->ioact == NULL) {
2732 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2734 DBGPRINTF(("FORKEXEC: returning setstatus(0)\n"));
2735 return setstatus(0);
2737 } else { /* cp != NULL */
2739 bltin = inbuilt(cp);
2745 DBGPRINTF(("FORKEXEC: bltin %p, no_fork %d, owp %p\n", bltin,
2747 /* Don't fork if it is a lone builtin (not in pipe)
2748 * OR we are told to _not_ fork */
2749 if ((!bltin || pin || pout) /* not lone bltin AND */
2750 && !no_fork /* not told to avoid fork */
2752 /* Save values in case child alters them after vfork */
2756 hinteractive = interactive;
2761 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2764 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2768 if (newpid > 0) { /* Parent */
2769 /* Restore values */
2773 interactive = hinteractive;
2779 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2783 DBGPRINTF(("FORKEXEC: child process, bltin=%p (%s)\n", bltin, bltin_name));
2785 signal(SIGINT, SIG_IGN);
2786 signal(SIGQUIT, SIG_IGN);
2797 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2801 if (pin) { /* NB: close _first_, then move fds! */
2803 xmove_fd(pin[0], 0);
2807 xmove_fd(pout[1], 1);
2812 if (bltin && bltin != doexec) {
2814 err(": cannot redirect shell command");
2820 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2821 /* system-detected error */
2830 if (forked || pin || pout) {
2831 /* Builtin in pipe: disallowed */
2832 /* TODO: allow "exec"? */
2834 err(": cannot run builtin as part of pipe");
2839 i = setstatus(bltin(t));
2842 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2846 /* should use FIOCEXCL */
2847 for (i = FDBASE; i < NOFILE; i++)
2850 signal(SIGINT, SIG_DFL);
2851 signal(SIGQUIT, SIG_DFL);
2854 if (t->type == TPAREN)
2855 _exit(execute(t->left, NOPIPE, NOPIPE, /* no_fork: */ 1));
2859 cp = rexecve(wp[0], wp, makenv(0, NULL));
2866 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", getpid()));
2874 * 0< 1> are ignored as required
2877 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2883 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2886 if (iop->io_unit == IODEFAULT) /* take default */
2887 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2889 if (pipein && iop->io_unit == 0)
2892 if (pipeout && iop->io_unit == 1)
2895 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2896 if ((iop->io_flag & IOHERE) == 0) {
2897 cp = iop->io_name; /* huh?? */
2898 cp = evalstr(cp, DOSUB | DOTRIM);
2903 if (iop->io_flag & IODUP) {
2904 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2906 err(": illegal >& argument");
2910 iop->io_flag = IOCLOSE;
2911 iop->io_flag &= ~(IOREAD | IOWRITE);
2914 switch (iop->io_flag) {
2916 u = open(cp, O_RDONLY);
2920 case IOHERE | IOXHERE:
2921 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2922 cp = (char*)"here file";
2925 case IOWRITE | IOCAT:
2926 u = open(cp, O_WRONLY);
2928 lseek(u, (long) 0, SEEK_END);
2931 /* fall through to creation if >>file doesn't exist */
2934 u = creat(cp, 0666);
2938 u = dup2(*cp - '0', iop->io_unit);
2942 close(iop->io_unit);
2952 if (u != iop->io_unit) {
2953 dup2(u, iop->io_unit);
2960 * Enter a new loop level (marked for break/continue).
2962 static void brkset(struct brkcon *bc)
2964 bc->nextlev = brklist;
2969 * Wait for the last process created.
2970 * Print a message for each process found
2971 * that was killed by a signal.
2972 * Ignore interrupt signals while waiting
2973 * unless `canintr' is true.
2975 static int waitfor(int lastpid, int canintr)
2979 smallint oheedint = heedint;
2986 if (errno != EINTR || canintr)
2991 if (rv < ARRAY_SIZE(signame)) {
2992 if (signame[rv] != NULL) {
2993 if (pid != lastpid) {
3000 if (pid != lastpid) {
3009 prs(" - core dumped");
3010 if (rv >= ARRAY_SIZE(signame) || signame[rv])
3016 } while (pid != lastpid);
3031 static int setstatus(int s)
3034 setval(lookup("?"), putn(s));
3039 * PATH-searching interface to execve.
3040 * If getenv("PATH") were kept up-to-date,
3041 * execvp might be used.
3043 static const char *rexecve(char *c, char **v, char **envp)
3051 if (ENABLE_FEATURE_SH_STANDALONE) {
3052 if (find_applet_by_name(name) >= 0) {
3053 /* We have to exec here since we vforked. Running
3054 * run_applet_and_exit() won't work and bad things
3056 execve(bb_busybox_exec_path, v, envp);
3060 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3062 sp = any('/', c) ? "" : path->value;
3063 asis = (*sp == '\0');
3064 while (asis || *sp != '\0') {
3066 tp = global_env.linep;
3067 for (; *sp != '\0'; tp++) {
3070 asis = (*sp == '\0');
3074 if (tp != global_env.linep)
3076 for (i = 0; (*tp++ = c[i++]) != '\0';);
3078 DBGPRINTF3(("REXECVE: global_env.linep is %s\n", global_env.linep));
3080 execve(global_env.linep, v, envp);
3084 *v = global_env.linep;
3086 *v = global_env.linep;
3087 execve(DEFAULT_SHELL, v, envp);
3092 return (char *) bb_msg_memory_exhausted;
3095 return "argument list too long";
3098 return errno == ENOENT ? "not found" : "cannot execute";
3102 * Run the command produced by generator `f'
3103 * applied to stream `arg'.
3105 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3108 struct wdblock *swdlist;
3109 struct wdblock *siolist;
3115 /* Avoid longjmp clobbering */
3119 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3120 areanum, outtree, failpt));
3130 if (newenv(setjmp(errpt)) == 0) {
3134 global_env.iobase = global_env.iop;
3137 if (setjmp(failpt) == 0 && yyparse() == 0)
3138 rv = execute(outtree, NOPIPE, NOPIPE, /* no_fork: */ 0);
3141 DBGPRINTF(("RUN: error from newenv()!\n"));
3148 freearea(areanum--);
3153 /* -------- do.c -------- */
3156 * built-in commands: doX
3159 static int dohelp(struct op *t)
3162 const struct builtincmd *x;
3164 puts("\nBuilt-in commands:\n"
3165 "-------------------");
3170 col += printf("%c%s", ((col == 0) ? '\t' : ' '), x->name);
3177 #if ENABLE_FEATURE_SH_STANDALONE
3179 const char *applet = applet_names;
3182 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applet);
3187 applet += strlen(applet) + 1;
3192 return EXIT_SUCCESS;
3195 static int dolabel(struct op *t)
3200 static int dochdir(struct op *t)
3202 const char *cp, *er;
3206 cp = homedir->value;
3209 er = ": no home directory";
3214 er = ": bad directory";
3216 prs(cp != NULL ? cp : "cd");
3221 static int doshift(struct op *t)
3225 n = t->words[1] ? getn(t->words[1]) : 1;
3227 err("nothing to shift");
3233 setval(lookup("#"), putn(dolc));
3238 * execute login and newgrp directly
3240 static int dologin(struct op *t)
3245 signal(SIGINT, SIG_DFL);
3246 signal(SIGQUIT, SIG_DFL);
3248 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3255 static int doumask(struct op *t)
3264 printf("%04o\n", i);
3266 i = bb_strtou(cp, NULL, 8);
3268 err("umask: bad octal number");
3276 static int doexec(struct op *t)
3283 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++)
3290 if (setjmp(failpt) == 0)
3291 execute(t, NOPIPE, NOPIPE, /* no_fork: */ 1);
3297 static int dodot(struct op *t)
3305 DBGPRINTF(("DODOT: enter, t=%p, tleft %p, tright %p, global_env.linep is %s\n",
3306 t, t->left, t->right, ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3310 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3313 DBGPRINTF(("DODOT: cp is %s\n", cp));
3315 sp = any('/', cp) ? ":" : path->value;
3317 DBGPRINTF(("DODOT: sp is %s, global_env.linep is %s\n",
3318 ((sp == NULL) ? "NULL" : sp),
3319 ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3322 tp = global_env.linep;
3323 while (*sp && (*tp = *sp++) != ':')
3325 if (tp != global_env.linep)
3328 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3331 i = open(global_env.linep, O_RDONLY);
3335 DBGPRINTF(("DODOT: remap=%d, exstat=%d, global_env.iofd %d, i %d, global_env.linep is %s\n",
3336 maltmp, exstat, global_env.iofd, i, global_env.linep));
3338 next(maltmp); /* Basically a PUSHIO */
3340 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3352 static int dowait(struct op *t)
3364 setstatus(waitfor(i, 1));
3368 static int doread(struct op *t)
3374 if (t->words[1] == NULL) {
3375 err("Usage: read name ...");
3378 for (wp = t->words + 1; *wp; wp++) {
3379 for (cp = global_env.linep; !nl && cp < elinep - 1; cp++) {
3380 nb = nonblock_safe_read(0, cp, sizeof(*cp));
3381 if (nb != sizeof(*cp))
3384 if (nl || (wp[1] && any(*cp, ifs->value)))
3390 setval(lookup(*wp), global_env.linep);
3395 static int doeval(struct op *t)
3397 return RUN(awordlist, t->words + 1, wdchar);
3400 static int dotrap(struct op *t)
3405 if (t->words[1] == NULL) {
3406 for (i = 0; i <= _NSIG; i++)
3415 resetsig = isdigit(*t->words[1]);
3416 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3417 n = getsig(t->words[i]);
3421 if (*t->words[1] != '\0') {
3422 trap[n] = strsave(t->words[1], 0);
3431 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3439 static int getsig(char *s)
3444 if (n < 0 || n > _NSIG) {
3445 err("trap: bad signal number");
3451 static void setsig(int n, sighandler_t f)
3455 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3461 static int getn(char *as)
3472 for (n = 0; isdigit(*s); s++)
3473 n = (n * 10) + (*s - '0');
3476 err(": bad number");
3481 static int dobreak(struct op *t)
3483 return brkcontin(t->words[1], 1);
3486 static int docontinue(struct op *t)
3488 return brkcontin(t->words[1], 0);
3491 static int brkcontin(char *cp, int val)
3496 nl = cp == NULL ? 1 : getn(cp);
3503 brklist = bc->nextlev;
3506 err("bad break/continue level");
3509 isbreak = (val != 0);
3510 longjmp(bc->brkpt, 1);
3514 static int doexit(struct op *t)
3521 setstatus(getn(cp));
3523 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3530 static int doexport(struct op *t)
3532 rdexp(t->words + 1, export, EXPORT);
3536 static int doreadonly(struct op *t)
3538 rdexp(t->words + 1, ronly, RONLY);
3542 static void rdexp(char **wp, void (*f) (struct var *), int key)
3544 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3545 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3548 for (; *wp != NULL; wp++) {
3549 if (isassign(*wp)) {
3553 for (cp = *wp; *cp != '='; cp++);
3565 static void badid(char *s)
3568 err(": bad identifier");
3571 static int doset(struct op *t)
3579 for (vp = vlist; vp; vp = vp->next)
3580 varput(vp->name, 1);
3584 /* bad: t->words++; */
3585 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3587 FLAG['x'] = FLAG['v'] = 0;
3597 if (*cp >= 'a' && *cp <= 'z')
3606 t->words[0] = dolv[0];
3607 for (n = 1; t->words[n]; n++)
3608 setarea((char *) t->words[n], 0);
3611 setval(lookup("#"), putn(dolc));
3612 setarea((char *) (dolv - 1), 0);
3617 static void varput(char *s, int out)
3619 if (isalnum(*s) || *s == '_') {
3620 write(out, s, strlen(s));
3621 write(out, "\n", 1);
3627 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3628 * This file contains code for the times builtin.
3630 static int dotimes(struct op *t)
3633 long clk_tck = sysconf(_SC_CLK_TCK);
3636 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3637 (int) (buf.tms_utime / clk_tck / 60),
3638 ((double) buf.tms_utime) / clk_tck,
3639 (int) (buf.tms_stime / clk_tck / 60),
3640 ((double) buf.tms_stime) / clk_tck,
3641 (int) (buf.tms_cutime / clk_tck / 60),
3642 ((double) buf.tms_cutime) / clk_tck,
3643 (int) (buf.tms_cstime / clk_tck / 60),
3644 ((double) buf.tms_cstime) / clk_tck);
3649 /* -------- eval.c -------- */
3654 * blank interpretation
3659 static char **eval(char **ap, int f)
3667 /* Avoid longjmp clobbering */
3672 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3678 if (newenv(setjmp(errpt)) == 0) {
3679 while (*ap && isassign(*ap))
3680 expand(*ap++, &wb, f & ~DOGLOB);
3682 for (wf = ap; *wf; wf++) {
3684 expand(*wf, &wb, f & ~DOGLOB);
3687 for (wb = addword((char *) NULL, wb); *ap; ap++) {
3688 if (!FLAG['k'] || !isassign(*ap))
3689 expand(*ap, &wb, f & ~DOKEY);
3691 wb = addword((char *) 0, wb);
3697 return gflg ? (char **) NULL : wp;
3702 * Make the exported environment from the exported
3703 * names in the dictionary. Keyword assignments
3704 * will already have been done.
3706 static char **makenv(int all, struct wdblock *wb)
3710 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3712 for (vp = vlist; vp; vp = vp->next)
3713 if (all || vp->status & EXPORT)
3714 wb = addword(vp->name, wb);
3715 wb = addword((char *) 0, wb);
3716 return getwords(wb);
3719 static int expand(const char *cp, struct wdblock **wbp, int f)
3725 /* Avoid longjmp clobbering */
3729 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3736 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3737 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3739 xp = strsave(cp, areanum);
3742 *wbp = addword(xp, *wbp);
3746 if (newenv(setjmp(errpt)) == 0) {
3747 PUSHIO(aword, cp, strchar);
3748 global_env.iobase = global_env.iop;
3749 while ((xp = blank(f)) && gflg == 0) {
3750 global_env.linep = xp;
3751 xp = strsave(xp, areanum);
3752 if ((f & DOGLOB) == 0) {
3755 *wbp = addword(xp, *wbp);
3757 *wbp = glob(xp, *wbp);
3765 static char *evalstr(char *cp, int f)
3769 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3772 if (expand(cp, &wb, f)) {
3773 if (wb == NULL || wb->w_nword == 0
3774 || (cp = wb->w_words[0]) == NULL
3776 // TODO: I suspect that
3777 // char *evalstr(char *cp, int f) is actually
3778 // const char *evalstr(const char *cp, int f)!
3789 * Blank interpretation and quoting
3791 static char *blank(int f)
3795 int scanequals, foundequals;
3797 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3799 sp = global_env.linep;
3800 scanequals = f & DOKEY;
3804 c = subgetc('"', foundequals);
3807 if (sp == global_env.linep)
3809 *global_env.linep++ = 0;
3813 if (f & DOBLANK && any(c, ifs->value))
3822 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3825 if (c == '\'' || !any(c, "$`\""))
3827 *global_env.linep++ = c;
3832 if (!isalpha(c) && c != '_')
3835 c = subgetc('"', foundequals);
3837 f & (DOBLANK && any(c, ifs->value)) ||
3838 (!INSUB() && any(c, "\"'"))) {
3849 } else if (!isalnum(c) && c != '_')
3852 *global_env.linep++ = c;
3854 *global_env.linep++ = 0;
3859 * Get characters, substituting for ` and $
3861 static int subgetc(char ec, int quoted)
3865 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3869 if (!INSUB() && ec != '\'') {
3871 if (grave(quoted) == 0)
3873 global_env.iop->task = XGRAVE;
3879 global_env.iop->task = XDOLL;
3888 * Prepare to generate the string returned by ${} substitution.
3890 static int dollar(int quoted)
3895 char *s, c, *cp = NULL;
3898 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3901 s = global_env.linep;
3903 *global_env.linep++ = c;
3904 if (isalpha(c) || c == '_') {
3905 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3906 if (global_env.linep < elinep)
3907 *global_env.linep++ = c;
3912 oiop = global_env.iop;
3913 otask = global_env.iop->task;
3915 global_env.iop->task = XOTHER;
3916 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3917 if (global_env.linep < elinep)
3918 *global_env.linep++ = c;
3919 if (oiop == global_env.iop)
3920 global_env.iop->task = otask;
3927 if (global_env.linep >= elinep) {
3928 err("string in ${} too long");
3930 global_env.linep -= 10;
3932 *global_env.linep = 0;
3934 for (cp = s + 1; *cp; cp++)
3935 if (any(*cp, "=-+?")) {
3940 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3942 /* currently this does not distinguish $* and $@ */
3943 /* should check dollar */
3944 global_env.linep = s;
3945 PUSHIO(awordlist, dolv + 1, dolchar);
3947 } else { /* trap the nasty ${=} */
3958 err("cannot use ${...=...} with $n");
3967 dolp = strsave(cp, areanum);
3972 prs("missing value for ");
3979 } else if (c == '+')
3980 dolp = strsave(cp, areanum);
3981 if (FLAG['u'] && dolp == null) {
3982 prs("unset variable: ");
3986 global_env.linep = s;
3987 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
3992 * Run the command in `...` and read its output.
3995 static int grave(int quoted)
3997 /* moved to G: static char child_cmd[LINELIM]; */
4008 char *argument_list[4];
4009 struct wdblock *wb = NULL;
4012 /* Avoid longjmp clobbering */
4016 for (cp = global_env.iop->argp->aword; *cp != '`'; cp++) {
4018 err("no closing `");
4023 /* string copy with dollar expansion */
4024 src = global_env.iop->argp->aword;
4029 while ((*src != '`') && (count < LINELIM)) {
4034 if (*src == '$' && !ignore && !ignore_once) {
4036 /* moved to G to reduce stack usage
4037 char var_name[LINELIM];
4038 char alt_value[LINELIM];
4040 #define var_name (G.grave__var_name)
4041 #define alt_value (G.grave__alt_value)
4054 var_name[var_index++] = *src++;
4055 while (isalnum(*src) || *src=='_')
4056 var_name[var_index++] = *src++;
4057 var_name[var_index] = 0;
4070 err("unclosed ${\n");
4075 while (*src && (*src != '}')) {
4076 alt_value[alt_index++] = *src++;
4078 alt_value[alt_index] = 0;
4080 err("unclosed ${\n");
4087 if (isalpha(*var_name)) {
4088 /* let subshell handle it instead */
4090 char *namep = var_name;
4098 char *altp = alt_value;
4106 wb = addword(lookup(var_name)->name, wb);
4110 vp = lookup(var_name);
4111 if (vp->value != null)
4112 value = (operator == '+') ?
4113 alt_value : vp->value;
4114 else if (operator == '?') {
4117 } else if (alt_index && (operator != '+')) {
4119 if (operator == '=')
4124 while (*value && (count < LINELIM)) {
4139 if (openpipe(pf) < 0)
4142 while ((i = vfork()) == -1 && errno == EAGAIN);
4144 DBGPRINTF3(("GRAVE: i is %p\n", io));
4148 err((char *) bb_msg_memory_exhausted);
4152 waitpid(i, NULL, 0); // safe_waitpid?
4153 global_env.iop->argp->aword = ++cp;
4155 PUSHIO(afile, remap(pf[0]),
4156 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4159 /* allow trapped signals */
4160 /* XXX - Maybe this signal stuff should go as well? */
4161 for (j = 0; j <= _NSIG; j++)
4162 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4165 /* Testcase where below checks are needed:
4166 * close stdout & run this script:
4174 argument_list[0] = (char *) DEFAULT_SHELL;
4175 argument_list[1] = (char *) "-c";
4176 argument_list[2] = child_cmd;
4177 argument_list[3] = NULL;
4179 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4180 prs(argument_list[0]);
4187 static char *unquote(char *as)
4198 /* -------- glob.c -------- */
4204 #define scopy(x) strsave((x), areanum)
4206 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4208 static struct wdblock *cl, *nl;
4209 static const char spcl[] ALIGN1= "[?*";
4211 static struct wdblock *glob(char *cp, struct wdblock *wb)
4219 for (pp = cp; *pp; pp++)
4222 else if (!any(*pp & ~QUOTE, spcl))
4225 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4226 nl = newword(cl->w_nword * 2);
4227 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4228 for (pp = cl->w_words[i]; *pp; pp++)
4229 if (any(*pp, spcl)) {
4230 globname(cl->w_words[i], pp);
4234 nl = addword(scopy(cl->w_words[i]), nl);
4236 for (i = 0; i < cl->w_nword; i++)
4237 DELETE(cl->w_words[i]);
4240 for (i = 0; i < cl->w_nword; i++)
4241 unquote(cl->w_words[i]);
4242 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4244 for (i = 0; i < cl->w_nword; i++)
4245 wb = addword(cl->w_words[i], wb);
4250 wb = addword(unquote(cp), wb);
4254 static void globname(char *we, char *pp)
4257 char *name, *gp, *dp;
4261 char dname[NAME_MAX + 1];
4264 for (np = we; np != pp; pp--)
4267 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4271 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4280 dname[NAME_MAX] = '\0';
4281 while ((de = readdir(dirp)) != NULL) {
4282 /* XXX Hmmm... What this could be? (abial) */
4284 if (ent[j].d_ino == 0)
4287 strncpy(dname, de->d_name, NAME_MAX);
4288 if (dname[0] == '.')
4291 for (k = 0; k < NAME_MAX; k++)
4292 if (any(dname[k], spcl))
4294 if (gmatch(dname, gp)) {
4295 name = generate(we, pp, dname, np);
4296 if (*np && !anys(np, spcl)) {
4297 if (stat(name, &dbuf)) {
4302 nl = addword(name, nl);
4311 * generate a pathname as below.
4312 * start..end1 / middle end
4313 * the slashes come for free
4315 static char *generate(char *start1, char *end1, char *middle, char *end)
4320 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4321 for (xp = start1; xp != end1;)
4323 for (xp = middle; (*op++ = *xp++) != '\0';);
4325 for (xp = end; (*op++ = *xp++) != '\0';);
4329 static int anyspcl(struct wdblock *wb)
4335 for (i = 0; i < wb->w_nword; i++)
4336 if (anys(spcl, *wd++))
4341 static int xstrcmp(char *p1, char *p2)
4343 return strcmp(*(char **) p1, *(char **) p2);
4347 /* -------- word.c -------- */
4349 static struct wdblock *newword(int nw)
4353 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4359 static struct wdblock *addword(char *wd, struct wdblock *wb)
4361 struct wdblock *wb2;
4365 wb = newword(NSTART);
4367 if (nw >= wb->w_bsize) {
4368 wb2 = newword(nw * 2);
4369 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4370 nw * sizeof(char *));
4375 wb->w_words[wb->w_nword++] = wd;
4379 static char **getwords(struct wdblock *wb)
4386 if (wb->w_nword == 0) {
4390 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4391 memcpy((char *) wd, (char *) wb->w_words, nb);
4392 DELETE(wb); /* perhaps should done by caller */
4396 static int (*func) (char *, char *);
4399 static void glob3(char *i, char *j, char *k)
4401 char *index1, *index2, *index3;
4411 *index1++ = *index3;
4412 *index3++ = *index2;
4417 static void glob2(char *i, char *j)
4419 char *index1, *index2, c;
4427 *index1++ = *index2;
4432 static void glob1(char *base, char *lim)
4443 n = (int) (lim - base);
4446 n = v2 * (n / (2 * v2));
4447 hptr = lptr = base + n;
4452 c = (*func) (i, lptr);
4466 c = (*func) (hptr, j);
4490 if (lptr - base >= lim - hptr) {
4491 glob1(hptr + v2, lim);
4506 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4510 glob1(a0, a0 + a1 * a2);
4514 /* -------- io.c -------- */
4520 static int my_getc(int ec)
4524 if (global_env.linep > elinep) {
4525 while ((c = readc()) != '\n' && c);
4526 err("input line too long");
4531 if ((ec != '\'') && (ec != '`') && (global_env.iop->task != XGRAVE)) {
4534 if (c == '\n' && ec != '\"')
4542 static void unget(int c)
4544 if (global_env.iop >= global_env.iobase)
4545 global_env.iop->peekc = c;
4548 static int eofc(void)
4550 return global_env.iop < global_env.iobase || (global_env.iop->peekc == 0 && global_env.iop->prev == 0);
4553 static int readc(void)
4557 RCPRINTF(("READC: global_env.iop %p, global_env.iobase %p\n", global_env.iop, global_env.iobase));
4559 for (; global_env.iop >= global_env.iobase; global_env.iop--) {
4560 RCPRINTF(("READC: global_env.iop %p, peekc 0x%x\n", global_env.iop, global_env.iop->peekc));
4561 c = global_env.iop->peekc;
4563 global_env.iop->peekc = 0;
4566 if (global_env.iop->prev != 0) {
4567 c = (*global_env.iop->iofn)(global_env.iop->argp, global_env.iop);
4573 if (global_env.iop == iostack)
4575 global_env.iop->prev = c;
4576 return global_env.iop->prev;
4578 if (global_env.iop->task == XIO && global_env.iop->prev != '\n') {
4579 global_env.iop->prev = 0;
4580 if (global_env.iop == iostack)
4585 if (global_env.iop->task == XIO) {
4587 global_env.iop->prev = 0;
4588 return global_env.iop->prev;
4590 if (interactive && global_env.iop == iostack + 1) {
4591 #if ENABLE_FEATURE_EDITING
4592 current_prompt = prompt->value;
4600 if (global_env.iop >= iostack) {
4601 RCPRINTF(("READC: return 0, global_env.iop %p\n", global_env.iop));
4605 DBGPRINTF(("READC: leave()...\n"));
4611 static void ioecho(char c)
4614 write(2, &c, sizeof c);
4617 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4619 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, global_env.iop %p\n", argp,
4620 argp->afid, global_env.iop));
4622 /* Set env ptr for io source to next array spot and check for array overflow */
4623 if (++global_env.iop >= &iostack[NPUSH]) {
4625 err("Shell input nested too deeply");
4630 /* We did not overflow the NPUSH array spots so setup data structs */
4632 global_env.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4634 if (argp->afid != AFID_NOBUF)
4635 global_env.iop->argp = argp;
4638 global_env.iop->argp = ioargstack + (global_env.iop - iostack); /* MAL - index into stack */
4639 *global_env.iop->argp = *argp; /* copy data from temp area into stack spot */
4641 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4643 if (global_env.iop == &iostack[0])
4644 global_env.iop->argp->afbuf = &mainbuf;
4646 global_env.iop->argp->afbuf = &sharedbuf;
4648 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4649 /* This line appears to be active when running scripts from command line */
4650 if ((isatty(global_env.iop->argp->afile) == 0)
4651 && (global_env.iop == &iostack[0]
4652 || lseek(global_env.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4653 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4654 bufid = AFID_ID; /* AFID_ID = 0 */
4656 global_env.iop->argp->afid = bufid; /* assign buffer id */
4659 DBGPRINTF(("PUSHIO: iostack %p, global_env.iop %p, afbuf %p\n",
4660 iostack, global_env.iop, global_env.iop->argp->afbuf));
4661 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, global_env.iop %p\n",
4662 &mainbuf, &sharedbuf, bufid, global_env.iop));
4666 global_env.iop->prev = ~'\n';
4667 global_env.iop->peekc = 0;
4668 global_env.iop->xchar = 0;
4669 global_env.iop->nlcount = 0;
4671 if (fn == filechar || fn == linechar)
4672 global_env.iop->task = XIO;
4673 else if (fn == (int (*)(struct ioarg *)) gravechar
4674 || fn == (int (*)(struct ioarg *)) qgravechar)
4675 global_env.iop->task = XGRAVE;
4677 global_env.iop->task = XOTHER;
4680 static struct io *setbase(struct io *ip)
4684 xp = global_env.iobase;
4685 global_env.iobase = ip;
4690 * Input generating functions
4694 * Produce the characters of a string, then a newline, then EOF.
4696 static int nlchar(struct ioarg *ap)
4700 if (ap->aword == NULL)
4711 * Given a list of words, produce the characters
4712 * in them, with a space after each word.
4714 static int wdchar(struct ioarg *ap)
4729 ap->awordlist = NULL;
4734 * Return the characters of a list of words,
4735 * producing a space between them.
4737 static int dolchar(struct ioarg *ap)
4741 wp = *ap->awordlist++;
4743 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4749 static int xxchar(struct ioarg *ap)
4753 if (ap->aword == NULL)
4764 * Produce the characters from a single word (string).
4766 static int strchar(struct ioarg *ap)
4768 if (ap->aword == NULL)
4770 return *ap->aword++;
4774 * Produce quoted characters from a single word (string).
4776 static int qstrchar(struct ioarg *ap)
4780 if (ap->aword == NULL)
4789 * Return the characters from a file.
4791 static int filechar(struct ioarg *ap)
4795 struct iobuf *bp = ap->afbuf;
4797 if (ap->afid != AFID_NOBUF) {
4798 i = (ap->afid != bp->id);
4799 if (i || bp->bufp == bp->ebufp) {
4801 lseek(ap->afile, ap->afpos, SEEK_SET);
4803 i = nonblock_safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4811 bp->ebufp = bp->bufp + i;
4815 return *bp->bufp++ & 0177;
4817 #if ENABLE_FEATURE_EDITING
4818 if (interactive && isatty(ap->afile)) {
4819 /* moved to G: static char filechar_cmdbuf[BUFSIZ]; */
4820 static int position = 0, size = 0;
4822 while (size == 0 || position >= size) {
4823 size = read_line_input(current_prompt, filechar_cmdbuf, BUFSIZ, line_input_state);
4824 if (size < 0) /* Error/EOF */
4827 /* if Ctrl-C, size == 0 and loop will repeat */
4829 c = filechar_cmdbuf[position];
4834 i = nonblock_safe_read(ap->afile, &c, sizeof(c));
4835 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4839 * Return the characters from a here temp file.
4841 static int herechar(struct ioarg *ap)
4845 if (nonblock_safe_read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4853 * Return the characters produced by a process (`...`).
4854 * Quote them if required, and remove any trailing newline characters.
4856 static int gravechar(struct ioarg *ap, struct io *iop)
4860 c = qgravechar(ap, iop) & ~QUOTE;
4866 static int qgravechar(struct ioarg *ap, struct io *iop)
4870 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4875 return '\n' | QUOTE;
4879 } else if ((c = filechar(ap)) == '\n') {
4881 while ((c = filechar(ap)) == '\n')
4889 return c != 0 ? c | QUOTE : 0;
4893 * Return a single command (usually the first line) from a file.
4895 static int linechar(struct ioarg *ap)
4903 ap->afile = -1; /* illegal value */
4910 * remap fd into Shell's fd space
4912 static int remap(int fd)
4918 DBGPRINTF(("REMAP: fd=%d, global_env.iofd=%d\n", fd, global_env.iofd));
4920 if (fd < global_env.iofd) {
4921 for (i = 0; i < NOFILE; i++)
4928 } while (fd >= 0 && fd < global_env.iofd);
4930 for (i = 0; i < NOFILE; i++)
4935 err("too many files open in shell");
4941 static int openpipe(int *pv)
4947 err("can't create pipe - try again");
4951 static void closepipe(int *pv)
4960 /* -------- here.c -------- */
4966 static void markhere(char *s, struct ioword *iop)
4968 struct here *h, *lh;
4970 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4972 h = (struct here *) space(sizeof(struct here));
4976 h->h_tag = evalstr(s, DOSUB);
4986 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4987 if (lh->h_next == 0) {
4993 iop->io_flag |= IOHERE | IOXHERE;
4994 for (s = h->h_tag; *s; s++) {
4996 iop->io_flag &= ~IOXHERE;
5000 h->h_dosub = ((iop->io_flag & IOXHERE) ? '\0' : '\'');
5003 static void gethere(void)
5005 struct here *h, *hp;
5007 DBGPRINTF7(("GETHERE: enter...\n"));
5009 /* Scan here files first leaving inhere list in place */
5010 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5011 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub /* NUL or ' */);
5013 /* Make inhere list active - keep list intact for scraphere */
5015 hp->h_next = acthere;
5021 static void readhere(char **name, char *s, int ec)
5024 char tname[30] = ".msh_XXXXXX";
5027 char myline[LINELIM + 1];
5030 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5032 tf = mkstemp(tname);
5036 *name = strsave(tname, areanum);
5038 if (newenv(setjmp(errpt)) != 0)
5041 pushio(global_env.iop->argp, (int (*)(struct ioarg *)) global_env.iop->iofn);
5042 global_env.iobase = global_env.iop;
5044 if (interactive && global_env.iop <= iostack) {
5045 #if ENABLE_FEATURE_EDITING
5046 current_prompt = cprompt->value;
5048 prs(cprompt->value);
5052 while ((c = my_getc(ec)) != '\n' && c) {
5055 if (thenext >= &myline[LINELIM]) {
5062 if (strcmp(s, myline) == 0 || c == 0)
5065 write(tf, myline, (int) (thenext - myline));
5068 prs("here document `");
5078 * open here temp file.
5079 * if unquoted here, expand here temp file into second temp file.
5081 static int herein(char *hname, int xdoll)
5087 /* Avoid longjmp clobbering */
5093 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5095 hf = open(hname, O_RDONLY);
5101 char tname[30] = ".msh_XXXXXX";
5104 tf = mkstemp(tname);
5108 if (newenv(setjmp(errpt)) == 0) {
5109 PUSHIO(afile, hf, herechar);
5110 setbase(global_env.iop);
5111 while ((c = subgetc(0, 0)) != 0) {
5113 write(tf, &c, sizeof c);
5119 tf = open(tname, O_RDONLY);
5126 static void scraphere(void)
5130 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5132 for (h = inhere; h != NULL; h = h->h_next) {
5133 if (h->h_iop && h->h_iop->io_name)
5134 unlink(h->h_iop->io_name);
5139 /* unlink here temp files before a freearea(area) */
5140 static void freehere(int area)
5142 struct here *h, *hl;
5144 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5147 for (h = acthere; h != NULL; h = h->h_next)
5148 if (getarea((char *) h) >= area) {
5149 if (h->h_iop->io_name != NULL)
5150 unlink(h->h_iop->io_name);
5152 acthere = h->h_next;
5154 hl->h_next = h->h_next;
5160 /* -------- sh.c -------- */
5165 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5166 int msh_main(int argc, char **argv)
5172 int (*iof) (struct ioarg *);
5176 sharedbuf.id = AFID_NOBUF;
5177 mainbuf.id = AFID_NOBUF;
5178 elinep = line + sizeof(line) - 5;
5180 #if ENABLE_FEATURE_EDITING
5181 line_input_state = new_line_input_t(FOR_SHELL);
5184 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5190 assign(*ap++, !COPYV);
5191 for (ap = environ; *ap;)
5192 export(lookup(*ap++));
5197 shell = lookup("SHELL");
5198 if (shell->value == null)
5199 setval(shell, (char *)DEFAULT_SHELL);
5202 homedir = lookup("HOME");
5203 if (homedir->value == null)
5204 setval(homedir, "/");
5207 setval(lookup("$"), putn(getpid()));
5209 path = lookup("PATH");
5210 if (path->value == null) {
5211 /* Can be merged with same string elsewhere in bbox */
5213 setval(path, bb_default_root_path);
5215 setval(path, bb_default_path);
5219 ifs = lookup("IFS");
5220 if (ifs->value == null)
5221 setval(ifs, " \t\n");
5224 mshdbg_var = lookup("MSHDEBUG");
5225 if (mshdbg_var->value == null)
5226 setval(mshdbg_var, "0");
5229 prompt = lookup("PS1");
5230 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5231 if (prompt->value == null)
5233 setval(prompt, DEFAULT_USER_PROMPT);
5234 if (geteuid() == 0) {
5235 setval(prompt, DEFAULT_ROOT_PROMPT);
5236 prompt->status &= ~EXPORT;
5238 cprompt = lookup("PS2");
5239 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5240 if (cprompt->value == null)
5242 setval(cprompt, "> ");
5248 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5249 for (s = argv[0] + 1; *s; s++)
5252 prompt->status &= ~EXPORT;
5253 cprompt->status &= ~EXPORT;
5255 setval(cprompt, "");
5258 PUSHIO(aword, *++argv, iof = nlchar);
5266 /* standard input */
5270 prompt->status &= ~EXPORT;
5278 if (*s >= 'a' && *s <= 'z')
5286 if (iof == filechar && --argc > 0) {
5288 setval(cprompt, "");
5289 prompt->status &= ~EXPORT;
5290 cprompt->status &= ~EXPORT;
5292 /* Shell is non-interactive, activate printf-based debug */
5294 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5298 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5302 exit(1); /* Exit on error */
5308 /* This won't be true if PUSHIO has been called, say from newfile() above */
5309 if (global_env.iop < iostack) {
5310 PUSHIO(afile, 0, iof);
5311 if (isatty(0) && isatty(1) && !cflag) {
5313 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5315 printf("\n\n%s built-in shell (msh with debug)\n", bb_banner);
5317 printf("\n\n%s built-in shell (msh)\n", bb_banner);
5319 printf("Enter 'help' for a list of built-in commands.\n\n");
5324 signal(SIGQUIT, qflag);
5325 if (name && name[0] == '-') {
5327 f = open(".profile", O_RDONLY);
5330 f = open("/etc/profile", O_RDONLY);
5335 signal(SIGTERM, sig);
5337 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5338 signal(SIGINT, onintr);
5340 /* Handle "msh SCRIPT VAR=val params..." */
5341 /* Disabled: bash does not do it! */
5344 /* skip leading args of the form VAR=val */
5345 while (*argv && assign(*argv, !COPYV)) {
5355 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5357 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, global_env.iop %p, iostack %p\n", interactive, global_env.iop, iostack));
5360 if (interactive && global_env.iop <= iostack) {
5361 #if ENABLE_FEATURE_EDITING
5362 current_prompt = prompt->value;
5368 /* Ensure that getenv("PATH") stays current */
5369 setenv("PATH", path->value, 1);
5372 DBGPRINTF(("MSH_MAIN: returning.\n"));
5377 * Copyright (c) 1987,1997, Prentice Hall
5378 * All rights reserved.
5380 * Redistribution and use of the MINIX operating system in source and
5381 * binary forms, with or without modification, are permitted provided
5382 * that the following conditions are met:
5384 * Redistributions of source code must retain the above copyright
5385 * notice, this list of conditions and the following disclaimer.
5387 * Redistributions in binary form must reproduce the above
5388 * copyright notice, this list of conditions and the following
5389 * disclaimer in the documentation and/or other materials provided
5390 * with the distribution.
5392 * Neither the name of Prentice Hall nor the names of the software
5393 * authors or contributors may be used to endorse or promote
5394 * products derived from this software without specific prior
5395 * written permission.
5397 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5398 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5399 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5400 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5401 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5402 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5403 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5404 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5405 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5406 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5407 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5408 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.