1
/* $NetBSD: exec.c,v 1.37 2003/08/07 09:05:31 agc Exp $ */
4
* Copyright (c) 1991, 1993
5
* The Regents of the University of California. All rights reserved.
7
* This code is derived from software contributed to Berkeley by
10
* Redistribution and use in source and binary forms, with or without
11
* modification, are permitted provided that the following conditions
13
* 1. Redistributions of source code must retain the above copyright
14
* notice, this list of conditions and the following disclaimer.
15
* 2. Redistributions in binary form must reproduce the above copyright
16
* notice, this list of conditions and the following disclaimer in the
17
* documentation and/or other materials provided with the distribution.
18
* 3. Neither the name of the University nor the names of its contributors
19
* may be used to endorse or promote products derived from this software
20
* without specific prior written permission.
22
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36
#include <sys/cdefs.h>
43
static char sccsid[] = "@(#)exec.c 8.4 (Berkeley) 6/8/95";
45
__RCSID("$NetBSD: exec.c,v 1.37 2003/08/07 09:05:31 agc Exp $");
49
#include <sys/types.h>
59
* When commands are first encountered, they are entered in a hash table.
60
* This ensures that a full path search will not have to be done for them
63
* We should investigate converting to a linear search, even though that
64
* would make the command name "hash" a misnomer.
89
/* Values for the second argument to access.
90
These may be OR'd together. */
91
#define R_OK 4 /* Test for read permission. */
92
#define W_OK 2 /* Test for write permission. */
93
#define X_OK 1 /* Test for execute permission. */
94
#define F_OK 0 /* Test for existence. */
97
#define CMDTABLESIZE 31 /* should be prime */
98
#define ARB 1 /* actual size determined at run time */
103
struct tblentry *next; /* next entry in hash chain */
104
union param param; /* definition of builtin function */
105
short cmdtype; /* index identifying command */
106
char rehash; /* if set, cd done since entry created */
107
char cmdname[ARB]; /* name of command */
111
STATIC struct tblentry *cmdtable[CMDTABLESIZE];
112
STATIC int builtinloc = -1; /* index in path of %builtin, or -1 */
113
int exerrno = 0; /* Last exec error */
116
STATIC void tryexec(char *, char **, char **, int);
117
STATIC void execinterp(char **, char **);
118
STATIC void printentry(struct tblentry *, int);
119
STATIC void clearcmdentry(int);
120
STATIC struct tblentry *cmdlookup(const char *, int);
121
STATIC void delete_cmd_entry(void);
124
extern char *const parsekwd[];
127
* Exec a program. Never returns. If you change this routine, you may
128
* have to change the find_command routine as well.
132
shellexec(char **argv, char **envp, const char *path, int idx, int vforked)
137
if (strchr(argv[0], '/') != NULL) {
138
tryexec(argv[0], argv, envp, vforked);
142
while ((cmdname = padvance(&path, argv[0])) != NULL) {
143
if (--idx < 0 && pathopt == NULL) {
144
tryexec(cmdname, argv, envp, vforked);
145
if (errno != ENOENT && errno != ENOTDIR)
152
/* Map to POSIX errors */
164
TRACE(("shellexec failed for %s, errno %d, vforked %d, suppressint %d\n",
165
argv[0], e, vforked, suppressint ));
166
exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
172
tryexec(char *cmd, char **argv, char **envp, int vforked)
181
execve(cmd, argv, envp);
182
} while (errno == EINTR);
184
execve(cmd, argv, envp);
189
/* We are currently vfork(2)ed, so raise an
190
* exception, and evalcommand will try again
191
* with a normal fork(2).
193
exraise(EXSHELLPROC);
196
setinputfile(cmd, 0);
197
commandname = arg0 = savestr(argv[0]);
198
#if !defined(BSD) && !defined(__linux__)
199
pgetc(); pungetc(); /* fill up input buffer */
201
if (parsenleft > 2 && p[0] == '#' && p[1] == '!') {
203
execinterp(argv, envp);
207
exraise(EXSHELLPROC);
213
#if !defined(BSD) && !defined(__linux__)
215
* Execute an interpreter introduced by "#!", for systems where this
216
* feature has not been built into the kernel. If the interpreter is
217
* the shell, return (effectively ignoring the "#!"). If the execution
218
* of the interpreter fails, exit.
220
* This code peeks inside the input buffer in order to avoid actually
221
* reading any input. It would benefit from a rewrite.
227
execinterp(char **argv, char **envp)
235
char *newargs[NEWARGS];
241
inp = parsenextc + 2;
244
while (--n >= 0 && (*inp == ' ' || *inp == '\t'))
248
if ((c = *inp++) == '\n')
250
if (ap == &newargs[NEWARGS])
251
bad: error("Bad #! line");
255
} while (--n >= 0 && (c = *inp++) != ' ' && c != '\t' && c != '\n');
258
*ap++ = grabstackstr(outp);
260
if (ap == newargs + 1) { /* if no args, maybe no exec is needed */
263
if (equal(p, "sh") || equal(p, "ash")) {
275
i = (char *)ap - (char *)newargs; /* size in bytes */
277
error("Bad #! line");
278
for (ap2 = argv ; *ap2++ != NULL ; );
279
new = ckmalloc(i + ((char *)ap2 - (char *)argv));
280
ap = newargs, ap2 = new;
281
while ((i -= sizeof (char **)) >= 0)
284
while (*ap2++ = *ap++);
285
shellexec(new, envp, pathval(), 0);
293
* Do a path search. The variable path (passed by reference) should be
294
* set to the start of the path before the first call; padvance will update
295
* this value as it proceeds. Successive calls to padvance will return
296
* the possible path expansions in sequence. If an option (indicated by
297
* a percent sign) appears in the path entry then the global variable
298
* pathopt will be set to point to it; otherwise pathopt will be set to
305
padvance(const char **path, const char *name)
315
for (p = start ; *p && *p != ':' && *p != '%' ; p++);
316
len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
317
while (stackblocksize() < len)
321
memcpy(q, start, p - start);
329
while (*p && *p != ':') p++;
340
/*** Command hashing code ***/
344
hashcmd(int argc, char **argv)
346
struct tblentry **pp;
347
struct tblentry *cmdp;
350
struct cmdentry entry;
354
while ((c = nextopt("rv")) != '\0') {
357
} else if (c == 'v') {
361
if (*argptr == NULL) {
362
for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
363
for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
364
if (verbose || cmdp->cmdtype == CMDNORMAL)
365
printentry(cmdp, verbose);
370
while ((name = *argptr) != NULL) {
371
if ((cmdp = cmdlookup(name, 0)) != NULL
372
&& (cmdp->cmdtype == CMDNORMAL
373
|| (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
375
find_command(name, &entry, DO_ERR, pathval());
377
if (entry.cmdtype != CMDUNKNOWN) { /* if no error msg */
378
cmdp = cmdlookup(name, 0);
379
printentry(cmdp, verbose);
390
printentry(struct tblentry *cmdp, int verbose)
396
switch (cmdp->cmdtype) {
398
idx = cmdp->param.index;
401
name = padvance(&path, cmdp->cmdname);
403
} while (--idx >= 0);
407
out1fmt("special builtin %s", cmdp->cmdname);
410
out1fmt("builtin %s", cmdp->cmdname);
413
out1fmt("function %s", cmdp->cmdname);
417
commandtext(&ps, cmdp->param.func);
425
error("internal error: %s cmdtype %d", cmdp->cmdname, cmdp->cmdtype);
435
* Resolve a command name. If you change this routine, you may have to
436
* change the shellexec routine as well.
440
find_command(char *name, struct cmdentry *entry, int act, const char *path)
442
struct tblentry *cmdp, loc_cmd;
448
int (*bltin)(int,char **);
450
/* If name contains a slash, don't use PATH or hash table */
451
if (strchr(name, '/') != NULL) {
453
while (stat(name, &statb) < 0) {
458
if (errno != ENOENT && errno != ENOTDIR)
460
entry->cmdtype = CMDUNKNOWN;
464
entry->cmdtype = CMDNORMAL;
468
entry->cmdtype = CMDNORMAL;
473
if (path != pathval())
476
if (act & DO_ALTPATH && strstr(path, "%builtin") != NULL)
479
/* If name is in the table, check answer will be ok */
480
if ((cmdp = cmdlookup(name, 0)) != NULL) {
482
switch (cmdp->cmdtype) {
484
if (act & DO_ALTPATH) {
490
if (act & DO_NOFUNC) {
496
if ((act & DO_ALTBLTIN) || builtinloc >= 0) {
502
/* if not invalidated by cd, we're done */
503
if (cmdp->rehash == 0)
508
/* If %builtin not in path, check for builtin next */
509
if ((act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : builtinloc < 0) &&
510
(bltin = find_builtin(name)) != 0)
511
goto builtin_success;
513
/* We have to search path. */
514
prev = -1; /* where to start */
515
if (cmdp) { /* doing a rehash */
516
if (cmdp->cmdtype == CMDBUILTIN)
519
prev = cmdp->param.index;
525
while ((fullname = padvance(&path, name)) != NULL) {
529
if (prefix("builtin", pathopt)) {
530
if ((bltin = find_builtin(name)) == 0)
532
goto builtin_success;
533
} else if (prefix("func", pathopt)) {
536
/* ignore unimplemented options */
540
/* if rehash, don't redo absolute path names */
541
if (fullname[0] == '/' && idx <= prev) {
544
TRACE(("searchexec \"%s\": no change\n", name));
547
while (stat(fullname, &statb) < 0) {
552
if (errno != ENOENT && errno != ENOTDIR)
556
e = EACCES; /* if we fail, this will be the error */
557
if (!S_ISREG(statb.st_mode))
559
if (pathopt) { /* this is a %func directory */
562
stalloc(strlen(fullname) + 1);
563
readcmdfile(fullname);
564
if ((cmdp = cmdlookup(name, 0)) == NULL ||
565
cmdp->cmdtype != CMDFUNCTION)
566
error("%s not defined in %s", name, fullname);
571
/* XXX this code stops root executing stuff, and is buggy
572
if you need a group from the group list. */
573
if (statb.st_uid == geteuid()) {
574
if ((statb.st_mode & 0100) == 0)
576
} else if (statb.st_gid == getegid()) {
577
if ((statb.st_mode & 010) == 0)
580
if ((statb.st_mode & 01) == 0)
584
TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
586
if (act & DO_ALTPATH) {
587
stalloc(strlen(fullname) + 1);
590
cmdp = cmdlookup(name, 1);
591
cmdp->cmdtype = CMDNORMAL;
592
cmdp->param.index = idx;
597
/* We failed. If there was an entry for this command, delete it */
601
outfmt(out2, "%s: %s\n", name, errmsg(e, E_EXEC));
602
entry->cmdtype = CMDUNKNOWN;
607
if (act & DO_ALTPATH)
610
cmdp = cmdlookup(name, 1);
611
if (cmdp->cmdtype == CMDFUNCTION)
612
/* DO_NOFUNC must have been set */
614
cmdp->cmdtype = CMDBUILTIN;
615
cmdp->param.bltin = bltin;
619
entry->cmdtype = cmdp->cmdtype;
620
entry->u = cmdp->param;
626
* Search the table of builtin commands.
630
(*find_builtin(name))(int, char **)
633
const struct builtincmd *bp;
635
for (bp = builtincmd ; bp->name ; bp++) {
636
if (*bp->name == *name && equal(bp->name, name))
643
(*find_splbltin(name))(int, char **)
646
const struct builtincmd *bp;
648
for (bp = splbltincmd ; bp->name ; bp++) {
649
if (*bp->name == *name && equal(bp->name, name))
656
* At shell startup put special builtins into hash table.
657
* ensures they are executed first (see posix).
658
* We stop functions being added with the same name
659
* (as they are impossible to call)
663
hash_special_builtins(void)
665
const struct builtincmd *bp;
666
struct tblentry *cmdp;
668
for (bp = splbltincmd ; bp->name ; bp++) {
669
cmdp = cmdlookup(bp->name, 1);
670
cmdp->cmdtype = CMDSPLBLTIN;
671
cmdp->param.bltin = bp->builtin;
678
* Called when a cd is done. Marks all commands so the next time they
679
* are executed they will be rehashed.
685
struct tblentry **pp;
686
struct tblentry *cmdp;
688
for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
689
for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
690
if (cmdp->cmdtype == CMDNORMAL
691
|| (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
700
* Fix command hash table when PATH changed.
701
* Called before PATH is changed. The argument is the new value of PATH;
702
* pathval() still returns the old value at this point.
703
* Called with interrupts off.
707
changepath(const char *newval)
709
const char *old, *new;
716
firstchange = 9999; /* assume no change */
722
if ((*old == '\0' && *new == ':')
723
|| (*old == ':' && *new == '\0'))
725
old = new; /* ignore subsequent differences */
729
if (*new == '%' && bltin < 0 && prefix("builtin", new + 1))
736
if (builtinloc < 0 && bltin >= 0)
737
builtinloc = bltin; /* zap builtins */
738
if (builtinloc >= 0 && bltin < 0)
740
clearcmdentry(firstchange);
746
* Clear out command entries. The argument specifies the first entry in
747
* PATH which has changed.
751
clearcmdentry(int firstchange)
753
struct tblentry **tblp;
754
struct tblentry **pp;
755
struct tblentry *cmdp;
758
for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
760
while ((cmdp = *pp) != NULL) {
761
if ((cmdp->cmdtype == CMDNORMAL &&
762
cmdp->param.index >= firstchange)
763
|| (cmdp->cmdtype == CMDBUILTIN &&
764
builtinloc >= firstchange)) {
777
* Delete all functions.
781
MKINIT void deletefuncs(void);
782
MKINIT void hash_special_builtins(void);
785
hash_special_builtins();
796
struct tblentry **tblp;
797
struct tblentry **pp;
798
struct tblentry *cmdp;
801
for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
803
while ((cmdp = *pp) != NULL) {
804
if (cmdp->cmdtype == CMDFUNCTION) {
806
freefunc(cmdp->param.func);
819
* Locate a command in the command hash table. If "add" is nonzero,
820
* add the command to the table if it is not already present. The
821
* variable "lastcmdentry" is set to point to the address of the link
822
* pointing to the entry, so that delete_cmd_entry can delete the
826
struct tblentry **lastcmdentry;
829
STATIC struct tblentry *
830
cmdlookup(const char *name, int add)
834
struct tblentry *cmdp;
835
struct tblentry **pp;
842
pp = &cmdtable[hashval % CMDTABLESIZE];
843
for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
844
if (equal(cmdp->cmdname, name))
848
if (add && cmdp == NULL) {
850
cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
853
cmdp->cmdtype = CMDUNKNOWN;
855
strcpy(cmdp->cmdname, name);
863
* Delete the command entry returned on the last lookup.
867
delete_cmd_entry(void)
869
struct tblentry *cmdp;
872
cmdp = *lastcmdentry;
873
*lastcmdentry = cmdp->next;
882
getcmdentry(char *name, struct cmdentry *entry)
884
struct tblentry *cmdp = cmdlookup(name, 0);
887
entry->u = cmdp->param;
888
entry->cmdtype = cmdp->cmdtype;
890
entry->cmdtype = CMDUNKNOWN;
898
* Add a new command entry, replacing any existing command entry for
899
* the same name - except special builtins.
903
addcmdentry(char *name, struct cmdentry *entry)
905
struct tblentry *cmdp;
908
cmdp = cmdlookup(name, 1);
909
if (cmdp->cmdtype != CMDSPLBLTIN) {
910
if (cmdp->cmdtype == CMDFUNCTION) {
911
freefunc(cmdp->param.func);
913
cmdp->cmdtype = entry->cmdtype;
914
cmdp->param = entry->u;
921
* Define a shell function.
925
defun(char *name, union node *func)
927
struct cmdentry entry;
930
entry.cmdtype = CMDFUNCTION;
931
entry.u.func = copyfunc(func);
932
addcmdentry(name, &entry);
938
* Delete a function if it exists.
942
unsetfunc(char *name)
944
struct tblentry *cmdp;
946
if ((cmdp = cmdlookup(name, 0)) != NULL &&
947
cmdp->cmdtype == CMDFUNCTION) {
948
freefunc(cmdp->param.func);
956
* Locate and print what a word is...
957
* also used for 'command -[v|V]'
961
typecmd(int argc, char **argv)
963
struct cmdentry entry;
964
struct tblentry *cmdp;
972
#ifdef KLIBC_SH_ALIAS
976
(void)argc; (void)argv;
978
while ((c = nextopt("vVp")) != 0) {
980
case 'v': v_flag = 1; break;
981
case 'V': V_flag = 1; break;
982
case 'p': p_flag = 1; break;
986
if (p_flag && (v_flag || V_flag))
987
error("cannot specify -p with -v or -V");
989
while ((arg = *argptr++)) {
992
/* First look at the keywords */
993
for (pp = parsekwd; *pp; pp++)
994
if (**pp == *arg && equal(*pp, arg))
1001
out1str(" is a shell keyword\n");
1005
/* Then look at the aliases */
1006
#ifdef KLIBC_SH_ALIAS
1007
if ((ap = lookupalias(arg, 1)) != NULL) {
1009
out1fmt(" is an alias for \n");
1010
out1fmt("%s\n", ap->val);
1015
/* Then check if it is a tracked alias */
1016
if ((cmdp = cmdlookup(arg, 0)) != NULL) {
1017
entry.cmdtype = cmdp->cmdtype;
1018
entry.u = cmdp->param;
1020
/* Finally use brute force */
1021
find_command(arg, &entry, DO_ABS, pathval());
1024
switch (entry.cmdtype) {
1026
if (strchr(arg, '/') == NULL) {
1027
const char *path = pathval();
1029
int j = entry.u.index;
1031
name = padvance(&path, arg);
1034
#ifdef KLIBC_SH_ALIAS
1037
cmdp ? " a tracked alias for" : "");
1039
out1fmt("%s\n", name);
1041
if (access(arg, X_OK) == 0) {
1044
out1fmt("%s\n", arg);
1057
out1str(" is a shell function\n");
1059
out1fmt("%s\n", arg);
1064
out1str(" is a shell builtin\n");
1066
out1fmt("%s\n", arg);
1071
out1str(" is a special shell builtin\n");
1073
out1fmt("%s\n", arg);
1078
out1str(": not found\n");