source: trunk/src/kash/exec.c@ 3475

Last change on this file since 3475 was 3475, checked in by bird, 5 years ago

kash: exec.c/h+eval.c: Fixed no-rehashing-needed optimizations so they work for windows and OS/2 as well (UNIX-specific abspath detection). Cache the suffix found by stat_pc_exec_exts so that we don't have to repeat it 2 microseconds after find_command called it. Use the specialized shfile_stat variants where possible. eval.c: Fixed double free of commandname in evalcommand_doit.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
File size: 31.8 KB
Line 
1/* $NetBSD: exec.c,v 1.37 2003/08/07 09:05:31 agc 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#if 0
36#ifndef lint
37static char sccsid[] = "@(#)exec.c 8.4 (Berkeley) 6/8/95";
38#else
39__RCSID("$NetBSD: exec.c,v 1.37 2003/08/07 09:05:31 agc Exp $");
40#endif /* not lint */
41#endif
42
43#include <sys/types.h>
44#include <errno.h>
45#include <stdio.h>
46#include <stdlib.h>
47#include <stddef.h>
48#include <assert.h>
49
50/*
51 * When commands are first encountered, they are entered in a hash table.
52 * This ensures that a full path search will not have to be done for them
53 * on each invocation.
54 *
55 * We should investigate converting to a linear search, even though that
56 * would make the command name "hash" a misnomer.
57 */
58
59#include "shell.h"
60#include "main.h"
61#include "nodes.h"
62#include "parser.h"
63#include "redir.h"
64#include "eval.h"
65#include "exec.h"
66#include "builtins.h"
67#include "var.h"
68#include "options.h"
69#include "input.h"
70#include "output.h"
71#include "syntax.h"
72#include "memalloc.h"
73#include "error.h"
74#include "init.h"
75#include "mystring.h"
76#include "show.h"
77#include "jobs.h"
78#include "alias.h"
79#ifdef __INNOTEK_LIBC__
80#include <InnoTekLIBC/backend.h>
81#endif
82#include "shinstance.h"
83
84//#define CMDTABLESIZE 31 /* should be prime */
85//#define ARB 1 /* actual size determined at run time */
86//
87//
88//
89//struct tblentry {
90// struct tblentry *next; /* next entry in hash chain */
91// union param param; /* definition of builtin function */
92// short cmdtype; /* index identifying command */
93// char rehash; /* if set, cd done since entry created */
94// char cmdname[ARB]; /* name of command */
95//};
96//
97//
98//STATIC struct tblentry *cmdtable[CMDTABLESIZE];
99//STATIC int builtinloc = -1; /* index in path of %builtin, or -1 */
100//int exerrno = 0; /* Last exec error */
101#ifdef PC_EXE_EXTS
102STATIC const char * const g_exe_suffixes[] = { "", ".exe", ".cmd", ".btm", ".com" };
103#endif
104
105
106STATIC void tryexec(shinstance *, char *, char **, char **, int);
107STATIC void execinterp(shinstance *, char **, char **);
108STATIC void printentry(shinstance *, struct tblentry *, int);
109STATIC void clearcmdentry(shinstance *, int);
110STATIC struct tblentry *cmdlookup(shinstance *, const char *, int);
111STATIC void delete_cmd_entry(shinstance *);
112#ifdef PC_EXE_EXTS
113STATIC int stat_pc_exec_exts(shinstance *, char *fullname, int has_ext, int *suffixp);
114#endif
115
116
117extern char *const parsekwd[];
118
119#ifndef SH_FORKED_MODE
120void
121subshellinitexec(shinstance *psh, shinstance *inherit)
122{
123 unsigned i;
124 for (i = 0; i < K_ELEMENTS(inherit->cmdtable); i++) {
125 struct tblentry const *csrc = inherit->cmdtable[i];
126 if (!csrc) {
127 } else {
128 struct tblentry **ppdst = &psh->cmdtable[i];
129 do
130 {
131 size_t const namesize = strlen(csrc->cmdname) + 1;
132 size_t const entrysize = offsetof(struct tblentry, cmdname) + namesize;
133 struct tblentry *dst = (struct tblentry *)ckmalloc(psh, entrysize);
134 memcpy(dst->cmdname, csrc->cmdname, namesize);
135 dst->rehash = csrc->rehash;
136 dst->cmdtype = csrc->cmdtype;
137
138 dst->param.func = NULL;
139 switch (csrc->cmdtype) {
140 case CMDUNKNOWN:
141 case CMDNORMAL:
142 dst->param.n.index = csrc->param.n.index;
143 dst->param.n.suffix = csrc->param.n.suffix;
144 break;
145 case CMDFUNCTION:
146 dst->param.func = copyfunc(psh, csrc->param.func); /** @todo optimize function allocations */
147 break;
148 case CMDBUILTIN:
149 case CMDSPLBLTIN:
150 dst->param.bltin = csrc->param.bltin;
151 break;
152 }
153
154 *ppdst = dst;
155 ppdst = &dst->next;
156
157 csrc = csrc->next;
158 } while (csrc);
159 *ppdst = NULL;
160 }
161 }
162
163 psh->builtinloc = inherit->builtinloc;
164}
165#endif /* SH_FORKED_MODE */
166
167
168/*
169 * Check if 'path' is an absolute (starts with root) path or not.
170 */
171K_INLINE isabspath(const char *path)
172{
173#if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
174 if (path[0] == '/' || path[0] == '\\') {
175 if ( (path[1] == '/' || path[1] == '\\')
176 && (path[2] != '/' && path[2] != '\\' && path[2]))
177 return 1;
178 } else if (path[0] && path[1] == ':' && (path[2] == '\\' || path[2] == '/') && isalpha(path[0])) {
179 return 1;
180 }
181 return 0;
182#else
183 return path[0] == '/';
184#endif
185}
186
187/*
188 * Checks if the filename include a path or not.
189 */
190K_INLINE haspath(const char *name)
191{
192#if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
193 return strchr(name, '/') != NULL
194 || strchr(name, '\\') != NULL
195 || (name[0] && name[1] == ':');
196#else
197 return strchr(name, '/') != NULL;
198#endif
199}
200
201
202/*
203 * Exec a program. Never returns. If you change this routine, you may
204 * have to change the find_command routine as well.
205 */
206
207SH_NORETURN_1 void
208shellexec(shinstance *psh, char **argv, char **envp, const char *path, int idx, int suffix)
209{
210 char *cmdname;
211 int e;
212 const char *argv0 = argv[0];
213 int argv0len = (int)strlen(argv0);
214 char kmkcmd[48];
215#ifdef PC_EXE_EXTS
216 int has_ext = argv0len - 4;
217 has_ext = has_ext > 0
218 && argv0[has_ext] == '.'
219 /* use strstr and upper/lower permuated extensions to avoid multiple strcasecmp calls. */
220 && strstr("exe;" "Exe;" "EXe;" "EXE;" "ExE;" "eXe;" "eXE;" "exE;"
221 "cmd;" "Cmd;" "CMd;" "CMD;" "CmD;" "cMd;" "cMD;" "cmD;"
222 "com;" "Com;" "COm;" "COM;" "CoM;" "cOm;" "cOM;" "coM;"
223 "bat;" "Bat;" "BAt;" "BAT;" "BaT;" "bAt;" "bAT;" "baT;"
224 "btm;" "Btm;" "BTm;" "BTM;" "BtM;" "bTm;" "bTM;" "btM;",
225 argv0 + has_ext + 1)
226 != NULL;
227#else
228 const int has_ext = 1;
229#endif
230 TRACE((psh, "shellexec: argv[0]=%s idx=%d suffix=%d\n", argv0, idx, suffix));
231 if (haspath(argv0)) {
232#ifdef PC_EXE_EXTS
233 if (!has_ext && suffix && (unsigned)suffix < K_ELEMENTS(g_exe_suffixes)) {
234 size_t sufflen = strlen(g_exe_suffixes[suffix]);
235 cmdname = stalloc(psh, argv0len + sufflen + 1);
236 memcpy(cmdname, argv0, argv0len);
237 memcpy(cmdname + argv0len, g_exe_suffixes[suffix], sufflen + 1);
238 } else
239#endif
240 {
241 cmdname = stalloc(psh, argv0len + 5);
242 memcpy(cmdname, argv0, argv0len + 1);
243 }
244 tryexec(psh, cmdname, argv, envp, has_ext);
245 TRACE((psh, "shellexec: cmdname=%s\n", cmdname));
246 stunalloc(psh, cmdname);
247 e = errno;
248 } else {
249 /* Before we search the PATH, transform kmk_builtin_% to kmk_% so we don't
250 need to be too careful mixing internal and external kmk commands. */
251 if ( argv0len > 12
252 && argv0len < 42
253 && strncmp(argv0, "kmk_builtin_", 12) == 0
254 && strpbrk(argv0 + 12, "./\\-:;<>") == NULL) {
255 memcpy(kmkcmd, "kmk_", 4);
256 memcpy(&kmkcmd[4], argv0 + 12, argv0len + 1 - 8);
257 TRACE((psh, "shellexec: dropped '_builtin' from %s to %s\n", argv0, kmkcmd));
258 argv0len -= 8;
259 argv0 = kmkcmd;
260 }
261
262 e = ENOENT;
263 while ((cmdname = padvance(psh, &path, argv0)) != NULL) {
264 if (--idx < 0 && psh->pathopt == NULL) {
265#ifdef PC_EXE_EXTS
266 if (!has_ext && idx == -1 && suffix && (unsigned)suffix < K_ELEMENTS(g_exe_suffixes))
267 strcat(cmdname, g_exe_suffixes[suffix]);
268#endif
269 tryexec(psh, cmdname, argv, envp, has_ext);
270 if (errno != ENOENT && errno != ENOTDIR)
271 e = errno;
272 }
273 stunalloc(psh, cmdname);
274 }
275 }
276
277 /* Map to POSIX errors */
278 switch (e) {
279 case EACCES:
280 psh->exerrno = 126;
281 break;
282 case ENOENT:
283 psh->exerrno = 127;
284 break;
285 default:
286 psh->exerrno = 2;
287 break;
288 }
289 TRACE((psh, "shellexec failed for '%s', errno %d, suppressint %d\n",
290 argv[0], e, psh->suppressint ));
291 exerror(psh, EXEXEC, "%s: %s", argv[0], errmsg(psh, e, E_EXEC));
292 /* NOTREACHED */
293}
294
295
296STATIC void
297tryexec(shinstance *psh, char *cmd, char **argv, char **envp, int has_ext)
298{
299 int e;
300#ifdef EXEC_HASH_BANG_SCRIPT
301 char *p;
302#endif
303#ifdef PC_EXE_EXTS
304 /* exploit the effect of stat_pc_exec_exts which adds the
305 * correct extentions to the file. */
306 if (!has_ext) {
307 int suffix;
308 int isreg = stat_pc_exec_exts(psh, cmd, 0, &suffix);
309 assert(isreg > 0);
310 }
311#endif
312#if defined(__INNOTEK_LIBC__) && defined(EXEC_HASH_BANG_SCRIPT)
313 __libc_Back_gfProcessHandleHashBangScripts = 0;
314#endif
315
316#ifdef SYSV
317 do {
318 sh_execve(psh, cmd, argv, envp);
319 } while (errno == EINTR);
320#else
321 sh_execve(psh, cmd, (const char * const*)argv, (const char * const*)envp);
322#endif
323 e = errno;
324 if (e == ENOEXEC) {
325 initshellproc(psh);
326 setinputfile(psh, cmd, 0);
327 if (psh->commandnamemalloc) {
328 sh_free(psh, psh->commandname);
329 psh->commandnamemalloc = 0;
330 }
331 if (psh->arg0malloc)
332 sh_free(psh, psh->arg0);
333 psh->commandname = psh->arg0 = savestr(psh, argv[0]);
334 psh->arg0malloc = 1;
335#ifdef EXEC_HASH_BANG_SCRIPT
336 pgetc(psh); pungetc(psh); /* fill up input buffer */
337 p = psh->parsenextc;
338 if (psh->parsenleft > 2 && p[0] == '#' && p[1] == '!') {
339 argv[0] = cmd;
340 execinterp(psh, argv, envp);
341 }
342#endif
343 setparam(psh, argv + 1);
344 exraise(psh, EXSHELLPROC);
345 }
346 errno = e;
347}
348
349#ifdef EXEC_HASH_BANG_SCRIPT
350
351/*
352 * Checks if NAME is the (base) name of the shell executable or something
353 * very similar.
354 */
355STATIC int
356is_shell_exe_name(const char *name)
357{
358 return equal(name, "kmk_ash")
359 || equal(name, "kmk_sh")
360 || equal(name, "kash")
361 || equal(name, "sh");
362}
363
364/*
365 * Execute an interpreter introduced by "#!", for systems where this
366 * feature has not been built into the kernel. If the interpreter is
367 * the shell, return (effectively ignoring the "#!"). If the execution
368 * of the interpreter fails, exit.
369 *
370 * This code peeks inside the input buffer in order to avoid actually
371 * reading any input. It would benefit from a rewrite.
372 */
373
374#define NEWARGS 16
375
376STATIC void
377execinterp(shinstance *psh, char **argv, char **envp)
378{
379 int n;
380 char *inp;
381 char *outp;
382 char c;
383 char *p;
384 char **ap;
385 char *newargs[NEWARGS];
386 intptr_t i;
387 char **ap2;
388 char **new;
389
390 /* Split the string into arguments. */
391 n = psh->parsenleft - 2;
392 inp = psh->parsenextc + 2;
393 ap = newargs;
394 for (;;) {
395 while (--n >= 0 && (*inp == ' ' || *inp == '\t'))
396 inp++;
397 if (n < 0)
398 goto bad;
399 if ((c = *inp++) == '\n')
400 break;
401 if (ap == &newargs[NEWARGS])
402bad: error(psh, "Bad #! line");
403 STARTSTACKSTR(psh, outp);
404 do {
405 STPUTC(psh, c, outp);
406 } while (--n >= 0 && (c = *inp++) != ' ' && c != '\t' && c != '\n');
407 STPUTC(psh, '\0', outp);
408 n++, inp--;
409 *ap++ = grabstackstr(psh, outp);
410 }
411
412 /* /usr/bin/env emulation, very common with kash/kmk_ash. */
413 i = ap - newargs;
414 if (i > 1 && equal(newargs[0], "/usr/bin/env")) {
415 if ( !strchr(newargs[1], '=')
416 && newargs[1][0] != '-') {
417 /* shellexec below searches the PATH for us, so just
418 drop /usr/bin/env. */
419 TRACE((psh, "hash bang /usr/bin/env utility, dropping /usr/bin/env\n"));
420 ap--;
421 i--;
422 for (n = 0; n < i; n++)
423 newargs[n] = newargs[n + 1];
424 } /* else: complicated invocation */
425 }
426
427 /* If the interpreter is the shell or a similar shell, there is
428 no need to exec. */
429 if (i == 1) {
430 p = strrchr(newargs[0], '/');
431 if (!p)
432 p = newargs[0];
433 if (is_shell_exe_name(p)) {
434 TRACE((psh, "hash bang self\n"));
435 return;
436 }
437 }
438
439 /* Combine the two argument lists and exec. */
440 i = (char *)ap - (char *)newargs; /* size in bytes */
441 if (i == 0)
442 error(psh, "Bad #! line");
443 for (ap2 = argv ; *ap2++ != NULL ; );
444 new = ckmalloc(psh, i + ((char *)ap2 - (char *)argv));
445 ap = newargs, ap2 = new;
446 while ((i -= sizeof (char **)) >= 0)
447 *ap2++ = *ap++;
448 ap = argv;
449 while ((*ap2++ = *ap++))
450 /* nothing*/;
451 TRACE((psh, "hash bang '%s'\n", new[0]));
452 shellexec(psh, new, envp, pathval(psh), 0, -1);
453 /* NOTREACHED */
454}
455
456#endif /* EXEC_HASH_BANG_SCRIPT */
457
458
459/*
460 * Do a path search. The variable path (passed by reference) should be
461 * set to the start of the path before the first call; padvance will update
462 * this value as it proceeds. Successive calls to padvance will return
463 * the possible path expansions in sequence. If an option (indicated by
464 * a percent sign) appears in the path entry then the global variable
465 * psh->pathopt will be set to point to it; otherwise psh->pathopt will be set to
466 * NULL.
467 */
468
469//const char *pathopt;
470
471char *
472padvance(shinstance *psh, const char **path, const char *name)
473{
474 const char *p;
475 char *q;
476 const char *start;
477 int len;
478
479 if (*path == NULL)
480 return NULL;
481 start = *path;
482#ifdef PC_PATH_SEP
483 for (p = start ; *p && *p != ';' && *p != '%' ; p++);
484#else
485 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
486#endif
487 len = (int)(p - start + strlen(name) + 2); /* "2" is for '/' and '\0' */
488#ifdef PC_EXE_EXTS
489 len += 4; /* "4" is for .exe/.com/.cmd/.bat/.btm */
490#endif
491 while (stackblocksize(psh) < len)
492 growstackblock(psh);
493 q = stackblock(psh);
494 if (p != start) {
495 memcpy(q, start, p - start);
496 q += p - start;
497 *q++ = '/';
498 }
499 strcpy(q, name);
500 psh->pathopt = NULL;
501 if (*p == '%') {
502 psh->pathopt = ++p;
503#ifdef PC_PATH_SEP
504 while (*p && *p != ';') p++;
505#else
506 while (*p && *p != ':') p++;
507#endif
508 }
509#ifdef PC_PATH_SEP
510 if (*p == ';')
511#else
512 if (*p == ':')
513#endif
514 *path = p + 1;
515 else
516 *path = NULL;
517 return stalloc(psh, len);
518}
519
520
521#ifdef PC_EXE_EXTS
522STATIC int stat_pc_exec_exts(shinstance *psh, char *fullname, int has_ext, int *suffixp)
523{
524 int isreg;
525
526 /* skip the SYSV crap */
527 if ((isreg = shfile_stat_isreg(&psh->fdtab, fullname)) >= 1) {
528 *suffixp = 0;
529 return isreg;
530 }
531 if (!has_ext && errno == ENOENT)
532 {
533 /* Ignore non-regular files here. */
534 char *psz = strchr(fullname, '\0');
535 int i;
536 for (i = 1 /*first entry is empty*/; i < K_ELEMENTS(g_exe_suffixes); i++) {
537 strcpy(psz, g_exe_suffixes[i]);
538 if ((isreg = shfile_stat_isreg(&psh->fdtab, fullname)) >= 1) {
539 *suffixp = i;
540 return isreg;
541 }
542 if (isreg < 0 && errno != ENOENT && errno != ENOTDIR)
543 break;
544 }
545 }
546 *suffixp = -1;
547 return isreg;
548}
549#endif /* PC_EXE_EXTS */
550
551
552
553/*** Command hashing code ***/
554
555
556int
557hashcmd(shinstance *psh, int argc, char **argv)
558{
559 struct tblentry **pp;
560 struct tblentry *cmdp;
561 int c;
562 int verbose;
563 struct cmdentry entry;
564 char *name;
565
566 verbose = 0;
567 while ((c = nextopt(psh, "rv")) != '\0') {
568 if (c == 'r') {
569 clearcmdentry(psh, 0);
570 } else if (c == 'v') {
571 verbose++;
572 }
573 }
574 if (*psh->argptr == NULL) {
575 for (pp = psh->cmdtable ; pp < &psh->cmdtable[CMDTABLESIZE] ; pp++) {
576 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
577 if (verbose || cmdp->cmdtype == CMDNORMAL)
578 printentry(psh, cmdp, verbose);
579 }
580 }
581 return 0;
582 }
583 while ((name = *psh->argptr) != NULL) {
584 if ((cmdp = cmdlookup(psh, name, 0)) != NULL
585 && (cmdp->cmdtype == CMDNORMAL
586 || (cmdp->cmdtype == CMDBUILTIN && psh->builtinloc >= 0)))
587 delete_cmd_entry(psh);
588 find_command(psh, name, &entry, DO_ERR, pathval(psh));
589 if (verbose) {
590 if (entry.cmdtype != CMDUNKNOWN) { /* if no error msg */
591 cmdp = cmdlookup(psh, name, 0);
592 printentry(psh, cmdp, verbose);
593 }
594 output_flushall(psh);
595 }
596 psh->argptr++;
597 }
598 return 0;
599}
600
601
602STATIC void
603printentry(shinstance *psh, struct tblentry *cmdp, int verbose)
604{
605 int idx;
606 const char *path;
607 char *name;
608
609 switch (cmdp->cmdtype) {
610 case CMDNORMAL:
611 idx = cmdp->param.n.index;
612 path = pathval(psh);
613 do {
614 name = padvance(psh, &path, cmdp->cmdname);
615 stunalloc(psh, name);
616 } while (--idx >= 0);
617 out1str(psh, name);
618#ifdef PC_EXE_EXTS
619 if ((unsigned)cmdp->param.n.suffix < K_ELEMENTS(g_exe_suffixes))
620 out1str(psh, g_exe_suffixes[cmdp->param.n.suffix]);
621#endif
622 break;
623 case CMDSPLBLTIN:
624 out1fmt(psh, "special builtin %s", cmdp->cmdname);
625 break;
626 case CMDBUILTIN:
627 out1fmt(psh, "builtin %s", cmdp->cmdname);
628 break;
629 case CMDFUNCTION:
630 out1fmt(psh, "function %s", cmdp->cmdname);
631 if (verbose) {
632 struct procstat ps;
633 INTOFF;
634 commandtext(psh, &ps, cmdp->param.func);
635 INTON;
636 out1str(psh, "() { ");
637 out1str(psh, ps.cmd);
638 out1str(psh, "; }");
639 }
640 break;
641 default:
642 error(psh, "internal error: %s cmdtype %d", cmdp->cmdname, cmdp->cmdtype);
643 }
644 if (cmdp->rehash)
645 out1c(psh, '*');
646 out1c(psh, '\n');
647}
648
649
650
651/*
652 * Resolve a command name. If you change this routine, you may have to
653 * change the shellexec routine as well.
654 */
655
656void
657find_command(shinstance *psh, char *name, struct cmdentry *entry, int act, const char *path)
658{
659 struct tblentry *cmdp, loc_cmd;
660 int idx;
661 int prev;
662 int norehashoncd = 1;
663 char *fullname;
664 int e;
665 int (*bltin)(shinstance*,int,char **);
666 int argv0len = (int)strlen(name);
667 char kmkcmd[48];
668#ifdef PC_EXE_EXTS
669 int has_ext = argv0len - 4;
670 has_ext = has_ext > 0
671 && name[has_ext] == '.'
672 /* use strstr and upper/lower permuated extensions to avoid multiple strcasecmp calls. */
673 && strstr("exe;" "Exe;" "EXe;" "EXE;" "ExE;" "eXe;" "eXE;" "exE;"
674 "cmd;" "Cmd;" "CMd;" "CMD;" "CmD;" "cMd;" "cMD;" "cmD;"
675 "com;" "Com;" "COm;" "COM;" "CoM;" "cOm;" "cOM;" "coM;"
676 "bat;" "Bat;" "BAt;" "BAT;" "BaT;" "bAt;" "bAT;" "baT;"
677 "btm;" "Btm;" "BTm;" "BTM;" "BtM;" "bTm;" "bTM;" "btM;",
678 name + has_ext + 1)
679 != NULL;
680#endif
681
682 /* If name contains a slash, don't use PATH or hash table */
683 if (haspath(name)) {
684 if (act & DO_ABS) {
685 while (shfile_stat_exists(&psh->fdtab, name) < 0) {
686#ifdef SYSV
687 if (errno == EINTR)
688 continue;
689#endif
690 if (errno != ENOENT && errno != ENOTDIR)
691 e = errno;
692 entry->cmdtype = CMDUNKNOWN;
693 entry->u.n.index = -1;
694 entry->u.n.suffix = -1;
695 return;
696 }
697 entry->cmdtype = CMDNORMAL;
698 entry->u.n.index = -1;
699 entry->u.n.suffix = -1;
700 return;
701 }
702 entry->cmdtype = CMDNORMAL;
703 entry->u.n.index = 0;
704 entry->u.n.suffix = 0;
705 return;
706 }
707
708 if (path != pathval(psh))
709 act |= DO_ALTPATH;
710
711 if (act & DO_ALTPATH && strstr(path, "%builtin") != NULL)
712 act |= DO_ALTBLTIN;
713
714 /* If name is in the table, check answer will be ok */
715 if ((cmdp = cmdlookup(psh, name, 0)) != NULL) {
716 do {
717 switch (cmdp->cmdtype) {
718 case CMDNORMAL:
719 if (act & DO_ALTPATH) {
720 cmdp = NULL;
721 continue;
722 }
723 break;
724 case CMDFUNCTION:
725 if (act & DO_NOFUNC) {
726 cmdp = NULL;
727 continue;
728 }
729 break;
730 case CMDBUILTIN:
731 if ((act & DO_ALTBLTIN) || psh->builtinloc >= 0) {
732 cmdp = NULL;
733 continue;
734 }
735 break;
736 }
737 /* if not invalidated by cd, we're done */
738 if (cmdp->rehash == 0)
739 goto success;
740 } while (0);
741 }
742
743 /* If %builtin not in path, check for builtin next */
744 if ((act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : psh->builtinloc < 0) &&
745 (bltin = find_builtin(psh, name)) != 0)
746 goto builtin_success;
747
748 /* We have to search path. */
749 prev = -1; /* where to start */
750 if (cmdp) { /* doing a rehash */
751 if (cmdp->cmdtype == CMDBUILTIN)
752 prev = psh->builtinloc;
753 else
754 prev = cmdp->param.n.index;
755 }
756
757 /* Before we search the PATH, transform kmk_builtin_% to kmk_% so we don't
758 need to be too careful mixing internal and external kmk command. */
759 if ( argv0len > 12
760 && argv0len < (int)sizeof(kmkcmd)
761 && strncmp(name, "kmk_builtin_", 12) == 0
762 && strpbrk(name + 12, "./\\-:;<>") == NULL) {
763 memcpy(kmkcmd, "kmk_", 4);
764 memcpy(&kmkcmd[4], name + 12, argv0len + 1 - 8);
765 TRACE((psh, "find_command: dropped '_builtin' from %s to %s\n", name, kmkcmd));
766 argv0len -= 8;
767 name = kmkcmd;
768 }
769
770 e = ENOENT;
771 idx = -1;
772loop:
773 while ((fullname = padvance(psh, &path, name)) != NULL) {
774#ifdef PC_EXE_EXTS
775 int suffix;
776#endif
777 int isreg;
778 stunalloc(psh, fullname);
779 idx++;
780 if (psh->pathopt) {
781 if (prefix("builtin", psh->pathopt)) {
782 if ((bltin = find_builtin(psh, name)) == 0)
783 goto loop;
784 goto builtin_success;
785 } else if (prefix("func", psh->pathopt)) {
786 /* handled below */
787 } else {
788 /* ignore unimplemented options */
789 goto loop;
790 }
791 }
792 /* if rehash, don't redo absolute path names */
793 if (idx <= prev && isabspath(fullname)) {
794 if (idx < prev)
795 goto loop;
796 TRACE((psh, "searchexec \"%s\": no change\n", name));
797 goto success;
798 }
799#ifdef PC_EXE_EXTS
800 while ((isreg = stat_pc_exec_exts(psh, fullname, has_ext, &suffix)) < 0) {
801#else
802 while ((isreg = shfile_stat_isreg(&psh->fdtab, fullname)) < 0) {
803#endif
804#ifdef SYSV
805 if (errno == EINTR)
806 continue;
807#endif
808 if (errno != ENOENT && errno != ENOTDIR)
809 e = errno;
810
811 goto loop;
812 }
813 e = EACCES; /* if we fail, this will be the error */
814 if (isreg < 1)
815 goto loop;
816 if (psh->pathopt) { /* this is a %func directory */
817 if (act & DO_NOFUNC)
818 goto loop;
819 stalloc(psh, strlen(fullname) + 1);
820 readcmdfile(psh, fullname);
821 if ((cmdp = cmdlookup(psh, name, 0)) == NULL ||
822 cmdp->cmdtype != CMDFUNCTION)
823 error(psh, "%s not defined in %s", name, fullname);
824 stunalloc(psh, fullname);
825 goto success;
826 }
827#ifdef notdef
828 /* XXX this code stops root executing stuff, and is buggy
829 if you need a group from the group list. */
830 if (statb.st_uid == sh_geteuid(psh)) {
831 if ((statb.st_mode & 0100) == 0)
832 goto loop;
833 } else if (statb.st_gid == sh_getegid(psh)) {
834 if ((statb.st_mode & 010) == 0)
835 goto loop;
836 } else {
837 if ((statb.st_mode & 01) == 0)
838 goto loop;
839 }
840#endif
841 TRACE((psh, "searchexec \"%s\" returns \"%s\"\n", name, fullname));
842 INTOFF;
843 if (act & DO_ALTPATH) {
844 stalloc(psh, strlen(fullname) + 1);
845 cmdp = &loc_cmd;
846 } else
847 cmdp = cmdlookup(psh, name, 1);
848 cmdp->cmdtype = CMDNORMAL;
849 cmdp->param.n.index = idx;
850 cmdp->param.n.suffix = suffix;
851 INTON;
852 goto success;
853 }
854
855 /* We failed. If there was an entry for this command, delete it */
856 if (cmdp)
857 delete_cmd_entry(psh);
858 if (act & DO_ERR)
859 outfmt(psh->out2, "%s: %s\n", name, errmsg(psh, e, E_EXEC));
860 entry->cmdtype = CMDUNKNOWN;
861 return;
862
863builtin_success:
864 INTOFF;
865 if (act & DO_ALTPATH)
866 cmdp = &loc_cmd;
867 else
868 cmdp = cmdlookup(psh, name, 1);
869 if (cmdp->cmdtype == CMDFUNCTION)
870 /* DO_NOFUNC must have been set */
871 cmdp = &loc_cmd;
872 cmdp->cmdtype = CMDBUILTIN;
873 cmdp->param.bltin = bltin;
874 INTON;
875success:
876 cmdp->rehash = 0;
877 entry->cmdtype = cmdp->cmdtype;
878 entry->u = cmdp->param;
879}
880
881
882
883/*
884 * Search the table of builtin commands.
885 */
886
887int
888(*find_builtin(shinstance *psh, char *name))(shinstance *psh, int, char **)
889{
890 const struct builtincmd *bp;
891
892 for (bp = builtincmd ; bp->name ; bp++) {
893 if (*bp->name == *name && equal(bp->name, name))
894 return bp->builtin;
895 }
896 return 0;
897}
898
899int
900(*find_splbltin(shinstance *psh, char *name))(shinstance *psh, int, char **)
901{
902 const struct builtincmd *bp;
903
904 for (bp = splbltincmd ; bp->name ; bp++) {
905 if (*bp->name == *name && equal(bp->name, name))
906 return bp->builtin;
907 }
908 return 0;
909}
910
911/*
912 * At shell startup put special builtins into hash table.
913 * ensures they are executed first (see posix).
914 * We stop functions being added with the same name
915 * (as they are impossible to call)
916 */
917
918void
919hash_special_builtins(shinstance *psh)
920{
921 const struct builtincmd *bp;
922 struct tblentry *cmdp;
923
924 for (bp = splbltincmd ; bp->name ; bp++) {
925 cmdp = cmdlookup(psh, bp->name, 1);
926 cmdp->cmdtype = CMDSPLBLTIN;
927 cmdp->param.bltin = bp->builtin;
928 }
929}
930
931
932
933/*
934 * Called when a cd is done. Marks all commands so the next time they
935 * are executed they will be rehashed.
936 */
937
938void
939hashcd(shinstance *psh)
940{
941 struct tblentry **pp;
942 struct tblentry *cmdp;
943
944 for (pp = psh->cmdtable ; pp < &psh->cmdtable[CMDTABLESIZE] ; pp++) {
945 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
946 if (cmdp->cmdtype == CMDNORMAL
947 || (cmdp->cmdtype == CMDBUILTIN && psh->builtinloc >= 0))
948 cmdp->rehash = 1;
949 }
950 }
951}
952
953
954
955/*
956 * Fix command hash table when PATH changed.
957 * Called before PATH is changed. The argument is the new value of PATH;
958 * pathval(psh) still returns the old value at this point.
959 * Called with interrupts off.
960 */
961
962void
963changepath(shinstance *psh, const char *newval)
964{
965 const char *old, *new;
966 int idx;
967 int firstchange;
968 int bltin;
969
970 old = pathval(psh);
971 new = newval;
972 firstchange = 9999; /* assume no change */
973 idx = 0;
974 bltin = -1;
975 for (;;) {
976 if (*old != *new) {
977 firstchange = idx;
978#ifdef PC_PATH_SEP
979 if ((*old == '\0' && *new == ';')
980 || (*old == ';' && *new == '\0'))
981#else
982 if ((*old == '\0' && *new == ':')
983 || (*old == ':' && *new == '\0'))
984#endif
985 firstchange++;
986 old = new; /* ignore subsequent differences */
987 }
988 if (*new == '\0')
989 break;
990 if (*new == '%' && bltin < 0 && prefix("builtin", new + 1))
991 bltin = idx;
992#ifdef PC_PATH_SEP
993 if (*new == ';') {
994#else
995 if (*new == ':') {
996#endif
997 idx++;
998 }
999 new++, old++;
1000 }
1001 if (psh->builtinloc < 0 && bltin >= 0)
1002 psh->builtinloc = bltin; /* zap builtins */
1003 if (psh->builtinloc >= 0 && bltin < 0)
1004 firstchange = 0;
1005 clearcmdentry(psh, firstchange);
1006 psh->builtinloc = bltin;
1007}
1008
1009
1010/*
1011 * Clear out command entries. The argument specifies the first entry in
1012 * PATH which has changed.
1013 */
1014
1015STATIC void
1016clearcmdentry(shinstance *psh, int firstchange)
1017{
1018 struct tblentry **tblp;
1019 struct tblentry **pp;
1020 struct tblentry *cmdp;
1021
1022 INTOFF;
1023 for (tblp = psh->cmdtable ; tblp < &psh->cmdtable[CMDTABLESIZE] ; tblp++) {
1024 pp = tblp;
1025 while ((cmdp = *pp) != NULL) {
1026 if ((cmdp->cmdtype == CMDNORMAL &&
1027 cmdp->param.n.index >= firstchange)
1028 || (cmdp->cmdtype == CMDBUILTIN &&
1029 psh->builtinloc >= firstchange)) {
1030 *pp = cmdp->next;
1031 ckfree(psh, cmdp);
1032 } else {
1033 pp = &cmdp->next;
1034 }
1035 }
1036 }
1037 INTON;
1038}
1039
1040
1041/*
1042 * Delete all functions.
1043 */
1044
1045#ifdef mkinit
1046MKINIT void deletefuncs(struct shinstance *);
1047MKINIT void hash_special_builtins(struct shinstance *);
1048
1049INIT {
1050 hash_special_builtins(psh);
1051}
1052
1053SHELLPROC {
1054 deletefuncs(psh);
1055}
1056#endif
1057
1058void
1059deletefuncs(shinstance *psh)
1060{
1061 struct tblentry **tblp;
1062 struct tblentry **pp;
1063 struct tblentry *cmdp;
1064
1065 INTOFF;
1066 for (tblp = psh->cmdtable ; tblp < &psh->cmdtable[CMDTABLESIZE] ; tblp++) {
1067 pp = tblp;
1068 while ((cmdp = *pp) != NULL) {
1069 if (cmdp->cmdtype == CMDFUNCTION) {
1070 *pp = cmdp->next;
1071 freefunc(psh, cmdp->param.func);
1072 ckfree(psh, cmdp);
1073 } else {
1074 pp = &cmdp->next;
1075 }
1076 }
1077 }
1078 INTON;
1079}
1080
1081
1082
1083/*
1084 * Locate a command in the command hash table. If "add" is nonzero,
1085 * add the command to the table if it is not already present. The
1086 * variable "lastcmdentry" is set to point to the address of the link
1087 * pointing to the entry, so that delete_cmd_entry can delete the
1088 * entry.
1089 */
1090
1091struct tblentry **lastcmdentry;
1092
1093
1094STATIC struct tblentry *
1095cmdlookup(shinstance *psh, const char *name, int add)
1096{
1097 int hashval;
1098 const char *p;
1099 struct tblentry *cmdp;
1100 struct tblentry **pp;
1101
1102 p = name;
1103 hashval = *p << 4;
1104 while (*p)
1105 hashval += *p++;
1106 hashval &= 0x7FFF;
1107 pp = &psh->cmdtable[hashval % CMDTABLESIZE];
1108 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
1109 if (equal(cmdp->cmdname, name))
1110 break;
1111 pp = &cmdp->next;
1112 }
1113 if (add && cmdp == NULL) {
1114 INTOFF;
1115 cmdp = *pp = ckmalloc(psh, sizeof (struct tblentry) - ARB
1116 + strlen(name) + 1);
1117 cmdp->next = NULL;
1118 cmdp->cmdtype = CMDUNKNOWN;
1119 cmdp->rehash = 0;
1120 cmdp->param.n.index = 0;
1121 cmdp->param.n.suffix = 0;
1122 strcpy(cmdp->cmdname, name);
1123 INTON;
1124 }
1125 lastcmdentry = pp;
1126 return cmdp;
1127}
1128
1129/*
1130 * Delete the command entry returned on the last lookup.
1131 */
1132
1133STATIC void
1134delete_cmd_entry(shinstance *psh)
1135{
1136 struct tblentry *cmdp;
1137
1138 INTOFF;
1139 cmdp = *lastcmdentry;
1140 *lastcmdentry = cmdp->next;
1141 ckfree(psh, cmdp);
1142 INTON;
1143}
1144
1145
1146
1147#ifdef notdef
1148void
1149getcmdentry(shinstance *psh, char *name, struct cmdentry *entry)
1150{
1151 struct tblentry *cmdp = cmdlookup(psh, name, 0);
1152
1153 if (cmdp) {
1154 entry->u = cmdp->param;
1155 entry->cmdtype = cmdp->cmdtype;
1156 } else {
1157 entry->cmdtype = CMDUNKNOWN;
1158 entry->u.index = 0;
1159 }
1160}
1161#endif
1162
1163
1164/*
1165 * Add a new command entry, replacing any existing command entry for
1166 * the same name - except special builtins.
1167 */
1168
1169STATIC void
1170addcmdentry(shinstance *psh, char *name, struct cmdentry *entry)
1171{
1172 struct tblentry *cmdp;
1173
1174 INTOFF;
1175 cmdp = cmdlookup(psh, name, 1);
1176 if (cmdp->cmdtype != CMDSPLBLTIN) {
1177 if (cmdp->cmdtype == CMDFUNCTION) {
1178 freefunc(psh, cmdp->param.func);
1179 }
1180 cmdp->cmdtype = entry->cmdtype;
1181 cmdp->param = entry->u;
1182 }
1183 INTON;
1184}
1185
1186
1187/*
1188 * Define a shell function.
1189 */
1190
1191void
1192defun(shinstance *psh, char *name, union node *func)
1193{
1194 struct cmdentry entry;
1195
1196 INTOFF;
1197 entry.cmdtype = CMDFUNCTION;
1198 entry.u.func = copyfunc(psh, func);
1199 addcmdentry(psh, name, &entry);
1200 INTON;
1201}
1202
1203
1204/*
1205 * Delete a function if it exists.
1206 */
1207
1208int
1209unsetfunc(shinstance *psh, char *name)
1210{
1211 struct tblentry *cmdp;
1212
1213 if ((cmdp = cmdlookup(psh, name, 0)) != NULL &&
1214 cmdp->cmdtype == CMDFUNCTION) {
1215 freefunc(psh, cmdp->param.func);
1216 delete_cmd_entry(psh);
1217 return (0);
1218 }
1219 return (1);
1220}
1221
1222/*
1223 * Locate and print what a word is...
1224 * also used for 'command -[v|V]'
1225 */
1226
1227int
1228typecmd(shinstance *psh, int argc, char **argv)
1229{
1230 struct cmdentry entry;
1231 struct tblentry *cmdp;
1232 char * const *pp;
1233 struct alias *ap;
1234 int err = 0;
1235 char *arg;
1236 int c;
1237 int V_flag = 0;
1238 int v_flag = 0;
1239 int p_flag = 0;
1240
1241 while ((c = nextopt(psh, "vVp")) != 0) {
1242 switch (c) {
1243 case 'v': v_flag = 1; break;
1244 case 'V': V_flag = 1; break;
1245 case 'p': p_flag = 1; break;
1246 }
1247 }
1248
1249 if (p_flag && (v_flag || V_flag))
1250 error(psh, "cannot specify -p with -v or -V");
1251
1252 while ((arg = *psh->argptr++)) {
1253 if (!v_flag)
1254 out1str(psh, arg);
1255 /* First look at the keywords */
1256 for (pp = parsekwd; *pp; pp++)
1257 if (**pp == *arg && equal(*pp, arg))
1258 break;
1259
1260 if (*pp) {
1261 if (v_flag)
1262 err = 1;
1263 else
1264 out1str(psh, " is a shell keyword\n");
1265 continue;
1266 }
1267
1268 /* Then look at the aliases */
1269 if ((ap = lookupalias(psh, arg, 1)) != NULL) {
1270 if (!v_flag)
1271 out1fmt(psh, " is an alias for \n");
1272 out1fmt(psh, "%s\n", ap->val);
1273 continue;
1274 }
1275
1276 /* Then check if it is a tracked alias */
1277 if ((cmdp = cmdlookup(psh, arg, 0)) != NULL) {
1278 entry.cmdtype = cmdp->cmdtype;
1279 entry.u = cmdp->param;
1280 } else {
1281 /* Finally use brute force */
1282 find_command(psh, arg, &entry, DO_ABS, pathval(psh));
1283 }
1284
1285 switch (entry.cmdtype) {
1286 case CMDNORMAL: {
1287 if (!haspath(arg)) {
1288 const char *path = pathval(psh);
1289 char *name;
1290 int j = entry.u.n.index;
1291 do {
1292 name = padvance(psh, &path, arg);
1293 stunalloc(psh, name);
1294 } while (--j >= 0);
1295 if (!v_flag)
1296 out1fmt(psh, " is%s ",
1297 cmdp ? " a tracked alias for" : "");
1298#ifdef PC_EXE_EXTS
1299 if ((unsigned)entry.u.n.suffix < K_ELEMENTS(g_exe_suffixes))
1300 out1fmt(psh, "%s%s\n", name, g_exe_suffixes[entry.u.n.suffix]);
1301 else
1302#endif
1303 out1fmt(psh, "%s\n", name);
1304 } else {
1305 if (shfile_access(&psh->fdtab, arg, X_OK) == 0) {
1306 if (!v_flag)
1307 out1fmt(psh, " is ");
1308 out1fmt(psh, "%s\n", arg);
1309 } else {
1310 if (!v_flag)
1311 out1fmt(psh, ": %s\n",
1312 sh_strerror(psh, errno));
1313 else
1314 err = 126;
1315 }
1316 }
1317 break;
1318 }
1319 case CMDFUNCTION:
1320 if (!v_flag)
1321 out1str(psh, " is a shell function\n");
1322 else
1323 out1fmt(psh, "%s\n", arg);
1324 break;
1325
1326 case CMDBUILTIN:
1327 if (!v_flag)
1328 out1str(psh, " is a shell builtin\n");
1329 else
1330 out1fmt(psh, "%s\n", arg);
1331 break;
1332
1333 case CMDSPLBLTIN:
1334 if (!v_flag)
1335 out1str(psh, " is a special shell builtin\n");
1336 else
1337 out1fmt(psh, "%s\n", arg);
1338 break;
1339
1340 default:
1341 if (!v_flag)
1342 out1str(psh, ": not found\n");
1343 err = 127;
1344 break;
1345 }
1346 }
1347 return err;
1348}
Note: See TracBrowser for help on using the repository browser.