//config: default y
//config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
//config:
+//config:config ASH_BASH_SOURCE_CURDIR
+//config: bool "'source' and '.' builtins search current directory after $PATH"
+//config: default n # do not encourage non-standard behavior
+//config: depends on ASH_BASH_COMPAT
+//config: help
+//config: This is not compliant with standards. Avoid if possible.
+//config:
+//config:config ASH_BASH_NOT_FOUND_HOOK
+//config: bool "command_not_found_handle hook support"
+//config: default y
+//config: depends on ASH_BASH_COMPAT
+//config: help
+//config: Enable support for the 'command_not_found_handle' hook function,
+//config: from GNU bash, which allows for alternative command not found
+//config: handling.
+//config:
//config:config ASH_JOB_CONTROL
//config: bool "Job control"
//config: default y
#define JOBS ENABLE_ASH_JOB_CONTROL
-#include <setjmp.h>
#include <fnmatch.h>
#include <sys/times.h>
#include <sys/utsname.h> /* for setting $HOSTNAME */
#define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
#define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
#define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
-/* [[ EXPR ]] */
+/* BASH_TEST2: [[ EXPR ]]
+ * Status of [[ support:
+ * We replace && and || with -a and -o
+ * TODO:
+ * singleword+noglob expansion:
+ * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
+ * [[ /bin/n* ]]; echo 0:$?
+ * -a/-o are not AND/OR ops! (they are just strings)
+ * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
+ * = is glob match operator, not equality operator: STR = GLOB
+ * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
+ * == same as =
+ * add =~ regex match operator: STR =~ REGEX
+ */
#define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
#define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
#define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
#endif
+#ifndef F_DUPFD_CLOEXEC
+# define F_DUPFD_CLOEXEC F_DUPFD
+#endif
+#ifndef O_CLOEXEC
+# define O_CLOEXEC 0
+#endif
#ifndef PIPE_BUF
# define PIPE_BUF 4096 /* amount of buffering in a pipe */
#endif
# error "Do not even bother, ash will not run on NOMMU machine"
#endif
+/* We use a trick to have more optimized code (fewer pointer reloads):
+ * ash.c: extern struct globals *const ash_ptr_to_globals;
+ * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
+ * This way, compiler in ash.c knows the pointer can not change.
+ *
+ * However, this may break on weird arches or toolchains. In this case,
+ * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
+ * this optimization.
+ */
+#ifndef BB_GLOBAL_CONST
+# define BB_GLOBAL_CONST const
+#endif
+
/* ============ Hash table sizes. Configurable. */
/* shell level: 0 for the main shell, 1 for its children, and so on */
int shlvl;
#define rootshell (!shlvl)
+ int errlinno;
+
char *minusc; /* argument to -c option */
char *curdir; // = nullstr; /* current working directory */
#endif
pid_t backgndpid; /* pid of last background process */
};
-extern struct globals_misc *const ash_ptr_to_globals_misc;
+extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
#define G_misc (*ash_ptr_to_globals_misc)
#define exitstatus (G_misc.exitstatus )
#define back_exitstatus (G_misc.back_exitstatus )
#define job_warning (G_misc.job_warning)
#define rootpid (G_misc.rootpid )
#define shlvl (G_misc.shlvl )
+#define errlinno (G_misc.errlinno )
#define minusc (G_misc.minusc )
#define curdir (G_misc.curdir )
#define physdir (G_misc.physdir )
struct ncmd {
smallint type; /* Nxxxx */
+ int linno;
union node *assign;
union node *args;
union node *redirect;
struct nredir {
smallint type;
+ int linno;
union node *n;
union node *redirect;
};
struct nfor {
smallint type;
+ int linno;
union node *args;
union node *body;
char *var;
struct ncase {
smallint type;
+ int linno;
union node *expr;
union node *cases;
};
union node *body;
};
+struct ndefun {
+ smallint type;
+ int linno;
+ char *text;
+ union node *body;
+};
+
struct narg {
smallint type;
union node *next;
struct nfor nfor;
struct ncase ncase;
struct nclist nclist;
+ struct ndefun ndefun;
struct narg narg;
struct nfile nfile;
struct ndup ndup;
static struct parsefile basepf; /* top level input file */
static struct parsefile *g_parsefile = &basepf; /* current input file */
-static int startlinno; /* line # where last token started */
static char *commandname; /* currently executing command */
if (strcmp(arg0, commandname))
fprintf(stderr, "%s: ", commandname);
if (!iflag || g_parsefile->pf_fd > 0)
- fprintf(stderr, "line %d: ", startlinno);
+ fprintf(stderr, "line %d: ", errlinno);
}
vfprintf(stderr, msg, ap);
newline_and_flush(stderr);
static void
raise_error_syntax(const char *msg)
{
+ errlinno = g_parsefile->linno;
ash_msg_and_raise_error("syntax error: %s", msg);
/* NOTREACHED */
}
size_t g_stacknleft; // = MINSIZE;
struct stack_block stackbase;
};
-extern struct globals_memstack *const ash_ptr_to_globals_memstack;
+extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
#define G_memstack (*ash_ptr_to_globals_memstack)
#define g_stackp (G_memstack.g_stackp )
#define g_stacknxt (G_memstack.g_stacknxt )
return memcpy(stalloc(len), p, len);
}
-static inline void
+static ALWAYS_INLINE void
grabstackblock(size_t len)
{
stalloc(len);
#if ENABLE_ASH_GETOPTS
{ VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
#endif
+ { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
#if ENABLE_ASH_RANDOM_SUPPORT
{ VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
#endif
int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
struct var *vartab[VTABSIZE];
struct var varinit[ARRAY_SIZE(varinit_data)];
+ int lineno;
+ char linenovar[sizeof("LINENO=") + sizeof(int)*3];
};
-extern struct globals_var *const ash_ptr_to_globals_var;
+extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
#define G_var (*ash_ptr_to_globals_var)
#define shellparam (G_var.shellparam )
//#define redirlist (G_var.redirlist )
#define preverrout_fd (G_var.preverrout_fd)
#define vartab (G_var.vartab )
#define varinit (G_var.varinit )
-#define INIT_G_var() do { \
- unsigned i; \
- (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
- barrier(); \
- for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
- varinit[i].flags = varinit_data[i].flags; \
- varinit[i].var_text = varinit_data[i].var_text; \
- varinit[i].var_func = varinit_data[i].var_func; \
- } \
-} while (0)
-
+#define lineno (G_var.lineno )
+#define linenovar (G_var.linenovar )
#define vifs varinit[0]
#if ENABLE_ASH_MAIL
# define vmail (&vifs)[1]
#define vps4 (&vps2)[1]
#if ENABLE_ASH_GETOPTS
# define voptind (&vps4)[1]
+# define vlineno (&voptind)[1]
# if ENABLE_ASH_RANDOM_SUPPORT
-# define vrandom (&voptind)[1]
+# define vrandom (&vlineno)[1]
# endif
#else
+# define vlineno (&vps4)[1]
# if ENABLE_ASH_RANDOM_SUPPORT
-# define vrandom (&vps4)[1]
+# define vrandom (&vlineno)[1]
# endif
#endif
+#define INIT_G_var() do { \
+ unsigned i; \
+ (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
+ barrier(); \
+ for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
+ varinit[i].flags = varinit_data[i].flags; \
+ varinit[i].var_text = varinit_data[i].var_text; \
+ varinit[i].var_func = varinit_data[i].var_func; \
+ } \
+ strcpy(linenovar, "LINENO="); \
+ vlineno.var_text = linenovar; \
+} while (0)
/*
* The following macros access the values of the above variables.
if (v->flags & VDYNAMIC)
v->var_func(NULL);
#endif
- if (!(v->flags & VUNSET))
+ if (!(v->flags & VUNSET)) {
+ if (v == &vlineno && v->var_text == linenovar) {
+ fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
+ }
return var_end(v->var_text);
+ }
}
return NULL;
}
goto out;
}
/* fd is a tty at this point */
- fd = fcntl(fd, F_DUPFD, 10);
+ fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
close(ofd);
if (fd < 0)
goto out; /* F_DUPFD failed */
- close_on_exec_on(fd);
+ if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
+ close_on_exec_on(fd);
while (1) { /* while we are in the background */
pgrp = tcgetpgrp(fd);
if (pgrp < 0) {
p = "; done";
goto dodo;
case NDEFUN:
- cmdputs(n->narg.text);
+ cmdputs(n->ndefun.text);
p = "() { ... }";
goto dotail2;
case NCMD:
f = open(fname, O_WRONLY, 0666);
if (f < 0)
goto ecreate;
- if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
+ if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
close(f);
errno = EEXIST;
goto ecreate;
int newfd;
int err;
- newfd = fcntl(from, F_DUPFD, 10);
+ newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
err = newfd < 0 ? errno : 0;
if (err != EBADF) {
if (err)
ash_msg_and_raise_perror("%d", from);
close(from);
- fcntl(newfd, F_SETFD, FD_CLOEXEC);
+ if (F_DUPFD_CLOEXEC == F_DUPFD)
+ close_on_exec_on(newfd);
}
return newfd;
return newfd;
}
static int
-fcntl_F_DUPFD(int fd, int avoid_fd)
+dup_CLOEXEC(int fd, int avoid_fd)
{
int newfd;
repeat:
- newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
- if (newfd < 0) {
+ newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
+ if (newfd >= 0) {
+ if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
+ close_on_exec_on(newfd);
+ } else { /* newfd < 0 */
if (errno == EBUSY)
goto repeat;
if (errno == EINTR)
{
int newfd;
repeat:
- newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
+ newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
if (newfd < 0) {
if (errno == EBUSY)
goto repeat;
return fd;
ash_msg_and_raise_perror("%d", newfd);
}
- fcntl(newfd, F_SETFD, FD_CLOEXEC);
+ if (F_DUPFD_CLOEXEC == F_DUPFD)
+ close_on_exec_on(newfd);
close(fd);
return newfd;
}
for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
/* If we collide with an already moved fd... */
if (fd == sq->two_fd[i].moved_to) {
- new_fd = fcntl_F_DUPFD(fd, avoid_fd);
+ new_fd = dup_CLOEXEC(fd, avoid_fd);
sq->two_fd[i].moved_to = new_fd;
TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
if (new_fd < 0) /* what? */
}
/* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
- new_fd = fcntl_F_DUPFD(fd, avoid_fd);
+ new_fd = dup_CLOEXEC(fd, avoid_fd);
TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
if (new_fd < 0) {
if (errno != EBADF)
* performs globbing, and thus diverges from what we do).
*/
#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
-#define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
-#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
-#define EXP_WORD 0x80 /* expand word in parameter expansion */
-#define EXP_QUOTED 0x100 /* expand word in double quotes */
+#define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
+#define EXP_WORD 0x40 /* expand word in parameter expansion */
+#define EXP_QUOTED 0x80 /* expand word in double quotes */
/*
* rmescape() flags
*/
#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
/* Add CTLESC when necessary. */
-#define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
+#define QUOTES_ESC (EXP_FULL | EXP_CASE)
/* Do not skip NUL characters. */
#define QUOTES_KEEPNUL EXP_TILDE
realifs = ifsset() ? ifsval() : defifs;
ifsp = &ifsfirst;
do {
+ int afternul;
+
p = string + ifsp->begoff;
+ afternul = nulonly;
nulonly = ifsp->nulonly;
ifs = nulonly ? nullstr : realifs;
ifsspc = 0;
p++;
continue;
}
- if (!nulonly)
+ if (!(afternul || nulonly))
ifsspc = (strchr(defifs, *p) != NULL);
/* Ignore IFS whitespace at start */
if (q == start && ifsspc) {
IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
char *p, *q, *r;
- unsigned inquotes;
unsigned protect_against_glob;
unsigned globbing;
}
}
- inquotes = 0;
globbing = flag & RMESCAPE_GLOB;
protect_against_glob = globbing;
while (*p) {
if ((unsigned char)*p == CTLQUOTEMARK) {
-// Note: both inquotes and protect_against_glob only affect whether
+// Note: protect_against_glob only affect whether
// CTLESC,<ch> gets converted to <ch> or to \<ch>
- inquotes = ~inquotes;
p++;
protect_against_glob = globbing;
continue;
}
+ if (*p == '\\') {
+ /* naked back slash */
+ protect_against_glob = 0;
+ goto copy;
+ }
if ((unsigned char)*p == CTLESC) {
p++;
#if DEBUG
if (*p == '*'
|| *p == '?'
|| *p == '['
- || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
- || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
- || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
- || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
+ || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
+ || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
+ || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
+ || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
/* Some libc support [^negate], that's why "^" also needs love */
- || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
+ || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
) {
*q++ = '\\';
}
}
- } else if (*p == '\\' && !inquotes) {
- /* naked back slash */
- protect_against_glob = 0;
- goto copy;
}
#if BASH_PATTERN_SUBST
else if (slash_position && p == str + *slash_position) {
case CTLENDVAR: /* ??? */
goto breakloop;
case CTLQUOTEMARK:
- inquotes ^= EXP_QUOTED;
/* "$@" syntax adherence hack */
- if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
- p = evalvar(p + 1, flags | inquotes) + 1;
+ if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
+ p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
goto start;
}
+ inquotes ^= EXP_QUOTED;
addquote:
if (flags & QUOTES_ESC) {
p--;
case CTLESC:
startloc++;
length++;
-
- /*
- * Quoted parameter expansion pattern: remove quote
- * unless inside inner quotes or we have a literal
- * backslash.
- */
- if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
- EXP_QPAT && *p != '\\')
- break;
-
goto addquote;
case CTLVAR:
TRACE(("argstr: evalvar('%s')\n", p));
}
#endif
argstr_flags = EXP_TILDE;
- if (subtype != VSASSIGN && subtype != VSQUESTION)
- argstr_flags |= (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE);
+ if (subtype != VSASSIGN
+ && subtype != VSQUESTION
+#if BASH_SUBSTR
+ && subtype != VSSUBSTR
+#endif
+ ) {
+ /* EXP_CASE keeps CTLESC's */
+ argstr_flags = EXP_TILDE | EXP_CASE;
+ }
argstr(p, argstr_flags);
+ //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
#if BASH_PATTERN_SUBST
slash_pos = -1;
if (repl) {
slash_pos = expdest - ((char *)stackblock() + strloc);
STPUTC('/', expdest);
- argstr(repl + 1, argstr_flags);
+ //bb_error_msg("repl+1:'%s'", repl + 1);
+ argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
*repl = '/';
}
#endif
case '-':
expdest = makestrspace(NOPTS, expdest);
for (i = NOPTS - 1; i >= 0; i--) {
- if (optlist[i]) {
+ if (optlist[i] && optletters(i)) {
USTPUTC(optletters(i), expdest);
len++;
}
p = strpbrk(p, chars);
if (!p)
break;
- switch ((unsigned char) *p) {
+ switch ((unsigned char)*p) {
case CTLQUOTEMARK:
for (;;) {
p++;
- if (*p == CTLQUOTEMARK)
+ if ((unsigned char)*p == CTLQUOTEMARK)
break;
- if (*p == CTLESC)
+ if ((unsigned char)*p == CTLESC)
p++;
if (*p == '\0') /* huh? */
return 0;
/*
* Do metacharacter (i.e. *, ?, [...]) expansion.
*/
+typedef struct exp_t {
+ char *dir;
+ unsigned dir_max;
+} exp_t;
static void
-expmeta(char *expdir, char *enddir, char *name)
+expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
{
+#define expdir exp->dir
+#define expdir_max exp->dir_max
+ char *enddir = expdir + expdir_len;
char *p;
const char *cp;
char *start;
}
}
if (metaflag == 0) { /* we've reached the end of the file name */
- if (enddir != expdir)
- metaflag++;
+ if (!expdir_len)
+ return;
p = name;
do {
if (*p == '\\')
p++;
*enddir++ = *p;
} while (*p++);
- if (metaflag == 0 || lstat(expdir, &statb) >= 0)
+ if (lstat(expdir, &statb) == 0)
addfname(expdir);
return;
}
*enddir++ = *p++;
} while (p < start);
}
- if (enddir == expdir) {
+ *enddir = '\0';
+ cp = expdir;
+ expdir_len = enddir - cp;
+ if (!expdir_len)
cp = ".";
- } else if (enddir == expdir + 1 && *expdir == '/') {
- cp = "/";
- } else {
- cp = expdir;
- enddir[-1] = '\0';
- }
dirp = opendir(cp);
if (dirp == NULL)
return;
- if (enddir != expdir)
- enddir[-1] = '/';
if (*endname == 0) {
atend = 1;
} else {
*endname = '\0';
endname += esc + 1;
}
+ name_len -= endname - name;
matchdot = 0;
p = start;
if (*p == '\\')
strcpy(enddir, dp->d_name);
addfname(expdir);
} else {
- for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
- continue;
- p[-1] = '/';
- expmeta(expdir, p, endname);
+ unsigned offset;
+ unsigned len;
+
+ p = stpcpy(enddir, dp->d_name);
+ *p = '/';
+
+ offset = p - expdir + 1;
+ len = offset + name_len + NAME_MAX;
+ if (len > expdir_max) {
+ len += PATH_MAX;
+ expdir = ckrealloc(expdir, len);
+ expdir_max = len;
+ }
+
+ expmeta(exp, endname, name_len, offset);
+ enddir = expdir + expdir_len;
}
}
}
closedir(dirp);
if (!atend)
endname[-esc - 1] = esc ? '\\' : '/';
+#undef expdir
+#undef expdir_max
}
static struct strlist *
/* TODO - EXP_REDIR */
while (str) {
- char *expdir;
+ exp_t exp;
struct strlist **savelastp;
struct strlist *sp;
char *p;
+ unsigned len;
if (fflag)
goto nometa;
INT_OFF;
p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
- {
- int i = strlen(str->text);
-//BUGGY estimation of how long expanded name can be
- expdir = ckmalloc(i < 2048 ? 2048 : i+1);
- }
- expmeta(expdir, expdir, p);
- free(expdir);
+ len = strlen(p);
+ exp.dir_max = len + PATH_MAX;
+ exp.dir = ckmalloc(exp.dir_max);
+
+ expmeta(&exp, p, len, 0);
+ free(exp.dir);
if (p != str->text)
free(p);
INT_ON;
funcblocksize = calcsize(funcblocksize, n->nclist.next);
break;
case NDEFUN:
+ funcblocksize = calcsize(funcblocksize, n->ndefun.body);
+ funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
+ break;
case NARG:
funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
new->ncmd.redirect = copynode(n->ncmd.redirect);
new->ncmd.args = copynode(n->ncmd.args);
new->ncmd.assign = copynode(n->ncmd.assign);
+ new->ncmd.linno = n->ncmd.linno;
break;
case NPIPE:
new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
case NSUBSHELL:
new->nredir.redirect = copynode(n->nredir.redirect);
new->nredir.n = copynode(n->nredir.n);
+ new->nredir.linno = n->nredir.linno;
break;
case NAND:
case NOR:
new->nfor.var = nodeckstrdup(n->nfor.var);
new->nfor.body = copynode(n->nfor.body);
new->nfor.args = copynode(n->nfor.args);
+ new->nfor.linno = n->nfor.linno;
break;
case NCASE:
new->ncase.cases = copynode(n->ncase.cases);
new->ncase.expr = copynode(n->ncase.expr);
+ new->ncase.linno = n->ncase.linno;
break;
case NCLIST:
new->nclist.body = copynode(n->nclist.body);
new->nclist.next = copynode(n->nclist.next);
break;
case NDEFUN:
+ new->ndefun.body = copynode(n->ndefun.body);
+ new->ndefun.text = nodeckstrdup(n->ndefun.text);
+ new->ndefun.linno = n->ndefun.linno;
+ break;
case NARG:
new->narg.backquote = copynodelist(n->narg.backquote);
new->narg.text = nodeckstrdup(n->narg.text);
INT_OFF;
entry.cmdtype = CMDFUNCTION;
entry.u.func = copyfunc(func);
- addcmdentry(func->narg.text, &entry);
+ addcmdentry(func->ndefun.text, &entry);
INT_ON;
}
#define SKIPFUNC (1 << 2)
static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
static int skipcount; /* number of levels to skip */
-static int funcnest; /* depth of function calls */
static int loopnest; /* current loop nesting level */
+static int funcline; /* starting line number of current function, or 0 if not in a function */
/* Forward decl way out to parsing code - dotrap needs it */
static int evalstring(char *s, int flags);
status = !evaltree(n->nnot.com, EV_TESTED);
goto setstatus;
case NREDIR:
+ errlinno = lineno = n->nredir.linno;
+ if (funcline)
+ lineno -= funcline - 1;
expredir(n->nredir.redirect);
pushredir(n->nredir.redirect);
status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
struct stackmark smark;
int status = 0;
+ errlinno = lineno = n->ncase.linno;
+ if (funcline)
+ lineno -= funcline - 1;
+
setstackmark(&smark);
arglist.list = NULL;
arglist.lastp = &arglist.list;
struct stackmark smark;
int status = 0;
+ errlinno = lineno = n->ncase.linno;
+ if (funcline)
+ lineno -= funcline - 1;
+
setstackmark(&smark);
arglist.list = NULL;
arglist.lastp = &arglist.list;
int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
int status;
+ errlinno = lineno = n->nredir.linno;
+ if (funcline)
+ lineno -= funcline - 1;
+
expredir(n->nredir.redirect);
if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
goto nofork;
struct jmploc *volatile savehandler;
struct jmploc jmploc;
int e;
+ int savefuncline;
saveparam = shellparam;
+ savefuncline = funcline;
savehandler = exception_handler;
e = setjmp(jmploc.loc);
if (e) {
exception_handler = &jmploc;
shellparam.malloced = 0;
func->count++;
- funcnest++;
+ funcline = func->n.ndefun.linno;
INT_ON;
shellparam.nparam = argc - 1;
shellparam.p = argv + 1;
shellparam.optoff = -1;
#endif
pushlocalvars();
- evaltree(func->n.narg.next, flags & EV_TESTED);
+ evaltree(func->n.ndefun.body, flags & EV_TESTED);
poplocalvars(0);
funcdone:
INT_OFF;
- funcnest--;
+ funcline = savefuncline;
freefunc(func);
freeparam(&shellparam);
shellparam = saveparam;
char **nargv;
smallint cmd_is_exec;
+ errlinno = lineno = cmd->ncmd.linno;
+ if (funcline)
+ lineno -= funcline - 1;
+
/* First expand the arguments. */
TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
setstackmark(&smark);
*nargv = NULL;
lastarg = NULL;
- if (iflag && funcnest == 0 && argc > 0)
+ if (iflag && funcline == 0 && argc > 0)
lastarg = nargv[-1];
expredir(cmd->ncmd.redirect);
switch (cmdentry.cmdtype) {
default: {
-#if ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1
+#if ENABLE_FEATURE_SH_STANDALONE \
+ && ENABLE_FEATURE_SH_NOFORK \
+ && NUM_APPLETS > 1
/* (1) BUG: if variables are set, we need to fork, or save/restore them
* around run_nofork_applet() call.
* (2) Should this check also be done in forkshell()?
return c;
}
+struct synstack {
+ smalluint syntax;
+ uint8_t innerdq :1;
+ uint8_t varpushed :1;
+ uint8_t dblquote :1;
+ int varnest; /* levels of variables expansion */
+ int dqvarnest; /* levels of variables expansion within double quotes */
+ int parenlevel; /* levels of parens in arithmetic */
+ struct synstack *prev;
+ struct synstack *next;
+};
+
+static void
+synstack_push(struct synstack **stack, struct synstack *next, int syntax)
+{
+ memset(next, 0, sizeof(*next));
+ next->syntax = syntax;
+ next->next = *stack;
+ (*stack)->prev = next;
+ *stack = next;
+}
+
+static ALWAYS_INLINE void
+synstack_pop(struct synstack **stack)
+{
+ *stack = (*stack)->next;
+}
+
/*
* To handle the "." command, a stack of input files is used. Pushfile
* adds a new entry to the stack and popfile restores the previous level.
int fd;
INT_OFF;
- fd = open(fname, O_RDONLY);
+ fd = open(fname, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
if (flags & INPUT_NOFILE_OK)
goto out;
}
if (fd < 10)
fd = savefd(fd);
- else
+ else if (O_CLOEXEC == 0) /* old libc */
close_on_exec_on(fd);
+
setinputfd(fd, flags & INPUT_PUSH_FILE);
out:
INT_ON;
union node *vars, **vpp;
union node **rpp, *redir;
int savecheckkwd;
+ int savelinno;
#if BASH_TEST2
smallint double_brackets_flag = 0;
#endif
rpp = &redir;
savecheckkwd = CHKALIAS;
+ savelinno = g_parsefile->linno;
for (;;) {
int t;
checkkwd = savecheckkwd;
case TLP:
function_flag = 0;
break;
+# if BASH_TEST2
case TWORD:
if (strcmp("[[", wordtext) == 0)
goto do_func;
/* fall through */
+# endif
default:
raise_error_unexpected_syntax(-1);
}
}
n->type = NDEFUN;
checkkwd = CHKNL | CHKKWD | CHKALIAS;
- n->narg.next = parse_command();
+ n->ndefun.text = n->narg.text;
+ n->ndefun.linno = g_parsefile->linno;
+ n->ndefun.body = parse_command();
return n;
}
IF_BASH_FUNCTION(function_flag = 0;)
*vpp = NULL;
*rpp = NULL;
n = stzalloc(sizeof(struct ncmd));
- n->type = NCMD;
+ if (NCMD != 0)
+ n->type = NCMD;
+ n->ncmd.linno = savelinno;
n->ncmd.args = args;
n->ncmd.assign = vars;
n->ncmd.redirect = redir;
union node *redir, **rpp;
union node **rpp2;
int t;
+ int savelinno;
redir = NULL;
rpp2 = &redir;
+ savelinno = g_parsefile->linno;
+
switch (readtoken()) {
default:
raise_error_unexpected_syntax(-1);
raise_error_syntax("bad for loop variable");
n1 = stzalloc(sizeof(struct nfor));
n1->type = NFOR;
+ n1->nfor.linno = savelinno;
n1->nfor.var = wordtext;
checkkwd = CHKNL | CHKKWD | CHKALIAS;
if (readtoken() == TIN) {
case TCASE:
n1 = stzalloc(sizeof(struct ncase));
n1->type = NCASE;
+ n1->ncase.linno = savelinno;
if (readtoken() != TWORD)
raise_error_unexpected_syntax(TWORD);
n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
case TLP:
n1 = stzalloc(sizeof(struct nredir));
n1->type = NSUBSHELL;
+ n1->nredir.linno = savelinno;
n1->nredir.n = list(0);
/*n1->nredir.redirect = NULL; - stzalloc did it */
t = TRP;
if (n1->type != NSUBSHELL) {
n2 = stzalloc(sizeof(struct nredir));
n2->type = NREDIR;
+ n2->nredir.linno = savelinno;
n2->nredir.n = n1;
n1 = n2;
}
size_t len;
struct nodelist *bqlist;
smallint quotef;
- smallint dblquote;
smallint oldstyle;
- IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
smallint pssyntax; /* we are expanding a prompt string */
- int varnest; /* levels of variables expansion */
- IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
- IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
- int dqvarnest; /* levels of variables expansion within double quotes */
-
IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
+ /* syntax stack */
+ struct synstack synbase = { };
+ struct synstack *synstack = &synbase;
- startlinno = g_parsefile->linno;
- bqlist = NULL;
- quotef = 0;
- IF_FEATURE_SH_MATH(prevsyntax = 0;)
#if ENABLE_ASH_EXPAND_PRMT
pssyntax = (syntax == PSSYNTAX);
if (pssyntax)
#else
pssyntax = 0; /* constant */
#endif
- dblquote = (syntax == DQSYNTAX);
- varnest = 0;
- IF_FEATURE_SH_MATH(arinest = 0;)
- IF_FEATURE_SH_MATH(parenlevel = 0;)
- dqvarnest = 0;
+ synstack->syntax = syntax;
+
+ if (syntax == DQSYNTAX)
+ synstack->dblquote = 1;
+ quotef = 0;
+ bqlist = NULL;
STARTSTACKSTR(out);
loop:
CHECKEND(); /* set c to PEOF if at end of here document */
for (;;) { /* until end of line or end of word */
CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
- switch (SIT(c, syntax)) {
+ switch (SIT(c, synstack->syntax)) {
case CNL: /* '\n' */
- if (syntax == BASESYNTAX)
+ if (synstack->syntax == BASESYNTAX
+ && !synstack->varnest
+ ) {
goto endword; /* exit outer loop */
+ }
USTPUTC(c, out);
nlprompt();
c = pgetc();
if (c & 0x100) {
/* Unknown escape. Encode as '\z' */
c = (unsigned char)c;
- if (eofmark == NULL || dblquote)
+ if (eofmark == NULL || synstack->dblquote)
USTPUTC(CTLESC, out);
USTPUTC('\\', out);
}
}
#endif
- if (eofmark == NULL || dblquote)
+ if (!eofmark || synstack->dblquote || synstack->varnest)
USTPUTC(CTLESC, out);
USTPUTC(c, out);
break;
USTPUTC(CTLESC, out);
USTPUTC('\\', out);
}
- /* Backslash is retained if we are in "str" and next char isn't special */
- if (dblquote
+ /* Backslash is retained if we are in "str"
+ * and next char isn't dquote-special.
+ */
+ if (synstack->dblquote
&& c != '\\'
&& c != '`'
&& c != '$'
- && (c != '"' || eofmark != NULL)
+ && (c != '"' || (eofmark != NULL && !synstack->varnest))
+ && (c != '}' || !synstack->varnest)
) {
+ USTPUTC(CTLESC, out); /* protect '\' from glob */
USTPUTC('\\', out);
}
USTPUTC(CTLESC, out);
}
break;
case CSQUOTE:
- syntax = SQSYNTAX;
+ synstack->syntax = SQSYNTAX;
quotemark:
if (eofmark == NULL) {
USTPUTC(CTLQUOTEMARK, out);
}
break;
case CDQUOTE:
- syntax = DQSYNTAX;
- dblquote = 1;
+ synstack->syntax = DQSYNTAX;
+ synstack->dblquote = 1;
+ toggledq:
+ if (synstack->varnest)
+ synstack->innerdq ^= 1;
goto quotemark;
case CENDQUOTE:
IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
- if (eofmark != NULL && varnest == 0) {
+ if (eofmark != NULL && synstack->varnest == 0) {
USTPUTC(c, out);
- } else {
- if (dqvarnest == 0) {
- syntax = BASESYNTAX;
- dblquote = 0;
- }
- quotef = 1;
- goto quotemark;
+ break;
}
- break;
+
+ if (synstack->dqvarnest == 0) {
+ synstack->syntax = BASESYNTAX;
+ synstack->dblquote = 0;
+ }
+
+ quotef = 1;
+
+ if (c == '"')
+ goto toggledq;
+
+ goto quotemark;
case CVAR: /* '$' */
PARSESUB(); /* parse substitution */
break;
case CENDVAR: /* '}' */
- if (varnest > 0) {
- varnest--;
- if (dqvarnest > 0) {
- dqvarnest--;
- }
+ if (!synstack->innerdq && synstack->varnest > 0) {
+ if (!--synstack->varnest && synstack->varpushed)
+ synstack_pop(&synstack);
+ else if (synstack->dqvarnest > 0)
+ synstack->dqvarnest--;
c = CTLENDVAR;
}
USTPUTC(c, out);
break;
#if ENABLE_FEATURE_SH_MATH
case CLP: /* '(' in arithmetic */
- parenlevel++;
+ synstack->parenlevel++;
USTPUTC(c, out);
break;
case CRP: /* ')' in arithmetic */
- if (parenlevel > 0) {
- parenlevel--;
+ if (synstack->parenlevel > 0) {
+ synstack->parenlevel--;
} else {
if (pgetc_eatbnl() == ')') {
c = CTLENDARI;
- if (--arinest == 0) {
- syntax = prevsyntax;
- }
+ synstack_pop(&synstack);
} else {
/*
* unbalanced parens
break;
#endif
case CBQUOTE: /* '`' */
+ if (checkkwd & CHKEOFMARK) {
+ quotef = 1;
+ USTPUTC('`', out);
+ break;
+ }
+
PARSEBACKQOLD();
break;
case CENDFILE:
case CIGN:
break;
default:
- if (varnest == 0) {
+ if (synstack->varnest == 0) {
#if BASH_REDIR_OUTPUT
if (c == '&') {
//Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
endword:
#if ENABLE_FEATURE_SH_MATH
- if (syntax == ARISYNTAX)
+ if (synstack->syntax == ARISYNTAX)
raise_error_syntax("missing '))'");
#endif
- if (syntax != BASESYNTAX && eofmark == NULL)
+ if (synstack->syntax != BASESYNTAX && eofmark == NULL)
raise_error_syntax("unterminated quoted string");
- if (varnest != 0) {
- startlinno = g_parsefile->linno;
+ if (synstack->varnest != 0) {
/* { */
raise_error_syntax("missing '}'");
}
np = stzalloc(sizeof(struct nfile));
if (c == '>') {
np->nfile.fd = 1;
- c = pgetc();
+ c = pgetc_eatbnl();
if (c == '>')
np->type = NAPPEND;
else if (c == '|')
#endif
else { /* c == '<' */
/*np->nfile.fd = 0; - stzalloc did it */
- c = pgetc();
+ c = pgetc_eatbnl();
switch (c) {
case '<':
if (sizeof(struct nfile) != sizeof(struct nhere)) {
np->type = NHERE;
heredoc = stzalloc(sizeof(struct heredoc));
heredoc->here = np;
- c = pgetc();
+ c = pgetc_eatbnl();
if (c == '-') {
heredoc->striptabs = 1;
} else {
|| (c != '(' && c != '{' && !is_name(c) && !is_special(c))
) {
#if BASH_DOLLAR_SQUOTE
- if (syntax != DQSYNTAX && c == '\'')
+ if (synstack->syntax != DQSYNTAX && c == '\'')
bash_dollar_squote = 1;
else
#endif
}
} else {
/* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
+ smalluint newsyn = synstack->syntax;
+
USTPUTC(CTLVAR, out);
typeloc = out - (char *)stackblock();
STADJUST(1, out);
static const char types[] ALIGN1 = "}-+?=";
/* ${VAR...} but not $VAR or ${#VAR} */
/* c == first char after VAR */
+ int cc = c;
+
switch (c) {
case ':':
c = pgetc_eatbnl();
break;
}
case '%':
- case '#': {
- int cc = c;
+ case '#':
subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
c = pgetc_eatbnl();
- if (c != cc)
- goto badsub;
- subtype++;
+ if (c == cc)
+ subtype++;
+ else
+ pungetc();
+
+ newsyn = BASESYNTAX;
break;
- }
#if BASH_PATTERN_SUBST
case '/':
/* ${v/[/]pattern/repl} */
//TODO: encode pattern and repl separately.
-// Currently ${v/$var_with_slash/repl} is horribly broken
+// Currently cases like: v=1;echo ${v/$((1/1))/ONE}
+// are broken (should print "ONE")
subtype = VSREPLACE;
+ newsyn = BASESYNTAX;
c = pgetc_eatbnl();
if (c != '/')
goto badsub;
badsub:
pungetc();
}
+
+ if (newsyn == ARISYNTAX)
+ newsyn = DQSYNTAX;
+
+ if ((newsyn != synstack->syntax || synstack->innerdq)
+ && subtype != VSNORMAL
+ ) {
+ synstack_push(&synstack,
+ synstack->prev ?: alloca(sizeof(*synstack)),
+ newsyn);
+
+ synstack->varpushed = 1;
+ synstack->dblquote = newsyn != BASESYNTAX;
+ }
+
((unsigned char *)stackblock())[typeloc] = subtype;
if (subtype != VSNORMAL) {
- varnest++;
- if (dblquote)
- dqvarnest++;
+ synstack->varnest++;
+ if (synstack->dblquote)
+ synstack->dqvarnest++;
}
STPUTC('=', out);
}
int pc;
setprompt_if(needprompt, 2);
- pc = pgetc();
+ pc = pgetc_eatbnl();
switch (pc) {
case '`':
goto done;
case '\\':
- pc = pgetc();
- if (pc == '\n') {
- nlprompt();
- /*
- * If eating a newline, avoid putting
- * the newline into the new character
- * stream (via the STPUTC after the
- * switch).
- */
- continue;
- }
+ pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
if (pc != '\\' && pc != '`' && pc != '$'
- && (!dblquote || pc != '"')
+ && (!synstack->dblquote || pc != '"')
) {
STPUTC('\\', pout);
}
case PEOF:
IF_ASH_ALIAS(case PEOA:)
- startlinno = g_parsefile->linno;
raise_error_syntax("EOF in backquote substitution");
case '\n':
* Parse an arithmetic expansion (indicate start of one and set state)
*/
parsearith: {
- if (++arinest == 1) {
- prevsyntax = syntax;
- syntax = ARISYNTAX;
- }
+
+ synstack_push(&synstack,
+ synstack->prev ?: alloca(sizeof(*synstack)),
+ ARISYNTAX);
+ synstack->dblquote = 1;
USTPUTC(CTLARI, out);
goto parsearith_return;
}
* quoted.
* If the token is TREDIR, then we set redirnode to a structure containing
* the redirection.
- * In all cases, the variable startlinno is set to the number of the line
- * on which the token starts.
*
* [Change comment: here documents and internal procedures]
* [Readtoken shouldn't have any arguments. Perhaps we should make the
return lasttoken;
}
setprompt_if(needprompt, 2);
- startlinno = g_parsefile->linno;
for (;;) { /* until token or start of word found */
- c = pgetc();
+ c = pgetc_eatbnl();
if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
continue;
continue;
pungetc();
} else if (c == '\\') {
- if (pgetc() != '\n') {
- pungetc();
- break; /* return readtoken1(...) */
- }
- nlprompt();
+ break; /* return readtoken1(...) */
} else {
const char *p;
break; /* return readtoken1(...) */
if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
- int cc = pgetc();
+ int cc = pgetc_eatbnl();
if (cc == c) { /* double occurrence? */
p += xxreadtoken_doubles + 1;
} else {
return lasttoken;
}
setprompt_if(needprompt, 2);
- startlinno = g_parsefile->linno;
for (;;) { /* until token or start of word found */
- c = pgetc();
+ c = pgetc_eatbnl();
switch (c) {
case ' ': case '\t':
IF_ASH_ALIAS(case PEOA:)
continue;
pungetc();
continue;
- case '\\':
- if (pgetc() == '\n') {
- nlprompt();
- continue;
- }
- pungetc();
- goto breakloop;
case '\n':
nlnoprompt();
RETURN(TNL);
case PEOF:
RETURN(TEOF);
case '&':
- if (pgetc() == '&')
+ if (pgetc_eatbnl() == '&')
RETURN(TAND);
pungetc();
RETURN(TBACKGND);
case '|':
- if (pgetc() == '|')
+ if (pgetc_eatbnl() == '|')
RETURN(TOR);
pungetc();
RETURN(TPIPE);
case ';':
- if (pgetc() == ';')
+ if (pgetc_eatbnl() == ';')
RETURN(TENDCASE);
pungetc();
RETURN(TSEMI);
RETURN(TLP);
case ')':
RETURN(TRP);
- default:
- goto breakloop;
}
+ break;
}
- breakloop:
return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
#undef RETURN
}
if (fullname != name)
stunalloc(fullname);
}
+ /* not found in PATH */
- /* not found in the PATH */
+#if ENABLE_ASH_BASH_SOURCE_CURDIR
+ return name;
+#else
ash_msg_and_raise_error("%s: not found", name);
/* NOTREACHED */
+#endif
}
static int FAST_FUNC
/* We failed. If there was an entry for this command, delete it */
if (cmdp && updatetbl)
delete_cmd_entry();
- if (act & DO_ERR)
+ if (act & DO_ERR) {
+#if ENABLE_ASH_BASH_NOT_FOUND_HOOK
+ struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
+ if (hookp && hookp->cmdtype == CMDFUNCTION) {
+ char *argv[3];
+ argv[0] = (char*) "command_not_found_handle";
+ argv[1] = name;
+ argv[2] = NULL;
+ evalfun(hookp->param.func, 2, argv, 0);
+ entry->cmdtype = CMDUNKNOWN;
+ return;
+ }
+#endif
ash_msg("%s: %s", name, errmsg(e, "not found"));
+ }
entry->cmdtype = CMDUNKNOWN;
return;
//usage:#define ash_trivial_usage
-//usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
+//usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
//usage:#define ash_full_usage "\n\n"
//usage: "Unix shell interpreter"