xref: /freebsd/contrib/tcsh/sh.exec.c (revision a5921bc3653e2e286715e6fe8d473ec0d02da38c)
1 /* $Header: /p/tcsh/cvsroot/tcsh/sh.exec.c,v 3.79 2011/02/25 23:58:34 christos Exp $ */
2 /*
3  * sh.exec.c: Search, find, and execute a command!
4  */
5 /*-
6  * Copyright (c) 1980, 1991 The Regents of the University of California.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 #include "sh.h"
34 
35 RCSID("$tcsh: sh.exec.c,v 3.79 2011/02/25 23:58:34 christos Exp $")
36 
37 #include "tc.h"
38 #include "tw.h"
39 #ifdef WINNT_NATIVE
40 #include <nt.const.h>
41 #endif /*WINNT_NATIVE*/
42 
43 /*
44  * C shell
45  */
46 
47 #ifndef OLDHASH
48 # define FASTHASH	/* Fast hashing is the default */
49 #endif /* OLDHASH */
50 
51 /*
52  * System level search and execute of a command.
53  * We look in each directory for the specified command name.
54  * If the name contains a '/' then we execute only the full path name.
55  * If there is no search path then we execute only full path names.
56  */
57 
58 /*
59  * As we search for the command we note the first non-trivial error
60  * message for presentation to the user.  This allows us often
61  * to show that a file has the wrong mode/no access when the file
62  * is not in the last component of the search path, so we must
63  * go on after first detecting the error.
64  */
65 static char *exerr;		/* Execution error message */
66 static Char *expath;		/* Path for exerr */
67 
68 /*
69  * The two part hash function is designed to let texec() call the
70  * more expensive hashname() only once and the simple hash() several
71  * times (once for each path component checked).
72  * Byte size is assumed to be 8.
73  */
74 #define BITS_PER_BYTE	8
75 
76 #ifdef FASTHASH
77 /*
78  * xhash is an array of hash buckets which are used to hash execs.  If
79  * it is allocated (havhash true), then to tell if ``name'' is
80  * (possibly) present in the i'th component of the variable path, look
81  * at the [hashname(name)] bucket of size [hashwidth] bytes, in the [i
82  * mod size*8]'th bit.  The cache size is defaults to a length of 1024
83  * buckets, each 1 byte wide.  This implementation guarantees that
84  * objects n bytes wide will be aligned on n byte boundaries.
85  */
86 # define HSHMUL		241
87 
88 static unsigned long *xhash = NULL;
89 static unsigned int hashlength = 0, uhashlength = 0;
90 static unsigned int hashwidth = 0, uhashwidth = 0;
91 static int hashdebug = 0;
92 
93 # define hash(a, b)	(((a) * HSHMUL + (b)) % (hashlength))
94 # define widthof(t)	(sizeof(t) * BITS_PER_BYTE)
95 # define tbit(f, i, t)	(((t *) xhash)[(f)] &  \
96 			 (1UL << (i & (widthof(t) - 1))))
97 # define tbis(f, i, t)	(((t *) xhash)[(f)] |= \
98 			 (1UL << (i & (widthof(t) - 1))))
99 # define cbit(f, i)	tbit(f, i, unsigned char)
100 # define cbis(f, i)	tbis(f, i, unsigned char)
101 # define sbit(f, i)	tbit(f, i, unsigned short)
102 # define sbis(f, i)	tbis(f, i, unsigned short)
103 # define ibit(f, i)	tbit(f, i, unsigned int)
104 # define ibis(f, i)	tbis(f, i, unsigned int)
105 # define lbit(f, i)	tbit(f, i, unsigned long)
106 # define lbis(f, i)	tbis(f, i, unsigned long)
107 
108 # define bit(f, i) (hashwidth==sizeof(unsigned char)  ? cbit(f,i) : \
109  		    ((hashwidth==sizeof(unsigned short) ? sbit(f,i) : \
110 		     ((hashwidth==sizeof(unsigned int)   ? ibit(f,i) : \
111 		     lbit(f,i))))))
112 # define bis(f, i) (hashwidth==sizeof(unsigned char)  ? cbis(f,i) : \
113  		    ((hashwidth==sizeof(unsigned short) ? sbis(f,i) : \
114 		     ((hashwidth==sizeof(unsigned int)   ? ibis(f,i) : \
115 		     lbis(f,i))))))
116 #else /* OLDHASH */
117 /*
118  * Xhash is an array of HSHSIZ bits (HSHSIZ / 8 chars), which are used
119  * to hash execs.  If it is allocated (havhash true), then to tell
120  * whether ``name'' is (possibly) present in the i'th component
121  * of the variable path, you look at the bit in xhash indexed by
122  * hash(hashname("name"), i).  This is setup automatically
123  * after .login is executed, and recomputed whenever ``path'' is
124  * changed.
125  */
126 # define HSHSIZ		8192	/* 1k bytes */
127 # define HSHMASK		(HSHSIZ - 1)
128 # define HSHMUL		243
129 static char xhash[HSHSIZ / BITS_PER_BYTE];
130 
131 # define hash(a, b)	(((a) * HSHMUL + (b)) & HSHMASK)
132 # define bit(h, b)	((h)[(b) >> 3] & 1 << ((b) & 7))	/* bit test */
133 # define bis(h, b)	((h)[(b) >> 3] |= 1 << ((b) & 7))	/* bit set */
134 
135 #endif /* FASTHASH */
136 
137 #ifdef VFORK
138 static int hits, misses;
139 #endif /* VFORK */
140 
141 /* Dummy search path for just absolute search when no path */
142 static Char *justabs[] = {STRNULL, 0};
143 
144 static	void	pexerr		(void) __attribute__((__noreturn__));
145 static	void	texec		(Char *, Char **);
146 int	hashname	(Char *);
147 static	int 	iscommand	(Char *);
148 
149 void
150 doexec(struct command *t, int do_glob)
151 {
152     Char *dp, **pv, **opv, **av, *sav;
153     struct varent *v;
154     int slash, gflag, rehashed;
155     int hashval, i;
156     Char   *blk[2];
157 
158     /*
159      * Glob the command name. We will search $path even if this does something,
160      * as in sh but not in csh.  One special case: if there is no PATH, then we
161      * execute only commands which start with '/'.
162      */
163     blk[0] = t->t_dcom[0];
164     blk[1] = 0;
165     gflag = 0;
166     if (do_glob)
167 	gflag = tglob(blk);
168     if (gflag) {
169 	pv = globall(blk, gflag);
170 	if (pv == 0) {
171 	    setname(short2str(blk[0]));
172 	    stderror(ERR_NAME | ERR_NOMATCH);
173 	}
174     }
175     else
176 	pv = saveblk(blk);
177     cleanup_push(pv, blk_cleanup);
178 
179     trim(pv);
180 
181     exerr = 0;
182     expath = Strsave(pv[0]);
183 #ifdef VFORK
184     Vexpath = expath;
185 #endif /* VFORK */
186 
187     v = adrof(STRpath);
188     if (v == 0 && expath[0] != '/' && expath[0] != '.')
189 	pexerr();
190     slash = any(short2str(expath), '/');
191 
192     /*
193      * Glob the argument list, if necessary. Otherwise trim off the quote bits.
194      */
195     gflag = 0;
196     av = &t->t_dcom[1];
197     if (do_glob)
198 	gflag = tglob(av);
199     if (gflag) {
200 	av = globall(av, gflag);
201 	if (av == 0) {
202 	    setname(short2str(expath));
203 	    stderror(ERR_NAME | ERR_NOMATCH);
204 	}
205     }
206     else
207 	av = saveblk(av);
208 
209     blkfree(t->t_dcom);
210     cleanup_ignore(pv);
211     cleanup_until(pv);
212     t->t_dcom = blkspl(pv, av);
213     xfree(pv);
214     xfree(av);
215     av = t->t_dcom;
216     trim(av);
217 
218     if (*av == NULL || **av == '\0')
219 	pexerr();
220 
221     xechoit(av);		/* Echo command if -x */
222 #ifdef CLOSE_ON_EXEC
223     /*
224      * Since all internal file descriptors are set to close on exec, we don't
225      * need to close them explicitly here.  Just reorient ourselves for error
226      * messages.
227      */
228     SHIN = 0;
229     SHOUT = 1;
230     SHDIAG = 2;
231     OLDSTD = 0;
232     isoutatty = isatty(SHOUT);
233     isdiagatty = isatty(SHDIAG);
234 #else
235     closech();			/* Close random fd's */
236 #endif
237     /*
238      * We must do this AFTER any possible forking (like `foo` in glob) so that
239      * this shell can still do subprocesses.
240      */
241     {
242 	sigset_t set;
243 	sigemptyset(&set);
244 	sigaddset(&set, SIGINT);
245 	sigaddset(&set, SIGCHLD);
246 	sigprocmask(SIG_UNBLOCK, &set, NULL);
247     }
248     pintr_disabled = 0;
249     pchild_disabled = 0;
250 
251     /*
252      * If no path, no words in path, or a / in the filename then restrict the
253      * command search.
254      */
255     if (v == NULL || v->vec == NULL || v->vec[0] == NULL || slash)
256 	opv = justabs;
257     else
258 	opv = v->vec;
259     sav = Strspl(STRslash, *av);/* / command name for postpending */
260 #ifndef VFORK
261     cleanup_push(sav, xfree);
262 #else /* VFORK */
263     Vsav = sav;
264 #endif /* VFORK */
265     hashval = havhash ? hashname(*av) : 0;
266 
267     rehashed = 0;
268 retry:
269     pv = opv;
270     i = 0;
271 #ifdef VFORK
272     hits++;
273 #endif /* VFORK */
274     do {
275 	/*
276 	 * Try to save time by looking at the hash table for where this command
277 	 * could be.  If we are doing delayed hashing, then we put the names in
278 	 * one at a time, as the user enters them.  This is kinda like Korn
279 	 * Shell's "tracked aliases".
280 	 */
281 	if (!slash && ABSOLUTEP(pv[0]) && havhash) {
282 #ifdef FASTHASH
283 	    if (!bit(hashval, i))
284 		goto cont;
285 #else /* OLDHASH */
286 	    int hashval1 = hash(hashval, i);
287 	    if (!bit(xhash, hashval1))
288 		goto cont;
289 #endif /* FASTHASH */
290 	}
291 	if (pv[0][0] == 0 || eq(pv[0], STRdot))	/* don't make ./xxx */
292 	    texec(*av, av);
293 	else {
294 	    dp = Strspl(*pv, sav);
295 #ifndef VFORK
296 	    cleanup_push(dp, xfree);
297 #else /* VFORK */
298 	    Vdp = dp;
299 #endif /* VFORK */
300 
301 	    texec(dp, av);
302 #ifndef VFORK
303 	    cleanup_until(dp);
304 #else /* VFORK */
305 	    Vdp = 0;
306 	    xfree(dp);
307 #endif /* VFORK */
308 	}
309 #ifdef VFORK
310 	misses++;
311 #endif /* VFORK */
312 cont:
313 	pv++;
314 	i++;
315     } while (*pv);
316 #ifdef VFORK
317     hits--;
318 #endif /* VFORK */
319     if (adrof(STRautorehash) && !rehashed && havhash && opv != justabs) {
320 	dohash(NULL, NULL);
321 	rehashed = 1;
322 	goto retry;
323     }
324 #ifndef VFORK
325     cleanup_until(sav);
326 #else /* VFORK */
327     Vsav = 0;
328     xfree(sav);
329 #endif /* VFORK */
330     pexerr();
331 }
332 
333 static void
334 pexerr(void)
335 {
336     /* Couldn't find the damn thing */
337     if (expath) {
338 	setname(short2str(expath));
339 #ifdef VFORK
340 	Vexpath = 0;
341 #endif /* VFORK */
342 	xfree(expath);
343 	expath = 0;
344     }
345     else
346 	setname("");
347     if (exerr)
348 	stderror(ERR_NAME | ERR_STRING, exerr);
349     stderror(ERR_NAME | ERR_COMMAND);
350 }
351 
352 /*
353  * Execute command f, arg list t.
354  * Record error message if not found.
355  * Also do shell scripts here.
356  */
357 static void
358 texec(Char *sf, Char **st)
359 {
360     char **t;
361     char *f;
362     struct varent *v;
363     Char  **vp;
364     Char   *lastsh[2];
365     char    pref[2];
366     int     fd;
367     Char   *st0, **ost;
368 
369     /* The order for the conversions is significant */
370     t = short2blk(st);
371     f = short2str(sf);
372 #ifdef VFORK
373     Vt = t;
374 #endif /* VFORK */
375     errno = 0;			/* don't use a previous error */
376 #ifdef apollo
377     /*
378      * If we try to execute an nfs mounted directory on the apollo, we
379      * hang forever. So until apollo fixes that..
380      */
381     {
382 	struct stat stb;
383 	if (stat(f, &stb) == 0 && S_ISDIR(stb.st_mode))
384 	    errno = EISDIR;
385     }
386     if (errno == 0)
387 #endif /* apollo */
388     {
389 #ifdef ISC_POSIX_EXEC_BUG
390 	__setostype(0);		/* "0" is "__OS_SYSV" in <sys/user.h> */
391 #endif /* ISC_POSIX_EXEC_BUG */
392 	(void) execv(f, t);
393 #ifdef ISC_POSIX_EXEC_BUG
394 	__setostype(1);		/* "1" is "__OS_POSIX" in <sys/user.h> */
395 #endif /* ISC_POSIX_EXEC_BUG */
396     }
397 #ifdef VFORK
398     Vt = 0;
399 #endif /* VFORK */
400     blkfree((Char **) t);
401     switch (errno) {
402 
403     case ENOEXEC:
404 #ifdef WINNT_NATIVE
405 		nt_feed_to_cmd(f,t);
406 #endif /* WINNT_NATIVE */
407 	/*
408 	 * From: casper@fwi.uva.nl (Casper H.S. Dik) If we could not execute
409 	 * it, don't feed it to the shell if it looks like a binary!
410 	 */
411 	if ((fd = xopen(f, O_RDONLY|O_LARGEFILE)) != -1) {
412 	    int nread;
413 	    if ((nread = xread(fd, pref, 2)) == 2) {
414 		if (!isprint((unsigned char)pref[0]) &&
415 		    (pref[0] != '\n' && pref[0] != '\t')) {
416 		    int err;
417 
418 		    err = errno;
419 		    xclose(fd);
420 		    /*
421 		     * We *know* what ENOEXEC means.
422 		     */
423 		    stderror(ERR_ARCH, f, strerror(err));
424 		}
425 	    }
426 	    else if (nread < 0) {
427 #ifdef convex
428 		int err;
429 
430 		err = errno;
431 		xclose(fd);
432 		/* need to print error incase the file is migrated */
433 		stderror(ERR_SYSTEM, f, strerror(err));
434 #endif
435 	    }
436 #ifdef _PATH_BSHELL
437 	    else {
438 		pref[0] = '#';
439 		pref[1] = '\0';
440 	    }
441 #endif
442 	}
443 #ifdef HASHBANG
444 	if (fd == -1 ||
445 	    pref[0] != '#' || pref[1] != '!' || hashbang(fd, &vp) == -1) {
446 #endif /* HASHBANG */
447 	/*
448 	 * If there is an alias for shell, then put the words of the alias in
449 	 * front of the argument list replacing the command name. Note no
450 	 * interpretation of the words at this point.
451 	 */
452 	    v = adrof1(STRshell, &aliases);
453 	    if (v == NULL || v->vec == NULL) {
454 		vp = lastsh;
455 		vp[0] = adrof(STRshell) ? varval(STRshell) : STR_SHELLPATH;
456 		vp[1] = NULL;
457 #ifdef _PATH_BSHELL
458 		if (fd != -1
459 # ifndef ISC	/* Compatible with ISC's /bin/csh */
460 		    && pref[0] != '#'
461 # endif /* ISC */
462 		    )
463 		    vp[0] = STR_BSHELL;
464 #endif
465 		vp = saveblk(vp);
466 	    }
467 	    else
468 		vp = saveblk(v->vec);
469 #ifdef HASHBANG
470 	}
471 #endif /* HASHBANG */
472 	if (fd != -1)
473 	    xclose(fd);
474 
475 	st0 = st[0];
476 	st[0] = sf;
477 	ost = st;
478 	st = blkspl(vp, st);	/* Splice up the new arglst */
479 	ost[0] = st0;
480 	sf = *st;
481 	/* The order for the conversions is significant */
482 	t = short2blk(st);
483 	f = short2str(sf);
484 	xfree(st);
485 	blkfree((Char **) vp);
486 #ifdef VFORK
487 	Vt = t;
488 #endif /* VFORK */
489 #ifdef ISC_POSIX_EXEC_BUG
490 	__setostype(0);		/* "0" is "__OS_SYSV" in <sys/user.h> */
491 #endif /* ISC_POSIX_EXEC_BUG */
492 	(void) execv(f, t);
493 #ifdef ISC_POSIX_EXEC_BUG
494 	__setostype(1);		/* "1" is "__OS_POSIX" in <sys/user.h> */
495 #endif /* ISC_POSIX_EXEC_BUG */
496 #ifdef VFORK
497 	Vt = 0;
498 #endif /* VFORK */
499 	blkfree((Char **) t);
500 	/* The sky is falling, the sky is falling! */
501 	stderror(ERR_SYSTEM, f, strerror(errno));
502 	break;
503 
504     case ENOMEM:
505 	stderror(ERR_SYSTEM, f, strerror(errno));
506 	break;
507 
508 #ifdef _IBMR2
509     case 0:			/* execv fails and returns 0! */
510 #endif /* _IBMR2 */
511     case ENOENT:
512 	break;
513 
514     default:
515 	if (exerr == 0) {
516 	    exerr = strerror(errno);
517 	    xfree(expath);
518 	    expath = Strsave(sf);
519 #ifdef VFORK
520 	    Vexpath = expath;
521 #endif /* VFORK */
522 	}
523 	break;
524     }
525 }
526 
527 struct execash_state
528 {
529     int saveIN, saveOUT, saveDIAG, saveSTD;
530     int SHIN, SHOUT, SHDIAG, OLDSTD;
531     int didfds;
532 #ifndef CLOSE_ON_EXEC
533     int didcch;
534 #endif
535     struct sigaction sigint, sigquit, sigterm;
536 };
537 
538 static void
539 execash_cleanup(void *xstate)
540 {
541     struct execash_state *state;
542 
543     state = xstate;
544     sigaction(SIGINT, &state->sigint, NULL);
545     sigaction(SIGQUIT, &state->sigquit, NULL);
546     sigaction(SIGTERM, &state->sigterm, NULL);
547 
548     doneinp = 0;
549 #ifndef CLOSE_ON_EXEC
550     didcch = state->didcch;
551 #endif /* CLOSE_ON_EXEC */
552     didfds = state->didfds;
553     xclose(SHIN);
554     xclose(SHOUT);
555     xclose(SHDIAG);
556     xclose(OLDSTD);
557     close_on_exec(SHIN = dmove(state->saveIN, state->SHIN), 1);
558     close_on_exec(SHOUT = dmove(state->saveOUT, state->SHOUT), 1);
559     close_on_exec(SHDIAG = dmove(state->saveDIAG, state->SHDIAG), 1);
560     close_on_exec(OLDSTD = dmove(state->saveSTD, state->OLDSTD), 1);
561 }
562 
563 /*ARGSUSED*/
564 void
565 execash(Char **t, struct command *kp)
566 {
567     struct execash_state state;
568 
569     USE(t);
570     if (chkstop == 0 && setintr)
571 	panystop(0);
572     /*
573      * Hmm, we don't really want to do that now because we might
574      * fail, but what is the choice
575      */
576     rechist(NULL, adrof(STRsavehist) != NULL);
577 
578 
579     sigaction(SIGINT, &parintr, &state.sigint);
580     sigaction(SIGQUIT, &parintr, &state.sigquit);
581     sigaction(SIGTERM, &parterm, &state.sigterm);
582 
583     state.didfds = didfds;
584 #ifndef CLOSE_ON_EXEC
585     state.didcch = didcch;
586 #endif /* CLOSE_ON_EXEC */
587     state.SHIN = SHIN;
588     state.SHOUT = SHOUT;
589     state.SHDIAG = SHDIAG;
590     state.OLDSTD = OLDSTD;
591 
592     (void)close_on_exec (state.saveIN = dcopy(SHIN, -1), 1);
593     (void)close_on_exec (state.saveOUT = dcopy(SHOUT, -1), 1);
594     (void)close_on_exec (state.saveDIAG = dcopy(SHDIAG, -1), 1);
595     (void)close_on_exec (state.saveSTD = dcopy(OLDSTD, -1), 1);
596 
597     lshift(kp->t_dcom, 1);
598 
599     (void)close_on_exec (SHIN = dcopy(0, -1), 1);
600     (void)close_on_exec (SHOUT = dcopy(1, -1), 1);
601     (void)close_on_exec (SHDIAG = dcopy(2, -1), 1);
602 #ifndef CLOSE_ON_EXEC
603     didcch = 0;
604 #endif /* CLOSE_ON_EXEC */
605     didfds = 0;
606     cleanup_push(&state, execash_cleanup);
607 
608     /*
609      * Decrement the shell level
610      */
611     shlvl(-1);
612 #ifdef WINNT_NATIVE
613     __nt_really_exec=1;
614 #endif /* WINNT_NATIVE */
615     doexec(kp, 1);
616 
617     cleanup_until(&state);
618 }
619 
620 void
621 xechoit(Char **t)
622 {
623     if (adrof(STRecho)) {
624 	int odidfds = didfds;
625 	flush();
626 	haderr = 1;
627 	didfds = 0;
628 	blkpr(t), xputchar('\n');
629 	flush();
630 	didfds = odidfds;
631 	haderr = 0;
632     }
633 }
634 
635 /*ARGSUSED*/
636 void
637 dohash(Char **vv, struct command *c)
638 {
639 #ifdef COMMENT
640     struct stat stb;
641 #endif
642     DIR    *dirp;
643     struct dirent *dp;
644     int     i = 0;
645     struct varent *v = adrof(STRpath);
646     Char  **pv;
647     int hashval;
648 #ifdef WINNT_NATIVE
649     int is_windir; /* check if it is the windows directory */
650     USE(hashval);
651 #endif /* WINNT_NATIVE */
652 
653     USE(c);
654 #ifdef FASTHASH
655     if (vv && vv[1]) {
656         uhashlength = atoi(short2str(vv[1]));
657         if (vv[2]) {
658 	    uhashwidth = atoi(short2str(vv[2]));
659 	    if ((uhashwidth != sizeof(unsigned char)) &&
660 	        (uhashwidth != sizeof(unsigned short)) &&
661 	        (uhashwidth != sizeof(unsigned long)))
662 	        uhashwidth = 0;
663 	    if (vv[3])
664 		hashdebug = atoi(short2str(vv[3]));
665         }
666     }
667 
668     if (uhashwidth)
669 	hashwidth = uhashwidth;
670     else {
671 	hashwidth = 0;
672 	if (v == NULL)
673 	    return;
674 	for (pv = v->vec; pv && *pv; pv++, hashwidth++)
675 	    continue;
676 	if (hashwidth <= widthof(unsigned char))
677 	    hashwidth = sizeof(unsigned char);
678 	else if (hashwidth <= widthof(unsigned short))
679 	    hashwidth = sizeof(unsigned short);
680 	else if (hashwidth <= widthof(unsigned int))
681 	    hashwidth = sizeof(unsigned int);
682 	else
683 	    hashwidth = sizeof(unsigned long);
684     }
685 
686     if (uhashlength)
687 	hashlength = uhashlength;
688     else
689         hashlength = hashwidth * (8*64);/* "average" files per dir in path */
690 
691     xfree(xhash);
692     xhash = xcalloc(hashlength * hashwidth, 1);
693 #endif /* FASTHASH */
694 
695     (void) getusername(NULL);	/* flush the tilde cashe */
696     tw_cmd_free();
697     havhash = 1;
698     if (v == NULL)
699 	return;
700     for (pv = v->vec; pv && *pv; pv++, i++) {
701 	if (!ABSOLUTEP(pv[0]))
702 	    continue;
703 	dirp = opendir(short2str(*pv));
704 	if (dirp == NULL)
705 	    continue;
706 	cleanup_push(dirp, opendir_cleanup);
707 #ifdef COMMENT			/* this isn't needed.  opendir won't open
708 				 * non-dirs */
709 	if (fstat(dirp->dd_fd, &stb) < 0 || !S_ISDIR(stb.st_mode)) {
710 	    cleanup_until(dirp);
711 	    continue;
712 	}
713 #endif
714 #ifdef WINNT_NATIVE
715 	is_windir = nt_check_if_windir(short2str(*pv));
716 #endif /* WINNT_NATIVE */
717 	while ((dp = readdir(dirp)) != NULL) {
718 	    if (dp->d_ino == 0)
719 		continue;
720 	    if (dp->d_name[0] == '.' &&
721 		(dp->d_name[1] == '\0' ||
722 		 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
723 		continue;
724 #ifdef WINNT_NATIVE
725 	    nt_check_name_and_hash(is_windir, dp->d_name, i);
726 #else /* !WINNT_NATIVE*/
727 #if defined(_UWIN) || defined(__CYGWIN__)
728 	    /* Turn foo.{exe,com,bat} into foo since UWIN's readdir returns
729 	     * the file with the .exe, .com, .bat extension
730 	     *
731 	     * Same for Cygwin, but only for .exe and .com extension.
732 	     */
733 	    {
734 		ssize_t	ext = strlen(dp->d_name) - 4;
735 		if ((ext > 0) && (strcasecmp(&dp->d_name[ext], ".exe") == 0 ||
736 #ifndef __CYGWIN__
737 				  strcasecmp(&dp->d_name[ext], ".bat") == 0 ||
738 #endif
739 				  strcasecmp(&dp->d_name[ext], ".com") == 0)) {
740 #ifdef __CYGWIN__
741 		    /* Also store the variation with extension. */
742 		    hashval = hashname(str2short(dp->d_name));
743 		    bis(hashval, i);
744 #endif /* __CYGWIN__ */
745 		    dp->d_name[ext] = '\0';
746 		}
747 	    }
748 #endif /* _UWIN || __CYGWIN__ */
749 # ifdef FASTHASH
750 	    hashval = hashname(str2short(dp->d_name));
751 	    bis(hashval, i);
752 	    if (hashdebug & 1)
753 	        xprintf(CGETS(13, 1, "hash=%-4d dir=%-2d prog=%s\n"),
754 		        hashname(str2short(dp->d_name)), i, dp->d_name);
755 # else /* OLD HASH */
756 	    hashval = hash(hashname(str2short(dp->d_name)), i);
757 	    bis(xhash, hashval);
758 # endif /* FASTHASH */
759 	    /* tw_add_comm_name (dp->d_name); */
760 #endif /* WINNT_NATIVE */
761 	}
762 	cleanup_until(dirp);
763     }
764 }
765 
766 /*ARGSUSED*/
767 void
768 dounhash(Char **v, struct command *c)
769 {
770     USE(c);
771     USE(v);
772     havhash = 0;
773 #ifdef FASTHASH
774     xfree(xhash);
775     xhash = NULL;
776 #endif /* FASTHASH */
777 }
778 
779 /*ARGSUSED*/
780 void
781 hashstat(Char **v, struct command *c)
782 {
783     USE(c);
784     USE(v);
785 #ifdef FASTHASH
786    if (havhash && hashlength && hashwidth)
787       xprintf(CGETS(13, 2, "%d hash buckets of %d bits each\n"),
788 	      hashlength, hashwidth*8);
789    if (hashdebug)
790       xprintf(CGETS(13, 3, "debug mask = 0x%08x\n"), hashdebug);
791 #endif /* FASTHASH */
792 #ifdef VFORK
793    if (hits + misses)
794       xprintf(CGETS(13, 4, "%d hits, %d misses, %d%%\n"),
795 	      hits, misses, 100 * hits / (hits + misses));
796 #endif
797 }
798 
799 
800 /*
801  * Hash a command name.
802  */
803 int
804 hashname(Char *cp)
805 {
806     unsigned long h;
807 
808     for (h = 0; *cp; cp++)
809 	h = hash(h, *cp);
810     return ((int) h);
811 }
812 
813 static int
814 iscommand(Char *name)
815 {
816     Char **opv, **pv;
817     Char *sav;
818     struct varent *v;
819     int slash = any(short2str(name), '/');
820     int hashval, rehashed, i;
821 
822     v = adrof(STRpath);
823     if (v == NULL || v->vec == NULL || v->vec[0] == NULL || slash)
824 	opv = justabs;
825     else
826 	opv = v->vec;
827     sav = Strspl(STRslash, name);	/* / command name for postpending */
828     hashval = havhash ? hashname(name) : 0;
829 
830     rehashed = 0;
831 retry:
832     pv = opv;
833     i = 0;
834     do {
835 	if (!slash && ABSOLUTEP(pv[0]) && havhash) {
836 #ifdef FASTHASH
837 	    if (!bit(hashval, i))
838 		goto cont;
839 #else /* OLDHASH */
840 	    int hashval1 = hash(hashval, i);
841 	    if (!bit(xhash, hashval1))
842 		goto cont;
843 #endif /* FASTHASH */
844 	}
845 	if (pv[0][0] == 0 || eq(pv[0], STRdot)) {	/* don't make ./xxx */
846 	    if (executable(NULL, name, 0)) {
847 		xfree(sav);
848 		return i + 1;
849 	    }
850 	}
851 	else {
852 	    if (executable(*pv, sav, 0)) {
853 		xfree(sav);
854 		return i + 1;
855 	    }
856 	}
857 cont:
858 	pv++;
859 	i++;
860     } while (*pv);
861     if (adrof(STRautorehash) && !rehashed && havhash && opv != justabs) {
862 	dohash(NULL, NULL);
863 	rehashed = 1;
864 	goto retry;
865     }
866     xfree(sav);
867     return 0;
868 }
869 
870 /* Also by:
871  *  Andreas Luik <luik@isaak.isa.de>
872  *  I S A  GmbH - Informationssysteme fuer computerintegrierte Automatisierung
873  *  Azenberstr. 35
874  *  D-7000 Stuttgart 1
875  *  West-Germany
876  * is the executable() routine below and changes to iscommand().
877  * Thanks again!!
878  */
879 
880 #ifndef WINNT_NATIVE
881 /*
882  * executable() examines the pathname obtained by concatenating dir and name
883  * (dir may be NULL), and returns 1 either if it is executable by us, or
884  * if dir_ok is set and the pathname refers to a directory.
885  * This is a bit kludgy, but in the name of optimization...
886  */
887 int
888 executable(const Char *dir, const Char *name, int dir_ok)
889 {
890     struct stat stbuf;
891     char   *strname;
892 
893     if (dir && *dir) {
894 	Char *path;
895 
896 	path = Strspl(dir, name);
897 	strname = short2str(path);
898 	xfree(path);
899     }
900     else
901 	strname = short2str(name);
902 
903     return (stat(strname, &stbuf) != -1 &&
904 	    ((dir_ok && S_ISDIR(stbuf.st_mode)) ||
905 	     (S_ISREG(stbuf.st_mode) &&
906     /* save time by not calling access() in the hopeless case */
907 	      (stbuf.st_mode & (S_IXOTH | S_IXGRP | S_IXUSR)) &&
908 	      access(strname, X_OK) == 0
909 	)));
910 }
911 #endif /*!WINNT_NATIVE*/
912 
913 struct tellmewhat_s0_cleanup
914 {
915     Char **dest, *val;
916 };
917 
918 static void
919 tellmewhat_s0_cleanup(void *xstate)
920 {
921     struct tellmewhat_s0_cleanup *state;
922 
923     state = xstate;
924     *state->dest = state->val;
925 }
926 
927 int
928 tellmewhat(struct wordent *lexp, Char **str)
929 {
930     struct tellmewhat_s0_cleanup s0;
931     int i;
932     const struct biltins *bptr;
933     struct wordent *sp = lexp->next;
934     int    aliased = 0, found;
935     Char   *s1, *s2, *cmd;
936     Char    qc;
937 
938     if (adrof1(sp->word, &aliases)) {
939 	alias(lexp);
940 	sp = lexp->next;
941 	aliased = 1;
942     }
943 
944     s0.dest = &sp->word;	/* to get the memory freeing right... */
945     s0.val = sp->word;
946     cleanup_push(&s0, tellmewhat_s0_cleanup);
947 
948     /* handle quoted alias hack */
949     if ((*(sp->word) & (QUOTE | TRIM)) == QUOTE)
950 	(sp->word)++;
951 
952     /* do quoting, if it hasn't been done */
953     s1 = s2 = sp->word;
954     while (*s2)
955 	switch (*s2) {
956 	case '\'':
957 	case '"':
958 	    qc = *s2++;
959 	    while (*s2 && *s2 != qc)
960 		*s1++ = *s2++ | QUOTE;
961 	    if (*s2)
962 		s2++;
963 	    break;
964 	case '\\':
965 	    if (*++s2)
966 		*s1++ = *s2++ | QUOTE;
967 	    break;
968 	default:
969 	    *s1++ = *s2++;
970 	}
971     *s1 = '\0';
972 
973     for (bptr = bfunc; bptr < &bfunc[nbfunc]; bptr++) {
974 	if (eq(sp->word, str2short(bptr->bname))) {
975 	    if (str == NULL) {
976 		if (aliased)
977 		    prlex(lexp);
978 		xprintf(CGETS(13, 5, "%S: shell built-in command.\n"),
979 			      sp->word);
980 		flush();
981 	    }
982 	    else
983 		*str = Strsave(sp->word);
984 	    cleanup_until(&s0);
985 	    return TRUE;
986 	}
987     }
988 #ifdef WINNT_NATIVE
989     for (bptr = nt_bfunc; bptr < &nt_bfunc[nt_nbfunc]; bptr++) {
990 	if (eq(sp->word, str2short(bptr->bname))) {
991 	    if (str == NULL) {
992 		if (aliased)
993 		    prlex(lexp);
994 		xprintf(CGETS(13, 5, "%S: shell built-in command.\n"),
995 			      sp->word);
996 		flush();
997 	    }
998 	    else
999 		*str = Strsave(sp->word);
1000 	    cleanup_until(&s0);
1001 	    return TRUE;
1002 	}
1003     }
1004 #endif /* WINNT_NATIVE*/
1005 
1006     sp->word = cmd = globone(sp->word, G_IGNORE);
1007     cleanup_push(cmd, xfree);
1008 
1009     if ((i = iscommand(sp->word)) != 0) {
1010 	Char **pv;
1011 	struct varent *v;
1012 	int    slash = any(short2str(sp->word), '/');
1013 
1014 	v = adrof(STRpath);
1015 	if (v == NULL || v->vec == NULL || v->vec[0] == NULL || slash)
1016 	    pv = justabs;
1017 	else
1018 	    pv = v->vec;
1019 
1020 	pv += i - 1;
1021 	if (pv[0][0] == 0 || eq(pv[0], STRdot)) {
1022 	    if (!slash) {
1023 		sp->word = Strspl(STRdotsl, sp->word);
1024 		cleanup_push(sp->word, xfree);
1025 		prlex(lexp);
1026 		cleanup_until(sp->word);
1027 	    }
1028 	    else
1029 		prlex(lexp);
1030 	}
1031 	else {
1032 	    s1 = Strspl(*pv, STRslash);
1033 	    sp->word = Strspl(s1, sp->word);
1034 	    xfree(s1);
1035 	    cleanup_push(sp->word, xfree);
1036 	    if (str == NULL)
1037 		prlex(lexp);
1038 	    else
1039 		*str = Strsave(sp->word);
1040 	    cleanup_until(sp->word);
1041 	}
1042 	found = 1;
1043     }
1044     else {
1045 	if (str == NULL) {
1046 	    if (aliased)
1047 		prlex(lexp);
1048 	    xprintf(CGETS(13, 6, "%S: Command not found.\n"), sp->word);
1049 	    flush();
1050 	}
1051 	else
1052 	    *str = Strsave(sp->word);
1053 	found = 0;
1054     }
1055     cleanup_until(&s0);
1056     return found;
1057 }
1058 
1059 /*
1060  * Builtin to look at and list all places a command may be defined:
1061  * aliases, shell builtins, and the path.
1062  *
1063  * Marc Horowitz <marc@mit.edu>
1064  * MIT Student Information Processing Board
1065  */
1066 
1067 /*ARGSUSED*/
1068 void
1069 dowhere(Char **v, struct command *c)
1070 {
1071     int found = 1;
1072     USE(c);
1073     for (v++; *v; v++)
1074 	found &= find_cmd(*v, 1);
1075     /* Make status nonzero if any command is not found. */
1076     if (!found)
1077 	setcopy(STRstatus, STR1, VAR_READWRITE);
1078 }
1079 
1080 int
1081 find_cmd(Char *cmd, int prt)
1082 {
1083     struct varent *var;
1084     const struct biltins *bptr;
1085     Char **pv;
1086     Char *sv;
1087     int hashval, rehashed, i, ex, rval = 0;
1088 
1089     if (prt && any(short2str(cmd), '/')) {
1090 	xprintf("%s", CGETS(13, 7, "where: / in command makes no sense\n"));
1091 	return rval;
1092     }
1093 
1094     /* first, look for an alias */
1095 
1096     if (prt && adrof1(cmd, &aliases)) {
1097 	if ((var = adrof1(cmd, &aliases)) != NULL) {
1098 	    xprintf(CGETS(13, 8, "%S is aliased to "), cmd);
1099 	    if (var->vec != NULL)
1100 		blkpr(var->vec);
1101 	    xputchar('\n');
1102 	    rval = 1;
1103 	}
1104     }
1105 
1106     /* next, look for a shell builtin */
1107 
1108     for (bptr = bfunc; bptr < &bfunc[nbfunc]; bptr++) {
1109 	if (eq(cmd, str2short(bptr->bname))) {
1110 	    rval = 1;
1111 	    if (prt)
1112 		xprintf(CGETS(13, 9, "%S is a shell built-in\n"), cmd);
1113 	    else
1114 		return rval;
1115 	}
1116     }
1117 #ifdef WINNT_NATIVE
1118     for (bptr = nt_bfunc; bptr < &nt_bfunc[nt_nbfunc]; bptr++) {
1119 	if (eq(cmd, str2short(bptr->bname))) {
1120 	    rval = 1;
1121 	    if (prt)
1122 		xprintf(CGETS(13, 9, "%S is a shell built-in\n"), cmd);
1123 	    else
1124 		return rval;
1125 	}
1126     }
1127 #endif /* WINNT_NATIVE*/
1128 
1129     /* last, look through the path for the command */
1130 
1131     if ((var = adrof(STRpath)) == NULL)
1132 	return rval;
1133 
1134     hashval = havhash ? hashname(cmd) : 0;
1135 
1136     sv = Strspl(STRslash, cmd);
1137     cleanup_push(sv, xfree);
1138 
1139     rehashed = 0;
1140 retry:
1141     for (pv = var->vec, i = 0; pv && *pv; pv++, i++) {
1142 	if (havhash && !eq(*pv, STRdot)) {
1143 #ifdef FASTHASH
1144 	    if (!bit(hashval, i))
1145 		continue;
1146 #else /* OLDHASH */
1147 	    int hashval1 = hash(hashval, i);
1148 	    if (!bit(xhash, hashval1))
1149 		continue;
1150 #endif /* FASTHASH */
1151 	}
1152 	ex = executable(*pv, sv, 0);
1153 #ifdef FASTHASH
1154 	if (!ex && (hashdebug & 2)) {
1155 	    xprintf("%s", CGETS(13, 10, "hash miss: "));
1156 	    ex = 1;	/* Force printing */
1157 	}
1158 #endif /* FASTHASH */
1159 	if (ex) {
1160 	    rval = 1;
1161 	    if (prt) {
1162 		xprintf("%S/", *pv);
1163 		xprintf("%S\n", cmd);
1164 	    }
1165 	    else
1166 		return rval;
1167 	}
1168     }
1169     if (adrof(STRautorehash) && !rehashed && havhash) {
1170 	dohash(NULL, NULL);
1171 	rehashed = 1;
1172 	goto retry;
1173     }
1174     cleanup_until(sv);
1175     return rval;
1176 }
1177 #ifdef WINNT_NATIVE
1178 int hashval_extern(cp)
1179 	Char *cp;
1180 {
1181 	return havhash?hashname(cp):0;
1182 }
1183 int bit_extern(val,i)
1184 	int val;
1185 	int i;
1186 {
1187 	return bit(val,i);
1188 }
1189 void bis_extern(val,i)
1190 	int val;
1191 	int i;
1192 {
1193 	bis(val,i);
1194 }
1195 #endif /* WINNT_NATIVE */
1196 
1197