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.
17 #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
45 #define DBGPRINTF0(x) ((void)0)
46 #define DBGPRINTF1(x) ((void)0)
47 #define DBGPRINTF2(x) ((void)0)
48 #define DBGPRINTF3(x) ((void)0)
49 #define DBGPRINTF4(x) ((void)0)
50 #define DBGPRINTF5(x) ((void)0)
51 #define DBGPRINTF6(x) ((void)0)
52 #define DBGPRINTF7(x) ((void)0)
53 #define DBGPRINTF8(x) ((void)0)
54 #define DBGPRINTF9(x) ((void)0)
56 #define RCPRINTF(x) ((void)0)
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 typedef int (*builtin_func_ptr)(struct op *);
262 static builtin_func_ptr inbuilt(char *s);
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(const char *s);
285 static int anys(const char *s1, const char *s2);
286 static int any(int c, const 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(const 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 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 NULL, /* interrupt */
602 "Illegal instruction",
606 "Floating Point Exception",
611 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]));
757 void print_tree(struct op *head)
760 DBGPRINTF(("PRINT_TREE: no tree\n"));
764 DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
768 print_tree(head->left);
771 print_tree(head->right);
773 #endif /* MSHDEBUG */
776 #if ENABLE_FEATURE_EDITING
777 static char *current_prompt;
780 /* -------- sh.c -------- */
786 #if ENABLE_FEATURE_EDITING
787 static line_input_t *line_input_state;
790 int msh_main(int argc, char **argv)
796 int (*iof) (struct ioarg *);
798 #if ENABLE_FEATURE_EDITING
799 line_input_state = new_line_input_t(FOR_SHELL);
802 DBGPRINTF(("MSH_MAIN: argc %d, environ %p\n", argc, environ));
808 assign(*ap++, !COPYV);
809 for (ap = environ; *ap;)
810 export(lookup(*ap++));
815 shell = lookup("SHELL");
816 if (shell->value == null)
817 setval(shell, (char *)DEFAULT_SHELL);
820 homedir = lookup("HOME");
821 if (homedir->value == null)
822 setval(homedir, "/");
825 setval(lookup("$"), putn(getpid()));
827 path = lookup("PATH");
828 if (path->value == null) {
830 setval(path, "/sbin:/bin:/usr/sbin:/usr/bin");
832 setval(path, "/bin:/usr/bin");
837 if (ifs->value == null)
838 setval(ifs, " \t\n");
841 mshdbg_var = lookup("MSHDEBUG");
842 if (mshdbg_var->value == null)
843 setval(mshdbg_var, "0");
846 prompt = lookup("PS1");
847 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
848 if (prompt->value == null)
850 setval(prompt, DEFAULT_USER_PROMPT);
851 if (geteuid() == 0) {
852 setval(prompt, DEFAULT_ROOT_PROMPT);
853 prompt->status &= ~EXPORT;
855 cprompt = lookup("PS2");
856 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
857 if (cprompt->value == null)
859 setval(cprompt, "> ");
865 if (argv[0][0] == '-' && argv[0][1] != '\0') {
866 for (s = argv[0] + 1; *s; s++)
869 prompt->status &= ~EXPORT;
870 cprompt->status &= ~EXPORT;
875 PUSHIO(aword, *++argv, iof = nlchar);
887 prompt->status &= ~EXPORT;
895 if (*s >= 'a' && *s <= 'z')
903 if (iof == filechar && --argc > 0) {
906 prompt->status &= ~EXPORT;
907 cprompt->status &= ~EXPORT;
909 /* Shell is non-interactive, activate printf-based debug */
911 mshdbg = (int) (((char) (mshdbg_var->value[0])) - '0');
915 DBGPRINTF(("MSH_MAIN: calling newfile()\n"));
919 exit(1); /* Exit on error */
925 /* This won't be true if PUSHIO has been called, say from newfile() above */
926 if (e.iop < iostack) {
927 PUSHIO(afile, 0, iof);
928 if (isatty(0) && isatty(1) && !cflag) {
930 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
932 printf("\n\n%s Built-in shell (msh with debug)\n", BB_BANNER);
934 printf("\n\n%s Built-in shell (msh)\n", BB_BANNER);
936 printf("Enter 'help' for a list of built-in commands.\n\n");
941 signal(SIGQUIT, qflag);
942 if (name && name[0] == '-') {
944 f = open(".profile", 0);
947 f = open("/etc/profile", 0);
952 signal(SIGTERM, sig);
954 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
955 signal(SIGINT, onintr);
960 for (ap = ++argv; --argc > 0;) {
962 if (assign(*ap, !COPYV)) {
963 dolc--; /* keyword */
969 setval(lookup("#"), putn((--dolc < 0) ? (dolc = 0) : dolc));
971 DBGPRINTF(("MSH_MAIN: begin FOR loop, interactive %d, e.iop %p, iostack %p\n", interactive, e.iop, iostack));
974 if (interactive && e.iop <= iostack) {
975 #if ENABLE_FEATURE_EDITING
976 current_prompt = prompt->value;
982 /* Ensure that getenv("PATH") stays current */
983 setenv("PATH", path->value, 1);
986 DBGPRINTF(("MSH_MAIN: returning.\n"));
989 static void setdash(void)
993 char m['z' - 'a' + 1];
996 for (c = 'a'; c <= 'z'; c++)
1000 setval(lookup("-"), m);
1003 static int newfile(char *s)
1007 DBGPRINTF7(("NEWFILE: opening %s\n", s));
1010 if (NOT_LONE_DASH(s)) {
1011 DBGPRINTF(("NEWFILE: s is %s\n", s));
1015 err(": cannot open");
1025 struct op *scantree(struct op *head)
1032 if (head->left != NULL) {
1033 dotnode = scantree(head->left);
1038 if (head->right != NULL) {
1039 dotnode = scantree(head->right);
1044 if (head->words == NULL)
1047 DBGPRINTF5(("SCANTREE: checking node %p\n", head));
1049 if ((head->type != TDOT) && (strcmp(".", head->words[0]) == 0)) {
1050 DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
1058 static void onecommand(void)
1063 DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
1083 setjmp(failpt); /* Bruce Evans' fix */
1085 if (setjmp(failpt) || yyparse() || intr) {
1087 DBGPRINTF(("ONECOMMAND: this is not good.\n"));
1092 if (!interactive && intr)
1105 DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
1107 execute(outtree, NOPIPE, NOPIPE, 0);
1110 if (!interactive && intr) {
1122 static void fail(void)
1128 static void leave(void)
1130 DBGPRINTF(("LEAVE: leave called!\n"));
1141 static void warn(const char *s)
1152 static void err(const char *s)
1160 longjmp(e.errpt, 1);
1162 e.iop = e.iobase = iostack;
1165 static int newenv(int f)
1169 DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
1176 ep = (struct env *) space(sizeof(*ep));
1189 static void quitenv(void)
1194 DBGPRINTF(("QUITENV: e.oenv=%p\n", e.oenv));
1200 /* should close `'d files */
1202 while (--fd >= e.iofd)
1208 * Is character c in s?
1210 static int any(int c, const char *s)
1219 * Is any character from s1 in s2?
1221 static int anys(const char *s1, const char *s2)
1229 static char *putn(int n)
1234 static void next(int f)
1236 PUSHIO(afile, f, filechar);
1239 static void onintr(int s) /* ANSI C requires a parameter */
1241 signal(SIGINT, onintr);
1248 } else if (heedint) {
1254 static char *space(int n)
1260 err("out of string space");
1264 static char *strsave(char *s, int a)
1268 cp = space(strlen(s) + 1);
1280 static void sig(int i)
1286 static void runtrap(int i)
1291 if (trapstr == NULL)
1297 RUN(aword, trapstr, nlchar);
1300 /* -------- var.c -------- */
1303 * Find the given name in the dictionary
1304 * and return its value. If the name was
1305 * not previously there, enter it now and
1306 * return a null value.
1308 static struct var *lookup(char *n)
1313 static struct var dummy;
1317 for (c = 0; isdigit(*n) && c < 1000; n++)
1318 c = c * 10 + *n - '0';
1319 dummy.status = RONLY;
1320 dummy.value = c <= dolc ? dolv[c] : null;
1323 for (vp = vlist; vp; vp = vp->next)
1324 if (eqname(vp->name, n))
1327 vp = (struct var *) space(sizeof(*vp));
1328 if (vp == 0 || (vp->name = space((int) (cp - n) + 2)) == 0) {
1329 dummy.name = dummy.value = "";
1332 for (cp = vp->name; (*cp = *n++) && *cp != '='; cp++);
1336 setarea((char *) vp, 0);
1337 setarea((char *) vp->name, 0);
1340 vp->status = GETCELL;
1346 * give variable at `vp' the value `val'.
1348 static void setval(struct var *vp, char *val)
1350 nameval(vp, val, (char *) NULL);
1354 * if name is not NULL, it must be
1355 * a prefix of the space `val',
1357 * this is all so that exporting
1358 * values is reasonably painless.
1360 static void nameval(struct var *vp, char *val, char *name)
1366 if (vp->status & RONLY) {
1367 for (xp = vp->name; *xp && *xp != '=';)
1368 putc(*xp++, stderr);
1369 err(" is read-only");
1374 xp = space(strlen(vp->name) + strlen(val) + 2);
1377 /* make string: name=value */
1378 setarea((char *) xp, 0);
1380 for (cp = vp->name; (*xp = *cp++) && *xp != '='; xp++);
1384 for (cp = val; (*xp++ = *cp++) != '\0';);
1388 if (vp->status & GETCELL)
1389 freecell(vp->name); /* form new string `name=value' */
1395 static void export(struct var *vp)
1397 vp->status |= EXPORT;
1400 static void ronly(struct var *vp)
1402 if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
1403 vp->status |= RONLY;
1406 static int isassign(char *s)
1408 DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
1410 if (!isalpha((int) *s) && *s != '_')
1412 for (; *s != '='; s++)
1413 if (*s == '\0' || (!isalnum(*s) && *s != '_'))
1419 static int assign(char *s, int cf)
1424 DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
1426 if (!isalpha(*s) && *s != '_')
1428 for (cp = s; *cp != '='; cp++)
1429 if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
1432 nameval(vp, ++cp, cf == COPYV ? (char *) NULL : s);
1434 vp->status &= ~GETCELL;
1438 static int checkname(char *cp)
1440 DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
1442 if (!isalpha(*cp++) && *(cp - 1) != '_')
1445 if (!isalnum(*cp++) && *(cp - 1) != '_')
1450 static void putvlist(int f, int out)
1454 for (vp = vlist; vp; vp = vp->next)
1455 if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
1456 if (vp->status & EXPORT)
1457 write(out, "export ", 7);
1458 if (vp->status & RONLY)
1459 write(out, "readonly ", 9);
1460 write(out, vp->name, (int) (findeq(vp->name) - vp->name));
1461 write(out, "\n", 1);
1465 static int eqname(char *n1, char *n2)
1467 for (; *n1 != '=' && *n1 != '\0'; n1++)
1470 return *n2 == '\0' || *n2 == '=';
1473 static char *findeq(char *cp)
1475 while (*cp != '\0' && *cp != '=')
1480 /* -------- gmatch.c -------- */
1482 * int gmatch(string, pattern)
1483 * char *string, *pattern;
1485 * Match a pattern as in sh(1).
1490 #define QMASK (CMASK&~QUOTE)
1491 #define NOT '!' /* might use ^ */
1493 static int gmatch(char *s, char *p)
1497 if (s == NULL || p == NULL)
1499 while ((pc = *p++ & CMASK) != '\0') {
1516 if (*p == '\0' || gmatch(s, p))
1518 } while (*s++ != '\0');
1522 if (sc != (pc & ~QUOTE))
1529 static char *cclass(char *p, int sub)
1531 int c, d, not, found;
1541 if (p[1] == '-' && p[2] != ']') {
1546 if (c == sub || (c <= sub && sub <= d))
1548 } while (*++p != ']');
1549 return found ? p + 1 : NULL;
1553 /* -------- area.c -------- */
1556 * All memory between (char *)areabot and (char *)(areatop+1) is
1557 * exclusively administered by the area management routines.
1558 * It is assumed that sbrk() and brk() manipulate the high end.
1561 #define sbrk(X) ({ \
1562 void * __q = (void *)-1; \
1563 if (brkaddr + (int)(X) < brktop) { \
1565 brkaddr += (int)(X); \
1570 static void initarea(void)
1572 brkaddr = xmalloc(AREASIZE);
1573 brktop = brkaddr + AREASIZE;
1575 while ((long) sbrk(0) & ALIGN)
1577 areabot = (struct region *) sbrk(REGSIZE);
1579 areabot->next = areabot;
1580 areabot->area = BUSY;
1585 char *getcell(unsigned nbytes)
1588 struct region *p, *q;
1595 /* silly and defeats the algorithm */
1597 * round upwards and add administration area
1599 nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
1600 for (p = areanxt;;) {
1601 if (p->area > areanum) {
1605 while ((q = p->next)->area > areanum && q != areanxt)
1608 * exit loop if cell big enough
1610 if (q >= p + nregio)
1617 i = nregio >= GROWBY ? nregio : GROWBY;
1618 p = (struct region *) sbrk(i * REGSIZE);
1619 if (p == (struct region *) -1)
1624 abort(); /* allocated areas are contiguous */
1634 * we found a FREE area big enough, pointed to by 'p', and up to 'q'
1636 areanxt = p + nregio;
1639 * split into requested area and rest
1641 if (areanxt + 1 > q) {
1643 abort(); /* insufficient space left for admin */
1646 areanxt->area = FREE;
1650 return (char *) (p + 1);
1653 static void freecell(char *cp)
1657 p = (struct region *) cp;
1666 static void freearea(int a)
1668 struct region *p, *top;
1671 for (p = areabot; p != top; p = p->next)
1676 static void setarea(char *cp, int a)
1680 p = (struct region *) cp;
1685 int getarea(char *cp)
1687 return ((struct region *) cp - 1)->area;
1690 static void garbage(void)
1692 struct region *p, *q, *top;
1695 for (p = areabot; p != top; p = p->next) {
1696 if (p->area > areanum) {
1697 while ((q = p->next)->area > areanum)
1703 if (areatop >= q + SHRINKBY && q->area > areanum) {
1704 brk((char *) (q + 1));
1712 /* -------- csyn.c -------- */
1714 * shell: syntax (C version)
1719 DBGPRINTF7(("YYPARSE: enter...\n"));
1726 return (yynerrs != 0);
1729 static struct op *pipeline(int cf)
1734 DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
1738 DBGPRINTF9(("PIPELINE: t=%p\n", t));
1741 while ((c = yylex(0)) == '|') {
1742 p = command(CONTIN);
1744 DBGPRINTF8(("PIPELINE: error!\n"));
1748 if (t->type != TPAREN && t->type != TCOM) {
1749 /* shell statement */
1750 t = block(TPAREN, t, NOBLOCK, NOWORDS);
1753 t = block(TPIPE, t, p, NOWORDS);
1758 DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
1762 static struct op *andor(void)
1767 DBGPRINTF7(("ANDOR: enter...\n"));
1771 DBGPRINTF9(("ANDOR: t=%p\n", t));
1774 while ((c = yylex(0)) == LOGAND || c == LOGOR) {
1775 p = pipeline(CONTIN);
1777 DBGPRINTF8(("ANDOR: error!\n"));
1781 t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
1787 DBGPRINTF7(("ANDOR: returning t=%p\n", t));
1791 static struct op *c_list(void)
1796 DBGPRINTF7(("C_LIST: enter...\n"));
1803 t = block(TASYNC, t, NOBLOCK, NOWORDS);
1805 while ((c = yylex(0)) == ';' || c == '&'
1806 || (multiline && c == '\n')) {
1814 p = block(TASYNC, p, NOBLOCK, NOWORDS);
1822 DBGPRINTF7(("C_LIST: returning t=%p\n", t));
1826 static int synio(int cf)
1832 DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
1835 if (c != '<' && c != '>') {
1842 iop = io(iounit, i, yylval.cp);
1846 markhere(yylval.cp, iop);
1848 DBGPRINTF7(("SYNIO: returning 1\n"));
1852 static void musthave(int c, int cf)
1854 peeksym = yylex(cf);
1856 DBGPRINTF7(("MUSTHAVE: error!\n"));
1863 static struct op *simple(void)
1869 switch (peeksym = yylex(0)) {
1890 static struct op *nested(int type, int mark)
1894 DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
1900 return block(type, t, NOBLOCK, NOWORDS);
1903 static struct op *command(int cf)
1906 struct wdblock *iosave;
1909 DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
1935 t = nested(TPAREN, ')');
1939 t = nested(TBRACE, '}');
1949 t->words = wordlist();
1951 if (c != '\n' && c != ';')
1953 t->left = dogroup(0);
1961 t->type = c == WHILE ? TWHILE : TUNTIL;
1963 t->right = dogroup(1);
1975 musthave(IN, CONTIN);
1978 t->left = caselist();
1989 t->right = thenpart();
1998 musthave(WORD, 0); /* gets name of file */
1999 DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
2001 word(yylval.cp); /* add word to wdlist */
2002 word(NOWORD); /* terminate wdlist */
2003 t->words = copyw(); /* dup wdlist */
2013 DBGPRINTF(("COMMAND: returning %p\n", t));
2018 static struct op *dowholefile(int type, int mark)
2022 DBGPRINTF(("DOWHOLEFILE: enter, type=%d, mark=%d\n", type, mark));
2027 t = block(type, t, NOBLOCK, NOWORDS);
2028 DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
2032 static struct op *dogroup(int onlydone)
2038 if (c == DONE && onlydone)
2047 static struct op *thenpart(void)
2060 if (t->left == NULL)
2062 t->right = elsepart();
2066 static struct op *elsepart(void)
2071 switch (c = yylex(0)) {
2082 t->right = thenpart();
2091 static struct op *caselist(void)
2096 while ((peeksym = yylex(CONTIN)) != ESAC) {
2097 DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
2098 t = list(t, casepart());
2101 DBGPRINTF(("CASELIST, returning t=%p\n", t));
2105 static struct op *casepart(void)
2109 DBGPRINTF7(("CASEPART: enter...\n"));
2113 t->words = pattern();
2116 peeksym = yylex(CONTIN);
2117 if (peeksym != ESAC)
2118 musthave(BREAK, CONTIN);
2120 DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
2125 static char **pattern(void)
2142 static char **wordlist(void)
2152 while ((c = yylex(0)) == WORD)
2160 * supporting functions
2162 static struct op *list(struct op *t1, struct op *t2)
2164 DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
2171 return block(TLIST, t1, t2, NOWORDS);
2174 static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
2178 DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
2186 DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1,
2192 /* See if given string is a shell multiline (FOR, IF, etc) */
2193 static int rlookup(char *n)
2195 const struct res *rp;
2197 DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
2199 for (rp = restab; rp->r_name; rp++)
2200 if (strcmp(rp->r_name, n) == 0) {
2201 DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
2202 return rp->r_val; /* Return numeric code for shell multiline */
2205 DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
2206 return 0; /* Not a shell multiline */
2209 static struct op *newtp(void)
2213 t = (struct op *) tree(sizeof(*t));
2221 DBGPRINTF3(("NEWTP: allocated %p\n", t));
2226 static struct op *namelist(struct op *t)
2229 DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
2230 T_CMD_NAMES[t->type], iolist));
2233 iolist = addword((char *) NULL, iolist);
2234 t->ioact = copyio();
2238 if (t->type != TCOM) {
2239 if (t->type != TPAREN && t->ioact != NULL) {
2240 t = block(TPAREN, t, NOBLOCK, NOWORDS);
2241 t->ioact = t->left->ioact;
2242 t->left->ioact = NULL;
2253 static char **copyw(void)
2257 wd = getwords(wdlist);
2262 static void word(char *cp)
2264 wdlist = addword(cp, wdlist);
2267 static struct ioword **copyio(void)
2269 struct ioword **iop;
2271 iop = (struct ioword **) getwords(iolist);
2276 static struct ioword *io(int u, int f, char *cp)
2280 iop = (struct ioword *) tree(sizeof(*iop));
2284 iolist = addword((char *) iop, iolist);
2288 static void zzerr(void)
2290 yyerror("syntax error");
2293 static void yyerror(char *s)
2296 if (interactive && e.iop <= iostack) {
2298 while (eofc() == 0 && yylex(0) != '\n');
2304 static int yylex(int cf)
2324 line[LINELIM - 1] = '\0';
2327 while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
2332 if (any(c, "0123456789")) {
2335 if (c1 == '<' || c1 == '>') {
2344 case '#': /* Comment, skip to next newline or End-of-string */
2345 while ((c = my_getc(0)) != '\0' && c != '\n');
2350 DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
2354 DBGPRINTF9(("YYLEX: found $\n"));
2358 c = collect(c, '}');
2377 /* If more chars process them, else return NULL char */
2395 if (multiline || cf & CONTIN) {
2396 if (interactive && e.iop <= iostack) {
2397 #if ENABLE_FEATURE_EDITING
2398 current_prompt = cprompt->value;
2400 prs(cprompt->value);
2417 while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
2418 if (e.linep >= elinep)
2419 err("word too long");
2426 if (any(c, "\"'`$"))
2439 yylval.cp = strsave(line, areanum);
2444 static int collect(int c, int c1)
2448 DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
2451 while ((c = my_getc(c1)) != c1) {
2460 if (interactive && c == '\n' && e.iop <= iostack) {
2461 #if ENABLE_FEATURE_EDITING
2462 current_prompt = cprompt->value;
2464 prs(cprompt->value);
2472 DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
2477 /* "multiline commands" helper func */
2478 /* see if next 2 chars form a shell multiline */
2479 static int dual(int c)
2484 DBGPRINTF8(("DUAL: enter, c=%d\n", c));
2486 *cp++ = c; /* c is the given "peek" char */
2487 *cp++ = my_getc(0); /* get next char of input */
2488 *cp = '\0'; /* add EOS marker */
2490 c = rlookup(s); /* see if 2 chars form a shell multiline */
2492 unget(*--cp); /* String is not a shell multiline, put peek char back */
2494 return c; /* String is multiline, return numeric multiline (restab) code */
2497 static void diag(int ec)
2501 DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
2504 if (c == '>' || c == '<') {
2507 yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
2510 yylval.i = (ec == '>' ? IOWRITE : IOREAD);
2511 if (c != '&' || yylval.i == IOHERE)
2517 static char *tree(unsigned size)
2523 DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
2524 prs("command line too complicated\n");
2534 /* -------- exec.c -------- */
2541 static int execute(struct op *t, int *pin, int *pout, int act)
2544 volatile int i, rv, a;
2545 char *cp, **wp, **wp2;
2547 struct op *outtree_save;
2551 /* Avoid longjmp clobbering */
2556 DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
2560 DBGPRINTF(("EXECUTE: t=%p, t->type=%d (%s), t->words is %s\n", t,
2561 t->type, T_CMD_NAMES[t->type],
2562 ((t->words == NULL) ? "NULL" : t->words[0])));
2566 wp = (wp2 = t->words) != NULL
2567 ? eval(wp2, t->type == TCOM ? DOALL : DOALL & ~DOKEY)
2572 DBGPRINTF3(("EXECUTE: TDOT\n"));
2574 outtree_save = outtree;
2576 newfile(evalstr(t->words[0], DOALL));
2578 t->left = dowholefile(TLIST, 0);
2581 outtree = outtree_save;
2584 rv = execute(t->left, pin, pout, 0);
2586 rv = execute(t->right, pin, pout, 0);
2590 rv = execute(t->left, pin, pout, 0);
2595 rv = forkexec(t, pin, pout, act, wp);
2606 pv[0] = remap(pv[0]);
2607 pv[1] = remap(pv[1]);
2608 (void) execute(t->left, pin, pv, 0);
2609 rv = execute(t->right, pv, pout, 0);
2614 (void) execute(t->left, pin, pout, 0);
2615 rv = execute(t->right, pin, pout, 0);
2620 int hinteractive = interactive;
2622 DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
2625 if (i == 0) { /* child */
2626 signal(SIGINT, SIG_IGN);
2627 signal(SIGQUIT, SIG_IGN);
2629 signal(SIGTERM, SIG_DFL);
2633 open(bb_dev_null, 0);
2635 _exit(execute(t->left, pin, pout, FEXEC));
2637 interactive = hinteractive;
2639 setval(lookup("!"), putn(i));
2654 rv = execute(t->left, pin, pout, 0);
2656 if (t1 != NULL && (rv == 0) == (t->type == TAND))
2657 rv = execute(t1, pin, pout, 0);
2668 while (*wp++ != NULL);
2670 vp = lookup(t->str);
2671 while (setjmp(bc.brkpt))
2675 for (t1 = t->left; i-- && *wp != NULL;) {
2677 rv = execute(t1, pin, pout, 0);
2679 brklist = brklist->nextlev;
2684 while (setjmp(bc.brkpt))
2689 while ((execute(t1, pin, pout, 0) == 0) == (t->type == TWHILE))
2690 rv = execute(t->right, pin, pout, 0);
2691 brklist = brklist->nextlev;
2696 if (t->right != NULL) {
2697 rv = !execute(t->left, pin, pout, 0) ?
2698 execute(t->right->left, pin, pout, 0) :
2699 execute(t->right->right, pin, pout, 0);
2704 cp = evalstr(t->str, DOSUB | DOTRIM);
2708 DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
2709 ((t->str == NULL) ? "NULL" : t->str),
2710 ((cp == NULL) ? "NULL" : cp)));
2712 t1 = findcase(t->left, cp);
2714 DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
2715 rv = execute(t1, pin, pout, 0);
2716 DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
2725 if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
2733 rv = execute(t1, pin, pout, 0);
2746 if (interactive && intr) {
2757 DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
2762 forkexec(struct op *t, int *pin, int *pout, int act, char **wp)
2766 builtin_func_ptr shcom = NULL;
2769 struct ioword **iopp;
2779 struct brkcon *hbrklist;
2783 /* Avoid longjmp clobbering */
2793 DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, act %d\n", t, pin,
2795 DBGPRINTF7(("FORKEXEC: t->words is %s\n",
2796 ((t->words == NULL) ? "NULL" : t->words[0])));
2800 rv = -1; /* system-detected error */
2801 if (t->type == TCOM) {
2802 while ((cp = *wp++) != NULL);
2805 /* strip all initial assignments */
2806 /* not correct wrt PATH=yyy command etc */
2808 DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
2810 echo(cp ? wp : owp);
2813 if (cp == NULL && t->ioact == NULL) {
2814 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2816 DBGPRINTF(("FORKEXEC: returning setstatus()\n"));
2817 return setstatus(0);
2820 shcom = inbuilt(cp);
2827 DBGPRINTF(("FORKEXEC: shcom %p, f&FEXEC 0x%x, owp %p\n", shcom,
2830 if (shcom == NULL && (f & FEXEC) == 0) {
2831 /* Save values in case the child process alters them */
2835 hinteractive = interactive;
2840 DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
2845 DBGPRINTF(("FORKEXEC: ERROR, cannot vfork()!\n"));
2849 if (newpid > 0) { /* Parent */
2851 /* Restore values */
2855 interactive = hinteractive;
2868 return (pout == NULL ? setstatus(waitfor(newpid, 0)) : 0);
2871 /* Must be the child process, pid should be 0 */
2872 DBGPRINTF(("FORKEXEC: child process, shcom=%p\n", shcom));
2875 signal(SIGINT, SIG_IGN);
2876 signal(SIGQUIT, SIG_IGN);
2887 while ((cp = *owp++) != NULL && assign(cp, COPYV))
2892 if ((pin != NULL || pout != NULL) && shcom != NULL && shcom != doexec) {
2893 err("piping to/from shell builtins not yet done");
2911 if (shcom != NULL && shcom != doexec) {
2913 err(": cannot redirect shell command");
2919 if (iosetup(*iopp++, pin != NULL, pout != NULL)) {
2927 i = setstatus((*shcom) (t));
2930 DBGPRINTF(("FORKEXEC: returning i=%d\n", i));
2934 /* should use FIOCEXCL */
2935 for (i = FDBASE; i < NOFILE; i++)
2938 signal(SIGINT, SIG_DFL);
2939 signal(SIGQUIT, SIG_DFL);
2942 if (t->type == TPAREN)
2943 _exit(execute(t->left, NOPIPE, NOPIPE, FEXEC));
2947 cp = rexecve(wp[0], wp, makenv(0, NULL));
2954 DBGPRINTF(("FORKEXEC: calling leave(), pid=%d\n", newpid));
2962 * 0< 1> are ignored as required
2965 static int iosetup(struct ioword *iop, int pipein, int pipeout)
2968 char *cp = NULL, *msg;
2970 DBGPRINTF(("IOSETUP: iop %p, pipein %i, pipeout %i\n", iop,
2973 if (iop->io_unit == IODEFAULT) /* take default */
2974 iop->io_unit = iop->io_flag & (IOREAD | IOHERE) ? 0 : 1;
2976 if (pipein && iop->io_unit == 0)
2979 if (pipeout && iop->io_unit == 1)
2982 msg = iop->io_flag & (IOREAD | IOHERE) ? "open" : "create";
2983 if ((iop->io_flag & IOHERE) == 0) {
2984 cp = iop->io_name; /* huh?? */
2985 cp = evalstr(cp, DOSUB | DOTRIM);
2990 if (iop->io_flag & IODUP) {
2991 if (cp[1] || (!isdigit(*cp) && *cp != '-')) {
2993 err(": illegal >& argument");
2997 iop->io_flag = IOCLOSE;
2998 iop->io_flag &= ~(IOREAD | IOWRITE);
3000 switch (iop->io_flag) {
3006 case IOHERE | IOXHERE:
3007 u = herein(iop->io_name, iop->io_flag & IOXHERE);
3011 case IOWRITE | IOCAT:
3014 lseek(u, (long) 0, SEEK_END);
3018 u = creat(cp, 0666);
3022 u = dup2(*cp - '0', iop->io_unit);
3026 close(iop->io_unit);
3035 if (u != iop->io_unit) {
3036 dup2(u, iop->io_unit);
3042 static void echo(char **wp)
3047 for (i = 0; wp[i]; i++) {
3055 static struct op **find1case(struct op *t, char *w)
3062 DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
3066 DBGPRINTF3(("FIND1CASE: enter, t->type=%d (%s)\n", t->type,
3067 T_CMD_NAMES[t->type]));
3069 if (t->type == TLIST) {
3070 tp = find1case(t->left, w);
3072 DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
3075 t1 = t->right; /* TPAT */
3079 for (wp = t1->words; *wp;) {
3080 cp = evalstr(*wp++, DOSUB);
3081 if (cp && gmatch(w, cp)) {
3082 DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
3088 DBGPRINTF(("FIND1CASE: returning NULL\n"));
3092 static struct op *findcase(struct op *t, char *w)
3096 tp = find1case(t, w);
3097 return tp != NULL ? *tp : NULL;
3101 * Enter a new loop level (marked for break/continue).
3103 static void brkset(struct brkcon *bc)
3105 bc->nextlev = brklist;
3110 * Wait for the last process created.
3111 * Print a message for each process found
3112 * that was killed by a signal.
3113 * Ignore interrupt signals while waiting
3114 * unless `canintr' is true.
3116 static int waitfor(int lastpid, int canintr)
3120 int oheedint = heedint;
3127 if (errno != EINTR || canintr)
3133 if (signame[rv] != NULL) {
3134 if (pid != lastpid) {
3141 if (pid != lastpid) {
3150 prs(" - core dumped");
3151 if (rv >= NSIGNAL || signame[rv])
3157 } while (pid != lastpid);
3172 static int setstatus(int s)
3175 setval(lookup("?"), putn(s));
3180 * PATH-searching interface to execve.
3181 * If getenv("PATH") were kept up-to-date,
3182 * execvp might be used.
3184 static char *rexecve(char *c, char **v, char **envp)
3188 int eacces = 0, asis = 0;
3191 if (ENABLE_FEATURE_SH_STANDALONE_SHELL) {
3193 if (find_applet_by_name(name)) {
3194 /* We have to exec here since we vforked. Running
3195 * run_applet_by_name() won't work and bad things
3197 execve(CONFIG_BUSYBOX_EXEC_PATH, v, envp);
3201 DBGPRINTF(("REXECVE: c=%p, v=%p, envp=%p\n", c, v, envp));
3203 sp = any('/', c) ? "" : path->value;
3205 while (asis || *sp != '\0') {
3208 for (; *sp != '\0'; tp++) {
3211 asis = (*sp == '\0');
3217 for (i = 0; (*tp++ = c[i++]) != '\0';);
3219 DBGPRINTF3(("REXECVE: e.linep is %s\n", e.linep));
3221 execve(e.linep, v, envp);
3228 execve(DEFAULT_SHELL, v, envp);
3233 return (char *) bb_msg_memory_exhausted;
3236 return "argument list too long";
3243 return errno == ENOENT ? "not found" : "cannot execute";
3247 * Run the command produced by generator `f'
3248 * applied to stream `arg'.
3250 static int run(struct ioarg *argp, int (*f) (struct ioarg *))
3253 struct wdblock *swdlist;
3254 struct wdblock *siolist;
3260 /* Avoid longjmp clobbering */
3264 DBGPRINTF(("RUN: enter, areanum %d, outtree %p, failpt %p\n",
3265 areanum, outtree, failpt));
3275 if (newenv(setjmp(errpt)) == 0) {
3282 if (setjmp(failpt) == 0 && yyparse() == 0)
3283 rv = execute(outtree, NOPIPE, NOPIPE, 0);
3286 DBGPRINTF(("RUN: error from newenv()!\n"));
3293 freearea(areanum--);
3298 /* -------- do.c -------- */
3301 * built-in commands: doX
3304 static int dohelp(struct op *t)
3307 const struct builtincmd *x;
3309 puts("\nBuilt-in commands:\n"
3310 "-------------------");
3312 for (col = 0, x = builtincmds; x->builtinfunc != NULL; x++) {
3315 col += printf("%s%s", ((col == 0) ? "\t" : " "), x->name);
3321 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
3324 const struct BB_applet *applet;
3326 for (i = 0, applet = applets; i < NUM_APPLETS; applet++, i++) {
3330 col += printf("%s%s", ((col == 0) ? "\t" : " "), applet->name);
3339 return EXIT_SUCCESS;
3344 static int dolabel(struct op *t)
3349 static int dochdir(struct op *t)
3355 cp = homedir->value;
3357 er = ": no home directory";
3358 } else if (chdir(cp) < 0)
3359 er = ": bad directory";
3362 prs(cp != NULL ? cp : "cd");
3367 static int doshift(struct op *t)
3371 n = t->words[1] ? getn(t->words[1]) : 1;
3373 err("nothing to shift");
3379 setval(lookup("#"), putn(dolc));
3384 * execute login and newgrp directly
3386 static int dologin(struct op *t)
3391 signal(SIGINT, SIG_DFL);
3392 signal(SIGQUIT, SIG_DFL);
3394 cp = rexecve(t->words[0], t->words, makenv(0, NULL));
3401 static int doumask(struct op *t)
3410 for (n = 3 * 4; (n -= 3) >= 0;)
3411 putc('0' + ((i >> n) & 07), stderr);
3414 /* huh??? '8','9' are not allowed! */
3415 for (n = 0; *cp >= '0' && *cp <= '9'; cp++)
3416 n = n * 8 + (*cp - '0');
3422 static int doexec(struct op *t)
3429 for (i = 0; (t->words[i] = t->words[i + 1]) != NULL; i++);
3435 if (setjmp(failpt) == 0)
3436 execute(t, NOPIPE, NOPIPE, FEXEC);
3442 static int dodot(struct op *t)
3449 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)));
3453 DBGPRINTF(("DODOT: bad args, ret 0\n"));
3456 DBGPRINTF(("DODOT: cp is %s\n", cp));
3458 sp = any('/', cp) ? ":" : path->value;
3460 DBGPRINTF(("DODOT: sp is %s, e.linep is %s\n",
3461 ((sp == NULL) ? "NULL" : sp),
3462 ((e.linep == NULL) ? "NULL" : e.linep)));
3466 while (*sp && (*tp = *sp++) != ':')
3471 for (i = 0; (*tp++ = cp[i++]) != '\0';);
3474 i = open(e.linep, 0);
3478 DBGPRINTF(("DODOT: remap=%d, exstat=%d, e.iofd %d, i %d, e.linep is %s\n", maltmp, exstat, e.iofd, i, e.linep));
3480 next(maltmp); /* Basically a PUSHIO */
3482 DBGPRINTF(("DODOT: returning exstat=%d\n", exstat));
3494 static int dowait(struct op *t)
3506 setstatus(waitfor(i, 1));
3510 static int doread(struct op *t)
3516 if (t->words[1] == NULL) {
3517 err("Usage: read name ...");
3520 for (wp = t->words + 1; *wp; wp++) {
3521 for (cp = e.linep; !nl && cp < elinep - 1; cp++) {
3522 nb = read(0, cp, sizeof(*cp));
3523 if (nb != sizeof(*cp))
3526 if (nl || (wp[1] && any(*cp, ifs->value)))
3532 setval(lookup(*wp), e.linep);
3537 static int doeval(struct op *t)
3539 return RUN(awordlist, t->words + 1, wdchar);
3542 static int dotrap(struct op *t)
3547 if (t->words[1] == NULL) {
3548 for (i = 0; i <= _NSIG; i++)
3557 resetsig = isdigit(*t->words[1]);
3558 for (i = resetsig ? 1 : 2; t->words[i] != NULL; ++i) {
3559 n = getsig(t->words[i]);
3563 if (*t->words[1] != '\0') {
3564 trap[n] = strsave(t->words[1], 0);
3573 setsig(n, n == SIGQUIT ? SIG_IGN : SIG_DFL);
3581 static int getsig(char *s)
3586 if (n < 0 || n > _NSIG) {
3587 err("trap: bad signal number");
3593 static void setsig(int n, sighandler_t f)
3597 if (signal(n, SIG_IGN) != SIG_IGN || ourtrap[n]) {
3603 static int getn(char *as)
3614 for (n = 0; isdigit(*s); s++)
3615 n = (n * 10) + (*s - '0');
3618 err(": bad number");
3623 static int dobreak(struct op *t)
3625 return brkcontin(t->words[1], 1);
3628 static int docontinue(struct op *t)
3630 return brkcontin(t->words[1], 0);
3633 static int brkcontin(char *cp, int val)
3638 nl = cp == NULL ? 1 : getn(cp);
3645 brklist = bc->nextlev;
3648 err("bad break/continue level");
3652 longjmp(bc->brkpt, 1);
3656 static int doexit(struct op *t)
3663 setstatus(getn(cp));
3665 DBGPRINTF(("DOEXIT: calling leave(), t=%p\n", t));
3672 static int doexport(struct op *t)
3674 rdexp(t->words + 1, export, EXPORT);
3678 static int doreadonly(struct op *t)
3680 rdexp(t->words + 1, ronly, RONLY);
3684 static void rdexp(char **wp, void (*f) (struct var *), int key)
3686 DBGPRINTF6(("RDEXP: enter, wp=%p, func=%p, key=%d\n", wp, f, key));
3687 DBGPRINTF6(("RDEXP: *wp=%s\n", *wp));
3690 for (; *wp != NULL; wp++) {
3691 if (isassign(*wp)) {
3695 for (cp = *wp; *cp != '='; cp++);
3707 static void badid(char *s)
3710 err(": bad identifier");
3713 static int doset(struct op *t)
3721 for (vp = vlist; vp; vp = vp->next)
3722 varput(vp->name, 1);
3726 /* bad: t->words++; */
3727 for (n = 0; (t->words[n] = t->words[n + 1]) != NULL; n++);
3729 flag['x'] = flag['v'] = 0;
3739 if (*cp >= 'a' && *cp <= 'z')
3748 t->words[0] = dolv[0];
3749 for (n = 1; t->words[n]; n++)
3750 setarea((char *) t->words[n], 0);
3753 setval(lookup("#"), putn(dolc));
3754 setarea((char *) (dolv - 1), 0);
3759 static void varput(char *s, int out)
3761 if (isalnum(*s) || *s == '_') {
3762 write(out, s, strlen(s));
3763 write(out, "\n", 1);
3769 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
3770 * This file contains code for the times builtin.
3772 static int dotimes(struct op *t)
3775 long clk_tck = sysconf(_SC_CLK_TCK);
3778 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
3779 (int) (buf.tms_utime / clk_tck / 60),
3780 ((double) buf.tms_utime) / clk_tck,
3781 (int) (buf.tms_stime / clk_tck / 60),
3782 ((double) buf.tms_stime) / clk_tck,
3783 (int) (buf.tms_cutime / clk_tck / 60),
3784 ((double) buf.tms_cutime) / clk_tck,
3785 (int) (buf.tms_cstime / clk_tck / 60),
3786 ((double) buf.tms_cstime) / clk_tck);
3791 static builtin_func_ptr inbuilt(char *s) {
3792 const struct builtincmd *bp;
3794 for (bp = builtincmds; bp->name != NULL; bp++)
3795 if (strcmp(bp->name, s) == 0)
3796 return bp->builtinfunc;
3801 /* -------- eval.c -------- */
3806 * blank interpretation
3811 static char **eval(char **ap, int f)
3819 /* Avoid longjmp clobbering */
3824 DBGPRINTF4(("EVAL: enter, f=%d\n", f));
3830 if (newenv(setjmp(errpt)) == 0) {
3831 while (*ap && isassign(*ap))
3832 expand(*ap++, &wb, f & ~DOGLOB);
3834 for (wf = ap; *wf; wf++) {
3836 expand(*wf, &wb, f & ~DOGLOB);
3839 for (wb = addword((char *) 0, wb); *ap; ap++) {
3840 if (!flag['k'] || !isassign(*ap))
3841 expand(*ap, &wb, f & ~DOKEY);
3843 wb = addword((char *) 0, wb);
3849 return gflg ? (char **) NULL : wp;
3853 * Make the exported environment from the exported
3854 * names in the dictionary. Keyword assignments
3855 * will already have been done.
3857 static char **makenv(int all, struct wdblock *wb)
3861 DBGPRINTF5(("MAKENV: enter, all=%d\n", all));
3863 for (vp = vlist; vp; vp = vp->next)
3864 if (all || vp->status & EXPORT)
3865 wb = addword(vp->name, wb);
3866 wb = addword((char *) 0, wb);
3867 return getwords(wb);
3870 static char *evalstr(char *cp, int f)
3874 DBGPRINTF6(("EVALSTR: enter, cp=%p, f=%d\n", cp, f));
3877 if (expand(cp, &wb, f)) {
3878 if (wb == NULL || wb->w_nword == 0
3879 || (cp = wb->w_words[0]) == NULL)
3887 static int expand(char *cp, struct wdblock **wbp, int f)
3892 /* Avoid longjmp clobbering */
3896 DBGPRINTF3(("EXPAND: enter, f=%d\n", f));
3903 if (!anys("$`'\"", cp) &&
3904 !anys(ifs->value, cp) && ((f & DOGLOB) == 0 || !anys("[*?", cp))) {
3905 cp = strsave(cp, areanum);
3908 *wbp = addword(cp, *wbp);
3912 if (newenv(setjmp(errpt)) == 0) {
3913 PUSHIO(aword, cp, strchar);
3915 while ((cp = blank(f)) && gflg == 0) {
3917 cp = strsave(cp, areanum);
3918 if ((f & DOGLOB) == 0) {
3921 *wbp = addword(cp, *wbp);
3923 *wbp = glob(cp, *wbp);
3932 * Blank interpretation and quoting
3934 static char *blank(int f)
3938 int scanequals, foundequals;
3940 DBGPRINTF3(("BLANK: enter, f=%d\n", f));
3943 scanequals = f & DOKEY;
3947 c = subgetc('"', foundequals);
3956 if (f & DOBLANK && any(c, ifs->value))
3965 for (c1 = c; (c = subgetc(c1, 1)) != c1;) {
3968 if (c == '\'' || !any(c, "$`\""))
3975 if (!isalpha(c) && c != '_')
3978 c = subgetc('"', foundequals);
3980 f & (DOBLANK && any(c, ifs->value)) ||
3981 (!INSUB() && any(c, "\"'"))) {
3992 } else if (!isalnum(c) && c != '_')
4002 * Get characters, substituting for ` and $
4004 static int subgetc(char ec, int quoted)
4008 DBGPRINTF3(("SUBGETC: enter, quoted=%d\n", quoted));
4012 if (!INSUB() && ec != '\'') {
4014 if (grave(quoted) == 0)
4016 e.iop->task = XGRAVE;
4022 e.iop->task = XDOLL;
4031 * Prepare to generate the string returned by ${} substitution.
4033 static int dollar(int quoted)
4038 char *s, c, *cp = NULL;
4041 DBGPRINTF3(("DOLLAR: enter, quoted=%d\n", quoted));
4047 if (isalpha(c) || c == '_') {
4048 while ((c = readc()) != 0 && (isalnum(c) || c == '_'))
4049 if (e.linep < elinep)
4056 otask = e.iop->task;
4058 e.iop->task = XOTHER;
4059 while ((c = subgetc('"', 0)) != 0 && c != '}' && c != '\n')
4060 if (e.linep < elinep)
4063 e.iop->task = otask;
4070 if (e.linep >= elinep) {
4071 err("string in ${} too long");
4077 for (cp = s + 1; *cp; cp++)
4078 if (any(*cp, "=-+?")) {
4083 if (s[1] == 0 && (*s == '*' || *s == '@')) {
4085 /* currently this does not distinguish $* and $@ */
4086 /* should check dollar */
4088 PUSHIO(awordlist, dolv + 1, dolchar);
4090 } else { /* trap the nasty ${=} */
4101 err("cannot use ${...=...} with $n");
4110 dolp = strsave(cp, areanum);
4115 prs("missing value for ");
4122 } else if (c == '+')
4123 dolp = strsave(cp, areanum);
4124 if (flag['u'] && dolp == null) {
4125 prs("unset variable: ");
4130 PUSHIO(aword, dolp, quoted ? qstrchar : strchar);
4135 * Run the command in `...` and read its output.
4138 static int grave(int quoted)
4144 static char child_cmd[LINELIM];
4150 char *argument_list[4];
4151 struct wdblock *wb = NULL;
4154 /* Avoid longjmp clobbering */
4158 for (cp = e.iop->argp->aword; *cp != '`'; cp++)
4160 err("no closing `");
4164 /* string copy with dollar expansion */
4165 src = e.iop->argp->aword;
4170 while ((*src != '`') && (count < LINELIM)) {
4175 if (*src == '$' && !ignore && !ignore_once) {
4177 char var_name[LINELIM];
4178 char alt_value[LINELIM];
4191 var_name[var_index++] = *src++;
4192 while (isalnum(*src) || *src=='_')
4193 var_name[var_index++] = *src++;
4194 var_name[var_index] = 0;
4207 err("unclosed ${\n");
4212 while (*src && (*src != '}')) {
4213 alt_value[alt_index++] = *src++;
4215 alt_value[alt_index] = 0;
4217 err("unclosed ${\n");
4224 if (isalpha(*var_name)) {
4225 /* let subshell handle it instead */
4227 char *namep = var_name;
4235 char *altp = alt_value;
4243 wb = addword(lookup(var_name)->name, wb);
4247 vp = lookup(var_name);
4248 if (vp->value != null)
4249 value = (operator == '+') ?
4250 alt_value : vp->value;
4251 else if (operator == '?') {
4254 } else if (alt_index && (operator != '+')) {
4256 if (operator == '=')
4261 while (*value && (count < LINELIM)) {
4274 if (openpipe(pf) < 0)
4277 while ((i = vfork()) == -1 && errno == EAGAIN);
4279 DBGPRINTF3(("GRAVE: i is %p\n", io));
4283 err((char *) bb_msg_memory_exhausted);
4287 waitpid(i, NULL, 0);
4288 e.iop->argp->aword = ++cp;
4290 PUSHIO(afile, remap(pf[0]),
4291 (int (*)(struct ioarg *)) ((quoted) ? qgravechar :
4295 /* allow trapped signals */
4296 /* XXX - Maybe this signal stuff should go as well? */
4297 for (j = 0; j <= _NSIG; j++)
4298 if (ourtrap[j] && signal(j, SIG_IGN) != SIG_IGN)
4304 argument_list[0] = (char *) DEFAULT_SHELL;
4305 argument_list[1] = "-c";
4306 argument_list[2] = child_cmd;
4307 argument_list[3] = 0;
4309 cp = rexecve(argument_list[0], argument_list, makenv(1, wb));
4310 prs(argument_list[0]);
4317 static char *unquote(char *as)
4328 /* -------- glob.c -------- */
4334 #define scopy(x) strsave((x), areanum)
4336 #define NDENT ((BLKSIZ+sizeof(struct dirent)-1)/sizeof(struct dirent))
4338 static struct wdblock *cl, *nl;
4339 static char spcl[] = "[?*";
4341 static struct wdblock *glob(char *cp, struct wdblock *wb)
4349 for (pp = cp; *pp; pp++)
4352 else if (!any(*pp & ~QUOTE, spcl))
4355 for (cl = addword(scopy(cp), NULL); anyspcl(cl); cl = nl) {
4356 nl = newword(cl->w_nword * 2);
4357 for (i = 0; i < cl->w_nword; i++) { /* for each argument */
4358 for (pp = cl->w_words[i]; *pp; pp++)
4359 if (any(*pp, spcl)) {
4360 globname(cl->w_words[i], pp);
4364 nl = addword(scopy(cl->w_words[i]), nl);
4366 for (i = 0; i < cl->w_nword; i++)
4367 DELETE(cl->w_words[i]);
4370 for (i = 0; i < cl->w_nword; i++)
4371 unquote(cl->w_words[i]);
4372 glob0((char *) cl->w_words, cl->w_nword, sizeof(char *), xstrcmp);
4374 for (i = 0; i < cl->w_nword; i++)
4375 wb = addword(cl->w_words[i], wb);
4380 wb = addword(unquote(cp), wb);
4384 static void globname(char *we, char *pp)
4387 char *name, *gp, *dp;
4391 char dname[NAME_MAX + 1];
4394 for (np = we; np != pp; pp--)
4397 for (dp = cp = space((int) (pp - np) + 3); np < pp;)
4401 for (gp = cp = space(strlen(pp) + 1); *np && *np != '/';)
4410 dname[NAME_MAX] = '\0';
4411 while ((de = readdir(dirp)) != NULL) {
4412 /* XXX Hmmm... What this could be? (abial) */
4414 if (ent[j].d_ino == 0)
4417 strncpy(dname, de->d_name, NAME_MAX);
4418 if (dname[0] == '.')
4421 for (k = 0; k < NAME_MAX; k++)
4422 if (any(dname[k], spcl))
4424 if (gmatch(dname, gp)) {
4425 name = generate(we, pp, dname, np);
4426 if (*np && !anys(np, spcl)) {
4427 if (stat(name, &dbuf)) {
4432 nl = addword(name, nl);
4441 * generate a pathname as below.
4442 * start..end1 / middle end
4443 * the slashes come for free
4445 static char *generate(char *start1, char *end1, char *middle, char *end)
4450 p = op = space((int)(end1 - start1) + strlen(middle) + strlen(end) + 2);
4451 for (xp = start1; xp != end1;)
4453 for (xp = middle; (*op++ = *xp++) != '\0';);
4455 for (xp = end; (*op++ = *xp++) != '\0';);
4459 static int anyspcl(struct wdblock *wb)
4465 for (i = 0; i < wb->w_nword; i++)
4466 if (anys(spcl, *wd++))
4471 static int xstrcmp(char *p1, char *p2)
4473 return strcmp(*(char **) p1, *(char **) p2);
4476 /* -------- word.c -------- */
4478 static struct wdblock *newword(int nw)
4482 wb = (struct wdblock *) space(sizeof(*wb) + nw * sizeof(char *));
4488 static struct wdblock *addword(char *wd, struct wdblock *wb)
4490 struct wdblock *wb2;
4494 wb = newword(NSTART);
4496 if (nw >= wb->w_bsize) {
4497 wb2 = newword(nw * 2);
4498 memcpy((char *) wb2->w_words, (char *) wb->w_words,
4499 nw * sizeof(char *));
4504 wb->w_words[wb->w_nword++] = wd;
4509 char **getwords(struct wdblock *wb)
4516 if (wb->w_nword == 0) {
4520 wd = (char **) space(nb = sizeof(*wd) * wb->w_nword);
4521 memcpy((char *) wd, (char *) wb->w_words, nb);
4522 DELETE(wb); /* perhaps should done by caller */
4526 static int (*func) (char *, char *);
4529 static void glob0(char *a0, unsigned a1, int a2, int (*a3) (char *, char *))
4533 glob1(a0, a0 + a1 * a2);
4536 static void glob1(char *base, char *lim)
4547 n = (int) (lim - base);
4550 n = v2 * (n / (2 * v2));
4551 hptr = lptr = base + n;
4556 c = (*func) (i, lptr);
4570 c = (*func) (hptr, j);
4594 if (lptr - base >= lim - hptr) {
4595 glob1(hptr + v2, lim);
4610 static void glob2(char *i, char *j)
4612 char *index1, *index2, c;
4620 *index1++ = *index2;
4625 static void glob3(char *i, char *j, char *k)
4627 char *index1, *index2, *index3;
4637 *index1++ = *index3;
4638 *index3++ = *index2;
4643 /* -------- io.c -------- */
4649 static int my_getc(int ec)
4653 if (e.linep > elinep) {
4654 while ((c = readc()) != '\n' && c);
4655 err("input line too long");
4660 if ((ec != '\'') && (ec != '`') && (e.iop->task != XGRAVE)) {
4663 if (c == '\n' && ec != '\"')
4671 static void unget(int c)
4673 if (e.iop >= e.iobase)
4677 static int eofc(void)
4679 return e.iop < e.iobase || (e.iop->peekc == 0 && e.iop->prev == 0);
4682 static int readc(void)
4686 RCPRINTF(("READC: e.iop %p, e.iobase %p\n", e.iop, e.iobase));
4688 for (; e.iop >= e.iobase; e.iop--) {
4689 RCPRINTF(("READC: e.iop %p, peekc 0x%x\n", e.iop, e.iop->peekc));
4695 if (e.iop->prev != 0) {
4696 c = (*e.iop->iofn)(e.iop->argp, e.iop);
4702 if (e.iop == iostack)
4707 if (e.iop->task == XIO && e.iop->prev != '\n') {
4709 if (e.iop == iostack)
4714 if (e.iop->task == XIO) {
4719 if (interactive && e.iop == iostack + 1) {
4720 #if ENABLE_FEATURE_EDITING
4721 current_prompt = prompt->value;
4729 if (e.iop >= iostack) {
4730 RCPRINTF(("READC: return 0, e.iop %p\n", e.iop));
4734 DBGPRINTF(("READC: leave()...\n"));
4741 static void ioecho(char c)
4744 write(2, &c, sizeof c);
4748 static void pushio(struct ioarg *argp, int (*fn) (struct ioarg *))
4750 DBGPRINTF(("PUSHIO: argp %p, argp->afid 0x%x, e.iop %p\n", argp,
4751 argp->afid, e.iop));
4753 /* Set env ptr for io source to next array spot and check for array overflow */
4754 if (++e.iop >= &iostack[NPUSH]) {
4756 err("Shell input nested too deeply");
4761 /* We did not overflow the NPUSH array spots so setup data structs */
4763 e.iop->iofn = (int (*)(struct ioarg *, struct io *)) fn; /* Store data source func ptr */
4765 if (argp->afid != AFID_NOBUF)
4769 e.iop->argp = ioargstack + (e.iop - iostack); /* MAL - index into stack */
4770 *e.iop->argp = *argp; /* copy data from temp area into stack spot */
4772 /* MAL - mainbuf is for 1st data source (command line?) and all nested use a single shared buffer? */
4774 if (e.iop == &iostack[0])
4775 e.iop->argp->afbuf = &mainbuf;
4777 e.iop->argp->afbuf = &sharedbuf;
4779 /* MAL - if not a termimal AND (commandline OR readable file) then give it a buffer id? */
4780 /* This line appears to be active when running scripts from command line */
4781 if ((isatty(e.iop->argp->afile) == 0)
4782 && (e.iop == &iostack[0]
4783 || lseek(e.iop->argp->afile, 0L, SEEK_CUR) != -1)) {
4784 if (++bufid == AFID_NOBUF) /* counter rollover check, AFID_NOBUF = 11111111 */
4785 bufid = AFID_ID; /* AFID_ID = 0 */
4787 e.iop->argp->afid = bufid; /* assign buffer id */
4790 DBGPRINTF(("PUSHIO: iostack %p, e.iop %p, afbuf %p\n",
4791 iostack, e.iop, e.iop->argp->afbuf));
4792 DBGPRINTF(("PUSHIO: mbuf %p, sbuf %p, bid %d, e.iop %p\n",
4793 &mainbuf, &sharedbuf, bufid, e.iop));
4797 e.iop->prev = ~'\n';
4802 if (fn == filechar || fn == linechar)
4804 else if (fn == (int (*)(struct ioarg *)) gravechar
4805 || fn == (int (*)(struct ioarg *)) qgravechar)
4806 e.iop->task = XGRAVE;
4808 e.iop->task = XOTHER;
4811 static struct io *setbase(struct io *ip)
4821 * Input generating functions
4825 * Produce the characters of a string, then a newline, then EOF.
4827 static int nlchar(struct ioarg *ap)
4831 if (ap->aword == NULL)
4842 * Given a list of words, produce the characters
4843 * in them, with a space after each word.
4845 static int wdchar(struct ioarg *ap)
4860 ap->awordlist = NULL;
4865 * Return the characters of a list of words,
4866 * producing a space between them.
4868 static int dolchar(struct ioarg *ap)
4872 wp = *ap->awordlist++;
4874 PUSHIO(aword, wp, *ap->awordlist == NULL ? strchar : xxchar);
4880 static int xxchar(struct ioarg *ap)
4884 if (ap->aword == NULL)
4895 * Produce the characters from a single word (string).
4897 static int strchar(struct ioarg *ap)
4899 if (ap->aword == NULL)
4901 return *ap->aword++;
4905 * Produce quoted characters from a single word (string).
4907 static int qstrchar(struct ioarg *ap)
4911 if (ap->aword == NULL)
4920 * Return the characters from a file.
4922 static int filechar(struct ioarg *ap)
4926 struct iobuf *bp = ap->afbuf;
4928 if (ap->afid != AFID_NOBUF) {
4929 i = (ap->afid != bp->id);
4930 if (i || bp->bufp == bp->ebufp) {
4932 lseek(ap->afile, ap->afpos, SEEK_SET);
4934 i = safe_read(ap->afile, bp->buf, sizeof(bp->buf));
4942 bp->ebufp = bp->bufp + i;
4946 return *bp->bufp++ & 0177;
4948 #if ENABLE_FEATURE_EDITING
4949 if (interactive && isatty(ap->afile)) {
4950 static char mycommand[BUFSIZ];
4951 static int position = 0, size = 0;
4953 while (size == 0 || position >= size) {
4954 read_line_input(current_prompt, mycommand, BUFSIZ, line_input_state);
4955 size = strlen(mycommand);
4958 c = mycommand[position];
4963 i = safe_read(ap->afile, &c, sizeof(c));
4964 return i == sizeof(c) ? (c & 0x7f) : (closef(ap->afile), 0);
4968 * Return the characters from a here temp file.
4970 static int herechar(struct ioarg *ap)
4974 if (read(ap->afile, &c, sizeof(c)) != sizeof(c)) {
4982 * Return the characters produced by a process (`...`).
4983 * Quote them if required, and remove any trailing newline characters.
4985 static int gravechar(struct ioarg *ap, struct io *iop)
4989 c = qgravechar(ap, iop) & ~QUOTE;
4995 static int qgravechar(struct ioarg *ap, struct io *iop)
4999 DBGPRINTF3(("QGRAVECHAR: enter, ap=%p, iop=%p\n", ap, iop));
5004 return '\n' | QUOTE;
5008 } else if ((c = filechar(ap)) == '\n') {
5010 while ((c = filechar(ap)) == '\n')
5018 return c != 0 ? c | QUOTE : 0;
5022 * Return a single command (usually the first line) from a file.
5024 static int linechar(struct ioarg *ap)
5032 ap->afile = -1; /* illegal value */
5038 static void prs(const char *s)
5041 write(2, s, strlen(s));
5044 static void prn(unsigned u)
5049 static void closef(int i)
5055 static void closeall(void)
5059 for (u = NUFILE; u < NOFILE;)
5065 * remap fd into Shell's fd space
5067 static int remap(int fd)
5073 DBGPRINTF(("REMAP: fd=%d, e.iofd=%d\n", fd, e.iofd));
5076 for (i = 0; i < NOFILE; i++)
5083 } while (fd >= 0 && fd < e.iofd);
5085 for (i = 0; i < NOFILE; i++)
5090 err("too many files open in shell");
5096 static int openpipe(int *pv)
5102 err("can't create pipe - try again");
5106 static void closepipe(int *pv)
5114 /* -------- here.c -------- */
5120 static void markhere(char *s, struct ioword *iop)
5122 struct here *h, *lh;
5124 DBGPRINTF7(("MARKHERE: enter, s=%p\n", s));
5126 h = (struct here *) space(sizeof(struct here));
5130 h->h_tag = evalstr(s, DOSUB);
5140 for (lh = inhere; lh != NULL; lh = lh->h_next) {
5141 if (lh->h_next == 0) {
5147 iop->io_flag |= IOHERE | IOXHERE;
5148 for (s = h->h_tag; *s; s++) {
5150 iop->io_flag &= ~IOXHERE;
5154 h->h_dosub = iop->io_flag & IOXHERE;
5157 static void gethere(void)
5159 struct here *h, *hp;
5161 DBGPRINTF7(("GETHERE: enter...\n"));
5163 /* Scan here files first leaving inhere list in place */
5164 for (hp = h = inhere; h != NULL; hp = h, h = h->h_next)
5165 readhere(&h->h_iop->io_name, h->h_tag, h->h_dosub ? 0 : '\'');
5167 /* Make inhere list active - keep list intact for scraphere */
5169 hp->h_next = acthere;
5175 static void readhere(char **name, char *s, int ec)
5178 char tname[30] = ".msh_XXXXXX";
5181 char myline[LINELIM + 1];
5184 DBGPRINTF7(("READHERE: enter, name=%p, s=%p\n", name, s));
5186 tf = mkstemp(tname);
5190 *name = strsave(tname, areanum);
5192 if (newenv(setjmp(errpt)) != 0)
5195 pushio(e.iop->argp, (int (*)(struct ioarg *)) e.iop->iofn);
5198 if (interactive && e.iop <= iostack) {
5199 #if ENABLE_FEATURE_EDITING
5200 current_prompt = cprompt->value;
5202 prs(cprompt->value);
5206 while ((c = my_getc(ec)) != '\n' && c) {
5209 if (thenext >= &myline[LINELIM]) {
5216 if (strcmp(s, myline) == 0 || c == 0)
5219 write(tf, myline, (int) (thenext - myline));
5222 prs("here document `");
5232 * open here temp file.
5233 * if unquoted here, expand here temp file into second temp file.
5235 static int herein(char *hname, int xdoll)
5241 /* Avoid longjmp clobbering */
5247 DBGPRINTF7(("HEREIN: hname is %s, xdoll=%d\n", hname, xdoll));
5249 hf = open(hname, 0);
5255 char tname[30] = ".msh_XXXXXX";
5258 tf = mkstemp(tname);
5262 if (newenv(setjmp(errpt)) == 0) {
5263 PUSHIO(afile, hf, herechar);
5265 while ((c = subgetc(0, 0)) != 0) {
5267 write(tf, &c, sizeof c);
5273 tf = open(tname, 0);
5280 static void scraphere(void)
5284 DBGPRINTF7(("SCRAPHERE: enter...\n"));
5286 for (h = inhere; h != NULL; h = h->h_next) {
5287 if (h->h_iop && h->h_iop->io_name)
5288 unlink(h->h_iop->io_name);
5293 /* unlink here temp files before a freearea(area) */
5294 static void freehere(int area)
5296 struct here *h, *hl;
5298 DBGPRINTF6(("FREEHERE: enter, area=%d\n", area));
5301 for (h = acthere; h != NULL; h = h->h_next)
5302 if (getarea((char *) h) >= area) {
5303 if (h->h_iop->io_name != NULL)
5304 unlink(h->h_iop->io_name);
5306 acthere = h->h_next;
5308 hl->h_next = h->h_next;
5315 * Copyright (c) 1987,1997, Prentice Hall
5316 * All rights reserved.
5318 * Redistribution and use of the MINIX operating system in source and
5319 * binary forms, with or without modification, are permitted provided
5320 * that the following conditions are met:
5322 * Redistributions of source code must retain the above copyright
5323 * notice, this list of conditions and the following disclaimer.
5325 * Redistributions in binary form must reproduce the above
5326 * copyright notice, this list of conditions and the following
5327 * disclaimer in the documentation and/or other materials provided
5328 * with the distribution.
5330 * Neither the name of Prentice Hall nor the names of the software
5331 * authors or contributors may be used to endorse or promote
5332 * products derived from this software without specific prior
5333 * written permission.
5335 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
5336 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
5337 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5338 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5339 * IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
5340 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
5341 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
5342 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
5343 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
5344 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
5345 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
5346 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.