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