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;
273 static int trapset; /* trap pending */
275 static int yynerrs; /* yacc */
277 /* moved to G: static char line[LINELIM]; */
279 #if ENABLE_FEATURE_EDITING
280 static char *current_prompt;
281 static line_input_t *line_input_state;
288 static const char *rexecve(char *c, char **v, char **envp);
289 static char *evalstr(char *cp, int f);
290 static char *putn(int n);
291 static char *unquote(char *as);
292 static int rlookup(char *n);
293 static struct wdblock *glob(char *cp, struct wdblock *wb);
294 static int my_getc(int ec);
295 static int subgetc(char ec, int quoted);
296 static char **makenv(int all, struct wdblock *wb);
297 static char **eval(char **ap, int f);
298 static int setstatus(int s);
299 static int waitfor(int lastpid, int canintr);
301 static void onintr(int s); /* SIGINT handler */
303 static int newenv(int f);
304 static void quitenv(void);
305 static void next(int f);
306 static void setdash(void);
307 static void onecommand(void);
308 static void runtrap(int i);
311 /* -------- area stuff -------- */
313 #define REGSIZE sizeof(struct region)
315 /* #define SHRINKBY (64) */
319 #define ALIGN (sizeof(int)-1)
328 /* -------- grammar stuff -------- */
353 /* Added for "." file expansion */
356 #define YYERRCODE 300
359 #define CONTIN 01 /* skip new lines to complete command */
361 static struct op *pipeline(int cf);
362 static struct op *andor(void);
363 static struct op *c_list(void);
364 static int synio(int cf);
365 static void musthave(int c, int cf);
366 static struct op *simple(void);
367 static struct op *nested(int type, int mark);
368 static struct op *command(int cf);
369 static struct op *dogroup(int onlydone);
370 static struct op *thenpart(void);
371 static struct op *elsepart(void);
372 static struct op *caselist(void);
373 static struct op *casepart(void);
374 static char **pattern(void);
375 static char **wordlist(void);
376 static struct op *list(struct op *t1, struct op *t2);
377 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
378 static struct op *newtp(void);
379 static struct op *namelist(struct op *t);
380 static char **copyw(void);
381 static void word(char *cp);
382 static struct ioword **copyio(void);
383 static struct ioword *io(int u, int f, char *cp);
384 static int yylex(int cf);
385 static int collect(int c, int c1);
386 static int dual(int c);
387 static void diag(int ec);
388 static char *tree(unsigned size);
390 /* -------- var.h -------- */
399 #define COPYV 1 /* flag to setval, suggesting copy */
400 #define RONLY 01 /* variable is read-only */
401 #define EXPORT 02 /* variable is to be exported */
402 #define GETCELL 04 /* name & value space was got with getcell */
404 static int yyparse(void);
406 static int execute(struct op *t, int *pin, int *pout, int act);
409 /* -------- io.h -------- */
412 unsigned id; /* buffer id */
413 char buf[512]; /* buffer */
414 char *bufp; /* pointer into buffer */
415 char *ebufp; /* pointer to end of buffer */
418 /* possible arguments to an IO function */
422 int afile; /* file descriptor */
423 unsigned afid; /* buffer id */
424 long afpos; /* file position */
425 struct iobuf *afbuf; /* buffer for this file */
428 /* an input generator's state */
430 int (*iofn) (struct ioarg *, struct io *);
433 char prev; /* previous character read by readc() */
434 char nlcount; /* for `'s */
435 char xchar; /* for `'s */
436 char task; /* reason for pushed IO */
439 #define XOTHER 0 /* none of the below */
440 #define XDOLL 1 /* expanding ${} */
441 #define XGRAVE 2 /* expanding `'s */
442 #define XIO 3 /* file IO */
446 * input generators for IO structure
448 static int nlchar(struct ioarg *ap);
449 static int strchar(struct ioarg *ap);
450 static int qstrchar(struct ioarg *ap);
451 static int filechar(struct ioarg *ap);
452 static int herechar(struct ioarg *ap);
453 static int linechar(struct ioarg *ap);
454 static int gravechar(struct ioarg *ap, struct io *iop);
455 static int qgravechar(struct ioarg *ap, struct io *iop);
456 static int dolchar(struct ioarg *ap);
457 static int wdchar(struct ioarg *ap);
458 static void scraphere(void);
459 static void freehere(int area);
460 static void gethere(void);
461 static void markhere(char *s, struct ioword *iop);
462 static int herein(char *hname, int xdoll);
463 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
466 static int eofc(void);
467 static int readc(void);
468 static void unget(int c);
469 static void ioecho(char c);
475 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
476 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
477 static int remap(int fd);
478 static int openpipe(int *pv);
479 static void closepipe(int *pv);
480 static struct io *setbase(struct io *ip);
482 /* -------- word.h -------- */
484 #define NSTART 16 /* default number of words to allow for initially */
489 /* bounds are arbitrary */
493 static struct wdblock *addword(char *wd, struct wdblock *wb);
494 static struct wdblock *newword(int nw);
495 static char **getwords(struct wdblock *wb);
497 /* -------- misc stuff -------- */
499 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
500 static int iosetup(struct ioword *iop, int pipein, int pipeout);
501 static void brkset(struct brkcon *bc);
502 static int dolabel(struct op *t);
503 static int dohelp(struct op *t);
504 static int dochdir(struct op *t);
505 static int doshift(struct op *t);
506 static int dologin(struct op *t);
507 static int doumask(struct op *t);
508 static int doexec(struct op *t);
509 static int dodot(struct op *t);
510 static int dowait(struct op *t);
511 static int doread(struct op *t);
512 static int doeval(struct op *t);
513 static int dotrap(struct op *t);
514 static int getsig(char *s);
515 static void setsig(int n, sighandler_t f);
516 static int getn(char *as);
517 static int dobreak(struct op *t);
518 static int docontinue(struct op *t);
519 static int brkcontin(char *cp, int val);
520 static int doexit(struct op *t);
521 static int doexport(struct op *t);
522 static int doreadonly(struct op *t);
523 static void rdexp(char **wp, void (*f) (struct var *), int key);
524 static void badid(char *s);
525 static int doset(struct op *t);
526 static void varput(char *s, int out);
527 static int dotimes(struct op *t);
528 static int expand(const char *cp, struct wdblock **wbp, int f);
529 static char *blank(int f);
530 static int dollar(int quoted);
531 static int grave(int quoted);
532 static void globname(char *we, char *pp);
533 static char *generate(char *start1, char *end1, char *middle, char *end);
534 static int anyspcl(struct wdblock *wb);
535 static int xstrcmp(char *p1, char *p2);
536 static void glob0(char *a0, unsigned a1, int a2,
537 int (*a3) (char *, char *));
538 static void readhere(char **name, char *s, int ec);
539 static int xxchar(struct ioarg *ap);
544 struct ioword *h_iop;
548 static const char *const signame[] = {
551 NULL, /* interrupt */
553 "Illegal instruction",
557 "Floating Point Exception",
562 NULL, /* broken pipe */
570 int (*builtinfunc)(struct op *t);
572 static const struct builtincmd builtincmds[] = {
575 { "break" , dobreak },
577 { "continue", docontinue },
581 { "export" , doexport },
583 { "login" , dologin },
584 { "newgrp" , dologin },
586 { "readonly", doreadonly },
588 { "shift" , doshift },
589 { "times" , dotimes },
591 { "umask" , doumask },
596 static struct op *scantree(struct op *);
597 static struct op *dowholefile(int, int);
605 static int interactive; /* Is this an interactive shell */
607 static int multiline; /* \n changed to ; */
608 static struct op *outtree; /* result from parser */
611 static struct brkcon *brklist;
613 static struct wdblock *wdlist;
614 static struct wdblock *iolist;
617 static struct var *mshdbg_var;
619 static struct var *vlist; /* dictionary */
620 static struct var *homedir; /* home directory */
621 static struct var *prompt; /* main prompt */
622 static struct var *cprompt; /* continuation prompt */
623 static struct var *path; /* search path for commands */
624 static struct var *shell; /* shell to interpret command files */
625 static struct var *ifs; /* field separators */
627 static int areanum; /* current allocation area */
628 static int intr; /* interrupt pending */
630 static char *null = (char*)""; /* null value for variable */
631 static int heedint = 1; /* heed interrupt signals */
632 static void (*qflag)(int) = SIG_IGN;
636 static int iounit = IODEFAULT;
637 static YYSTYPE yylval;
638 static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
640 static struct here *inhere; /* list of hear docs while parsing */
641 static struct here *acthere; /* list of active here documents */
642 static struct region *areabot; /* bottom of area */
643 static struct region *areatop; /* top of area */
644 static struct region *areanxt; /* starting point of scan */
646 static void *brkaddr;
648 #define AFID_NOBUF (~0)
653 * parsing & execution environment
659 xint *errpt; /* void * */
666 struct env global_env;
667 struct ioarg temparg; // = { .afid = AFID_NOBUF }; /* temporary for PUSHIO */
668 unsigned bufid; // = AFID_ID; /* buffer id counter */
669 char ourtrap[_NSIG + 1];
670 char *trap[_NSIG + 1];
671 struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
672 struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
673 struct ioarg ioargstack[NPUSH];
677 * -k: look for name=value everywhere on command line
679 * -t: exit after reading and executing one command
682 * -u: unset variables net diagnostic
684 char flags['z' - 'a' + 1];
685 char filechar_cmdbuf[BUFSIZ];
687 char child_cmd[LINELIM];
689 struct io iostack[NPUSH];
691 char grave__var_name[LINELIM];
692 char grave__alt_value[LINELIM];
695 #define G (*ptr_to_globals)
696 #define global_env (G.global_env )
697 #define temparg (G.temparg )
698 #define bufid (G.bufid )
699 #define ourtrap (G.ourtrap )
700 #define trap (G.trap )
701 #define sharedbuf (G.sharedbuf )
702 #define mainbuf (G.mainbuf )
703 #define ioargstack (G.ioargstack )
704 /* this looks weird, but is OK ... we index FLAG with 'a'...'z' */
705 #define FLAG (G.flags - 'a' )
706 #define filechar_cmdbuf (G.filechar_cmdbuf)
707 #define line (G.line )
708 #define child_cmd (G.child_cmd )
709 #define iostack (G.iostack )
710 #define INIT_G() do { \
711 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
712 global_env.linep = line; \
713 global_env.iobase = iostack; \
714 global_env.iop = iostack - 1; \
715 global_env.iofd = FDBASE; \
716 temparg.afid = AFID_NOBUF; \
721 /* in substitution */
722 #define INSUB() (global_env.iop->task == XGRAVE || global_env.iop->task == XDOLL)
724 #define RUN(what, arg, gen) ((temparg.what = (arg)), run(&temparg, (gen)))
727 void print_t(struct op *t)
729 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
730 T_CMD_NAMES[t->type], t->words, t->ioact));
733 DBGPRINTF(("T: W1: %s", t->words[0]));
737 void print_tree(struct op *head)
740 DBGPRINTF(("PRINT_TREE: no tree\n"));
744 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
748 print_tree(head->left);
751 print_tree(head->right);
753 #endif /* MSHDEBUG */
759 static void prs(const char *s)
762 write(2, s, strlen(s));
765 static void prn(unsigned u)
770 static void echo(char **wp)
775 for (i = 0; wp[i]; i++) {
783 static void closef(int i)
789 static void closeall(void)
793 for (u = NUFILE; u < NOFILE;)
798 /* fail but return to process next command */
799 static void fail(void) ATTRIBUTE_NORETURN;
800 static void fail(void)
806 /* abort shell (or fail in subshell) */
807 static void leave(void) ATTRIBUTE_NORETURN;
808 static void leave(void)
810 DBGPRINTF(("LEAVE: leave called!\n"));
821 static void warn(const char *s)
832 static void err(const char *s)
839 if (global_env.errpt)
840 longjmp(global_env.errpt, 1);
842 global_env.iop = global_env.iobase = iostack;
846 /* -------- area.c -------- */
849 * All memory between (char *)areabot and (char *)(areatop+1) is
850 * exclusively administered by the area management routines.
851 * It is assumed that sbrk() and brk() manipulate the high end.
855 void * __q = (void *)-1; \
856 if (brkaddr + (int)(X) < brktop) { \
858 brkaddr += (int)(X); \
863 static void initarea(void)
865 brkaddr = xmalloc(AREASIZE);
866 brktop = brkaddr + AREASIZE;
868 while ((long) sbrk(0) & ALIGN)
870 areabot = (struct region *) sbrk(REGSIZE);
872 areabot->next = areabot;
873 areabot->area = BUSY;
878 static char *getcell(unsigned nbytes)
881 struct region *p, *q;
888 /* silly and defeats the algorithm */
890 * round upwards and add administration area
892 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
895 if (p->area > areanum) {
899 while ((q = p->next)->area > areanum && q != areanxt)
902 * exit loop if cell big enough
911 i = nregio >= GROWBY ? nregio : GROWBY;
912 p = (struct region *) sbrk(i * REGSIZE);
913 if (p == (struct region *) -1)
918 abort(); /* allocated areas are contiguous */
928 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
930 areanxt = p + nregio;
933 * split into requested area and rest
935 if (areanxt + 1 > q) {
937 abort(); /* insufficient space left for admin */
940 areanxt->area = FREE;
944 return (char *) (p + 1);
947 static void freecell(char *cp)
951 p = (struct region *) cp;
959 #define DELETE(obj) freecell((char *)obj)
961 static void freearea(int a)
963 struct region *p, *top;
966 for (p = areabot; p != top; p = p->next)
971 static void setarea(char *cp, int a)
975 p = (struct region *) cp;
980 static int getarea(char *cp)
982 return ((struct region *) cp - 1)->area;
985 static void garbage(void)
987 struct region *p, *q, *top;
990 for (p = areabot; p != top; p = p->next) {
991 if (p->area > areanum) {
992 while ((q = p->next)->area > areanum)
998 if (areatop >= q + SHRINKBY && q->area > areanum) {
999 brk((char *) (q + 1));
1007 static char *space(int n)
1013 err("out of string space");
1017 static char *strsave(const char *s, int a)
1021 cp = space(strlen(s) + 1);
1023 // FIXME: I highly doubt this is good.
1032 /* -------- var.c -------- */
1034 static int eqname(const char *n1, const char *n2)
1036 for (; *n1 != '=' && *n1 != '\0'; n1++)
1039 return *n2 == '\0' || *n2 == '=';
1042 static const char *findeq(const char *cp)
1044 while (*cp != '\0' && *cp != '=')
1050 * Find the given name in the dictionary
1051 * and return its value. If the name was
1052 * not previously there, enter it now and
1053 * return a null value.
1055 static struct var *lookup(const char *n)
1057 // FIXME: dirty hack
1058 static struct var dummy;
1066 dummy.name = (char*)n;
1067 for (c = 0; isdigit(*n) && c < 1000; n++)
1068 c = c * 10 + *n - '0';
1069 dummy.status = RONLY;
1070 dummy.value = (c <= dolc ? dolv[c] : null);
1074 for (vp = vlist; vp; vp = vp->next)
1075 if (eqname(vp->name, n))
1079 vp = (struct var *) space(sizeof(*vp));
1080 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1081 dummy.name = dummy.value = (char*)"";
1086 while ((*xp = *n++) != '\0' && *xp != '=')
1090 setarea((char *) vp, 0);
1091 setarea((char *) vp->name, 0);
1094 vp->status = GETCELL;
1100 * if name is not NULL, it must be
1101 * a prefix of the space `val',
1103 * this is all so that exporting
1104 * values is reasonably painless.
1106 static void nameval(struct var *vp, const char *val, const char *name)
1112 if (vp->status & RONLY) {
1114 while (*xp && *xp != '=')
1115 fputc(*xp++, stderr);
1116 err(" is read-only");
1121 xp = space(strlen(vp->name) + strlen(val) + 2);
1124 /* make string: name=value */
1128 while ((*xp = *cp++) != '\0' && *xp != '=')
1135 if (vp->status & GETCELL)
1136 freecell(vp->name); /* form new string `name=value' */
1137 vp->name = (char*)name;
1138 vp->value = (char*)val;
1143 * give variable at `vp' the value `val'.
1145 static void setval(struct var *vp, const char *val)
1147 nameval(vp, val, NULL);
1150 static void export(struct var *vp)
1152 vp->status |= EXPORT;
1155 static void ronly(struct var *vp)
1157 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1158 vp->status |= RONLY;
1161 static int isassign(const char *s)
1164 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1167 /* no isalpha() - we shouldn't use locale */
1168 /* c | 0x20 - lowercase (Latin) letters */
1169 if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
1180 && (unsigned)(c - '0') > 9 /* not number */
1181 && (unsigned)((c|0x20) - 'a') > 25 /* not letter */
1188 static int assign(const char *s, int cf)
1193 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1195 if (!isalpha(*s) && *s != '_')
1197 for (cp = s; *cp != '='; cp++)
1198 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1201 nameval(vp, ++cp, cf == COPYV ? NULL : s);
1203 vp->status &= ~GETCELL;
1207 static int checkname(char *cp)
1209 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1211 if (!isalpha(*cp++) && *(cp - 1) != '_')
1214 if (!isalnum(*cp++) && *(cp - 1) != '_')
1219 static void putvlist(int f, int out)
1223 for (vp = vlist; vp; vp = vp->next) {
1224 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1225 if (vp->status & EXPORT)
1226 write(out, "export ", 7);
1227 if (vp->status & RONLY)
1228 write(out, "readonly ", 9);
1229 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1230 write(out, "\n", 1);
1239 static void sig(int i)
1245 static void runtrap(int i)
1250 if (trapstr == NULL)
1256 RUN(aword, trapstr, nlchar);
1260 static void setdash(void)
1264 char m['z' - 'a' + 1];
1267 for (c = 'a'; c <= 'z'; c++)
1271 setval(lookup("-"), m);
1274 static int newfile(char *s)
1278 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1281 if (NOT_LONE_DASH(s)) {
1282 DBGPRINTF(("NEWFILE: s is %s\n", s));
1283 f = open(s, O_RDONLY);
1286 err(": cannot open");
1296 struct op *scantree(struct op *head)
1303 if (head->left != NULL) {
1304 dotnode = scantree(head->left);
1309 if (head->right != NULL) {
1310 dotnode = scantree(head->right);
1315 if (head->words == NULL)
1318 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1320 if ((head->type != TDOT) && LONE_CHAR(head->words[0], '.')) {
1321 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1329 static void onecommand(void)
1334 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1336 while (global_env.oenv)
1345 global_env.errpt = 0;
1346 global_env.linep = line;
1354 setjmp(failpt); /* Bruce Evans' fix */
1356 if (setjmp(failpt) || yyparse() || intr) {
1357 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1359 while (global_env.oenv)
1362 if (!interactive && intr)
1375 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1377 execute(outtree, NOPIPE, NOPIPE, 0);
1380 if (!interactive && intr) {
1392 static int newenv(int f)
1396 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1403 ep = (struct env *) space(sizeof(*ep));
1405 while (global_env.oenv)
1410 global_env.oenv = ep;
1411 global_env.errpt = errpt;
1416 static void quitenv(void)
1421 DBGPRINTF(("QUITENV: global_env.oenv=%p\n", global_env.oenv));
1423 ep = global_env.oenv;
1425 fd = global_env.iofd;
1427 /* should close `'d files */
1429 while (--fd >= global_env.iofd)
1435 * Is character c in s?
1437 static int any(int c, const char *s)
1446 * Is any character from s1 in s2?
1448 static int anys(const char *s1, const char *s2)
1456 static char *putn(int n)
1461 static void next(int f)
1463 PUSHIO(afile, f, filechar);
1466 static void onintr(int s) /* ANSI C requires a parameter */
1468 signal(SIGINT, onintr);
1475 } else if (heedint) {
1482 /* -------- gmatch.c -------- */
1484 * int gmatch(string, pattern)
1485 * char *string, *pattern;
1487 * Match a pattern as in sh(1).
1492 #define QMASK (CMASK & ~QUOTE)
1493 #define NOT '!' /* might use ^ */
1495 static const char *cclass(const char *p, int sub)
1497 int c, d, not, found;
1507 if (p[1] == '-' && p[2] != ']') {
1512 if (c == sub || (c <= sub && sub <= d))
1514 } while (*++p != ']');
1515 return found ? p + 1 : NULL;
1518 static int gmatch(const char *s, const char *p)
1522 if (s == NULL || p == NULL)
1525 while ((pc = *p++ & CMASK) != '\0') {
1542 if (*p == '\0' || gmatch(s, p))
1544 } while (*s++ != '\0');
1548 if (sc != (pc & ~QUOTE))
1556 /* -------- csyn.c -------- */
1558 * shell: syntax (C version)
1561 static void yyerror(const char *s) ATTRIBUTE_NORETURN;
1562 static void yyerror(const char *s)
1565 if (interactive && global_env.iop <= iostack) {
1567 while (eofc() == 0 && yylex(0) != '\n');
1573 static void zzerr(void) ATTRIBUTE_NORETURN;
1574 static void zzerr(void)
1576 yyerror("syntax error");
1581 DBGPRINTF7(("YYPARSE: enter...\n"));
1588 return (yynerrs != 0);
1591 static struct op *pipeline(int cf)
1596 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1600 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1603 while ((c = yylex(0)) == '|') {
1604 p = command(CONTIN);
1606 DBGPRINTF8(("PIPELINE: error!\n"));
1610 if (t->type != TPAREN && t->type != TCOM) {
1611 /* shell statement */
1612 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1615 t = block(TPIPE, t, p, NOWORDS);
1620 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1624 static struct op *andor(void)
1629 DBGPRINTF7(("ANDOR: enter...\n"));
1633 DBGPRINTF9(("ANDOR: t=%p\n", t));
1636 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1637 p = pipeline(CONTIN);
1639 DBGPRINTF8(("ANDOR: error!\n"));
1643 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1649 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1653 static struct op *c_list(void)
1658 DBGPRINTF7(("C_LIST: enter...\n"));
1665 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1667 while ((c = yylex(0)) == ';' || c == '&'
1668 || (multiline && c == '\n')) {
1676 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1684 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1688 static int synio(int cf)
1694 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1697 if (c != '<' && c != '>') {
1704 iop = io(iounit, i, yylval.cp);
1708 markhere(yylval.cp, iop);
1710 DBGPRINTF7(("SYNIO: returning 1\n"));
1714 static void musthave(int c, int cf)
1716 peeksym = yylex(cf);
1718 DBGPRINTF7(("MUSTHAVE: error!\n"));
1725 static struct op *simple(void)
1731 switch (peeksym = yylex(0)) {
1752 static struct op *nested(int type, int mark)
1756 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1762 return block(type, t, NOBLOCK, NOWORDS);
1765 static struct op *command(int cf)
1768 struct wdblock *iosave;
1771 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1797 t = nested(TPAREN, ')');
1801 t = nested(TBRACE, '}');
1811 t->words = wordlist();
1813 if (c != '\n' && c != ';')
1815 t->left = dogroup(0);
1823 t->type = c == WHILE ? TWHILE : TUNTIL;
1825 t->right = dogroup(1);
1837 musthave(IN, CONTIN);
1840 t->left = caselist();
1851 t->right = thenpart();
1860 musthave(WORD, 0); /* gets name of file */
1861 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1863 word(yylval.cp); /* add word to wdlist */
1864 word(NOWORD); /* terminate wdlist */
1865 t->words = copyw(); /* dup wdlist */
1875 DBGPRINTF(("COMMAND: returning %p\n", t));
1880 static struct op *dowholefile(int type, int mark)
1884 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
1889 t = block(type, t, NOBLOCK, NOWORDS);
1890 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
1894 static struct op *dogroup(int onlydone)
1900 if (c == DONE && onlydone)
1909 static struct op *thenpart(void)
1922 if (t->left == NULL)
1924 t->right = elsepart();
1928 static struct op *elsepart(void)
1933 switch (c = yylex(0)) {
1944 t->right = thenpart();
1953 static struct op *caselist(void)
1958 while ((peeksym = yylex(CONTIN)) != ESAC) {
1959 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
1960 t = list(t, casepart());
1963 DBGPRINTF(("CASELIST, returning t=%p\n", t));
1967 static struct op *casepart(void)
1971 DBGPRINTF7(("CASEPART: enter...\n"));
1975 t->words = pattern();
1978 peeksym = yylex(CONTIN);
1979 if (peeksym != ESAC)
1980 musthave(BREAK, CONTIN);
1982 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
1987 static char **pattern(void)
2004 static char **wordlist(void)
2014 while ((c = yylex(0)) == WORD)
2022 * supporting functions
2024 static struct op *list(struct op *t1, struct op *t2)
2026 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2033 return block(TLIST, t1, t2, NOWORDS);
2036 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2040 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2048 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2054 /* See if given string is a shell multiline (FOR, IF, etc) */
2055 static int rlookup(char *n)
2061 static const struct res restab[] = {
2084 const struct res *rp;
2086 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2088 for (rp = restab; rp->r_name[0]; rp++)
2089 if (strcmp(rp->r_name, n) == 0) {
2090 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2091 return rp->r_val; /* Return numeric code for shell multiline */
2094 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2095 return 0; /* Not a shell multiline */
2098 static struct op *newtp(void)
2102 t = (struct op *) tree(sizeof(*t));
2110 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2115 static struct op *namelist(struct op *t)
2117 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2118 T_CMD_NAMES[t->type], iolist));
2121 iolist = addword((char *) NULL, iolist);
2122 t->ioact = copyio();
2126 if (t->type != TCOM) {
2127 if (t->type != TPAREN && t->ioact != NULL) {
2128 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2129 t->ioact = t->left->ioact;
2130 t->left->ioact = NULL;
2141 static char **copyw(void)
2145 wd = getwords(wdlist);
2150 static void word(char *cp)
2152 wdlist = addword(cp, wdlist);
2155 static struct ioword **copyio(void)
2157 struct ioword **iop;
2159 iop = (struct ioword **) getwords(iolist);
2164 static struct ioword *io(int u, int f, char *cp)
2168 iop = (struct ioword *) tree(sizeof(*iop));
2172 iolist = addword((char *) iop, iolist);
2176 static int yylex(int cf)
2193 global_env.linep = line;
2196 line[LINELIM - 1] = '\0';
2199 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2204 if (any(c, "0123456789")) {
2207 if (c1 == '<' || c1 == '>') {
2211 *global_env.linep++ = c;
2216 case '#': /* Comment, skip to next newline or End-of-string */
2217 while ((c = my_getc(0)) != '\0' && c != '\n');
2222 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2226 DBGPRINTF9(("YYLEX: found $\n"));
2227 *global_env.linep++ = c;
2230 c = collect(c, '}');
2249 /* If more chars process them, else return NULL char */
2267 if (multiline || cf & CONTIN) {
2268 if (interactive && global_env.iop <= iostack) {
2269 #if ENABLE_FEATURE_EDITING
2270 current_prompt = cprompt->value;
2272 prs(cprompt->value);
2289 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2290 if (global_env.linep >= elinep)
2291 err("word too long");
2293 *global_env.linep++ = c;
2298 if (any(c, "\"'`$"))
2301 *global_env.linep++ = '\0';
2311 yylval.cp = strsave(line, areanum);
2316 static int collect(int c, int c1)
2320 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2322 *global_env.linep++ = c;
2323 while ((c = my_getc(c1)) != c1) {
2332 if (interactive && c == '\n' && global_env.iop <= iostack) {
2333 #if ENABLE_FEATURE_EDITING
2334 current_prompt = cprompt->value;
2336 prs(cprompt->value);
2339 *global_env.linep++ = c;
2342 *global_env.linep++ = c;
2344 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2349 /* "multiline commands" helper func */
2350 /* see if next 2 chars form a shell multiline */
2351 static int dual(int c)
2356 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2358 *cp++ = c; /* c is the given "peek" char */
2359 *cp++ = my_getc(0); /* get next char of input */
2360 *cp = '\0'; /* add EOS marker */
2362 c = rlookup(s); /* see if 2 chars form a shell multiline */
2364 unget(*--cp); /* String is not a shell multiline, put peek char back */
2366 return c; /* String is multiline, return numeric multiline (restab) code */
2369 static void diag(int ec)
2373 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2376 if (c == '>' || c == '<') {
2379 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2382 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2383 if (c != '&' || yylval.i == IOHERE)
2389 static char *tree(unsigned size)
2395 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2396 prs("command line too complicated\n");
2407 /* -------- exec.c -------- */
2409 static struct op **find1case(struct op *t, const char *w)
2417 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
2421 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
2422 T_CMD_NAMES[t->type]));
2424 if (t->type == TLIST) {
2425 tp = find1case(t->left, w);
2427 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
2430 t1 = t->right; /* TPAT */
2434 for (wp = t1->words; *wp;) {
2435 cp = evalstr(*wp++, DOSUB);
2436 if (cp && gmatch(w, cp)) {
2437 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
2443 DBGPRINTF(("FIND1CASE: returning NULL\n"));
2447 static struct op *findcase(struct op *t, const char *w)
2451 tp = find1case(t, w);
2452 return tp != NULL ? *tp : NULL;
2459 static int execute(struct op *t, int *pin, int *pout, int act)
2462 volatile int i, rv, a;
2466 struct op *outtree_save;
2470 /* Avoid longjmp clobbering */
2475 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2479 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2480 t->type, T_CMD_NAMES[t->type],
2481 ((t->words == NULL) ? "NULL" : t->words[0])));
2485 wp = (wp2 = t->words) != NULL
2486 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2491 DBGPRINTF3(("EXECUTE: TDOT\n"));
2493 outtree_save = outtree;
2495 newfile(evalstr(t->words[0], DOALL));
2497 t->left = dowholefile(TLIST, 0);
2500 outtree = outtree_save;
2503 rv = execute(t->left, pin, pout, 0);
2505 rv = execute(t->right, pin, pout, 0);
2509 rv = execute(t->left, pin, pout, 0);
2513 rv = forkexec(t, pin, pout, act, wp);
2523 pv[0] = remap(pv[0]);
2524 pv[1] = remap(pv[1]);
2525 (void) execute(t->left, pin, pv, 0);
2526 rv = execute(t->right, pv, pout, 0);
2531 (void) execute(t->left, pin, pout, 0);
2532 rv = execute(t->right, pin, pout, 0);
2537 int hinteractive = interactive;
2539 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2542 if (i == 0) { /* child */
2543 signal(SIGINT, SIG_IGN);
2544 signal(SIGQUIT, SIG_IGN);
2546 signal(SIGTERM, SIG_DFL);
2550 xopen(bb_dev_null, O_RDONLY);
2552 _exit(execute(t->left, pin, pout, FEXEC));
2554 interactive = hinteractive;
2556 setval(lookup("!"), putn(i));
2571 rv = execute(t->left, pin, pout, 0);
2573 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2574 rv = execute(t1, pin, pout, 0);
2585 while (*wp++ != NULL);
2587 vp = lookup(t->str);
2588 while (setjmp(bc.brkpt))
2592 for (t1 = t->left; i-- && *wp != NULL;) {
2594 rv = execute(t1, pin, pout, 0);
2596 brklist = brklist->nextlev;
2601 while (setjmp(bc.brkpt))
2606 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2607 rv = execute(t->right, pin, pout, 0);
2608 brklist = brklist->nextlev;
2613 if (t->right != NULL) {
2614 rv = !execute(t->left, pin, pout, 0) ?
2615 execute(t->right->left, pin, pout, 0) :
2616 execute(t->right->right, pin, pout, 0);
2621 cp = evalstr(t->str, DOSUB | DOTRIM);
2625 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2626 ((t->str == NULL) ? "NULL" : t->str),
2627 ((cp == NULL) ? "NULL" : cp)));
2629 t1 = findcase(t->left, cp);
2631 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2632 rv = execute(t1, pin, pout, 0);
2633 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2642 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2650 rv = execute(t1, pin, pout, 0);
2663 if (interactive && intr) {
2674 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2678 typedef int (*builtin_func_ptr)(struct op *);
2680 static builtin_func_ptr inbuilt(const char *s)
2682 const struct builtincmd *bp;
2684 for (bp = builtincmds; bp->name; bp++)
2685 if (strcmp(bp->name, s) == 0)
2686 return bp->builtinfunc;
2690 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2694 builtin_func_ptr shcom = NULL;
2696 const char *cp = NULL;
2697 struct ioword **iopp;
2707 struct brkcon *hbrklist;
2711 /* Avoid longjmp clobbering */
2721 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2723 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2724 ((t->words == NULL) ? "NULL" : t->words[0])));
2728 rv = -1; /* system-detected error */
2729 if (t->type == TCOM) {
2730 while (*wp++ != NULL)
2734 /* strip all initial assignments */
2735 /* not correct wrt PATH=yyy command etc */
2737 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2739 echo(cp ? wp : owp);
2742 if (cp == NULL && t->ioact == NULL) {
2743 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2745 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2746 return setstatus(0);
2749 shcom = inbuilt(cp);
2756 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2759 if (shcom == NULL && (f & FEXEC) == 0) {
2760 /* Save values in case the child process alters them */
2764 hinteractive = interactive;
2769 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2774 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2778 if (newpid > 0) { /* Parent */
2779 /* Restore values */
2783 interactive = hinteractive;
2794 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2797 /* Must be the child process, pid should be 0 */
2798 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2801 signal(SIGINT, SIG_IGN);
2802 signal(SIGQUIT, SIG_IGN);
2813 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2818 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2819 err("piping to/from shell builtins not yet done");
2827 xmove_fd(pin[0], 0);
2828 if (pin[1] != 0) close(pin[1]);
2831 xmove_fd(pout[1], 1);
2832 if (pout[1] != 1) close(pout[0]);
2837 if (shcom != NULL && shcom != doexec) {
2839 err(": cannot redirect shell command");
2845 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2853 i = setstatus((*shcom) (t));
2856 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2860 /* should use FIOCEXCL */
2861 for (i = FDBASE; i < NOFILE; i++)
2864 signal(SIGINT, SIG_DFL);
2865 signal(SIGQUIT, SIG_DFL);
2868 if (t->type == TPAREN)
2869 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2873 cp = rexecve(wp[0], wp, makenv(0, NULL));
2880 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2888 * 0< 1> are ignored as required
2891 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2897 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2900 if (iop->io_unit == IODEFAULT) /* take default */
2901 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2903 if (pipein && iop->io_unit == 0)
2906 if (pipeout && iop->io_unit == 1)
2909 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2910 if ((iop->io_flag & IOHERE) == 0) {
2911 cp = iop->io_name; /* huh?? */
2912 cp = evalstr(cp, DOSUB | DOTRIM);
2917 if (iop->io_flag & IODUP) {
2918 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2920 err(": illegal >& argument");
2924 iop->io_flag = IOCLOSE;
2925 iop->io_flag &= ~(IOREAD | IOWRITE);
2927 switch (iop->io_flag) {
2929 u = open(cp, O_RDONLY);
2933 case IOHERE | IOXHERE:
2934 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2935 cp = (char*)"here file";
2938 case IOWRITE | IOCAT:
2939 u = open(cp, O_WRONLY);
2941 lseek(u, (long) 0, SEEK_END);
2945 u = creat(cp, 0666);
2949 u = dup2(*cp - '0', iop->io_unit);
2953 close(iop->io_unit);
2962 if (u != iop->io_unit) {
2963 dup2(u, iop->io_unit);
2970 * Enter a new loop level (marked for break/continue).
2972 static void brkset(struct brkcon *bc)
2974 bc->nextlev = brklist;
2979 * Wait for the last process created.
2980 * Print a message for each process found
2981 * that was killed by a signal.
2982 * Ignore interrupt signals while waiting
2983 * unless `canintr' is true.
2985 static int waitfor(int lastpid, int canintr)
2989 int oheedint = heedint;
2996 if (errno != EINTR || canintr)
3001 if (rv < ARRAY_SIZE(signame)) {
3002 if (signame[rv] != NULL) {
3003 if (pid != lastpid) {
3010 if (pid != lastpid) {
3019 prs(" - core dumped");
3020 if (rv >= ARRAY_SIZE(signame) || signame[rv])
3026 } while (pid != lastpid);
3041 static int setstatus(int s)
3044 setval(lookup("?"), putn(s));
3049 * PATH-searching interface to execve.
3050 * If getenv("PATH") were kept up-to-date,
3051 * execvp might be used.
3053 static const char *rexecve(char *c, char **v, char **envp)
3058 int eacces = 0, asis = 0;
3061 if (ENABLE_FEATURE_SH_STANDALONE) {
3062 if (find_applet_by_name(name) >= 0) {
3063 /* We have to exec here since we vforked. Running
3064 * run_applet_and_exit() won't work and bad things
3066 execve(bb_busybox_exec_path, v, envp);
3070 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3072 sp = any('/', c) ? "" : path->value;
3073 asis = (*sp == '\0');
3074 while (asis || *sp != '\0') {
3076 tp = global_env.linep;
3077 for (; *sp != '\0'; tp++) {
3080 asis = (*sp == '\0');
3084 if (tp != global_env.linep)
3086 for (i = 0; (*tp++ = c[i++]) != '\0';);
3088 DBGPRINTF3(("REXECVE: global_env.linep is %s\n", global_env.linep));
3090 execve(global_env.linep, v, envp);
3094 *v = global_env.linep;
3096 *v = global_env.linep;
3097 execve(DEFAULT_SHELL, v, envp);
3102 return (char *) bb_msg_memory_exhausted;
3105 return "argument list too long";
3112 return errno == ENOENT ? "not found" : "cannot execute";
3116 * Run the command produced by generator `f'
3117 * applied to stream `arg'.
3119 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3122 struct wdblock *swdlist;
3123 struct wdblock *siolist;
3129 /* Avoid longjmp clobbering */
3133 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3134 areanum, outtree, failpt));
3144 if (newenv(setjmp(errpt)) == 0) {
3148 global_env.iobase = global_env.iop;
3151 if (setjmp(failpt) == 0 && yyparse() == 0)
3152 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3155 DBGPRINTF(("RUN: error from newenv()!\n"));
3162 freearea(areanum--);
3167 /* -------- do.c -------- */
3170 * built-in commands: doX
3173 static int dohelp(struct op *t)
3176 const struct builtincmd *x;
3178 puts("\nBuilt-in commands:\n"
3179 "-------------------");
3184 col += printf("%c%s", ((col == 0) ? '\t' : ' '), x->name);
3191 #if ENABLE_FEATURE_SH_STANDALONE
3193 const char *applet = applet_names;
3196 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applet);
3201 applet += strlen(applet) + 1;
3206 return EXIT_SUCCESS;
3209 static int dolabel(struct op *t)
3214 static int dochdir(struct op *t)
3216 const char *cp, *er;
3220 cp = homedir->value;
3223 er = ": no home directory";
3228 er = ": bad directory";
3230 prs(cp != NULL ? cp : "cd");
3235 static int doshift(struct op *t)
3239 n = t->words[1] ? getn(t->words[1]) : 1;
3241 err("nothing to shift");
3247 setval(lookup("#"), putn(dolc));
3252 * execute login and newgrp directly
3254 static int dologin(struct op *t)
3259 signal(SIGINT, SIG_DFL);
3260 signal(SIGQUIT, SIG_DFL);
3262 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3269 static int doumask(struct op *t)
3278 for (n = 3 * 4; (n -= 3) >= 0;)
3279 fputc('0' + ((i >> n) & 07), stderr);
3280 fputc('\n', stderr);
3282 /* huh??? '8','9' are not allowed! */
3283 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3284 n = n * 8 + (*cp - '0');
3290 static int doexec(struct op *t)
3297 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3303 if (setjmp(failpt) == 0)
3304 execute(t, NOPIPE, NOPIPE, FEXEC);
3310 static int dodot(struct op *t)
3318 DBGPRINTF(("DODOT: enter, t=%p, tleft %p, tright %p, global_env.linep is %s\n",
3319 t, t->left, t->right, ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3323 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3326 DBGPRINTF(("DODOT: cp is %s\n", cp));
3328 sp = any('/', cp) ? ":" : path->value;
3330 DBGPRINTF(("DODOT: sp is %s, global_env.linep is %s\n",
3331 ((sp == NULL) ? "NULL" : sp),
3332 ((global_env.linep == NULL) ? "NULL" : global_env.linep)));
3335 tp = global_env.linep;
3336 while (*sp && (*tp = *sp++) != ':')
3338 if (tp != global_env.linep)
3341 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3344 i = open(global_env.linep, O_RDONLY);
3348 DBGPRINTF(("DODOT: remap=%d, exstat=%d, global_env.iofd %d, i %d, global_env.linep is %s\n",
3349 maltmp, exstat, global_env.iofd, i, global_env.linep));
3351 next(maltmp); /* Basically a PUSHIO */
3353 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3365 static int dowait(struct op *t)
3377 setstatus(waitfor(i, 1));
3381 static int doread(struct op *t)
3387 if (t->words[1] == NULL) {
3388 err("Usage: read name ...");
3391 for (wp = t->words + 1; *wp; wp++) {
3392 for (cp = global_env.linep; !nl && cp < elinep - 1; cp++) {
3393 nb = read(0, cp, sizeof(*cp));
3394 if (nb != sizeof(*cp))
3397 if (nl || (wp[1] && any(*cp, ifs->value)))
3403 setval(lookup(*wp), global_env.linep);
3408 static int doeval(struct op *t)
3410 return RUN(awordlist, t->words + 1, wdchar);
3413 static int dotrap(struct op *t)
3418 if (t->words[1] == NULL) {
3419 for (i = 0; i <= _NSIG; i++)
3428 resetsig = isdigit(*t->words[1]);
3429 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3430 n = getsig(t->words[i]);
3434 if (*t->words[1] != '\0') {
3435 trap[n] = strsave(t->words[1], 0);
3444 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3452 static int getsig(char *s)
3457 if (n < 0 || n > _NSIG) {
3458 err("trap: bad signal number");
3464 static void setsig(int n, sighandler_t f)
3468 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3474 static int getn(char *as)
3485 for (n = 0; isdigit(*s); s++)
3486 n = (n * 10) + (*s - '0');
3489 err(": bad number");
3494 static int dobreak(struct op *t)
3496 return brkcontin(t->words[1], 1);
3499 static int docontinue(struct op *t)
3501 return brkcontin(t->words[1], 0);
3504 static int brkcontin(char *cp, int val)
3509 nl = cp == NULL ? 1 : getn(cp);
3516 brklist = bc->nextlev;
3519 err("bad break/continue level");
3523 longjmp(bc->brkpt, 1);
3527 static int doexit(struct op *t)
3534 setstatus(getn(cp));
3536 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3543 static int doexport(struct op *t)
3545 rdexp(t->words + 1, export, EXPORT);
3549 static int doreadonly(struct op *t)
3551 rdexp(t->words + 1, ronly, RONLY);
3555 static void rdexp(char **wp, void (*f) (struct var *), int key)
3557 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3558 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3561 for (; *wp != NULL; wp++) {
3562 if (isassign(*wp)) {
3566 for (cp = *wp; *cp != '='; cp++);
3578 static void badid(char *s)
3581 err(": bad identifier");
3584 static int doset(struct op *t)
3592 for (vp = vlist; vp; vp = vp->next)
3593 varput(vp->name, 1);
3597 /* bad: t->words++; */
3598 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3600 FLAG['x'] = FLAG['v'] = 0;
3610 if (*cp >= 'a' && *cp <= 'z')
3619 t->words[0] = dolv[0];
3620 for (n = 1; t->words[n]; n++)
3621 setarea((char *) t->words[n], 0);
3624 setval(lookup("#"), putn(dolc));
3625 setarea((char *) (dolv - 1), 0);
3630 static void varput(char *s, int out)
3632 if (isalnum(*s) || *s == '_') {
3633 write(out, s, strlen(s));
3634 write(out, "\n", 1);
3640 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3641 * This file contains code for the times builtin.
3643 static int dotimes(struct op *t)
3646 long clk_tck = sysconf(_SC_CLK_TCK);
3649 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3650 (int) (buf.tms_utime / clk_tck / 60),
3651 ((double) buf.tms_utime) / clk_tck,
3652 (int) (buf.tms_stime / clk_tck / 60),
3653 ((double) buf.tms_stime) / clk_tck,
3654 (int) (buf.tms_cutime / clk_tck / 60),
3655 ((double) buf.tms_cutime) / clk_tck,
3656 (int) (buf.tms_cstime / clk_tck / 60),
3657 ((double) buf.tms_cstime) / clk_tck);
3662 /* -------- eval.c -------- */
3667 * blank interpretation
3672 static char **eval(char **ap, int f)
3680 /* Avoid longjmp clobbering */
3685 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3691 if (newenv(setjmp(errpt)) == 0) {
3692 while (*ap && isassign(*ap))
3693 expand(*ap++, &wb, f & ~DOGLOB);
3695 for (wf = ap; *wf; wf++) {
3697 expand(*wf, &wb, f & ~DOGLOB);
3700 for (wb = addword((char *) 0, wb); *ap; ap++) {
3701 if (!FLAG['k'] || !isassign(*ap))
3702 expand(*ap, &wb, f & ~DOKEY);
3704 wb = addword((char *) 0, wb);
3710 return gflg ? (char **) NULL : wp;
3715 * Make the exported environment from the exported
3716 * names in the dictionary. Keyword assignments
3717 * will already have been done.
3719 static char **makenv(int all, struct wdblock *wb)
3723 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3725 for (vp = vlist; vp; vp = vp->next)
3726 if (all || vp->status & EXPORT)
3727 wb = addword(vp->name, wb);
3728 wb = addword((char *) 0, wb);
3729 return getwords(wb);
3732 static int expand(const char *cp, struct wdblock **wbp, int f)
3738 /* Avoid longjmp clobbering */
3742 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3749 if (!anys("$`'\"", cp) && !anys(ifs->value, cp)
3750 && ((f & DOGLOB) == 0 || !anys("[*?", cp))
3752 xp = strsave(cp, areanum);
3755 *wbp = addword(xp, *wbp);
3759 if (newenv(setjmp(errpt)) == 0) {
3760 PUSHIO(aword, cp, strchar);
3761 global_env.iobase = global_env.iop;
3762 while ((xp = blank(f)) && gflg == 0) {
3763 global_env.linep = xp;
3764 xp = strsave(xp, areanum);
3765 if ((f & DOGLOB) == 0) {
3768 *wbp = addword(xp, *wbp);
3770 *wbp = glob(xp, *wbp);
3778 static char *evalstr(char *cp, int f)
3782 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3785 if (expand(cp, &wb, f)) {
3786 if (wb == NULL || wb->w_nword == 0
3787 || (cp = wb->w_words[0]) == NULL
3789 // TODO: I suspect that
3790 // char *evalstr(char *cp, int f) is actually
3791 // const char *evalstr(const char *cp, int f)!
3802 * Blank interpretation and quoting
3804 static char *blank(int f)
3808 int scanequals, foundequals;
3810 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3812 sp = global_env.linep;
3813 scanequals = f & DOKEY;
3817 c = subgetc('"', foundequals);
3820 if (sp == global_env.linep)
3822 *global_env.linep++ = 0;
3826 if (f & DOBLANK && any(c, ifs->value))
3835 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3838 if (c == '\'' || !any(c, "$`\""))
3840 *global_env.linep++ = c;
3845 if (!isalpha(c) && c != '_')
3848 c = subgetc('"', foundequals);
3850 f & (DOBLANK && any(c, ifs->value)) ||
3851 (!INSUB() && any(c, "\"'"))) {
3862 } else if (!isalnum(c) && c != '_')
3865 *global_env.linep++ = c;
3867 *global_env.linep++ = 0;
3872 * Get characters, substituting for ` and $
3874 static int subgetc(char ec, int quoted)
3878 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3882 if (!INSUB() && ec != '\'') {
3884 if (grave(quoted) == 0)
3886 global_env.iop->task = XGRAVE;
3892 global_env.iop->task = XDOLL;
3901 * Prepare to generate the string returned by ${} substitution.
3903 static int dollar(int quoted)
3908 char *s, c, *cp = NULL;
3911 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
3914 s = global_env.linep;
3916 *global_env.linep++ = c;
3917 if (isalpha(c) || c == '_') {
3918 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
3919 if (global_env.linep < elinep)
3920 *global_env.linep++ = c;
3925 oiop = global_env.iop;
3926 otask = global_env.iop->task;
3928 global_env.iop->task = XOTHER;
3929 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
3930 if (global_env.linep < elinep)
3931 *global_env.linep++ = c;
3932 if (oiop == global_env.iop)
3933 global_env.iop->task = otask;
3940 if (global_env.linep >= elinep) {
3941 err("string in ${} too long");
3943 global_env.linep -= 10;
3945 *global_env.linep = 0;
3947 for (cp = s + 1; *cp; cp++)
3948 if (any(*cp, "=-+?")) {
3953 if (s[1] == 0 && (*s == '*' || *s == '@')) {
3955 /* currently this does not distinguish $* and $@ */
3956 /* should check dollar */
3957 global_env.linep = s;
3958 PUSHIO(awordlist, dolv + 1, dolchar);
3960 } else { /* trap the nasty ${=} */
3971 err("cannot use ${...=...} with $n");
3980 dolp = strsave(cp, areanum);
3985 prs("missing value for ");
3992 } else if (c == '+')
3993 dolp = strsave(cp, areanum);
3994 if (FLAG['u'] && dolp == null) {
3995 prs("unset variable: ");
3999 global_env.linep = s;
4000 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4005 * Run the command in `...` and read its output.
4008 static int grave(int quoted)
4010 /* moved to G: static char child_cmd[LINELIM]; */
4021 char *argument_list[4];
4022 struct wdblock *wb = NULL;
4025 /* Avoid longjmp clobbering */
4029 for (cp = global_env.iop->argp->aword; *cp != '`'; cp++) {
4031 err("no closing `");
4036 /* string copy with dollar expansion */
4037 src = global_env.iop->argp->aword;
4042 while ((*src != '`') && (count < LINELIM)) {
4047 if (*src == '$' && !ignore && !ignore_once) {
4049 /* moved to G to reduce stack usage
4050 char var_name[LINELIM];
4051 char alt_value[LINELIM];
4053 #define var_name (G.grave__var_name)
4054 #define alt_value (G.grave__alt_value)
4067 var_name[var_index++] = *src++;
4068 while (isalnum(*src) || *src=='_')
4069 var_name[var_index++] = *src++;
4070 var_name[var_index] = 0;
4083 err("unclosed ${\n");
4088 while (*src && (*src != '}')) {
4089 alt_value[alt_index++] = *src++;
4091 alt_value[alt_index] = 0;
4093 err("unclosed ${\n");
4100 if (isalpha(*var_name)) {
4101 /* let subshell handle it instead */
4103 char *namep = var_name;
4111 char *altp = alt_value;
4119 wb = addword(lookup(var_name)->name, wb);
4123 vp = lookup(var_name);
4124 if (vp->value != null)
4125 value = (operator == '+') ?
4126 alt_value : vp->value;
4127 else if (operator == '?') {
4130 } else if (alt_index && (operator != '+')) {
4132 if (operator == '=')
4137 while (*value && (count < LINELIM)) {
4152 if (openpipe(pf) < 0)
4155 while ((i = vfork()) == -1 && errno == EAGAIN);
4157 DBGPRINTF3(("GRAVE: i is %p\n", io));
4161 err((char *) bb_msg_memory_exhausted);
4165 waitpid(i, NULL, 0);
4166 global_env.iop->argp->aword = ++cp;
4168 PUSHIO(afile, remap(pf[0]),
4169 (int (*)(struct ioarg *)) ((quoted) ? qgravechar : gravechar));
4172 /* allow trapped signals */
4173 /* XXX - Maybe this signal stuff should go as well? */
4174 for (j = 0; j <= _NSIG; j++)
4175 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4178 /* Testcase where below checks are needed:
4179 * close stdout & run this script:
4184 if (pf[0] != 1) close(pf[0]);
4186 argument_list[0] = (char *) DEFAULT_SHELL;
4187 argument_list[1] = (char *) "-c";
4188 argument_list[2] = child_cmd;
4189 argument_list[3] = NULL;
4191 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4192 prs(argument_list[0]);
4199 static char *unquote(char *as)
4210 /* -------- glob.c -------- */
4216 #define scopy(x) strsave((x), areanum)
4218 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4220 static struct wdblock *cl, *nl;
4221 static const char spcl[] ALIGN1= "[?*";
4223 static struct wdblock *glob(char *cp, struct wdblock *wb)
4231 for (pp = cp; *pp; pp++)
4234 else if (!any(*pp & ~QUOTE, spcl))
4237 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4238 nl = newword(cl->w_nword * 2);
4239 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4240 for (pp = cl->w_words[i]; *pp; pp++)
4241 if (any(*pp, spcl)) {
4242 globname(cl->w_words[i], pp);
4246 nl = addword(scopy(cl->w_words[i]), nl);
4248 for (i = 0; i < cl->w_nword; i++)
4249 DELETE(cl->w_words[i]);
4252 for (i = 0; i < cl->w_nword; i++)
4253 unquote(cl->w_words[i]);
4254 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4256 for (i = 0; i < cl->w_nword; i++)
4257 wb = addword(cl->w_words[i], wb);
4262 wb = addword(unquote(cp), wb);
4266 static void globname(char *we, char *pp)
4269 char *name, *gp, *dp;
4273 char dname[NAME_MAX + 1];
4276 for (np = we; np != pp; pp--)
4279 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4283 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4292 dname[NAME_MAX] = '\0';
4293 while ((de = readdir(dirp)) != NULL) {
4294 /* XXX Hmmm... What this could be? (abial) */
4296 if (ent[j].d_ino == 0)
4299 strncpy(dname, de->d_name, NAME_MAX);
4300 if (dname[0] == '.')
4303 for (k = 0; k < NAME_MAX; k++)
4304 if (any(dname[k], spcl))
4306 if (gmatch(dname, gp)) {
4307 name = generate(we, pp, dname, np);
4308 if (*np && !anys(np, spcl)) {
4309 if (stat(name, &dbuf)) {
4314 nl = addword(name, nl);
4323 * generate a pathname as below.
4324 * start..end1 / middle end
4325 * the slashes come for free
4327 static char *generate(char *start1, char *end1, char *middle, char *end)
4332 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4333 for (xp = start1; xp != end1;)
4335 for (xp = middle; (*op++ = *xp++) != '\0';);
4337 for (xp = end; (*op++ = *xp++) != '\0';);
4341 static int anyspcl(struct wdblock *wb)
4347 for (i = 0; i < wb->w_nword; i++)
4348 if (anys(spcl, *wd++))
4353 static int xstrcmp(char *p1, char *p2)
4355 return strcmp(*(char **) p1, *(char **) p2);
4359 /* -------- word.c -------- */
4361 static struct wdblock *newword(int nw)
4365 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4371 static struct wdblock *addword(char *wd, struct wdblock *wb)
4373 struct wdblock *wb2;
4377 wb = newword(NSTART);
4379 if (nw >= wb->w_bsize) {
4380 wb2 = newword(nw * 2);
4381 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4382 nw * sizeof(char *));
4387 wb->w_words[wb->w_nword++] = wd;
4391 static char **getwords(struct wdblock *wb)
4398 if (wb->w_nword == 0) {
4402 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4403 memcpy((char *) wd, (char *) wb->w_words, nb);
4404 DELETE(wb); /* perhaps should done by caller */
4408 static int (*func) (char *, char *);
4411 static void glob3(char *i, char *j, char *k)
4413 char *index1, *index2, *index3;
4423 *index1++ = *index3;
4424 *index3++ = *index2;
4429 static void glob2(char *i, char *j)
4431 char *index1, *index2, c;
4439 *index1++ = *index2;
4444 static void glob1(char *base, char *lim)
4455 n = (int) (lim - base);
4458 n = v2 * (n / (2 * v2));
4459 hptr = lptr = base + n;
4464 c = (*func) (i, lptr);
4478 c = (*func) (hptr, j);
4502 if (lptr - base >= lim - hptr) {
4503 glob1(hptr + v2, lim);
4518 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4522 glob1(a0, a0 + a1 * a2);
4526 /* -------- io.c -------- */
4532 static int my_getc(int ec)
4536 if (global_env.linep > elinep) {
4537 while ((c = readc()) != '\n' && c);
4538 err("input line too long");
4543 if ((ec != '\'') && (ec != '`') && (global_env.iop->task != XGRAVE)) {
4546 if (c == '\n' && ec != '\"')
4554 static void unget(int c)
4556 if (global_env.iop >= global_env.iobase)
4557 global_env.iop->peekc = c;
4560 static int eofc(void)
4562 return global_env.iop < global_env.iobase || (global_env.iop->peekc == 0 && global_env.iop->prev == 0);
4565 static int readc(void)
4569 RCPRINTF(("READC: global_env.iop %p, global_env.iobase %p\n", global_env.iop, global_env.iobase));
4571 for (; global_env.iop >= global_env.iobase; global_env.iop--) {
4572 RCPRINTF(("READC: global_env.iop %p, peekc 0x%x\n", global_env.iop, global_env.iop->peekc));
4573 c = global_env.iop->peekc;
4575 global_env.iop->peekc = 0;
4578 if (global_env.iop->prev != 0) {
4579 c = (*global_env.iop->iofn)(global_env.iop->argp, global_env.iop);
4585 if (global_env.iop == iostack)
4587 global_env.iop->prev = c;
4588 return global_env.iop->prev;
4590 if (global_env.iop->task == XIO && global_env.iop->prev != '\n') {
4591 global_env.iop->prev = 0;
4592 if (global_env.iop == iostack)
4597 if (global_env.iop->task == XIO) {
4599 global_env.iop->prev = 0;
4600 return global_env.iop->prev;
4602 if (interactive && global_env.iop == iostack + 1) {
4603 #if ENABLE_FEATURE_EDITING
4604 current_prompt = prompt->value;
4612 if (global_env.iop >= iostack) {
4613 RCPRINTF(("READC: return 0, global_env.iop %p\n", global_env.iop));
4617 DBGPRINTF(("READC: leave()...\n"));
4624 static void ioecho(char c)
4627 write(2, &c, sizeof c);
4631 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4633 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, global_env.iop %p\n", argp,
4634 argp->afid, global_env.iop));
4636 /* Set env ptr for io source to next array spot and check for array overflow */
4637 if (++global_env.iop >= &iostack[NPUSH]) {
4639 err("Shell input nested too deeply");
4644 /* We did not overflow the NPUSH array spots so setup data structs */
4646 global_env.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4648 if (argp->afid != AFID_NOBUF)
4649 global_env.iop->argp = argp;
4652 global_env.iop->argp = ioargstack + (global_env.iop - iostack); /* MAL - index into stack */
4653 *global_env.iop->argp = *argp; /* copy data from temp area into stack spot */
4655 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4657 if (global_env.iop == &iostack[0])
4658 global_env.iop->argp->afbuf = &mainbuf;
4660 global_env.iop->argp->afbuf = &sharedbuf;
4662 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4663 /* This line appears to be active when running scripts from command line */
4664 if ((isatty(global_env.iop->argp->afile) == 0)
4665 && (global_env.iop == &iostack[0]
4666 || lseek(global_env.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4667 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4668 bufid = AFID_ID; /* AFID_ID = 0 */
4670 global_env.iop->argp->afid = bufid; /* assign buffer id */
4673 DBGPRINTF(("PUSHIO: iostack %p, global_env.iop %p, afbuf %p\n",
4674 iostack, global_env.iop, global_env.iop->argp->afbuf));
4675 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, global_env.iop %p\n",
4676 &mainbuf, &sharedbuf, bufid, global_env.iop));
4680 global_env.iop->prev = ~'\n';
4681 global_env.iop->peekc = 0;
4682 global_env.iop->xchar = 0;
4683 global_env.iop->nlcount = 0;
4685 if (fn == filechar || fn == linechar)
4686 global_env.iop->task = XIO;
4687 else if (fn == (int (*)(struct ioarg *)) gravechar
4688 || fn == (int (*)(struct ioarg *)) qgravechar)
4689 global_env.iop->task = XGRAVE;
4691 global_env.iop->task = XOTHER;
4694 static struct io *setbase(struct io *ip)
4698 xp = global_env.iobase;
4699 global_env.iobase = ip;
4704 * Input generating functions
4708 * Produce the characters of a string, then a newline, then EOF.
4710 static int nlchar(struct ioarg *ap)
4714 if (ap->aword == NULL)
4725 * Given a list of words, produce the characters
4726 * in them, with a space after each word.
4728 static int wdchar(struct ioarg *ap)
4743 ap->awordlist = NULL;
4748 * Return the characters of a list of words,
4749 * producing a space between them.
4751 static int dolchar(struct ioarg *ap)
4755 wp = *ap->awordlist++;
4757 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4763 static int xxchar(struct ioarg *ap)
4767 if (ap->aword == NULL)
4778 * Produce the characters from a single word (string).
4780 static int strchar(struct ioarg *ap)
4782 if (ap->aword == NULL)
4784 return *ap->aword++;
4788 * Produce quoted characters from a single word (string).
4790 static int qstrchar(struct ioarg *ap)
4794 if (ap->aword == NULL)
4803 * Return the characters from a file.
4805 static int filechar(struct ioarg *ap)
4809 struct iobuf *bp = ap->afbuf;
4811 if (ap->afid != AFID_NOBUF) {
4812 i = (ap->afid != bp->id);
4813 if (i || bp->bufp == bp->ebufp) {
4815 lseek(ap->afile, ap->afpos, SEEK_SET);
4817 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4825 bp->ebufp = bp->bufp + i;
4829 return *bp->bufp++ & 0177;
4831 #if ENABLE_FEATURE_EDITING
4832 if (interactive && isatty(ap->afile)) {
4833 /* moved to G: static char filechar_cmdbuf[BUFSIZ]; */
4834 static int position = 0, size = 0;
4836 while (size == 0 || position >= size) {
4837 read_line_input(current_prompt, filechar_cmdbuf, BUFSIZ, line_input_state);
4838 size = strlen(filechar_cmdbuf);
4841 c = filechar_cmdbuf[position];
4846 i = safe_read(ap->afile, &c, sizeof(c));
4847 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4851 * Return the characters from a here temp file.
4853 static int herechar(struct ioarg *ap)
4857 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4865 * Return the characters produced by a process (`...`).
4866 * Quote them if required, and remove any trailing newline characters.
4868 static int gravechar(struct ioarg *ap, struct io *iop)
4872 c = qgravechar(ap, iop) & ~QUOTE;
4878 static int qgravechar(struct ioarg *ap, struct io *iop)
4882 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4887 return '\n' | QUOTE;
4891 } else if ((c = filechar(ap)) == '\n') {
4893 while ((c = filechar(ap)) == '\n')
4901 return c != 0 ? c | QUOTE : 0;
4905 * Return a single command (usually the first line) from a file.
4907 static int linechar(struct ioarg *ap)
4915 ap->afile = -1; /* illegal value */
4922 * remap fd into Shell's fd space
4924 static int remap(int fd)
4930 DBGPRINTF(("REMAP: fd=%d, global_env.iofd=%d\n", fd, global_env.iofd));
4932 if (fd < global_env.iofd) {
4933 for (i = 0; i < NOFILE; i++)
4940 } while (fd >= 0 && fd < global_env.iofd);
4942 for (i = 0; i < NOFILE; i++)
4947 err("too many files open in shell");
4953 static int openpipe(int *pv)
4959 err("can't create pipe - try again");
4963 static void closepipe(int *pv)
4972 /* -------- here.c -------- */
4978 static void markhere(char *s, struct ioword *iop)
4980 struct here *h, *lh;
4982 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
4984 h = (struct here *) space(sizeof(struct here));
4988 h->h_tag = evalstr(s, DOSUB);
4998 for (lh = inhere; lh != NULL; lh = lh->h_next) {
4999 if (lh->h_next == 0) {
5005 iop->io_flag |= IOHERE | IOXHERE;
5006 for (s = h->h_tag; *s; s++) {
5008 iop->io_flag &= ~IOXHERE;
5012 h->h_dosub = iop->io_flag & IOXHERE;
5015 static void gethere(void)
5017 struct here *h, *hp;
5019 DBGPRINTF7(("GETHERE: enter...\n"));
5021 /* Scan here files first leaving inhere list in place */
5022 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5023 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5025 /* Make inhere list active - keep list intact for scraphere */
5027 hp->h_next = acthere;
5033 static void readhere(char **name, char *s, int ec)
5036 char tname[30] = ".msh_XXXXXX";
5039 char myline[LINELIM + 1];
5042 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5044 tf = mkstemp(tname);
5048 *name = strsave(tname, areanum);
5050 if (newenv(setjmp(errpt)) != 0)
5053 pushio(global_env.iop->argp, (int (*)(struct ioarg *)) global_env.iop->iofn);
5054 global_env.iobase = global_env.iop;
5056 if (interactive && global_env.iop <= iostack) {
5057 #if ENABLE_FEATURE_EDITING
5058 current_prompt = cprompt->value;
5060 prs(cprompt->value);
5064 while ((c = my_getc(ec)) != '\n' && c) {
5067 if (thenext >= &myline[LINELIM]) {
5074 if (strcmp(s, myline) == 0 || c == 0)
5077 write(tf, myline, (int) (thenext - myline));
5080 prs("here document `");
5090 * open here temp file.
5091 * if unquoted here, expand here temp file into second temp file.
5093 static int herein(char *hname, int xdoll)
5099 /* Avoid longjmp clobbering */
5105 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5107 hf = open(hname, O_RDONLY);
5113 char tname[30] = ".msh_XXXXXX";
5116 tf = mkstemp(tname);
5120 if (newenv(setjmp(errpt)) == 0) {
5121 PUSHIO(afile, hf, herechar);
5122 setbase(global_env.iop);
5123 while ((c = subgetc(0, 0)) != 0) {
5125 write(tf, &c, sizeof c);
5131 tf = open(tname, O_RDONLY);
5138 static void scraphere(void)
5142 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5144 for (h = inhere; h != NULL; h = h->h_next) {
5145 if (h->h_iop && h->h_iop->io_name)
5146 unlink(h->h_iop->io_name);
5151 /* unlink here temp files before a freearea(area) */
5152 static void freehere(int area)
5154 struct here *h, *hl;
5156 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5159 for (h = acthere; h != NULL; h = h->h_next)
5160 if (getarea((char *) h) >= area) {
5161 if (h->h_iop->io_name != NULL)
5162 unlink(h->h_iop->io_name);
5164 acthere = h->h_next;
5166 hl->h_next = h->h_next;
5172 /* -------- sh.c -------- */
5177 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5178 int msh_main(int argc, char **argv)
5184 int (*iof) (struct ioarg *);
5188 sharedbuf.id = AFID_NOBUF;
5189 mainbuf.id = AFID_NOBUF;
5190 elinep = line + sizeof(line) - 5;
5192 #if ENABLE_FEATURE_EDITING
5193 line_input_state = new_line_input_t(FOR_SHELL);
5196 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
5202 assign(*ap++, !COPYV);
5203 for (ap = environ; *ap;)
5204 export(lookup(*ap++));
5209 shell = lookup("SHELL");
5210 if (shell->value == null)
5211 setval(shell, (char *)DEFAULT_SHELL);
5214 homedir = lookup("HOME");
5215 if (homedir->value == null)
5216 setval(homedir, "/");
5219 setval(lookup("$"), putn(getpid()));
5221 path = lookup("PATH");
5222 if (path->value == null) {
5223 /* Can be merged with same string elsewhere in bbox */
5225 setval(path, bb_default_root_path);
5227 setval(path, bb_default_path);
5231 ifs = lookup("IFS");
5232 if (ifs->value == null)
5233 setval(ifs, " \t\n");
5236 mshdbg_var = lookup("MSHDEBUG");
5237 if (mshdbg_var->value == null)
5238 setval(mshdbg_var, "0");
5241 prompt = lookup("PS1");
5242 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5243 if (prompt->value == null)
5245 setval(prompt, DEFAULT_USER_PROMPT);
5246 if (geteuid() == 0) {
5247 setval(prompt, DEFAULT_ROOT_PROMPT);
5248 prompt->status &= ~EXPORT;
5250 cprompt = lookup("PS2");
5251 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
5252 if (cprompt->value == null)
5254 setval(cprompt, "> ");
5260 if (argv[0][0] == '-' && argv[0][1] != '\0') {
5261 for (s = argv[0] + 1; *s; s++)
5264 prompt->status &= ~EXPORT;
5265 cprompt->status &= ~EXPORT;
5267 setval(cprompt, "");
5270 PUSHIO(aword, *++argv, iof = nlchar);
5278 /* standard input */
5282 prompt->status &= ~EXPORT;
5290 if (*s >= 'a' && *s <= 'z')
5298 if (iof == filechar && --argc > 0) {
5300 setval(cprompt, "");
5301 prompt->status &= ~EXPORT;
5302 cprompt->status &= ~EXPORT;
5304 /* Shell is non-interactive, activate printf-based debug */
5306 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
5310 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
5314 exit(1); /* Exit on error */
5320 /* This won't be true if PUSHIO has been called, say from newfile() above */
5321 if (global_env.iop < iostack) {
5322 PUSHIO(afile, 0, iof);
5323 if (isatty(0) && isatty(1) && !cflag) {
5325 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
5327 printf("\n\n%s built-in shell (msh with debug)\n", bb_banner);
5329 printf("\n\n%s built-in shell (msh)\n", bb_banner);
5331 printf("Enter 'help' for a list of built-in commands.\n\n");
5336 signal(SIGQUIT, qflag);
5337 if (name && name[0] == '-') {
5339 f = open(".profile", O_RDONLY);
5342 f = open("/etc/profile", O_RDONLY);
5347 signal(SIGTERM, sig);
5349 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
5350 signal(SIGINT, onintr);
5355 for (ap = ++argv; --argc > 0;) {
5357 if (assign(*ap, !COPYV)) {
5358 dolc--; /* keyword */
5364 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
5366 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, global_env.iop %p, iostack %p\n", interactive, global_env.iop, iostack));
5369 if (interactive && global_env.iop <= iostack) {
5370 #if ENABLE_FEATURE_EDITING
5371 current_prompt = prompt->value;
5377 /* Ensure that getenv("PATH") stays current */
5378 setenv("PATH", path->value, 1);
5381 DBGPRINTF(("MSH_MAIN: returning.\n"));
5386 * Copyright (c) 1987,1997, Prentice Hall
5387 * All rights reserved.
5389 * Redistribution and use of the MINIX operating system in source and
5390 * binary forms, with or without modification, are permitted provided
5391 * that the following conditions are met:
5393 * Redistributions of source code must retain the above copyright
5394 * notice, this list of conditions and the following disclaimer.
5396 * Redistributions in binary form must reproduce the above
5397 * copyright notice, this list of conditions and the following
5398 * disclaimer in the documentation and/or other materials provided
5399 * with the distribution.
5401 * Neither the name of Prentice Hall nor the names of the software
5402 * authors or contributors may be used to endorse or promote
5403 * products derived from this software without specific prior
5404 * written permission.
5406 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5407 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5408 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5409 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5410 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5411 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5412 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5413 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5414 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5415 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5416 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5417 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.