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 */
87 extern char **environ;
90 /*#define MSHDEBUG 1*/
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 int type; /* operation type, see 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[] = {
249 * actions determining the environment of a process
251 #define FEXEC 1 /* execute without forking */
253 #define AREASIZE (90000)
256 * flags to control evaluation of words
258 #define DOSUB 1 /* interpret $, `, and quotes */
259 #define DOBLANK 2 /* perform blank interpretation */
260 #define DOGLOB 4 /* interpret [?* */
261 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
262 #define DOTRIM 16 /* trim resulting string */
264 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
269 struct brkcon *nextlev;
276 * -k: look for name=value everywhere on command line
278 * -t: exit after reading and executing one command
281 * -u: unset variables net diagnostic
283 static char flags['z' - 'a' + 1] ALIGN1;
284 /* this looks weird, but is OK ... we index FLAG with 'a'...'z' */
285 #define FLAG (flags - 'a')
287 /* moved to G: static char *trap[_NSIG + 1]; */
288 /* moved to G: static char ourtrap[_NSIG + 1]; */
289 static int trapset; /* trap pending */
291 static int yynerrs; /* yacc */
293 /* moved to G: static char line[LINELIM]; */
295 #if ENABLE_FEATURE_EDITING
296 static char *current_prompt;
297 static line_input_t *line_input_state;
304 static const char *rexecve(char *c, char **v, char **envp);
305 static char *evalstr(char *cp, int f);
306 static char *putn(int n);
307 static char *unquote(char *as);
308 static int rlookup(char *n);
309 static struct wdblock *glob(char *cp, struct wdblock *wb);
310 static int my_getc(int ec);
311 static int subgetc(char ec, int quoted);
312 static char **makenv(int all, struct wdblock *wb);
313 static char **eval(char **ap, int f);
314 static int setstatus(int s);
315 static int waitfor(int lastpid, int canintr);
317 static void onintr(int s); /* SIGINT handler */
319 static int newenv(int f);
320 static void quitenv(void);
321 static void next(int f);
322 static void setdash(void);
323 static void onecommand(void);
324 static void runtrap(int i);
327 /* -------- area stuff -------- */
329 #define REGSIZE sizeof(struct region)
331 /* #define SHRINKBY (64) */
335 #define ALIGN (sizeof(int)-1)
344 /* -------- grammar stuff -------- */
369 /* Added for "." file expansion */
372 #define YYERRCODE 300
375 #define CONTIN 01 /* skip new lines to complete command */
377 static struct op *pipeline(int cf);
378 static struct op *andor(void);
379 static struct op *c_list(void);
380 static int synio(int cf);
381 static void musthave(int c, int cf);
382 static struct op *simple(void);
383 static struct op *nested(int type, int mark);
384 static struct op *command(int cf);
385 static struct op *dogroup(int onlydone);
386 static struct op *thenpart(void);
387 static struct op *elsepart(void);
388 static struct op *caselist(void);
389 static struct op *casepart(void);
390 static char **pattern(void);
391 static char **wordlist(void);
392 static struct op *list(struct op *t1, struct op *t2);
393 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
394 static struct op *newtp(void);
395 static struct op *namelist(struct op *t);
396 static char **copyw(void);
397 static void word(char *cp);
398 static struct ioword **copyio(void);
399 static struct ioword *io(int u, int f, char *cp);
400 static int yylex(int cf);
401 static int collect(int c, int c1);
402 static int dual(int c);
403 static void diag(int ec);
404 static char *tree(unsigned size);
406 /* -------- var.h -------- */
415 #define COPYV 1 /* flag to setval, suggesting copy */
416 #define RONLY 01 /* variable is read-only */
417 #define EXPORT 02 /* variable is to be exported */
418 #define GETCELL 04 /* name & value space was got with getcell */
420 static int yyparse(void);
422 static int execute(struct op *t, int *pin, int *pout, int act);
425 #define AFID_NOBUF (~0)
429 /* -------- io.h -------- */
432 unsigned id; /* buffer id */
433 char buf[512]; /* buffer */
434 char *bufp; /* pointer into buffer */
435 char *ebufp; /* pointer to end of buffer */
438 /* possible arguments to an IO function */
442 int afile; /* file descriptor */
443 unsigned afid; /* buffer id */
444 long afpos; /* file position */
445 struct iobuf *afbuf; /* buffer for this file */
448 /* an input generator's state */
450 int (*iofn) (struct ioarg *, struct io *);
453 char prev; /* previous character read by readc() */
454 char nlcount; /* for `'s */
455 char xchar; /* for `'s */
456 char task; /* reason for pushed IO */
459 #define XOTHER 0 /* none of the below */
460 #define XDOLL 1 /* expanding ${} */
461 #define XGRAVE 2 /* expanding `'s */
462 #define XIO 3 /* file IO */
464 /* in substitution */
465 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
467 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
468 /* moved to G: static struct ioarg ioargstack[NPUSH]; */
469 static struct io iostack[NPUSH];
470 /* moved to G: static struct iobuf sharedbuf = { AFID_NOBUF }; */
471 /* moved to G: static struct iobuf mainbuf = { AFID_NOBUF }; */
472 static unsigned bufid = AFID_ID; /* buffer id counter */
474 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
478 * input generators for IO structure
480 static int nlchar(struct ioarg *ap);
481 static int strchar(struct ioarg *ap);
482 static int qstrchar(struct ioarg *ap);
483 static int filechar(struct ioarg *ap);
484 static int herechar(struct ioarg *ap);
485 static int linechar(struct ioarg *ap);
486 static int gravechar(struct ioarg *ap, struct io *iop);
487 static int qgravechar(struct ioarg *ap, struct io *iop);
488 static int dolchar(struct ioarg *ap);
489 static int wdchar(struct ioarg *ap);
490 static void scraphere(void);
491 static void freehere(int area);
492 static void gethere(void);
493 static void markhere(char *s, struct ioword *iop);
494 static int herein(char *hname, int xdoll);
495 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
498 static int eofc(void);
499 static int readc(void);
500 static void unget(int c);
501 static void ioecho(char c);
507 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
508 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
509 static int remap(int fd);
510 static int openpipe(int *pv);
511 static void closepipe(int *pv);
512 static struct io *setbase(struct io *ip);
514 /* -------- word.h -------- */
516 #define NSTART 16 /* default number of words to allow for initially */
521 /* bounds are arbitrary */
525 static struct wdblock *addword(char *wd, struct wdblock *wb);
526 static struct wdblock *newword(int nw);
527 static char **getwords(struct wdblock *wb);
529 /* -------- misc stuff -------- */
531 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
532 static int iosetup(struct ioword *iop, int pipein, int pipeout);
533 static void brkset(struct brkcon *bc);
534 static int dolabel(struct op *t);
535 static int dohelp(struct op *t);
536 static int dochdir(struct op *t);
537 static int doshift(struct op *t);
538 static int dologin(struct op *t);
539 static int doumask(struct op *t);
540 static int doexec(struct op *t);
541 static int dodot(struct op *t);
542 static int dowait(struct op *t);
543 static int doread(struct op *t);
544 static int doeval(struct op *t);
545 static int dotrap(struct op *t);
546 static int getsig(char *s);
547 static void setsig(int n, sighandler_t f);
548 static int getn(char *as);
549 static int dobreak(struct op *t);
550 static int docontinue(struct op *t);
551 static int brkcontin(char *cp, int val);
552 static int doexit(struct op *t);
553 static int doexport(struct op *t);
554 static int doreadonly(struct op *t);
555 static void rdexp(char **wp, void (*f) (struct var *), int key);
556 static void badid(char *s);
557 static int doset(struct op *t);
558 static void varput(char *s, int out);
559 static int dotimes(struct op *t);
560 static int expand(const char *cp, struct wdblock **wbp, int f);
561 static char *blank(int f);
562 static int dollar(int quoted);
563 static int grave(int quoted);
564 static void globname(char *we, char *pp);
565 static char *generate(char *start1, char *end1, char *middle, char *end);
566 static int anyspcl(struct wdblock *wb);
567 static int xstrcmp(char *p1, char *p2);
568 static void glob0(char *a0, unsigned a1, int a2,
569 int (*a3) (char *, char *));
570 static void readhere(char **name, char *s, int ec);
571 static int xxchar(struct ioarg *ap);
576 struct ioword *h_iop;
580 static const char *const signame[] = {
583 NULL, /* interrupt */
585 "Illegal instruction",
589 "Floating Point Exception",
594 NULL, /* broken pipe */
604 static const struct res restab[] = {
629 int (*builtinfunc)(struct op *t);
631 static const struct builtincmd builtincmds[] = {
634 { "break" , dobreak },
636 { "continue", docontinue },
640 { "export" , doexport },
642 { "login" , dologin },
643 { "newgrp" , dologin },
645 { "readonly", doreadonly },
647 { "shift" , doshift },
648 { "times" , dotimes },
650 { "umask" , doumask },
655 static struct op *scantree(struct op *);
656 static struct op *dowholefile(int, int);
664 static int interactive; /* Is this an interactive shell */
666 static int multiline; /* \n changed to ; */
667 static struct op *outtree; /* result from parser */
670 static struct brkcon *brklist;
672 static struct wdblock *wdlist;
673 static struct wdblock *iolist;
676 static struct var *mshdbg_var;
678 static struct var *vlist; /* dictionary */
679 static struct var *homedir; /* home directory */
680 static struct var *prompt; /* main prompt */
681 static struct var *cprompt; /* continuation prompt */
682 static struct var *path; /* search path for commands */
683 static struct var *shell; /* shell to interpret command files */
684 static struct var *ifs; /* field separators */
686 static int areanum; /* current allocation area */
687 static int intr; /* interrupt pending */
689 static char *null = (char*)""; /* null value for variable */
690 static int heedint = 1; /* heed interrupt signals */
691 static void (*qflag)(int) = SIG_IGN;
695 static int iounit = IODEFAULT;
696 static YYSTYPE yylval;
697 static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
699 static struct here *inhere; /* list of hear docs while parsing */
700 static struct here *acthere; /* list of active here documents */
701 static struct region *areabot; /* bottom of area */
702 static struct region *areatop; /* top of area */
703 static struct region *areanxt; /* starting point of scan */
705 static void *brkaddr;
708 * parsing & execution environment
714 xint *errpt; /* void * */
719 static struct env e = {
720 NULL /* set to line in main() */, /* linep: char ptr */
721 iostack, /* iobase: struct io ptr */
722 iostack - 1, /* iop: struct io ptr */
723 (xint *) NULL, /* errpt: void ptr for errors? */
724 FDBASE, /* iofd: file desc */
725 (struct env *) NULL /* oenv: struct env ptr */
730 char ourtrap[_NSIG + 1];
731 char *trap[_NSIG + 1];
732 struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
733 struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
734 struct ioarg ioargstack[NPUSH];
735 char filechar_cmdbuf[BUFSIZ];
737 char child_cmd[LINELIM];
739 char grave__var_name[LINELIM];
740 char grave__alt_value[LINELIM];
743 #define G (*ptr_to_globals)
744 #define ourtrap (G.ourtrap )
745 #define trap (G.trap )
746 #define sharedbuf (G.sharedbuf )
747 #define mainbuf (G.mainbuf )
748 #define ioargstack (G.ioargstack )
749 #define filechar_cmdbuf (G.filechar_cmdbuf)
750 #define line (G.line )
751 #define child_cmd (G.child_cmd )
752 #define INIT_G() do { \
753 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
758 void print_t(struct op *t)
760 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
761 T_CMD_NAMES[t->type], t->words, t->ioact));
764 DBGPRINTF(("T: W1: %s", t->words[0]));
768 void print_tree(struct op *head)
771 DBGPRINTF(("PRINT_TREE: no tree\n"));
775 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
779 print_tree(head->left);
782 print_tree(head->right);
784 #endif /* MSHDEBUG */
790 static void prs(const char *s)
793 write(2, s, strlen(s));
796 static void prn(unsigned u)
801 static void echo(char **wp)
806 for (i = 0; wp[i]; i++) {
814 static void closef(int i)
820 static void closeall(void)
824 for (u = NUFILE; u < NOFILE;)
829 /* fail but return to process next command */
830 static void fail(void) ATTRIBUTE_NORETURN;
831 static void fail(void)
837 /* abort shell (or fail in subshell) */
838 static void leave(void) ATTRIBUTE_NORETURN;
839 static void leave(void)
841 DBGPRINTF(("LEAVE: leave called!\n"));
852 static void warn(const char *s)
863 static void err(const char *s)
873 e.iop = e.iobase = iostack;
877 /* -------- area.c -------- */
880 * All memory between (char *)areabot and (char *)(areatop+1) is
881 * exclusively administered by the area management routines.
882 * It is assumed that sbrk() and brk() manipulate the high end.
886 void * __q = (void *)-1; \
887 if (brkaddr + (int)(X) < brktop) { \
889 brkaddr += (int)(X); \
894 static void initarea(void)
896 brkaddr = xmalloc(AREASIZE);
897 brktop = brkaddr + AREASIZE;
899 while ((long) sbrk(0) & ALIGN)
901 areabot = (struct region *) sbrk(REGSIZE);
903 areabot->next = areabot;
904 areabot->area = BUSY;
909 static char *getcell(unsigned nbytes)
912 struct region *p, *q;
919 /* silly and defeats the algorithm */
921 * round upwards and add administration area
923 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
926 if (p->area > areanum) {
930 while ((q = p->next)->area > areanum && q != areanxt)
933 * exit loop if cell big enough
942 i = nregio >= GROWBY ? nregio : GROWBY;
943 p = (struct region *) sbrk(i * REGSIZE);
944 if (p == (struct region *) -1)
949 abort(); /* allocated areas are contiguous */
959 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
961 areanxt = p + nregio;
964 * split into requested area and rest
966 if (areanxt + 1 > q) {
968 abort(); /* insufficient space left for admin */
971 areanxt->area = FREE;
975 return (char *) (p + 1);
978 static void freecell(char *cp)
982 p = (struct region *) cp;
990 #define DELETE(obj) freecell((char *)obj)
992 static void freearea(int a)
994 struct region *p, *top;
997 for (p = areabot; p != top; p = p->next)
1002 static void setarea(char *cp, int a)
1006 p = (struct region *) cp;
1011 static int getarea(char *cp)
1013 return ((struct region *) cp - 1)->area;
1016 static void garbage(void)
1018 struct region *p, *q, *top;
1021 for (p = areabot; p != top; p = p->next) {
1022 if (p->area > areanum) {
1023 while ((q = p->next)->area > areanum)
1029 if (areatop >= q + SHRINKBY && q->area > areanum) {
1030 brk((char *) (q + 1));
1038 static char *space(int n)
1044 err("out of string space");
1048 static char *strsave(const char *s, int a)
1052 cp = space(strlen(s) + 1);
1054 // FIXME: I highly doubt this is good.
1063 /* -------- var.c -------- */
1065 static int eqname(const char *n1, const char *n2)
1067 for (; *n1 != '=' && *n1 != '\0'; n1++)
1070 return *n2 == '\0' || *n2 == '=';
1073 static const char *findeq(const char *cp)
1075 while (*cp != '\0' && *cp != '=')
1081 * Find the given name in the dictionary
1082 * and return its value. If the name was
1083 * not previously there, enter it now and
1084 * return a null value.
1086 static struct var *lookup(const char *n)
1088 // FIXME: dirty hack
1089 static struct var dummy;
1097 dummy.name = (char*)n;
1098 for (c = 0; isdigit(*n) && c < 1000; n++)
1099 c = c * 10 + *n - '0';
1100 dummy.status = RONLY;
1101 dummy.value = (c <= dolc ? dolv[c] : null);
1105 for (vp = vlist; vp; vp = vp->next)
1106 if (eqname(vp->name, n))
1110 vp = (struct var *) space(sizeof(*vp));
1111 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1112 dummy.name = dummy.value = (char*)"";
1117 while ((*xp = *n++) != '\0' && *xp != '=')
1121 setarea((char *) vp, 0);
1122 setarea((char *) vp->name, 0);
1125 vp->status = GETCELL;
1131 * if name is not NULL, it must be
1132 * a prefix of the space `val',
1134 * this is all so that exporting
1135 * values is reasonably painless.
1137 static void nameval(struct var *vp, const char *val, const char *name)
1143 if (vp->status & RONLY) {
1145 while (*xp && *xp != '=')
1146 fputc(*xp++, stderr);
1147 err(" is read-only");
1152 xp = space(strlen(vp->name) + strlen(val) + 2);
1155 /* make string: name=value */
1159 while ((*xp = *cp++) != '\0' && *xp != '=')
1166 if (vp->status & GETCELL)
1167 freecell(vp->name); /* form new string `name=value' */
1168 vp->name = (char*)name;
1169 vp->value = (char*)val;
1174 * give variable at `vp' the value `val'.
1176 static void setval(struct var *vp, const char *val)
1178 nameval(vp, val, NULL);
1181 static void export(struct var *vp)
1183 vp->status |= EXPORT;
1186 static void ronly(struct var *vp)
1188 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1189 vp->status |= RONLY;
1192 static int isassign(const char *s)
1195 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1198 /* no isalpha() - we shouldn't use locale */
1199 /* c | 0x20 - lowercase (Latin) letters */
1200 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1211 && (unsigned)(c - '0') > 9 /* not number */
1212 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1219 static int assign(const char *s, int cf)
1224 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1226 if (!isalpha(*s) && *s != '_')
1228 for (cp = s; *cp != '='; cp++)
1229 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1232 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1234 vp->status &= ~GETCELL;
1238 static int checkname(char *cp)
1240 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1242 if (!isalpha(*cp++) && *(cp - 1) != '_')
1245 if (!isalnum(*cp++) && *(cp - 1) != '_')
1250 static void putvlist(int f, int out)
1254 for (vp = vlist; vp; vp = vp->next) {
1255 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1256 if (vp->status & EXPORT)
1257 write(out, "export ", 7);
1258 if (vp->status & RONLY)
1259 write(out, "readonly ", 9);
1260 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1261 write(out, "\n", 1);
1270 static void sig(int i)
1276 static void runtrap(int i)
1281 if (trapstr == NULL)
1287 RUN(aword, trapstr, nlchar);
1291 static void setdash(void)
1295 char m['z' - 'a' + 1];
1298 for (c = 'a'; c <= 'z'; c++)
1302 setval(lookup("-"), m);
1305 static int newfile(char *s)
1309 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1312 if (NOT_LONE_DASH(s)) {
1313 DBGPRINTF(("NEWFILE: s is %s\n", s));
1314 f = open(s, O_RDONLY);
1317 err(": cannot open");
1327 struct op *scantree(struct op *head)
1334 if (head->left != NULL) {
1335 dotnode = scantree(head->left);
1340 if (head->right != NULL) {
1341 dotnode = scantree(head->right);
1346 if (head->words == NULL)
1349 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1351 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1352 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1360 static void onecommand(void)
1365 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1385 setjmp(failpt); /* Bruce Evans' fix */
1387 if (setjmp(failpt) || yyparse() || intr) {
1388 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1393 if (!interactive && intr)
1406 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1408 execute(outtree, NOPIPE, NOPIPE, 0);
1411 if (!interactive && intr) {
1423 static int newenv(int f)
1427 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1434 ep = (struct env *) space(sizeof(*ep));
1447 static void quitenv(void)
1452 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1458 /* should close `'d files */
1460 while (--fd >= e.iofd)
1466 * Is character c in s?
1468 static int any(int c, const char *s)
1477 * Is any character from s1 in s2?
1479 static int anys(const char *s1, const char *s2)
1487 static char *putn(int n)
1492 static void next(int f)
1494 PUSHIO(afile, f, filechar);
1497 static void onintr(int s) /* ANSI C requires a parameter */
1499 signal(SIGINT, onintr);
1506 } else if (heedint) {
1513 /* -------- gmatch.c -------- */
1515 * int gmatch(string, pattern)
1516 * char *string, *pattern;
1518 * Match a pattern as in sh(1).
1523 #define QMASK (CMASK & ~QUOTE)
1524 #define NOT '!' /* might use ^ */
1526 static const char *cclass(const char *p, int sub)
1528 int c, d, not, found;
1538 if (p[1] == '-' && p[2] != ']') {
1543 if (c == sub || (c <= sub && sub <= d))
1545 } while (*++p != ']');
1546 return found ? p + 1 : NULL;
1549 static int gmatch(const char *s, const char *p)
1553 if (s == NULL || p == NULL)
1556 while ((pc = *p++ & CMASK) != '\0') {
1573 if (*p == '\0' || gmatch(s, p))
1575 } while (*s++ != '\0');
1579 if (sc != (pc & ~QUOTE))
1587 /* -------- csyn.c -------- */
1589 * shell: syntax (C version)
1592 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1593 static void yyerror(const char *s)
1596 if (interactive && e.iop <= iostack) {
1598 while (eofc() == 0 && yylex(0) != '\n');
1604 static void zzerr(void) ATTRIBUTE_NORETURN;
1605 static void zzerr(void)
1607 yyerror("syntax error");
1612 DBGPRINTF7(("YYPARSE: enter...\n"));
1619 return (yynerrs != 0);
1622 static struct op *pipeline(int cf)
1627 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1631 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1634 while ((c = yylex(0)) == '|') {
1635 p = command(CONTIN);
1637 DBGPRINTF8(("PIPELINE: error!\n"));
1641 if (t->type != TPAREN && t->type != TCOM) {
1642 /* shell statement */
1643 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1646 t = block(TPIPE, t, p, NOWORDS);
1651 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1655 static struct op *andor(void)
1660 DBGPRINTF7(("ANDOR: enter...\n"));
1664 DBGPRINTF9(("ANDOR: t=%p\n", t));
1667 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1668 p = pipeline(CONTIN);
1670 DBGPRINTF8(("ANDOR: error!\n"));
1674 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1680 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1684 static struct op *c_list(void)
1689 DBGPRINTF7(("C_LIST: enter...\n"));
1696 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1698 while ((c = yylex(0)) == ';' || c == '&'
1699 || (multiline && c == '\n')) {
1707 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1715 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1719 static int synio(int cf)
1725 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1728 if (c != '<' && c != '>') {
1735 iop = io(iounit, i, yylval.cp);
1739 markhere(yylval.cp, iop);
1741 DBGPRINTF7(("SYNIO: returning 1\n"));
1745 static void musthave(int c, int cf)
1747 peeksym = yylex(cf);
1749 DBGPRINTF7(("MUSTHAVE: error!\n"));
1756 static struct op *simple(void)
1762 switch (peeksym = yylex(0)) {
1783 static struct op *nested(int type, int mark)
1787 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1793 return block(type, t, NOBLOCK, NOWORDS);
1796 static struct op *command(int cf)
1799 struct wdblock *iosave;
1802 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1828 t = nested(TPAREN, ')');
1832 t = nested(TBRACE, '}');
1842 t->words = wordlist();
1844 if (c != '\n' && c != ';')
1846 t->left = dogroup(0);
1854 t->type = c == WHILE ? TWHILE : TUNTIL;
1856 t->right = dogroup(1);
1868 musthave(IN, CONTIN);
1871 t->left = caselist();
1882 t->right = thenpart();
1891 musthave(WORD, 0); /* gets name of file */
1892 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1894 word(yylval.cp); /* add word to wdlist */
1895 word(NOWORD); /* terminate wdlist */
1896 t->words = copyw(); /* dup wdlist */
1906 DBGPRINTF(("COMMAND: returning %p\n", t));
1911 static struct op *dowholefile(int type, int mark)
1915 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1920 t = block(type, t, NOBLOCK, NOWORDS);
1921 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1925 static struct op *dogroup(int onlydone)
1931 if (c == DONE && onlydone)
1940 static struct op *thenpart(void)
1953 if (t->left == NULL)
1955 t->right = elsepart();
1959 static struct op *elsepart(void)
1964 switch (c = yylex(0)) {
1975 t->right = thenpart();
1984 static struct op *caselist(void)
1989 while ((peeksym = yylex(CONTIN)) != ESAC) {
1990 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1991 t = list(t, casepart());
1994 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1998 static struct op *casepart(void)
2002 DBGPRINTF7(("CASEPART: enter...\n"));
2006 t->words = pattern();
2009 peeksym = yylex(CONTIN);
2010 if (peeksym != ESAC)
2011 musthave(BREAK, CONTIN);
2013 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2018 static char **pattern(void)
2035 static char **wordlist(void)
2045 while ((c = yylex(0)) == WORD)
2053 * supporting functions
2055 static struct op *list(struct op *t1, struct op *t2)
2057 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2064 return block(TLIST, t1, t2, NOWORDS);
2067 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2071 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2079 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2085 /* See if given string is a shell multiline (FOR, IF, etc) */
2086 static int rlookup(char *n)
2088 const struct res *rp;
2090 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2092 for (rp = restab; rp->r_name; rp++)
2093 if (strcmp(rp->r_name, n) == 0) {
2094 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2095 return rp->r_val; /* Return numeric code for shell multiline */
2098 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2099 return 0; /* Not a shell multiline */
2102 static struct op *newtp(void)
2106 t = (struct op *) tree(sizeof(*t));
2114 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2119 static struct op *namelist(struct op *t)
2121 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2122 T_CMD_NAMES[t->type], iolist));
2125 iolist = addword((char *) NULL, iolist);
2126 t->ioact = copyio();
2130 if (t->type != TCOM) {
2131 if (t->type != TPAREN && t->ioact != NULL) {
2132 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2133 t->ioact = t->left->ioact;
2134 t->left->ioact = NULL;
2145 static char **copyw(void)
2149 wd = getwords(wdlist);
2154 static void word(char *cp)
2156 wdlist = addword(cp, wdlist);
2159 static struct ioword **copyio(void)
2161 struct ioword **iop;
2163 iop = (struct ioword **) getwords(iolist);
2168 static struct ioword *io(int u, int f, char *cp)
2172 iop = (struct ioword *) tree(sizeof(*iop));
2176 iolist = addword((char *) iop, iolist);
2180 static int yylex(int cf)
2200 line[LINELIM - 1] = '\0';
2203 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2208 if (any(c, "0123456789")) {
2211 if (c1 == '<' || c1 == '>') {
2220 case '#': /* Comment, skip to next newline or End-of-string */
2221 while ((c = my_getc(0)) != '\0' && c != '\n');
2226 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2230 DBGPRINTF9(("YYLEX: found $\n"));
2234 c = collect(c, '}');
2253 /* If more chars process them, else return NULL char */
2271 if (multiline || cf & CONTIN) {
2272 if (interactive && e.iop <= iostack) {
2273 #if ENABLE_FEATURE_EDITING
2274 current_prompt = cprompt->value;
2276 prs(cprompt->value);
2293 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2294 if (e.linep >= elinep)
2295 err("word too long");
2302 if (any(c, "\"'`$"))
2315 yylval.cp = strsave(line, areanum);
2320 static int collect(int c, int c1)
2324 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2327 while ((c = my_getc(c1)) != c1) {
2336 if (interactive && c == '\n' && e.iop <= iostack) {
2337 #if ENABLE_FEATURE_EDITING
2338 current_prompt = cprompt->value;
2340 prs(cprompt->value);
2348 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2353 /* "multiline commands" helper func */
2354 /* see if next 2 chars form a shell multiline */
2355 static int dual(int c)
2360 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2362 *cp++ = c; /* c is the given "peek" char */
2363 *cp++ = my_getc(0); /* get next char of input */
2364 *cp = '\0'; /* add EOS marker */
2366 c = rlookup(s); /* see if 2 chars form a shell multiline */
2368 unget(*--cp); /* String is not a shell multiline, put peek char back */
2370 return c; /* String is multiline, return numeric multiline (restab) code */
2373 static void diag(int ec)
2377 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2380 if (c == '>' || c == '<') {
2383 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2386 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2387 if (c != '&' || yylval.i == IOHERE)
2393 static char *tree(unsigned size)
2399 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2400 prs("command line too complicated\n");
2411 /* -------- exec.c -------- */
2413 static struct op **find1case(struct op *t, const char *w)
2421 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2425 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2426 T_CMD_NAMES[t->type]));
2428 if (t->type == TLIST) {
2429 tp = find1case(t->left, w);
2431 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2434 t1 = t->right; /* TPAT */
2438 for (wp = t1->words; *wp;) {
2439 cp = evalstr(*wp++, DOSUB);
2440 if (cp && gmatch(w, cp)) {
2441 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2447 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2451 static struct op *findcase(struct op *t, const char *w)
2455 tp = find1case(t, w);
2456 return tp != NULL ? *tp : NULL;
2463 static int execute(struct op *t, int *pin, int *pout, int act)
2466 volatile int i, rv, a;
2470 struct op *outtree_save;
2474 /* Avoid longjmp clobbering */
2479 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2483 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2484 t->type, T_CMD_NAMES[t->type],
2485 ((t->words == NULL) ? "NULL" : t->words[0])));
2489 wp = (wp2 = t->words) != NULL
2490 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2495 DBGPRINTF3(("EXECUTE: TDOT\n"));
2497 outtree_save = outtree;
2499 newfile(evalstr(t->words[0], DOALL));
2501 t->left = dowholefile(TLIST, 0);
2504 outtree = outtree_save;
2507 rv = execute(t->left, pin, pout, 0);
2509 rv = execute(t->right, pin, pout, 0);
2513 rv = execute(t->left, pin, pout, 0);
2517 rv = forkexec(t, pin, pout, act, wp);
2527 pv[0] = remap(pv[0]);
2528 pv[1] = remap(pv[1]);
2529 (void) execute(t->left, pin, pv, 0);
2530 rv = execute(t->right, pv, pout, 0);
2535 (void) execute(t->left, pin, pout, 0);
2536 rv = execute(t->right, pin, pout, 0);
2541 int hinteractive = interactive;
2543 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2546 if (i == 0) { /* child */
2547 signal(SIGINT, SIG_IGN);
2548 signal(SIGQUIT, SIG_IGN);
2550 signal(SIGTERM, SIG_DFL);
2554 xopen(bb_dev_null, O_RDONLY);
2556 _exit(execute(t->left, pin, pout, FEXEC));
2558 interactive = hinteractive;
2560 setval(lookup("!"), putn(i));
2575 rv = execute(t->left, pin, pout, 0);
2577 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2578 rv = execute(t1, pin, pout, 0);
2589 while (*wp++ != NULL);
2591 vp = lookup(t->str);
2592 while (setjmp(bc.brkpt))
2596 for (t1 = t->left; i-- && *wp != NULL;) {
2598 rv = execute(t1, pin, pout, 0);
2600 brklist = brklist->nextlev;
2605 while (setjmp(bc.brkpt))
2610 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2611 rv = execute(t->right, pin, pout, 0);
2612 brklist = brklist->nextlev;
2617 if (t->right != NULL) {
2618 rv = !execute(t->left, pin, pout, 0) ?
2619 execute(t->right->left, pin, pout, 0) :
2620 execute(t->right->right, pin, pout, 0);
2625 cp = evalstr(t->str, DOSUB | DOTRIM);
2629 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2630 ((t->str == NULL) ? "NULL" : t->str),
2631 ((cp == NULL) ? "NULL" : cp)));
2633 t1 = findcase(t->left, cp);
2635 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2636 rv = execute(t1, pin, pout, 0);
2637 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2646 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2654 rv = execute(t1, pin, pout, 0);
2667 if (interactive && intr) {
2678 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2682 typedef int (*builtin_func_ptr)(struct op *);
2684 static builtin_func_ptr inbuilt(const char *s)
2686 const struct builtincmd *bp;
2688 for (bp = builtincmds; bp->name; bp++)
2689 if (strcmp(bp->name, s) == 0)
2690 return bp->builtinfunc;
2694 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2698 builtin_func_ptr shcom = NULL;
2700 const char *cp = NULL;
2701 struct ioword **iopp;
2711 struct brkcon *hbrklist;
2715 /* Avoid longjmp clobbering */
2725 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2727 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2728 ((t->words == NULL) ? "NULL" : t->words[0])));
2732 rv = -1; /* system-detected error */
2733 if (t->type == TCOM) {
2734 while (*wp++ != NULL)
2738 /* strip all initial assignments */
2739 /* not correct wrt PATH=yyy command etc */
2741 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2743 echo(cp ? wp : owp);
2746 if (cp == NULL && t->ioact == NULL) {
2747 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2749 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2750 return setstatus(0);
2753 shcom = inbuilt(cp);
2760 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2763 if (shcom == NULL && (f & FEXEC) == 0) {
2764 /* Save values in case the child process alters them */
2768 hinteractive = interactive;
2773 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2778 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2782 if (newpid > 0) { /* Parent */
2783 /* Restore values */
2787 interactive = hinteractive;
2798 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2801 /* Must be the child process, pid should be 0 */
2802 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2805 signal(SIGINT, SIG_IGN);
2806 signal(SIGQUIT, SIG_IGN);
2817 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2822 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2823 err("piping to/from shell builtins not yet done");
2831 xmove_fd(pin[0], 0);
2832 if (pin[1] != 0) close(pin[1]);
2835 xmove_fd(pout[1], 1);
2836 if (pout[1] != 1) close(pout[0]);
2841 if (shcom != NULL && shcom != doexec) {
2843 err(": cannot redirect shell command");
2849 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2857 i = setstatus((*shcom) (t));
2860 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2864 /* should use FIOCEXCL */
2865 for (i = FDBASE; i < NOFILE; i++)
2868 signal(SIGINT, SIG_DFL);
2869 signal(SIGQUIT, SIG_DFL);
2872 if (t->type == TPAREN)
2873 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2877 cp = rexecve(wp[0], wp, makenv(0, NULL));
2884 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2892 * 0< 1> are ignored as required
2895 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2901 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2904 if (iop->io_unit == IODEFAULT) /* take default */
2905 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2907 if (pipein && iop->io_unit == 0)
2910 if (pipeout && iop->io_unit == 1)
2913 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2914 if ((iop->io_flag & IOHERE) == 0) {
2915 cp = iop->io_name; /* huh?? */
2916 cp = evalstr(cp, DOSUB | DOTRIM);
2921 if (iop->io_flag & IODUP) {
2922 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2924 err(": illegal >& argument");
2928 iop->io_flag = IOCLOSE;
2929 iop->io_flag &= ~(IOREAD | IOWRITE);
2931 switch (iop->io_flag) {
2933 u = open(cp, O_RDONLY);
2937 case IOHERE | IOXHERE:
2938 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2939 cp = (char*)"here file";
2942 case IOWRITE | IOCAT:
2943 u = open(cp, O_WRONLY);
2945 lseek(u, (long) 0, SEEK_END);
2949 u = creat(cp, 0666);
2953 u = dup2(*cp - '0', iop->io_unit);
2957 close(iop->io_unit);
2966 if (u != iop->io_unit) {
2967 dup2(u, iop->io_unit);
2974 * Enter a new loop level (marked for break/continue).
2976 static void brkset(struct brkcon *bc)
2978 bc->nextlev = brklist;
2983 * Wait for the last process created.
2984 * Print a message for each process found
2985 * that was killed by a signal.
2986 * Ignore interrupt signals while waiting
2987 * unless `canintr' is true.
2989 static int waitfor(int lastpid, int canintr)
2993 int oheedint = heedint;
3000 if (errno != EINTR || canintr)
3005 if (rv < ARRAY_SIZE(signame)) {
3006 if (signame[rv] != NULL) {
3007 if (pid != lastpid) {
3014 if (pid != lastpid) {
3023 prs(" - core dumped");
3024 if (rv >= ARRAY_SIZE(signame) || signame[rv])
3030 } while (pid != lastpid);
3045 static int setstatus(int s)
3048 setval(lookup("?"), putn(s));
3053 * PATH-searching interface to execve.
3054 * If getenv("PATH") were kept up-to-date,
3055 * execvp might be used.
3057 static const char *rexecve(char *c, char **v, char **envp)
3062 int eacces = 0, asis = 0;
3065 if (ENABLE_FEATURE_SH_STANDALONE) {
3066 if (find_applet_by_name(name) >= 0) {
3067 /* We have to exec here since we vforked. Running
3068 * run_applet_and_exit() won't work and bad things
3070 execve(bb_busybox_exec_path, v, envp);
3074 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3076 sp = any('/', c) ? "" : path->value;
3077 asis = (*sp == '\0');
3078 while (asis || *sp != '\0') {
3081 for (; *sp != '\0'; tp++) {
3084 asis = (*sp == '\0');
3090 for (i = 0; (*tp++ = c[i++]) != '\0';);
3092 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3094 execve(e.linep, v, envp);
3101 execve(DEFAULT_SHELL, v, envp);
3106 return (char *) bb_msg_memory_exhausted;
3109 return "argument list too long";
3116 return errno == ENOENT ? "not found" : "cannot execute";
3120 * Run the command produced by generator `f'
3121 * applied to stream `arg'.
3123 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3126 struct wdblock *swdlist;
3127 struct wdblock *siolist;
3133 /* Avoid longjmp clobbering */
3137 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3138 areanum, outtree, failpt));
3148 if (newenv(setjmp(errpt)) == 0) {
3155 if (setjmp(failpt) == 0 && yyparse() == 0)
3156 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3159 DBGPRINTF(("RUN: error from newenv()!\n"));
3166 freearea(areanum--);
3171 /* -------- do.c -------- */
3174 * built-in commands: doX
3177 static int dohelp(struct op *t)
3180 const struct builtincmd *x;
3182 puts("\nBuilt-in commands:\n"
3183 "-------------------");
3188 col += printf("%c%s", ((col == 0) ? '\t' : ' '), x->name);
3195 #if ENABLE_FEATURE_SH_STANDALONE
3197 const char *applet = applet_names;
3200 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applet);
3205 applet += strlen(applet) + 1;
3210 return EXIT_SUCCESS;
3213 static int dolabel(struct op *t)
3218 static int dochdir(struct op *t)
3220 const char *cp, *er;
3224 cp = homedir->value;
3227 er = ": no home directory";
3232 er = ": bad directory";
3234 prs(cp != NULL ? cp : "cd");
3239 static int doshift(struct op *t)
3243 n = t->words[1] ? getn(t->words[1]) : 1;
3245 err("nothing to shift");
3251 setval(lookup("#"), putn(dolc));
3256 * execute login and newgrp directly
3258 static int dologin(struct op *t)
3263 signal(SIGINT, SIG_DFL);
3264 signal(SIGQUIT, SIG_DFL);
3266 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3273 static int doumask(struct op *t)
3282 for (n = 3 * 4; (n -= 3) >= 0;)
3283 fputc('0' + ((i >> n) & 07), stderr);
3284 fputc('\n', stderr);
3286 /* huh??? '8','9' are not allowed! */
3287 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3288 n = n * 8 + (*cp - '0');
3294 static int doexec(struct op *t)
3301 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3307 if (setjmp(failpt) == 0)
3308 execute(t, NOPIPE, NOPIPE, FEXEC);
3314 static int dodot(struct op *t)
3322 DBGPRINTF(("DODOT: enter, t=%p, tleft %p, tright %p, e.linep is %s\n", t, t->left, t->right, ((e.linep == NULL) ? "NULL" : e.linep)));
3326 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3329 DBGPRINTF(("DODOT: cp is %s\n", cp));
3331 sp = any('/', cp) ? ":" : path->value;
3333 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3334 ((sp == NULL) ? "NULL" : sp),
3335 ((e.linep == NULL) ? "NULL" : e.linep)));
3339 while (*sp && (*tp = *sp++) != ':')
3344 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3347 i = open(e.linep, O_RDONLY);
3351 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.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 = e.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), e.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);
3764 while ((xp = blank(f)) && gflg == 0) {
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));
3815 scanequals = f & DOKEY;
3819 c = subgetc('"', foundequals);
3828 if (f & DOBLANK && any(c, ifs->value))
3837 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3840 if (c == '\'' || !any(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 != '_')
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 e.iop->task = XGRAVE;
3894 e.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));
3919 if (isalpha(c) || c == '_') {
3920 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3921 if (e.linep < elinep)
3928 otask = e.iop->task;
3930 e.iop->task = XOTHER;
3931 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3932 if (e.linep < elinep)
3935 e.iop->task = otask;
3942 if (e.linep >= elinep) {
3943 err("string in ${} too long");
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 */
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: ");
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 = e.iop->argp->aword; *cp != '`'; cp++) {
4033 err("no closing `");
4038 /* string copy with dollar expansion */
4039 src = e.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);
4168 e.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:
4186 if (pf[0] != 1) close(pf[0]);
4188 argument_list[0] = (char *) DEFAULT_SHELL;
4189 argument_list[1] = (char *) "-c";
4190 argument_list[2] = child_cmd;
4191 argument_list[3] = NULL;
4193 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4194 prs(argument_list[0]);
4201 static char *unquote(char *as)
4212 /* -------- glob.c -------- */
4218 #define scopy(x) strsave((x), areanum)
4220 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4222 static struct wdblock *cl, *nl;
4223 static const char spcl[] ALIGN1= "[?*";
4225 static struct wdblock *glob(char *cp, struct wdblock *wb)
4233 for (pp = cp; *pp; pp++)
4236 else if (!any(*pp & ~QUOTE, spcl))
4239 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4240 nl = newword(cl->w_nword * 2);
4241 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4242 for (pp = cl->w_words[i]; *pp; pp++)
4243 if (any(*pp, spcl)) {
4244 globname(cl->w_words[i], pp);
4248 nl = addword(scopy(cl->w_words[i]), nl);
4250 for (i = 0; i < cl->w_nword; i++)
4251 DELETE(cl->w_words[i]);
4254 for (i = 0; i < cl->w_nword; i++)
4255 unquote(cl->w_words[i]);
4256 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4258 for (i = 0; i < cl->w_nword; i++)
4259 wb = addword(cl->w_words[i], wb);
4264 wb = addword(unquote(cp), wb);
4268 static void globname(char *we, char *pp)
4271 char *name, *gp, *dp;
4275 char dname[NAME_MAX + 1];
4278 for (np = we; np != pp; pp--)
4281 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4285 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4294 dname[NAME_MAX] = '\0';
4295 while ((de = readdir(dirp)) != NULL) {
4296 /* XXX Hmmm... What this could be? (abial) */
4298 if (ent[j].d_ino == 0)
4301 strncpy(dname, de->d_name, NAME_MAX);
4302 if (dname[0] == '.')
4305 for (k = 0; k < NAME_MAX; k++)
4306 if (any(dname[k], spcl))
4308 if (gmatch(dname, gp)) {
4309 name = generate(we, pp, dname, np);
4310 if (*np && !anys(np, spcl)) {
4311 if (stat(name, &dbuf)) {
4316 nl = addword(name, nl);
4325 * generate a pathname as below.
4326 * start..end1 / middle end
4327 * the slashes come for free
4329 static char *generate(char *start1, char *end1, char *middle, char *end)
4334 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4335 for (xp = start1; xp != end1;)
4337 for (xp = middle; (*op++ = *xp++) != '\0';);
4339 for (xp = end; (*op++ = *xp++) != '\0';);
4343 static int anyspcl(struct wdblock *wb)
4349 for (i = 0; i < wb->w_nword; i++)
4350 if (anys(spcl, *wd++))
4355 static int xstrcmp(char *p1, char *p2)
4357 return strcmp(*(char **) p1, *(char **) p2);
4361 /* -------- word.c -------- */
4363 static struct wdblock *newword(int nw)
4367 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4373 static struct wdblock *addword(char *wd, struct wdblock *wb)
4375 struct wdblock *wb2;
4379 wb = newword(NSTART);
4381 if (nw >= wb->w_bsize) {
4382 wb2 = newword(nw * 2);
4383 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4384 nw * sizeof(char *));
4389 wb->w_words[wb->w_nword++] = wd;
4393 static char **getwords(struct wdblock *wb)
4400 if (wb->w_nword == 0) {
4404 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4405 memcpy((char *) wd, (char *) wb->w_words, nb);
4406 DELETE(wb); /* perhaps should done by caller */
4410 static int (*func) (char *, char *);
4413 static void glob3(char *i, char *j, char *k)
4415 char *index1, *index2, *index3;
4425 *index1++ = *index3;
4426 *index3++ = *index2;
4431 static void glob2(char *i, char *j)
4433 char *index1, *index2, c;
4441 *index1++ = *index2;
4446 static void glob1(char *base, char *lim)
4457 n = (int) (lim - base);
4460 n = v2 * (n / (2 * v2));
4461 hptr = lptr = base + n;
4466 c = (*func) (i, lptr);
4480 c = (*func) (hptr, j);
4504 if (lptr - base >= lim - hptr) {
4505 glob1(hptr + v2, lim);
4520 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4524 glob1(a0, a0 + a1 * a2);
4528 /* -------- io.c -------- */
4534 static int my_getc(int ec)
4538 if (e.linep > elinep) {
4539 while ((c = readc()) != '\n' && c);
4540 err("input line too long");
4545 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4548 if (c == '\n' && ec != '\"')
4556 static void unget(int c)
4558 if (e.iop >= e.iobase)
4562 static int eofc(void)
4564 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4567 static int readc(void)
4571 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4573 for (; e.iop >= e.iobase; e.iop--) {
4574 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4580 if (e.iop->prev != 0) {
4581 c = (*e.iop->iofn)(e.iop->argp, e.iop);
4587 if (e.iop == iostack)
4592 if (e.iop->task == XIO && e.iop->prev != '\n') {
4594 if (e.iop == iostack)
4599 if (e.iop->task == XIO) {
4604 if (interactive && e.iop == iostack + 1) {
4605 #if ENABLE_FEATURE_EDITING
4606 current_prompt = prompt->value;
4614 if (e.iop >= iostack) {
4615 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4619 DBGPRINTF(("READC: leave()...\n"));
4626 static void ioecho(char c)
4629 write(2, &c, sizeof c);
4633 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4635 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4636 argp->afid, e.iop));
4638 /* Set env ptr for io source to next array spot and check for array overflow */
4639 if (++e.iop >= &iostack[NPUSH]) {
4641 err("Shell input nested too deeply");
4646 /* We did not overflow the NPUSH array spots so setup data structs */
4648 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4650 if (argp->afid != AFID_NOBUF)
4654 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4655 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4657 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4659 if (e.iop == &iostack[0])
4660 e.iop->argp->afbuf = &mainbuf;
4662 e.iop->argp->afbuf = &sharedbuf;
4664 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4665 /* This line appears to be active when running scripts from command line */
4666 if ((isatty(e.iop->argp->afile) == 0)
4667 && (e.iop == &iostack[0]
4668 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4669 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4670 bufid = AFID_ID; /* AFID_ID = 0 */
4672 e.iop->argp->afid = bufid; /* assign buffer id */
4675 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4676 iostack, e.iop, e.iop->argp->afbuf));
4677 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4678 &mainbuf, &sharedbuf, bufid, e.iop));
4682 e.iop->prev = ~'\n';
4687 if (fn == filechar || fn == linechar)
4689 else if (fn == (int (*)(struct ioarg *)) gravechar
4690 || fn == (int (*)(struct ioarg *)) qgravechar)
4691 e.iop->task = XGRAVE;
4693 e.iop->task = XOTHER;
4696 static struct io *setbase(struct io *ip)
4706 * Input generating functions
4710 * Produce the characters of a string, then a newline, then EOF.
4712 static int nlchar(struct ioarg *ap)
4716 if (ap->aword == NULL)
4727 * Given a list of words, produce the characters
4728 * in them, with a space after each word.
4730 static int wdchar(struct ioarg *ap)
4745 ap->awordlist = NULL;
4750 * Return the characters of a list of words,
4751 * producing a space between them.
4753 static int dolchar(struct ioarg *ap)
4757 wp = *ap->awordlist++;
4759 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4765 static int xxchar(struct ioarg *ap)
4769 if (ap->aword == NULL)
4780 * Produce the characters from a single word (string).
4782 static int strchar(struct ioarg *ap)
4784 if (ap->aword == NULL)
4786 return *ap->aword++;
4790 * Produce quoted characters from a single word (string).
4792 static int qstrchar(struct ioarg *ap)
4796 if (ap->aword == NULL)
4805 * Return the characters from a file.
4807 static int filechar(struct ioarg *ap)
4811 struct iobuf *bp = ap->afbuf;
4813 if (ap->afid != AFID_NOBUF) {
4814 i = (ap->afid != bp->id);
4815 if (i || bp->bufp == bp->ebufp) {
4817 lseek(ap->afile, ap->afpos, SEEK_SET);
4819 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4827 bp->ebufp = bp->bufp + i;
4831 return *bp->bufp++ & 0177;
4833 #if ENABLE_FEATURE_EDITING
4834 if (interactive && isatty(ap->afile)) {
4835 /* moved to G: static char filechar_cmdbuf[BUFSIZ]; */
4836 static int position = 0, size = 0;
4838 while (size == 0 || position >= size) {
4839 read_line_input(current_prompt, filechar_cmdbuf, BUFSIZ, line_input_state);
4840 size = strlen(filechar_cmdbuf);
4843 c = filechar_cmdbuf[position];
4848 i = safe_read(ap->afile, &c, sizeof(c));
4849 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4853 * Return the characters from a here temp file.
4855 static int herechar(struct ioarg *ap)
4859 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4867 * Return the characters produced by a process (`...`).
4868 * Quote them if required, and remove any trailing newline characters.
4870 static int gravechar(struct ioarg *ap, struct io *iop)
4874 c = qgravechar(ap, iop) & ~QUOTE;
4880 static int qgravechar(struct ioarg *ap, struct io *iop)
4884 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4889 return '\n' | QUOTE;
4893 } else if ((c = filechar(ap)) == '\n') {
4895 while ((c = filechar(ap)) == '\n')
4903 return c != 0 ? c | QUOTE : 0;
4907 * Return a single command (usually the first line) from a file.
4909 static int linechar(struct ioarg *ap)
4917 ap->afile = -1; /* illegal value */
4924 * remap fd into Shell's fd space
4926 static int remap(int fd)
4932 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
4935 for (i = 0; i < NOFILE; i++)
4942 } while (fd >= 0 && fd < e.iofd);
4944 for (i = 0; i < NOFILE; i++)
4949 err("too many files open in shell");
4955 static int openpipe(int *pv)
4961 err("can't create pipe - try again");
4965 static void closepipe(int *pv)
4974 /* -------- here.c -------- */
4980 static void markhere(char *s, struct ioword *iop)
4982 struct here *h, *lh;
4984 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4986 h = (struct here *) space(sizeof(struct here));
4990 h->h_tag = evalstr(s, DOSUB);
5000 for (lh = inhere; lh != NULL; lh = lh->h_next) {
5001 if (lh->h_next == 0) {
5007 iop->io_flag |= IOHERE | IOXHERE;
5008 for (s = h->h_tag; *s; s++) {
5010 iop->io_flag &= ~IOXHERE;
5014 h->h_dosub = iop->io_flag & IOXHERE;
5017 static void gethere(void)
5019 struct here *h, *hp;
5021 DBGPRINTF7(("GETHERE: enter...\n"));
5023 /* Scan here files first leaving inhere list in place */
5024 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5025 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5027 /* Make inhere list active - keep list intact for scraphere */
5029 hp->h_next = acthere;
5035 static void readhere(char **name, char *s, int ec)
5038 char tname[30] = ".msh_XXXXXX";
5041 char myline[LINELIM + 1];
5044 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5046 tf = mkstemp(tname);
5050 *name = strsave(tname, areanum);
5052 if (newenv(setjmp(errpt)) != 0)
5055 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5058 if (interactive && e.iop <= iostack) {
5059 #if ENABLE_FEATURE_EDITING
5060 current_prompt = cprompt->value;
5062 prs(cprompt->value);
5066 while ((c = my_getc(ec)) != '\n' && c) {
5069 if (thenext >= &myline[LINELIM]) {
5076 if (strcmp(s, myline) == 0 || c == 0)
5079 write(tf, myline, (int) (thenext - myline));
5082 prs("here document `");
5092 * open here temp file.
5093 * if unquoted here, expand here temp file into second temp file.
5095 static int herein(char *hname, int xdoll)
5101 /* Avoid longjmp clobbering */
5107 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5109 hf = open(hname, O_RDONLY);
5115 char tname[30] = ".msh_XXXXXX";
5118 tf = mkstemp(tname);
5122 if (newenv(setjmp(errpt)) == 0) {
5123 PUSHIO(afile, hf, herechar);
5125 while ((c = subgetc(0, 0)) != 0) {
5127 write(tf, &c, sizeof c);
5133 tf = open(tname, O_RDONLY);
5140 static void scraphere(void)
5144 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5146 for (h = inhere; h != NULL; h = h->h_next) {
5147 if (h->h_iop && h->h_iop->io_name)
5148 unlink(h->h_iop->io_name);
5153 /* unlink here temp files before a freearea(area) */
5154 static void freehere(int area)
5156 struct here *h, *hl;
5158 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5161 for (h = acthere; h != NULL; h = h->h_next)
5162 if (getarea((char *) h) >= area) {
5163 if (h->h_iop->io_name != NULL)
5164 unlink(h->h_iop->io_name);
5166 acthere = h->h_next;
5168 hl->h_next = h->h_next;
5174 /* -------- sh.c -------- */
5179 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5180 int msh_main(int argc, char **argv)
5186 int (*iof) (struct ioarg *);
5190 sharedbuf.id = AFID_NOBUF;
5191 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 (e.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, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
5372 if (interactive && e.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.