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