xref: /freebsd/contrib/tcsh/sh.exec.c (revision 0957b409)
1 /* $Header: /p/tcsh/cvsroot/tcsh/sh.exec.c,v 3.81 2016/09/12 16:33:54 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.81 2016/09/12 16:33:54 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, if not in a subshell
610      */
611     if (mainpid == getpid())
612 	shlvl(-1);
613 #ifdef WINNT_NATIVE
614     __nt_really_exec=1;
615 #endif /* WINNT_NATIVE */
616     doexec(kp, 1);
617 
618     cleanup_until(&state);
619 }
620 
621 void
622 xechoit(Char **t)
623 {
624     if (adrof(STRecho)) {
625 	int odidfds = didfds;
626 	flush();
627 	haderr = 1;
628 	didfds = 0;
629 	blkpr(t), xputchar('\n');
630 	flush();
631 	didfds = odidfds;
632 	haderr = 0;
633     }
634 }
635 
636 /*ARGSUSED*/
637 void
638 dohash(Char **vv, struct command *c)
639 {
640 #ifdef COMMENT
641     struct stat stb;
642 #endif
643     DIR    *dirp;
644     struct dirent *dp;
645     int     i = 0;
646     struct varent *v = adrof(STRpath);
647     Char  **pv;
648     int hashval;
649 #ifdef WINNT_NATIVE
650     int is_windir; /* check if it is the windows directory */
651     USE(hashval);
652 #endif /* WINNT_NATIVE */
653 
654     USE(c);
655 #ifdef FASTHASH
656     if (vv && vv[1]) {
657         uhashlength = atoi(short2str(vv[1]));
658         if (vv[2]) {
659 	    uhashwidth = atoi(short2str(vv[2]));
660 	    if ((uhashwidth != sizeof(unsigned char)) &&
661 	        (uhashwidth != sizeof(unsigned short)) &&
662 	        (uhashwidth != sizeof(unsigned long)))
663 	        uhashwidth = 0;
664 	    if (vv[3])
665 		hashdebug = atoi(short2str(vv[3]));
666         }
667     }
668 
669     if (uhashwidth)
670 	hashwidth = uhashwidth;
671     else {
672 	hashwidth = 0;
673 	if (v == NULL)
674 	    return;
675 	for (pv = v->vec; pv && *pv; pv++, hashwidth++)
676 	    continue;
677 	if (hashwidth <= widthof(unsigned char))
678 	    hashwidth = sizeof(unsigned char);
679 	else if (hashwidth <= widthof(unsigned short))
680 	    hashwidth = sizeof(unsigned short);
681 	else if (hashwidth <= widthof(unsigned int))
682 	    hashwidth = sizeof(unsigned int);
683 	else
684 	    hashwidth = sizeof(unsigned long);
685     }
686 
687     if (uhashlength)
688 	hashlength = uhashlength;
689     else
690         hashlength = hashwidth * (8*64);/* "average" files per dir in path */
691 
692     xfree(xhash);
693     xhash = xcalloc(hashlength * hashwidth, 1);
694 #endif /* FASTHASH */
695 
696     (void) getusername(NULL);	/* flush the tilde cashe */
697     tw_cmd_free();
698     havhash = 1;
699     if (v == NULL)
700 	return;
701     for (pv = v->vec; pv && *pv; pv++, i++) {
702 	if (!ABSOLUTEP(pv[0]))
703 	    continue;
704 	dirp = opendir(short2str(*pv));
705 	if (dirp == NULL)
706 	    continue;
707 	cleanup_push(dirp, opendir_cleanup);
708 #ifdef COMMENT			/* this isn't needed.  opendir won't open
709 				 * non-dirs */
710 	if (fstat(dirp->dd_fd, &stb) < 0 || !S_ISDIR(stb.st_mode)) {
711 	    cleanup_until(dirp);
712 	    continue;
713 	}
714 #endif
715 #ifdef WINNT_NATIVE
716 	is_windir = nt_check_if_windir(short2str(*pv));
717 #endif /* WINNT_NATIVE */
718 	while ((dp = readdir(dirp)) != NULL) {
719 	    if (dp->d_ino == 0)
720 		continue;
721 	    if (dp->d_name[0] == '.' &&
722 		(dp->d_name[1] == '\0' ||
723 		 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
724 		continue;
725 #ifdef WINNT_NATIVE
726 	    nt_check_name_and_hash(is_windir, dp->d_name, i);
727 #else /* !WINNT_NATIVE*/
728 #if defined(_UWIN) || defined(__CYGWIN__)
729 	    /* Turn foo.{exe,com,bat} into foo since UWIN's readdir returns
730 	     * the file with the .exe, .com, .bat extension
731 	     *
732 	     * Same for Cygwin, but only for .exe and .com extension.
733 	     */
734 	    {
735 		ssize_t	ext = strlen(dp->d_name) - 4;
736 		if ((ext > 0) && (strcasecmp(&dp->d_name[ext], ".exe") == 0 ||
737 #ifndef __CYGWIN__
738 				  strcasecmp(&dp->d_name[ext], ".bat") == 0 ||
739 #endif
740 				  strcasecmp(&dp->d_name[ext], ".com") == 0)) {
741 #ifdef __CYGWIN__
742 		    /* Also store the variation with extension. */
743 		    hashval = hashname(str2short(dp->d_name));
744 		    bis(hashval, i);
745 #endif /* __CYGWIN__ */
746 		    dp->d_name[ext] = '\0';
747 		}
748 	    }
749 #endif /* _UWIN || __CYGWIN__ */
750 # ifdef FASTHASH
751 	    hashval = hashname(str2short(dp->d_name));
752 	    bis(hashval, i);
753 	    if (hashdebug & 1)
754 	        xprintf(CGETS(13, 1, "hash=%-4d dir=%-2d prog=%s\n"),
755 		        hashname(str2short(dp->d_name)), i, dp->d_name);
756 # else /* OLD HASH */
757 	    hashval = hash(hashname(str2short(dp->d_name)), i);
758 	    bis(xhash, hashval);
759 # endif /* FASTHASH */
760 	    /* tw_add_comm_name (dp->d_name); */
761 #endif /* WINNT_NATIVE */
762 	}
763 	cleanup_until(dirp);
764     }
765 }
766 
767 /*ARGSUSED*/
768 void
769 dounhash(Char **v, struct command *c)
770 {
771     USE(c);
772     USE(v);
773     havhash = 0;
774 #ifdef FASTHASH
775     xfree(xhash);
776     xhash = NULL;
777 #endif /* FASTHASH */
778 }
779 
780 /*ARGSUSED*/
781 void
782 hashstat(Char **v, struct command *c)
783 {
784     USE(c);
785     USE(v);
786 #ifdef FASTHASH
787    if (havhash && hashlength && hashwidth)
788       xprintf(CGETS(13, 2, "%d hash buckets of %d bits each\n"),
789 	      hashlength, hashwidth*8);
790    if (hashdebug)
791       xprintf(CGETS(13, 3, "debug mask = 0x%08x\n"), hashdebug);
792 #endif /* FASTHASH */
793 #ifdef VFORK
794    if (hits + misses)
795       xprintf(CGETS(13, 4, "%d hits, %d misses, %d%%\n"),
796 	      hits, misses, 100 * hits / (hits + misses));
797 #endif
798 }
799 
800 
801 /*
802  * Hash a command name.
803  */
804 int
805 hashname(Char *cp)
806 {
807     unsigned long h;
808 
809     for (h = 0; *cp; cp++)
810 	h = hash(h, *cp);
811     return ((int) h);
812 }
813 
814 static int
815 iscommand(Char *name)
816 {
817     Char **opv, **pv;
818     Char *sav;
819     struct varent *v;
820     int slash = any(short2str(name), '/');
821     int hashval, rehashed, i;
822 
823     v = adrof(STRpath);
824     if (v == NULL || v->vec == NULL || v->vec[0] == NULL || slash)
825 	opv = justabs;
826     else
827 	opv = v->vec;
828     sav = Strspl(STRslash, name);	/* / command name for postpending */
829     hashval = havhash ? hashname(name) : 0;
830 
831     rehashed = 0;
832 retry:
833     pv = opv;
834     i = 0;
835     do {
836 	if (!slash && ABSOLUTEP(pv[0]) && havhash) {
837 #ifdef FASTHASH
838 	    if (!bit(hashval, i))
839 		goto cont;
840 #else /* OLDHASH */
841 	    int hashval1 = hash(hashval, i);
842 	    if (!bit(xhash, hashval1))
843 		goto cont;
844 #endif /* FASTHASH */
845 	}
846 	if (pv[0][0] == 0 || eq(pv[0], STRdot)) {	/* don't make ./xxx */
847 	    if (executable(NULL, name, 0)) {
848 		xfree(sav);
849 		return i + 1;
850 	    }
851 	}
852 	else {
853 	    if (executable(*pv, sav, 0)) {
854 		xfree(sav);
855 		return i + 1;
856 	    }
857 	}
858 cont:
859 	pv++;
860 	i++;
861     } while (*pv);
862     if (adrof(STRautorehash) && !rehashed && havhash && opv != justabs) {
863 	dohash(NULL, NULL);
864 	rehashed = 1;
865 	goto retry;
866     }
867     xfree(sav);
868     return 0;
869 }
870 
871 /* Also by:
872  *  Andreas Luik <luik@isaak.isa.de>
873  *  I S A  GmbH - Informationssysteme fuer computerintegrierte Automatisierung
874  *  Azenberstr. 35
875  *  D-7000 Stuttgart 1
876  *  West-Germany
877  * is the executable() routine below and changes to iscommand().
878  * Thanks again!!
879  */
880 
881 #ifndef WINNT_NATIVE
882 /*
883  * executable() examines the pathname obtained by concatenating dir and name
884  * (dir may be NULL), and returns 1 either if it is executable by us, or
885  * if dir_ok is set and the pathname refers to a directory.
886  * This is a bit kludgy, but in the name of optimization...
887  */
888 int
889 executable(const Char *dir, const Char *name, int dir_ok)
890 {
891     struct stat stbuf;
892     char   *strname;
893 
894     if (dir && *dir) {
895 	Char *path;
896 
897 	path = Strspl(dir, name);
898 	strname = short2str(path);
899 	xfree(path);
900     }
901     else
902 	strname = short2str(name);
903 
904     return (stat(strname, &stbuf) != -1 &&
905 	    ((dir_ok && S_ISDIR(stbuf.st_mode)) ||
906 	     (S_ISREG(stbuf.st_mode) &&
907     /* save time by not calling access() in the hopeless case */
908 	      (stbuf.st_mode & (S_IXOTH | S_IXGRP | S_IXUSR)) &&
909 	      access(strname, X_OK) == 0
910 	)));
911 }
912 #endif /*!WINNT_NATIVE*/
913 
914 struct tellmewhat_s0_cleanup
915 {
916     Char **dest, *val;
917 };
918 
919 static void
920 tellmewhat_s0_cleanup(void *xstate)
921 {
922     struct tellmewhat_s0_cleanup *state;
923 
924     state = xstate;
925     *state->dest = state->val;
926 }
927 
928 int
929 tellmewhat(struct wordent *lexp, Char **str)
930 {
931     struct tellmewhat_s0_cleanup s0;
932     int i;
933     const struct biltins *bptr;
934     struct wordent *sp = lexp->next;
935     int    aliased = 0, found;
936     Char   *s1, *s2, *cmd;
937     Char    qc;
938 
939     if (adrof1(sp->word, &aliases)) {
940 	alias(lexp);
941 	sp = lexp->next;
942 	aliased = 1;
943     }
944 
945     s0.dest = &sp->word;	/* to get the memory freeing right... */
946     s0.val = sp->word;
947     cleanup_push(&s0, tellmewhat_s0_cleanup);
948 
949     /* handle quoted alias hack */
950     if ((*(sp->word) & (QUOTE | TRIM)) == QUOTE)
951 	(sp->word)++;
952 
953     /* do quoting, if it hasn't been done */
954     s1 = s2 = sp->word;
955     while (*s2)
956 	switch (*s2) {
957 	case '\'':
958 	case '"':
959 	    qc = *s2++;
960 	    while (*s2 && *s2 != qc)
961 		*s1++ = *s2++ | QUOTE;
962 	    if (*s2)
963 		s2++;
964 	    break;
965 	case '\\':
966 	    if (*++s2)
967 		*s1++ = *s2++ | QUOTE;
968 	    break;
969 	default:
970 	    *s1++ = *s2++;
971 	}
972     *s1 = '\0';
973 
974     for (bptr = bfunc; bptr < &bfunc[nbfunc]; bptr++) {
975 	if (eq(sp->word, str2short(bptr->bname))) {
976 	    if (str == NULL) {
977 		if (aliased)
978 		    prlex(lexp);
979 		xprintf(CGETS(13, 5, "%S: shell built-in command.\n"),
980 			      sp->word);
981 		flush();
982 	    }
983 	    else
984 		*str = Strsave(sp->word);
985 	    cleanup_until(&s0);
986 	    return TRUE;
987 	}
988     }
989 #ifdef WINNT_NATIVE
990     for (bptr = nt_bfunc; bptr < &nt_bfunc[nt_nbfunc]; bptr++) {
991 	if (eq(sp->word, str2short(bptr->bname))) {
992 	    if (str == NULL) {
993 		if (aliased)
994 		    prlex(lexp);
995 		xprintf(CGETS(13, 5, "%S: shell built-in command.\n"),
996 			      sp->word);
997 		flush();
998 	    }
999 	    else
1000 		*str = Strsave(sp->word);
1001 	    cleanup_until(&s0);
1002 	    return TRUE;
1003 	}
1004     }
1005 #endif /* WINNT_NATIVE*/
1006 
1007     sp->word = cmd = globone(sp->word, G_IGNORE);
1008     cleanup_push(cmd, xfree);
1009 
1010     if ((i = iscommand(sp->word)) != 0) {
1011 	Char **pv;
1012 	struct varent *v;
1013 	int    slash = any(short2str(sp->word), '/');
1014 
1015 	v = adrof(STRpath);
1016 	if (v == NULL || v->vec == NULL || v->vec[0] == NULL || slash)
1017 	    pv = justabs;
1018 	else
1019 	    pv = v->vec;
1020 
1021 	pv += i - 1;
1022 	if (pv[0][0] == 0 || eq(pv[0], STRdot)) {
1023 	    if (!slash) {
1024 		sp->word = Strspl(STRdotsl, sp->word);
1025 		cleanup_push(sp->word, xfree);
1026 		prlex(lexp);
1027 		cleanup_until(sp->word);
1028 	    }
1029 	    else
1030 		prlex(lexp);
1031 	}
1032 	else {
1033 	    s1 = Strspl(*pv, STRslash);
1034 	    sp->word = Strspl(s1, sp->word);
1035 	    xfree(s1);
1036 	    cleanup_push(sp->word, xfree);
1037 	    if (str == NULL)
1038 		prlex(lexp);
1039 	    else
1040 		*str = Strsave(sp->word);
1041 	    cleanup_until(sp->word);
1042 	}
1043 	found = 1;
1044     }
1045     else {
1046 	if (str == NULL) {
1047 	    if (aliased)
1048 		prlex(lexp);
1049 	    xprintf(CGETS(13, 6, "%S: Command not found.\n"), sp->word);
1050 	    flush();
1051 	}
1052 	else
1053 	    *str = Strsave(sp->word);
1054 	found = 0;
1055     }
1056     cleanup_until(&s0);
1057     return found;
1058 }
1059 
1060 /*
1061  * Builtin to look at and list all places a command may be defined:
1062  * aliases, shell builtins, and the path.
1063  *
1064  * Marc Horowitz <marc@mit.edu>
1065  * MIT Student Information Processing Board
1066  */
1067 
1068 /*ARGSUSED*/
1069 void
1070 dowhere(Char **v, struct command *c)
1071 {
1072     int found = 1;
1073     USE(c);
1074 
1075     if (adrof(STRautorehash))
1076 	dohash(NULL, NULL);
1077     for (v++; *v; v++)
1078 	found &= find_cmd(*v, 1);
1079     /* Make status nonzero if any command is not found. */
1080     if (!found)
1081 	setcopy(STRstatus, STR1, VAR_READWRITE);
1082 }
1083 
1084 int
1085 find_cmd(Char *cmd, int prt)
1086 {
1087     struct varent *var;
1088     const struct biltins *bptr;
1089     Char **pv;
1090     Char *sv;
1091     int hashval, rehashed, i, ex, rval = 0;
1092 
1093     if (prt && any(short2str(cmd), '/')) {
1094 	xprintf("%s", CGETS(13, 7, "where: / in command makes no sense\n"));
1095 	return rval;
1096     }
1097 
1098     /* first, look for an alias */
1099 
1100     if (prt && adrof1(cmd, &aliases)) {
1101 	if ((var = adrof1(cmd, &aliases)) != NULL) {
1102 	    xprintf(CGETS(13, 8, "%S is aliased to "), cmd);
1103 	    if (var->vec != NULL)
1104 		blkpr(var->vec);
1105 	    xputchar('\n');
1106 	    rval = 1;
1107 	}
1108     }
1109 
1110     /* next, look for a shell builtin */
1111 
1112     for (bptr = bfunc; bptr < &bfunc[nbfunc]; bptr++) {
1113 	if (eq(cmd, str2short(bptr->bname))) {
1114 	    rval = 1;
1115 	    if (prt)
1116 		xprintf(CGETS(13, 9, "%S is a shell built-in\n"), cmd);
1117 	    else
1118 		return rval;
1119 	}
1120     }
1121 #ifdef WINNT_NATIVE
1122     for (bptr = nt_bfunc; bptr < &nt_bfunc[nt_nbfunc]; bptr++) {
1123 	if (eq(cmd, str2short(bptr->bname))) {
1124 	    rval = 1;
1125 	    if (prt)
1126 		xprintf(CGETS(13, 9, "%S is a shell built-in\n"), cmd);
1127 	    else
1128 		return rval;
1129 	}
1130     }
1131 #endif /* WINNT_NATIVE*/
1132 
1133     /* last, look through the path for the command */
1134 
1135     if ((var = adrof(STRpath)) == NULL)
1136 	return rval;
1137 
1138     hashval = havhash ? hashname(cmd) : 0;
1139 
1140     sv = Strspl(STRslash, cmd);
1141     cleanup_push(sv, xfree);
1142 
1143     rehashed = 0;
1144 retry:
1145     for (pv = var->vec, i = 0; pv && *pv; pv++, i++) {
1146 	if (havhash && !eq(*pv, STRdot)) {
1147 #ifdef FASTHASH
1148 	    if (!bit(hashval, i))
1149 		continue;
1150 #else /* OLDHASH */
1151 	    int hashval1 = hash(hashval, i);
1152 	    if (!bit(xhash, hashval1))
1153 		continue;
1154 #endif /* FASTHASH */
1155 	}
1156 	ex = executable(*pv, sv, 0);
1157 #ifdef FASTHASH
1158 	if (!ex && (hashdebug & 2)) {
1159 	    xprintf("%s", CGETS(13, 10, "hash miss: "));
1160 	    ex = 1;	/* Force printing */
1161 	}
1162 #endif /* FASTHASH */
1163 	if (ex) {
1164 	    rval = 1;
1165 	    if (prt) {
1166 		xprintf("%S/", *pv);
1167 		xprintf("%S\n", cmd);
1168 	    }
1169 	    else
1170 		return rval;
1171 	}
1172     }
1173     /*
1174      * If we are printing, we are being called from dowhere() which it
1175      * has rehashed already
1176      */
1177     if (!prt && adrof(STRautorehash) && !rehashed && havhash) {
1178 	dohash(NULL, NULL);
1179 	rehashed = 1;
1180 	goto retry;
1181     }
1182     cleanup_until(sv);
1183     return rval;
1184 }
1185 #ifdef WINNT_NATIVE
1186 int hashval_extern(cp)
1187 	Char *cp;
1188 {
1189 	return havhash?hashname(cp):0;
1190 }
1191 int bit_extern(val,i)
1192 	int val;
1193 	int i;
1194 {
1195 	return bit(val,i);
1196 }
1197 void bis_extern(val,i)
1198 	int val;
1199 	int i;
1200 {
1201 	bis(val,i);
1202 }
1203 #endif /* WINNT_NATIVE */
1204 
1205