blob: dffacf02adac12befb6f19d093b60b185f532ce5 [file] [log] [blame]
/* vi: set sw=4 ts=4: */
/*
* Minix shell port for busybox
*
* This version of the Minix shell was adapted for use in busybox
* by Erik Andersen <andersen@codepoet.org>
*
* - backtick expansion did not work properly
* Jonas Holmberg <jonas.holmberg@axis.com>
* Robert Schwebel <r.schwebel@pengutronix.de>
* Erik Andersen <andersen@codepoet.org>
*
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <sys/times.h>
#include <setjmp.h>
#ifdef STANDALONE
# ifndef _GNU_SOURCE
# define _GNU_SOURCE
# endif
# include <sys/types.h>
# include <sys/stat.h>
# include <sys/wait.h>
# include <signal.h>
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
# include <string.h>
# include <errno.h>
# include <dirent.h>
# include <fcntl.h>
# include <ctype.h>
# include <assert.h>
# define bb_dev_null "/dev/null"
# define DEFAULT_SHELL "/proc/self/exe"
# define bb_banner "busybox standalone"
# define ENABLE_FEATURE_SH_STANDALONE 0
# define bb_msg_memory_exhausted "memory exhausted"
# define xmalloc(size) malloc(size)
# define msh_main(argc,argv) main(argc,argv)
# define safe_read(fd,buf,count) read(fd,buf,count)
# define nonblock_safe_read(fd,buf,count) read(fd,buf,count)
# define NOT_LONE_DASH(s) ((s)[0] != '-' || (s)[1])
# define LONE_CHAR(s,c) ((s)[0] == (c) && !(s)[1])
# define NORETURN __attribute__ ((__noreturn__))
static int find_applet_by_name(const char *applet)
{
return -1;
}
static char *utoa_to_buf(unsigned n, char *buf, unsigned buflen)
{
unsigned i, out, res;
assert(sizeof(unsigned) == 4);
if (buflen) {
out = 0;
for (i = 1000000000; i; i /= 10) {
res = n / i;
if (res || out || i == 1) {
if (!--buflen) break;
out++;
n -= res*i;
*buf++ = '0' + res;
}
}
}
return buf;
}
static char *itoa_to_buf(int n, char *buf, unsigned buflen)
{
if (buflen && n < 0) {
n = -n;
*buf++ = '-';
buflen--;
}
return utoa_to_buf((unsigned)n, buf, buflen);
}
static char local_buf[12];
static char *itoa(int n)
{
*(itoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
return local_buf;
}
#else
# include "busybox.h" /* for applet_names */
#endif
//#define MSHDEBUG 4
#ifdef MSHDEBUG
static int mshdbg = MSHDEBUG;
#define DBGPRINTF(x) if (mshdbg > 0) printf x
#define DBGPRINTF0(x) if (mshdbg > 0) printf x
#define DBGPRINTF1(x) if (mshdbg > 1) printf x
#define DBGPRINTF2(x) if (mshdbg > 2) printf x
#define DBGPRINTF3(x) if (mshdbg > 3) printf x
#define DBGPRINTF4(x) if (mshdbg > 4) printf x
#define DBGPRINTF5(x) if (mshdbg > 5) printf x
#define DBGPRINTF6(x) if (mshdbg > 6) printf x
#define DBGPRINTF7(x) if (mshdbg > 7) printf x
#define DBGPRINTF8(x) if (mshdbg > 8) printf x
#define DBGPRINTF9(x) if (mshdbg > 9) printf x
static int mshdbg_rc = 0;
#define RCPRINTF(x) if (mshdbg_rc) printf x
#else
#define DBGPRINTF(x)
#define DBGPRINTF0(x) ((void)0)
#define DBGPRINTF1(x) ((void)0)
#define DBGPRINTF2(x) ((void)0)
#define DBGPRINTF3(x) ((void)0)
#define DBGPRINTF4(x) ((void)0)
#define DBGPRINTF5(x) ((void)0)
#define DBGPRINTF6(x) ((void)0)
#define DBGPRINTF7(x) ((void)0)
#define DBGPRINTF8(x) ((void)0)
#define DBGPRINTF9(x) ((void)0)
#define RCPRINTF(x) ((void)0)
#endif /* MSHDEBUG */
#if ENABLE_FEATURE_EDITING_FANCY_PROMPT
# define DEFAULT_ROOT_PROMPT "\\u:\\w> "
# define DEFAULT_USER_PROMPT "\\u:\\w$ "
#else
# define DEFAULT_ROOT_PROMPT "# "
# define DEFAULT_USER_PROMPT "$ "
#endif
/* -------- sh.h -------- */
/*
* shell
*/
#define LINELIM 2100
#define NPUSH 8 /* limit to input nesting */
#undef NOFILE
#define NOFILE 20 /* Number of open files */
#define NUFILE 10 /* Number of user-accessible files */
#define FDBASE 10 /* First file usable by Shell */
/*
* values returned by wait
*/
#define WAITSIG(s) ((s) & 0177)
#define WAITVAL(s) (((s) >> 8) & 0377)
#define WAITCORE(s) (((s) & 0200) != 0)
/*
* library and system definitions
*/
typedef void xint; /* base type of jmp_buf, for not broken compilers */
/*
* shell components
*/
#define NOBLOCK ((struct op *)NULL)
#define NOWORD ((char *)NULL)
#define NOWORDS ((char **)NULL)
#define NOPIPE ((int *)NULL)
/*
* redirection
*/
struct ioword {
smallint io_flag; /* action (below) */
int io_fd; /* fd affected */
char *io_name; /* file name */
};
#define IOREAD 1 /* < */
#define IOHERE 2 /* << (here file) */
#define IOWRITE 4 /* > */
#define IOCAT 8 /* >> */
#define IOXHERE 16 /* ${}, ` in << */
#define IODUP 32 /* >&digit */
#define IOCLOSE 64 /* >&- */
#define IODEFAULT (-1) /* "default" IO fd */
/*
* Description of a command or an operation on commands.
* Might eventually use a union.
*/
struct op {
smallint op_type; /* operation type, see Txxxx below */
char **op_words; /* arguments to a command */
struct ioword **ioact; /* IO actions (eg, < > >>) */
struct op *left;
struct op *right;
char *str; /* identifier for case and for */
};
#define TCOM 1 /* command */
#define TPAREN 2 /* (c-list) */
#define TPIPE 3 /* a | b */
#define TLIST 4 /* a [&;] b */
#define TOR 5 /* || */
#define TAND 6 /* && */
#define TFOR 7
#define TDO 8
#define TCASE 9
#define TIF 10
#define TWHILE 11
#define TUNTIL 12
#define TELIF 13
#define TPAT 14 /* pattern in case */
#define TBRACE 15 /* {c-list} */
#define TASYNC 16 /* c & */
/* Added to support "." file expansion */
#define TDOT 17
/* Strings for names to make debug easier */
#ifdef MSHDEBUG
static const char *const T_CMD_NAMES[] = {
"PLACEHOLDER",
"TCOM",
"TPAREN",
"TPIPE",
"TLIST",
"TOR",
"TAND",
"TFOR",
"TDO",
"TCASE",
"TIF",
"TWHILE",
"TUNTIL",
"TELIF",
"TPAT",
"TBRACE",
"TASYNC",
"TDOT",
};
#endif
#define AREASIZE (90000)
/*
* flags to control evaluation of words
*/
#define DOSUB 1 /* interpret $, `, and quotes */
#define DOBLANK 2 /* perform blank interpretation */
#define DOGLOB 4 /* interpret [?* */
#define DOKEY 8 /* move words with `=' to 2nd arg. list */
#define DOTRIM 16 /* trim resulting string */
#define DOALL (DOSUB|DOBLANK|DOGLOB|DOKEY|DOTRIM)
struct brkcon {
jmp_buf brkpt;
struct brkcon *nextlev;
};
static smallint trapset; /* trap pending (signal number) */
static smallint yynerrs; /* yacc (flag) */
/* moved to G: static char line[LINELIM]; */
#if ENABLE_FEATURE_EDITING
static char *current_prompt;
static line_input_t *line_input_state;
#endif
/*
* other functions
*/
static const char *rexecve(char *c, char **v, char **envp);
static char *evalstr(char *cp, int f);
static char *putn(int n);
static char *unquote(char *as);
static int rlookup(char *n);
static struct wdblock *glob(char *cp, struct wdblock *wb);
static int my_getc(int ec);
static int subgetc(char ec, int quoted);
static char **makenv(int all, struct wdblock *wb);
static char **eval(char **ap, int f);
static int setstatus(int s);
static int waitfor(int lastpid, int canintr);
static void onintr(int s); /* SIGINT handler */
static int newenv(int f);
static void quitenv(void);
static void next(int f);
static void setdash(void);
static void onecommand(void);
static void runtrap(int i);
/* -------- area stuff -------- */
#define REGSIZE sizeof(struct region)
#define GROWBY (256)
/* #define SHRINKBY (64) */
#undef SHRINKBY
#define FREE (32767)
#define BUSY (0)
#define ALIGN (sizeof(int)-1)
struct region {
struct region *next;
int area;
};
/* -------- grammar stuff -------- */
typedef union {
char *cp;
char **wp;
int i;
struct op *o;
} YYSTYPE;
#define WORD 256
#define LOGAND 257
#define LOGOR 258
#define BREAK 259
#define IF 260
#define THEN 261
#define ELSE 262
#define ELIF 263
#define FI 264
#define CASE 265
#define ESAC 266
#define FOR 267
#define WHILE 268
#define UNTIL 269
#define DO 270
#define DONE 271
#define IN 272
/* Added for "." file expansion */
#define DOT 273
#define YYERRCODE 300
/* flags to yylex */
#define CONTIN 01 /* skip new lines to complete command */
static struct op *pipeline(int cf);
static struct op *andor(void);
static struct op *c_list(void);
static int synio(int cf);
static void musthave(int c, int cf);
static struct op *simple(void);
static struct op *nested(int type, int mark);
static struct op *command(int cf);
static struct op *dogroup(int onlydone);
static struct op *thenpart(void);
static struct op *elsepart(void);
static struct op *caselist(void);
static struct op *casepart(void);
static char **pattern(void);
static char **wordlist(void);
static struct op *list(struct op *t1, struct op *t2);
static struct op *block(int type, struct op *t1, struct op *t2, char **wp);
static struct op *newtp(void);
static struct op *namelist(struct op *t);
static char **copyw(void);
static void word(char *cp);
static struct ioword **copyio(void);
static struct ioword *io(int u, int f, char *cp);
static int yylex(int cf);
static int collect(int c, int c1);
static int dual(int c);
static void diag(int ec);
static char *tree(unsigned size);
/* -------- var.h -------- */
struct var {
char *value;
char *name;
struct var *next;
char status;
};
#define COPYV 1 /* flag to setval, suggesting copy */
#define RONLY 01 /* variable is read-only */
#define EXPORT 02 /* variable is to be exported */
#define GETCELL 04 /* name & value space was got with getcell */
static int yyparse(void);
/* -------- io.h -------- */
/* io buffer */
struct iobuf {
unsigned id; /* buffer id */
char buf[512]; /* buffer */
char *bufp; /* pointer into buffer */
char *ebufp; /* pointer to end of buffer */
};
/* possible arguments to an IO function */
struct ioarg {
const char *aword;
char **awordlist;
int afile; /* file descriptor */
unsigned afid; /* buffer id */
off_t afpos; /* file position */
struct iobuf *afbuf; /* buffer for this file */
};
/* an input generator's state */
struct io {
int (*iofn) (struct ioarg *, struct io *);
struct ioarg *argp;
int peekc;
char prev; /* previous character read by readc() */
char nlcount; /* for `'s */
char xchar; /* for `'s */
char task; /* reason for pushed IO */
};
/* ->task: */
#define XOTHER 0 /* none of the below */
#define XDOLL 1 /* expanding ${} */
#define XGRAVE 2 /* expanding `'s */
#define XIO 3 /* file IO */
/*
* input generators for IO structure
*/
static int nlchar(struct ioarg *ap);
static int strchar(struct ioarg *ap);
static int qstrchar(struct ioarg *ap);
static int filechar(struct ioarg *ap);
static int herechar(struct ioarg *ap);
static int linechar(struct ioarg *ap);
static int gravechar(struct ioarg *ap, struct io *iop);
static int qgravechar(struct ioarg *ap, struct io *iop);
static int dolchar(struct ioarg *ap);
static int wdchar(struct ioarg *ap);
static void scraphere(void);
static void freehere(int area);
static void gethere(void);
static void markhere(char *s, struct ioword *iop);
static int herein(char *hname, int xdoll);
static int run(struct ioarg *argp, int (*f) (struct ioarg *));
static int eofc(void);
static int readc(void);
static void unget(int c);
static void ioecho(char c);
/*
* IO control
*/
static void pushio(struct ioarg *argp, int (*f) (struct ioarg *));
#define PUSHIO(what,arg,gen) ((temparg.what = (arg)), pushio(&temparg,(gen)))
static int remap(int fd);
static int openpipe(int *pv);
static void closepipe(int *pv);
static struct io *setbase(struct io *ip);
/* -------- word.h -------- */
#define NSTART 16 /* default number of words to allow for initially */
struct wdblock {
short w_bsize;
short w_nword;
/* bounds are arbitrary */
char *w_words[1];
};
static struct wdblock *addword(char *wd, struct wdblock *wb);
static struct wdblock *newword(int nw);
static char **getwords(struct wdblock *wb);
/* -------- misc stuff -------- */
static int dolabel(struct op *t, char **args);
static int dohelp(struct op *t, char **args);
static int dochdir(struct op *t, char **args);
static int doshift(struct op *t, char **args);
static int dologin(struct op *t, char **args);
static int doumask(struct op *t, char **args);
static int doexec(struct op *t, char **args);
static int dodot(struct op *t, char **args);
static int dowait(struct op *t, char **args);
static int doread(struct op *t, char **args);
static int doeval(struct op *t, char **args);
static int dotrap(struct op *t, char **args);
static int dobreak(struct op *t, char **args);
static int doexit(struct op *t, char **args);
static int doexport(struct op *t, char **args);
static int doreadonly(struct op *t, char **args);
static int doset(struct op *t, char **args);
static int dotimes(struct op *t, char **args);
static int docontinue(struct op *t, char **args);
static int forkexec(struct op *t, int *pin, int *pout, int no_fork, char **wp);
static int execute(struct op *t, int *pin, int *pout, int no_fork);
static int iosetup(struct ioword *iop, int pipein, int pipeout);
static void brkset(struct brkcon *bc);
static int getsig(char *s);
static void setsig(int n, sighandler_t f);
static int getn(char *as);
static int brkcontin(char *cp, int val);
static void rdexp(char **wp, void (*f) (struct var *), int key);
static void badid(char *s);
static void varput(char *s, int out);
static int expand(const char *cp, struct wdblock **wbp, int f);
static char *blank(int f);
static int dollar(int quoted);
static int grave(int quoted);
static void globname(char *we, char *pp);
static char *generate(char *start1, char *end1, char *middle, char *end);
static int anyspcl(struct wdblock *wb);
static void readhere(char **name, char *s, int ec);
static int xxchar(struct ioarg *ap);
struct here {
char *h_tag;
char h_dosub;
struct ioword *h_iop;
struct here *h_next;
};
static const char *const signame[] = {
"Signal 0",
"Hangup",
NULL, /* interrupt */
"Quit",
"Illegal instruction",
"Trace/BPT trap",
"Abort",
"Bus error",
"Floating Point Exception",
"Killed",
"SIGUSR1",
"SIGSEGV",
"SIGUSR2",
NULL, /* broken pipe */
"Alarm clock",
"Terminated"
};
typedef int (*builtin_func_ptr)(struct op *, char **);
struct builtincmd {
const char *name;
builtin_func_ptr builtinfunc;
};
static const struct builtincmd builtincmds[] = {
{ "." , dodot },
{ ":" , dolabel },
{ "break" , dobreak },
{ "cd" , dochdir },
{ "continue", docontinue },
{ "eval" , doeval },
{ "exec" , doexec },
{ "exit" , doexit },
{ "export" , doexport },
{ "help" , dohelp },
{ "login" , dologin },
{ "newgrp" , dologin },
{ "read" , doread },
{ "readonly", doreadonly },
{ "set" , doset },
{ "shift" , doshift },
{ "times" , dotimes },
{ "trap" , dotrap },
{ "umask" , doumask },
{ "wait" , dowait },
{ NULL , NULL },
};
static struct op *dowholefile(int /*, int*/);
/* Globals */
static char **dolv;
static int dolc;
static uint8_t exstat;
static smallint gflg; /* (seems to be a parse error indicator) */
static smallint interactive; /* Is this an interactive shell */
static smallint execflg;
static smallint isbreak; /* "break" statement was seen */
static int multiline; /* '\n' changed to ';' (counter) */
static struct op *outtree; /* result from parser */
static xint *failpt;
static xint *errpt;
static struct brkcon *brklist;
static struct wdblock *wdlist;
static struct wdblock *iolist;
#ifdef MSHDEBUG
static struct var *mshdbg_var;
#endif
static struct var *vlist; /* dictionary */
static struct var *homedir; /* home directory */
static struct var *prompt; /* main prompt */
static struct var *cprompt; /* continuation prompt */
static struct var *path; /* search path for commands */
static struct var *shell; /* shell to interpret command files */
static struct var *ifs; /* field separators */
static int areanum; /* current allocation area */
static smallint intr; /* interrupt pending (bool) */
static smallint heedint = 1; /* heed interrupt signals (bool) */
static int inparse;
static char *null = (char*)""; /* null value for variable */
static void (*qflag)(int) = SIG_IGN;
static int startl;
static int peeksym;
static int nlseen;
static int iounit = IODEFAULT;
static YYSTYPE yylval;
static char *elinep; /* done in main(): = line + sizeof(line) - 5 */
static struct here *inhere; /* list of hear docs while parsing */
static struct here *acthere; /* list of active here documents */
static struct region *areabot; /* bottom of area */
static struct region *areatop; /* top of area */
static struct region *areanxt; /* starting point of scan */
static void *brktop;
static void *brkaddr;
#define AFID_NOBUF (~0)
#define AFID_ID 0
/*
* parsing & execution environment
*/
struct env {
char *linep;
struct io *iobase;
struct io *iop;
xint *errpt; /* void * */
int iofd;
struct env *oenv;
};
struct globals {
struct env global_env;
struct ioarg temparg; // = { .afid = AFID_NOBUF }; /* temporary for PUSHIO */
unsigned bufid; // = AFID_ID; /* buffer id counter */
char ourtrap[_NSIG + 1];
char *trap[_NSIG + 1];
struct iobuf sharedbuf; /* in main(): set to { AFID_NOBUF } */
struct iobuf mainbuf; /* in main(): set to { AFID_NOBUF } */
struct ioarg ioargstack[NPUSH];
/*
* flags:
* -e: quit on error
* -k: look for name=value everywhere on command line
* -n: no execution
* -t: exit after reading and executing one command
* -v: echo as read
* -x: trace
* -u: unset variables net diagnostic
*/
char flags['z' - 'a' + 1];
char filechar_cmdbuf[BUFSIZ];
char line[LINELIM];
char child_cmd[LINELIM];
struct io iostack[NPUSH];
char grave__var_name[LINELIM];
char grave__alt_value[LINELIM];
};
#define G (*ptr_to_globals)
#define global_env (G.global_env )
#define temparg (G.temparg )
#define bufid (G.bufid )
#define ourtrap (G.ourtrap )
#define trap (G.trap )
#define sharedbuf (G.sharedbuf )
#define mainbuf (G.mainbuf )
#define ioargstack (G.ioargstack )
/* this looks weird, but is OK ... we index FLAG with 'a'...'z' */
#define FLAG (G.flags - 'a' )
#define filechar_cmdbuf (G.filechar_cmdbuf)
#define line (G.line )
#define child_cmd (G.child_cmd )
#define iostack (G.iostack )
#define INIT_G() do { \
SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
global_env.linep = line; \
global_env.iobase = iostack; \
global_env.iop = iostack - 1; \
global_env.iofd = FDBASE; \
temparg.afid = AFID_NOBUF; \
bufid = AFID_ID; \
} while (0)
/* in substitution */
#define INSUB() (global_env.iop->task == XGRAVE || global_env.iop->task == XDOLL)
#define RUN(what, arg, gen) ((temparg.what = (arg)), run(&temparg, (gen)))
#ifdef MSHDEBUG
static void print_tree(struct op *head)
{
if (head == NULL) {
DBGPRINTF(("PRINT_TREE: no tree\n"));
return;
}
DBGPRINTF(("NODE: %p, left %p, right %p\n", head, head->left,
head->right));
if (head->left)
print_tree(head->left);
if (head->right)
print_tree(head->right);
}
#endif /* MSHDEBUG */
/*
* IO functions
*/
static void prs(const char *s)
{
if (*s)
xwrite_str(STDERR_FILENO, s);
}
static void prn(unsigned u)
{
prs(itoa(u));
}
static void echo(char **wp)
{
int i;
prs("+");
for (i = 0; wp[i]; i++) {
if (i)
prs(" ");
prs(wp[i]);
}
prs("\n");
}
static void closef(int i)
{
if (i > 2)
close(i);
}
static void closeall(void)
{
int u;
for (u = NUFILE; u < NOFILE;)
close(u++);
}
/* fail but return to process next command */
static void fail(void) NORETURN;
static void fail(void)
{
longjmp(failpt, 1);
/* NOTREACHED */
}
/* abort shell (or fail in subshell) */
static void leave(void) NORETURN;
static void leave(void)
{
DBGPRINTF(("LEAVE: leave called!\n"));
if (execflg)
fail();
scraphere();
freehere(1);
runtrap(0);
_exit(exstat);
/* NOTREACHED */
}
static void warn(const char *s)
{
if (*s) {
prs(s);
if (!exstat)
exstat = 255;
}
prs("\n");
if (FLAG['e'])
leave();
}
static void err(const char *s)
{
warn(s);
if (FLAG['n'])
return;
if (!interactive)
leave();
if (global_env.errpt)
longjmp(global_env.errpt, 1);
closeall();
global_env.iop = global_env.iobase = iostack;
}
/* -------- area.c -------- */
/*
* All memory between (char *)areabot and (char *)(areatop+1) is
* exclusively administered by the area management routines.
* It is assumed that sbrk() and brk() manipulate the high end.
*/
#define sbrk(X) ({ \
void * __q = (void *)-1; \
if (brkaddr + (int)(X) < brktop) { \
__q = brkaddr; \
brkaddr += (int)(X); \
} \
__q; \
})
static void initarea(void)
{
brkaddr = xmalloc(AREASIZE);
brktop = brkaddr + AREASIZE;
while ((long) sbrk(0) & ALIGN)
sbrk(1);
areabot = (struct region *) sbrk(REGSIZE);
areabot->next = areabot;
areabot->area = BUSY;
areatop = areabot;
areanxt = areabot;
}
static char *getcell(unsigned nbytes)
{
int nregio;
struct region *p, *q;
int i;
if (nbytes == 0) {
puts("getcell(0)");
abort();
}
/* silly and defeats the algorithm */
/*
* round upwards and add administration area
*/
nregio = (nbytes + (REGSIZE - 1)) / REGSIZE + 1;
p = areanxt;
for (;;) {
if (p->area > areanum) {
/*
* merge free cells
*/
while ((q = p->next)->area > areanum && q != areanxt)
p->next = q->next;
/*
* exit loop if cell big enough
*/
if (q >= p + nregio)
goto found;
}
p = p->next;
if (p == areanxt)
break;
}
i = nregio >= GROWBY ? nregio : GROWBY;
p = (struct region *) sbrk(i * REGSIZE);
if (p == (struct region *) -1)
return NULL;
p--;
if (p != areatop) {
puts("not contig");
abort(); /* allocated areas are contiguous */
}
q = p + i;
p->next = q;
p->area = FREE;
q->next = areabot;
q->area = BUSY;
areatop = q;
found:
/*
* we found a FREE area big enough, pointed to by 'p', and up to 'q'
*/
areanxt = p + nregio;
if (areanxt < q) {
/*
* split into requested area and rest
*/
if (areanxt + 1 > q) {
puts("OOM");
abort(); /* insufficient space left for admin */
}
areanxt->next = q;
areanxt->area = FREE;
p->next = areanxt;
}
p->area = areanum;
return (char *) (p + 1);
}
static void freecell(char *cp)
{
struct region *p;
p = (struct region *) cp;
if (p != NULL) {
p--;
if (p < areanxt)
areanxt = p;
p->area = FREE;
}
}
#define DELETE(obj) freecell((char *)obj)
static void freearea(int a)
{
struct region *p, *top;
top = areatop;
for (p = areabot; p != top; p = p->next)
if (p->area >= a)
p->area = FREE;
}
static void setarea(char *cp, int a)
{
struct region *p;
p = (struct region *) cp;
if (p != NULL)
(p - 1)->area = a;
}
static int getarea(char *cp)
{
return ((struct region *) cp - 1)->area;
}
static void garbage(void)
{
struct region *p, *q, *top;
top = areatop;
for (p = areabot; p != top; p = p->next) {
if (p->area > areanum) {
while ((q = p->next)->area > areanum)
p->next = q->next;
areanxt = p;
}
}
#ifdef SHRINKBY
if (areatop >= q + SHRINKBY && q->area > areanum) {
brk((char *) (q + 1));
q->next = areabot;
q->area = BUSY;
areatop = q;
}
#endif
}
static void *get_space(int n)
{
char *cp;
cp = getcell(n);
if (cp == NULL)
err("out of string space");
return cp;
}
static char *strsave(const char *s, int a)
{
char *cp;
cp = get_space(strlen(s) + 1);
if (cp == NULL) {
// FIXME: I highly doubt this is good.
return (char*)"";
}
setarea(cp, a);
strcpy(cp, s);
return cp;
}
/* -------- var.c -------- */
static int eqname(const char *n1, const char *n2)
{
for (; *n1 != '=' && *n1 != '\0'; n1++)
if (*n2++ != *n1)
return 0;
return *n2 == '\0' || *n2 == '=';
}
static const char *findeq(const char *cp)
{
while (*cp != '\0' && *cp != '=')
cp++;
return cp;
}
/*
* Find the given name in the dictionary
* and return its value. If the name was
* not previously there, enter it now and
* return a null value.
*/
static struct var *lookup(const char *n)
{
// FIXME: dirty hack
static struct var dummy;
struct var *vp;
const char *cp;
char *xp;
int c;
if (isdigit(*n)) {
dummy.name = (char*)n;
for (c = 0; isdigit(*n) && c < 1000; n++)
c = c * 10 + *n - '0';
dummy.status = RONLY;
dummy.value = (c <= dolc ? dolv[c] : null);
return &dummy;
}
for (vp = vlist; vp; vp = vp->next)
if (eqname(vp->name, n))
return vp;
cp = findeq(n);
vp = get_space(sizeof(*vp));
if (vp == 0 || (vp->name = get_space((int) (cp - n) + 2)) == NULL) {
dummy.name = dummy.value = (char*)"";
return &dummy;
}
xp = vp->name;
while ((*xp = *n++) != '\0' && *xp != '=')
xp++;
*xp++ = '=';
*xp = '\0';
setarea((char *) vp, 0);
setarea((char *) vp->name, 0);
vp->value = null;
vp->next = vlist;
vp->status = GETCELL;
vlist = vp;
return vp;
}
/*
* if name is not NULL, it must be
* a prefix of the space `val',
* and end with `='.
* this is all so that exporting
* values is reasonably painless.
*/
static void nameval(struct var *vp, const char *val, const char *name)
{
const char *cp;
char *xp;
int fl;
if (vp->status & RONLY) {
xp = vp->name;
while (*xp && *xp != '=')
fputc(*xp++, stderr);
err(" is read-only");
return;
}
fl = 0;
if (name == NULL) {
xp = get_space(strlen(vp->name) + strlen(val) + 2);
if (xp == NULL)
return;
/* make string: name=value */
setarea(xp, 0);
name = xp;
cp = vp->name;
while ((*xp = *cp++) != '\0' && *xp != '=')
xp++;
*xp++ = '=';
strcpy(xp, val);
val = xp;
fl = GETCELL;
}
if (vp->status & GETCELL)
freecell(vp->name); /* form new string `name=value' */
vp->name = (char*)name;
vp->value = (char*)val;
vp->status |= fl;
}
/*
* give variable at `vp' the value `val'.
*/
static void setval(struct var *vp, const char *val)
{
nameval(vp, val, NULL);
}
static void export(struct var *vp)
{
vp->status |= EXPORT;
}
static void ronly(struct var *vp)
{
if (isalpha(vp->name[0]) || vp->name[0] == '_') /* not an internal symbol */
vp->status |= RONLY;
}
static int isassign(const char *s)
{
unsigned char c;
DBGPRINTF7(("ISASSIGN: enter, s=%s\n", s));
c = *s;
/* no isalpha() - we shouldn't use locale */
/* c | 0x20 - lowercase (Latin) letters */
if (c != '_' && (unsigned)((c|0x20) - 'a') > 25)
/* not letter */
return 0;
while (1) {
c = *++s;
if (c == '=')
return 1;
if (c == '\0')
return 0;
if (c != '_'
&& (unsigned)(c - '0') > 9 /* not number */
&& (unsigned)((c|0x20) - 'a') > 25 /* not letter */
) {
return 0;
}
}
}
static int assign(const char *s, int cf)
{
const char *cp;
struct var *vp;
DBGPRINTF7(("ASSIGN: enter, s=%s, cf=%d\n", s, cf));
if (!isalpha(*s) && *s != '_')
return 0;
for (cp = s; *cp != '='; cp++)
if (*cp == '\0' || (!isalnum(*cp) && *cp != '_'))
return 0;
vp = lookup(s);
nameval(vp, ++cp, cf == COPYV ? NULL : s);
if (cf != COPYV)
vp->status &= ~GETCELL;
return 1;
}
static int checkname(char *cp)
{
DBGPRINTF7(("CHECKNAME: enter, cp=%s\n", cp));
if (!isalpha(*cp++) && *(cp - 1) != '_')
return 0;
while (*cp)
if (!isalnum(*cp++) && *(cp - 1) != '_')
return 0;
return 1;
}
static void putvlist(int f, int out)
{
struct var *vp;
for (vp = vlist; vp; vp = vp->next) {
if (vp->status & f && (isalpha(*vp->name) || *vp->name == '_')) {
if (vp->status & EXPORT)
write(out, "export ", 7);
if (vp->status & RONLY)
write(out, "readonly ", 9);
write(out, vp->name, (int) (findeq(vp->name) - vp->name));
write(out, "\n", 1);
}
}
}
/*
* trap handling
*/
static void sig(int i)
{
trapset = i;
signal(i, sig);
}
static void runtrap(int i)
{
char *trapstr;
trapstr = trap[i];
if (trapstr == NULL)
return;
if (i == 0)
trap[i] = NULL;
RUN(aword, trapstr, nlchar);
}
static void setdash(void)
{
char *cp;
int c;
char m['z' - 'a' + 1];
cp = m;
for (c = 'a'; c <= 'z'; c++)
if (FLAG[c])
*cp++ = c;
*cp = '\0';
setval(lookup("-"), m);
}
static int newfile(char *s)
{
int f;
DBGPRINTF7(("NEWFILE: opening %s\n", s));
f = 0;
if (NOT_LONE_DASH(s)) {
DBGPRINTF(("NEWFILE: s is %s\n", s));
f = open(s, O_RDONLY);
if (f < 0) {
prs(s);
err(": can't open");
return 1;
}
}
next(remap(f));
return 0;
}
#ifdef UNUSED
struct op *scantree(struct op *head)
{
struct op *dotnode;
if (head == NULL)
return NULL;
if (head->left != NULL) {
dotnode = scantree(head->left);
if (dotnode)
return dotnode;
}
if (head->right != NULL) {
dotnode = scantree(head->right);
if (dotnode)
return dotnode;
}
if (head->op_words == NULL)
return NULL;
DBGPRINTF5(("SCANTREE: checking node %p\n", head));
if ((head->op_type != TDOT) && LONE_CHAR(head->op_words[0], '.')) {
DBGPRINTF5(("SCANTREE: dot found in node %p\n", head));
return head;
}
return NULL;
}
#endif
static void onecommand(void)
{
int i;
jmp_buf m1;
DBGPRINTF(("ONECOMMAND: enter, outtree=%p\n", outtree));
while (global_env.oenv)
quitenv();
areanum = 1;
freehere(areanum);
freearea(areanum);
garbage();
wdlist = NULL;
iolist = NULL;
global_env.errpt = NULL;
global_env.linep = line;
yynerrs = 0;
multiline = 0;
inparse = 1;
intr = 0;
execflg = 0;
failpt = m1;
setjmp(failpt); /* Bruce Evans' fix */
failpt = m1;
if (setjmp(failpt) || yyparse() || intr) {
DBGPRINTF(("ONECOMMAND: this is not good.\n"));
while (global_env.oenv)
quitenv();
scraphere();
if (!interactive && intr)
leave();
inparse = 0;
intr = 0;
return;
}
inparse = 0;
brklist = 0;
intr = 0;
execflg = 0;
if (!FLAG['n']) {
DBGPRINTF(("ONECOMMAND: calling execute, t=outtree=%p\n",
outtree));
execute(outtree, NOPIPE, NOPIPE, /* no_fork: */ 0);
}
if (!interactive && intr) {
execflg = 0;
leave();
}
i = trapset;
if (i != 0) {
trapset = 0;
runtrap(i);
}
}
static int newenv(int f)
{
struct env *ep;
DBGPRINTF(("NEWENV: f=%d (indicates quitenv and return)\n", f));
if (f) {
quitenv();
return 1;
}
ep = get_space(sizeof(*ep));
if (ep == NULL) {
while (global_env.oenv)
quitenv();
fail();
}
*ep = global_env;
global_env.oenv = ep;
global_env.errpt = errpt;
return 0;
}
static void quitenv(void)
{
struct env *ep;
int fd;
DBGPRINTF(("QUITENV: global_env.oenv=%p\n", global_env.oenv));
ep = global_env.oenv;
if (ep != NULL) {
fd = global_env.iofd;
global_env = *ep;
/* should close `'d files */
DELETE(ep);
while (--fd >= global_env.iofd)
close(fd);
}
}
/*
* Is character c in s?
*/
static int any(int c, const char *s)
{
while (*s)
if (*s++ == c)
return 1;
return 0;
}
/*
* Is any character from s1 in s2?
*/
static int anys(const char *s1, const char *s2)
{
while (*s1)
if (any(*s1++, s2))
return 1;
return 0;
}
static char *putn(int n)
{
return itoa(n);
}
static void next(int f)
{
PUSHIO(afile, f, filechar);
}
static void onintr(int s UNUSED_PARAM) /* ANSI C requires a parameter */
{
signal(SIGINT, onintr);
intr = 1;
if (interactive) {
if (inparse) {
prs("\n");
fail();
}
} else if (heedint) {
execflg = 0;
leave();
}
}
/* -------- gmatch.c -------- */
/*
* int gmatch(string, pattern)
* char *string, *pattern;
*
* Match a pattern as in sh(1).
*/
#define CMASK 0377
#define QUOTE 0200
#define QMASK (CMASK & ~QUOTE)
#define NOT '!' /* might use ^ */
static const char *cclass(const char *p, int sub)
{
int c, d, not, found;
not = (*p == NOT);
if (not != 0)
p++;
found = not;
do {
if (*p == '\0')
return NULL;
c = *p & CMASK;
if (p[1] == '-' && p[2] != ']') {
d = p[2] & CMASK;
p++;
} else
d = c;
if (c == sub || (c <= sub && sub <= d))
found = !not;
} while (*++p != ']');
return found ? p + 1 : NULL;
}
static int gmatch(const char *s, const char *p)
{
int sc, pc;
if (s == NULL || p == NULL)
return 0;
while ((pc = *p++ & CMASK) != '\0') {
sc = *s++ & QMASK;
switch (pc) {
case '[':
p = cclass(p, sc);
if (p == NULL)
return 0;
break;
case '?':
if (sc == 0)
return 0;
break;
case '*':
s--;
do {
if (*p == '\0' || gmatch(s, p))
return 1;
} while (*s++ != '\0');
return 0;
default:
if (sc != (pc & ~QUOTE))
return 0;
}
}
return *s == '\0';
}
/* -------- csyn.c -------- */
/*
* shell: syntax (C version)
*/
static void yyerror(const char *s) NORETURN;
static void yyerror(const char *s)
{
yynerrs = 1;
if (interactive && global_env.iop <= iostack) {
multiline = 0;
while (eofc() == 0 && yylex(0) != '\n')
continue;
}
err(s);
fail();
}
static void zzerr(void) NORETURN;
static void zzerr(void)
{
yyerror("syntax error");
}
int yyparse(void)
{
DBGPRINTF7(("YYPARSE: enter...\n"));
startl = 1;
peeksym = 0;
yynerrs = 0;
outtree = c_list();
musthave('\n', 0);
return yynerrs; /* 0/1 */
}
static struct op *pipeline(int cf)
{
struct op *t, *p;
int c;
DBGPRINTF7(("PIPELINE: enter, cf=%d\n", cf));
t = command(cf);
DBGPRINTF9(("PIPELINE: t=%p\n", t));
if (t != NULL) {
while ((c = yylex(0)) == '|') {
p = command(CONTIN);
if (p == NULL) {
DBGPRINTF8(("PIPELINE: error!\n"));
zzerr();
}
if (t->op_type != TPAREN && t->op_type != TCOM) {
/* shell statement */
t = block(TPAREN, t, NOBLOCK, NOWORDS);
}
t = block(TPIPE, t, p, NOWORDS);
}
peeksym = c;
}
DBGPRINTF7(("PIPELINE: returning t=%p\n", t));
return t;
}
static struct op *andor(void)
{
struct op *t, *p;
int c;
DBGPRINTF7(("ANDOR: enter...\n"));
t = pipeline(0);
DBGPRINTF9(("ANDOR: t=%p\n", t));
if (t != NULL) {
while ((c = yylex(0)) == LOGAND || c == LOGOR) {
p = pipeline(CONTIN);
if (p == NULL) {
DBGPRINTF8(("ANDOR: error!\n"));
zzerr();
}
t = block(c == LOGAND ? TAND : TOR, t, p, NOWORDS);
}
peeksym = c;
}
DBGPRINTF7(("ANDOR: returning t=%p\n", t));
return t;
}
static struct op *c_list(void)
{
struct op *t, *p;
int c;
DBGPRINTF7(("C_LIST: enter...\n"));
t = andor();
if (t != NULL) {
peeksym = yylex(0);
if (peeksym == '&')
t = block(TASYNC, t, NOBLOCK, NOWORDS);
while ((c = yylex(0)) == ';' || c == '&'
|| (multiline && c == '\n')
) {
p = andor();
if (p== NULL)
return t;
peeksym = yylex(0);
if (peeksym == '&')
p = block(TASYNC, p, NOBLOCK, NOWORDS);
t = list(t, p);
} /* WHILE */
peeksym = c;
}
/* IF */
DBGPRINTF7(("C_LIST: returning t=%p\n", t));
return t;
}
static int synio(int cf)
{
struct ioword *iop;
int i;
int c;
DBGPRINTF7(("SYNIO: enter, cf=%d\n", cf));
c = yylex(cf);
if (c != '<' && c != '>') {
peeksym = c;
return 0;
}
i = yylval.i;
musthave(WORD, 0);
iop = io(iounit, i, yylval.cp);
iounit = IODEFAULT;
if (i & IOHERE)
markhere(yylval.cp, iop);
DBGPRINTF7(("SYNIO: returning 1\n"));
return 1;
}
static void musthave(int c, int cf)
{
peeksym = yylex(cf);
if (peeksym != c) {
DBGPRINTF7(("MUSTHAVE: error!\n"));
zzerr();
}
peeksym = 0;
}
static struct op *simple(void)
{
struct op *t;
t = NULL;
for (;;) {
switch (peeksym = yylex(0)) {
case '<':
case '>':
(void) synio(0);
break;
case WORD:
if (t == NULL) {
t = newtp();
t->op_type = TCOM;
}
peeksym = 0;
word(yylval.cp);
break;
default:
return t;
}
}
}
static struct op *nested(int type, int mark)
{
struct op *t;
DBGPRINTF3(("NESTED: enter, type=%d, mark=%d\n", type, mark));
multiline++;
t = c_list();
musthave(mark, 0);
multiline--;
return block(type, t, NOBLOCK, NOWORDS);
}
static struct op *command(int cf)
{
struct op *t;
struct wdblock *iosave;
int c;
DBGPRINTF(("COMMAND: enter, cf=%d\n", cf));
iosave = iolist;
iolist = NULL;
if (multiline)
cf |= CONTIN;
while (synio(cf))
cf = 0;
c = yylex(cf);
switch (c) {
default:
peeksym = c;
t = simple();
if (t == NULL) {
if (iolist == NULL)
return NULL;
t = newtp();
t->op_type = TCOM;
}
break;
case '(':
t = nested(TPAREN, ')');
break;
case '{':
t = nested(TBRACE, '}');
break;
case FOR:
t = newtp();
t->op_type = TFOR;
musthave(WORD, 0);
startl = 1;
t->str = yylval.cp;
multiline++;
t->op_words = wordlist();
c = yylex(0);
if (c != '\n' && c != ';')
peeksym = c;
t->left = dogroup(0);
multiline--;
break;
case WHILE:
case UNTIL:
multiline++;
t = newtp();
t->op_type = (c == WHILE ? TWHILE : TUNTIL);
t->left = c_list();
t->right = dogroup(1);
/* t->op_words = NULL; - newtp() did this */
multiline--;
break;
case CASE:
t = newtp();
t->op_type = TCASE;
musthave(WORD, 0);
t->str = yylval.cp;
startl++;
multiline++;
musthave(IN, CONTIN);
startl++;
t->left = caselist();
musthave(ESAC, 0);
multiline--;
break;
case IF:
multiline++;
t = newtp();
t->op_type = TIF;
t->left = c_list();
t->right = thenpart();
musthave(FI, 0);
multiline--;
break;
case DOT:
t = newtp();
t->op_type = TDOT;
musthave(WORD, 0); /* gets name of file */
DBGPRINTF7(("COMMAND: DOT clause, yylval.cp is %s\n", yylval.cp));
word(yylval.cp); /* add word to wdlist */
word(NOWORD); /* terminate wdlist */
t->op_words = copyw(); /* dup wdlist */
break;
}
while (synio(0))
continue;
t = namelist(t);
iolist = iosave;
DBGPRINTF(("COMMAND: returning %p\n", t));
return t;
}
static struct op *dowholefile(int type /*, int mark*/)
{
struct op *t;
DBGPRINTF(("DOWHOLEFILE: enter, type=%d\n", type /*, mark*/));
multiline++;
t = c_list();
multiline--;
t = block(type, t, NOBLOCK, NOWORDS);
DBGPRINTF(("DOWHOLEFILE: return t=%p\n", t));
return t;
}
static struct op *dogroup(int onlydone)
{
int c;
struct op *mylist;
c = yylex(CONTIN);
if (c == DONE && onlydone)
return NULL;
if (c != DO)
zzerr();
mylist = c_list();
musthave(DONE, 0);
return mylist;
}
static struct op *thenpart(void)
{
int c;
struct op *t;
c = yylex(0);
if (c != THEN) {
peeksym = c;
return NULL;
}
t = newtp();
/*t->op_type = 0; - newtp() did this */
t->left = c_list();
if (t->left == NULL)
zzerr();
t->right = elsepart();
return t;
}
static struct op *elsepart(void)
{
int c;
struct op *t;
switch (c = yylex(0)) {
case ELSE:
t = c_list();
if (t == NULL)
zzerr();
return t;
case ELIF:
t = newtp();
t->op_type = TELIF;
t->left = c_list();
t->right = thenpart();
return t;
default:
peeksym = c;
return NULL;
}
}
static struct op *caselist(void)
{
struct op *t;
t = NULL;
while ((peeksym = yylex(CONTIN)) != ESAC) {
DBGPRINTF(("CASELIST, doing yylex, peeksym=%d\n", peeksym));
t = list(t, casepart());
}
DBGPRINTF(("CASELIST, returning t=%p\n", t));
return t;
}
static struct op *casepart(void)
{
struct op *t;
DBGPRINTF7(("CASEPART: enter...\n"));
t = newtp();
t->op_type = TPAT;
t->op_words = pattern();
musthave(')', 0);
t->left = c_list();
peeksym = yylex(CONTIN);
if (peeksym != ESAC)
musthave(BREAK, CONTIN);
DBGPRINTF7(("CASEPART: made newtp(TPAT, t=%p)\n", t));
return t;
}
static char **pattern(void)
{
int c, cf;
cf = CONTIN;
do {
musthave(WORD, cf);
word(yylval.cp);
cf = 0;
c = yylex(0);
} while (c == '|');
peeksym = c;
word(NOWORD);
return copyw();
}
static char **wordlist(void)
{
int c;
c = yylex(0);
if (c != IN) {
peeksym = c;
return NULL;
}
startl = 0;
while ((c = yylex(0)) == WORD)
word(yylval.cp);
word(NOWORD);
peeksym = c;
return copyw();
}
/*
* supporting functions
*/
static struct op *list(struct op *t1, struct op *t2)
{
DBGPRINTF7(("LIST: enter, t1=%p, t2=%p\n", t1, t2));
if (t1 == NULL)
return t2;
if (t2 == NULL)
return t1;
return block(TLIST, t1, t2, NOWORDS);
}
static struct op *block(int type, struct op *t1, struct op *t2, char **wp)
{
struct op *t;
DBGPRINTF7(("BLOCK: enter, type=%d (%s)\n", type, T_CMD_NAMES[type]));
t = newtp();
t->op_type = type;
t->left = t1;
t->right = t2;
t->op_words = wp;
DBGPRINTF7(("BLOCK: inserted %p between %p and %p\n", t, t1, t2));
return t;
}
/* See if given string is a shell multiline (FOR, IF, etc) */
static int rlookup(char *n)
{
struct res {
char r_name[6];
int16_t r_val;
};
static const struct res restab[] = {
{ "for" , FOR },
{ "case" , CASE },
{ "esac" , ESAC },
{ "while", WHILE },
{ "do" , DO },
{ "done" , DONE },
{ "if" , IF },
{ "in" , IN },
{ "then" , THEN },
{ "else" , ELSE },
{ "elif" , ELIF },
{ "until", UNTIL },
{ "fi" , FI },
{ ";;" , BREAK },
{ "||" , LOGOR },
{ "&&" , LOGAND },
{ "{" , '{' },
{ "}" , '}' },
{ "." , DOT },
{ },
};
const struct res *rp;
DBGPRINTF7(("RLOOKUP: enter, n is %s\n", n));
for (rp = restab; rp->r_name[0]; rp++)
if (strcmp(rp->r_name, n) == 0) {
DBGPRINTF7(("RLOOKUP: match, returning %d\n", rp->r_val));
return rp->r_val; /* Return numeric code for shell multiline */
}
DBGPRINTF7(("RLOOKUP: NO match, returning 0\n"));
return 0; /* Not a shell multiline */
}
static struct op *newtp(void)
{
struct op *t;
t = (struct op *) tree(sizeof(*t));
memset(t, 0, sizeof(*t));
DBGPRINTF3(("NEWTP: allocated %p\n", t));
return t;
}
static struct op *namelist(struct op *t)
{
DBGPRINTF7(("NAMELIST: enter, t=%p, type %s, iolist=%p\n", t,
T_CMD_NAMES[t->op_type], iolist));
if (iolist) {
iolist = addword((char *) NULL, iolist);
t->ioact = copyio();
} else
t->ioact = NULL;
if (t->op_type != TCOM) {
if (t->op_type != TPAREN && t->ioact != NULL) {
t = block(TPAREN, t, NOBLOCK, NOWORDS);
t->ioact = t->left->ioact;
t->left->ioact = NULL;
}
return t;
}
word(NOWORD);
t->op_words = copyw();
return t;
}
static char **copyw(void)
{
char **wd;
wd = getwords(wdlist);
wdlist = NULL;
return wd;
}
static void word(char *cp)
{
wdlist = addword(cp, wdlist);
}
static struct ioword **copyio(void)
{
struct ioword **iop;
iop = (struct ioword **) getwords(iolist);
iolist = NULL;
return iop;
}
static struct ioword *io(int u, int f, char *cp)
{
struct ioword *iop;
iop = (struct ioword *) tree(sizeof(*iop));
iop->io_fd = u;
iop->io_flag = f;
iop->io_name = cp;
iolist = addword((char *) iop, iolist);
return iop;
}
static int yylex(int cf)
{
int c, c1;
int atstart;
c = peeksym;
if (c > 0) {
peeksym = 0;
if (c == '\n')
startl = 1;
return c;
}
nlseen = 0;
atstart = startl;
startl = 0;
yylval.i = 0;
global_env.linep = line;
/* MALAMO */
line[LINELIM - 1] = '\0';
loop:
while ((c = my_getc(0)) == ' ' || c == '\t') /* Skip whitespace */
continue;
switch (c) {
default:
if (any(c, "0123456789")) {
c1 = my_getc(0);
unget(c1);
if (c1 == '<' || c1 == '>') {
iounit = c - '0';
goto loop;
}
*global_env.linep++ = c;
c = c1;
}
break;
case '#': /* Comment, skip to next newline or End-of-string */
while ((c = my_getc(0)) != '\0' && c != '\n')
continue;
unget(c);
goto loop;
case 0:
DBGPRINTF5(("YYLEX: return 0, c=%d\n", c));
return c;
case '$':
DBGPRINTF9(("YYLEX: found $\n"));
*global_env.linep++ = c;
c = my_getc(0);
if (c == '{') {
c = collect(c, '}');
if (c != '\0')
return c;
goto pack;
}
break;
case '`':
case '\'':
case '"':
c = collect(c, c);
if (c != '\0')
return c;
goto pack;
case '|':
case '&':
case ';':
startl = 1;
/* If more chars process them, else return NULL char */
c1 = dual(c);
if (c1 != '\0')
return c1;
return c;
case '^':
startl = 1;
return '|';
case '>':
case '<':
diag(c);
return c;
case '\n':
nlseen++;
gethere();
startl = 1;
if (multiline || cf & CONTIN) {
if (interactive && global_env.iop <= iostack) {
#if ENABLE_FEATURE_EDITING
current_prompt = cprompt->value;
#else
prs(cprompt->value);
#endif
}
if (cf & CONTIN)
goto loop;
}
return c;
case '(':
case ')':
startl = 1;
return c;
}
unget(c);
pack:
while ((c = my_getc(0)) != '\0' && !any(c, "`$ '\"\t;&<>()|^\n")) {
if (global_env.linep >= elinep)
err("word too long");
else
*global_env.linep++ = c;
};
unget(c);
if (any(c, "\"'`$"))
goto loop;
*global_env.linep++ = '\0';
if (atstart) {
c = rlookup(line);
if (c != 0) {
startl = 1;
return c;
}
}
yylval.cp = strsave(line, areanum);
return WORD;
}
static int collect(int c, int c1)
{
char s[2];
DBGPRINTF8(("COLLECT: enter, c=%d, c1=%d\n", c, c1));
*global_env.linep++ = c;
while ((c = my_getc(c1)) != c1) {
if (c == 0) {
unget(c);
s[0] = c1;
s[1] = 0;
prs("no closing ");
yyerror(s);
return YYERRCODE;
}
if (interactive && c == '\n' && global_env.iop <= iostack) {
#if ENABLE_FEATURE_EDITING
current_prompt = cprompt->value;
#else
prs(cprompt->value);
#endif
}
*global_env.linep++ = c;
}
*global_env.linep++ = c;
DBGPRINTF8(("COLLECT: return 0, line is %s\n", line));
return 0;
}
/* "multiline commands" helper func */
/* see if next 2 chars form a shell multiline */
static int dual(int c)
{
char s[3];
char *cp = s;
DBGPRINTF8(("DUAL: enter, c=%d\n", c));
*cp++ = c; /* c is the given "peek" char */
*cp++ = my_getc(0); /* get next char of input */
*cp = '\0'; /* add EOS marker */
c = rlookup(s); /* see if 2 chars form a shell multiline */
if (c == 0)
unget(*--cp); /* String is not a shell multiline, put peek char back */
return c; /* String is multiline, return numeric multiline (restab) code */
}
static void diag(int ec)
{
int c;
DBGPRINTF8(("DIAG: enter, ec=%d\n", ec));
c = my_getc(0);
if (c == '>' || c == '<') {
if (c != ec)
zzerr();
yylval.i = (ec == '>' ? IOWRITE | IOCAT : IOHERE);
c = my_getc(0);
} else
yylval.i = (ec == '>' ? IOWRITE : IOREAD);
if (c != '&' || yylval.i == IOHERE)
unget(c);
else
yylval.i |= IODUP;
}
static char *tree(unsigned size)
{
char *t;
t = getcell(size);
if (t == NULL) {
DBGPRINTF2(("TREE: getcell(%d) failed!\n", size));
prs("command line too complicated\n");
fail();
/* NOTREACHED */
}
return t;
}
/* VARARGS1 */
/* ARGSUSED */
/* -------- exec.c -------- */
static struct op **find1case(struct op *t, const char *w)
{
struct op *t1;
struct op **tp;
char **wp;
char *cp;
if (t == NULL) {
DBGPRINTF3(("FIND1CASE: enter, t==NULL, returning.\n"));
return NULL;
}
DBGPRINTF3(("FIND1CASE: enter, t->op_type=%d (%s)\n", t->op_type,
T_CMD_NAMES[t->op_type]));
if (t->op_type == TLIST) {
tp = find1case(t->left, w);
if (tp != NULL) {
DBGPRINTF3(("FIND1CASE: found one to the left, returning tp=%p\n", tp));
return tp;
}
t1 = t->right; /* TPAT */
} else
t1 = t;
for (wp = t1->op_words; *wp;) {
cp = evalstr(*wp++, DOSUB);
if (cp && gmatch(w, cp)) {
DBGPRINTF3(("FIND1CASE: returning &t1->left= %p.\n",
&t1->left));
return &t1->left;
}
}
DBGPRINTF(("FIND1CASE: returning NULL\n"));
return NULL;
}
static struct op *findcase(struct op *t, const char *w)
{
struct op **tp;
tp = find1case(t, w);
return tp != NULL ? *tp : NULL;
}
/*
* execute tree
*/
static int execute(struct op *t, int *pin, int *pout, int no_fork)
{
struct op *t1;
volatile int i, rv, a;
const char *cp;
char **wp, **wp2;
struct var *vp;
struct op *outtree_save;
struct brkcon bc;
#if __GNUC__
/* Avoid longjmp clobbering */
(void) &wp;
#endif
if (t == NULL) {
DBGPRINTF4(("EXECUTE: enter, t==null, returning.\n"));
return 0;
}
DBGPRINTF(("EXECUTE: t=%p, t->op_type=%d (%s), t->op_words is %s\n", t,
t->op_type, T_CMD_NAMES[t->op_type],
((t->op_words == NULL) ? "NULL" : t->op_words[0])));
rv = 0;
a = areanum++;
wp2 = t->op_words;
wp = (wp2 != NULL)
? eval(wp2, t->op_type == TCOM ? DOALL : DOALL & ~DOKEY)
: NULL;
switch (t->op_type) {
case TDOT:
DBGPRINTF3(("EXECUTE: TDOT\n"));
outtree_save = outtree;
newfile(evalstr(t->op_words[0], DOALL));
t->left = dowholefile(TLIST /*, 0*/);
t->right = NULL;
outtree = outtree_save;
if (t->left)
rv = execute(t->left, pin, pout, /* no_fork: */ 0);
if (t->right)
rv = execute(t->right, pin, pout, /* no_fork: */ 0);
break;
case TPAREN:
rv = execute(t->left, pin, pout, /* no_fork: */ 0);
break;
case TCOM:
rv = forkexec(t, pin, pout, no_fork, wp);
break;
case TPIPE:
{
int pv[2];
rv = openpipe(pv);
if (rv < 0)
break;
pv[0] = remap(pv[0]);
pv[1] = remap(pv[1]);
(void) execute(t->left, pin, pv, /* no_fork: */ 0);
rv = execute(t->right, pv, pout, /* no_fork: */ 0);
}
break;
case TLIST:
(void) execute(t->left, pin, pout, /* no_fork: */ 0);
rv = execute(t->right, pin, pout, /* no_fork: */ 0);
break;
case TASYNC:
{
smallint hinteractive = interactive;
DBGPRINTF7(("EXECUTE: TASYNC clause, calling vfork()...\n"));
i = vfork();
if (i == 0) { /* child */
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
if (interactive)
signal(SIGTERM, SIG_DFL);
interactive = 0;
if (pin == NULL) {
close(0);
xopen(bb_dev_null, O_RDONLY);
}
_exit(execute(t->left, pin, pout, /* no_fork: */ 1));
}
interactive = hinteractive;
if (i != -1) {
setval(lookup("!"), putn(i));
closepipe(pin);
if (interactive) {
prs(putn(i));
prs("\n");
}
} else
rv = -1;
setstatus(rv);
}
break;
case TOR:
case TAND:
rv = execute(t->left, pin, pout, /* no_fork: */ 0);
t1 = t->right;
if (t1 != NULL && (rv == 0) == (t->op_type == TAND))
rv = execute(t1, pin, pout, /* no_fork: */ 0);
break;
case TFOR:
if (wp == NULL) {
wp = dolv + 1;
i = dolc;
if (i < 0)
i = 0;
} else {
i = -1;
while (*wp++ != NULL)
continue;
}
vp = lookup(t->str);
while (setjmp(bc.brkpt))
if (isbreak)
goto broken;
/* Restore areanum value. It may be incremented by execute()
* below, and then "continue" may jump back to setjmp above */
areanum = a + 1;
freearea(areanum + 1);
brkset(&bc);
for (t1 = t->left; i-- && *wp != NULL;) {
setval(vp, *wp++);
rv = execute(t1, pin, pout, /* no_fork: */ 0);
}
brklist = brklist->nextlev;
break;
case TWHILE:
case TUNTIL:
while (setjmp(bc.brkpt))
if (isbreak)
goto broken;
/* Restore areanum value. It may be incremented by execute()
* below, and then "continue" may jump back to setjmp above */
areanum = a + 1;
freearea(areanum + 1);
brkset(&bc);
t1 = t->left;
while ((execute(t1, pin, pout, /* no_fork: */ 0) == 0) == (t->op_type == TWHILE))
rv = execute(t->right, pin, pout, /* no_fork: */ 0);
brklist = brklist->nextlev;
break;
case TIF:
case TELIF:
if (t->right != NULL) {
rv = !execute(t->left, pin, pout, /* no_fork: */ 0) ?
execute(t->right->left, pin, pout, /* no_fork: */ 0) :
execute(t->right->right, pin, pout, /* no_fork: */ 0);
}
break;
case TCASE:
cp = evalstr(t->str, DOSUB | DOTRIM);
if (cp == NULL)
cp = "";
DBGPRINTF7(("EXECUTE: TCASE, t->str is %s, cp is %s\n",
((t->str == NULL) ? "NULL" : t->str),
((cp == NULL) ? "NULL" : cp)));
t1 = findcase(t->left, cp);
if (t1 != NULL) {
DBGPRINTF7(("EXECUTE: TCASE, calling execute(t=%p, t1=%p)...\n", t, t1));
rv = execute(t1, pin, pout, /* no_fork: */ 0);
DBGPRINTF7(("EXECUTE: TCASE, back from execute(t=%p, t1=%p)...\n", t, t1));
}
break;
case TBRACE:
/*
iopp = t->ioact;
if (i)
while (*iopp)
if (iosetup(*iopp++, pin!=NULL, pout!=NULL)) {
rv = -1;
break;
}
*/
if (rv >= 0) {
t1 = t->left;
if (t1) {
rv = execute(t1, pin, pout, /* no_fork: */ 0);
}
}
break;
};
broken:
// Restoring op_words is most likely not needed now: see comment in forkexec()
// (also take a look at exec builtin (doexec) - it touches t->op_words)
t->op_words = wp2;
isbreak = 0;
freehere(areanum);
freearea(areanum);
areanum = a;
if (interactive && intr) {
closeall();
fail();
}
i = trapset;
if (i != 0) {
trapset = 0;
runtrap(i);
}
DBGPRINTF(("EXECUTE: returning from t=%p, rv=%d\n", t, rv));
return rv;
}
static builtin_func_ptr inbuilt(const char *s)
{
const struct builtincmd *bp;
for (bp = builtincmds; bp->name; bp++)
if (strcmp(bp->name, s) == 0)
return bp->builtinfunc;
return NULL;
}
static int forkexec(struct op *t, int *pin, int *pout, int no_fork, char **wp)
{
pid_t newpid;
int i;
builtin_func_ptr bltin = NULL;
const char *bltin_name = NULL;
const char *cp;
struct ioword **iopp;
int resetsig;
char **owp;
int forked;
int *hpin = pin;
int *hpout = pout;
char *hwp;
smallint hinteractive;
smallint hintr;
smallint hexecflg;
struct brkcon *hbrklist;
#if __GNUC__
/* Avoid longjmp clobbering */
(void) &pin;
(void) &pout;
(void) &wp;
(void) &bltin;
(void) &cp;
(void) &resetsig;
(void) &owp;
#endif
DBGPRINTF(("FORKEXEC: t=%p, pin %p, pout %p, no_fork %d\n", t, pin,
pout, no_fork));
DBGPRINTF7(("FORKEXEC: t->op_words is %s\n",
((t->op_words == NULL) ? "NULL" : t->op_words[0])));
owp = wp;
resetsig = 0;
if (t->op_type == TCOM) {
while (*wp++ != NULL)
continue;
cp = *wp;
/* strip all initial assignments */
/* FIXME: not correct wrt PATH=yyy command etc */
if (FLAG['x']) {
DBGPRINTF9(("FORKEXEC: echo'ing, cp=%p, wp=%p, owp=%p\n",
cp, wp, owp));
echo(cp ? wp : owp);
}
if (cp == NULL) {
if (t->ioact == NULL) {
while ((cp = *owp++) != NULL && assign(cp, COPYV))
continue;
DBGPRINTF(("FORKEXEC: returning setstatus(0)\n"));
return setstatus(0);
}
} else { /* cp != NULL */
bltin_name = cp;
bltin = inbuilt(cp);
}
}
forked = 0;
// We were pointing t->op_words to temporary (expanded) arg list:
// t->op_words = wp;
// and restored it later (in execute()), but "break"
// longjmps away (at "Run builtin" below), leaving t->op_words clobbered!
// See http://bugs.busybox.net/view.php?id=846.
// Now we do not touch t->op_words, but separately pass wp as param list
// to builtins
DBGPRINTF(("FORKEXEC: bltin %p, no_fork %d, owp %p\n", bltin,
no_fork, owp));
/* Don't fork if it is a lone builtin (not in pipe)
* OR we are told to _not_ fork */
if ((!bltin || pin || pout) /* not lone bltin AND */
&& !no_fork /* not told to avoid fork */
) {
/* Save values in case child alters them after vfork */
hpin = pin;
hpout = pout;
hwp = *wp;
hinteractive = interactive;
hintr = intr;
hbrklist = brklist;
hexecflg = execflg;
DBGPRINTF3(("FORKEXEC: calling vfork()...\n"));
newpid = vfork();
if (newpid == -1) {
DBGPRINTF(("FORKEXEC: ERROR, can't vfork()!\n"));
return -1;
}
if (newpid > 0) { /* Parent */
/* Restore values */
pin = hpin;
pout = hpout;
*wp = hwp;
interactive = hinteractive;
intr = hintr;
brklist