]> git.cameronkatri.com Git - apple_cmds.git/blob - shell_cmds/sh/exec.c
Import macOS userland
[apple_cmds.git] / shell_cmds / sh / exec.c
1 /*-
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)exec.c 8.4 (Berkeley) 6/8/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD: head/bin/sh/exec.c 317882 2017-05-06 13:28:42Z jilles $");
40
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <errno.h>
46 #include <paths.h>
47 #include <stdlib.h>
48
49 /*
50 * When commands are first encountered, they are entered in a hash table.
51 * This ensures that a full path search will not have to be done for them
52 * on each invocation.
53 *
54 * We should investigate converting to a linear search, even though that
55 * would make the command name "hash" a misnomer.
56 */
57
58 #include "shell.h"
59 #include "main.h"
60 #include "nodes.h"
61 #include "parser.h"
62 #include "redir.h"
63 #include "eval.h"
64 #include "exec.h"
65 #include "builtins.h"
66 #include "var.h"
67 #include "options.h"
68 #include "input.h"
69 #include "output.h"
70 #include "syntax.h"
71 #include "memalloc.h"
72 #include "error.h"
73 #include "mystring.h"
74 #include "show.h"
75 #include "jobs.h"
76 #include "alias.h"
77
78
79 #ifdef __APPLE__
80 #define eaccess(path, mode) faccessat(AT_FDCWD, path, mode, AT_EACCESS)
81 #endif /* __APPLE__ */
82
83 #define CMDTABLESIZE 31 /* should be prime */
84
85
86
87 struct tblentry {
88 struct tblentry *next; /* next entry in hash chain */
89 union param param; /* definition of builtin function */
90 int special; /* flag for special builtin commands */
91 signed char cmdtype; /* index identifying command */
92 char cmdname[]; /* name of command */
93 };
94
95
96 static struct tblentry *cmdtable[CMDTABLESIZE];
97 static int cmdtable_cd = 0; /* cmdtable contains cd-dependent entries */
98 int exerrno = 0; /* Last exec error */
99
100
101 static void tryexec(char *, char **, char **);
102 static void printentry(struct tblentry *, int);
103 static struct tblentry *cmdlookup(const char *, int);
104 static void delete_cmd_entry(void);
105 static void addcmdentry(const char *, struct cmdentry *);
106
107
108
109 /*
110 * Exec a program. Never returns. If you change this routine, you may
111 * have to change the find_command routine as well.
112 *
113 * The argv array may be changed and element argv[-1] should be writable.
114 */
115
116 void
117 shellexec(char **argv, char **envp, const char *path, int idx)
118 {
119 char *cmdname;
120 int e;
121
122 if (strchr(argv[0], '/') != NULL) {
123 tryexec(argv[0], argv, envp);
124 e = errno;
125 } else {
126 e = ENOENT;
127 while ((cmdname = padvance(&path, argv[0])) != NULL) {
128 if (--idx < 0 && pathopt == NULL) {
129 tryexec(cmdname, argv, envp);
130 if (errno != ENOENT && errno != ENOTDIR)
131 e = errno;
132 if (e == ENOEXEC)
133 break;
134 }
135 stunalloc(cmdname);
136 }
137 }
138
139 /* Map to POSIX errors */
140 if (e == ENOENT || e == ENOTDIR) {
141 exerrno = 127;
142 exerror(EXEXEC, "%s: not found", argv[0]);
143 } else {
144 exerrno = 126;
145 exerror(EXEXEC, "%s: %s", argv[0], strerror(e));
146 }
147 }
148
149
150 static void
151 tryexec(char *cmd, char **argv, char **envp)
152 {
153 int e, in;
154 ssize_t n;
155 char buf[256];
156
157 execve(cmd, argv, envp);
158 e = errno;
159 if (e == ENOEXEC) {
160 INTOFF;
161 in = open(cmd, O_RDONLY | O_NONBLOCK);
162 if (in != -1) {
163 n = pread(in, buf, sizeof buf, 0);
164 close(in);
165 if (n > 0 && memchr(buf, '\0', n) != NULL) {
166 errno = ENOEXEC;
167 return;
168 }
169 }
170 *argv = cmd;
171 *--argv = __DECONST(char *, _PATH_BSHELL);
172 execve(_PATH_BSHELL, argv, envp);
173 }
174 errno = e;
175 }
176
177 /*
178 * Do a path search. The variable path (passed by reference) should be
179 * set to the start of the path before the first call; padvance will update
180 * this value as it proceeds. Successive calls to padvance will return
181 * the possible path expansions in sequence. If an option (indicated by
182 * a percent sign) appears in the path entry then the global variable
183 * pathopt will be set to point to it; otherwise pathopt will be set to
184 * NULL.
185 */
186
187 const char *pathopt;
188
189 char *
190 padvance(const char **path, const char *name)
191 {
192 const char *p, *start;
193 char *q;
194 size_t len, namelen;
195
196 if (*path == NULL)
197 return NULL;
198 start = *path;
199 for (p = start; *p && *p != ':' && *p != '%'; p++)
200 ; /* nothing */
201 namelen = strlen(name);
202 len = p - start + namelen + 2; /* "2" is for '/' and '\0' */
203 STARTSTACKSTR(q);
204 CHECKSTRSPACE(len, q);
205 if (p != start) {
206 memcpy(q, start, p - start);
207 q += p - start;
208 *q++ = '/';
209 }
210 memcpy(q, name, namelen + 1);
211 pathopt = NULL;
212 if (*p == '%') {
213 pathopt = ++p;
214 while (*p && *p != ':') p++;
215 }
216 if (*p == ':')
217 *path = p + 1;
218 else
219 *path = NULL;
220 return stalloc(len);
221 }
222
223
224
225 /*** Command hashing code ***/
226
227
228 int
229 hashcmd(int argc __unused, char **argv __unused)
230 {
231 struct tblentry **pp;
232 struct tblentry *cmdp;
233 int c;
234 int verbose;
235 struct cmdentry entry;
236 char *name;
237 int errors;
238
239 errors = 0;
240 verbose = 0;
241 while ((c = nextopt("rv")) != '\0') {
242 if (c == 'r') {
243 clearcmdentry();
244 } else if (c == 'v') {
245 verbose++;
246 }
247 }
248 if (*argptr == NULL) {
249 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
250 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
251 if (cmdp->cmdtype == CMDNORMAL)
252 printentry(cmdp, verbose);
253 }
254 }
255 return 0;
256 }
257 while ((name = *argptr) != NULL) {
258 if ((cmdp = cmdlookup(name, 0)) != NULL
259 && cmdp->cmdtype == CMDNORMAL)
260 delete_cmd_entry();
261 find_command(name, &entry, DO_ERR, pathval());
262 if (entry.cmdtype == CMDUNKNOWN)
263 errors = 1;
264 else if (verbose) {
265 cmdp = cmdlookup(name, 0);
266 if (cmdp != NULL)
267 printentry(cmdp, verbose);
268 else {
269 outfmt(out2, "%s: not found\n", name);
270 errors = 1;
271 }
272 flushall();
273 }
274 argptr++;
275 }
276 return errors;
277 }
278
279
280 static void
281 printentry(struct tblentry *cmdp, int verbose)
282 {
283 int idx;
284 const char *path;
285 char *name;
286
287 if (cmdp->cmdtype == CMDNORMAL) {
288 idx = cmdp->param.index;
289 path = pathval();
290 do {
291 name = padvance(&path, cmdp->cmdname);
292 stunalloc(name);
293 } while (--idx >= 0);
294 out1str(name);
295 } else if (cmdp->cmdtype == CMDBUILTIN) {
296 out1fmt("builtin %s", cmdp->cmdname);
297 } else if (cmdp->cmdtype == CMDFUNCTION) {
298 out1fmt("function %s", cmdp->cmdname);
299 if (verbose) {
300 INTOFF;
301 name = commandtext(getfuncnode(cmdp->param.func));
302 out1c(' ');
303 out1str(name);
304 ckfree(name);
305 INTON;
306 }
307 #ifdef DEBUG
308 } else {
309 error("internal error: cmdtype %d", cmdp->cmdtype);
310 #endif
311 }
312 out1c('\n');
313 }
314
315
316
317 /*
318 * Resolve a command name. If you change this routine, you may have to
319 * change the shellexec routine as well.
320 */
321
322 void
323 find_command(const char *name, struct cmdentry *entry, int act,
324 const char *path)
325 {
326 struct tblentry *cmdp, loc_cmd;
327 int idx;
328 char *fullname;
329 struct stat statb;
330 int e;
331 int i;
332 int spec;
333 int cd;
334
335 /* If name contains a slash, don't use the hash table */
336 if (strchr(name, '/') != NULL) {
337 entry->cmdtype = CMDNORMAL;
338 entry->u.index = 0;
339 entry->special = 0;
340 return;
341 }
342
343 cd = 0;
344
345 /* If name is in the table, we're done */
346 if ((cmdp = cmdlookup(name, 0)) != NULL) {
347 if (cmdp->cmdtype == CMDFUNCTION && act & DO_NOFUNC)
348 cmdp = NULL;
349 else
350 goto success;
351 }
352
353 /* Check for builtin next */
354 if ((i = find_builtin(name, &spec)) >= 0) {
355 INTOFF;
356 cmdp = cmdlookup(name, 1);
357 if (cmdp->cmdtype == CMDFUNCTION)
358 cmdp = &loc_cmd;
359 cmdp->cmdtype = CMDBUILTIN;
360 cmdp->param.index = i;
361 cmdp->special = spec;
362 INTON;
363 goto success;
364 }
365
366 /* We have to search path. */
367
368 e = ENOENT;
369 idx = -1;
370 for (;(fullname = padvance(&path, name)) != NULL; stunalloc(fullname)) {
371 idx++;
372 if (pathopt) {
373 if (strncmp(pathopt, "func", 4) == 0) {
374 /* handled below */
375 } else {
376 continue; /* ignore unimplemented options */
377 }
378 }
379 if (fullname[0] != '/')
380 cd = 1;
381 if (stat(fullname, &statb) < 0) {
382 if (errno != ENOENT && errno != ENOTDIR)
383 e = errno;
384 continue;
385 }
386 e = EACCES; /* if we fail, this will be the error */
387 if (!S_ISREG(statb.st_mode))
388 continue;
389 if (pathopt) { /* this is a %func directory */
390 readcmdfile(fullname);
391 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
392 error("%s not defined in %s", name, fullname);
393 stunalloc(fullname);
394 goto success;
395 }
396 #ifdef notdef
397 if (statb.st_uid == geteuid()) {
398 if ((statb.st_mode & 0100) == 0)
399 goto loop;
400 } else if (statb.st_gid == getegid()) {
401 if ((statb.st_mode & 010) == 0)
402 goto loop;
403 } else {
404 if ((statb.st_mode & 01) == 0)
405 goto loop;
406 }
407 #endif
408 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
409 INTOFF;
410 stunalloc(fullname);
411 cmdp = cmdlookup(name, 1);
412 if (cmdp->cmdtype == CMDFUNCTION)
413 cmdp = &loc_cmd;
414 cmdp->cmdtype = CMDNORMAL;
415 cmdp->param.index = idx;
416 cmdp->special = 0;
417 INTON;
418 goto success;
419 }
420
421 if (act & DO_ERR) {
422 if (e == ENOENT || e == ENOTDIR)
423 outfmt(out2, "%s: not found\n", name);
424 else
425 outfmt(out2, "%s: %s\n", name, strerror(e));
426 }
427 entry->cmdtype = CMDUNKNOWN;
428 entry->u.index = 0;
429 entry->special = 0;
430 return;
431
432 success:
433 if (cd)
434 cmdtable_cd = 1;
435 entry->cmdtype = cmdp->cmdtype;
436 entry->u = cmdp->param;
437 entry->special = cmdp->special;
438 }
439
440
441
442 /*
443 * Search the table of builtin commands.
444 */
445
446 int
447 find_builtin(const char *name, int *special)
448 {
449 const unsigned char *bp;
450 size_t len;
451
452 len = strlen(name);
453 for (bp = builtincmd ; *bp ; bp += 2 + bp[0]) {
454 if (bp[0] == len && memcmp(bp + 2, name, len) == 0) {
455 *special = (bp[1] & BUILTIN_SPECIAL) != 0;
456 return bp[1] & ~BUILTIN_SPECIAL;
457 }
458 }
459 return -1;
460 }
461
462
463
464 /*
465 * Called when a cd is done. If any entry in cmdtable depends on the current
466 * directory, simply clear cmdtable completely.
467 */
468
469 void
470 hashcd(void)
471 {
472 if (cmdtable_cd)
473 clearcmdentry();
474 }
475
476
477
478 /*
479 * Called before PATH is changed. The argument is the new value of PATH;
480 * pathval() still returns the old value at this point. Called with
481 * interrupts off.
482 */
483
484 void
485 changepath(const char *newval __unused)
486 {
487 clearcmdentry();
488 }
489
490
491 /*
492 * Clear out cached utility locations.
493 */
494
495 void
496 clearcmdentry(void)
497 {
498 struct tblentry **tblp;
499 struct tblentry **pp;
500 struct tblentry *cmdp;
501
502 INTOFF;
503 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
504 pp = tblp;
505 while ((cmdp = *pp) != NULL) {
506 if (cmdp->cmdtype == CMDNORMAL) {
507 *pp = cmdp->next;
508 ckfree(cmdp);
509 } else {
510 pp = &cmdp->next;
511 }
512 }
513 }
514 cmdtable_cd = 0;
515 INTON;
516 }
517
518
519 /*
520 * Locate a command in the command hash table. If "add" is nonzero,
521 * add the command to the table if it is not already present. The
522 * variable "lastcmdentry" is set to point to the address of the link
523 * pointing to the entry, so that delete_cmd_entry can delete the
524 * entry.
525 */
526
527 static struct tblentry **lastcmdentry;
528
529
530 static struct tblentry *
531 cmdlookup(const char *name, int add)
532 {
533 unsigned int hashval;
534 const char *p;
535 struct tblentry *cmdp;
536 struct tblentry **pp;
537 size_t len;
538
539 p = name;
540 hashval = (unsigned char)*p << 4;
541 while (*p)
542 hashval += *p++;
543 pp = &cmdtable[hashval % CMDTABLESIZE];
544 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
545 if (equal(cmdp->cmdname, name))
546 break;
547 pp = &cmdp->next;
548 }
549 if (add && cmdp == NULL) {
550 INTOFF;
551 len = strlen(name);
552 cmdp = *pp = ckmalloc(sizeof (struct tblentry) + len + 1);
553 cmdp->next = NULL;
554 cmdp->cmdtype = CMDUNKNOWN;
555 memcpy(cmdp->cmdname, name, len + 1);
556 INTON;
557 }
558 lastcmdentry = pp;
559 return cmdp;
560 }
561
562 /*
563 * Delete the command entry returned on the last lookup.
564 */
565
566 static void
567 delete_cmd_entry(void)
568 {
569 struct tblentry *cmdp;
570
571 INTOFF;
572 cmdp = *lastcmdentry;
573 *lastcmdentry = cmdp->next;
574 ckfree(cmdp);
575 INTON;
576 }
577
578
579
580 /*
581 * Add a new command entry, replacing any existing command entry for
582 * the same name.
583 */
584
585 static void
586 addcmdentry(const char *name, struct cmdentry *entry)
587 {
588 struct tblentry *cmdp;
589
590 INTOFF;
591 cmdp = cmdlookup(name, 1);
592 if (cmdp->cmdtype == CMDFUNCTION) {
593 unreffunc(cmdp->param.func);
594 }
595 cmdp->cmdtype = entry->cmdtype;
596 cmdp->param = entry->u;
597 cmdp->special = entry->special;
598 INTON;
599 }
600
601
602 /*
603 * Define a shell function.
604 */
605
606 void
607 defun(const char *name, union node *func)
608 {
609 struct cmdentry entry;
610
611 INTOFF;
612 entry.cmdtype = CMDFUNCTION;
613 entry.u.func = copyfunc(func);
614 entry.special = 0;
615 addcmdentry(name, &entry);
616 INTON;
617 }
618
619
620 /*
621 * Delete a function if it exists.
622 * Called with interrupts off.
623 */
624
625 int
626 unsetfunc(const char *name)
627 {
628 struct tblentry *cmdp;
629
630 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
631 unreffunc(cmdp->param.func);
632 delete_cmd_entry();
633 return (0);
634 }
635 return (0);
636 }
637
638
639 /*
640 * Check if a function by a certain name exists.
641 */
642 int
643 isfunc(const char *name)
644 {
645 struct tblentry *cmdp;
646 cmdp = cmdlookup(name, 0);
647 return (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION);
648 }
649
650
651 /*
652 * Shared code for the following builtin commands:
653 * type, command -v, command -V
654 */
655
656 int
657 typecmd_impl(int argc, char **argv, int cmd, const char *path)
658 {
659 struct cmdentry entry;
660 struct tblentry *cmdp;
661 const char *const *pp;
662 struct alias *ap;
663 int i;
664 int error1 = 0;
665
666 if (path != pathval())
667 clearcmdentry();
668
669 for (i = 1; i < argc; i++) {
670 /* First look at the keywords */
671 for (pp = parsekwd; *pp; pp++)
672 if (**pp == *argv[i] && equal(*pp, argv[i]))
673 break;
674
675 if (*pp) {
676 if (cmd == TYPECMD_SMALLV)
677 out1fmt("%s\n", argv[i]);
678 else
679 out1fmt("%s is a shell keyword\n", argv[i]);
680 continue;
681 }
682
683 /* Then look at the aliases */
684 if ((ap = lookupalias(argv[i], 1)) != NULL) {
685 if (cmd == TYPECMD_SMALLV) {
686 out1fmt("alias %s=", argv[i]);
687 out1qstr(ap->val);
688 outcslow('\n', out1);
689 } else
690 out1fmt("%s is an alias for %s\n", argv[i],
691 ap->val);
692 continue;
693 }
694
695 /* Then check if it is a tracked alias */
696 if ((cmdp = cmdlookup(argv[i], 0)) != NULL) {
697 entry.cmdtype = cmdp->cmdtype;
698 entry.u = cmdp->param;
699 entry.special = cmdp->special;
700 }
701 else {
702 /* Finally use brute force */
703 find_command(argv[i], &entry, 0, path);
704 }
705
706 switch (entry.cmdtype) {
707 case CMDNORMAL: {
708 if (strchr(argv[i], '/') == NULL) {
709 const char *path2 = path;
710 char *name;
711 int j = entry.u.index;
712 do {
713 name = padvance(&path2, argv[i]);
714 stunalloc(name);
715 } while (--j >= 0);
716 if (cmd == TYPECMD_SMALLV)
717 out1fmt("%s\n", name);
718 else
719 out1fmt("%s is%s %s\n", argv[i],
720 (cmdp && cmd == TYPECMD_TYPE) ?
721 " a tracked alias for" : "",
722 name);
723 } else {
724 if (eaccess(argv[i], X_OK) == 0) {
725 if (cmd == TYPECMD_SMALLV)
726 out1fmt("%s\n", argv[i]);
727 else
728 out1fmt("%s is %s\n", argv[i],
729 argv[i]);
730 } else {
731 if (cmd != TYPECMD_SMALLV)
732 outfmt(out2, "%s: %s\n",
733 argv[i], strerror(errno));
734 error1 |= 127;
735 }
736 }
737 break;
738 }
739 case CMDFUNCTION:
740 if (cmd == TYPECMD_SMALLV)
741 out1fmt("%s\n", argv[i]);
742 else
743 out1fmt("%s is a shell function\n", argv[i]);
744 break;
745
746 case CMDBUILTIN:
747 if (cmd == TYPECMD_SMALLV)
748 out1fmt("%s\n", argv[i]);
749 else if (entry.special)
750 out1fmt("%s is a special shell builtin\n",
751 argv[i]);
752 else
753 out1fmt("%s is a shell builtin\n", argv[i]);
754 break;
755
756 default:
757 if (cmd != TYPECMD_SMALLV)
758 outfmt(out2, "%s: not found\n", argv[i]);
759 error1 |= 127;
760 break;
761 }
762 }
763
764 if (path != pathval())
765 clearcmdentry();
766
767 return error1;
768 }
769
770 /*
771 * Locate and print what a word is...
772 */
773
774 int
775 typecmd(int argc, char **argv)
776 {
777 if (argc > 2 && strcmp(argv[1], "--") == 0)
778 argc--, argv++;
779 return typecmd_impl(argc, argv, TYPECMD_TYPE, bltinlookup("PATH", 1));
780 }