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