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.
18 #include <sys/times.h>
21 /*#define MSHDEBUG 1*/
24 int mshdbg = MSHDEBUG;
26 #define DBGPRINTF(x) if(mshdbg>0)printf x
27 #define DBGPRINTF0(x) if(mshdbg>0)printf x
28 #define DBGPRINTF1(x) if(mshdbg>1)printf x
29 #define DBGPRINTF2(x) if(mshdbg>2)printf x
30 #define DBGPRINTF3(x) if(mshdbg>3)printf x
31 #define DBGPRINTF4(x) if(mshdbg>4)printf x
32 #define DBGPRINTF5(x) if(mshdbg>5)printf x
33 #define DBGPRINTF6(x) if(mshdbg>6)printf x
34 #define DBGPRINTF7(x) if(mshdbg>7)printf x
35 #define DBGPRINTF8(x) if(mshdbg>8)printf x
36 #define DBGPRINTF9(x) if(mshdbg>9)printf x
40 #define RCPRINTF(x) if(mshdbg_rc)printf x
61 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
62 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
63 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
65 # define DEFAULT_ROOT_PROMPT "# "
66 # define DEFAULT_USER_PROMPT "$ "
70 /* -------- sh.h -------- */
76 #define NPUSH 8 /* limit to input nesting */
79 #define NOFILE 20 /* Number of open files */
80 #define NUFILE 10 /* Number of user-accessible files */
81 #define FDBASE 10 /* First file usable by Shell */
84 * values returned by wait
86 #define WAITSIG(s) ((s)&0177)
87 #define WAITVAL(s) (((s)>>8)&0377)
88 #define WAITCORE(s) (((s)&0200)!=0)
91 * library and system definitions
93 typedef void xint; /* base type of jmp_buf, for not broken compilers */
101 #define NOBLOCK ((struct op *)NULL)
102 #define NOWORD ((char *)NULL)
103 #define NOWORDS ((char **)NULL)
104 #define NOPIPE ((int *)NULL)
107 * Description of a command or an operation on commands.
108 * Might eventually use a union.
111 int type; /* operation type, see below */
112 char **words; /* arguments to a command */
113 struct ioword **ioact; /* IO actions (eg, < > >>) */
116 char *str; /* identifier for case and for */
119 #define TCOM 1 /* command */
120 #define TPAREN 2 /* (c-list) */
121 #define TPIPE 3 /* a | b */
122 #define TLIST 4 /* a [&;] b */
123 #define TOR 5 /* || */
124 #define TAND 6 /* && */
132 #define TPAT 14 /* pattern in case */
133 #define TBRACE 15 /* {c-list} */
134 #define TASYNC 16 /* c & */
135 /* Added to support "." file expansion */
138 /* Strings for names to make debug easier */
140 static const char *const T_CMD_NAMES[] = {
163 * actions determining the environment of a process
165 #define BIT(i) (1<<(i))
166 #define FEXEC BIT(0) /* execute without forking */
168 #define AREASIZE (90000)
171 * flags to control evaluation of words
173 #define DOSUB 1 /* interpret $, `, and quotes */
174 #define DOBLANK 2 /* perform blank interpretation */
175 #define DOGLOB 4 /* interpret [?* */
176 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
177 #define DOTRIM 16 /* trim resulting string */
179 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
183 static int newfile(char *s);
184 static char *findeq(char *cp);
185 static char *cclass(char *p, int sub);
186 static void initarea(void);
187 extern int msh_main(int argc, char **argv);
192 struct brkcon *nextlev;
200 short io_unit; /* unit affected */
201 short io_flag; /* action (below) */
202 char *io_name; /* file name */
205 #define IOREAD 1 /* < */
206 #define IOHERE 2 /* << (here file) */
207 #define IOWRITE 4 /* > */
208 #define IOCAT 8 /* >> */
209 #define IOXHERE 16 /* ${}, ` in << */
210 #define IODUP 32 /* >&digit */
211 #define IOCLOSE 64 /* >&- */
213 #define IODEFAULT (-1) /* token for default IO unit */
218 * parsing & execution environment
224 xint *errpt; /* void * */
232 * -k: look for name=value everywhere on command line
234 * -t: exit after reading and executing one command
237 * -u: unset variables net diagnostic
239 static char flags['z' - 'a' + 1];
240 /* this looks weird, but is OK ... we index flag with 'a'...'z' */
241 static char *flag = flags - 'a';
243 static char *null; /* null value for variable */
244 static int intr; /* interrupt pending */
246 static char *trap[_NSIG + 1];
247 static char ourtrap[_NSIG + 1];
248 static int trapset; /* trap pending */
250 static int heedint; /* heed interrupt signals */
252 static int yynerrs; /* yacc */
254 static char line[LINELIM];
261 static int (*inbuilt(char *s)) (struct op *);
263 static char *rexecve(char *c, char **v, char **envp);
264 static char *space(int n);
265 static char *strsave(char *s, int a);
266 static char *evalstr(char *cp, int f);
267 static char *putn(int n);
268 static char *unquote(char *as);
269 static struct var *lookup(char *n);
270 static int rlookup(char *n);
271 static struct wdblock *glob(char *cp, struct wdblock *wb);
272 static int my_getc(int ec);
273 static int subgetc(char ec, int quoted);
274 static char **makenv(int all, struct wdblock *wb);
275 static char **eval(char **ap, int f);
276 static int setstatus(int s);
277 static int waitfor(int lastpid, int canintr);
279 static void onintr(int s); /* SIGINT handler */
281 static int newenv(int f);
282 static void quitenv(void);
283 static void err(const char *s);
284 static int anys(const char *s1, const char *s2);
285 static int any(int c, const char *s);
286 static void next(int f);
287 static void setdash(void);
288 static void onecommand(void);
289 static void runtrap(int i);
290 static int gmatch(char *s, char *p);
296 static void leave(void); /* abort shell (or fail in subshell) */
297 static void fail(void); /* fail but return to process next command */
298 static void warn(const char *s);
299 static void sig(int i); /* default signal handler */
303 /* -------- area stuff -------- */
305 #define REGSIZE sizeof(struct region)
307 /* #define SHRINKBY (64) */
311 #define ALIGN (sizeof(int)-1)
321 /* -------- grammar stuff -------- */
346 /* Added for "." file expansion */
349 #define YYERRCODE 300
352 #define CONTIN 01 /* skip new lines to complete command */
354 #define SYNTAXERR zzerr()
356 static struct op *pipeline(int cf);
357 static struct op *andor(void);
358 static struct op *c_list(void);
359 static int synio(int cf);
360 static void musthave(int c, int cf);
361 static struct op *simple(void);
362 static struct op *nested(int type, int mark);
363 static struct op *command(int cf);
364 static struct op *dogroup(int onlydone);
365 static struct op *thenpart(void);
366 static struct op *elsepart(void);
367 static struct op *caselist(void);
368 static struct op *casepart(void);
369 static char **pattern(void);
370 static char **wordlist(void);
371 static struct op *list(struct op *t1, struct op *t2);
372 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
373 static struct op *newtp(void);
374 static struct op *namelist(struct op *t);
375 static char **copyw(void);
376 static void word(char *cp);
377 static struct ioword **copyio(void);
378 static struct ioword *io(int u, int f, char *cp);
379 static void zzerr(void);
380 static void yyerror(char *s);
381 static int yylex(int cf);
382 static int collect(int c, int c1);
383 static int dual(int c);
384 static void diag(int ec);
385 static char *tree(unsigned size);
387 /* -------- var.h -------- */
396 #define COPYV 1 /* flag to setval, suggesting copy */
397 #define RONLY 01 /* variable is read-only */
398 #define EXPORT 02 /* variable is to be exported */
399 #define GETCELL 04 /* name & value space was got with getcell */
401 static int yyparse(void);
402 static struct var *lookup(char *n);
403 static void setval(struct var *vp, char *val);
404 static void nameval(struct var *vp, char *val, char *name);
405 static void export(struct var *vp);
406 static void ronly(struct var *vp);
407 static int isassign(char *s);
408 static int checkname(char *cp);
409 static int assign(char *s, int cf);
410 static void putvlist(int f, int out);
411 static int eqname(char *n1, char *n2);
413 static int execute(struct op *t, int *pin, int *pout, int act);
416 /* -------- io.h -------- */
419 unsigned id; /* buffer id */
420 char buf[512]; /* buffer */
421 char *bufp; /* pointer into buffer */
422 char *ebufp; /* pointer to end of buffer */
425 /* possible arguments to an IO function */
429 int afile; /* file descriptor */
430 unsigned afid; /* buffer id */
431 long afpos; /* file position */
432 struct iobuf *afbuf; /* buffer for this file */
435 //static struct ioarg ioargstack[NPUSH];
436 #define AFID_NOBUF (~0)
439 /* an input generator's state */
441 int (*iofn) (struct ioarg *, struct io *);
444 char prev; /* previous character read by readc() */
445 char nlcount; /* for `'s */
446 char xchar; /* for `'s */
447 char task; /* reason for pushed IO */
450 //static struct io iostack[NPUSH];
451 #define XOTHER 0 /* none of the below */
452 #define XDOLL 1 /* expanding ${} */
453 #define XGRAVE 2 /* expanding `'s */
454 #define XIO 3 /* file IO */
456 /* in substitution */
457 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
461 * input generators for IO structure
463 static int nlchar(struct ioarg *ap);
464 static int strchar(struct ioarg *ap);
465 static int qstrchar(struct ioarg *ap);
466 static int filechar(struct ioarg *ap);
467 static int herechar(struct ioarg *ap);
468 static int linechar(struct ioarg *ap);
469 static int gravechar(struct ioarg *ap, struct io *iop);
470 static int qgravechar(struct ioarg *ap, struct io *iop);
471 static int dolchar(struct ioarg *ap);
472 static int wdchar(struct ioarg *ap);
473 static void scraphere(void);
474 static void freehere(int area);
475 static void gethere(void);
476 static void markhere(char *s, struct ioword *iop);
477 static int herein(char *hname, int xdoll);
478 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
484 static int eofc(void);
485 static int readc(void);
486 static void unget(int c);
487 static void ioecho(char c);
488 static void prs(const char *s);
489 static void prn(unsigned u);
490 static void closef(int i);
491 static void closeall(void);
497 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
498 static int remap(int fd);
499 static int openpipe(int *pv);
500 static void closepipe(int *pv);
501 static struct io *setbase(struct io *ip);
503 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)),pushio(&temparg,(gen)))
504 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
506 /* -------- word.h -------- */
508 #define NSTART 16 /* default number of words to allow for initially */
513 /* bounds are arbitrary */
517 static struct wdblock *addword(char *wd, struct wdblock *wb);
518 static struct wdblock *newword(int nw);
519 static char **getwords(struct wdblock *wb);
521 /* -------- area.h -------- */
526 static char *getcell(unsigned nbytes);
527 static void garbage(void);
528 static void setarea(char *cp, int a);
529 static int getarea(char *cp);
530 static void freearea(int a);
531 static void freecell(char *cp);
532 static int areanum; /* current allocation area */
534 #define NEW(type) (type *)getcell(sizeof(type))
535 #define DELETE(obj) freecell((char *)obj)
538 /* -------- misc stuff -------- */
540 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
541 static int iosetup(struct ioword *iop, int pipein, int pipeout);
542 static void echo(char **wp);
543 static struct op **find1case(struct op *t, char *w);
544 static struct op *findcase(struct op *t, char *w);
545 static void brkset(struct brkcon *bc);
546 static int dolabel(struct op *t);
547 static int dohelp(struct op *t);
548 static int dochdir(struct op *t);
549 static int doshift(struct op *t);
550 static int dologin(struct op *t);
551 static int doumask(struct op *t);
552 static int doexec(struct op *t);
553 static int dodot(struct op *t);
554 static int dowait(struct op *t);
555 static int doread(struct op *t);
556 static int doeval(struct op *t);
557 static int dotrap(struct op *t);
558 static int getsig(char *s);
559 static void setsig(int n, sighandler_t f);
560 static int getn(char *as);
561 static int dobreak(struct op *t);
562 static int docontinue(struct op *t);
563 static int brkcontin(char *cp, int val);
564 static int doexit(struct op *t);
565 static int doexport(struct op *t);
566 static int doreadonly(struct op *t);
567 static void rdexp(char **wp, void (*f) (struct var *), int key);
568 static void badid(char *s);
569 static int doset(struct op *t);
570 static void varput(char *s, int out);
571 static int dotimes(struct op *t);
572 static int expand(char *cp, struct wdblock **wbp, int f);
573 static char *blank(int f);
574 static int dollar(int quoted);
575 static int grave(int quoted);
576 static void globname(char *we, char *pp);
577 static char *generate(char *start1, char *end1, char *middle, char *end);
578 static int anyspcl(struct wdblock *wb);
579 static int xstrcmp(char *p1, char *p2);
580 static void glob0(char *a0, unsigned int a1, int a2,
581 int (*a3) (char *, char *));
582 static void glob1(char *base, char *lim);
583 static void glob2(char *i, char *j);
584 static void glob3(char *i, char *j, char *k);
585 static void readhere(char **name, char *s, int ec);
586 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
587 static int xxchar(struct ioarg *ap);
592 struct ioword *h_iop;
596 static const char * const signame[] = {
599 (char *) NULL, /* interrupt */
601 "Illegal instruction",
605 "Floating Point Exception",
610 (char *) NULL, /* broken pipe */
615 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
621 static const struct res restab[] = {
647 int (*builtinfunc) (struct op * t);
649 static const struct builtincmd builtincmds[] = {
654 {"continue", docontinue},
658 {"export", doexport},
663 {"readonly", doreadonly},
673 static struct op *scantree(struct op *);
674 static struct op *dowholefile(int, int);
677 extern char **environ; /* environment pointer */
683 static int interactive; /* Is this an interactive shell */
685 static int multiline; /* \n changed to ; */
686 static struct op *outtree; /* result from parser */
689 static struct brkcon *brklist;
691 static struct wdblock *wdlist;
692 static struct wdblock *iolist;
693 static char *trap[_NSIG + 1];
694 static char ourtrap[_NSIG + 1];
695 static int trapset; /* trap pending */
698 static struct var *mshdbg_var;
700 static struct var *vlist; /* dictionary */
701 static struct var *homedir; /* home directory */
702 static struct var *prompt; /* main prompt */
703 static struct var *cprompt; /* continuation prompt */
704 static struct var *path; /* search path for commands */
705 static struct var *shell; /* shell to interpret command files */
706 static struct var *ifs; /* field separators */
708 static int areanum; /* current allocation area */
711 static char *null = "";
712 static int heedint = 1;
713 static void (*qflag) (int) = SIG_IGN;
717 static int iounit = IODEFAULT;
718 static YYSTYPE yylval;
719 static char *elinep = line + sizeof(line) - 5;
721 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
722 static struct ioarg ioargstack[NPUSH];
723 static struct io iostack[NPUSH];
724 static struct iobuf sharedbuf = { AFID_NOBUF };
725 static struct iobuf mainbuf = { AFID_NOBUF };
726 static unsigned bufid = AFID_ID; /* buffer id counter */
728 static struct here *inhere; /* list of hear docs while parsing */
729 static struct here *acthere; /* list of active here documents */
730 static struct region *areabot; /* bottom of area */
731 static struct region *areatop; /* top of area */
732 static struct region *areanxt; /* starting point of scan */
734 static void *brkaddr;
736 static struct env e = {
737 line, /* linep: char ptr */
738 iostack, /* iobase: struct io ptr */
739 iostack - 1, /* iop: struct io ptr */
740 (xint *) NULL, /* errpt: void ptr for errors? */
741 FDBASE, /* iofd: file desc */
742 (struct env *) NULL /* oenv: struct env ptr */
746 void print_t(struct op *t)
748 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
749 T_CMD_NAMES[t->type], t->words, t->ioact));
752 DBGPRINTF(("T: W1: %s", t->words[0]));
758 void print_tree(struct op *head)
761 DBGPRINTF(("PRINT_TREE: no tree\n"));
765 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
769 print_tree(head->left);
772 print_tree(head->right);
776 #endif /* MSHDEBUG */
779 #if ENABLE_FEATURE_EDITING
780 static char *current_prompt;
783 /* -------- sh.c -------- */
789 #if ENABLE_FEATURE_EDITING
790 static line_input_t *line_input_state;
793 int msh_main(int argc, char **argv)
799 int (*iof) (struct ioarg *);
801 #if ENABLE_FEATURE_EDITING
802 line_input_state = new_line_input_t(FOR_SHELL);
805 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
811 assign(*ap++, !COPYV);
812 for (ap = environ; *ap;)
813 export(lookup(*ap++));
818 shell = lookup("SHELL");
819 if (shell->value == null)
820 setval(shell, (char *)DEFAULT_SHELL);
823 homedir = lookup("HOME");
824 if (homedir->value == null)
825 setval(homedir, "/");
828 setval(lookup("$"), putn(getpid()));
830 path = lookup("PATH");
831 if (path->value == null) {
833 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
835 setval(path, "/bin:/usr/bin");
840 if (ifs->value == null)
841 setval(ifs, " \t\n");
844 mshdbg_var = lookup("MSHDEBUG");
845 if (mshdbg_var->value == null)
846 setval(mshdbg_var, "0");
849 prompt = lookup("PS1");
850 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
851 if (prompt->value == null)
853 setval(prompt, DEFAULT_USER_PROMPT);
854 if (geteuid() == 0) {
855 setval(prompt, DEFAULT_ROOT_PROMPT);
856 prompt->status &= ~EXPORT;
858 cprompt = lookup("PS2");
859 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
860 if (cprompt->value == null)
862 setval(cprompt, "> ");
868 if (argv[0][0] == '-' && argv[0][1] != '\0') {
869 for (s = argv[0] + 1; *s; s++)
872 prompt->status &= ~EXPORT;
873 cprompt->status &= ~EXPORT;
878 PUSHIO(aword, *++argv, iof = nlchar);
890 prompt->status &= ~EXPORT;
898 if (*s >= 'a' && *s <= 'z')
906 if (iof == filechar && --argc > 0) {
909 prompt->status &= ~EXPORT;
910 cprompt->status &= ~EXPORT;
912 /* Shell is non-interactive, activate printf-based debug */
914 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
918 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
920 if (newfile(name = *++argv))
921 exit(1); /* Exit on error */
927 /* This won't be true if PUSHIO has been called, say from newfile() above */
928 if (e.iop < iostack) {
929 PUSHIO(afile, 0, iof);
930 if (isatty(0) && isatty(1) && !cflag) {
932 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
934 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
936 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
938 printf("Enter 'help' for a list of built-in commands.\n\n");
943 signal(SIGQUIT, qflag);
944 if (name && name[0] == '-') {
946 if ((f = open(".profile", 0)) >= 0)
948 if ((f = open("/etc/profile", 0)) >= 0)
952 signal(SIGTERM, sig);
954 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
955 signal(SIGINT, onintr);
960 for (ap = ++argv; --argc > 0;) {
961 if (assign(*ap = *argv++, !COPYV)) {
962 dolc--; /* keyword */
968 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
970 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
973 if (interactive && e.iop <= iostack) {
974 #if ENABLE_FEATURE_EDITING
975 current_prompt = prompt->value;
981 /* Ensure that getenv("PATH") stays current */
982 setenv("PATH", path->value, 1);
985 DBGPRINTF(("MSH_MAIN: returning.\n"));
988 static void setdash(void)
992 char m['z' - 'a' + 1];
995 for (c = 'a'; c <= 'z'; c++)
999 setval(lookup("-"), m);
1002 static int newfile(char *s)
1006 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1008 if (NOT_LONE_DASH(s)) {
1009 DBGPRINTF(("NEWFILE: s is %s\n", s));
1013 err(": cannot open");
1024 struct op *scantree(struct op *head)
1031 if (head->left != NULL) {
1032 dotnode = scantree(head->left);
1037 if (head->right != NULL) {
1038 dotnode = scantree(head->right);
1043 if (head->words == NULL)
1046 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1048 if ((head->type != TDOT) && (strcmp(".", head->words[0]) == 0)) {
1049 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1057 static void onecommand(void)
1062 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1081 setjmp(failpt = m1); /* Bruce Evans' fix */
1082 if (setjmp(failpt = m1) || yyparse() || intr) {
1084 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1089 if (!interactive && intr)
1102 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1104 execute(outtree, NOPIPE, NOPIPE, 0);
1107 if (!interactive && intr) {
1119 static void fail(void)
1125 static void leave(void)
1127 DBGPRINTF(("LEAVE: leave called!\n"));
1138 static void warn(const char *s)
1149 static void err(const char *s)
1157 longjmp(e.errpt, 1);
1159 e.iop = e.iobase = iostack;
1162 static int newenv(int f)
1166 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1173 ep = (struct env *) space(sizeof(*ep));
1186 static void quitenv(void)
1191 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1197 /* should close `'d files */
1199 while (--fd >= e.iofd)
1205 * Is character c in s?
1207 static int any(int c, const char *s)
1216 * Is any character from s1 in s2?
1218 static int anys(const char *s1, const char *s2)
1226 static char *putn(int n)
1231 static void next(int f)
1233 PUSHIO(afile, f, filechar);
1236 static void onintr(int s) /* ANSI C requires a parameter */
1238 signal(SIGINT, onintr);
1245 } else if (heedint) {
1251 static char *space(int n)
1257 err("out of string space");
1261 static char *strsave(char *s, int a)
1265 cp = space(strlen(s) + 1);
1277 static void sig(int i)
1283 static void runtrap(int i)
1288 if (trapstr == NULL)
1294 RUN(aword, trapstr, nlchar);
1297 /* -------- var.c -------- */
1300 * Find the given name in the dictionary
1301 * and return its value. If the name was
1302 * not previously there, enter it now and
1303 * return a null value.
1305 static struct var *lookup(char *n)
1310 static struct var dummy;
1314 for (c = 0; isdigit(*n) && c < 1000; n++)
1315 c = c * 10 + *n - '0';
1316 dummy.status = RONLY;
1317 dummy.value = c <= dolc ? dolv[c] : null;
1320 for (vp = vlist; vp; vp = vp->next)
1321 if (eqname(vp->name, n))
1324 vp = (struct var *) space(sizeof(*vp));
1325 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1326 dummy.name = dummy.value = "";
1329 for (cp = vp->name; (*cp = *n++) && *cp != '='; cp++);
1333 setarea((char *) vp, 0);
1334 setarea((char *) vp->name, 0);
1337 vp->status = GETCELL;
1343 * give variable at `vp' the value `val'.
1345 static void setval(struct var *vp, char *val)
1347 nameval(vp, val, (char *) NULL);
1351 * if name is not NULL, it must be
1352 * a prefix of the space `val',
1354 * this is all so that exporting
1355 * values is reasonably painless.
1357 static void nameval(struct var *vp, char *val, char *name)
1363 if (vp->status & RONLY) {
1364 for (xp = vp->name; *xp && *xp != '=';)
1365 putc(*xp++, stderr);
1366 err(" is read-only");
1371 xp = space(strlen(vp->name) + strlen(val) + 2);
1374 /* make string: name=value */
1375 setarea((char *) xp, 0);
1377 for (cp = vp->name; (*xp = *cp++) && *xp != '='; xp++);
1381 for (cp = val; (*xp++ = *cp++) != '\0';);
1385 if (vp->status & GETCELL)
1386 freecell(vp->name); /* form new string `name=value' */
1392 static void export(struct var *vp)
1394 vp->status |= EXPORT;
1397 static void ronly(struct var *vp)
1399 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1400 vp->status |= RONLY;
1403 static int isassign(char *s)
1405 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1407 if (!isalpha((int) *s) && *s != '_')
1409 for (; *s != '='; s++)
1410 if (*s == 0 || (!isalnum(*s) && *s != '_'))
1416 static int assign(char *s, int cf)
1421 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1423 if (!isalpha(*s) && *s != '_')
1425 for (cp = s; *cp != '='; cp++)
1426 if (*cp == 0 || (!isalnum(*cp) && *cp != '_'))
1429 nameval(vp, ++cp, cf == COPYV ? (char *) NULL : s);
1431 vp->status &= ~GETCELL;
1435 static int checkname(char *cp)
1437 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1439 if (!isalpha(*cp++) && *(cp - 1) != '_')
1442 if (!isalnum(*cp++) && *(cp - 1) != '_')
1447 static void putvlist(int f, int out)
1451 for (vp = vlist; vp; vp = vp->next)
1452 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1453 if (vp->status & EXPORT)
1454 write(out, "export ", 7);
1455 if (vp->status & RONLY)
1456 write(out, "readonly ", 9);
1457 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1458 write(out, "\n", 1);
1462 static int eqname(char *n1, char *n2)
1464 for (; *n1 != '=' && *n1 != 0; n1++)
1467 return *n2 == 0 || *n2 == '=';
1470 static char *findeq(char *cp)
1472 while (*cp != '\0' && *cp != '=')
1477 /* -------- gmatch.c -------- */
1479 * int gmatch(string, pattern)
1480 * char *string, *pattern;
1482 * Match a pattern as in sh(1).
1487 #define QMASK (CMASK&~QUOTE)
1488 #define NOT '!' /* might use ^ */
1490 static int gmatch(char *s, char *p)
1494 if (s == NULL || p == NULL)
1496 while ((pc = *p++ & CMASK) != '\0') {
1513 if (*p == '\0' || gmatch(s, p))
1515 } while (*s++ != '\0');
1519 if (sc != (pc & ~QUOTE))
1526 static char *cclass(char *p, int sub)
1528 int c, d, not, found;
1530 if ((not = *p == NOT) != 0)
1537 if (p[1] == '-' && p[2] != ']') {
1542 if (c == sub || (c <= sub && sub <= d))
1544 } while (*++p != ']');
1545 return found ? p + 1 : NULL;
1549 /* -------- area.c -------- */
1552 * All memory between (char *)areabot and (char *)(areatop+1) is
1553 * exclusively administered by the area management routines.
1554 * It is assumed that sbrk() and brk() manipulate the high end.
1557 #define sbrk(X) ({ void * __q = (void *)-1; if (brkaddr + (int)(X) < brktop) { __q = brkaddr; brkaddr+=(int)(X); } __q;})
1559 static void initarea(void)
1561 brkaddr = xmalloc(AREASIZE);
1562 brktop = brkaddr + AREASIZE;
1564 while ((long) sbrk(0) & ALIGN)
1566 areabot = (struct region *) sbrk(REGSIZE);
1568 areabot->next = areabot;
1569 areabot->area = BUSY;
1574 char *getcell(unsigned nbytes)
1577 struct region *p, *q;
1584 /* silly and defeats the algorithm */
1586 * round upwards and add administration area
1588 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
1589 for (p = areanxt;;) {
1590 if (p->area > areanum) {
1594 while ((q = p->next)->area > areanum && q != areanxt)
1597 * exit loop if cell big enough
1599 if (q >= p + nregio)
1606 i = nregio >= GROWBY ? nregio : GROWBY;
1607 p = (struct region *) sbrk(i * REGSIZE);
1608 if (p == (struct region *) -1)
1613 abort(); /* allocated areas are contiguous */
1623 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
1625 areanxt = p + nregio;
1628 * split into requested area and rest
1630 if (areanxt + 1 > q) {
1632 abort(); /* insufficient space left for admin */
1635 areanxt->area = FREE;
1639 return (char *) (p + 1);
1642 static void freecell(char *cp)
1646 p = (struct region *) cp;
1655 static void freearea(int a)
1657 struct region *p, *top;
1660 for (p = areabot; p != top; p = p->next)
1665 static void setarea(char *cp, int a)
1669 if ((p = (struct region *) cp) != NULL)
1673 int getarea(char *cp)
1675 return ((struct region *) cp - 1)->area;
1678 static void garbage(void)
1680 struct region *p, *q, *top;
1683 for (p = areabot; p != top; p = p->next) {
1684 if (p->area > areanum) {
1685 while ((q = p->next)->area > areanum)
1691 if (areatop >= q + SHRINKBY && q->area > areanum) {
1692 brk((char *) (q + 1));
1700 /* -------- csyn.c -------- */
1702 * shell: syntax (C version)
1707 DBGPRINTF7(("YYPARSE: enter...\n"));
1714 return (yynerrs != 0);
1717 static struct op *pipeline(int cf)
1722 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1726 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1729 while ((c = yylex(0)) == '|') {
1730 p = command(CONTIN);
1732 DBGPRINTF8(("PIPELINE: error!\n"));
1736 if (t->type != TPAREN && t->type != TCOM) {
1737 /* shell statement */
1738 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1741 t = block(TPIPE, t, p, NOWORDS);
1746 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1750 static struct op *andor(void)
1755 DBGPRINTF7(("ANDOR: enter...\n"));
1759 DBGPRINTF9(("ANDOR: t=%p\n", t));
1762 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1763 p = pipeline(CONTIN);
1765 DBGPRINTF8(("ANDOR: error!\n"));
1769 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1775 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1779 static struct op *c_list(void)
1784 DBGPRINTF7(("C_LIST: enter...\n"));
1791 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1793 while ((c = yylex(0)) == ';' || c == '&'
1794 || (multiline && c == '\n')) {
1802 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1810 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1814 static int synio(int cf)
1820 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1823 if (c != '<' && c != '>') {
1830 iop = io(iounit, i, yylval.cp);
1834 markhere(yylval.cp, iop);
1836 DBGPRINTF7(("SYNIO: returning 1\n"));
1840 static void musthave(int c, int cf)
1842 if ((peeksym = yylex(cf)) != c) {
1843 DBGPRINTF7(("MUSTHAVE: error!\n"));
1850 static struct op *simple(void)
1856 switch (peeksym = yylex(0)) {
1877 static struct op *nested(int type, int mark)
1881 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1887 return block(type, t, NOBLOCK, NOWORDS);
1890 static struct op *command(int cf)
1893 struct wdblock *iosave;
1896 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1922 t = nested(TPAREN, ')');
1926 t = nested(TBRACE, '}');
1936 t->words = wordlist();
1938 if (c != '\n' && c != ';')
1940 t->left = dogroup(0);
1948 t->type = c == WHILE ? TWHILE : TUNTIL;
1950 t->right = dogroup(1);
1962 musthave(IN, CONTIN);
1965 t->left = caselist();
1976 t->right = thenpart();
1985 musthave(WORD, 0); /* gets name of file */
1986 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1988 word(yylval.cp); /* add word to wdlist */
1989 word(NOWORD); /* terminate wdlist */
1990 t->words = copyw(); /* dup wdlist */
2000 DBGPRINTF(("COMMAND: returning %p\n", t));
2005 static struct op *dowholefile(int type, int mark)
2009 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
2014 t = block(type, t, NOBLOCK, NOWORDS);
2015 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
2019 static struct op *dogroup(int onlydone)
2025 if (c == DONE && onlydone)
2034 static struct op *thenpart(void)
2047 if (t->left == NULL)
2049 t->right = elsepart();
2053 static struct op *elsepart(void)
2058 switch (c = yylex(0)) {
2069 t->right = thenpart();
2078 static struct op *caselist(void)
2083 while ((peeksym = yylex(CONTIN)) != ESAC) {
2084 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
2085 t = list(t, casepart());
2088 DBGPRINTF(("CASELIST, returning t=%p\n", t));
2092 static struct op *casepart(void)
2096 DBGPRINTF7(("CASEPART: enter...\n"));
2100 t->words = pattern();
2103 peeksym = yylex(CONTIN);
2104 if (peeksym != ESAC)
2105 musthave(BREAK, CONTIN);
2107 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2112 static char **pattern(void)
2129 static char **wordlist(void)
2139 while ((c = yylex(0)) == WORD)
2147 * supporting functions
2149 static struct op *list(struct op *t1, struct op *t2)
2151 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2158 return block(TLIST, t1, t2, NOWORDS);
2161 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2165 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2173 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2179 /* See if given string is a shell multiline (FOR, IF, etc) */
2180 static int rlookup(char *n)
2182 const struct res *rp;
2184 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2186 for (rp = restab; rp->r_name; rp++)
2187 if (strcmp(rp->r_name, n) == 0) {
2188 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2189 return rp->r_val; /* Return numeric code for shell multiline */
2192 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2193 return 0; /* Not a shell multiline */
2196 static struct op *newtp(void)
2200 t = (struct op *) tree(sizeof(*t));
2208 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2213 static struct op *namelist(struct op *t)
2216 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2217 T_CMD_NAMES[t->type], iolist));
2220 iolist = addword((char *) NULL, iolist);
2221 t->ioact = copyio();
2225 if (t->type != TCOM) {
2226 if (t->type != TPAREN && t->ioact != NULL) {
2227 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2228 t->ioact = t->left->ioact;
2229 t->left->ioact = NULL;
2240 static char **copyw(void)
2244 wd = getwords(wdlist);
2249 static void word(char *cp)
2251 wdlist = addword(cp, wdlist);
2254 static struct ioword **copyio(void)
2256 struct ioword **iop;
2258 iop = (struct ioword **) getwords(iolist);
2263 static struct ioword *io(int u, int f, char *cp)
2267 iop = (struct ioword *) tree(sizeof(*iop));
2271 iolist = addword((char *) iop, iolist);
2275 static void zzerr(void)
2277 yyerror("syntax error");
2280 static void yyerror(char *s)
2283 if (interactive && e.iop <= iostack) {
2285 while (eofc() == 0 && yylex(0) != '\n');
2291 static int yylex(int cf)
2312 line[LINELIM - 1] = '\0';
2315 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2320 if (any(c, "0123456789")) {
2321 unget(c1 = my_getc(0));
2322 if (c1 == '<' || c1 == '>') {
2331 case '#': /* Comment, skip to next newline or End-of-string */
2332 while ((c = my_getc(0)) != 0 && c != '\n');
2337 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2341 DBGPRINTF9(("YYLEX: found $\n"));
2343 if ((c = my_getc(0)) == '{') {
2344 if ((c = collect(c, '}')) != '\0')
2353 if ((c = collect(c, c)) != '\0')
2361 /* If more chars process them, else return NULL char */
2362 if ((c1 = dual(c)) != '\0')
2379 if (multiline || cf & CONTIN) {
2380 if (interactive && e.iop <= iostack) {
2381 #if ENABLE_FEATURE_EDITING
2382 current_prompt = cprompt->value;
2384 prs(cprompt->value);
2401 while ((c = my_getc(0)) != 0 && !any(c, "`$ '\"\t;&<>()|^\n")) {
2402 if (e.linep >= elinep)
2403 err("word too long");
2410 if (any(c, "\"'`$"))
2415 if (atstart && (c = rlookup(line)) != 0) {
2420 yylval.cp = strsave(line, areanum);
2425 static int collect(int c, int c1)
2429 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2432 while ((c = my_getc(c1)) != c1) {
2441 if (interactive && c == '\n' && e.iop <= iostack) {
2442 #if ENABLE_FEATURE_EDITING
2443 current_prompt = cprompt->value;
2445 prs(cprompt->value);
2453 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2458 /* "multiline commands" helper func */
2459 /* see if next 2 chars form a shell multiline */
2460 static int dual(int c)
2465 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2467 *cp++ = c; /* c is the given "peek" char */
2468 *cp++ = my_getc(0); /* get next char of input */
2469 *cp = 0; /* add EOS marker */
2471 c = rlookup(s); /* see if 2 chars form a shell multiline */
2473 unget(*--cp); /* String is not a shell multiline, put peek char back */
2475 return c; /* String is multiline, return numeric multiline (restab) code */
2478 static void diag(int ec)
2482 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2485 if (c == '>' || c == '<') {
2488 yylval.i = ec == '>' ? IOWRITE | IOCAT : IOHERE;
2491 yylval.i = ec == '>' ? IOWRITE : IOREAD;
2492 if (c != '&' || yylval.i == IOHERE)
2498 static char *tree(unsigned size)
2504 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2505 prs("command line too complicated\n");
2515 /* -------- exec.c -------- */
2522 static int execute(struct op *t, int *pin, int *pout, int act)
2525 volatile int i, rv, a;
2526 char *cp, **wp, **wp2;
2528 struct op *outtree_save;
2532 /* Avoid longjmp clobbering */
2537 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2541 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2542 t->type, T_CMD_NAMES[t->type],
2543 ((t->words == NULL) ? "NULL" : t->words[0])));
2547 wp = (wp2 = t->words) != NULL
2548 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2553 DBGPRINTF3(("EXECUTE: TDOT\n"));
2555 outtree_save = outtree;
2557 newfile(evalstr(t->words[0], DOALL));
2559 t->left = dowholefile(TLIST, 0);
2562 outtree = outtree_save;
2565 rv = execute(t->left, pin, pout, 0);
2567 rv = execute(t->right, pin, pout, 0);
2571 rv = execute(t->left, pin, pout, 0);
2576 rv = forkexec(t, pin, pout, act, wp);
2587 pv[0] = remap(pv[0]);
2588 pv[1] = remap(pv[1]);
2589 (void) execute(t->left, pin, pv, 0);
2590 rv = execute(t->right, pv, pout, 0);
2595 (void) execute(t->left, pin, pout, 0);
2596 rv = execute(t->right, pin, pout, 0);
2601 int hinteractive = interactive;
2603 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2607 interactive = hinteractive;
2609 setval(lookup("!"), putn(i));
2620 signal(SIGINT, SIG_IGN);
2621 signal(SIGQUIT, SIG_IGN);
2623 signal(SIGTERM, SIG_DFL);
2627 open(bb_dev_null, 0);
2629 _exit(execute(t->left, pin, pout, FEXEC));
2636 rv = execute(t->left, pin, pout, 0);
2638 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2639 rv = execute(t1, pin, pout, 0);
2649 while (*wp++ != NULL);
2651 vp = lookup(t->str);
2652 while (setjmp(bc.brkpt))
2656 for (t1 = t->left; i-- && *wp != NULL;) {
2658 rv = execute(t1, pin, pout, 0);
2660 brklist = brklist->nextlev;
2665 while (setjmp(bc.brkpt))
2670 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2671 rv = execute(t->right, pin, pout, 0);
2672 brklist = brklist->nextlev;
2677 if (t->right != NULL) {
2678 rv = !execute(t->left, pin, pout, 0) ?
2679 execute(t->right->left, pin, pout, 0) :
2680 execute(t->right->right, pin, pout, 0);
2685 cp = evalstr(t->str, DOSUB | DOTRIM);
2689 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2690 ((t->str == NULL) ? "NULL" : t->str),
2691 ((cp == NULL) ? "NULL" : cp)));
2693 t1 = findcase(t->left, cp);
2695 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2696 rv = execute(t1, pin, pout, 0);
2697 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2703 if (iopp = t->ioact)
2705 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2710 if (rv >= 0 && (t1 = t->left))
2711 rv = execute(t1, pin, pout, 0);
2722 if (interactive && intr) {
2733 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2738 forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2742 int (*shcom) (struct op *) = NULL;
2745 struct ioword **iopp;
2755 struct brkcon *hbrklist;
2759 /* Avoid longjmp clobbering */
2769 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2771 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2772 ((t->words == NULL) ? "NULL" : t->words[0])));
2776 rv = -1; /* system-detected error */
2777 if (t->type == TCOM) {
2778 while ((cp = *wp++) != NULL);
2781 /* strip all initial assignments */
2782 /* not correct wrt PATH=yyy command etc */
2784 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2786 echo(cp ? wp : owp);
2789 if (cp == NULL && t->ioact == NULL) {
2790 while ((cp = *owp++) != NULL && assign(cp, COPYV));
2791 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2792 return setstatus(0);
2793 } else if (cp != NULL) {
2794 shcom = inbuilt(cp);
2801 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2804 if (shcom == NULL && (f & FEXEC) == 0) {
2805 /* Save values in case the child process alters them */
2809 hinteractive = interactive;
2814 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2819 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2824 if (newpid > 0) { /* Parent */
2826 /* Restore values */
2830 interactive = hinteractive;
2843 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2846 /* Must be the child process, pid should be 0 */
2847 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2850 signal(SIGINT, SIG_IGN);
2851 signal(SIGQUIT, SIG_IGN);
2863 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2868 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2869 err("piping to/from shell builtins not yet done");
2887 if (shcom != NULL && shcom != doexec) {
2889 err(": cannot redirect shell command");
2895 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2903 i = setstatus((*shcom) (t));
2906 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2910 /* should use FIOCEXCL */
2911 for (i = FDBASE; i < NOFILE; i++)
2914 signal(SIGINT, SIG_DFL);
2915 signal(SIGQUIT, SIG_DFL);
2918 if (t->type == TPAREN)
2919 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2923 cp = rexecve(wp[0], wp, makenv(0, NULL));
2930 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2938 * 0< 1> are ignored as required
2941 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2944 char *cp = NULL, *msg;
2946 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2949 if (iop->io_unit == IODEFAULT) /* take default */
2950 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2952 if (pipein && iop->io_unit == 0)
2955 if (pipeout && iop->io_unit == 1)
2958 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2959 if ((iop->io_flag & IOHERE) == 0) {
2961 if ((cp = evalstr(cp, DOSUB | DOTRIM)) == NULL)
2965 if (iop->io_flag & IODUP) {
2966 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2968 err(": illegal >& argument");
2972 iop->io_flag = IOCLOSE;
2973 iop->io_flag &= ~(IOREAD | IOWRITE);
2975 switch (iop->io_flag) {
2981 case IOHERE | IOXHERE:
2982 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2986 case IOWRITE | IOCAT:
2987 if ((u = open(cp, 1)) >= 0) {
2988 lseek(u, (long) 0, SEEK_END);
2992 u = creat(cp, 0666);
2996 u = dup2(*cp - '0', iop->io_unit);
3000 close(iop->io_unit);
3009 if (u != iop->io_unit) {
3010 dup2(u, iop->io_unit);
3017 static void echo(char **wp)
3022 for (i = 0; wp[i]; i++) {
3030 static struct op **find1case(struct op *t, char *w)
3038 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
3042 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
3043 T_CMD_NAMES[t->type]));
3045 if (t->type == TLIST) {
3046 if ((tp = find1case(t->left, w)) != NULL) {
3047 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
3050 t1 = t->right; /* TPAT */
3054 for (wp = t1->words; *wp;)
3055 if ((cp = evalstr(*wp++, DOSUB)) && gmatch(w, cp)) {
3056 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
3061 DBGPRINTF(("FIND1CASE: returning NULL\n"));
3065 static struct op *findcase(struct op *t, char *w)
3069 tp = find1case(t, w);
3070 return tp != NULL ? *tp : NULL;
3074 * Enter a new loop level (marked for break/continue).
3076 static void brkset(struct brkcon *bc)
3078 bc->nextlev = brklist;
3083 * Wait for the last process created.
3084 * Print a message for each process found
3085 * that was killed by a signal.
3086 * Ignore interrupt signals while waiting
3087 * unless `canintr' is true.
3089 static int waitfor(int lastpid, int canintr)
3093 int oheedint = heedint;
3100 if (errno != EINTR || canintr)
3106 if (signame[rv] != NULL) {
3107 if (pid != lastpid) {
3114 if (pid != lastpid) {
3123 prs(" - core dumped");
3124 if (rv >= NSIGNAL || signame[rv])
3130 } while (pid != lastpid);
3145 static int setstatus(int s)
3148 setval(lookup("?"), putn(s));
3153 * PATH-searching interface to execve.
3154 * If getenv("PATH") were kept up-to-date,
3155 * execvp might be used.
3157 static char *rexecve(char *c, char **v, char **envp)
3161 int eacces = 0, asis = 0;
3164 if (ENABLE_FEATURE_SH_STANDALONE_SHELL) {
3166 if (find_applet_by_name(name)) {
3167 /* We have to exec here since we vforked. Running
3168 * run_applet_by_name() won't work and bad things
3170 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3174 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3176 sp = any('/', c) ? "" : path->value;
3178 while (asis || *sp != '\0') {
3181 for (; *sp != '\0'; tp++)
3182 if ((*tp = *sp++) == ':') {
3188 for (i = 0; (*tp++ = c[i++]) != '\0';);
3190 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3192 execve(e.linep, v, envp);
3199 execve(DEFAULT_SHELL, v, envp);
3204 return (char *) bb_msg_memory_exhausted;
3207 return "argument list too long";
3214 return errno == ENOENT ? "not found" : "cannot execute";
3218 * Run the command produced by generator `f'
3219 * applied to stream `arg'.
3221 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3224 struct wdblock *swdlist;
3225 struct wdblock *siolist;
3231 /* Avoid longjmp clobbering */
3235 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3236 areanum, outtree, failpt));
3246 if (newenv(setjmp(errpt)) == 0) {
3253 if (setjmp(failpt) == 0 && yyparse() == 0)
3254 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3257 DBGPRINTF(("RUN: error from newenv()!\n"));
3264 freearea(areanum--);
3269 /* -------- do.c -------- */
3272 * built-in commands: doX
3275 static int dohelp(struct op *t)
3278 const struct builtincmd *x;
3280 puts("\nBuilt-in commands:\n"
3281 "-------------------");
3283 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3286 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3292 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
3295 const struct BB_applet *applet;
3297 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3301 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3310 return EXIT_SUCCESS;
3315 static int dolabel(struct op *t)
3320 static int dochdir(struct op *t)
3325 if (cp == NULL && (cp = homedir->value) == NULL)
3326 er = ": no home directory";
3327 else if (chdir(cp) < 0)
3328 er = ": bad directory";
3331 prs(cp != NULL ? cp : "cd");
3336 static int doshift(struct op *t)
3340 n = t->words[1] ? getn(t->words[1]) : 1;
3342 err("nothing to shift");
3348 setval(lookup("#"), putn(dolc));
3353 * execute login and newgrp directly
3355 static int dologin(struct op *t)
3360 signal(SIGINT, SIG_DFL);
3361 signal(SIGQUIT, SIG_DFL);
3363 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3370 static int doumask(struct op *t)
3379 for (n = 3 * 4; (n -= 3) >= 0;)
3380 putc('0' + ((i >> n) & 07), stderr);
3383 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3384 n = n * 8 + (*cp - '0');
3390 static int doexec(struct op *t)
3397 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3403 if (setjmp(failpt) == 0)
3404 execute(t, NOPIPE, NOPIPE, FEXEC);
3410 static int dodot(struct op *t)
3417 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)));
3421 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3424 DBGPRINTF(("DODOT: cp is %s\n", cp));
3427 sp = any('/', cp) ? ":" : path->value;
3429 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3430 ((sp == NULL) ? "NULL" : sp),
3431 ((e.linep == NULL) ? "NULL" : e.linep)));
3435 while (*sp && (*tp = *sp++) != ':')
3440 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3443 i = open(e.linep, 0);
3447 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3449 next(maltmp); /* Basically a PUSHIO */
3451 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3464 static int dowait(struct op *t)
3476 setstatus(waitfor(i, 1));
3480 static int doread(struct op *t)
3486 if (t->words[1] == NULL) {
3487 err("Usage: read name ...");
3490 for (wp = t->words + 1; *wp; wp++) {
3491 for (cp = e.linep; !nl && cp < elinep - 1; cp++) {
3492 nb = read(0, cp, sizeof(*cp));
3493 if (nb != sizeof(*cp) || (nl = (*cp == '\n'))
3494 || (wp[1] && any(*cp, ifs->value))
3502 setval(lookup(*wp), e.linep);
3507 static int doeval(struct op *t)
3509 return RUN(awordlist, t->words + 1, wdchar);
3512 static int dotrap(struct op *t)
3517 if (t->words[1] == NULL) {
3518 for (i = 0; i <= _NSIG; i++)
3527 resetsig = isdigit(*t->words[1]);
3528 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3529 n = getsig(t->words[i]);
3533 if (*t->words[1] != '\0') {
3534 trap[n] = strsave(t->words[1], 0);
3543 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3551 static int getsig(char *s)
3556 if (n < 0 || n > _NSIG) {
3557 err("trap: bad signal number");
3563 static void setsig(int n, sighandler_t f)
3567 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3573 static int getn(char *as)
3584 for (n = 0; isdigit(*s); s++)
3585 n = (n * 10) + (*s - '0');
3588 err(": bad number");
3593 static int dobreak(struct op *t)
3595 return brkcontin(t->words[1], 1);
3598 static int docontinue(struct op *t)
3600 return brkcontin(t->words[1], 0);
3603 static int brkcontin(char *cp, int val)
3608 nl = cp == NULL ? 1 : getn(cp);
3612 if ((bc = brklist) == NULL)
3614 brklist = bc->nextlev;
3617 err("bad break/continue level");
3621 longjmp(bc->brkpt, 1);
3625 static int doexit(struct op *t)
3630 if ((cp = t->words[1]) != NULL)
3631 setstatus(getn(cp));
3633 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3640 static int doexport(struct op *t)
3642 rdexp(t->words + 1, export, EXPORT);
3646 static int doreadonly(struct op *t)
3648 rdexp(t->words + 1, ronly, RONLY);
3652 static void rdexp(char **wp, void (*f) (struct var *), int key)
3654 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3655 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3658 for (; *wp != NULL; wp++) {
3659 if (isassign(*wp)) {
3663 for (cp = *wp; *cp != '='; cp++);
3675 static void badid(char *s)
3678 err(": bad identifier");
3681 static int doset(struct op *t)
3689 for (vp = vlist; vp; vp = vp->next)
3690 varput(vp->name, 1);
3694 /* bad: t->words++; */
3695 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3697 flag['x'] = flag['v'] = 0;
3707 if (*cp >= 'a' && *cp <= 'z')
3714 t->words[0] = dolv[0];
3715 for (n = 1; t->words[n]; n++)
3716 setarea((char *) t->words[n], 0);
3719 setval(lookup("#"), putn(dolc));
3720 setarea((char *) (dolv - 1), 0);
3725 static void varput(char *s, int out)
3727 if (isalnum(*s) || *s == '_') {
3728 write(out, s, strlen(s));
3729 write(out, "\n", 1);
3735 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3736 * This file contains code for the times builtin.
3738 static int dotimes(struct op *t)
3741 long int clk_tck = sysconf(_SC_CLK_TCK);
3744 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3745 (int) (buf.tms_utime / clk_tck / 60),
3746 ((double) buf.tms_utime) / clk_tck,
3747 (int) (buf.tms_stime / clk_tck / 60),
3748 ((double) buf.tms_stime) / clk_tck,
3749 (int) (buf.tms_cutime / clk_tck / 60),
3750 ((double) buf.tms_cutime) / clk_tck,
3751 (int) (buf.tms_cstime / clk_tck / 60),
3752 ((double) buf.tms_cstime) / clk_tck);
3757 static int (*inbuilt(char *s)) (struct op *) {
3758 const struct builtincmd *bp;
3760 for (bp = builtincmds; bp->name != NULL; bp++)
3761 if (strcmp(bp->name, s) == 0)
3762 return bp->builtinfunc;
3767 /* -------- eval.c -------- */
3772 * blank interpretation
3777 static char **eval(char **ap, int f)
3785 /* Avoid longjmp clobbering */
3790 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3796 if (newenv(setjmp(errpt)) == 0) {
3797 while (*ap && isassign(*ap))
3798 expand(*ap++, &wb, f & ~DOGLOB);
3800 for (wf = ap; *wf; wf++) {
3802 expand(*wf, &wb, f & ~DOGLOB);
3805 for (wb = addword((char *) 0, wb); *ap; ap++) {
3806 if (!flag['k'] || !isassign(*ap))
3807 expand(*ap, &wb, f & ~DOKEY);
3809 wb = addword((char *) 0, wb);
3815 return gflg ? (char **) NULL : wp;
3819 * Make the exported environment from the exported
3820 * names in the dictionary. Keyword assignments
3821 * will already have been done.
3823 static char **makenv(int all, struct wdblock *wb)
3827 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3829 for (vp = vlist; vp; vp = vp->next)
3830 if (all || vp->status & EXPORT)
3831 wb = addword(vp->name, wb);
3832 wb = addword((char *) 0, wb);
3833 return getwords(wb);
3836 static char *evalstr(char *cp, int f)
3840 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3843 if (expand(cp, &wb, f)) {
3844 if (wb == NULL || wb->w_nword == 0
3845 || (cp = wb->w_words[0]) == NULL)
3853 static int expand(char *cp, struct wdblock **wbp, int f)
3858 /* Avoid longjmp clobbering */
3862 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3869 if (!anys("$`'\"", cp) &&
3870 !anys(ifs->value, cp) && ((f & DOGLOB) == 0 || !anys("[*?", cp))) {
3871 cp = strsave(cp, areanum);
3874 *wbp = addword(cp, *wbp);
3877 if (newenv(setjmp(errpt = ev)) == 0) {
3878 PUSHIO(aword, cp, strchar);
3880 while ((cp = blank(f)) && gflg == 0) {
3882 cp = strsave(cp, areanum);
3883 if ((f & DOGLOB) == 0) {
3886 *wbp = addword(cp, *wbp);
3888 *wbp = glob(cp, *wbp);
3897 * Blank interpretation and quoting
3899 static char *blank(int f)
3903 int scanequals, foundequals;
3905 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3908 scanequals = f & DOKEY;
3912 c = subgetc('"', foundequals);
3921 if (f & DOBLANK && any(c, ifs->value))
3930 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3933 if (c == '\'' || !any(c, "$`\""))
3940 if (!isalpha(c) && c != '_')
3943 c = subgetc('"', foundequals);
3945 f & (DOBLANK && any(c, ifs->value)) ||
3946 (!INSUB() && any(c, "\"'"))) {
3957 } else if (!isalnum(c) && c != '_')
3967 * Get characters, substituting for ` and $
3969 static int subgetc(char ec, int quoted)
3973 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3977 if (!INSUB() && ec != '\'') {
3979 if (grave(quoted) == 0)
3981 e.iop->task = XGRAVE;
3984 if (c == '$' && (c = dollar(quoted)) == 0) {
3985 e.iop->task = XDOLL;
3993 * Prepare to generate the string returned by ${} substitution.
3995 static int dollar(int quoted)
4000 char *s, c, *cp = NULL;
4003 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
4009 if (isalpha(c) || c == '_') {
4010 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
4011 if (e.linep < elinep)
4018 otask = e.iop->task;
4020 e.iop->task = XOTHER;
4021 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
4022 if (e.linep < elinep)
4025 e.iop->task = otask;
4032 if (e.linep >= elinep) {
4033 err("string in ${} too long");
4039 for (cp = s + 1; *cp; cp++)
4040 if (any(*cp, "=-+?")) {
4045 if (s[1] == 0 && (*s == '*' || *s == '@')) {
4047 /* currently this does not distinguish $* and $@ */
4048 /* should check dollar */
4050 PUSHIO(awordlist, dolv + 1, dolchar);
4052 } else { /* trap the nasty ${=} */
4058 if ((dolp = vp->value) == null) {
4062 err("cannot use ${...=...} with $n");
4071 dolp = strsave(cp, areanum);
4076 prs("missing value for ");
4083 } else if (c == '+')
4084 dolp = strsave(cp, areanum);
4085 if (flag['u'] && dolp == null) {
4086 prs("unset variable: ");
4091 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4096 * Run the command in `...` and read its output.
4099 static int grave(int quoted)
4105 static char child_cmd[LINELIM];
4111 char *argument_list[4];
4112 struct wdblock *wb = NULL;
4115 /* Avoid longjmp clobbering */
4119 for (cp = e.iop->argp->aword; *cp != '`'; cp++)
4121 err("no closing `");
4125 /* string copy with dollar expansion */
4126 src = e.iop->argp->aword;
4131 while ((*src != '`') && (count < LINELIM)) {
4136 if (*src == '$' && !ignore && !ignore_once) {
4138 char var_name[LINELIM];
4139 char alt_value[LINELIM];
4152 var_name[var_index++] = *src++;
4153 while (isalnum(*src) || *src=='_')
4154 var_name[var_index++] = *src++;
4155 var_name[var_index] = 0;
4168 err("unclosed ${\n");
4173 while (*src && (*src != '}')) {
4174 alt_value[alt_index++] = *src++;
4176 alt_value[alt_index] = 0;
4178 err("unclosed ${\n");
4185 if (isalpha(*var_name)) {
4186 /* let subshell handle it instead */
4188 char *namep = var_name;
4196 char *altp = alt_value;
4204 wb = addword(lookup(var_name)->name, wb);
4208 vp = lookup(var_name);
4209 if (vp->value != null)
4210 value = (operator == '+') ?
4211 alt_value : vp->value;
4212 else if (operator == '?') {
4215 } else if (alt_index && (operator != '+')) {
4217 if (operator == '=')
4222 while (*value && (count < LINELIM)) {
4235 if (openpipe(pf) < 0)
4238 while ((i = vfork()) == -1 && errno == EAGAIN);
4240 DBGPRINTF3(("GRAVE: i is %p\n", io));
4244 err((char *) bb_msg_memory_exhausted);
4248 waitpid(i, NULL, 0);
4249 e.iop->argp->aword = ++cp;
4251 PUSHIO(afile, remap(pf[0]),
4252 (int (*)(struct ioarg *)) ((quoted) ? qgravechar :
4256 /* allow trapped signals */
4257 /* XXX - Maybe this signal stuff should go as well? */
4258 for (j = 0; j <= _NSIG; j++)
4259 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4265 argument_list[0] = (char *) DEFAULT_SHELL;
4266 argument_list[1] = "-c";
4267 argument_list[2] = child_cmd;
4268 argument_list[3] = 0;
4270 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4271 prs(argument_list[0]);
4278 static char *unquote(char *as)
4289 /* -------- glob.c -------- */
4295 #define scopy(x) strsave((x), areanum)
4297 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4299 static struct wdblock *cl, *nl;
4300 static char spcl[] = "[?*";
4302 static struct wdblock *glob(char *cp, struct wdblock *wb)
4310 for (pp = cp; *pp; pp++)
4313 else if (!any(*pp & ~QUOTE, spcl))
4316 for (cl = addword(scopy(cp), (struct wdblock *) 0); anyspcl(cl);
4318 nl = newword(cl->w_nword * 2);
4319 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4320 for (pp = cl->w_words[i]; *pp; pp++)
4321 if (any(*pp, spcl)) {
4322 globname(cl->w_words[i], pp);
4326 nl = addword(scopy(cl->w_words[i]), nl);
4328 for (i = 0; i < cl->w_nword; i++)
4329 DELETE(cl->w_words[i]);
4332 for (i = 0; i < cl->w_nword; i++)
4333 unquote(cl->w_words[i]);
4334 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4336 for (i = 0; i < cl->w_nword; i++)
4337 wb = addword(cl->w_words[i], wb);
4342 wb = addword(unquote(cp), wb);
4346 static void globname(char *we, char *pp)
4349 char *name, *gp, *dp;
4353 char dname[NAME_MAX + 1];
4356 for (np = we; np != pp; pp--)
4359 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4363 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4372 dname[NAME_MAX] = '\0';
4373 while ((de = readdir(dirp)) != NULL) {
4374 /* XXX Hmmm... What this could be? (abial) */
4376 if (ent[j].d_ino == 0)
4379 strncpy(dname, de->d_name, NAME_MAX);
4380 if (dname[0] == '.')
4383 for (k = 0; k < NAME_MAX; k++)
4384 if (any(dname[k], spcl))
4386 if (gmatch(dname, gp)) {
4387 name = generate(we, pp, dname, np);
4388 if (*np && !anys(np, spcl)) {
4389 if (stat(name, &dbuf)) {
4394 nl = addword(name, nl);
4403 * generate a pathname as below.
4404 * start..end1 / middle end
4405 * the slashes come for free
4407 static char *generate(char *start1, char *end1, char *middle, char *end)
4413 space((int) (end1 - start1) + strlen(middle) + strlen(end) + 2);
4414 for (xp = start1; xp != end1;)
4416 for (xp = middle; (*op++ = *xp++) != '\0';);
4418 for (xp = end; (*op++ = *xp++) != '\0';);
4422 static int anyspcl(struct wdblock *wb)
4428 for (i = 0; i < wb->w_nword; i++)
4429 if (anys(spcl, *wd++))
4434 static int xstrcmp(char *p1, char *p2)
4436 return strcmp(*(char **) p1, *(char **) p2);
4439 /* -------- word.c -------- */
4441 static struct wdblock *newword(int nw)
4445 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4451 static struct wdblock *addword(char *wd, struct wdblock *wb)
4453 struct wdblock *wb2;
4457 wb = newword(NSTART);
4459 if (nw >= wb->w_bsize) {
4460 wb2 = newword(nw * 2);
4461 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4462 nw * sizeof(char *));
4467 wb->w_words[wb->w_nword++] = wd;
4472 char **getwords(struct wdblock *wb)
4479 if (wb->w_nword == 0) {
4483 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4484 memcpy((char *) wd, (char *) wb->w_words, nb);
4485 DELETE(wb); /* perhaps should done by caller */
4489 static int (*func) (char *, char *);
4492 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4496 glob1(a0, a0 + a1 * a2);
4499 static void glob1(char *base, char *lim)
4510 n = (int) (lim - base);
4513 n = v2 * (n / (2 * v2));
4514 hptr = lptr = base + n;
4519 c = (*func) (i, lptr);
4521 glob2(i, lptr -= v2);
4532 c = (*func) (hptr, j);
4534 glob2(hptr += v2, j);
4539 glob3(i, hptr += v2, j);
4554 if (lptr - base >= lim - hptr) {
4555 glob1(hptr + v2, lim);
4565 glob3(j, lptr -= v2, i);
4570 static void glob2(char *i, char *j)
4572 char *index1, *index2, c;
4580 *index1++ = *index2;
4585 static void glob3(char *i, char *j, char *k)
4587 char *index1, *index2, *index3;
4597 *index1++ = *index3;
4598 *index3++ = *index2;
4603 /* -------- io.c -------- */
4609 static int my_getc(int ec)
4613 if (e.linep > elinep) {
4614 while ((c = readc()) != '\n' && c);
4615 err("input line too long");
4620 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4623 if (c == '\n' && ec != '\"')
4631 static void unget(int c)
4633 if (e.iop >= e.iobase)
4637 static int eofc(void)
4639 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4642 static int readc(void)
4646 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4648 for (; e.iop >= e.iobase; e.iop--) {
4649 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4655 if (e.iop->prev != 0) {
4656 if ((c = (*e.iop->iofn) (e.iop->argp, e.iop)) != '\0') {
4661 if (e.iop == iostack)
4663 return (e.iop->prev = c);
4664 } else if (e.iop->task == XIO && e.iop->prev != '\n') {
4666 if (e.iop == iostack)
4671 if (e.iop->task == XIO) {
4673 return e.iop->prev = 0;
4675 if (interactive && e.iop == iostack + 1) {
4676 #if ENABLE_FEATURE_EDITING
4677 current_prompt = prompt->value;
4687 if (e.iop >= iostack) {
4688 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4692 DBGPRINTF(("READC: leave()...\n"));
4699 static void ioecho(char c)
4702 write(2, &c, sizeof c);
4706 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4708 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4709 argp->afid, e.iop));
4711 /* Set env ptr for io source to next array spot and check for array overflow */
4712 if (++e.iop >= &iostack[NPUSH]) {
4714 err("Shell input nested too deeply");
4719 /* We did not overflow the NPUSH array spots so setup data structs */
4721 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4723 if (argp->afid != AFID_NOBUF)
4727 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4728 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4730 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4732 if (e.iop == &iostack[0])
4733 e.iop->argp->afbuf = &mainbuf;
4735 e.iop->argp->afbuf = &sharedbuf;
4737 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4738 /* This line appears to be active when running scripts from command line */
4739 if ((isatty(e.iop->argp->afile) == 0)
4740 && (e.iop == &iostack[0]
4741 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4742 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4743 bufid = AFID_ID; /* AFID_ID = 0 */
4745 e.iop->argp->afid = bufid; /* assign buffer id */
4748 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4749 iostack, e.iop, e.iop->argp->afbuf));
4750 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4751 &mainbuf, &sharedbuf, bufid, e.iop));
4755 e.iop->prev = ~'\n';
4760 if (fn == filechar || fn == linechar)
4762 else if (fn == (int (*)(struct ioarg *)) gravechar
4763 || fn == (int (*)(struct ioarg *)) qgravechar)
4764 e.iop->task = XGRAVE;
4766 e.iop->task = XOTHER;
4771 static struct io *setbase(struct io *ip)
4781 * Input generating functions
4785 * Produce the characters of a string, then a newline, then EOF.
4787 static int nlchar(struct ioarg *ap)
4791 if (ap->aword == NULL)
4793 if ((c = *ap->aword++) == 0) {
4801 * Given a list of words, produce the characters
4802 * in them, with a space after each word.
4804 static int wdchar(struct ioarg *ap)
4819 ap->awordlist = NULL;
4824 * Return the characters of a list of words,
4825 * producing a space between them.
4827 static int dolchar(struct ioarg *ap)
4831 wp = *ap->awordlist++;
4833 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4839 static int xxchar(struct ioarg *ap)
4843 if (ap->aword == NULL)
4854 * Produce the characters from a single word (string).
4856 static int strchar(struct ioarg *ap)
4858 if (ap->aword == NULL)
4860 return *ap->aword++;
4864 * Produce quoted characters from a single word (string).
4866 static int qstrchar(struct ioarg *ap)
4870 if (ap->aword == NULL)
4879 * Return the characters from a file.
4881 static int filechar(struct ioarg *ap)
4885 struct iobuf *bp = ap->afbuf;
4887 if (ap->afid != AFID_NOBUF) {
4888 i = (ap->afid != bp->id);
4889 if (i || bp->bufp == bp->ebufp) {
4891 lseek(ap->afile, ap->afpos, SEEK_SET);
4893 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4902 bp->ebufp = bp->bufp + i;
4906 return *bp->bufp++ & 0177;
4908 #if ENABLE_FEATURE_EDITING
4909 if (interactive && isatty(ap->afile)) {
4910 static char mycommand[BUFSIZ];
4911 static int position = 0, size = 0;
4913 while (size == 0 || position >= size) {
4914 read_line_input(current_prompt, mycommand, BUFSIZ, line_input_state);
4915 size = strlen(mycommand);
4918 c = mycommand[position];
4924 i = safe_read(ap->afile, &c, sizeof(c));
4925 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4930 * Return the characters from a here temp file.
4932 static int herechar(struct ioarg *ap)
4936 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4945 * Return the characters produced by a process (`...`).
4946 * Quote them if required, and remove any trailing newline characters.
4948 static int gravechar(struct ioarg *ap, struct io *iop)
4952 c = qgravechar(ap, iop) & ~QUOTE;
4958 static int qgravechar(struct ioarg *ap, struct io *iop)
4962 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4967 return '\n' | QUOTE;
4971 } else if ((c = filechar(ap)) == '\n') {
4973 while ((c = filechar(ap)) == '\n')
4981 return c != 0 ? c | QUOTE : 0;
4985 * Return a single command (usually the first line) from a file.
4987 static int linechar(struct ioarg *ap)
4995 ap->afile = -1; /* illegal value */
5001 static void prs(const char *s)
5004 write(2, s, strlen(s));
5007 static void prn(unsigned u)
5012 static void closef(int i)
5018 static void closeall(void)
5022 for (u = NUFILE; u < NOFILE;)
5028 * remap fd into Shell's fd space
5030 static int remap(int fd)
5036 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
5039 for (i = 0; i < NOFILE; i++)
5046 } while (fd >= 0 && fd < e.iofd);
5048 for (i = 0; i < NOFILE; i++)
5053 err("too many files open in shell");
5059 static int openpipe(int *pv)
5065 err("can't create pipe - try again");
5069 static void closepipe(int *pv)
5077 /* -------- here.c -------- */
5083 static void markhere(char *s, struct ioword *iop)
5085 struct here *h, *lh;
5087 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
5089 h = (struct here *) space(sizeof(struct here));
5093 h->h_tag = evalstr(s, DOSUB);
5103 for (lh = inhere; lh != NULL; lh = lh->h_next)
5104 if (lh->h_next == 0) {
5108 iop->io_flag |= IOHERE | IOXHERE;
5109 for (s = h->h_tag; *s; s++)
5111 iop->io_flag &= ~IOXHERE;
5114 h->h_dosub = iop->io_flag & IOXHERE;
5117 static void gethere(void)
5119 struct here *h, *hp;
5121 DBGPRINTF7(("GETHERE: enter...\n"));
5123 /* Scan here files first leaving inhere list in place */
5124 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5125 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5127 /* Make inhere list active - keep list intact for scraphere */
5129 hp->h_next = acthere;
5135 static void readhere(char **name, char *s, int ec)
5138 char tname[30] = ".msh_XXXXXX";
5141 char myline[LINELIM + 1];
5144 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5146 tf = mkstemp(tname);
5150 *name = strsave(tname, areanum);
5152 if (newenv(setjmp(errpt)) != 0)
5155 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5158 if (interactive && e.iop <= iostack) {
5159 #if ENABLE_FEATURE_EDITING
5160 current_prompt = cprompt->value;
5162 prs(cprompt->value);
5166 while ((c = my_getc(ec)) != '\n' && c) {
5169 if (thenext >= &myline[LINELIM]) {
5176 if (strcmp(s, myline) == 0 || c == 0)
5179 write(tf, myline, (int) (thenext - myline));
5182 prs("here document `");
5192 * open here temp file.
5193 * if unquoted here, expand here temp file into second temp file.
5195 static int herein(char *hname, int xdoll)
5201 /* Avoid longjmp clobbering */
5207 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5209 hf = open(hname, 0);
5215 char tname[30] = ".msh_XXXXXX";
5218 tf = mkstemp(tname);
5221 if (newenv(setjmp(errpt = ev)) == 0) {
5222 PUSHIO(afile, hf, herechar);
5224 while ((c = subgetc(0, 0)) != 0) {
5226 write(tf, &c, sizeof c);
5232 tf = open(tname, 0);
5239 static void scraphere(void)
5243 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5245 for (h = inhere; h != NULL; h = h->h_next) {
5246 if (h->h_iop && h->h_iop->io_name)
5247 unlink(h->h_iop->io_name);
5252 /* unlink here temp files before a freearea(area) */
5253 static void freehere(int area)
5255 struct here *h, *hl;
5257 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5260 for (h = acthere; h != NULL; h = h->h_next)
5261 if (getarea((char *) h) >= area) {
5262 if (h->h_iop->io_name != NULL)
5263 unlink(h->h_iop->io_name);
5265 acthere = h->h_next;
5267 hl->h_next = h->h_next;
5275 * Copyright (c) 1987,1997, Prentice Hall
5276 * All rights reserved.
5278 * Redistribution and use of the MINIX operating system in source and
5279 * binary forms, with or without modification, are permitted provided
5280 * that the following conditions are met:
5282 * Redistributions of source code must retain the above copyright
5283 * notice, this list of conditions and the following disclaimer.
5285 * Redistributions in binary form must reproduce the above
5286 * copyright notice, this list of conditions and the following
5287 * disclaimer in the documentation and/or other materials provided
5288 * with the distribution.
5290 * Neither the name of Prentice Hall nor the names of the software
5291 * authors or contributors may be used to endorse or promote
5292 * products derived from this software without specific prior
5293 * written permission.
5295 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5296 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5297 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5298 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5299 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5300 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5301 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5302 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5303 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5304 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5305 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5306 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.