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>
22 /*#define MSHDEBUG 1*/
25 int mshdbg = MSHDEBUG;
27 #define DBGPRINTF(x) if(mshdbg>0)printf x
28 #define DBGPRINTF0(x) if(mshdbg>0)printf x
29 #define DBGPRINTF1(x) if(mshdbg>1)printf x
30 #define DBGPRINTF2(x) if(mshdbg>2)printf x
31 #define DBGPRINTF3(x) if(mshdbg>3)printf x
32 #define DBGPRINTF4(x) if(mshdbg>4)printf x
33 #define DBGPRINTF5(x) if(mshdbg>5)printf x
34 #define DBGPRINTF6(x) if(mshdbg>6)printf x
35 #define DBGPRINTF7(x) if(mshdbg>7)printf x
36 #define DBGPRINTF8(x) if(mshdbg>8)printf x
37 #define DBGPRINTF9(x) if(mshdbg>9)printf x
41 #define RCPRINTF(x) if(mshdbg_rc)printf x
62 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
63 # define DEFAULT_ROOT_PROMPT "\\u:\\w> "
64 # define DEFAULT_USER_PROMPT "\\u:\\w$ "
66 # define DEFAULT_ROOT_PROMPT "# "
67 # define DEFAULT_USER_PROMPT "$ "
71 /* -------- sh.h -------- */
77 #define NPUSH 8 /* limit to input nesting */
80 #define NOFILE 20 /* Number of open files */
81 #define NUFILE 10 /* Number of user-accessible files */
82 #define FDBASE 10 /* First file usable by Shell */
85 * values returned by wait
87 #define WAITSIG(s) ((s)&0177)
88 #define WAITVAL(s) (((s)>>8)&0377)
89 #define WAITCORE(s) (((s)&0200)!=0)
92 * library and system definitions
94 typedef void xint; /* base type of jmp_buf, for not broken compilers */
102 #define NOBLOCK ((struct op *)NULL)
103 #define NOWORD ((char *)NULL)
104 #define NOWORDS ((char **)NULL)
105 #define NOPIPE ((int *)NULL)
108 * Description of a command or an operation on commands.
109 * Might eventually use a union.
112 int type; /* operation type, see below */
113 char **words; /* arguments to a command */
114 struct ioword **ioact; /* IO actions (eg, < > >>) */
117 char *str; /* identifier for case and for */
120 #define TCOM 1 /* command */
121 #define TPAREN 2 /* (c-list) */
122 #define TPIPE 3 /* a | b */
123 #define TLIST 4 /* a [&;] b */
124 #define TOR 5 /* || */
125 #define TAND 6 /* && */
133 #define TPAT 14 /* pattern in case */
134 #define TBRACE 15 /* {c-list} */
135 #define TASYNC 16 /* c & */
136 /* Added to support "." file expansion */
139 /* Strings for names to make debug easier */
141 static const char *const T_CMD_NAMES[] = {
164 * actions determining the environment of a process
166 #define BIT(i) (1<<(i))
167 #define FEXEC BIT(0) /* execute without forking */
169 #define AREASIZE (90000)
172 * flags to control evaluation of words
174 #define DOSUB 1 /* interpret $, `, and quotes */
175 #define DOBLANK 2 /* perform blank interpretation */
176 #define DOGLOB 4 /* interpret [?* */
177 #define DOKEY 8 /* move words with `=' to 2nd arg. list */
178 #define DOTRIM 16 /* trim resulting string */
180 #define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
184 static int newfile(char *s);
185 static char *findeq(char *cp);
186 static char *cclass(char *p, int sub);
187 static void initarea(void);
188 extern int msh_main(int argc, char **argv);
193 struct brkcon *nextlev;
201 short io_unit; /* unit affected */
202 short io_flag; /* action (below) */
203 char *io_name; /* file name */
206 #define IOREAD 1 /* < */
207 #define IOHERE 2 /* << (here file) */
208 #define IOWRITE 4 /* > */
209 #define IOCAT 8 /* >> */
210 #define IOXHERE 16 /* ${}, ` in << */
211 #define IODUP 32 /* >&digit */
212 #define IOCLOSE 64 /* >&- */
214 #define IODEFAULT (-1) /* token for default IO unit */
219 * parsing & execution environment
225 xint *errpt; /* void * */
233 * -k: look for name=value everywhere on command line
235 * -t: exit after reading and executing one command
238 * -u: unset variables net diagnostic
240 static char flags['z' - 'a' + 1];
241 /* this looks weird, but is OK ... we index flag with 'a'...'z' */
242 static char *flag = flags - 'a';
244 static char *null; /* null value for variable */
245 static int intr; /* interrupt pending */
247 static char *trap[_NSIG + 1];
248 static char ourtrap[_NSIG + 1];
249 static int trapset; /* trap pending */
251 static int heedint; /* heed interrupt signals */
253 static int yynerrs; /* yacc */
255 static char line[LINELIM];
262 static int (*inbuilt(char *s)) (struct op *);
264 static char *rexecve(char *c, char **v, char **envp);
265 static char *space(int n);
266 static char *strsave(char *s, int a);
267 static char *evalstr(char *cp, int f);
268 static char *putn(int n);
269 static char *unquote(char *as);
270 static struct var *lookup(char *n);
271 static int rlookup(char *n);
272 static struct wdblock *glob(char *cp, struct wdblock *wb);
273 static int my_getc(int ec);
274 static int subgetc(char ec, int quoted);
275 static char **makenv(int all, struct wdblock *wb);
276 static char **eval(char **ap, int f);
277 static int setstatus(int s);
278 static int waitfor(int lastpid, int canintr);
280 static void onintr(int s); /* SIGINT handler */
282 static int newenv(int f);
283 static void quitenv(void);
284 static void err(char *s);
285 static int anys(char *s1, char *s2);
286 static int any(int c, char *s);
287 static void next(int f);
288 static void setdash(void);
289 static void onecommand(void);
290 static void runtrap(int i);
291 static int gmatch(char *s, char *p);
297 static void leave(void); /* abort shell (or fail in subshell) */
298 static void fail(void); /* fail but return to process next command */
299 static void warn(char *s);
300 static void sig(int i); /* default signal handler */
304 /* -------- area stuff -------- */
306 #define REGSIZE sizeof(struct region)
308 /* #define SHRINKBY (64) */
312 #define ALIGN (sizeof(int)-1)
322 /* -------- grammar stuff -------- */
347 /* Added for "." file expansion */
350 #define YYERRCODE 300
353 #define CONTIN 01 /* skip new lines to complete command */
355 #define SYNTAXERR zzerr()
357 static struct op *pipeline(int cf);
358 static struct op *andor(void);
359 static struct op *c_list(void);
360 static int synio(int cf);
361 static void musthave(int c, int cf);
362 static struct op *simple(void);
363 static struct op *nested(int type, int mark);
364 static struct op *command(int cf);
365 static struct op *dogroup(int onlydone);
366 static struct op *thenpart(void);
367 static struct op *elsepart(void);
368 static struct op *caselist(void);
369 static struct op *casepart(void);
370 static char **pattern(void);
371 static char **wordlist(void);
372 static struct op *list(struct op *t1, struct op *t2);
373 static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
374 static struct op *newtp(void);
375 static struct op *namelist(struct op *t);
376 static char **copyw(void);
377 static void word(char *cp);
378 static struct ioword **copyio(void);
379 static struct ioword *io(int u, int f, char *cp);
380 static void zzerr(void);
381 static void yyerror(char *s);
382 static int yylex(int cf);
383 static int collect(int c, int c1);
384 static int dual(int c);
385 static void diag(int ec);
386 static char *tree(unsigned size);
388 /* -------- var.h -------- */
397 #define COPYV 1 /* flag to setval, suggesting copy */
398 #define RONLY 01 /* variable is read-only */
399 #define EXPORT 02 /* variable is to be exported */
400 #define GETCELL 04 /* name & value space was got with getcell */
402 static int yyparse(void);
403 static struct var *lookup(char *n);
404 static void setval(struct var *vp, char *val);
405 static void nameval(struct var *vp, char *val, char *name);
406 static void export(struct var *vp);
407 static void ronly(struct var *vp);
408 static int isassign(char *s);
409 static int checkname(char *cp);
410 static int assign(char *s, int cf);
411 static void putvlist(int f, int out);
412 static int eqname(char *n1, char *n2);
414 static int execute(struct op *t, int *pin, int *pout, int act);
417 /* -------- io.h -------- */
420 unsigned id; /* buffer id */
421 char buf[512]; /* buffer */
422 char *bufp; /* pointer into buffer */
423 char *ebufp; /* pointer to end of buffer */
426 /* possible arguments to an IO function */
430 int afile; /* file descriptor */
431 unsigned afid; /* buffer id */
432 long afpos; /* file position */
433 struct iobuf *afbuf; /* buffer for this file */
436 //static struct ioarg ioargstack[NPUSH];
437 #define AFID_NOBUF (~0)
440 /* an input generator's state */
442 int (*iofn) (struct ioarg *, struct io *);
445 char prev; /* previous character read by readc() */
446 char nlcount; /* for `'s */
447 char xchar; /* for `'s */
448 char task; /* reason for pushed IO */
451 //static struct io iostack[NPUSH];
452 #define XOTHER 0 /* none of the below */
453 #define XDOLL 1 /* expanding ${} */
454 #define XGRAVE 2 /* expanding `'s */
455 #define XIO 3 /* file IO */
457 /* in substitution */
458 #define INSUB() (e.iop->task == XGRAVE || e.iop->task == XDOLL)
462 * input generators for IO structure
464 static int nlchar(struct ioarg *ap);
465 static int strchar(struct ioarg *ap);
466 static int qstrchar(struct ioarg *ap);
467 static int filechar(struct ioarg *ap);
468 static int herechar(struct ioarg *ap);
469 static int linechar(struct ioarg *ap);
470 static int gravechar(struct ioarg *ap, struct io *iop);
471 static int qgravechar(struct ioarg *ap, struct io *iop);
472 static int dolchar(struct ioarg *ap);
473 static int wdchar(struct ioarg *ap);
474 static void scraphere(void);
475 static void freehere(int area);
476 static void gethere(void);
477 static void markhere(char *s, struct ioword *iop);
478 static int herein(char *hname, int xdoll);
479 static int run(struct ioarg *argp, int (*f) (struct ioarg *));
485 static int eofc(void);
486 static int readc(void);
487 static void unget(int c);
488 static void ioecho(char c);
489 static void prs(const char *s);
490 static void prn(unsigned u);
491 static void closef(int i);
492 static void closeall(void);
498 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
499 static int remap(int fd);
500 static int openpipe(int *pv);
501 static void closepipe(int *pv);
502 static struct io *setbase(struct io *ip);
504 #define PUSHIO(what,arg,gen) ((temparg.what = (arg)),pushio(&temparg,(gen)))
505 #define RUN(what,arg,gen) ((temparg.what = (arg)), run(&temparg,(gen)))
507 /* -------- word.h -------- */
509 #define NSTART 16 /* default number of words to allow for initially */
514 /* bounds are arbitrary */
518 static struct wdblock *addword(char *wd, struct wdblock *wb);
519 static struct wdblock *newword(int nw);
520 static char **getwords(struct wdblock *wb);
522 /* -------- area.h -------- */
527 static char *getcell(unsigned nbytes);
528 static void garbage(void);
529 static void setarea(char *cp, int a);
530 static int getarea(char *cp);
531 static void freearea(int a);
532 static void freecell(char *cp);
533 static int areanum; /* current allocation area */
535 #define NEW(type) (type *)getcell(sizeof(type))
536 #define DELETE(obj) freecell((char *)obj)
539 /* -------- misc stuff -------- */
541 static int forkexec(struct op *t, int *pin, int *pout, int act, char **wp);
542 static int iosetup(struct ioword *iop, int pipein, int pipeout);
543 static void echo(char **wp);
544 static struct op **find1case(struct op *t, char *w);
545 static struct op *findcase(struct op *t, char *w);
546 static void brkset(struct brkcon *bc);
547 static int dolabel(struct op *t);
548 static int dohelp(struct op *t);
549 static int dochdir(struct op *t);
550 static int doshift(struct op *t);
551 static int dologin(struct op *t);
552 static int doumask(struct op *t);
553 static int doexec(struct op *t);
554 static int dodot(struct op *t);
555 static int dowait(struct op *t);
556 static int doread(struct op *t);
557 static int doeval(struct op *t);
558 static int dotrap(struct op *t);
559 static int getsig(char *s);
560 static void setsig(int n, sighandler_t f);
561 static int getn(char *as);
562 static int dobreak(struct op *t);
563 static int docontinue(struct op *t);
564 static int brkcontin(char *cp, int val);
565 static int doexit(struct op *t);
566 static int doexport(struct op *t);
567 static int doreadonly(struct op *t);
568 static void rdexp(char **wp, void (*f) (struct var *), int key);
569 static void badid(char *s);
570 static int doset(struct op *t);
571 static void varput(char *s, int out);
572 static int dotimes(struct op *t);
573 static int expand(char *cp, struct wdblock **wbp, int f);
574 static char *blank(int f);
575 static int dollar(int quoted);
576 static int grave(int quoted);
577 static void globname(char *we, char *pp);
578 static char *generate(char *start1, char *end1, char *middle, char *end);
579 static int anyspcl(struct wdblock *wb);
580 static int xstrcmp(char *p1, char *p2);
581 static void glob0(char *a0, unsigned int a1, int a2,
582 int (*a3) (char *, char *));
583 static void glob1(char *base, char *lim);
584 static void glob2(char *i, char *j);
585 static void glob3(char *i, char *j, char *k);
586 static void readhere(char **name, char *s, int ec);
587 static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
588 static int xxchar(struct ioarg *ap);
593 struct ioword *h_iop;
597 static const char * const signame[] = {
600 (char *) NULL, /* interrupt */
602 "Illegal instruction",
606 "Floating Point Exception",
611 (char *) NULL, /* broken pipe */
616 #define NSIGNAL (sizeof(signame)/sizeof(signame[0]))
622 static const struct res restab[] = {
648 int (*builtinfunc) (struct op * t);
650 static const struct builtincmd builtincmds[] = {
655 {"continue", docontinue},
659 {"export", doexport},
664 {"readonly", doreadonly},
674 static struct op *scantree(struct op *);
675 static struct op *dowholefile(int, int);
678 extern char **environ; /* environment pointer */
684 static int interactive; /* Is this an interactive shell */
686 static int multiline; /* \n changed to ; */
687 static struct op *outtree; /* result from parser */
690 static struct brkcon *brklist;
692 static struct wdblock *wdlist;
693 static struct wdblock *iolist;
694 static char *trap[_NSIG + 1];
695 static char ourtrap[_NSIG + 1];
696 static int trapset; /* trap pending */
699 static struct var *mshdbg_var;
701 static struct var *vlist; /* dictionary */
702 static struct var *homedir; /* home directory */
703 static struct var *prompt; /* main prompt */
704 static struct var *cprompt; /* continuation prompt */
705 static struct var *path; /* search path for commands */
706 static struct var *shell; /* shell to interpret command files */
707 static struct var *ifs; /* field separators */
709 static int areanum; /* current allocation area */
712 static char *null = "";
713 static int heedint = 1;
714 static void (*qflag) (int) = SIG_IGN;
718 static int iounit = IODEFAULT;
719 static YYSTYPE yylval;
720 static char *elinep = line + sizeof(line) - 5;
722 static struct ioarg temparg = { 0, 0, 0, AFID_NOBUF, 0 }; /* temporary for PUSHIO */
723 static struct ioarg ioargstack[NPUSH];
724 static struct io iostack[NPUSH];
725 static struct iobuf sharedbuf = { AFID_NOBUF };
726 static struct iobuf mainbuf = { AFID_NOBUF };
727 static unsigned bufid = AFID_ID; /* buffer id counter */
729 static struct here *inhere; /* list of hear docs while parsing */
730 static struct here *acthere; /* list of active here documents */
731 static struct region *areabot; /* bottom of area */
732 static struct region *areatop; /* top of area */
733 static struct region *areanxt; /* starting point of scan */
735 static void *brkaddr;
737 static struct env e = {
738 line, /* linep: char ptr */
739 iostack, /* iobase: struct io ptr */
740 iostack - 1, /* iop: struct io ptr */
741 (xint *) NULL, /* errpt: void ptr for errors? */
742 FDBASE, /* iofd: file desc */
743 (struct env *) NULL /* oenv: struct env ptr */
747 void print_t(struct op *t)
749 DBGPRINTF(("T: t=%p, type %s, words=%p, IOword=%p\n", t,
750 T_CMD_NAMES[t->type], t->words, t->ioact));
753 DBGPRINTF(("T: W1: %s", t->words[0]));
759 void print_tree(struct op *head)
762 DBGPRINTF(("PRINT_TREE: no tree\n"));
766 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
770 print_tree(head->left);
773 print_tree(head->right);
777 #endif /* MSHDEBUG */
780 #ifdef CONFIG_FEATURE_COMMAND_EDITING
781 static char *current_prompt;
784 /* -------- sh.c -------- */
790 int msh_main(int argc, char **argv)
796 int (*iof) (struct ioarg *);
798 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
804 assign(*ap++, !COPYV);
805 for (ap = environ; *ap;)
806 export(lookup(*ap++));
811 shell = lookup("SHELL");
812 if (shell->value == null)
813 setval(shell, (char *)DEFAULT_SHELL);
816 homedir = lookup("HOME");
817 if (homedir->value == null)
818 setval(homedir, "/");
821 setval(lookup("$"), putn(getpid()));
823 path = lookup("PATH");
824 if (path->value == null) {
826 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
828 setval(path, "/bin:/usr/bin");
833 if (ifs->value == null)
834 setval(ifs, " \t\n");
837 mshdbg_var = lookup("MSHDEBUG");
838 if (mshdbg_var->value == null)
839 setval(mshdbg_var, "0");
842 prompt = lookup("PS1");
843 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
844 if (prompt->value == null)
846 setval(prompt, DEFAULT_USER_PROMPT);
847 if (geteuid() == 0) {
848 setval(prompt, DEFAULT_ROOT_PROMPT);
849 prompt->status &= ~EXPORT;
851 cprompt = lookup("PS2");
852 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
853 if (cprompt->value == null)
855 setval(cprompt, "> ");
861 if (argv[0][0] == '-' && argv[0][1] != '\0') {
862 for (s = argv[0] + 1; *s; s++)
865 prompt->status &= ~EXPORT;
866 cprompt->status &= ~EXPORT;
871 PUSHIO(aword, *++argv, iof = nlchar);
883 prompt->status &= ~EXPORT;
891 if (*s >= 'a' && *s <= 'z')
899 if (iof == filechar && --argc > 0) {
902 prompt->status &= ~EXPORT;
903 cprompt->status &= ~EXPORT;
905 /* Shell is non-interactive, activate printf-based debug */
907 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
911 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
913 if (newfile(name = *++argv))
914 exit(1); /* Exit on error */
920 /* This won't be true if PUSHIO has been called, say from newfile() above */
921 if (e.iop < iostack) {
922 PUSHIO(afile, 0, iof);
923 if (isatty(0) && isatty(1) && !cflag) {
925 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
927 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
929 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
931 printf("Enter 'help' for a list of built-in commands.\n\n");
936 signal(SIGQUIT, qflag);
937 if (name && name[0] == '-') {
939 if ((f = open(".profile", 0)) >= 0)
941 if ((f = open("/etc/profile", 0)) >= 0)
945 signal(SIGTERM, sig);
947 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
948 signal(SIGINT, onintr);
953 for (ap = ++argv; --argc > 0;) {
954 if (assign(*ap = *argv++, !COPYV)) {
955 dolc--; /* keyword */
961 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
963 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
966 if (interactive && e.iop <= iostack) {
967 #ifdef CONFIG_FEATURE_COMMAND_EDITING
968 current_prompt = prompt->value;
974 /* Ensure that getenv("PATH") stays current */
975 setenv("PATH", path->value, 1);
978 DBGPRINTF(("MSH_MAIN: returning.\n"));
981 static void setdash(void)
985 char m['z' - 'a' + 1];
988 for (c = 'a'; c <= 'z'; c++)
992 setval(lookup("-"), m);
995 static int newfile(char *s)
999 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1001 if (NOT_LONE_DASH(s)) {
1002 DBGPRINTF(("NEWFILE: s is %s\n", s));
1006 err(": cannot open");
1017 struct op *scantree(struct op *head)
1024 if (head->left != NULL) {
1025 dotnode = scantree(head->left);
1030 if (head->right != NULL) {
1031 dotnode = scantree(head->right);
1036 if (head->words == NULL)
1039 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1041 if ((head->type != TDOT) && (strcmp(".", head->words[0]) == 0)) {
1042 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1050 static void onecommand(void)
1055 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1074 setjmp(failpt = m1); /* Bruce Evans' fix */
1075 if (setjmp(failpt = m1) || yyparse() || intr) {
1077 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1082 if (!interactive && intr)
1095 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1097 execute(outtree, NOPIPE, NOPIPE, 0);
1100 if (!interactive && intr) {
1112 static void fail(void)
1118 static void leave(void)
1120 DBGPRINTF(("LEAVE: leave called!\n"));
1131 static void warn(char *s)
1142 static void err(char *s)
1150 longjmp(e.errpt, 1);
1152 e.iop = e.iobase = iostack;
1155 static int newenv(int f)
1159 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1166 ep = (struct env *) space(sizeof(*ep));
1179 static void quitenv(void)
1184 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1190 /* should close `'d files */
1192 while (--fd >= e.iofd)
1198 * Is any character from s1 in s2?
1200 static int anys(char *s1, char *s2)
1209 * Is character c in s?
1211 static int any(int c, char *s)
1219 static char *putn(int n)
1224 static void next(int f)
1226 PUSHIO(afile, f, filechar);
1229 static void onintr(int s) /* ANSI C requires a parameter */
1231 signal(SIGINT, onintr);
1238 } else if (heedint) {
1244 static char *space(int n)
1250 err("out of string space");
1254 static char *strsave(char *s, int a)
1258 cp = space(strlen(s) + 1);
1270 static void sig(int i)
1276 static void runtrap(int i)
1281 if (trapstr == NULL)
1287 RUN(aword, trapstr, nlchar);
1290 /* -------- var.c -------- */
1293 * Find the given name in the dictionary
1294 * and return its value. If the name was
1295 * not previously there, enter it now and
1296 * return a null value.
1298 static struct var *lookup(char *n)
1303 static struct var dummy;
1307 for (c = 0; isdigit(*n) && c < 1000; n++)
1308 c = c * 10 + *n - '0';
1309 dummy.status = RONLY;
1310 dummy.value = c <= dolc ? dolv[c] : null;
1313 for (vp = vlist; vp; vp = vp->next)
1314 if (eqname(vp->name, n))
1317 vp = (struct var *) space(sizeof(*vp));
1318 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1319 dummy.name = dummy.value = "";
1322 for (cp = vp->name; (*cp = *n++) && *cp != '='; cp++);
1326 setarea((char *) vp, 0);
1327 setarea((char *) vp->name, 0);
1330 vp->status = GETCELL;
1336 * give variable at `vp' the value `val'.
1338 static void setval(struct var *vp, char *val)
1340 nameval(vp, val, (char *) NULL);
1344 * if name is not NULL, it must be
1345 * a prefix of the space `val',
1347 * this is all so that exporting
1348 * values is reasonably painless.
1350 static void nameval(struct var *vp, char *val, char *name)
1356 if (vp->status & RONLY) {
1357 for (xp = vp->name; *xp && *xp != '=';)
1358 putc(*xp++, stderr);
1359 err(" is read-only");
1364 xp = space(strlen(vp->name) + strlen(val) + 2);
1367 /* make string: name=value */
1368 setarea((char *) xp, 0);
1370 for (cp = vp->name; (*xp = *cp++) && *xp != '='; xp++);
1374 for (cp = val; (*xp++ = *cp++) != '\0';);
1378 if (vp->status & GETCELL)
1379 freecell(vp->name); /* form new string `name=value' */
1385 static void export(struct var *vp)
1387 vp->status |= EXPORT;
1390 static void ronly(struct var *vp)
1392 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1393 vp->status |= RONLY;
1396 static int isassign(char *s)
1398 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1400 if (!isalpha((int) *s) && *s != '_')
1402 for (; *s != '='; s++)
1403 if (*s == 0 || (!isalnum(*s) && *s != '_'))
1409 static int assign(char *s, int cf)
1414 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1416 if (!isalpha(*s) && *s != '_')
1418 for (cp = s; *cp != '='; cp++)
1419 if (*cp == 0 || (!isalnum(*cp) && *cp != '_'))
1422 nameval(vp, ++cp, cf == COPYV ? (char *) NULL : s);
1424 vp->status &= ~GETCELL;
1428 static int checkname(char *cp)
1430 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1432 if (!isalpha(*cp++) && *(cp - 1) != '_')
1435 if (!isalnum(*cp++) && *(cp - 1) != '_')
1440 static void putvlist(int f, int out)
1444 for (vp = vlist; vp; vp = vp->next)
1445 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1446 if (vp->status & EXPORT)
1447 write(out, "export ", 7);
1448 if (vp->status & RONLY)
1449 write(out, "readonly ", 9);
1450 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1451 write(out, "\n", 1);
1455 static int eqname(char *n1, char *n2)
1457 for (; *n1 != '=' && *n1 != 0; n1++)
1460 return *n2 == 0 || *n2 == '=';
1463 static char *findeq(char *cp)
1465 while (*cp != '\0' && *cp != '=')
1470 /* -------- gmatch.c -------- */
1472 * int gmatch(string, pattern)
1473 * char *string, *pattern;
1475 * Match a pattern as in sh(1).
1480 #define QMASK (CMASK&~QUOTE)
1481 #define NOT '!' /* might use ^ */
1483 static int gmatch(char *s, char *p)
1487 if (s == NULL || p == NULL)
1489 while ((pc = *p++ & CMASK) != '\0') {
1506 if (*p == '\0' || gmatch(s, p))
1508 } while (*s++ != '\0');
1512 if (sc != (pc & ~QUOTE))
1519 static char *cclass(char *p, int sub)
1521 int c, d, not, found;
1523 if ((not = *p == NOT) != 0)
1530 if (p[1] == '-' && p[2] != ']') {
1535 if (c == sub || (c <= sub && sub <= d))
1537 } while (*++p != ']');
1538 return found ? p + 1 : NULL;
1542 /* -------- area.c -------- */
1545 * All memory between (char *)areabot and (char *)(areatop+1) is
1546 * exclusively administered by the area management routines.
1547 * It is assumed that sbrk() and brk() manipulate the high end.
1550 #define sbrk(X) ({ void * __q = (void *)-1; if (brkaddr + (int)(X) < brktop) { __q = brkaddr; brkaddr+=(int)(X); } __q;})
1552 static void initarea(void)
1554 brkaddr = xmalloc(AREASIZE);
1555 brktop = brkaddr + AREASIZE;
1557 while ((long) sbrk(0) & ALIGN)
1559 areabot = (struct region *) sbrk(REGSIZE);
1561 areabot->next = areabot;
1562 areabot->area = BUSY;
1567 char *getcell(unsigned nbytes)
1570 struct region *p, *q;
1577 /* silly and defeats the algorithm */
1579 * round upwards and add administration area
1581 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
1582 for (p = areanxt;;) {
1583 if (p->area > areanum) {
1587 while ((q = p->next)->area > areanum && q != areanxt)
1590 * exit loop if cell big enough
1592 if (q >= p + nregio)
1599 i = nregio >= GROWBY ? nregio : GROWBY;
1600 p = (struct region *) sbrk(i * REGSIZE);
1601 if (p == (struct region *) -1)
1606 abort(); /* allocated areas are contiguous */
1616 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
1618 areanxt = p + nregio;
1621 * split into requested area and rest
1623 if (areanxt + 1 > q) {
1625 abort(); /* insufficient space left for admin */
1628 areanxt->area = FREE;
1632 return (char *) (p + 1);
1635 static void freecell(char *cp)
1639 p = (struct region *) cp;
1648 static void freearea(int a)
1650 struct region *p, *top;
1653 for (p = areabot; p != top; p = p->next)
1658 static void setarea(char *cp, int a)
1662 if ((p = (struct region *) cp) != NULL)
1666 int getarea(char *cp)
1668 return ((struct region *) cp - 1)->area;
1671 static void garbage(void)
1673 struct region *p, *q, *top;
1676 for (p = areabot; p != top; p = p->next) {
1677 if (p->area > areanum) {
1678 while ((q = p->next)->area > areanum)
1684 if (areatop >= q + SHRINKBY && q->area > areanum) {
1685 brk((char *) (q + 1));
1693 /* -------- csyn.c -------- */
1695 * shell: syntax (C version)
1700 DBGPRINTF7(("YYPARSE: enter...\n"));
1707 return (yynerrs != 0);
1710 static struct op *pipeline(int cf)
1715 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1719 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1722 while ((c = yylex(0)) == '|') {
1723 p = command(CONTIN);
1725 DBGPRINTF8(("PIPELINE: error!\n"));
1729 if (t->type != TPAREN && t->type != TCOM) {
1730 /* shell statement */
1731 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1734 t = block(TPIPE, t, p, NOWORDS);
1739 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1743 static struct op *andor(void)
1748 DBGPRINTF7(("ANDOR: enter...\n"));
1752 DBGPRINTF9(("ANDOR: t=%p\n", t));
1755 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1756 p = pipeline(CONTIN);
1758 DBGPRINTF8(("ANDOR: error!\n"));
1762 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1768 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1772 static struct op *c_list(void)
1777 DBGPRINTF7(("C_LIST: enter...\n"));
1784 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1786 while ((c = yylex(0)) == ';' || c == '&'
1787 || (multiline && c == '\n')) {
1795 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1803 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1807 static int synio(int cf)
1813 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1816 if (c != '<' && c != '>') {
1823 iop = io(iounit, i, yylval.cp);
1827 markhere(yylval.cp, iop);
1829 DBGPRINTF7(("SYNIO: returning 1\n"));
1833 static void musthave(int c, int cf)
1835 if ((peeksym = yylex(cf)) != c) {
1836 DBGPRINTF7(("MUSTHAVE: error!\n"));
1843 static struct op *simple(void)
1849 switch (peeksym = yylex(0)) {
1870 static struct op *nested(int type, int mark)
1874 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1880 return block(type, t, NOBLOCK, NOWORDS);
1883 static struct op *command(int cf)
1886 struct wdblock *iosave;
1889 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1915 t = nested(TPAREN, ')');
1919 t = nested(TBRACE, '}');
1929 t->words = wordlist();
1931 if (c != '\n' && c != ';')
1933 t->left = dogroup(0);
1941 t->type = c == WHILE ? TWHILE : TUNTIL;
1943 t->right = dogroup(1);
1955 musthave(IN, CONTIN);
1958 t->left = caselist();
1969 t->right = thenpart();
1978 musthave(WORD, 0); /* gets name of file */
1979 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
1981 word(yylval.cp); /* add word to wdlist */
1982 word(NOWORD); /* terminate wdlist */
1983 t->words = copyw(); /* dup wdlist */
1993 DBGPRINTF(("COMMAND: returning %p\n", t));
1998 static struct op *dowholefile(int type, int mark)
2002 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
2007 t = block(type, t, NOBLOCK, NOWORDS);
2008 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
2012 static struct op *dogroup(int onlydone)
2018 if (c == DONE && onlydone)
2027 static struct op *thenpart(void)
2040 if (t->left == NULL)
2042 t->right = elsepart();
2046 static struct op *elsepart(void)
2051 switch (c = yylex(0)) {
2062 t->right = thenpart();
2071 static struct op *caselist(void)
2076 while ((peeksym = yylex(CONTIN)) != ESAC) {
2077 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
2078 t = list(t, casepart());
2081 DBGPRINTF(("CASELIST, returning t=%p\n", t));
2085 static struct op *casepart(void)
2089 DBGPRINTF7(("CASEPART: enter...\n"));
2093 t->words = pattern();
2096 peeksym = yylex(CONTIN);
2097 if (peeksym != ESAC)
2098 musthave(BREAK, CONTIN);
2100 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2105 static char **pattern(void)
2122 static char **wordlist(void)
2132 while ((c = yylex(0)) == WORD)
2140 * supporting functions
2142 static struct op *list(struct op *t1, struct op *t2)
2144 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2151 return block(TLIST, t1, t2, NOWORDS);
2154 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2158 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2166 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2172 /* See if given string is a shell multiline (FOR, IF, etc) */
2173 static int rlookup(char *n)
2175 const struct res *rp;
2177 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2179 for (rp = restab; rp->r_name; rp++)
2180 if (strcmp(rp->r_name, n) == 0) {
2181 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2182 return rp->r_val; /* Return numeric code for shell multiline */
2185 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2186 return 0; /* Not a shell multiline */
2189 static struct op *newtp(void)
2193 t = (struct op *) tree(sizeof(*t));
2201 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2206 static struct op *namelist(struct op *t)
2209 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2210 T_CMD_NAMES[t->type], iolist));
2213 iolist = addword((char *) NULL, iolist);
2214 t->ioact = copyio();
2218 if (t->type != TCOM) {
2219 if (t->type != TPAREN && t->ioact != NULL) {
2220 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2221 t->ioact = t->left->ioact;
2222 t->left->ioact = NULL;
2233 static char **copyw(void)
2237 wd = getwords(wdlist);
2242 static void word(char *cp)
2244 wdlist = addword(cp, wdlist);
2247 static struct ioword **copyio(void)
2249 struct ioword **iop;
2251 iop = (struct ioword **) getwords(iolist);
2256 static struct ioword *io(int u, int f, char *cp)
2260 iop = (struct ioword *) tree(sizeof(*iop));
2264 iolist = addword((char *) iop, iolist);
2268 static void zzerr(void)
2270 yyerror("syntax error");
2273 static void yyerror(char *s)
2276 if (interactive && e.iop <= iostack) {
2278 while (eofc() == 0 && yylex(0) != '\n');
2284 static int yylex(int cf)
2305 line[LINELIM - 1] = '\0';
2308 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2313 if (any(c, "0123456789")) {
2314 unget(c1 = my_getc(0));
2315 if (c1 == '<' || c1 == '>') {
2324 case '#': /* Comment, skip to next newline or End-of-string */
2325 while ((c = my_getc(0)) != 0 && c != '\n');
2330 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2334 DBGPRINTF9(("YYLEX: found $\n"));
2336 if ((c = my_getc(0)) == '{') {
2337 if ((c = collect(c, '}')) != '\0')
2346 if ((c = collect(c, c)) != '\0')
2354 /* If more chars process them, else return NULL char */
2355 if ((c1 = dual(c)) != '\0')
2372 if (multiline || cf & CONTIN) {
2373 if (interactive && e.iop <= iostack) {
2374 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2375 current_prompt = cprompt->value;
2377 prs(cprompt->value);
2394 while ((c = my_getc(0)) != 0 && !any(c, "`$ '\"\t;&<>()|^\n")) {
2395 if (e.linep >= elinep)
2396 err("word too long");
2403 if (any(c, "\"'`$"))
2408 if (atstart && (c = rlookup(line)) != 0) {
2413 yylval.cp = strsave(line, areanum);
2418 static int collect(int c, int c1)
2422 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2425 while ((c = my_getc(c1)) != c1) {
2434 if (interactive && c == '\n' && e.iop <= iostack) {
2435 #ifdef CONFIG_FEATURE_COMMAND_EDITING
2436 current_prompt = cprompt->value;
2438 prs(cprompt->value);
2446 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2451 /* "multiline commands" helper func */
2452 /* see if next 2 chars form a shell multiline */
2453 static int dual(int c)
2458 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2460 *cp++ = c; /* c is the given "peek" char */
2461 *cp++ = my_getc(0); /* get next char of input */
2462 *cp = 0; /* add EOS marker */
2464 c = rlookup(s); /* see if 2 chars form a shell multiline */
2466 unget(*--cp); /* String is not a shell multiline, put peek char back */
2468 return c; /* String is multiline, return numeric multiline (restab) code */
2471 static void diag(int ec)
2475 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2478 if (c == '>' || c == '<') {
2481 yylval.i = ec == '>' ? IOWRITE | IOCAT : IOHERE;
2484 yylval.i = ec == '>' ? IOWRITE : IOREAD;
2485 if (c != '&' || yylval.i == IOHERE)
2491 static char *tree(unsigned size)
2497 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2498 prs("command line too complicated\n");
2508 /* -------- exec.c -------- */
2515 static int execute(struct op *t, int *pin, int *pout, int act)
2518 volatile int i, rv, a;
2519 char *cp, **wp, **wp2;
2521 struct op *outtree_save;
2525 /* Avoid longjmp clobbering */
2530 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2534 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2535 t->type, T_CMD_NAMES[t->type],
2536 ((t->words == NULL) ? "NULL" : t->words[0])));
2540 wp = (wp2 = t->words) != NULL
2541 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2546 DBGPRINTF3(("EXECUTE: TDOT\n"));
2548 outtree_save = outtree;
2550 newfile(evalstr(t->words[0], DOALL));
2552 t->left = dowholefile(TLIST, 0);
2555 outtree = outtree_save;
2558 rv = execute(t->left, pin, pout, 0);
2560 rv = execute(t->right, pin, pout, 0);
2564 rv = execute(t->left, pin, pout, 0);
2569 rv = forkexec(t, pin, pout, act, wp);
2580 pv[0] = remap(pv[0]);
2581 pv[1] = remap(pv[1]);
2582 (void) execute(t->left, pin, pv, 0);
2583 rv = execute(t->right, pv, pout, 0);
2588 (void) execute(t->left, pin, pout, 0);
2589 rv = execute(t->right, pin, pout, 0);
2594 int hinteractive = interactive;
2596 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2600 interactive = hinteractive;
2602 setval(lookup("!"), putn(i));
2613 signal(SIGINT, SIG_IGN);
2614 signal(SIGQUIT, SIG_IGN);
2616 signal(SIGTERM, SIG_DFL);
2620 open(bb_dev_null, 0);
2622 _exit(execute(t->left, pin, pout, FEXEC));
2629 rv = execute(t->left, pin, pout, 0);
2631 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2632 rv = execute(t1, pin, pout, 0);
2642 while (*wp++ != NULL);
2644 vp = lookup(t->str);
2645 while (setjmp(bc.brkpt))
2649 for (t1 = t->left; i-- && *wp != NULL;) {
2651 rv = execute(t1, pin, pout, 0);
2653 brklist = brklist->nextlev;
2658 while (setjmp(bc.brkpt))
2663 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2664 rv = execute(t->right, pin, pout, 0);
2665 brklist = brklist->nextlev;
2670 if (t->right != NULL) {
2671 rv = !execute(t->left, pin, pout, 0) ?
2672 execute(t->right->left, pin, pout, 0) :
2673 execute(t->right->right, pin, pout, 0);
2678 cp = evalstr(t->str, DOSUB | DOTRIM);
2682 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2683 ((t->str == NULL) ? "NULL" : t->str),
2684 ((cp == NULL) ? "NULL" : cp)));
2686 t1 = findcase(t->left, cp);
2688 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2689 rv = execute(t1, pin, pout, 0);
2690 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2696 if (iopp = t->ioact)
2698 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2703 if (rv >= 0 && (t1 = t->left))
2704 rv = execute(t1, pin, pout, 0);
2715 if (interactive && intr) {
2726 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2731 forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2735 int (*shcom) (struct op *) = NULL;
2738 struct ioword **iopp;
2748 struct brkcon *hbrklist;
2752 /* Avoid longjmp clobbering */
2762 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2764 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2765 ((t->words == NULL) ? "NULL" : t->words[0])));
2769 rv = -1; /* system-detected error */
2770 if (t->type == TCOM) {
2771 while ((cp = *wp++) != NULL);
2774 /* strip all initial assignments */
2775 /* not correct wrt PATH=yyy command etc */
2777 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2779 echo(cp ? wp : owp);
2782 if (cp == NULL && t->ioact == NULL) {
2783 while ((cp = *owp++) != NULL && assign(cp, COPYV));
2784 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2785 return setstatus(0);
2786 } else if (cp != NULL) {
2787 shcom = inbuilt(cp);
2794 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2797 if (shcom == NULL && (f & FEXEC) == 0) {
2798 /* Save values in case the child process alters them */
2802 hinteractive = interactive;
2807 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2812 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2817 if (newpid > 0) { /* Parent */
2819 /* Restore values */
2823 interactive = hinteractive;
2836 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2839 /* Must be the child process, pid should be 0 */
2840 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2843 signal(SIGINT, SIG_IGN);
2844 signal(SIGQUIT, SIG_IGN);
2856 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2861 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2862 err("piping to/from shell builtins not yet done");
2880 if (shcom != NULL && shcom != doexec) {
2882 err(": cannot redirect shell command");
2888 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2896 i = setstatus((*shcom) (t));
2899 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2903 /* should use FIOCEXCL */
2904 for (i = FDBASE; i < NOFILE; i++)
2907 signal(SIGINT, SIG_DFL);
2908 signal(SIGQUIT, SIG_DFL);
2911 if (t->type == TPAREN)
2912 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2916 cp = rexecve(wp[0], wp, makenv(0, NULL));
2923 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2931 * 0< 1> are ignored as required
2934 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2937 char *cp = NULL, *msg;
2939 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2942 if (iop->io_unit == IODEFAULT) /* take default */
2943 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2945 if (pipein && iop->io_unit == 0)
2948 if (pipeout && iop->io_unit == 1)
2951 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2952 if ((iop->io_flag & IOHERE) == 0) {
2954 if ((cp = evalstr(cp, DOSUB | DOTRIM)) == NULL)
2958 if (iop->io_flag & IODUP) {
2959 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2961 err(": illegal >& argument");
2965 iop->io_flag = IOCLOSE;
2966 iop->io_flag &= ~(IOREAD | IOWRITE);
2968 switch (iop->io_flag) {
2974 case IOHERE | IOXHERE:
2975 u = herein(iop->io_name, iop->io_flag & IOXHERE);
2979 case IOWRITE | IOCAT:
2980 if ((u = open(cp, 1)) >= 0) {
2981 lseek(u, (long) 0, SEEK_END);
2985 u = creat(cp, 0666);
2989 u = dup2(*cp - '0', iop->io_unit);
2993 close(iop->io_unit);
3002 if (u != iop->io_unit) {
3003 dup2(u, iop->io_unit);
3010 static void echo(char **wp)
3015 for (i = 0; wp[i]; i++) {
3023 static struct op **find1case(struct op *t, char *w)
3031 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
3035 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
3036 T_CMD_NAMES[t->type]));
3038 if (t->type == TLIST) {
3039 if ((tp = find1case(t->left, w)) != NULL) {
3040 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
3043 t1 = t->right; /* TPAT */
3047 for (wp = t1->words; *wp;)
3048 if ((cp = evalstr(*wp++, DOSUB)) && gmatch(w, cp)) {
3049 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
3054 DBGPRINTF(("FIND1CASE: returning NULL\n"));
3058 static struct op *findcase(struct op *t, char *w)
3062 tp = find1case(t, w);
3063 return tp != NULL ? *tp : NULL;
3067 * Enter a new loop level (marked for break/continue).
3069 static void brkset(struct brkcon *bc)
3071 bc->nextlev = brklist;
3076 * Wait for the last process created.
3077 * Print a message for each process found
3078 * that was killed by a signal.
3079 * Ignore interrupt signals while waiting
3080 * unless `canintr' is true.
3082 static int waitfor(int lastpid, int canintr)
3086 int oheedint = heedint;
3093 if (errno != EINTR || canintr)
3099 if (signame[rv] != NULL) {
3100 if (pid != lastpid) {
3107 if (pid != lastpid) {
3116 prs(" - core dumped");
3117 if (rv >= NSIGNAL || signame[rv])
3123 } while (pid != lastpid);
3138 static int setstatus(int s)
3141 setval(lookup("?"), putn(s));
3146 * PATH-searching interface to execve.
3147 * If getenv("PATH") were kept up-to-date,
3148 * execvp might be used.
3150 static char *rexecve(char *c, char **v, char **envp)
3154 int eacces = 0, asis = 0;
3157 if (ENABLE_FEATURE_SH_STANDALONE_SHELL) {
3159 if (find_applet_by_name(name)) {
3160 /* We have to exec here since we vforked. Running
3161 * run_applet_by_name() won't work and bad things
3163 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3167 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3169 sp = any('/', c) ? "" : path->value;
3171 while (asis || *sp != '\0') {
3174 for (; *sp != '\0'; tp++)
3175 if ((*tp = *sp++) == ':') {
3181 for (i = 0; (*tp++ = c[i++]) != '\0';);
3183 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3185 execve(e.linep, v, envp);
3192 execve(DEFAULT_SHELL, v, envp);
3197 return (char *) bb_msg_memory_exhausted;
3200 return "argument list too long";
3207 return errno == ENOENT ? "not found" : "cannot execute";
3211 * Run the command produced by generator `f'
3212 * applied to stream `arg'.
3214 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3217 struct wdblock *swdlist;
3218 struct wdblock *siolist;
3224 /* Avoid longjmp clobbering */
3228 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3229 areanum, outtree, failpt));
3239 if (newenv(setjmp(errpt)) == 0) {
3246 if (setjmp(failpt) == 0 && yyparse() == 0)
3247 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3250 DBGPRINTF(("RUN: error from newenv()!\n"));
3257 freearea(areanum--);
3262 /* -------- do.c -------- */
3265 * built-in commands: doX
3268 static int dohelp(struct op *t)
3271 const struct builtincmd *x;
3273 puts("\nBuilt-in commands:\n"
3274 "-------------------");
3276 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3279 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3285 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3288 const struct BB_applet *applet;
3290 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3294 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3303 return EXIT_SUCCESS;
3308 static int dolabel(struct op *t)
3313 static int dochdir(struct op *t)
3318 if (cp == NULL && (cp = homedir->value) == NULL)
3319 er = ": no home directory";
3320 else if (chdir(cp) < 0)
3321 er = ": bad directory";
3324 prs(cp != NULL ? cp : "cd");
3329 static int doshift(struct op *t)
3333 n = t->words[1] ? getn(t->words[1]) : 1;
3335 err("nothing to shift");
3341 setval(lookup("#"), putn(dolc));
3346 * execute login and newgrp directly
3348 static int dologin(struct op *t)
3353 signal(SIGINT, SIG_DFL);
3354 signal(SIGQUIT, SIG_DFL);
3356 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3363 static int doumask(struct op *t)
3372 for (n = 3 * 4; (n -= 3) >= 0;)
3373 putc('0' + ((i >> n) & 07), stderr);
3376 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3377 n = n * 8 + (*cp - '0');
3383 static int doexec(struct op *t)
3390 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3396 if (setjmp(failpt) == 0)
3397 execute(t, NOPIPE, NOPIPE, FEXEC);
3403 static int dodot(struct op *t)
3410 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)));
3414 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3417 DBGPRINTF(("DODOT: cp is %s\n", cp));
3420 sp = any('/', cp) ? ":" : path->value;
3422 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3423 ((sp == NULL) ? "NULL" : sp),
3424 ((e.linep == NULL) ? "NULL" : e.linep)));
3428 while (*sp && (*tp = *sp++) != ':')
3433 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3436 i = open(e.linep, 0);
3440 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3442 next(maltmp); /* Basically a PUSHIO */
3444 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3457 static int dowait(struct op *t)
3469 setstatus(waitfor(i, 1));
3473 static int doread(struct op *t)
3479 if (t->words[1] == NULL) {
3480 err("Usage: read name ...");
3483 for (wp = t->words + 1; *wp; wp++) {
3484 for (cp = e.linep; !nl && cp < elinep - 1; cp++) {
3485 nb = read(0, cp, sizeof(*cp));
3486 if (nb != sizeof(*cp) || (nl = (*cp == '\n'))
3487 || (wp[1] && any(*cp, ifs->value))
3495 setval(lookup(*wp), e.linep);
3500 static int doeval(struct op *t)
3502 return RUN(awordlist, t->words + 1, wdchar);
3505 static int dotrap(struct op *t)
3510 if (t->words[1] == NULL) {
3511 for (i = 0; i <= _NSIG; i++)
3520 resetsig = isdigit(*t->words[1]);
3521 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3522 n = getsig(t->words[i]);
3526 if (*t->words[1] != '\0') {
3527 trap[n] = strsave(t->words[1], 0);
3536 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3544 static int getsig(char *s)
3549 if (n < 0 || n > _NSIG) {
3550 err("trap: bad signal number");
3556 static void setsig(int n, sighandler_t f)
3560 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3566 static int getn(char *as)
3577 for (n = 0; isdigit(*s); s++)
3578 n = (n * 10) + (*s - '0');
3581 err(": bad number");
3586 static int dobreak(struct op *t)
3588 return brkcontin(t->words[1], 1);
3591 static int docontinue(struct op *t)
3593 return brkcontin(t->words[1], 0);
3596 static int brkcontin(char *cp, int val)
3601 nl = cp == NULL ? 1 : getn(cp);
3605 if ((bc = brklist) == NULL)
3607 brklist = bc->nextlev;
3610 err("bad break/continue level");
3614 longjmp(bc->brkpt, 1);
3618 static int doexit(struct op *t)
3623 if ((cp = t->words[1]) != NULL)
3624 setstatus(getn(cp));
3626 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3633 static int doexport(struct op *t)
3635 rdexp(t->words + 1, export, EXPORT);
3639 static int doreadonly(struct op *t)
3641 rdexp(t->words + 1, ronly, RONLY);
3645 static void rdexp(char **wp, void (*f) (struct var *), int key)
3647 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3648 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3651 for (; *wp != NULL; wp++) {
3652 if (isassign(*wp)) {
3656 for (cp = *wp; *cp != '='; cp++);
3668 static void badid(char *s)
3671 err(": bad identifier");
3674 static int doset(struct op *t)
3682 for (vp = vlist; vp; vp = vp->next)
3683 varput(vp->name, 1);
3687 /* bad: t->words++; */
3688 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3690 flag['x'] = flag['v'] = 0;
3700 if (*cp >= 'a' && *cp <= 'z')
3707 t->words[0] = dolv[0];
3708 for (n = 1; t->words[n]; n++)
3709 setarea((char *) t->words[n], 0);
3712 setval(lookup("#"), putn(dolc));
3713 setarea((char *) (dolv - 1), 0);
3718 static void varput(char *s, int out)
3720 if (isalnum(*s) || *s == '_') {
3721 write(out, s, strlen(s));
3722 write(out, "\n", 1);
3728 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3729 * This file contains code for the times builtin.
3731 static int dotimes(struct op *t)
3734 long int clk_tck = sysconf(_SC_CLK_TCK);
3737 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3738 (int) (buf.tms_utime / clk_tck / 60),
3739 ((double) buf.tms_utime) / clk_tck,
3740 (int) (buf.tms_stime / clk_tck / 60),
3741 ((double) buf.tms_stime) / clk_tck,
3742 (int) (buf.tms_cutime / clk_tck / 60),
3743 ((double) buf.tms_cutime) / clk_tck,
3744 (int) (buf.tms_cstime / clk_tck / 60),
3745 ((double) buf.tms_cstime) / clk_tck);
3750 static int (*inbuilt(char *s)) (struct op *) {
3751 const struct builtincmd *bp;
3753 for (bp = builtincmds; bp->name != NULL; bp++)
3754 if (strcmp(bp->name, s) == 0)
3755 return bp->builtinfunc;
3760 /* -------- eval.c -------- */
3765 * blank interpretation
3770 static char **eval(char **ap, int f)
3778 /* Avoid longjmp clobbering */
3783 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3789 if (newenv(setjmp(errpt)) == 0) {
3790 while (*ap && isassign(*ap))
3791 expand(*ap++, &wb, f & ~DOGLOB);
3793 for (wf = ap; *wf; wf++) {
3795 expand(*wf, &wb, f & ~DOGLOB);
3798 for (wb = addword((char *) 0, wb); *ap; ap++) {
3799 if (!flag['k'] || !isassign(*ap))
3800 expand(*ap, &wb, f & ~DOKEY);
3802 wb = addword((char *) 0, wb);
3808 return gflg ? (char **) NULL : wp;
3812 * Make the exported environment from the exported
3813 * names in the dictionary. Keyword assignments
3814 * will already have been done.
3816 static char **makenv(int all, struct wdblock *wb)
3820 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3822 for (vp = vlist; vp; vp = vp->next)
3823 if (all || vp->status & EXPORT)
3824 wb = addword(vp->name, wb);
3825 wb = addword((char *) 0, wb);
3826 return getwords(wb);
3829 static char *evalstr(char *cp, int f)
3833 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3836 if (expand(cp, &wb, f)) {
3837 if (wb == NULL || wb->w_nword == 0
3838 || (cp = wb->w_words[0]) == NULL)
3846 static int expand(char *cp, struct wdblock **wbp, int f)
3851 /* Avoid longjmp clobbering */
3855 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3862 if (!anys("$`'\"", cp) &&
3863 !anys(ifs->value, cp) && ((f & DOGLOB) == 0 || !anys("[*?", cp))) {
3864 cp = strsave(cp, areanum);
3867 *wbp = addword(cp, *wbp);
3870 if (newenv(setjmp(errpt = ev)) == 0) {
3871 PUSHIO(aword, cp, strchar);
3873 while ((cp = blank(f)) && gflg == 0) {
3875 cp = strsave(cp, areanum);
3876 if ((f & DOGLOB) == 0) {
3879 *wbp = addword(cp, *wbp);
3881 *wbp = glob(cp, *wbp);
3890 * Blank interpretation and quoting
3892 static char *blank(int f)
3896 int scanequals, foundequals;
3898 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3901 scanequals = f & DOKEY;
3905 c = subgetc('"', foundequals);
3914 if (f & DOBLANK && any(c, ifs->value))
3923 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3926 if (c == '\'' || !any(c, "$`\""))
3933 if (!isalpha(c) && c != '_')
3936 c = subgetc('"', foundequals);
3938 f & (DOBLANK && any(c, ifs->value)) ||
3939 (!INSUB() && any(c, "\"'"))) {
3950 } else if (!isalnum(c) && c != '_')
3960 * Get characters, substituting for ` and $
3962 static int subgetc(char ec, int quoted)
3966 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
3970 if (!INSUB() && ec != '\'') {
3972 if (grave(quoted) == 0)
3974 e.iop->task = XGRAVE;
3977 if (c == '$' && (c = dollar(quoted)) == 0) {
3978 e.iop->task = XDOLL;
3986 * Prepare to generate the string returned by ${} substitution.
3988 static int dollar(int quoted)
3993 char *s, c, *cp = NULL;
3996 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
4002 if (isalpha(c) || c == '_') {
4003 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
4004 if (e.linep < elinep)
4011 otask = e.iop->task;
4013 e.iop->task = XOTHER;
4014 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
4015 if (e.linep < elinep)
4018 e.iop->task = otask;
4025 if (e.linep >= elinep) {
4026 err("string in ${} too long");
4032 for (cp = s + 1; *cp; cp++)
4033 if (any(*cp, "=-+?")) {
4038 if (s[1] == 0 && (*s == '*' || *s == '@')) {
4040 /* currently this does not distinguish $* and $@ */
4041 /* should check dollar */
4043 PUSHIO(awordlist, dolv + 1, dolchar);
4045 } else { /* trap the nasty ${=} */
4051 if ((dolp = vp->value) == null) {
4055 err("cannot use ${...=...} with $n");
4064 dolp = strsave(cp, areanum);
4069 prs("missing value for ");
4076 } else if (c == '+')
4077 dolp = strsave(cp, areanum);
4078 if (flag['u'] && dolp == null) {
4079 prs("unset variable: ");
4084 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4089 * Run the command in `...` and read its output.
4092 static int grave(int quoted)
4098 static char child_cmd[LINELIM];
4104 char *argument_list[4];
4105 struct wdblock *wb = NULL;
4108 /* Avoid longjmp clobbering */
4112 for (cp = e.iop->argp->aword; *cp != '`'; cp++)
4114 err("no closing `");
4118 /* string copy with dollar expansion */
4119 src = e.iop->argp->aword;
4124 while ((*src != '`') && (count < LINELIM)) {
4129 if (*src == '$' && !ignore && !ignore_once) {
4131 char var_name[LINELIM];
4132 char alt_value[LINELIM];
4145 var_name[var_index++] = *src++;
4146 while (isalnum(*src) || *src=='_')
4147 var_name[var_index++] = *src++;
4148 var_name[var_index] = 0;
4161 err("unclosed ${\n");
4166 while (*src && (*src != '}')) {
4167 alt_value[alt_index++] = *src++;
4169 alt_value[alt_index] = 0;
4171 err("unclosed ${\n");
4178 if (isalpha(*var_name)) {
4179 /* let subshell handle it instead */
4181 char *namep = var_name;
4189 char *altp = alt_value;
4197 wb = addword(lookup(var_name)->name, wb);
4201 vp = lookup(var_name);
4202 if (vp->value != null)
4203 value = (operator == '+') ?
4204 alt_value : vp->value;
4205 else if (operator == '?') {
4208 } else if (alt_index && (operator != '+')) {
4210 if (operator == '=')
4215 while (*value && (count < LINELIM)) {
4228 if (openpipe(pf) < 0)
4231 while ((i = vfork()) == -1 && errno == EAGAIN);
4233 DBGPRINTF3(("GRAVE: i is %p\n", io));
4237 err((char *) bb_msg_memory_exhausted);
4241 waitpid(i, NULL, 0);
4242 e.iop->argp->aword = ++cp;
4244 PUSHIO(afile, remap(pf[0]),
4245 (int (*)(struct ioarg *)) ((quoted) ? qgravechar :
4249 /* allow trapped signals */
4250 /* XXX - Maybe this signal stuff should go as well? */
4251 for (j = 0; j <= _NSIG; j++)
4252 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4258 argument_list[0] = (char *) DEFAULT_SHELL;
4259 argument_list[1] = "-c";
4260 argument_list[2] = child_cmd;
4261 argument_list[3] = 0;
4263 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4264 prs(argument_list[0]);
4271 static char *unquote(char *as)
4282 /* -------- glob.c -------- */
4288 #define scopy(x) strsave((x), areanum)
4290 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4292 static struct wdblock *cl, *nl;
4293 static char spcl[] = "[?*";
4295 static struct wdblock *glob(char *cp, struct wdblock *wb)
4303 for (pp = cp; *pp; pp++)
4306 else if (!any(*pp & ~QUOTE, spcl))
4309 for (cl = addword(scopy(cp), (struct wdblock *) 0); anyspcl(cl);
4311 nl = newword(cl->w_nword * 2);
4312 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4313 for (pp = cl->w_words[i]; *pp; pp++)
4314 if (any(*pp, spcl)) {
4315 globname(cl->w_words[i], pp);
4319 nl = addword(scopy(cl->w_words[i]), nl);
4321 for (i = 0; i < cl->w_nword; i++)
4322 DELETE(cl->w_words[i]);
4325 for (i = 0; i < cl->w_nword; i++)
4326 unquote(cl->w_words[i]);
4327 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4329 for (i = 0; i < cl->w_nword; i++)
4330 wb = addword(cl->w_words[i], wb);
4335 wb = addword(unquote(cp), wb);
4339 static void globname(char *we, char *pp)
4342 char *name, *gp, *dp;
4346 char dname[NAME_MAX + 1];
4349 for (np = we; np != pp; pp--)
4352 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4356 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4365 dname[NAME_MAX] = '\0';
4366 while ((de = readdir(dirp)) != NULL) {
4367 /* XXX Hmmm... What this could be? (abial) */
4369 if (ent[j].d_ino == 0)
4372 strncpy(dname, de->d_name, NAME_MAX);
4373 if (dname[0] == '.')
4376 for (k = 0; k < NAME_MAX; k++)
4377 if (any(dname[k], spcl))
4379 if (gmatch(dname, gp)) {
4380 name = generate(we, pp, dname, np);
4381 if (*np && !anys(np, spcl)) {
4382 if (stat(name, &dbuf)) {
4387 nl = addword(name, nl);
4396 * generate a pathname as below.
4397 * start..end1 / middle end
4398 * the slashes come for free
4400 static char *generate(char *start1, char *end1, char *middle, char *end)
4406 space((int) (end1 - start1) + strlen(middle) + strlen(end) + 2);
4407 for (xp = start1; xp != end1;)
4409 for (xp = middle; (*op++ = *xp++) != '\0';);
4411 for (xp = end; (*op++ = *xp++) != '\0';);
4415 static int anyspcl(struct wdblock *wb)
4421 for (i = 0; i < wb->w_nword; i++)
4422 if (anys(spcl, *wd++))
4427 static int xstrcmp(char *p1, char *p2)
4429 return strcmp(*(char **) p1, *(char **) p2);
4432 /* -------- word.c -------- */
4434 static struct wdblock *newword(int nw)
4438 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4444 static struct wdblock *addword(char *wd, struct wdblock *wb)
4446 struct wdblock *wb2;
4450 wb = newword(NSTART);
4452 if (nw >= wb->w_bsize) {
4453 wb2 = newword(nw * 2);
4454 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4455 nw * sizeof(char *));
4460 wb->w_words[wb->w_nword++] = wd;
4465 char **getwords(struct wdblock *wb)
4472 if (wb->w_nword == 0) {
4476 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4477 memcpy((char *) wd, (char *) wb->w_words, nb);
4478 DELETE(wb); /* perhaps should done by caller */
4482 static int (*func) (char *, char *);
4485 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4489 glob1(a0, a0 + a1 * a2);
4492 static void glob1(char *base, char *lim)
4503 n = (int) (lim - base);
4506 n = v2 * (n / (2 * v2));
4507 hptr = lptr = base + n;
4512 c = (*func) (i, lptr);
4514 glob2(i, lptr -= v2);
4525 c = (*func) (hptr, j);
4527 glob2(hptr += v2, j);
4532 glob3(i, hptr += v2, j);
4547 if (lptr - base >= lim - hptr) {
4548 glob1(hptr + v2, lim);
4558 glob3(j, lptr -= v2, i);
4563 static void glob2(char *i, char *j)
4565 char *index1, *index2, c;
4573 *index1++ = *index2;
4578 static void glob3(char *i, char *j, char *k)
4580 char *index1, *index2, *index3;
4590 *index1++ = *index3;
4591 *index3++ = *index2;
4596 /* -------- io.c -------- */
4602 static int my_getc(int ec)
4606 if (e.linep > elinep) {
4607 while ((c = readc()) != '\n' && c);
4608 err("input line too long");
4613 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4616 if (c == '\n' && ec != '\"')
4624 static void unget(int c)
4626 if (e.iop >= e.iobase)
4630 static int eofc(void)
4632 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4635 static int readc(void)
4639 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4641 for (; e.iop >= e.iobase; e.iop--) {
4642 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4648 if (e.iop->prev != 0) {
4649 if ((c = (*e.iop->iofn) (e.iop->argp, e.iop)) != '\0') {
4654 if (e.iop == iostack)
4656 return (e.iop->prev = c);
4657 } else if (e.iop->task == XIO && e.iop->prev != '\n') {
4659 if (e.iop == iostack)
4664 if (e.iop->task == XIO) {
4666 return e.iop->prev = 0;
4668 if (interactive && e.iop == iostack + 1) {
4669 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4670 current_prompt = prompt->value;
4680 if (e.iop >= iostack) {
4681 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4685 DBGPRINTF(("READC: leave()...\n"));
4692 static void ioecho(char c)
4695 write(2, &c, sizeof c);
4699 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4701 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4702 argp->afid, e.iop));
4704 /* Set env ptr for io source to next array spot and check for array overflow */
4705 if (++e.iop >= &iostack[NPUSH]) {
4707 err("Shell input nested too deeply");
4712 /* We did not overflow the NPUSH array spots so setup data structs */
4714 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4716 if (argp->afid != AFID_NOBUF)
4720 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4721 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4723 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4725 if (e.iop == &iostack[0])
4726 e.iop->argp->afbuf = &mainbuf;
4728 e.iop->argp->afbuf = &sharedbuf;
4730 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4731 /* This line appears to be active when running scripts from command line */
4732 if ((isatty(e.iop->argp->afile) == 0)
4733 && (e.iop == &iostack[0]
4734 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4735 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4736 bufid = AFID_ID; /* AFID_ID = 0 */
4738 e.iop->argp->afid = bufid; /* assign buffer id */
4741 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4742 iostack, e.iop, e.iop->argp->afbuf));
4743 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4744 &mainbuf, &sharedbuf, bufid, e.iop));
4748 e.iop->prev = ~'\n';
4753 if (fn == filechar || fn == linechar)
4755 else if (fn == (int (*)(struct ioarg *)) gravechar
4756 || fn == (int (*)(struct ioarg *)) qgravechar)
4757 e.iop->task = XGRAVE;
4759 e.iop->task = XOTHER;
4764 static struct io *setbase(struct io *ip)
4774 * Input generating functions
4778 * Produce the characters of a string, then a newline, then EOF.
4780 static int nlchar(struct ioarg *ap)
4784 if (ap->aword == NULL)
4786 if ((c = *ap->aword++) == 0) {
4794 * Given a list of words, produce the characters
4795 * in them, with a space after each word.
4797 static int wdchar(struct ioarg *ap)
4812 ap->awordlist = NULL;
4817 * Return the characters of a list of words,
4818 * producing a space between them.
4820 static int dolchar(struct ioarg *ap)
4824 wp = *ap->awordlist++;
4826 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4832 static int xxchar(struct ioarg *ap)
4836 if (ap->aword == NULL)
4847 * Produce the characters from a single word (string).
4849 static int strchar(struct ioarg *ap)
4851 if (ap->aword == NULL)
4853 return *ap->aword++;
4857 * Produce quoted characters from a single word (string).
4859 static int qstrchar(struct ioarg *ap)
4863 if (ap->aword == NULL) || (c = *ap->aword++) == 0)
4869 * Return the characters from a file.
4871 static int filechar(struct ioarg *ap)
4875 struct iobuf *bp = ap->afbuf;
4877 if (ap->afid != AFID_NOBUF) {
4878 i = (ap->afid != bp->id);
4879 if (i || bp->bufp == bp->ebufp) {
4881 lseek(ap->afile, ap->afpos, SEEK_SET);
4883 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4892 bp->ebufp = bp->bufp + i;
4896 return *bp->bufp++ & 0177;
4898 #ifdef CONFIG_FEATURE_COMMAND_EDITING
4899 if (interactive && isatty(ap->afile)) {
4900 static char mycommand[BUFSIZ];
4901 static int position = 0, size = 0;
4903 while (size == 0 || position >= size) {
4904 cmdedit_read_input(current_prompt, mycommand);
4905 size = strlen(mycommand);
4908 c = mycommand[position];
4915 i = safe_read(ap->afile, &c, sizeof(c));
4916 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4921 * Return the characters from a here temp file.
4923 static int herechar(struct ioarg *ap)
4927 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4936 * Return the characters produced by a process (`...`).
4937 * Quote them if required, and remove any trailing newline characters.
4939 static int gravechar(struct ioarg *ap, struct io *iop)
4943 c = qgravechar(ap, iop) & ~QUOTE;
4949 static int qgravechar(struct ioarg *ap, struct io *iop)
4953 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
4958 return '\n' | QUOTE;
4962 } else if ((c = filechar(ap)) == '\n') {
4964 while ((c = filechar(ap)) == '\n')
4972 return c != 0 ? c | QUOTE : 0;
4976 * Return a single command (usually the first line) from a file.
4978 static int linechar(struct ioarg *ap)
4986 ap->afile = -1; /* illegal value */
4992 static void prs(const char *s)
4995 write(2, s, strlen(s));
4998 static void prn(unsigned u)
5003 static void closef(int i)
5009 static void closeall(void)
5013 for (u = NUFILE; u < NOFILE;)
5019 * remap fd into Shell's fd space
5021 static int remap(int fd)
5027 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
5030 for (i = 0; i < NOFILE; i++)
5037 } while (fd >= 0 && fd < e.iofd);
5039 for (i = 0; i < NOFILE; i++)
5044 err("too many files open in shell");
5050 static int openpipe(int *pv)
5056 err("can't create pipe - try again");
5060 static void closepipe(int *pv)
5068 /* -------- here.c -------- */
5074 static void markhere(char *s, struct ioword *iop)
5076 struct here *h, *lh;
5078 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
5080 h = (struct here *) space(sizeof(struct here));
5084 h->h_tag = evalstr(s, DOSUB);
5094 for (lh = inhere; lh != NULL; lh = lh->h_next)
5095 if (lh->h_next == 0) {
5099 iop->io_flag |= IOHERE | IOXHERE;
5100 for (s = h->h_tag; *s; s++)
5102 iop->io_flag &= ~IOXHERE;
5105 h->h_dosub = iop->io_flag & IOXHERE;
5108 static void gethere(void)
5110 struct here *h, *hp;
5112 DBGPRINTF7(("GETHERE: enter...\n"));
5114 /* Scan here files first leaving inhere list in place */
5115 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5116 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5118 /* Make inhere list active - keep list intact for scraphere */
5120 hp->h_next = acthere;
5126 static void readhere(char **name, char *s, int ec)
5129 char tname[30] = ".msh_XXXXXX";
5132 char myline[LINELIM + 1];
5135 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5137 tf = mkstemp(tname);
5141 *name = strsave(tname, areanum);
5143 if (newenv(setjmp(errpt)) != 0)
5146 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5149 if (interactive && e.iop <= iostack) {
5150 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5151 current_prompt = cprompt->value;
5153 prs(cprompt->value);
5157 while ((c = my_getc(ec)) != '\n' && c) {
5160 if (thenext >= &myline[LINELIM]) {
5167 if (strcmp(s, myline) == 0 || c == 0)
5170 write(tf, myline, (int) (thenext - myline));
5173 prs("here document `");
5183 * open here temp file.
5184 * if unquoted here, expand here temp file into second temp file.
5186 static int herein(char *hname, int xdoll)
5192 /* Avoid longjmp clobbering */
5198 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5200 hf = open(hname, 0);
5206 char tname[30] = ".msh_XXXXXX";
5209 tf = mkstemp(tname);
5212 if (newenv(setjmp(errpt = ev)) == 0) {
5213 PUSHIO(afile, hf, herechar);
5215 while ((c = subgetc(0, 0)) != 0) {
5217 write(tf, &c, sizeof c);
5223 tf = open(tname, 0);
5230 static void scraphere(void)
5234 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5236 for (h = inhere; h != NULL; h = h->h_next) {
5237 if (h->h_iop && h->h_iop->io_name)
5238 unlink(h->h_iop->io_name);
5243 /* unlink here temp files before a freearea(area) */
5244 static void freehere(int area)
5246 struct here *h, *hl;
5248 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5251 for (h = acthere; h != NULL; h = h->h_next)
5252 if (getarea((char *) h) >= area) {
5253 if (h->h_iop->io_name != NULL)
5254 unlink(h->h_iop->io_name);
5256 acthere = h->h_next;
5258 hl->h_next = h->h_next;
5266 * Copyright (c) 1987,1997, Prentice Hall
5267 * All rights reserved.
5269 * Redistribution and use of the MINIX operating system in source and
5270 * binary forms, with or without modification, are permitted provided
5271 * that the following conditions are met:
5273 * Redistributions of source code must retain the above copyright
5274 * notice, this list of conditions and the following disclaimer.
5276 * Redistributions in binary form must reproduce the above
5277 * copyright notice, this list of conditions and the following
5278 * disclaimer in the documentation and/or other materials provided
5279 * with the distribution.
5281 * Neither the name of Prentice Hall nor the names of the software
5282 * authors or contributors may be used to endorse or promote
5283 * products derived from this software without specific prior
5284 * written permission.
5286 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5287 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5288 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5289 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5290 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5291 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5292 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5293 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5294 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5295 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5296 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5297 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.