source: trunk/src/kash/exec.c@ 2649

Last change on this file since 2649 was 2649, checked in by bird, 13 years ago

kash: detect shell invokations via /usr/bin/env in hash bang.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
File size: 27.9 KB
Line 
1/* $NetBSD: exec.c,v 1.37 2003/08/07 09:05:31 agc Exp $ */
2
3/*-
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Kenneth Almquist.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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.
21 *
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
32 * SUCH DAMAGE.
33 */
34
35#if 0
36#ifndef lint
37static char sccsid[] = "@(#)exec.c 8.4 (Berkeley) 6/8/95";
38#else
39__RCSID("$NetBSD: exec.c,v 1.37 2003/08/07 09:05:31 agc Exp $");
40#endif /* not lint */
41#endif
42
43#include <sys/types.h>
44#include <errno.h>
45#include <stdio.h>
46#include <stdlib.h>
47
48/*
49 * When commands are first encountered, they are entered in a hash table.
50 * This ensures that a full path search will not have to be done for them
51 * on each invocation.
52 *
53 * We should investigate converting to a linear search, even though that
54 * would make the command name "hash" a misnomer.
55 */
56
57#include "shell.h"
58#include "main.h"
59#include "nodes.h"
60#include "parser.h"
61#include "redir.h"
62#include "eval.h"
63#include "exec.h"
64#include "builtins.h"
65#include "var.h"
66#include "options.h"
67#include "input.h"
68#include "output.h"
69#include "syntax.h"
70#include "memalloc.h"
71#include "error.h"
72#include "init.h"
73#include "mystring.h"
74#include "show.h"
75#include "jobs.h"
76#include "alias.h"
77#ifdef __INNOTEK_LIBC__
78#include <InnoTekLIBC/backend.h>
79#endif
80#include "shinstance.h"
81
82//#define CMDTABLESIZE 31 /* should be prime */
83//#define ARB 1 /* actual size determined at run time */
84//
85//
86//
87//struct tblentry {
88// struct tblentry *next; /* next entry in hash chain */
89// union param param; /* definition of builtin function */
90// short cmdtype; /* index identifying command */
91// char rehash; /* if set, cd done since entry created */
92// char cmdname[ARB]; /* name of command */
93//};
94//
95//
96//STATIC struct tblentry *cmdtable[CMDTABLESIZE];
97//STATIC int builtinloc = -1; /* index in path of %builtin, or -1 */
98//int exerrno = 0; /* Last exec error */
99
100
101STATIC void tryexec(shinstance *, char *, char **, char **, int, int);
102STATIC void execinterp(shinstance *, char **, char **);
103STATIC void printentry(shinstance *, struct tblentry *, int);
104STATIC void clearcmdentry(shinstance *, int);
105STATIC struct tblentry *cmdlookup(shinstance *, const char *, int);
106STATIC void delete_cmd_entry(shinstance *);
107#ifdef PC_EXE_EXTS
108STATIC int stat_pc_exec_exts(shinstance *, char *fullname, struct stat *st, int has_ext);
109#endif
110
111
112extern char *const parsekwd[];
113
114/*
115 * Exec a program. Never returns. If you change this routine, you may
116 * have to change the find_command routine as well.
117 */
118
119SH_NORETURN_1 void
120shellexec(shinstance *psh, char **argv, char **envp, const char *path, int idx, int vforked)
121{
122 char *cmdname;
123 int e;
124#ifdef PC_EXE_EXTS
125 int has_ext = (int)strlen(argv[0]) - 4;
126 has_ext = has_ext > 0
127 && argv[0][has_ext] == '.'
128 /* use strstr and upper/lower permuated extensions to avoid multiple strcasecmp calls. */
129 && strstr("exe;" "Exe;" "EXe;" "EXE;" "ExE;" "eXe;" "eXE;" "exE;"
130 "cmd;" "Cmd;" "CMd;" "CMD;" "CmD;" "cMd;" "cMD;" "cmD;"
131 "com;" "Com;" "COm;" "COM;" "CoM;" "cOm;" "cOM;" "coM;"
132 "bat;" "Bat;" "BAt;" "BAT;" "BaT;" "bAt;" "bAT;" "baT;"
133 "btm;" "Btm;" "BTm;" "BTM;" "BtM;" "bTm;" "bTM;" "btM;",
134 argv[0] + has_ext + 1)
135 != NULL;
136#else
137 const int has_ext = 1;
138#endif
139 TRACE((psh, "shellexec: argv[0]=%s idx=%d\n", argv[0], idx));
140 if (strchr(argv[0], '/') != NULL) {
141 cmdname = stalloc(psh, strlen(argv[0]) + 5);
142 strcpy(cmdname, argv[0]);
143 tryexec(psh, cmdname, argv, envp, vforked, has_ext);
144 TRACE((psh, "shellexec: cmdname=%s\n", cmdname));
145 stunalloc(psh, cmdname);
146 e = errno;
147 } else {
148 e = ENOENT;
149 while ((cmdname = padvance(psh, &path, argv[0])) != NULL) {
150 if (--idx < 0 && psh->pathopt == NULL) {
151 tryexec(psh, cmdname, argv, envp, vforked, has_ext);
152 if (errno != ENOENT && errno != ENOTDIR)
153 e = errno;
154 }
155 stunalloc(psh, cmdname);
156 }
157 }
158
159 /* Map to POSIX errors */
160 switch (e) {
161 case EACCES:
162 psh->exerrno = 126;
163 break;
164 case ENOENT:
165 psh->exerrno = 127;
166 break;
167 default:
168 psh->exerrno = 2;
169 break;
170 }
171 TRACE((psh, "shellexec failed for '%s', errno %d, vforked %d, suppressint %d\n",
172 argv[0], e, vforked, psh->suppressint ));
173 exerror(psh, EXEXEC, "%s: %s", argv[0], errmsg(psh, e, E_EXEC));
174 /* NOTREACHED */
175}
176
177
178STATIC void
179tryexec(shinstance *psh, char *cmd, char **argv, char **envp, int vforked, int has_ext)
180{
181 int e;
182#ifdef EXEC_HASH_BANG_SCRIPT
183 char *p;
184#endif
185#ifdef PC_EXE_EXTS
186 /* exploit the effect of stat_pc_exec_exts which adds the
187 * correct extentions to the file.
188 */
189 struct stat st;
190 if (!has_ext)
191 stat_pc_exec_exts(psh, cmd, &st, 0);
192#endif
193#if defined(__INNOTEK_LIBC__) && defined(EXEC_HASH_BANG_SCRIPT)
194 __libc_Back_gfProcessHandleHashBangScripts = 0;
195#endif
196
197#ifdef SYSV
198 do {
199 sh_execve(psh, cmd, argv, envp);
200 } while (errno == EINTR);
201#else
202 sh_execve(psh, cmd, (const char * const*)argv, (const char * const*)envp);
203#endif
204 e = errno;
205 if (e == ENOEXEC) {
206 if (vforked) {
207 /* We are currently vfork(2)ed, so raise an
208 * exception, and evalcommand will try again
209 * with a normal fork(2).
210 */
211 exraise(psh, EXSHELLPROC);
212 }
213 initshellproc(psh);
214 setinputfile(psh, cmd, 0);
215 psh->commandname = psh->arg0 = savestr(psh, argv[0]);
216#ifdef EXEC_HASH_BANG_SCRIPT
217 pgetc(psh); pungetc(psh); /* fill up input buffer */
218 p = psh->parsenextc;
219 if (psh->parsenleft > 2 && p[0] == '#' && p[1] == '!') {
220 argv[0] = cmd;
221 execinterp(psh, argv, envp);
222 }
223#endif
224 setparam(psh, argv + 1);
225 exraise(psh, EXSHELLPROC);
226 }
227 errno = e;
228}
229
230#ifdef EXEC_HASH_BANG_SCRIPT
231
232/*
233 * Checks if NAME is the (base) name of the shell executable or something
234 * very similar.
235 */
236STATIC int
237is_shell_exe_name(const char *name)
238{
239 return equal(name, "kmk_ash")
240 || equal(name, "kmk_sh")
241 || equal(name, "kash")
242 || equal(name, "sh");
243}
244
245/*
246 * Execute an interpreter introduced by "#!", for systems where this
247 * feature has not been built into the kernel. If the interpreter is
248 * the shell, return (effectively ignoring the "#!"). If the execution
249 * of the interpreter fails, exit.
250 *
251 * This code peeks inside the input buffer in order to avoid actually
252 * reading any input. It would benefit from a rewrite.
253 */
254
255#define NEWARGS 16
256
257STATIC void
258execinterp(shinstance *psh, char **argv, char **envp)
259{
260 int n;
261 char *inp;
262 char *outp;
263 char c;
264 char *p;
265 char **ap;
266 char *newargs[NEWARGS];
267 int i;
268 char **ap2;
269 char **new;
270
271 n = psh->parsenleft - 2;
272 inp = psh->parsenextc + 2;
273 ap = newargs;
274 for (;;) {
275 while (--n >= 0 && (*inp == ' ' || *inp == '\t'))
276 inp++;
277 if (n < 0)
278 goto bad;
279 if ((c = *inp++) == '\n')
280 break;
281 if (ap == &newargs[NEWARGS])
282bad: error(psh, "Bad #! line");
283 STARTSTACKSTR(psh, outp);
284 do {
285 STPUTC(psh, c, outp);
286 } while (--n >= 0 && (c = *inp++) != ' ' && c != '\t' && c != '\n');
287 STPUTC(psh, '\0', outp);
288 n++, inp--;
289 *ap++ = grabstackstr(psh, outp);
290 }
291
292 /* Special optimizations / builtins. */
293 i = ap - newargs;
294 if (i > 1 && equal(newargs[0], "/usr/bin/env")) {
295 /* /usr/bin/env <self> -> easy. */
296 if (i == 2 && is_shell_exe_name(newargs[1])) {
297 TRACE((psh, "hash bang /usr/bin/env self\n"));
298 return;
299 }
300 /** @todo implement simple /usr/bin/env that locates an exec in the PATH. */
301
302 } else if (i == 1) { /* if no args, maybe shell and no exec is needed. */
303 p = strrchr(newargs[0], '/');
304 if (!p)
305 p = newargs[0];
306 if (is_shell_exe_name(p)) {
307 TRACE((psh, "hash bang self\n"));
308 return;
309 }
310 }
311
312 /* Combine the argument lists and exec. */
313 i = (char *)ap - (char *)newargs; /* size in bytes */
314 if (i == 0)
315 error(psh, "Bad #! line");
316 for (ap2 = argv ; *ap2++ != NULL ; );
317 new = ckmalloc(psh, i + ((char *)ap2 - (char *)argv));
318 ap = newargs, ap2 = new;
319 while ((i -= sizeof (char **)) >= 0)
320 *ap2++ = *ap++;
321 ap = argv;
322 while ((*ap2++ = *ap++))
323 /* nothing*/;
324 TRACE((psh, "hash bang '%s'\n", new[0]));
325 shellexec(psh, new, envp, pathval(psh), 0, 0);
326 /* NOTREACHED */
327}
328
329#endif /* EXEC_HASH_BANG_SCRIPT */
330
331
332/*
333 * Do a path search. The variable path (passed by reference) should be
334 * set to the start of the path before the first call; padvance will update
335 * this value as it proceeds. Successive calls to padvance will return
336 * the possible path expansions in sequence. If an option (indicated by
337 * a percent sign) appears in the path entry then the global variable
338 * psh->pathopt will be set to point to it; otherwise psh->pathopt will be set to
339 * NULL.
340 */
341
342//const char *pathopt;
343
344char *
345padvance(shinstance *psh, const char **path, const char *name)
346{
347 const char *p;
348 char *q;
349 const char *start;
350 int len;
351
352 if (*path == NULL)
353 return NULL;
354 start = *path;
355#ifdef PC_PATH_SEP
356 for (p = start ; *p && *p != ';' && *p != '%' ; p++);
357#else
358 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
359#endif
360 len = (int)(p - start + strlen(name) + 2); /* "2" is for '/' and '\0' */
361#ifdef PC_EXE_EXTS
362 len += 4; /* "4" is for .exe/.com/.cmd/.bat/.btm */
363#endif
364 while (stackblocksize(psh) < len)
365 growstackblock(psh);
366 q = stackblock(psh);
367 if (p != start) {
368 memcpy(q, start, p - start);
369 q += p - start;
370 *q++ = '/';
371 }
372 strcpy(q, name);
373 psh->pathopt = NULL;
374 if (*p == '%') {
375 psh->pathopt = ++p;
376#ifdef PC_PATH_SEP
377 while (*p && *p != ';') p++;
378#else
379 while (*p && *p != ':') p++;
380#endif
381 }
382#ifdef PC_PATH_SEP
383 if (*p == ';')
384#else
385 if (*p == ':')
386#endif
387 *path = p + 1;
388 else
389 *path = NULL;
390 return stalloc(psh, len);
391}
392
393
394#ifdef PC_EXE_EXTS
395STATIC int stat_pc_exec_exts(shinstance *psh, char *fullname, struct stat *st, int has_ext)
396{
397 /* skip the SYSV crap */
398 if (shfile_stat(&psh->fdtab, fullname, st) >= 0)
399 return 0;
400 if (!has_ext && errno == ENOENT)
401 {
402 char *psz = strchr(fullname, '\0');
403 memcpy(psz, ".exe", 5);
404 if (shfile_stat(&psh->fdtab, fullname, st) >= 0)
405 return 0;
406 if (errno != ENOENT && errno != ENOTDIR)
407 return -1;
408
409 memcpy(psz, ".cmd", 5);
410 if (shfile_stat(&psh->fdtab, fullname, st) >= 0)
411 return 0;
412 if (errno != ENOENT && errno != ENOTDIR)
413 return -1;
414
415 memcpy(psz, ".bat", 5);
416 if (shfile_stat(&psh->fdtab, fullname, st) >= 0)
417 return 0;
418 if (errno != ENOENT && errno != ENOTDIR)
419 return -1;
420
421 memcpy(psz, ".com", 5);
422 if (shfile_stat(&psh->fdtab, fullname, st) >= 0)
423 return 0;
424 if (errno != ENOENT && errno != ENOTDIR)
425 return -1;
426
427 memcpy(psz, ".btm", 5);
428 if (shfile_stat(&psh->fdtab, fullname, st) >= 0)
429 return 0;
430 *psz = '\0';
431 }
432 return -1;
433}
434#endif /* PC_EXE_EXTS */
435
436
437
438/*** Command hashing code ***/
439
440
441int
442hashcmd(shinstance *psh, int argc, char **argv)
443{
444 struct tblentry **pp;
445 struct tblentry *cmdp;
446 int c;
447 int verbose;
448 struct cmdentry entry;
449 char *name;
450
451 verbose = 0;
452 while ((c = nextopt(psh, "rv")) != '\0') {
453 if (c == 'r') {
454 clearcmdentry(psh, 0);
455 } else if (c == 'v') {
456 verbose++;
457 }
458 }
459 if (*psh->argptr == NULL) {
460 for (pp = psh->cmdtable ; pp < &psh->cmdtable[CMDTABLESIZE] ; pp++) {
461 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
462 if (verbose || cmdp->cmdtype == CMDNORMAL)
463 printentry(psh, cmdp, verbose);
464 }
465 }
466 return 0;
467 }
468 while ((name = *psh->argptr) != NULL) {
469 if ((cmdp = cmdlookup(psh, name, 0)) != NULL
470 && (cmdp->cmdtype == CMDNORMAL
471 || (cmdp->cmdtype == CMDBUILTIN && psh->builtinloc >= 0)))
472 delete_cmd_entry(psh);
473 find_command(psh, name, &entry, DO_ERR, pathval(psh));
474 if (verbose) {
475 if (entry.cmdtype != CMDUNKNOWN) { /* if no error msg */
476 cmdp = cmdlookup(psh, name, 0);
477 printentry(psh, cmdp, verbose);
478 }
479 output_flushall(psh);
480 }
481 psh->argptr++;
482 }
483 return 0;
484}
485
486
487STATIC void
488printentry(shinstance *psh, struct tblentry *cmdp, int verbose)
489{
490 int idx;
491 const char *path;
492 char *name;
493
494 switch (cmdp->cmdtype) {
495 case CMDNORMAL:
496 idx = cmdp->param.index;
497 path = pathval(psh);
498 do {
499 name = padvance(psh, &path, cmdp->cmdname);
500 stunalloc(psh, name);
501 } while (--idx >= 0);
502 out1str(psh, name);
503 break;
504 case CMDSPLBLTIN:
505 out1fmt(psh, "special builtin %s", cmdp->cmdname);
506 break;
507 case CMDBUILTIN:
508 out1fmt(psh, "builtin %s", cmdp->cmdname);
509 break;
510 case CMDFUNCTION:
511 out1fmt(psh, "function %s", cmdp->cmdname);
512 if (verbose) {
513 struct procstat ps;
514 INTOFF;
515 commandtext(psh, &ps, cmdp->param.func);
516 INTON;
517 out1str(psh, "() { ");
518 out1str(psh, ps.cmd);
519 out1str(psh, "; }");
520 }
521 break;
522 default:
523 error(psh, "internal error: %s cmdtype %d", cmdp->cmdname, cmdp->cmdtype);
524 }
525 if (cmdp->rehash)
526 out1c(psh, '*');
527 out1c(psh, '\n');
528}
529
530
531
532/*
533 * Resolve a command name. If you change this routine, you may have to
534 * change the shellexec routine as well.
535 */
536
537void
538find_command(shinstance *psh, char *name, struct cmdentry *entry, int act, const char *path)
539{
540 struct tblentry *cmdp, loc_cmd;
541 int idx;
542 int prev;
543 char *fullname;
544 struct stat statb;
545 int e;
546 int (*bltin)(shinstance*,int,char **);
547
548#ifdef PC_EXE_EXTS
549 int has_ext = (int)(strlen(name) - 4);
550 has_ext = has_ext > 0
551 && name[has_ext] == '.'
552 /* use strstr and upper/lower permuated extensions to avoid multiple strcasecmp calls. */
553 && strstr("exe;" "Exe;" "EXe;" "EXE;" "ExE;" "eXe;" "eXE;" "exE;"
554 "cmd;" "Cmd;" "CMd;" "CMD;" "CmD;" "cMd;" "cMD;" "cmD;"
555 "com;" "Com;" "COm;" "COM;" "CoM;" "cOm;" "cOM;" "coM;"
556 "bat;" "Bat;" "BAt;" "BAT;" "BaT;" "bAt;" "bAT;" "baT;"
557 "btm;" "Btm;" "BTm;" "BTM;" "BtM;" "bTm;" "bTM;" "btM;",
558 name + has_ext + 1)
559 != NULL;
560#endif
561
562 /* If name contains a slash, don't use PATH or hash table */
563 if (strchr(name, '/') != NULL) {
564 if (act & DO_ABS) {
565 while (shfile_stat(&psh->fdtab, name, &statb) < 0) {
566#ifdef SYSV
567 if (errno == EINTR)
568 continue;
569#endif
570 if (errno != ENOENT && errno != ENOTDIR)
571 e = errno;
572 entry->cmdtype = CMDUNKNOWN;
573 entry->u.index = -1;
574 return;
575 }
576 entry->cmdtype = CMDNORMAL;
577 entry->u.index = -1;
578 return;
579 }
580 entry->cmdtype = CMDNORMAL;
581 entry->u.index = 0;
582 return;
583 }
584
585 if (path != pathval(psh))
586 act |= DO_ALTPATH;
587
588 if (act & DO_ALTPATH && strstr(path, "%builtin") != NULL)
589 act |= DO_ALTBLTIN;
590
591 /* If name is in the table, check answer will be ok */
592 if ((cmdp = cmdlookup(psh, name, 0)) != NULL) {
593 do {
594 switch (cmdp->cmdtype) {
595 case CMDNORMAL:
596 if (act & DO_ALTPATH) {
597 cmdp = NULL;
598 continue;
599 }
600 break;
601 case CMDFUNCTION:
602 if (act & DO_NOFUNC) {
603 cmdp = NULL;
604 continue;
605 }
606 break;
607 case CMDBUILTIN:
608 if ((act & DO_ALTBLTIN) || psh->builtinloc >= 0) {
609 cmdp = NULL;
610 continue;
611 }
612 break;
613 }
614 /* if not invalidated by cd, we're done */
615 if (cmdp->rehash == 0)
616 goto success;
617 } while (0);
618 }
619
620 /* If %builtin not in path, check for builtin next */
621 if ((act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : psh->builtinloc < 0) &&
622 (bltin = find_builtin(psh, name)) != 0)
623 goto builtin_success;
624
625 /* We have to search path. */
626 prev = -1; /* where to start */
627 if (cmdp) { /* doing a rehash */
628 if (cmdp->cmdtype == CMDBUILTIN)
629 prev = psh->builtinloc;
630 else
631 prev = cmdp->param.index;
632 }
633
634 e = ENOENT;
635 idx = -1;
636loop:
637 while ((fullname = padvance(psh, &path, name)) != NULL) {
638 stunalloc(psh, fullname);
639 idx++;
640 if (psh->pathopt) {
641 if (prefix("builtin", psh->pathopt)) {
642 if ((bltin = find_builtin(psh, name)) == 0)
643 goto loop;
644 goto builtin_success;
645 } else if (prefix("func", psh->pathopt)) {
646 /* handled below */
647 } else {
648 /* ignore unimplemented options */
649 goto loop;
650 }
651 }
652 /* if rehash, don't redo absolute path names */
653 if (fullname[0] == '/' && idx <= prev) {
654 if (idx < prev)
655 goto loop;
656 TRACE((psh, "searchexec \"%s\": no change\n", name));
657 goto success;
658 }
659#ifdef PC_EXE_EXTS
660 while (stat_pc_exec_exts(psh, fullname, &statb, has_ext) < 0) {
661#else
662 while (shfile_stat(&psh->fdtab, fullname, &statb) < 0) {
663#endif
664#ifdef SYSV
665 if (errno == EINTR)
666 continue;
667#endif
668 if (errno != ENOENT && errno != ENOTDIR)
669 e = errno;
670
671 goto loop;
672 }
673 e = EACCES; /* if we fail, this will be the error */
674 if (!S_ISREG(statb.st_mode))
675 goto loop;
676 if (psh->pathopt) { /* this is a %func directory */
677 if (act & DO_NOFUNC)
678 goto loop;
679 stalloc(psh, strlen(fullname) + 1);
680 readcmdfile(psh, fullname);
681 if ((cmdp = cmdlookup(psh, name, 0)) == NULL ||
682 cmdp->cmdtype != CMDFUNCTION)
683 error(psh, "%s not defined in %s", name, fullname);
684 stunalloc(psh, fullname);
685 goto success;
686 }
687#ifdef notdef
688 /* XXX this code stops root executing stuff, and is buggy
689 if you need a group from the group list. */
690 if (statb.st_uid == sh_geteuid(psh)) {
691 if ((statb.st_mode & 0100) == 0)
692 goto loop;
693 } else if (statb.st_gid == sh_getegid(psh)) {
694 if ((statb.st_mode & 010) == 0)
695 goto loop;
696 } else {
697 if ((statb.st_mode & 01) == 0)
698 goto loop;
699 }
700#endif
701 TRACE((psh, "searchexec \"%s\" returns \"%s\"\n", name, fullname));
702 INTOFF;
703 if (act & DO_ALTPATH) {
704 stalloc(psh, strlen(fullname) + 1);
705 cmdp = &loc_cmd;
706 } else
707 cmdp = cmdlookup(psh, name, 1);
708 cmdp->cmdtype = CMDNORMAL;
709 cmdp->param.index = idx;
710 INTON;
711 goto success;
712 }
713
714 /* We failed. If there was an entry for this command, delete it */
715 if (cmdp)
716 delete_cmd_entry(psh);
717 if (act & DO_ERR)
718 outfmt(psh->out2, "%s: %s\n", name, errmsg(psh, e, E_EXEC));
719 entry->cmdtype = CMDUNKNOWN;
720 return;
721
722builtin_success:
723 INTOFF;
724 if (act & DO_ALTPATH)
725 cmdp = &loc_cmd;
726 else
727 cmdp = cmdlookup(psh, name, 1);
728 if (cmdp->cmdtype == CMDFUNCTION)
729 /* DO_NOFUNC must have been set */
730 cmdp = &loc_cmd;
731 cmdp->cmdtype = CMDBUILTIN;
732 cmdp->param.bltin = bltin;
733 INTON;
734success:
735 cmdp->rehash = 0;
736 entry->cmdtype = cmdp->cmdtype;
737 entry->u = cmdp->param;
738}
739
740
741
742/*
743 * Search the table of builtin commands.
744 */
745
746int
747(*find_builtin(shinstance *psh, char *name))(shinstance *psh, int, char **)
748{
749 const struct builtincmd *bp;
750
751 for (bp = builtincmd ; bp->name ; bp++) {
752 if (*bp->name == *name && equal(bp->name, name))
753 return bp->builtin;
754 }
755 return 0;
756}
757
758int
759(*find_splbltin(shinstance *psh, char *name))(shinstance *psh, int, char **)
760{
761 const struct builtincmd *bp;
762
763 for (bp = splbltincmd ; bp->name ; bp++) {
764 if (*bp->name == *name && equal(bp->name, name))
765 return bp->builtin;
766 }
767 return 0;
768}
769
770/*
771 * At shell startup put special builtins into hash table.
772 * ensures they are executed first (see posix).
773 * We stop functions being added with the same name
774 * (as they are impossible to call)
775 */
776
777void
778hash_special_builtins(shinstance *psh)
779{
780 const struct builtincmd *bp;
781 struct tblentry *cmdp;
782
783 for (bp = splbltincmd ; bp->name ; bp++) {
784 cmdp = cmdlookup(psh, bp->name, 1);
785 cmdp->cmdtype = CMDSPLBLTIN;
786 cmdp->param.bltin = bp->builtin;
787 }
788}
789
790
791
792/*
793 * Called when a cd is done. Marks all commands so the next time they
794 * are executed they will be rehashed.
795 */
796
797void
798hashcd(shinstance *psh)
799{
800 struct tblentry **pp;
801 struct tblentry *cmdp;
802
803 for (pp = psh->cmdtable ; pp < &psh->cmdtable[CMDTABLESIZE] ; pp++) {
804 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
805 if (cmdp->cmdtype == CMDNORMAL
806 || (cmdp->cmdtype == CMDBUILTIN && psh->builtinloc >= 0))
807 cmdp->rehash = 1;
808 }
809 }
810}
811
812
813
814/*
815 * Fix command hash table when PATH changed.
816 * Called before PATH is changed. The argument is the new value of PATH;
817 * pathval(psh) still returns the old value at this point.
818 * Called with interrupts off.
819 */
820
821void
822changepath(shinstance *psh, const char *newval)
823{
824 const char *old, *new;
825 int idx;
826 int firstchange;
827 int bltin;
828
829 old = pathval(psh);
830 new = newval;
831 firstchange = 9999; /* assume no change */
832 idx = 0;
833 bltin = -1;
834 for (;;) {
835 if (*old != *new) {
836 firstchange = idx;
837#ifdef PC_PATH_SEP
838 if ((*old == '\0' && *new == ';')
839 || (*old == ';' && *new == '\0'))
840#else
841 if ((*old == '\0' && *new == ':')
842 || (*old == ':' && *new == '\0'))
843#endif
844 firstchange++;
845 old = new; /* ignore subsequent differences */
846 }
847 if (*new == '\0')
848 break;
849 if (*new == '%' && bltin < 0 && prefix("builtin", new + 1))
850 bltin = idx;
851#ifdef PC_PATH_SEP
852 if (*new == ';') {
853#else
854 if (*new == ':') {
855#endif
856 idx++;
857 }
858 new++, old++;
859 }
860 if (psh->builtinloc < 0 && bltin >= 0)
861 psh->builtinloc = bltin; /* zap builtins */
862 if (psh->builtinloc >= 0 && bltin < 0)
863 firstchange = 0;
864 clearcmdentry(psh, firstchange);
865 psh->builtinloc = bltin;
866}
867
868
869/*
870 * Clear out command entries. The argument specifies the first entry in
871 * PATH which has changed.
872 */
873
874STATIC void
875clearcmdentry(shinstance *psh, int firstchange)
876{
877 struct tblentry **tblp;
878 struct tblentry **pp;
879 struct tblentry *cmdp;
880
881 INTOFF;
882 for (tblp = psh->cmdtable ; tblp < &psh->cmdtable[CMDTABLESIZE] ; tblp++) {
883 pp = tblp;
884 while ((cmdp = *pp) != NULL) {
885 if ((cmdp->cmdtype == CMDNORMAL &&
886 cmdp->param.index >= firstchange)
887 || (cmdp->cmdtype == CMDBUILTIN &&
888 psh->builtinloc >= firstchange)) {
889 *pp = cmdp->next;
890 ckfree(psh, cmdp);
891 } else {
892 pp = &cmdp->next;
893 }
894 }
895 }
896 INTON;
897}
898
899
900/*
901 * Delete all functions.
902 */
903
904#ifdef mkinit
905MKINIT void deletefuncs(struct shinstance *);
906MKINIT void hash_special_builtins(struct shinstance *);
907
908INIT {
909 hash_special_builtins(psh);
910}
911
912SHELLPROC {
913 deletefuncs(psh);
914}
915#endif
916
917void
918deletefuncs(shinstance *psh)
919{
920 struct tblentry **tblp;
921 struct tblentry **pp;
922 struct tblentry *cmdp;
923
924 INTOFF;
925 for (tblp = psh->cmdtable ; tblp < &psh->cmdtable[CMDTABLESIZE] ; tblp++) {
926 pp = tblp;
927 while ((cmdp = *pp) != NULL) {
928 if (cmdp->cmdtype == CMDFUNCTION) {
929 *pp = cmdp->next;
930 freefunc(psh, cmdp->param.func);
931 ckfree(psh, cmdp);
932 } else {
933 pp = &cmdp->next;
934 }
935 }
936 }
937 INTON;
938}
939
940
941
942/*
943 * Locate a command in the command hash table. If "add" is nonzero,
944 * add the command to the table if it is not already present. The
945 * variable "lastcmdentry" is set to point to the address of the link
946 * pointing to the entry, so that delete_cmd_entry can delete the
947 * entry.
948 */
949
950struct tblentry **lastcmdentry;
951
952
953STATIC struct tblentry *
954cmdlookup(shinstance *psh, const char *name, int add)
955{
956 int hashval;
957 const char *p;
958 struct tblentry *cmdp;
959 struct tblentry **pp;
960
961 p = name;
962 hashval = *p << 4;
963 while (*p)
964 hashval += *p++;
965 hashval &= 0x7FFF;
966 pp = &psh->cmdtable[hashval % CMDTABLESIZE];
967 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
968 if (equal(cmdp->cmdname, name))
969 break;
970 pp = &cmdp->next;
971 }
972 if (add && cmdp == NULL) {
973 INTOFF;
974 cmdp = *pp = ckmalloc(psh, sizeof (struct tblentry) - ARB
975 + strlen(name) + 1);
976 cmdp->next = NULL;
977 cmdp->cmdtype = CMDUNKNOWN;
978 cmdp->rehash = 0;
979 strcpy(cmdp->cmdname, name);
980 INTON;
981 }
982 lastcmdentry = pp;
983 return cmdp;
984}
985
986/*
987 * Delete the command entry returned on the last lookup.
988 */
989
990STATIC void
991delete_cmd_entry(shinstance *psh)
992{
993 struct tblentry *cmdp;
994
995 INTOFF;
996 cmdp = *lastcmdentry;
997 *lastcmdentry = cmdp->next;
998 ckfree(psh, cmdp);
999 INTON;
1000}
1001
1002
1003
1004#ifdef notdef
1005void
1006getcmdentry(shinstance *psh, char *name, struct cmdentry *entry)
1007{
1008 struct tblentry *cmdp = cmdlookup(psh, name, 0);
1009
1010 if (cmdp) {
1011 entry->u = cmdp->param;
1012 entry->cmdtype = cmdp->cmdtype;
1013 } else {
1014 entry->cmdtype = CMDUNKNOWN;
1015 entry->u.index = 0;
1016 }
1017}
1018#endif
1019
1020
1021/*
1022 * Add a new command entry, replacing any existing command entry for
1023 * the same name - except special builtins.
1024 */
1025
1026STATIC void
1027addcmdentry(shinstance *psh, char *name, struct cmdentry *entry)
1028{
1029 struct tblentry *cmdp;
1030
1031 INTOFF;
1032 cmdp = cmdlookup(psh, name, 1);
1033 if (cmdp->cmdtype != CMDSPLBLTIN) {
1034 if (cmdp->cmdtype == CMDFUNCTION) {
1035 freefunc(psh, cmdp->param.func);
1036 }
1037 cmdp->cmdtype = entry->cmdtype;
1038 cmdp->param = entry->u;
1039 }
1040 INTON;
1041}
1042
1043
1044/*
1045 * Define a shell function.
1046 */
1047
1048void
1049defun(shinstance *psh, char *name, union node *func)
1050{
1051 struct cmdentry entry;
1052
1053 INTOFF;
1054 entry.cmdtype = CMDFUNCTION;
1055 entry.u.func = copyfunc(psh, func);
1056 addcmdentry(psh, name, &entry);
1057 INTON;
1058}
1059
1060
1061/*
1062 * Delete a function if it exists.
1063 */
1064
1065int
1066unsetfunc(shinstance *psh, char *name)
1067{
1068 struct tblentry *cmdp;
1069
1070 if ((cmdp = cmdlookup(psh, name, 0)) != NULL &&
1071 cmdp->cmdtype == CMDFUNCTION) {
1072 freefunc(psh, cmdp->param.func);
1073 delete_cmd_entry(psh);
1074 return (0);
1075 }
1076 return (1);
1077}
1078
1079/*
1080 * Locate and print what a word is...
1081 * also used for 'command -[v|V]'
1082 */
1083
1084int
1085typecmd(shinstance *psh, int argc, char **argv)
1086{
1087 struct cmdentry entry;
1088 struct tblentry *cmdp;
1089 char * const *pp;
1090 struct alias *ap;
1091 int err = 0;
1092 char *arg;
1093 int c;
1094 int V_flag = 0;
1095 int v_flag = 0;
1096 int p_flag = 0;
1097
1098 while ((c = nextopt(psh, "vVp")) != 0) {
1099 switch (c) {
1100 case 'v': v_flag = 1; break;
1101 case 'V': V_flag = 1; break;
1102 case 'p': p_flag = 1; break;
1103 }
1104 }
1105
1106 if (p_flag && (v_flag || V_flag))
1107 error(psh, "cannot specify -p with -v or -V");
1108
1109 while ((arg = *psh->argptr++)) {
1110 if (!v_flag)
1111 out1str(psh, arg);
1112 /* First look at the keywords */
1113 for (pp = parsekwd; *pp; pp++)
1114 if (**pp == *arg && equal(*pp, arg))
1115 break;
1116
1117 if (*pp) {
1118 if (v_flag)
1119 err = 1;
1120 else
1121 out1str(psh, " is a shell keyword\n");
1122 continue;
1123 }
1124
1125 /* Then look at the aliases */
1126 if ((ap = lookupalias(psh, arg, 1)) != NULL) {
1127 if (!v_flag)
1128 out1fmt(psh, " is an alias for \n");
1129 out1fmt(psh, "%s\n", ap->val);
1130 continue;
1131 }
1132
1133 /* Then check if it is a tracked alias */
1134 if ((cmdp = cmdlookup(psh, arg, 0)) != NULL) {
1135 entry.cmdtype = cmdp->cmdtype;
1136 entry.u = cmdp->param;
1137 } else {
1138 /* Finally use brute force */
1139 find_command(psh, arg, &entry, DO_ABS, pathval(psh));
1140 }
1141
1142 switch (entry.cmdtype) {
1143 case CMDNORMAL: {
1144 if (strchr(arg, '/') == NULL) {
1145 const char *path = pathval(psh);
1146 char *name;
1147 int j = entry.u.index;
1148 do {
1149 name = padvance(psh, &path, arg);
1150 stunalloc(psh, name);
1151 } while (--j >= 0);
1152 if (!v_flag)
1153 out1fmt(psh, " is%s ",
1154 cmdp ? " a tracked alias for" : "");
1155 out1fmt(psh, "%s\n", name);
1156 } else {
1157 if (shfile_access(&psh->fdtab, arg, X_OK) == 0) {
1158 if (!v_flag)
1159 out1fmt(psh, " is ");
1160 out1fmt(psh, "%s\n", arg);
1161 } else {
1162 if (!v_flag)
1163 out1fmt(psh, ": %s\n",
1164 sh_strerror(psh, errno));
1165 else
1166 err = 126;
1167 }
1168 }
1169 break;
1170 }
1171 case CMDFUNCTION:
1172 if (!v_flag)
1173 out1str(psh, " is a shell function\n");
1174 else
1175 out1fmt(psh, "%s\n", arg);
1176 break;
1177
1178 case CMDBUILTIN:
1179 if (!v_flag)
1180 out1str(psh, " is a shell builtin\n");
1181 else
1182 out1fmt(psh, "%s\n", arg);
1183 break;
1184
1185 case CMDSPLBLTIN:
1186 if (!v_flag)
1187 out1str(psh, " is a special shell builtin\n");
1188 else
1189 out1fmt(psh, "%s\n", arg);
1190 break;
1191
1192 default:
1193 if (!v_flag)
1194 out1str(psh, ": not found\n");
1195 err = 127;
1196 break;
1197 }
1198 }
1199 return err;
1200}
Note: See TracBrowser for help on using the repository browser.