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