1 /* vi: set sw=4 ts=4: */
3 * Minix shell port for busybox
5 * This version of the Minix shell was adapted for use in busybox
6 * by Erik Andersen <andersen@codepoet.org>
8 * - backtick expansion did not work properly
9 * Jonas Holmberg <jonas.holmberg@axis.com>
10 * Robert Schwebel <r.schwebel@pengutronix.de>
11 * Erik Andersen <andersen@codepoet.org>
13 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
16 #include <sys/times.h>
23 # include <sys/types.h>
24 # include <sys/stat.h>
25 # include <sys/wait.h>
36 # define bb_dev_null "/dev/null"
37 # define DEFAULT_SHELL "/proc/self/exe"
38 # define CONFIG_BUSYBOX_EXEC_PATH "/proc/self/exe"
39 # define bb_banner "busybox standalone"
40 # define ENABLE_FEATURE_SH_STANDALONE 0
41 # define bb_msg_memory_exhausted "memory exhausted"
42 # define xmalloc(size) malloc(size)
43 # define msh_main(argc,argv) main(argc,argv)
44 # define safe_read(fd,buf,count) read(fd,buf,count)
45 # define NOT_LONE_DASH(s) ((s)[0] != '-' || (s)[1])
46 # define LONE_CHAR(s,c) ((s)[0] == (c) && !(s)[1])
47 # define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
48 static int find_applet_by_name(const char *applet)
52 static char *utoa_to_buf(unsigned n, char *buf, unsigned buflen)
55 assert(sizeof(unsigned) == 4);
58 for (i = 1000000000; i; i /= 10) {
60 if (res || out || i == 1) {
70 static char *itoa_to_buf(int n, char *buf, unsigned buflen)
72 if (buflen && n < 0) {
77 return utoa_to_buf((unsigned)n, buf, buflen);
79 static char local_buf[12];
80 static char *itoa(int n)
82 *(itoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
86 # include "busybox.h" /* for applet_names */
89 /*#define MSHDEBUG 1*/
92 int mshdbg = MSHDEBUG;
94 #define DBGPRINTF(x) if (mshdbg>0) printf x
95 #define DBGPRINTF0(x) if (mshdbg>0) printf x
96 #define DBGPRINTF1(x) if (mshdbg>1) printf x
97 #define DBGPRINTF2(x) if (mshdbg>2) printf x
98 #define DBGPRINTF3(x) if (mshdbg>3) printf x
99 #define DBGPRINTF4(x) if (mshdbg>4) printf x
100 #define DBGPRINTF5(x) if (mshdbg>5) printf x
101 #define DBGPRINTF6(x) if (mshdbg>6) printf x
102 #define DBGPRINTF7(x) if (mshdbg>7) printf x
103 #define DBGPRINTF8(x) if (mshdbg>8) printf x
104 #define DBGPRINTF9(x) if (mshdbg>9) printf x
108 #define RCPRINTF(x) if (mshdbg_rc) printf x
113 #define DBGPRINTF0(x) ((void)0)
114 #define DBGPRINTF1(x) ((void)0)
115 #define DBGPRINTF2(x) ((void)0)
116 #define DBGPRINTF3(x) ((void)0)
117 #define DBGPRINTF4(x) ((void)0)
118 #define DBGPRINTF5(x) ((void)0)
119 #define DBGPRINTF6(x) ((void)0)
120 #define DBGPRINTF7(x) ((void)0)
121 #define DBGPRINTF8(x) ((void)0)
122 #define DBGPRINTF9(x) ((void)0)
124 #define RCPRINTF(x) ((void)0)
126 #endif /* MSHDEBUG */
129 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
130 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
131 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
133 # define DEFAULT_ROOT_PROMPT "# "
134 # define DEFAULT_USER_PROMPT "$ "
138 /* -------- sh.h -------- */
144 #define NPUSH 8 /* limit to input nesting */
147 #define NOFILE 20 /* Number of open files */
148 #define NUFILE 10 /* Number of user-accessible files */
149 #define FDBASE 10 /* First file usable by Shell */
152 * values returned by wait
154 #define WAITSIG(s) ((s) & 0177)
155 #define WAITVAL(s) (((s) >> 8) & 0377)
156 #define WAITCORE(s) (((s) & 0200) != 0)
159 * library and system definitions
161 typedef void xint; /* base type of jmp_buf, for not broken compilers */
166 #define NOBLOCK ((struct op *)NULL)
167 #define NOWORD ((char *)NULL)
168 #define NOWORDS ((char **)NULL)
169 #define NOPIPE ((int *)NULL)
175 short io_unit; /* unit affected */
176 short io_flag; /* action (below) */
177 char *io_name; /* file name */
180 #define IOREAD 1 /* < */
181 #define IOHERE 2 /* << (here file) */
182 #define IOWRITE 4 /* > */
183 #define IOCAT 8 /* >> */
184 #define IOXHERE 16 /* ${}, ` in << */
185 #define IODUP 32 /* >&digit */
186 #define IOCLOSE 64 /* >&- */
188 #define IODEFAULT (-1) /* token for default IO unit */
192 * Description of a command or an operation on commands.
193 * Might eventually use a union.
196 int type; /* operation type, see below */
197 char **words; /* arguments to a command */
198 struct ioword **ioact; /* IO actions (eg, < > >>) */
201 char *str; /* identifier for case and for */
204 #define TCOM 1 /* command */
205 #define TPAREN 2 /* (c-list) */
206 #define TPIPE 3 /* a | b */
207 #define TLIST 4 /* a [&;] b */
208 #define TOR 5 /* || */
209 #define TAND 6 /* && */
217 #define TPAT 14 /* pattern in case */
218 #define TBRACE 15 /* {c-list} */
219 #define TASYNC 16 /* c & */
220 /* Added to support "." file expansion */
223 /* Strings for names to make debug easier */
225 static const char *const T_CMD_NAMES[] = {
248 * actions determining the environment of a process
250 #define FEXEC 1 /* execute without forking */
252 #define AREASIZE (90000)
255 * flags to control evaluation of words
257 #define DOSUB 1 /* interpret $, `, and quotes */
258 #define DOBLANK 2 /* perform blank interpretation */
259 #define DOGLOB 4 /* interpret [?* */
260 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
261 #define DOTRIM 16 /* trim resulting string */
263 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
268 struct brkcon *nextlev;
272 static int trapset; /* trap pending */
274 static int yynerrs; /* yacc */
276 /* moved to G: static char line[LINELIM]; */
278 #if ENABLE_FEATURE_EDITING
279 static char *current_prompt;
280 static line_input_t *line_input_state;
287 static const char *rexecve(char *c, char **v, char **envp);
288 static char *evalstr(char *cp, int f);
289 static char *putn(int n);
290 static char *unquote(char *as);
291 static int rlookup(char *n);
292 static struct wdblock *glob(char *cp, struct wdblock *wb);
293 static int my_getc(int ec);
294 static int subgetc(char ec, int quoted);
295 static char **makenv(int all, struct wdblock *wb);
296 static char **eval(char **ap, int f);
297 static int setstatus(int s);
298 static int waitfor(int lastpid, int canintr);
300 static void onintr(int s); /* SIGINT handler */
302 static int newenv(int f);
303 static void quitenv(void);
304 static void next(int f);
305 static void setdash(void);
306 static void onecommand(void);
307 static void runtrap(int i);
310 /* -------- area stuff -------- */
312 #define REGSIZE sizeof(struct region)
314 /* #define SHRINKBY (64) */
318 #define ALIGN (sizeof(int)-1)
327 /* -------- grammar stuff -------- */
352 /* Added for "." file expansion */
355 #define YYERRCODE 300
358 #define CONTIN 01 /* skip new lines to complete command */
360 static struct op *pipeline(int cf);
361 static struct op *andor(void);
362 static struct op *c_list(void);
363 static int synio(int cf);
364 static void musthave(int c, int cf);
365 static struct op *simple(void);
366 static struct op *nested(int type, int mark);
367 static struct op *command(int cf);
368 static struct op *dogroup(int onlydone);
369 static struct op *thenpart(void);
370 static struct op *elsepart(void);
371 static struct op *caselist(void);
372 static struct op *casepart(void);
373 static char **pattern(void);
374 static char **wordlist(void);
375 static struct op *list(struct op *t1, struct op *t2);
376 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
377 static struct op *newtp(void);
378 static struct op *namelist(struct op *t);
379 static char **copyw(void);
380 static void word(char *cp);
381 static struct ioword **copyio(void);
382 static struct ioword *io(int u, int f, char *cp);
383 static int yylex(int cf);
384 static int collect(int c, int c1);
385 static int dual(int c);
386 static void diag(int ec);
387 static char *tree(unsigned size);
389 /* -------- var.h -------- */
398 #define COPYV 1 /* flag to setval, suggesting copy */
399 #define RONLY 01 /* variable is read-only */
400 #define EXPORT 02 /* variable is to be exported */
401 #define GETCELL 04 /* name & value space was got with getcell */
403 static int yyparse(void);
405 static int execute(struct op *t, int *pin, int *pout, int act);
408 /* -------- io.h -------- */
411 unsigned id; /* buffer id */
412 char buf[512]; /* buffer */
413 char *bufp; /* pointer into buffer */
414 char *ebufp; /* pointer to end of buffer */
417 /* possible arguments to an IO function */
421 int afile; /* file descriptor */
422 unsigned afid; /* buffer id */
423 long afpos; /* file position */
424 struct iobuf *afbuf; /* buffer for this file */
427 /* an input generator's state */
429 int (*iofn) (struct ioarg *, struct io *);
432 char prev; /* previous character read by readc() */
433 char nlcount; /* for `'s */
434 char xchar; /* for `'s */
435 char task; /* reason for pushed IO */
438 #define XOTHER 0 /* none of the below */
439 #define XDOLL 1 /* expanding ${} */
440 #define XGRAVE 2 /* expanding `'s */
441 #define XIO 3 /* file IO */
445 * input generators for IO structure
447 static int nlchar(struct ioarg *ap);
448 static int strchar(struct ioarg *ap);
449 static int qstrchar(struct ioarg *ap);
450 static int filechar(struct ioarg *ap);
451 static int herechar(struct ioarg *ap);
452 static int linechar(struct ioarg *ap);
453 static int gravechar(struct ioarg *ap, struct io *iop);
454 static int qgravechar(struct ioarg *ap, struct io *iop);
455 static int dolchar(struct ioarg *ap);
456 static int wdchar(struct ioarg *ap);
457 static void scraphere(void);
458 static void freehere(int area);
459 static void gethere(void);
460 static void markhere(char *s, struct ioword *iop);
461 static int herein(char *hname, int xdoll);
462 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
465 static int eofc(void);
466 static int readc(void);
467 static void unget(int c);
468 static void ioecho(char c);
474 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
475 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
476 static int remap(int fd);
477 static int openpipe(int *pv);
478 static void closepipe(int *pv);
479 static struct io *setbase(struct io *ip);
481 /* -------- word.h -------- */
483 #define NSTART 16 /* default number of words to allow for initially */
488 /* bounds are arbitrary */
492 static struct wdblock *addword(char *wd, struct wdblock *wb);
493 static struct wdblock *newword(int nw);
494 static char **getwords(struct wdblock *wb);
496 /* -------- misc stuff -------- */
498 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
499 static int iosetup(struct ioword *iop, int pipein, int pipeout);
500 static void brkset(struct brkcon *bc);
501 static int dolabel(struct op *t);
502 static int dohelp(struct op *t);
503 static int dochdir(struct op *t);
504 static int doshift(struct op *t);
505 static int dologin(struct op *t);
506 static int doumask(struct op *t);
507 static int doexec(struct op *t);
508 static int dodot(struct op *t);
509 static int dowait(struct op *t);
510 static int doread(struct op *t);
511 static int doeval(struct op *t);
512 static int dotrap(struct op *t);
513 static int getsig(char *s);
514 static void setsig(int n, sighandler_t f);
515 static int getn(char *as);
516 static int dobreak(struct op *t);
517 static int docontinue(struct op *t);
518 static int brkcontin(char *cp, int val);
519 static int doexit(struct op *t);
520 static int doexport(struct op *t);
521 static int doreadonly(struct op *t);
522 static void rdexp(char **wp, void (*f) (struct var *), int key);
523 static void badid(char *s);
524 static int doset(struct op *t);
525 static void varput(char *s, int out);
526 static int dotimes(struct op *t);
527 static int expand(const char *cp, struct wdblock **wbp, int f);
528 static char *blank(int f);
529 static int dollar(int quoted);
530 static int grave(int quoted);
531 static void globname(char *we, char *pp);
532 static char *generate(char *start1, char *end1, char *middle, char *end);
533 static int anyspcl(struct wdblock *wb);
534 static int xstrcmp(char *p1, char *p2);
535 static void glob0(char *a0, unsigned a1, int a2,
536 int (*a3) (char *, char *));
537 static void readhere(char **name, char *s, int ec);
538 static int xxchar(struct ioarg *ap);
543 struct ioword *h_iop;
547 static const char *const signame[] = {
550 NULL, /* interrupt */
552 "Illegal instruction",
556 "Floating Point Exception",
561 NULL, /* broken pipe */
569 int (*builtinfunc)(struct op *t);
571 static const struct builtincmd builtincmds[] = {
574 { "break" , dobreak },
576 { "continue", docontinue },
580 { "export" , doexport },
582 { "login" , dologin },
583 { "newgrp" , dologin },
585 { "readonly", doreadonly },
587 { "shift" , doshift },
588 { "times" , dotimes },
590 { "umask" , doumask },
595 static struct op *scantree(struct op *);
596 static struct op *dowholefile(int, int);
604 static int interactive; /* Is this an interactive shell */
606 static int multiline; /* \n changed to ; */
607 static struct op *outtree; /* result from parser */
610 static struct brkcon *brklist;
612 static struct wdblock *wdlist;
613 static struct wdblock *iolist;
616 static struct var *mshdbg_var;
618 static struct var *vlist; /* dictionary */
619 static struct var *homedir; /* home directory */
620 static struct var *prompt; /* main prompt */
621 static struct var *cprompt; /* continuation prompt */
622 static struct var *path; /* search path for commands */
623 static struct var *shell; /* shell to interpret command files */
624 static struct var *ifs; /* field separators */
626 static int areanum; /* current allocation area */
627 static int intr; /* interrupt pending */
629 static char *null = (char*)""; /* null value for variable */
630 static int heedint = 1; /* heed interrupt signals */
631 static void (*qflag)(int) = SIG_IGN;
635 static int iounit = IODEFAULT;
636 static YYSTYPE yylval;
637 static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
639 static struct here *inhere; /* list of hear docs while parsing */
640 static struct here *acthere; /* list of active here documents */
641 static struct region *areabot; /* bottom of area */
642 static struct region *areatop; /* top of area */
643 static struct region *areanxt; /* starting point of scan */
645 static void *brkaddr;
647 #define AFID_NOBUF (~0)
652 * parsing & execution environment
658 xint *errpt; /* void * */
665 struct env global_env;
666 struct ioarg temparg; // = { .afid = AFID_NOBUF }; /* temporary for PUSHIO */
667 unsigned bufid; // = AFID_ID; /* buffer id counter */
668 char ourtrap[_NSIG + 1];
669 char *trap[_NSIG + 1];
670 struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
671 struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
672 struct ioarg ioargstack[NPUSH];
676 * -k: look for name=value everywhere on command line
678 * -t: exit after reading and executing one command
681 * -u: unset variables net diagnostic
683 char flags['z' - 'a' + 1];
684 char filechar_cmdbuf[BUFSIZ];
686 char child_cmd[LINELIM];
688 struct io iostack[NPUSH];
690 char grave__var_name[LINELIM];
691 char grave__alt_value[LINELIM];
694 #define G (*ptr_to_globals)
695 #define global_env (G.global_env )
696 #define temparg (G.temparg )
697 #define bufid (G.bufid )
698 #define ourtrap (G.ourtrap )
699 #define trap (G.trap )
700 #define sharedbuf (G.sharedbuf )
701 #define mainbuf (G.mainbuf )
702 #define ioargstack (G.ioargstack )
703 /* this looks weird, but is OK ... we index FLAG with 'a'...'z' */
704 #define FLAG (G.flags - 'a' )
705 #define filechar_cmdbuf (G.filechar_cmdbuf)
706 #define line (G.line )
707 #define child_cmd (G.child_cmd )
708 #define iostack (G.iostack )
709 #define INIT_G() do { \
710 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
711 global_env.linep = line; \
712 global_env.iobase = iostack; \
713 global_env.iop = iostack - 1; \
714 global_env.iofd = FDBASE; \
715 temparg.afid = AFID_NOBUF; \
720 /* in substitution */
721 #define INSUB() (global_env.iop->task == XGRAVE || global_env.iop->task == XDOLL)
723 #define RUN(what, arg, gen) ((temparg.what = (arg)), run(&temparg, (gen)))
726 void print_t(struct op *t)
728 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
729 T_CMD_NAMES[t->type], t->words, t->ioact));
732 DBGPRINTF(("T: W1: %s", t->words[0]));
736 void print_tree(struct op *head)
739 DBGPRINTF(("PRINT_TREE: no tree\n"));
743 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
747 print_tree(head->left);
750 print_tree(head->right);
752 #endif /* MSHDEBUG */
758 static void prs(const char *s)
761 write(2, s, strlen(s));
764 static void prn(unsigned u)
769 static void echo(char **wp)
774 for (i = 0; wp[i]; i++) {
782 static void closef(int i)
788 static void closeall(void)
792 for (u = NUFILE; u < NOFILE;)
797 /* fail but return to process next command */
798 static void fail(void) ATTRIBUTE_NORETURN;
799 static void fail(void)
805 /* abort shell (or fail in subshell) */
806 static void leave(void) ATTRIBUTE_NORETURN;
807 static void leave(void)
809 DBGPRINTF(("LEAVE: leave called!\n"));
820 static void warn(const char *s)
831 static void err(const char *s)
838 if (global_env.errpt)
839 longjmp(global_env.errpt, 1);
841 global_env.iop = global_env.iobase = iostack;
845 /* -------- area.c -------- */
848 * All memory between (char *)areabot and (char *)(areatop+1) is
849 * exclusively administered by the area management routines.
850 * It is assumed that sbrk() and brk() manipulate the high end.
854 void * __q = (void *)-1; \
855 if (brkaddr + (int)(X) < brktop) { \
857 brkaddr += (int)(X); \
862 static void initarea(void)
864 brkaddr = xmalloc(AREASIZE);
865 brktop = brkaddr + AREASIZE;
867 while ((long) sbrk(0) & ALIGN)
869 areabot = (struct region *) sbrk(REGSIZE);
871 areabot->next = areabot;
872 areabot->area = BUSY;
877 static char *getcell(unsigned nbytes)
880 struct region *p, *q;
887 /* silly and defeats the algorithm */
889 * round upwards and add administration area
891 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
894 if (p->area > areanum) {
898 while ((q = p->next)->area > areanum && q != areanxt)
901 * exit loop if cell big enough
910 i = nregio >= GROWBY ? nregio : GROWBY;
911 p = (struct region *) sbrk(i * REGSIZE);
912 if (p == (struct region *) -1)
917 abort(); /* allocated areas are contiguous */
927 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
929 areanxt = p + nregio;
932 * split into requested area and rest
934 if (areanxt + 1 > q) {
936 abort(); /* insufficient space left for admin */
939 areanxt->area = FREE;
943 return (char *) (p + 1);
946 static void freecell(char *cp)
950 p = (struct region *) cp;
958 #define DELETE(obj) freecell((char *)obj)
960 static void freearea(int a)
962 struct region *p, *top;
965 for (p = areabot; p != top; p = p->next)
970 static void setarea(char *cp, int a)
974 p = (struct region *) cp;
979 static int getarea(char *cp)
981 return ((struct region *) cp - 1)->area;
984 static void garbage(void)
986 struct region *p, *q, *top;
989 for (p = areabot; p != top; p = p->next) {
990 if (p->area > areanum) {
991 while ((q = p->next)->area > areanum)
997 if (areatop >= q + SHRINKBY && q->area > areanum) {
998 brk((char *) (q + 1));
1006 static char *space(int n)
1012 err("out of string space");
1016 static char *strsave(const char *s, int a)
1020 cp = space(strlen(s) + 1);
1022 // FIXME: I highly doubt this is good.
1031 /* -------- var.c -------- */
1033 static int eqname(const char *n1, const char *n2)
1035 for (; *n1 != '=' && *n1 != '\0'; n1++)
1038 return *n2 == '\0' || *n2 == '=';
1041 static const char *findeq(const char *cp)
1043 while (*cp != '\0' && *cp != '=')
1049 * Find the given name in the dictionary
1050 * and return its value. If the name was
1051 * not previously there, enter it now and
1052 * return a null value.
1054 static struct var *lookup(const char *n)
1056 // FIXME: dirty hack
1057 static struct var dummy;
1065 dummy.name = (char*)n;
1066 for (c = 0; isdigit(*n) && c < 1000; n++)
1067 c = c * 10 + *n - '0';
1068 dummy.status = RONLY;
1069 dummy.value = (c <= dolc ? dolv[c] : null);
1073 for (vp = vlist; vp; vp = vp->next)
1074 if (eqname(vp->name, n))
1078 vp = (struct var *) space(sizeof(*vp));
1079 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1080 dummy.name = dummy.value = (char*)"";
1085 while ((*xp = *n++) != '\0' && *xp != '=')
1089 setarea((char *) vp, 0);
1090 setarea((char *) vp->name, 0);
1093 vp->status = GETCELL;
1099 * if name is not NULL, it must be
1100 * a prefix of the space `val',
1102 * this is all so that exporting
1103 * values is reasonably painless.
1105 static void nameval(struct var *vp, const char *val, const char *name)
1111 if (vp->status & RONLY) {
1113 while (*xp && *xp != '=')
1114 fputc(*xp++, stderr);
1115 err(" is read-only");
1120 xp = space(strlen(vp->name) + strlen(val) + 2);
1123 /* make string: name=value */
1127 while ((*xp = *cp++) != '\0' && *xp != '=')
1134 if (vp->status & GETCELL)
1135 freecell(vp->name); /* form new string `name=value' */
1136 vp->name = (char*)name;
1137 vp->value = (char*)val;
1142 * give variable at `vp' the value `val'.
1144 static void setval(struct var *vp, const char *val)
1146 nameval(vp, val, NULL);
1149 static void export(struct var *vp)
1151 vp->status |= EXPORT;
1154 static void ronly(struct var *vp)
1156 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1157 vp->status |= RONLY;
1160 static int isassign(const char *s)
1163 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1166 /* no isalpha() - we shouldn't use locale */
1167 /* c | 0x20 - lowercase (Latin) letters */
1168 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1179 && (unsigned)(c - '0') > 9 /* not number */
1180 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1187 static int assign(const char *s, int cf)
1192 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1194 if (!isalpha(*s) && *s != '_')
1196 for (cp = s; *cp != '='; cp++)
1197 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1200 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1202 vp->status &= ~GETCELL;
1206 static int checkname(char *cp)
1208 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1210 if (!isalpha(*cp++) && *(cp - 1) != '_')
1213 if (!isalnum(*cp++) && *(cp - 1) != '_')
1218 static void putvlist(int f, int out)
1222 for (vp = vlist; vp; vp = vp->next) {
1223 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1224 if (vp->status & EXPORT)
1225 write(out, "export ", 7);
1226 if (vp->status & RONLY)
1227 write(out, "readonly ", 9);
1228 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1229 write(out, "\n", 1);
1238 static void sig(int i)
1244 static void runtrap(int i)
1249 if (trapstr == NULL)
1255 RUN(aword, trapstr, nlchar);
1259 static void setdash(void)
1263 char m['z' - 'a' + 1];
1266 for (c = 'a'; c <= 'z'; c++)
1270 setval(lookup("-"), m);
1273 static int newfile(char *s)
1277 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1280 if (NOT_LONE_DASH(s)) {
1281 DBGPRINTF(("NEWFILE: s is %s\n", s));
1282 f = open(s, O_RDONLY);
1285 err(": cannot open");
1295 struct op *scantree(struct op *head)
1302 if (head->left != NULL) {
1303 dotnode = scantree(head->left);
1308 if (head->right != NULL) {
1309 dotnode = scantree(head->right);
1314 if (head->words == NULL)
1317 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1319 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1320 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1328 static void onecommand(void)
1333 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1335 while (global_env.oenv)
1344 global_env.errpt = 0;
1345 global_env.linep = line;
1353 setjmp(failpt); /* Bruce Evans' fix */
1355 if (setjmp(failpt) || yyparse() || intr) {
1356 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1358 while (global_env.oenv)
1361 if (!interactive && intr)
1374 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1376 execute(outtree, NOPIPE, NOPIPE, 0);
1379 if (!interactive && intr) {
1391 static int newenv(int f)
1395 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1402 ep = (struct env *) space(sizeof(*ep));
1404 while (global_env.oenv)
1409 global_env.oenv = ep;
1410 global_env.errpt = errpt;
1415 static void quitenv(void)
1420 DBGPRINTF(("QUITENV: global_env.oenv=%p\n", global_env.oenv));
1422 ep = global_env.oenv;
1424 fd = global_env.iofd;
1426 /* should close `'d files */
1428 while (--fd >= global_env.iofd)
1434 * Is character c in s?
1436 static int any(int c, const char *s)
1445 * Is any character from s1 in s2?
1447 static int anys(const char *s1, const char *s2)
1455 static char *putn(int n)
1460 static void next(int f)
1462 PUSHIO(afile, f, filechar);
1465 static void onintr(int s) /* ANSI C requires a parameter */
1467 signal(SIGINT, onintr);
1474 } else if (heedint) {
1481 /* -------- gmatch.c -------- */
1483 * int gmatch(string, pattern)
1484 * char *string, *pattern;
1486 * Match a pattern as in sh(1).
1491 #define QMASK (CMASK & ~QUOTE)
1492 #define NOT '!' /* might use ^ */
1494 static const char *cclass(const char *p, int sub)
1496 int c, d, not, found;
1506 if (p[1] == '-' && p[2] != ']') {
1511 if (c == sub || (c <= sub && sub <= d))
1513 } while (*++p != ']');
1514 return found ? p + 1 : NULL;
1517 static int gmatch(const char *s, const char *p)
1521 if (s == NULL || p == NULL)
1524 while ((pc = *p++ & CMASK) != '\0') {
1541 if (*p == '\0' || gmatch(s, p))
1543 } while (*s++ != '\0');
1547 if (sc != (pc & ~QUOTE))
1555 /* -------- csyn.c -------- */
1557 * shell: syntax (C version)
1560 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1561 static void yyerror(const char *s)
1564 if (interactive && global_env.iop <= iostack) {
1566 while (eofc() == 0 && yylex(0) != '\n');
1572 static void zzerr(void) ATTRIBUTE_NORETURN;
1573 static void zzerr(void)
1575 yyerror("syntax error");
1580 DBGPRINTF7(("YYPARSE: enter...\n"));
1587 return (yynerrs != 0);
1590 static struct op *pipeline(int cf)
1595 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1599 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1602 while ((c = yylex(0)) == '|') {
1603 p = command(CONTIN);
1605 DBGPRINTF8(("PIPELINE: error!\n"));
1609 if (t->type != TPAREN && t->type != TCOM) {
1610 /* shell statement */
1611 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1614 t = block(TPIPE, t, p, NOWORDS);
1619 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1623 static struct op *andor(void)
1628 DBGPRINTF7(("ANDOR: enter...\n"));
1632 DBGPRINTF9(("ANDOR: t=%p\n", t));
1635 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1636 p = pipeline(CONTIN);
1638 DBGPRINTF8(("ANDOR: error!\n"));
1642 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1648 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1652 static struct op *c_list(void)
1657 DBGPRINTF7(("C_LIST: enter...\n"));
1664 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1666 while ((c = yylex(0)) == ';' || c == '&'
1667 || (multiline && c == '\n')) {
1675 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1683 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1687 static int synio(int cf)
1693 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1696 if (c != '<' && c != '>') {
1703 iop = io(iounit, i, yylval.cp);
1707 markhere(yylval.cp, iop);
1709 DBGPRINTF7(("SYNIO: returning 1\n"));
1713 static void musthave(int c, int cf)
1715 peeksym = yylex(cf);
1717 DBGPRINTF7(("MUSTHAVE: error!\n"));
1724 static struct op *simple(void)
1730 switch (peeksym = yylex(0)) {
1751 static struct op *nested(int type, int mark)
1755 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1761 return block(type, t, NOBLOCK, NOWORDS);
1764 static struct op *command(int cf)
1767 struct wdblock *iosave;
1770 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1796 t = nested(TPAREN, ')');
1800 t = nested(TBRACE, '}');
1810 t->words = wordlist();
1812 if (c != '\n' && c != ';')
1814 t->left = dogroup(0);
1822 t->type = c == WHILE ? TWHILE : TUNTIL;
1824 t->right = dogroup(1);
1836 musthave(IN, CONTIN);
1839 t->left = caselist();
1850 t->right = thenpart();
1859 musthave(WORD, 0); /* gets name of file */
1860 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1862 word(yylval.cp); /* add word to wdlist */
1863 word(NOWORD); /* terminate wdlist */
1864 t->words = copyw(); /* dup wdlist */
1874 DBGPRINTF(("COMMAND: returning %p\n", t));
1879 static struct op *dowholefile(int type, int mark)
1883 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1888 t = block(type, t, NOBLOCK, NOWORDS);
1889 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1893 static struct op *dogroup(int onlydone)
1899 if (c == DONE && onlydone)
1908 static struct op *thenpart(void)
1921 if (t->left == NULL)
1923 t->right = elsepart();
1927 static struct op *elsepart(void)
1932 switch (c = yylex(0)) {
1943 t->right = thenpart();
1952 static struct op *caselist(void)
1957 while ((peeksym = yylex(CONTIN)) != ESAC) {
1958 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1959 t = list(t, casepart());
1962 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1966 static struct op *casepart(void)
1970 DBGPRINTF7(("CASEPART: enter...\n"));
1974 t->words = pattern();
1977 peeksym = yylex(CONTIN);
1978 if (peeksym != ESAC)
1979 musthave(BREAK, CONTIN);
1981 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
1986 static char **pattern(void)
2003 static char **wordlist(void)
2013 while ((c = yylex(0)) == WORD)
2021 * supporting functions
2023 static struct op *list(struct op *t1, struct op *t2)
2025 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2032 return block(TLIST, t1, t2, NOWORDS);
2035 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2039 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2047 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2053 /* See if given string is a shell multiline (FOR, IF, etc) */
2054 static int rlookup(char *n)
2060 static const struct res restab[] = {
2083 const struct res *rp;
2085 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2087 for (rp = restab; rp->r_name[0]; rp++)
2088 if (strcmp(rp->r_name, n) == 0) {
2089 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2090 return rp->r_val; /* Return numeric code for shell multiline */
2093 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2094 return 0; /* Not a shell multiline */
2097 static struct op *newtp(void)
2101 t = (struct op *) tree(sizeof(*t));
2109 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2114 static struct op *namelist(struct op *t)
2116 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2117 T_CMD_NAMES[t->type], iolist));
2120 iolist = addword((char *) NULL, iolist);
2121 t->ioact = copyio();
2125 if (t->type != TCOM) {
2126 if (t->type != TPAREN && t->ioact != NULL) {
2127 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2128 t->ioact = t->left->ioact;
2129 t->left->ioact = NULL;
2140 static char **copyw(void)
2144 wd = getwords(wdlist);
2149 static void word(char *cp)
2151 wdlist = addword(cp, wdlist);
2154 static struct ioword **copyio(void)
2156 struct ioword **iop;
2158 iop = (struct ioword **) getwords(iolist);
2163 static struct ioword *io(int u, int f, char *cp)
2167 iop = (struct ioword *) tree(sizeof(*iop));
2171 iolist = addword((char *) iop, iolist);
2175 static int yylex(int cf)
2192 global_env.linep = line;
2195 line[LINELIM - 1] = '\0';
2198 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2203 if (any(c, "0123456789")) {
2206 if (c1 == '<' || c1 == '>') {
2210 *global_env.linep++ = c;
2215 case '#': /* Comment, skip to next newline or End-of-string */
2216 while ((c = my_getc(0)) != '\0' && c != '\n');
2221 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2225 DBGPRINTF9(("YYLEX: found $\n"));
2226 *global_env.linep++ = c;
2229 c = collect(c, '}');
2248 /* If more chars process them, else return NULL char */
2266 if (multiline || cf & CONTIN) {
2267 if (interactive && global_env.iop <= iostack) {
2268 #if ENABLE_FEATURE_EDITING
2269 current_prompt = cprompt->value;
2271 prs(cprompt->value);
2288 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2289 if (global_env.linep >= elinep)
2290 err("word too long");
2292 *global_env.linep++ = c;
2297 if (any(c, "\"'`$"))
2300 *global_env.linep++ = '\0';
2310 yylval.cp = strsave(line, areanum);
2315 static int collect(int c, int c1)
2319 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2321 *global_env.linep++ = c;
2322 while ((c = my_getc(c1)) != c1) {
2331 if (interactive && c == '\n' && global_env.iop <= iostack) {
2332 #if ENABLE_FEATURE_EDITING
2333 current_prompt = cprompt->value;
2335 prs(cprompt->value);
2338 *global_env.linep++ = c;
2341 *global_env.linep++ = c;
2343 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2348 /* "multiline commands" helper func */
2349 /* see if next 2 chars form a shell multiline */
2350 static int dual(int c)
2355 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2357 *cp++ = c; /* c is the given "peek" char */
2358 *cp++ = my_getc(0); /* get next char of input */
2359 *cp = '\0'; /* add EOS marker */
2361 c = rlookup(s); /* see if 2 chars form a shell multiline */
2363 unget(*--cp); /* String is not a shell multiline, put peek char back */
2365 return c; /* String is multiline, return numeric multiline (restab) code */
2368 static void diag(int ec)
2372 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2375 if (c == '>' || c == '<') {
2378 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2381 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2382 if (c != '&' || yylval.i == IOHERE)
2388 static char *tree(unsigned size)
2394 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2395 prs("command line too complicated\n");
2406 /* -------- exec.c -------- */
2408 static struct op **find1case(struct op *t, const char *w)
2416 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2420 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2421 T_CMD_NAMES[t->type]));
2423 if (t->type == TLIST) {
2424 tp = find1case(t->left, w);
2426 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2429 t1 = t->right; /* TPAT */
2433 for (wp = t1->words; *wp;) {
2434 cp = evalstr(*wp++, DOSUB);
2435 if (cp && gmatch(w, cp)) {
2436 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2442 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2446 static struct op *findcase(struct op *t, const char *w)
2450 tp = find1case(t, w);
2451 return tp != NULL ? *tp : NULL;
2458 static int execute(struct op *t, int *pin, int *pout, int act)
2461 volatile int i, rv, a;
2465 struct op *outtree_save;
2469 /* Avoid longjmp clobbering */
2474 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2478 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2479 t->type, T_CMD_NAMES[t->type],
2480 ((t->words == NULL) ? "NULL" : t->words[0])));
2484 wp = (wp2 = t->words) != NULL
2485 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2490 DBGPRINTF3(("EXECUTE: TDOT\n"));
2492 outtree_save = outtree;
2494 newfile(evalstr(t->words[0], DOALL));
2496 t->left = dowholefile(TLIST, 0);
2499 outtree = outtree_save;
2502 rv = execute(t->left, pin, pout, 0);
2504 rv = execute(t->right, pin, pout, 0);
2508 rv = execute(t->left, pin, pout, 0);
2512 rv = forkexec(t, pin, pout, act, wp);
2522 pv[0] = remap(pv[0]);
2523 pv[1] = remap(pv[1]);
2524 (void) execute(t->left, pin, pv, 0);
2525 rv = execute(t->right, pv, pout, 0);
2530 (void) execute(t->left, pin, pout, 0);
2531 rv = execute(t->right, pin, pout, 0);
2536 int hinteractive = interactive;
2538 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2541 if (i == 0) { /* child */
2542 signal(SIGINT, SIG_IGN);
2543 signal(SIGQUIT, SIG_IGN);
2545 signal(SIGTERM, SIG_DFL);
2549 xopen(bb_dev_null, O_RDONLY);
2551 _exit(execute(t->left, pin, pout, FEXEC));
2553 interactive = hinteractive;
2555 setval(lookup("!"), putn(i));
2569 rv = execute(t->left, pin, pout, 0);
2571 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2572 rv = execute(t1, pin, pout, 0);
2583 while (*wp++ != NULL);
2585 vp = lookup(t->str);
2586 while (setjmp(bc.brkpt))
2590 for (t1 = t->left; i-- && *wp != NULL;) {
2592 rv = execute(t1, pin, pout, 0);
2594 brklist = brklist->nextlev;
2599 while (setjmp(bc.brkpt))
2604 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2605 rv = execute(t->right, pin, pout, 0);
2606 brklist = brklist->nextlev;
2611 if (t->right != NULL) {
2612 rv = !execute(t->left, pin, pout, 0) ?
2613 execute(t->right->left, pin, pout, 0) :
2614 execute(t->right->right, pin, pout, 0);
2619 cp = evalstr(t->str, DOSUB | DOTRIM);
2623 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2624 ((t->str == NULL) ? "NULL" : t->str),
2625 ((cp == NULL) ? "NULL" : cp)));
2627 t1 = findcase(t->left, cp);
2629 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2630 rv = execute(t1, pin, pout, 0);
2631 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2640 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2648 rv = execute(t1, pin, pout, 0);
2661 if (interactive && intr) {
2672 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2676 typedef int (*builtin_func_ptr)(struct op *);
2678 static builtin_func_ptr inbuilt(const char *s)
2680 const struct builtincmd *bp;
2682 for (bp = builtincmds; bp->name; bp++)
2683 if (strcmp(bp->name, s) == 0)
2684 return bp->builtinfunc;
2688 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2692 builtin_func_ptr bltin = NULL;
2694 const char *cp = NULL;
2695 struct ioword **iopp;
2705 struct brkcon *hbrklist;
2709 /* Avoid longjmp clobbering */
2719 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2721 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2722 ((t->words == NULL) ? "NULL" : t->words[0])));
2726 if (t->type == TCOM) {
2727 while (*wp++ != NULL)
2731 /* strip all initial assignments */
2732 /* not correct wrt PATH=yyy command etc */
2734 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2736 echo(cp ? wp : owp);
2739 if (cp == NULL && t->ioact == NULL) {
2740 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2742 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2743 return setstatus(0);
2746 bltin = inbuilt(cp);
2753 DBGPRINTF(("FORKEXEC: bltin %p, f&FEXEC 0x%x, owp %p\n", bltin,
2756 if (!bltin && (f & FEXEC) == 0) {
2757 /* Save values in case the child process alters them */
2761 hinteractive = interactive;
2766 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2771 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2775 if (newpid > 0) { /* Parent */
2776 /* Restore values */
2780 interactive = hinteractive;
2786 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2790 DBGPRINTF(("FORKEXEC: child process, bltin=%p\n", bltin));
2793 signal(SIGINT, SIG_IGN);
2794 signal(SIGQUIT, SIG_IGN);
2805 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2811 * explicitly pass pin[0] and pout[1] to builtins
2812 * instead of making them rely on fd 0/1,
2813 * and do not xmove_fd(pin[0]/pout[1]) below if bltin != NULL.
2815 if ((pin || pout) && bltin && bltin != doexec) {
2816 err("piping to/from shell builtins not yet done");
2824 xmove_fd(pin[0], 0);
2829 xmove_fd(pout[1], 1);
2836 if (bltin && bltin != doexec) {
2838 err(": cannot redirect shell command");
2844 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2845 /* system-detected error */
2853 i = setstatus(bltin(t));
2856 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2857 /* Builtins in pipes ("ls /dev/null | cd"):
2858 * here "cd" (which is not a child) will return to main msh,
2859 * and we will read from ls's output as if it is our next command!
2860 * Result: "/dev/null: cannot execute"
2861 * and then we reach EOF on stdin and exit.
2862 * See above for possible way to fix this.
2867 /* should use FIOCEXCL */
2868 for (i = FDBASE; i < NOFILE; i++)
2871 signal(SIGINT, SIG_DFL);
2872 signal(SIGQUIT, SIG_DFL);
2875 if (t->type == TPAREN)
2876 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2880 cp = rexecve(wp[0], wp, makenv(0, NULL));
2887 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2895 * 0< 1> are ignored as required
2898 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2904 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2907 if (iop->io_unit == IODEFAULT) /* take default */
2908 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2910 if (pipein && iop->io_unit == 0)
2913 if (pipeout && iop->io_unit == 1)
2916 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2917 if ((iop->io_flag & IOHERE) == 0) {
2918 cp = iop->io_name; /* huh?? */
2919 cp = evalstr(cp, DOSUB | DOTRIM);
2924 if (iop->io_flag & IODUP) {
2925 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2927 err(": illegal >& argument");
2931 iop->io_flag = IOCLOSE;
2932 iop->io_flag &= ~(IOREAD | IOWRITE);
2934 switch (iop->io_flag) {
2936 u = open(cp, O_RDONLY);
2940 case IOHERE | IOXHERE:
2941 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2942 cp = (char*)"here file";
2945 case IOWRITE | IOCAT:
2946 u = open(cp, O_WRONLY);
2948 lseek(u, (long) 0, SEEK_END);
2952 u = creat(cp, 0666);
2956 u = dup2(*cp - '0', iop->io_unit);
2960 close(iop->io_unit);
2969 if (u != iop->io_unit) {
2970 dup2(u, iop->io_unit);
2977 * Enter a new loop level (marked for break/continue).
2979 static void brkset(struct brkcon *bc)
2981 bc->nextlev = brklist;
2986 * Wait for the last process created.
2987 * Print a message for each process found
2988 * that was killed by a signal.
2989 * Ignore interrupt signals while waiting
2990 * unless `canintr' is true.
2992 static int waitfor(int lastpid, int canintr)
2996 int oheedint = heedint;
3003 if (errno != EINTR || canintr)
3008 if (rv < ARRAY_SIZE(signame)) {
3009 if (signame[rv] != NULL) {
3010 if (pid != lastpid) {
3017 if (pid != lastpid) {
3026 prs(" - core dumped");
3027 if (rv >= ARRAY_SIZE(signame) || signame[rv])
3033 } while (pid != lastpid);
3048 static int setstatus(int s)
3051 setval(lookup("?"), putn(s));
3056 * PATH-searching interface to execve.
3057 * If getenv("PATH") were kept up-to-date,
3058 * execvp might be used.
3060 static const char *rexecve(char *c, char **v, char **envp)
3068 if (ENABLE_FEATURE_SH_STANDALONE) {
3069 if (find_applet_by_name(name) >= 0) {
3070 /* We have to exec here since we vforked. Running
3071 * run_applet_and_exit() won't work and bad things
3073 execve(bb_busybox_exec_path, v, envp);
3077 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3079 sp = any('/', c) ? "" : path->value;
3080 asis = (*sp == '\0');
3081 while (asis || *sp != '\0') {
3083 tp = global_env.linep;
3084 for (; *sp != '\0'; tp++) {
3087 asis = (*sp == '\0');
3091 if (tp != global_env.linep)
3093 for (i = 0; (*tp++ = c[i++]) != '\0';);
3095 DBGPRINTF3(("REXECVE: global_env.linep is %s\n", global_env.linep));
3097 execve(global_env.linep, v, envp);
3101 *v = global_env.linep;
3103 *v = global_env.linep;
3104 execve(DEFAULT_SHELL, v, envp);
3109 return (char *) bb_msg_memory_exhausted;
3112 return "argument list too long";
3115 return errno == ENOENT ? "not found" : "cannot execute";
3119 * Run the command produced by generator `f'
3120 * applied to stream `arg'.
3122 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3125 struct wdblock *swdlist;
3126 struct wdblock *siolist;
3132 /* Avoid longjmp clobbering */
3136 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3137 areanum, outtree, failpt));
3147 if (newenv(setjmp(errpt)) == 0) {
3151 global_env.iobase = global_env.iop;
3154 if (setjmp(failpt) == 0 && yyparse() == 0)
3155 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3158 DBGPRINTF(("RUN: error from newenv()!\n"));
3165 freearea(areanum--);
3170 /* -------- do.c -------- */
3173 * built-in commands: doX
3176 static int dohelp(struct op *t)
3179 const struct builtincmd *x;
3181 puts("\nBuilt-in commands:\n"
3182 "-------------------");
3187 col += printf("%c%s", ((col == 0) ? '\t' : ' '), x->name);
3194 #if ENABLE_FEATURE_SH_STANDALONE
3196 const char *applet = applet_names;
3199 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applet);
3204 applet += strlen(applet) + 1;
3209 return EXIT_SUCCESS;
3212 static int dolabel(struct op *t)
3217 static int dochdir(struct op *t)
3219 const char *cp, *er;
3223 cp = homedir->value;
3226 er = ": no home directory";
3231 er = ": bad directory";
3233 prs(cp != NULL ? cp : "cd");
3238 static int doshift(struct op *t)
3242 n = t->words[1] ? getn(t->words[1]) : 1;
3244 err("nothing to shift");
3250 setval(lookup("#"), putn(dolc));
3255 * execute login and newgrp directly
3257 static int dologin(struct op *t)
3262 signal(SIGINT, SIG_DFL);
3263 signal(SIGQUIT, SIG_DFL);
3265 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3272 static int doumask(struct op *t)
3281 for (n = 3 * 4; (n -= 3) >= 0;)
3282 fputc('0' + ((i >> n) & 07), stderr);
3283 fputc('\n', stderr);
3285 for (n = 0; *cp >= '0' && *cp <= '7'; cp++)
3286 n = n * 8 + (*cp - '0');
3292 static int doexec(struct op *t)
3299 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3305 if (setjmp(failpt) == 0)
3306 execute(t, NOPIPE, NOPIPE, FEXEC);
3312 static int dodot(struct op *t)
3320 DBGPRINTF(("DODOT: enter, t=%p, tleft %p, tright %p, global_env.linep is %s\n",
3321 t, t->left, t->right, ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3325 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3328 DBGPRINTF(("DODOT: cp is %s\n", cp));
3330 sp = any('/', cp) ? ":" : path->value;
3332 DBGPRINTF(("DODOT: sp is %s, global_env.linep is %s\n",
3333 ((sp == NULL) ? "NULL" : sp),
3334 ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3337 tp = global_env.linep;
3338 while (*sp && (*tp = *sp++) != ':')
3340 if (tp != global_env.linep)
3343 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3346 i = open(global_env.linep, O_RDONLY);
3350 DBGPRINTF(("DODOT: remap=%d, exstat=%d, global_env.iofd %d, i %d, global_env.linep is %s\n",
3351 maltmp, exstat, global_env.iofd, i, global_env.linep));
3353 next(maltmp); /* Basically a PUSHIO */
3355 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3367 static int dowait(struct op *t)
3379 setstatus(waitfor(i, 1));
3383 static int doread(struct op *t)
3389 if (t->words[1] == NULL) {
3390 err("Usage: read name ...");
3393 for (wp = t->words + 1; *wp; wp++) {
3394 for (cp = global_env.linep; !nl && cp < elinep - 1; cp++) {
3395 nb = read(0, cp, sizeof(*cp));
3396 if (nb != sizeof(*cp))
3399 if (nl || (wp[1] && any(*cp, ifs->value)))
3405 setval(lookup(*wp), global_env.linep);
3410 static int doeval(struct op *t)
3412 return RUN(awordlist, t->words + 1, wdchar);
3415 static int dotrap(struct op *t)
3420 if (t->words[1] == NULL) {
3421 for (i = 0; i <= _NSIG; i++)
3430 resetsig = isdigit(*t->words[1]);
3431 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3432 n = getsig(t->words[i]);
3436 if (*t->words[1] != '\0') {
3437 trap[n] = strsave(t->words[1], 0);
3446 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3454 static int getsig(char *s)
3459 if (n < 0 || n > _NSIG) {
3460 err("trap: bad signal number");
3466 static void setsig(int n, sighandler_t f)
3470 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3476 static int getn(char *as)
3487 for (n = 0; isdigit(*s); s++)
3488 n = (n * 10) + (*s - '0');
3491 err(": bad number");
3496 static int dobreak(struct op *t)
3498 return brkcontin(t->words[1], 1);
3501 static int docontinue(struct op *t)
3503 return brkcontin(t->words[1], 0);
3506 static int brkcontin(char *cp, int val)
3511 nl = cp == NULL ? 1 : getn(cp);
3518 brklist = bc->nextlev;
3521 err("bad break/continue level");
3525 longjmp(bc->brkpt, 1);
3529 static int doexit(struct op *t)
3536 setstatus(getn(cp));
3538 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3545 static int doexport(struct op *t)
3547 rdexp(t->words + 1, export, EXPORT);
3551 static int doreadonly(struct op *t)
3553 rdexp(t->words + 1, ronly, RONLY);
3557 static void rdexp(char **wp, void (*f) (struct var *), int key)
3559 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3560 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3563 for (; *wp != NULL; wp++) {
3564 if (isassign(*wp)) {
3568 for (cp = *wp; *cp != '='; cp++);
3580 static void badid(char *s)
3583 err(": bad identifier");
3586 static int doset(struct op *t)
3594 for (vp = vlist; vp; vp = vp->next)
3595 varput(vp->name, 1);
3599 /* bad: t->words++; */
3600 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3602 FLAG['x'] = FLAG['v'] = 0;
3612 if (*cp >= 'a' && *cp <= 'z')
3621 t->words[0] = dolv[0];
3622 for (n = 1; t->words[n]; n++)
3623 setarea((char *) t->words[n], 0);
3626 setval(lookup("#"), putn(dolc));
3627 setarea((char *) (dolv - 1), 0);
3632 static void varput(char *s, int out)
3634 if (isalnum(*s) || *s == '_') {
3635 write(out, s, strlen(s));
3636 write(out, "\n", 1);
3642 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3643 * This file contains code for the times builtin.
3645 static int dotimes(struct op *t)
3648 long clk_tck = sysconf(_SC_CLK_TCK);
3651 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3652 (int) (buf.tms_utime / clk_tck / 60),
3653 ((double) buf.tms_utime) / clk_tck,
3654 (int) (buf.tms_stime / clk_tck / 60),
3655 ((double) buf.tms_stime) / clk_tck,
3656 (int) (buf.tms_cutime / clk_tck / 60),
3657 ((double) buf.tms_cutime) / clk_tck,
3658 (int) (buf.tms_cstime / clk_tck / 60),
3659 ((double) buf.tms_cstime) / clk_tck);
3664 /* -------- eval.c -------- */
3669 * blank interpretation
3674 static char **eval(char **ap, int f)
3682 /* Avoid longjmp clobbering */
3687 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3693 if (newenv(setjmp(errpt)) == 0) {
3694 while (*ap && isassign(*ap))
3695 expand(*ap++, &wb, f & ~DOGLOB);
3697 for (wf = ap; *wf; wf++) {
3699 expand(*wf, &wb, f & ~DOGLOB);
3702 for (wb = addword((char *) 0, wb); *ap; ap++) {
3703 if (!FLAG['k'] || !isassign(*ap))
3704 expand(*ap, &wb, f & ~DOKEY);
3706 wb = addword((char *) 0, wb);
3712 return gflg ? (char **) NULL : wp;
3717 * Make the exported environment from the exported
3718 * names in the dictionary. Keyword assignments
3719 * will already have been done.
3721 static char **makenv(int all, struct wdblock *wb)
3725 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3727 for (vp = vlist; vp; vp = vp->next)
3728 if (all || vp->status & EXPORT)
3729 wb = addword(vp->name, wb);
3730 wb = addword((char *) 0, wb);
3731 return getwords(wb);
3734 static int expand(const char *cp, struct wdblock **wbp, int f)
3740 /* Avoid longjmp clobbering */
3744 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3751 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3752 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3754 xp = strsave(cp, areanum);
3757 *wbp = addword(xp, *wbp);
3761 if (newenv(setjmp(errpt)) == 0) {
3762 PUSHIO(aword, cp, strchar);
3763 global_env.iobase = global_env.iop;
3764 while ((xp = blank(f)) && gflg == 0) {
3765 global_env.linep = xp;
3766 xp = strsave(xp, areanum);
3767 if ((f & DOGLOB) == 0) {
3770 *wbp = addword(xp, *wbp);
3772 *wbp = glob(xp, *wbp);
3780 static char *evalstr(char *cp, int f)
3784 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3787 if (expand(cp, &wb, f)) {
3788 if (wb == NULL || wb->w_nword == 0
3789 || (cp = wb->w_words[0]) == NULL
3791 // TODO: I suspect that
3792 // char *evalstr(char *cp, int f) is actually
3793 // const char *evalstr(const char *cp, int f)!
3804 * Blank interpretation and quoting
3806 static char *blank(int f)
3810 int scanequals, foundequals;
3812 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3814 sp = global_env.linep;
3815 scanequals = f & DOKEY;
3819 c = subgetc('"', foundequals);
3822 if (sp == global_env.linep)
3824 *global_env.linep++ = 0;
3828 if (f & DOBLANK && any(c, ifs->value))
3837 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3840 if (c == '\'' || !any(c, "$`\""))
3842 *global_env.linep++ = c;
3847 if (!isalpha(c) && c != '_')
3850 c = subgetc('"', foundequals);
3852 f & (DOBLANK && any(c, ifs->value)) ||
3853 (!INSUB() && any(c, "\"'"))) {
3864 } else if (!isalnum(c) && c != '_')
3867 *global_env.linep++ = c;
3869 *global_env.linep++ = 0;
3874 * Get characters, substituting for ` and $
3876 static int subgetc(char ec, int quoted)
3880 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3884 if (!INSUB() && ec != '\'') {
3886 if (grave(quoted) == 0)
3888 global_env.iop->task = XGRAVE;
3894 global_env.iop->task = XDOLL;
3903 * Prepare to generate the string returned by ${} substitution.
3905 static int dollar(int quoted)
3910 char *s, c, *cp = NULL;
3913 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3916 s = global_env.linep;
3918 *global_env.linep++ = c;
3919 if (isalpha(c) || c == '_') {
3920 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3921 if (global_env.linep < elinep)
3922 *global_env.linep++ = c;
3927 oiop = global_env.iop;
3928 otask = global_env.iop->task;
3930 global_env.iop->task = XOTHER;
3931 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3932 if (global_env.linep < elinep)
3933 *global_env.linep++ = c;
3934 if (oiop == global_env.iop)
3935 global_env.iop->task = otask;
3942 if (global_env.linep >= elinep) {
3943 err("string in ${} too long");
3945 global_env.linep -= 10;
3947 *global_env.linep = 0;
3949 for (cp = s + 1; *cp; cp++)
3950 if (any(*cp, "=-+?")) {
3955 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3957 /* currently this does not distinguish $* and $@ */
3958 /* should check dollar */
3959 global_env.linep = s;
3960 PUSHIO(awordlist, dolv + 1, dolchar);
3962 } else { /* trap the nasty ${=} */
3973 err("cannot use ${...=...} with $n");
3982 dolp = strsave(cp, areanum);
3987 prs("missing value for ");
3994 } else if (c == '+')
3995 dolp = strsave(cp, areanum);
3996 if (FLAG['u'] && dolp == null) {
3997 prs("unset variable: ");
4001 global_env.linep = s;
4002 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4007 * Run the command in `...` and read its output.
4010 static int grave(int quoted)
4012 /* moved to G: static char child_cmd[LINELIM]; */
4023 char *argument_list[4];
4024 struct wdblock *wb = NULL;
4027 /* Avoid longjmp clobbering */
4031 for (cp = global_env.iop->argp->aword; *cp != '`'; cp++) {
4033 err("no closing `");
4038 /* string copy with dollar expansion */
4039 src = global_env.iop->argp->aword;
4044 while ((*src != '`') && (count < LINELIM)) {
4049 if (*src == '$' && !ignore && !ignore_once) {
4051 /* moved to G to reduce stack usage
4052 char var_name[LINELIM];
4053 char alt_value[LINELIM];
4055 #define var_name (G.grave__var_name)
4056 #define alt_value (G.grave__alt_value)
4069 var_name[var_index++] = *src++;
4070 while (isalnum(*src) || *src=='_')
4071 var_name[var_index++] = *src++;
4072 var_name[var_index] = 0;
4085 err("unclosed ${\n");
4090 while (*src && (*src != '}')) {
4091 alt_value[alt_index++] = *src++;
4093 alt_value[alt_index] = 0;
4095 err("unclosed ${\n");
4102 if (isalpha(*var_name)) {
4103 /* let subshell handle it instead */
4105 char *namep = var_name;
4113 char *altp = alt_value;
4121 wb = addword(lookup(var_name)->name, wb);
4125 vp = lookup(var_name);
4126 if (vp->value != null)
4127 value = (operator == '+') ?
4128 alt_value : vp->value;
4129 else if (operator == '?') {
4132 } else if (alt_index && (operator != '+')) {
4134 if (operator == '=')
4139 while (*value && (count < LINELIM)) {
4154 if (openpipe(pf) < 0)
4157 while ((i = vfork()) == -1 && errno == EAGAIN);
4159 DBGPRINTF3(("GRAVE: i is %p\n", io));
4163 err((char *) bb_msg_memory_exhausted);
4167 waitpid(i, NULL, 0); // safe_waitpid?
4168 global_env.iop->argp->aword = ++cp;
4170 PUSHIO(afile, remap(pf[0]),
4171 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4174 /* allow trapped signals */
4175 /* XXX - Maybe this signal stuff should go as well? */
4176 for (j = 0; j <= _NSIG; j++)
4177 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4180 /* Testcase where below checks are needed:
4181 * close stdout & run this script:
4189 argument_list[0] = (char *) DEFAULT_SHELL;
4190 argument_list[1] = (char *) "-c";
4191 argument_list[2] = child_cmd;
4192 argument_list[3] = NULL;
4194 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4195 prs(argument_list[0]);
4202 static char *unquote(char *as)
4213 /* -------- glob.c -------- */
4219 #define scopy(x) strsave((x), areanum)
4221 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4223 static struct wdblock *cl, *nl;
4224 static const char spcl[] ALIGN1= "[?*";
4226 static struct wdblock *glob(char *cp, struct wdblock *wb)
4234 for (pp = cp; *pp; pp++)
4237 else if (!any(*pp & ~QUOTE, spcl))
4240 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4241 nl = newword(cl->w_nword * 2);
4242 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4243 for (pp = cl->w_words[i]; *pp; pp++)
4244 if (any(*pp, spcl)) {
4245 globname(cl->w_words[i], pp);
4249 nl = addword(scopy(cl->w_words[i]), nl);
4251 for (i = 0; i < cl->w_nword; i++)
4252 DELETE(cl->w_words[i]);
4255 for (i = 0; i < cl->w_nword; i++)
4256 unquote(cl->w_words[i]);
4257 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4259 for (i = 0; i < cl->w_nword; i++)
4260 wb = addword(cl->w_words[i], wb);
4265 wb = addword(unquote(cp), wb);
4269 static void globname(char *we, char *pp)
4272 char *name, *gp, *dp;
4276 char dname[NAME_MAX + 1];
4279 for (np = we; np != pp; pp--)
4282 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4286 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4295 dname[NAME_MAX] = '\0';
4296 while ((de = readdir(dirp)) != NULL) {
4297 /* XXX Hmmm... What this could be? (abial) */
4299 if (ent[j].d_ino == 0)
4302 strncpy(dname, de->d_name, NAME_MAX);
4303 if (dname[0] == '.')
4306 for (k = 0; k < NAME_MAX; k++)
4307 if (any(dname[k], spcl))
4309 if (gmatch(dname, gp)) {
4310 name = generate(we, pp, dname, np);
4311 if (*np && !anys(np, spcl)) {
4312 if (stat(name, &dbuf)) {
4317 nl = addword(name, nl);
4326 * generate a pathname as below.
4327 * start..end1 / middle end
4328 * the slashes come for free
4330 static char *generate(char *start1, char *end1, char *middle, char *end)
4335 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4336 for (xp = start1; xp != end1;)
4338 for (xp = middle; (*op++ = *xp++) != '\0';);
4340 for (xp = end; (*op++ = *xp++) != '\0';);
4344 static int anyspcl(struct wdblock *wb)
4350 for (i = 0; i < wb->w_nword; i++)
4351 if (anys(spcl, *wd++))
4356 static int xstrcmp(char *p1, char *p2)
4358 return strcmp(*(char **) p1, *(char **) p2);
4362 /* -------- word.c -------- */
4364 static struct wdblock *newword(int nw)
4368 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4374 static struct wdblock *addword(char *wd, struct wdblock *wb)
4376 struct wdblock *wb2;
4380 wb = newword(NSTART);
4382 if (nw >= wb->w_bsize) {
4383 wb2 = newword(nw * 2);
4384 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4385 nw * sizeof(char *));
4390 wb->w_words[wb->w_nword++] = wd;
4394 static char **getwords(struct wdblock *wb)
4401 if (wb->w_nword == 0) {
4405 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4406 memcpy((char *) wd, (char *) wb->w_words, nb);
4407 DELETE(wb); /* perhaps should done by caller */
4411 static int (*func) (char *, char *);
4414 static void glob3(char *i, char *j, char *k)
4416 char *index1, *index2, *index3;
4426 *index1++ = *index3;
4427 *index3++ = *index2;
4432 static void glob2(char *i, char *j)
4434 char *index1, *index2, c;
4442 *index1++ = *index2;
4447 static void glob1(char *base, char *lim)
4458 n = (int) (lim - base);
4461 n = v2 * (n / (2 * v2));
4462 hptr = lptr = base + n;
4467 c = (*func) (i, lptr);
4481 c = (*func) (hptr, j);
4505 if (lptr - base >= lim - hptr) {
4506 glob1(hptr + v2, lim);
4521 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4525 glob1(a0, a0 + a1 * a2);
4529 /* -------- io.c -------- */
4535 static int my_getc(int ec)
4539 if (global_env.linep > elinep) {
4540 while ((c = readc()) != '\n' && c);
4541 err("input line too long");
4546 if ((ec != '\'') && (ec != '`') && (global_env.iop->task != XGRAVE)) {
4549 if (c == '\n' && ec != '\"')
4557 static void unget(int c)
4559 if (global_env.iop >= global_env.iobase)
4560 global_env.iop->peekc = c;
4563 static int eofc(void)
4565 return global_env.iop < global_env.iobase || (global_env.iop->peekc == 0 && global_env.iop->prev == 0);
4568 static int readc(void)
4572 RCPRINTF(("READC: global_env.iop %p, global_env.iobase %p\n", global_env.iop, global_env.iobase));
4574 for (; global_env.iop >= global_env.iobase; global_env.iop--) {
4575 RCPRINTF(("READC: global_env.iop %p, peekc 0x%x\n", global_env.iop, global_env.iop->peekc));
4576 c = global_env.iop->peekc;
4578 global_env.iop->peekc = 0;
4581 if (global_env.iop->prev != 0) {
4582 c = (*global_env.iop->iofn)(global_env.iop->argp, global_env.iop);
4588 if (global_env.iop == iostack)
4590 global_env.iop->prev = c;
4591 return global_env.iop->prev;
4593 if (global_env.iop->task == XIO && global_env.iop->prev != '\n') {
4594 global_env.iop->prev = 0;
4595 if (global_env.iop == iostack)
4600 if (global_env.iop->task == XIO) {
4602 global_env.iop->prev = 0;
4603 return global_env.iop->prev;
4605 if (interactive && global_env.iop == iostack + 1) {
4606 #if ENABLE_FEATURE_EDITING
4607 current_prompt = prompt->value;
4615 if (global_env.iop >= iostack) {
4616 RCPRINTF(("READC: return 0, global_env.iop %p\n", global_env.iop));
4620 DBGPRINTF(("READC: leave()...\n"));
4626 static void ioecho(char c)
4629 write(2, &c, sizeof c);
4632 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4634 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, global_env.iop %p\n", argp,
4635 argp->afid, global_env.iop));
4637 /* Set env ptr for io source to next array spot and check for array overflow */
4638 if (++global_env.iop >= &iostack[NPUSH]) {
4640 err("Shell input nested too deeply");
4645 /* We did not overflow the NPUSH array spots so setup data structs */
4647 global_env.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4649 if (argp->afid != AFID_NOBUF)
4650 global_env.iop->argp = argp;
4653 global_env.iop->argp = ioargstack + (global_env.iop - iostack); /* MAL - index into stack */
4654 *global_env.iop->argp = *argp; /* copy data from temp area into stack spot */
4656 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4658 if (global_env.iop == &iostack[0])
4659 global_env.iop->argp->afbuf = &mainbuf;
4661 global_env.iop->argp->afbuf = &sharedbuf;
4663 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4664 /* This line appears to be active when running scripts from command line */
4665 if ((isatty(global_env.iop->argp->afile) == 0)
4666 && (global_env.iop == &iostack[0]
4667 || lseek(global_env.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4668 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4669 bufid = AFID_ID; /* AFID_ID = 0 */
4671 global_env.iop->argp->afid = bufid; /* assign buffer id */
4674 DBGPRINTF(("PUSHIO: iostack %p, global_env.iop %p, afbuf %p\n",
4675 iostack, global_env.iop, global_env.iop->argp->afbuf));
4676 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, global_env.iop %p\n",
4677 &mainbuf, &sharedbuf, bufid, global_env.iop));
4681 global_env.iop->prev = ~'\n';
4682 global_env.iop->peekc = 0;
4683 global_env.iop->xchar = 0;
4684 global_env.iop->nlcount = 0;
4686 if (fn == filechar || fn == linechar)
4687 global_env.iop->task = XIO;
4688 else if (fn == (int (*)(struct ioarg *)) gravechar
4689 || fn == (int (*)(struct ioarg *)) qgravechar)
4690 global_env.iop->task = XGRAVE;
4692 global_env.iop->task = XOTHER;
4695 static struct io *setbase(struct io *ip)
4699 xp = global_env.iobase;
4700 global_env.iobase = ip;
4705 * Input generating functions
4709 * Produce the characters of a string, then a newline, then EOF.
4711 static int nlchar(struct ioarg *ap)
4715 if (ap->aword == NULL)
4726 * Given a list of words, produce the characters
4727 * in them, with a space after each word.
4729 static int wdchar(struct ioarg *ap)
4744 ap->awordlist = NULL;
4749 * Return the characters of a list of words,
4750 * producing a space between them.
4752 static int dolchar(struct ioarg *ap)
4756 wp = *ap->awordlist++;
4758 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4764 static int xxchar(struct ioarg *ap)
4768 if (ap->aword == NULL)
4779 * Produce the characters from a single word (string).
4781 static int strchar(struct ioarg *ap)
4783 if (ap->aword == NULL)
4785 return *ap->aword++;
4789 * Produce quoted characters from a single word (string).
4791 static int qstrchar(struct ioarg *ap)
4795 if (ap->aword == NULL)
4804 * Return the characters from a file.
4806 static int filechar(struct ioarg *ap)
4810 struct iobuf *bp = ap->afbuf;
4812 if (ap->afid != AFID_NOBUF) {
4813 i = (ap->afid != bp->id);
4814 if (i || bp->bufp == bp->ebufp) {
4816 lseek(ap->afile, ap->afpos, SEEK_SET);
4818 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4826 bp->ebufp = bp->bufp + i;
4830 return *bp->bufp++ & 0177;
4832 #if ENABLE_FEATURE_EDITING
4833 if (interactive && isatty(ap->afile)) {
4834 /* moved to G: static char filechar_cmdbuf[BUFSIZ]; */
4835 static int position = 0, size = 0;
4837 while (size == 0 || position >= size) {
4838 size = read_line_input(current_prompt, filechar_cmdbuf, BUFSIZ, line_input_state);
4839 if (size < 0) /* Error/EOF */
4842 /* if Ctrl-C, size == 0 and loop will repeat */
4844 c = filechar_cmdbuf[position];
4849 i = safe_read(ap->afile, &c, sizeof(c));
4850 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4854 * Return the characters from a here temp file.
4856 static int herechar(struct ioarg *ap)
4860 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4868 * Return the characters produced by a process (`...`).
4869 * Quote them if required, and remove any trailing newline characters.
4871 static int gravechar(struct ioarg *ap, struct io *iop)
4875 c = qgravechar(ap, iop) & ~QUOTE;
4881 static int qgravechar(struct ioarg *ap, struct io *iop)
4885 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4890 return '\n' | QUOTE;
4894 } else if ((c = filechar(ap)) == '\n') {
4896 while ((c = filechar(ap)) == '\n')
4904 return c != 0 ? c | QUOTE : 0;
4908 * Return a single command (usually the first line) from a file.
4910 static int linechar(struct ioarg *ap)
4918 ap->afile = -1; /* illegal value */
4925 * remap fd into Shell's fd space
4927 static int remap(int fd)
4933 DBGPRINTF(("REMAP: fd=%d, global_env.iofd=%d\n", fd, global_env.iofd));
4935 if (fd < global_env.iofd) {
4936 for (i = 0; i < NOFILE; i++)
4943 } while (fd >= 0 && fd < global_env.iofd);
4945 for (i = 0; i < NOFILE; i++)
4950 err("too many files open in shell");
4956 static int openpipe(int *pv)
4962 err("can't create pipe - try again");
4966 static void closepipe(int *pv)
4975 /* -------- here.c -------- */
4981 static void markhere(char *s, struct ioword *iop)
4983 struct here *h, *lh;
4985 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4987 h = (struct here *) space(sizeof(struct here));
4991 h->h_tag = evalstr(s, DOSUB);
5001 for (lh = inhere; lh != NULL; lh = lh->h_next) {
5002 if (lh->h_next == 0) {
5008 iop->io_flag |= IOHERE | IOXHERE;
5009 for (s = h->h_tag; *s; s++) {
5011 iop->io_flag &= ~IOXHERE;
5015 h->h_dosub = iop->io_flag & IOXHERE;
5018 static void gethere(void)
5020 struct here *h, *hp;
5022 DBGPRINTF7(("GETHERE: enter...\n"));
5024 /* Scan here files first leaving inhere list in place */
5025 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5026 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5028 /* Make inhere list active - keep list intact for scraphere */
5030 hp->h_next = acthere;
5036 static void readhere(char **name, char *s, int ec)
5039 char tname[30] = ".msh_XXXXXX";
5042 char myline[LINELIM + 1];
5045 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5047 tf = mkstemp(tname);
5051 *name = strsave(tname, areanum);
5053 if (newenv(setjmp(errpt)) != 0)
5056 pushio(global_env.iop->argp, (int (*)(struct ioarg *)) global_env.iop->iofn);
5057 global_env.iobase = global_env.iop;
5059 if (interactive && global_env.iop <= iostack) {
5060 #if ENABLE_FEATURE_EDITING
5061 current_prompt = cprompt->value;
5063 prs(cprompt->value);
5067 while ((c = my_getc(ec)) != '\n' && c) {
5070 if (thenext >= &myline[LINELIM]) {
5077 if (strcmp(s, myline) == 0 || c == 0)
5080 write(tf, myline, (int) (thenext - myline));
5083 prs("here document `");
5093 * open here temp file.
5094 * if unquoted here, expand here temp file into second temp file.
5096 static int herein(char *hname, int xdoll)
5102 /* Avoid longjmp clobbering */
5108 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5110 hf = open(hname, O_RDONLY);
5116 char tname[30] = ".msh_XXXXXX";
5119 tf = mkstemp(tname);
5123 if (newenv(setjmp(errpt)) == 0) {
5124 PUSHIO(afile, hf, herechar);
5125 setbase(global_env.iop);
5126 while ((c = subgetc(0, 0)) != 0) {
5128 write(tf, &c, sizeof c);
5134 tf = open(tname, O_RDONLY);
5141 static void scraphere(void)
5145 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5147 for (h = inhere; h != NULL; h = h->h_next) {
5148 if (h->h_iop && h->h_iop->io_name)
5149 unlink(h->h_iop->io_name);
5154 /* unlink here temp files before a freearea(area) */
5155 static void freehere(int area)
5157 struct here *h, *hl;
5159 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5162 for (h = acthere; h != NULL; h = h->h_next)
5163 if (getarea((char *) h) >= area) {
5164 if (h->h_iop->io_name != NULL)
5165 unlink(h->h_iop->io_name);
5167 acthere = h->h_next;
5169 hl->h_next = h->h_next;
5175 /* -------- sh.c -------- */
5180 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5181 int msh_main(int argc, char **argv)
5187 int (*iof) (struct ioarg *);
5191 sharedbuf.id = AFID_NOBUF;
5192 mainbuf.id = AFID_NOBUF;
5193 elinep = line + sizeof(line) - 5;
5195 #if ENABLE_FEATURE_EDITING
5196 line_input_state = new_line_input_t(FOR_SHELL);
5199 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5205 assign(*ap++, !COPYV);
5206 for (ap = environ; *ap;)
5207 export(lookup(*ap++));
5212 shell = lookup("SHELL");
5213 if (shell->value == null)
5214 setval(shell, (char *)DEFAULT_SHELL);
5217 homedir = lookup("HOME");
5218 if (homedir->value == null)
5219 setval(homedir, "/");
5222 setval(lookup("$"), putn(getpid()));
5224 path = lookup("PATH");
5225 if (path->value == null) {
5226 /* Can be merged with same string elsewhere in bbox */
5228 setval(path, bb_default_root_path);
5230 setval(path, bb_default_path);
5234 ifs = lookup("IFS");
5235 if (ifs->value == null)
5236 setval(ifs, " \t\n");
5239 mshdbg_var = lookup("MSHDEBUG");
5240 if (mshdbg_var->value == null)
5241 setval(mshdbg_var, "0");
5244 prompt = lookup("PS1");
5245 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5246 if (prompt->value == null)
5248 setval(prompt, DEFAULT_USER_PROMPT);
5249 if (geteuid() == 0) {
5250 setval(prompt, DEFAULT_ROOT_PROMPT);
5251 prompt->status &= ~EXPORT;
5253 cprompt = lookup("PS2");
5254 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5255 if (cprompt->value == null)
5257 setval(cprompt, "> ");
5263 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5264 for (s = argv[0] + 1; *s; s++)
5267 prompt->status &= ~EXPORT;
5268 cprompt->status &= ~EXPORT;
5270 setval(cprompt, "");
5273 PUSHIO(aword, *++argv, iof = nlchar);
5281 /* standard input */
5285 prompt->status &= ~EXPORT;
5293 if (*s >= 'a' && *s <= 'z')
5301 if (iof == filechar && --argc > 0) {
5303 setval(cprompt, "");
5304 prompt->status &= ~EXPORT;
5305 cprompt->status &= ~EXPORT;
5307 /* Shell is non-interactive, activate printf-based debug */
5309 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5313 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5317 exit(1); /* Exit on error */
5323 /* This won't be true if PUSHIO has been called, say from newfile() above */
5324 if (global_env.iop < iostack) {
5325 PUSHIO(afile, 0, iof);
5326 if (isatty(0) && isatty(1) && !cflag) {
5328 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5330 printf("\n\n%s built-in shell (msh with debug)\n", bb_banner);
5332 printf("\n\n%s built-in shell (msh)\n", bb_banner);
5334 printf("Enter 'help' for a list of built-in commands.\n\n");
5339 signal(SIGQUIT, qflag);
5340 if (name && name[0] == '-') {
5342 f = open(".profile", O_RDONLY);
5345 f = open("/etc/profile", O_RDONLY);
5350 signal(SIGTERM, sig);
5352 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5353 signal(SIGINT, onintr);
5358 for (ap = ++argv; --argc > 0;) {
5360 if (assign(*ap, !COPYV)) {
5361 dolc--; /* keyword */
5367 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5369 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, global_env.iop %p, iostack %p\n", interactive, global_env.iop, iostack));
5372 if (interactive && global_env.iop <= iostack) {
5373 #if ENABLE_FEATURE_EDITING
5374 current_prompt = prompt->value;
5380 /* Ensure that getenv("PATH") stays current */
5381 setenv("PATH", path->value, 1);
5384 DBGPRINTF(("MSH_MAIN: returning.\n"));
5389 * Copyright (c) 1987,1997, Prentice Hall
5390 * All rights reserved.
5392 * Redistribution and use of the MINIX operating system in source and
5393 * binary forms, with or without modification, are permitted provided
5394 * that the following conditions are met:
5396 * Redistributions of source code must retain the above copyright
5397 * notice, this list of conditions and the following disclaimer.
5399 * Redistributions in binary form must reproduce the above
5400 * copyright notice, this list of conditions and the following
5401 * disclaimer in the documentation and/or other materials provided
5402 * with the distribution.
5404 * Neither the name of Prentice Hall nor the names of the software
5405 * authors or contributors may be used to endorse or promote
5406 * products derived from this software without specific prior
5407 * written permission.
5409 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5410 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5411 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5412 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5413 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5414 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5415 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5416 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5417 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5418 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5419 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5420 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.