xref: /dflybsd-src/usr.bin/fstat/fstat.c (revision ac9843a1ff1bb81f022a04b6a7ed9756fd99238c)
1 /*-
2  * Copyright (c) 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#) Copyright (c) 1988, 1993 The Regents of the University of California.  All rights reserved.
30  * @(#)fstat.c	8.3 (Berkeley) 5/2/95
31  * $FreeBSD: src/usr.bin/fstat/fstat.c,v 1.21.2.7 2001/11/21 10:49:37 dwmalone Exp $
32  */
33 
34 #include <sys/user.h>
35 #include <sys/param.h>
36 #include <sys/time.h>
37 #include <sys/stat.h>
38 #include <sys/vnode.h>
39 #include <sys/socket.h>
40 #include <sys/socketvar.h>
41 #include <sys/domain.h>
42 #include <sys/protosw.h>
43 #include <sys/un.h>
44 #include <sys/unpcb.h>
45 #include <sys/sysctl.h>
46 #include <sys/filedesc.h>
47 #include <sys/queue.h>
48 #include <sys/pipe.h>
49 #include <sys/conf.h>
50 #include <sys/file.h>
51 #include <sys/ktrace.h>
52 #include <vfs/ufs/quota.h>
53 #include <vfs/ufs/inode.h>
54 #include <sys/mount.h>
55 #include <sys/namecache.h>
56 #include <nfs/nfsproto.h>
57 #include <nfs/rpcv2.h>
58 #include <nfs/nfs.h>
59 #include <nfs/nfsnode.h>
60 #include <sys/devfs.h>
61 
62 #include <vm/vm.h>
63 #include <vm/vm_map.h>
64 #include <vm/vm_object.h>
65 
66 #include <net/route.h>
67 #include <netinet/in.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
70 #include <netinet/in_pcb.h>
71 
72 #include <ctype.h>
73 #include <err.h>
74 #include <fcntl.h>
75 #include <kvm.h>
76 #include <limits.h>
77 #include <nlist.h>
78 #include <paths.h>
79 #include <pwd.h>
80 #include <stdio.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #include <unistd.h>
84 #include <netdb.h>
85 
86 #include "fstat.h"
87 
88 #define	TEXT	-1
89 #define	CDIR	-2
90 #define	RDIR	-3
91 #define	TRACE	-4
92 #define	MMAP	-5
93 
94 DEVS *devs;
95 
96 static void make_printable(char *buf, int len);
97 
98 #ifdef notdef
99 struct nlist nl[] = {
100 	{ "" },
101 };
102 #endif
103 
104 int 	fsflg,	/* show files on same filesystem as file(s) argument */
105 	pflg,	/* show files open by a particular pid */
106 	uflg;	/* show files open by a particular (effective) user */
107 int 	checkfile; /* true if restricting to particular files or filesystems */
108 int	nflg;	/* (numerical) display f.s. and rdev as dev_t */
109 int	vflg;	/* display errors in locating kernel data objects etc... */
110 int	mflg;	/* include memory-mapped files */
111 int	wflg_mnt = 16;
112 int	wflg_cmd = 10;
113 int	pid_width = 5;
114 int	ino_width = 6;
115 
116 
117 struct fdnode *ofiles; 	/* buffer of pointers to file structures */
118 int maxfiles;
119 
120 #define ALLOC_OFILES(d)	\
121 	if ((d) > maxfiles) { \
122 		free(ofiles); \
123 		ofiles = malloc((d) * sizeof(struct fdnode)); \
124 		if (ofiles == NULL) { \
125 			err(1, NULL); \
126 		} \
127 		maxfiles = (d); \
128 	}
129 
130 kvm_t *kd;
131 
132 void dofiles(struct kinfo_proc *kp, struct proc *p);
133 void dommap(struct proc *p);
134 void vtrans(struct vnode *vp, struct nchandle *ncr, int i, int flag, off_t off);
135 int  ufs_filestat(struct vnode *vp, struct filestat *fsp);
136 int  nfs_filestat(struct vnode *vp, struct filestat *fsp);
137 int  devfs_filestat(struct vnode *vp, struct filestat *fsp);
138 char *getmnton(struct mount *m, struct namecache_list *ncplist, struct nchandle *ncr);
139 void pipetrans(struct pipe *pi, int i, int flag);
140 void socktrans(struct socket *sock, int i);
141 void getinetproto(int number);
142 int  getfname(const char *filename);
143 void usage(void);
144 
145 
146 int
147 main(int argc, char **argv)
148 {
149 	struct passwd *passwd;
150 	struct kinfo_proc *p, *plast;
151 	struct proc proc;
152 	int arg, ch, what;
153 	char *memf, *nlistf;
154 	char buf[_POSIX2_LINE_MAX];
155 	int cnt;
156 
157 	arg = 0;
158 	what = KERN_PROC_ALL;
159 	nlistf = memf = NULL;
160 	while ((ch = getopt(argc, argv, "fmnp:u:vwN:M:")) != -1)
161 		switch((char)ch) {
162 		case 'f':
163 			fsflg = 1;
164 			break;
165 		case 'M':
166 			memf = optarg;
167 			break;
168 		case 'N':
169 			nlistf = optarg;
170 			break;
171 		case 'm':
172 			mflg = 1;
173 			break;
174 		case 'n':
175 			nflg = 1;
176 			break;
177 		case 'p':
178 			if (pflg++)
179 				usage();
180 			if (!isdigit(*optarg)) {
181 				warnx("-p requires a process id");
182 				usage();
183 			}
184 			what = KERN_PROC_PID;
185 			arg = atoi(optarg);
186 			break;
187 		case 'u':
188 			if (uflg++)
189 				usage();
190 			if (!(passwd = getpwnam(optarg)))
191 				errx(1, "%s: unknown uid", optarg);
192 			what = KERN_PROC_UID;
193 			arg = passwd->pw_uid;
194 			break;
195 		case 'v':
196 			vflg = 1;
197 			break;
198 		case 'w':
199 			wflg_mnt = 40;
200 			wflg_cmd = 16;
201 			break;
202 		case '?':
203 		default:
204 			usage();
205 		}
206 
207 	if (*(argv += optind)) {
208 		for (; *argv; ++argv) {
209 			if (getfname(*argv))
210 				checkfile = 1;
211 		}
212 		if (!checkfile)	/* file(s) specified, but none accessable */
213 			exit(1);
214 	}
215 
216 	ALLOC_OFILES(256);	/* reserve space for file pointers */
217 
218 	if (fsflg && !checkfile) {
219 		/* -f with no files means use wd */
220 		if (getfname(".") == 0)
221 			exit(1);
222 		checkfile = 1;
223 	}
224 
225 	/*
226 	 * Discard setgid privileges if not the running kernel so that bad
227 	 * guys can't print interesting stuff from kernel memory.
228 	 */
229 	if (nlistf != NULL || memf != NULL)
230 		setgid(getgid());
231 
232 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == NULL)
233 		errx(1, "%s", buf);
234 #ifdef notdef
235 	if (kvm_nlist(kd, nl) != 0)
236 		errx(1, "no namelist: %s", kvm_geterr(kd));
237 #endif
238 	if ((p = kvm_getprocs(kd, what, arg, &cnt)) == NULL)
239 		errx(1, "%s", kvm_geterr(kd));
240 	if (nflg)
241 		printf("USER     %-*.*s %*.*s   FD DEV              %*.*s MODE   SZ|DV R/W",
242 			wflg_cmd, wflg_cmd, "CMD",
243 			pid_width, pid_width, "PID",
244 			ino_width, ino_width, "INUM");
245 	else
246 		printf("USER     %-*.*s %*.*s   FD %-*.*s %*.*s MODE           SZ|DV R/W",
247 			wflg_cmd, wflg_cmd, "CMD",
248 			pid_width, pid_width, "PID",
249 			wflg_mnt, wflg_mnt, "PATH",
250 			ino_width, ino_width, "INUM");
251 	if (checkfile && fsflg == 0)
252 		printf(" NAME\n");
253 	else
254 		putchar('\n');
255 
256 	for (plast = &p[cnt]; p < plast; ++p) {
257 		if (p->kp_stat == SZOMB)
258 			continue;
259 		if (!kread((void *)p->kp_paddr, &proc, sizeof(proc))) {
260 			dprintf(stderr, "can't read proc at %p for pid %d\n",
261 			    (void *)p->kp_paddr, Pid);
262 			continue;
263 		}
264 		dofiles(p, &proc);
265 		if (mflg)
266 			dommap(&proc);
267 	}
268 	exit(0);
269 }
270 
271 const char *Uname;
272 char	*Comm;
273 int	Pid;
274 
275 #define PREFIX(i) \
276 	printf("%-8.8s %-*s %*d", Uname, wflg_cmd, Comm, pid_width, Pid); \
277 	switch(i) { \
278 	case TEXT: \
279 		printf(" text"); \
280 		break; \
281 	case CDIR: \
282 		printf("   wd"); \
283 		break; \
284 	case RDIR: \
285 		printf(" root"); \
286 		break; \
287 	case TRACE: \
288 		printf("   tr"); \
289 		break; \
290 	case MMAP: \
291 		printf(" mmap"); \
292 		break; \
293 	default: \
294 		printf(" %4d", i); \
295 		break; \
296 	}
297 
298 /*
299  * print open files attributed to this process
300  */
301 void
302 dofiles(struct kinfo_proc *kp, struct proc *p)
303 {
304 	int i;
305 	struct file file;
306 	struct filedesc filed;
307 	struct ktrace_node ktrace_node;
308 
309 	Uname = user_from_uid(kp->kp_uid, 0);
310 	Pid = kp->kp_pid;
311 	Comm = kp->kp_comm;
312 	make_printable(Comm, strlen(Comm));
313 
314 	if (p->p_fd == NULL)
315 		return;
316 	if (!kread(p->p_fd, &filed, sizeof (filed))) {
317 		dprintf(stderr, "can't read filedesc at %p for pid %d\n",
318 		    (void *)p->p_fd, Pid);
319 		return;
320 	}
321 	/*
322 	 * root directory vnode, if one
323 	 */
324 	if (filed.fd_rdir)
325 		vtrans(filed.fd_rdir, &filed.fd_nrdir, RDIR, FREAD, 0);
326 	/*
327 	 * current working directory vnode
328 	 */
329 	vtrans(filed.fd_cdir, &filed.fd_ncdir, CDIR, FREAD, 0);
330 	/*
331 	 * ktrace vnode, if one
332 	 */
333 	if (p->p_tracenode) {
334 		if (kread(p->p_tracenode, &ktrace_node, sizeof (ktrace_node)))
335 			vtrans(ktrace_node.kn_vp, NULL, TRACE, FREAD|FWRITE, 0);
336 	}
337 	/*
338 	 * text vnode, if one
339 	 */
340 	if (p->p_textvp)
341 		vtrans(p->p_textvp, NULL, TEXT, FREAD, 0);
342 	/*
343 	 * open files
344 	 */
345 	ALLOC_OFILES(filed.fd_lastfile+1);
346 	if (!kread(filed.fd_files, ofiles,
347 	    (filed.fd_lastfile+1) * sizeof(struct fdnode))) {
348 		dprintf(stderr,
349 		    "can't read file structures at %p for pid %d\n",
350 		    (void *)filed.fd_files, Pid);
351 		return;
352 	}
353 	for (i = 0; i <= filed.fd_lastfile; i++) {
354 		if (ofiles[i].fp == NULL)
355 			continue;
356 		if (!kread(ofiles[i].fp, &file, sizeof (struct file))) {
357 			dprintf(stderr, "can't read file %d at %p for pid %d\n",
358 			    i, (void *)ofiles[i].fp, Pid);
359 			continue;
360 		}
361 		if (file.f_type == DTYPE_VNODE) {
362 			vtrans((struct vnode *)file.f_data, &file.f_nchandle,
363 				i, file.f_flag, file.f_offset);
364 		} else if (file.f_type == DTYPE_SOCKET) {
365 			if (checkfile == 0)
366 				socktrans((struct socket *)file.f_data, i);
367 		}
368 #ifdef DTYPE_PIPE
369 		else if (file.f_type == DTYPE_PIPE) {
370 			if (checkfile == 0)
371 				pipetrans((struct pipe *)file.f_data, i,
372 				    file.f_flag);
373 		}
374 #endif
375 #ifdef DTYPE_FIFO
376 		else if (file.f_type == DTYPE_FIFO) {
377 			if (checkfile == 0)
378 				vtrans((struct vnode *)file.f_data,
379 					&file.f_nchandle,
380 					i, file.f_flag, file.f_offset);
381 		}
382 #endif
383 		else {
384 			dprintf(stderr,
385 			    "unknown file type %d for file %d of pid %d\n",
386 			    file.f_type, i, Pid);
387 		}
388 	}
389 }
390 
391 void
392 dommap(struct proc *p)
393 {
394 	struct vmspace vmspace;
395 	vm_map_t map;
396 	struct vm_map_entry entry;
397 	vm_map_entry_t entryp;
398 	struct vm_object object;
399 	vm_object_t objp;
400 	int prot, fflags;
401 
402 	if (!kread(p->p_vmspace, &vmspace, sizeof(vmspace))) {
403 		dprintf(stderr, "can't read vmspace at %p for pid %d\n",
404 		    (void *)p->p_vmspace, Pid);
405 		return;
406 	}
407 
408 	map = &vmspace.vm_map;
409 
410 	for (entryp = map->header.next; entryp != &p->p_vmspace->vm_map.header;
411 	    entryp = entry.next) {
412 		if (!kread(entryp, &entry, sizeof(entry))) {
413 			dprintf(stderr,
414 			    "can't read vm_map_entry at %p for pid %d\n",
415 			    (void *)entryp, Pid);
416 			return;
417 		}
418 
419 		if (entry.maptype == VM_MAPTYPE_SUBMAP)
420 			continue;
421 
422 		if ((objp = entry.object.vm_object) == NULL)
423 			continue;
424 
425 		for (; objp; objp = object.backing_object) {
426 			if (!kread(objp, &object, sizeof(object))) {
427 				dprintf(stderr,
428 				    "can't read vm_object at %p for pid %d\n",
429 				    (void *)objp, Pid);
430 				return;
431 			}
432 		}
433 
434 		prot = entry.protection;
435 		fflags = (prot & VM_PROT_READ ? FREAD : 0) |
436 		    (prot & VM_PROT_WRITE ? FWRITE : 0);
437 
438 		switch (object.type) {
439 		case OBJT_VNODE:
440 			vtrans((struct vnode *)object.handle, NULL,
441 				MMAP, fflags, 0);
442 			break;
443 		default:
444 			break;
445 		}
446 	}
447 }
448 
449 void
450 vtrans(struct vnode *vp, struct nchandle *ncr, int i, int flag, off_t off)
451 {
452 	struct vnode vn;
453 	struct filestat fst;
454 	char rw[3], mode[15];
455 	const char *badtype = NULL, *filename;
456 	char *name;
457 
458 	fst.offset = off;
459 	filename = badtype = NULL;
460 	if (!kread(vp, &vn, sizeof (struct vnode))) {
461 		dprintf(stderr, "can't read vnode at %p for pid %d\n",
462 		    (void *)vp, Pid);
463 		return;
464 	}
465 	if (vn.v_type == VNON || vn.v_tag == VT_NON)
466 		badtype = "none";
467 	else if (vn.v_type == VBAD)
468 		badtype = "bad";
469 	else
470 		switch (vn.v_tag) {
471 		case VT_UFS:
472 			if (!ufs_filestat(&vn, &fst))
473 				badtype = "error";
474 			break;
475 		case VT_MFS:
476 			if (!ufs_filestat(&vn, &fst))
477 				badtype = "error";
478 			break;
479 		case VT_NFS:
480 			if (!nfs_filestat(&vn, &fst))
481 				badtype = "error";
482 			break;
483 
484 		case VT_MSDOSFS:
485 			if (!msdosfs_filestat(&vn, &fst))
486 				badtype = "error";
487 			break;
488 
489 		case VT_ISOFS:
490 			if (!isofs_filestat(&vn, &fst))
491 				badtype = "error";
492 			break;
493 
494 		case VT_DEVFS:
495 			if (!devfs_filestat(&vn, &fst))
496 				badtype = "error";
497 			break;
498 
499 		default: {
500 			static char unknown[10];
501 			sprintf(unknown, "?(%x)", vn.v_tag);
502 			badtype=unknown;
503 			break;
504 		}
505 	}
506 	if (checkfile) {
507 		int fsmatch = 0;
508 		DEVS *d;
509 
510 		if (badtype)
511 			return;
512 		for (d = devs; d != NULL; d = d->next)
513 			if (d->fsid == fst.fsid) {
514 				fsmatch = 1;
515 				if (d->ino == (ino_t)fst.fileid) {
516 					filename = d->name;
517 					break;
518 				}
519 			}
520 		if (fsmatch == 0 || (filename == NULL && fsflg == 0))
521 			return;
522 	}
523 	PREFIX(i);
524 	if (badtype) {
525 		(void)printf(" %-*s  %10s    %jd\n",
526 			     wflg_mnt,
527 			     getmnton(vn.v_mount, &vn.v_namecache, ncr),
528 			     badtype,
529 			     (intmax_t)off);
530 		return;
531 	}
532 	if (nflg)
533 		(void)printf(" %3d,%-9d   ", major(fst.fsid), minor(fst.fsid));
534 	else
535 		(void)printf(" %-*s", wflg_mnt, getmnton(vn.v_mount, &vn.v_namecache, ncr));
536 	if (nflg)
537 		(void)sprintf(mode, "%o", fst.mode);
538 	else
539 		strmode(fst.mode, mode);
540 	(void)printf(" %*ld %10s", ino_width, fst.fileid, mode);
541 	switch (vn.v_type) {
542 	case VBLK:
543 	case VCHR:
544 		if (nflg || ((name = devname(fst.rdev, vn.v_type == VCHR ?
545 		    S_IFCHR : S_IFBLK)) == NULL))
546 			printf(" %3d,%-4d", major(fst.rdev), minor(fst.rdev));
547 		else
548 			printf(" %8s", name);
549 		break;
550 	case VREG:
551 		printf(" %jd", (intmax_t)fst.offset);
552 		break;
553 	default:
554 		printf(" %8ju", (uintmax_t)fst.size);
555 	}
556 	rw[0] = '\0';
557 	if (flag & FREAD)
558 		strcat(rw, "r");
559 	if (flag & FWRITE)
560 		strcat(rw, "w");
561 	printf(" %2s", rw);
562 	if (filename && !fsflg)
563 		printf("  %s", filename);
564 	putchar('\n');
565 }
566 
567 int
568 ufs_filestat(struct vnode *vp, struct filestat *fsp)
569 {
570 	struct inode inode;
571 
572 	if (!kread(VTOI(vp), &inode, sizeof (inode))) {
573 		dprintf(stderr, "can't read inode at %p for pid %d\n",
574 		    (void *)VTOI(vp), Pid);
575 		return 0;
576 	}
577 	/*
578 	 * The st_dev from stat(2) is a udev_t. These kernel structures
579 	 * contain dev_t structures. We need to convert to udev to make
580 	 * comparisons
581 	 */
582 	fsp->fsid = dev2udev(inode.i_dev);
583 	fsp->fileid = (long)inode.i_number;
584 	fsp->mode = (mode_t)inode.i_mode;
585 	fsp->size = inode.i_size;
586 	fsp->rdev = inode.i_rdev;
587 
588 	return 1;
589 }
590 
591 int
592 nfs_filestat(struct vnode *vp, struct filestat *fsp)
593 {
594 	struct nfsnode nfsnode;
595 	mode_t mode;
596 
597 	if (!kread(VTONFS(vp), &nfsnode, sizeof (nfsnode))) {
598 		dprintf(stderr, "can't read nfsnode at %p for pid %d\n",
599 		    (void *)VTONFS(vp), Pid);
600 		return 0;
601 	}
602 	fsp->fsid = nfsnode.n_vattr.va_fsid;
603 	fsp->fileid = nfsnode.n_vattr.va_fileid;
604 	fsp->size = nfsnode.n_size;
605 	fsp->rdev = makeudev(nfsnode.n_vattr.va_rmajor,
606 			     nfsnode.n_vattr.va_rminor);
607 	mode = (mode_t)nfsnode.n_vattr.va_mode;
608 	switch (vp->v_type) {
609 	case VREG:
610 		mode |= S_IFREG;
611 		break;
612 	case VDIR:
613 		mode |= S_IFDIR;
614 		break;
615 	case VBLK:
616 		mode |= S_IFBLK;
617 		break;
618 	case VCHR:
619 		mode |= S_IFCHR;
620 		break;
621 	case VLNK:
622 		mode |= S_IFLNK;
623 		break;
624 	case VSOCK:
625 		mode |= S_IFSOCK;
626 		break;
627 	case VFIFO:
628 		mode |= S_IFIFO;
629 		break;
630 	case VDATABASE:
631 		break;
632 	case VINT:
633 	case VNON:
634 	case VBAD:
635 		return 0;
636 	}
637 	fsp->mode = mode;
638 
639 	return 1;
640 }
641 
642 int
643 devfs_filestat(struct vnode *vp, struct filestat *fsp)
644 {
645 	struct devfs_node devfs_node;
646 
647 	if (!kread(vp->v_data, &devfs_node, sizeof (devfs_node))) {
648 		dprintf(stderr, "can't read devfs_node at %p for pid %d\n",
649 		    (void *)vp->v_data, Pid);
650 		return 0;
651 	}
652 	fsp->fsid = fsp->rdev = dev2udev(vp->v_rdev);
653 	fsp->fileid = devfs_node.d_dir.d_ino;
654 	fsp->mode = (devfs_node.mode & ~S_IFMT) | S_IFCHR;
655 	fsp->size = 0;
656 
657 	return 1;
658 }
659 
660 char *
661 getmnton(struct mount *m, struct namecache_list *ncplist, struct nchandle *ncr)
662 {
663 	static struct mount mount_l;
664 	static struct mtab {
665 		struct mtab *next;
666 		struct mount *m;
667 		char mntonname[MNAMELEN];
668 	} *mhead = NULL;
669 	struct mtab *mt;
670 	struct namecache *ncp;
671 	struct namecache ncp_copy;
672 	static char path[1024];
673 	int i;
674 
675 	/*
676 	 * If no ncp is passed try to find one via ncplist.  Make sure
677 	 * we are using the correct mount pointer or the matching code
678 	 * will not know how to transition mount points properly.
679 	 */
680 	if (ncr == NULL || ncr->ncp == NULL) {
681 		ncp = ncplist->tqh_first;
682 	} else {
683 		ncp = ncr->ncp;
684 		if (ncr->mount)
685 			m = ncr->mount;
686 	}
687 
688 	/*
689 	 * If we have an ncp, traceback the path.  This is a kvm pointer.
690 	 */
691 	if (ncp) {
692 		if (!kread(m, &mount_l, sizeof(struct mount))) {
693 			warnx("can't read mount table at %p", (void *)m);
694 			return (NULL);
695 		}
696 		i = sizeof(path) - 1;
697 		path[i] = 0;
698 		while (ncp) {
699 			/*
700 			 * If this is the root of the mount then traverse
701 			 * to the parent mount.
702 			 */
703 			if (ncp == mount_l.mnt_ncmountpt.ncp) {
704 				ncp = mount_l.mnt_ncmounton.ncp;
705 				if (ncp == NULL)
706 					break;
707 				m = mount_l.mnt_ncmounton.mount;
708 				if (!kread(m, &mount_l, sizeof(struct mount))) {
709 					warnx("can't read mount table at %p", (void *)m);
710 					return (NULL);
711 				}
712 			}
713 
714 			/*
715 			 * Ok, pull out the ncp and extract the name
716 			 */
717 			if (!kread(ncp, &ncp_copy, sizeof(ncp_copy))) {
718 				warnx("can't read ncp at %p", ncp);
719 				return (NULL);
720 			}
721 			if (i <= ncp_copy.nc_nlen)
722 				break;
723 			i -= ncp_copy.nc_nlen;
724 			if (!kread(ncp_copy.nc_name, path + i, ncp_copy.nc_nlen)) {
725 				warnx("can't read ncp %p path component at %p", ncp, ncp_copy.nc_name);
726 				return (NULL);
727 			}
728 			make_printable(path + i, ncp_copy.nc_nlen);
729 			path[--i] = '/';
730 			ncp = ncp_copy.nc_parent;
731 		}
732 		if (i == sizeof(path) - 1)
733 			path[--i] = '/';
734 		return(path + i);
735 	}
736 
737 	/*
738 	 * If all else fails print out the mount point path
739 	 */
740 	for (mt = mhead; mt != NULL; mt = mt->next) {
741 		if (m == mt->m)
742 			return (mt->mntonname);
743 	}
744 	if (!kread(m, &mount_l, sizeof(struct mount))) {
745 		warnx("can't read mount table at %p", (void *)m);
746 		return (NULL);
747 	}
748 	if ((mt = malloc(sizeof (struct mtab))) == NULL)
749 		err(1, NULL);
750 	mt->m = m;
751 	bcopy(&mount_l.mnt_stat.f_mntonname[0], &mt->mntonname[0], MNAMELEN);
752 	mt->next = mhead;
753 	mhead = mt;
754 	return (mt->mntonname);
755 }
756 
757 void
758 pipetrans(struct pipe *pi, int i, int flag)
759 {
760 	struct pipe pip;
761 	char rw[3];
762 
763 	PREFIX(i);
764 
765 	/* fill in socket */
766 	if (!kread(pi, &pip, sizeof(struct pipe))) {
767 		dprintf(stderr, "can't read pipe at %p\n", (void *)pi);
768 		goto bad;
769 	}
770 
771 	printf("* pipe %8lx <-> %8lx", (u_long)pi, (u_long)pip.pipe_peer);
772 	printf(" %6d", (int)(pip.pipe_buffer.windex - pip.pipe_buffer.rindex));
773 	rw[0] = '\0';
774 	if (flag & FREAD)
775 		strcat(rw, "r");
776 	if (flag & FWRITE)
777 		strcat(rw, "w");
778 	printf(" %2s", rw);
779 	putchar('\n');
780 	return;
781 
782 bad:
783 	printf("* error\n");
784 }
785 
786 void
787 socktrans(struct socket *sock, int i)
788 {
789 	static const char *stypename[] = {
790 		"unused",	/* 0 */
791 		"stream", 	/* 1 */
792 		"dgram",	/* 2 */
793 		"raw",		/* 3 */
794 		"rdm",		/* 4 */
795 		"seqpak"	/* 5 */
796 	};
797 #define	STYPEMAX 5
798 	struct socket	so;
799 	struct protosw	proto;
800 	struct domain	dom;
801 	struct inpcb	inpcb;
802 	struct unpcb	unpcb;
803 	int len;
804 	char dname[32];
805 
806 	PREFIX(i);
807 
808 	/* fill in socket */
809 	if (!kread(sock, &so, sizeof(struct socket))) {
810 		dprintf(stderr, "can't read sock at %p\n", (void *)sock);
811 		goto bad;
812 	}
813 
814 	/* fill in protosw entry */
815 	if (!kread(so.so_proto, &proto, sizeof(struct protosw))) {
816 		dprintf(stderr, "can't read protosw at %p",
817 		    (void *)so.so_proto);
818 		goto bad;
819 	}
820 
821 	/* fill in domain */
822 	if (!kread(proto.pr_domain, &dom, sizeof(struct domain))) {
823 		dprintf(stderr, "can't read domain at %p\n",
824 		    (const void *)proto.pr_domain);
825 		goto bad;
826 	}
827 
828 	if ((len = kvm_read(kd, (u_long)dom.dom_name, dname,
829 	    sizeof(dname) - 1)) < 0) {
830 		dprintf(stderr, "can't read domain name at %p\n",
831 		    (void *)dom.dom_name);
832 		dname[0] = '\0';
833 	}
834 	else
835 		dname[len] = '\0';
836 
837 	if ((u_short)so.so_type > STYPEMAX)
838 		printf("* %s ?%d", dname, so.so_type);
839 	else
840 		printf("* %s %s", dname, stypename[so.so_type]);
841 
842 	/*
843 	 * protocol specific formatting
844 	 *
845 	 * Try to find interesting things to print.  For tcp, the interesting
846 	 * thing is the address of the tcpcb, for udp and others, just the
847 	 * inpcb (socket pcb).  For unix domain, its the address of the socket
848 	 * pcb and the address of the connected pcb (if connected).  Otherwise
849 	 * just print the protocol number and address of the socket itself.
850 	 * The idea is not to duplicate netstat, but to make available enough
851 	 * information for further analysis.
852 	 */
853 	switch(dom.dom_family) {
854 	case AF_INET:
855 	case AF_INET6:
856 		getinetproto(proto.pr_protocol);
857 		if (proto.pr_protocol == IPPROTO_TCP ) {
858 			if (so.so_pcb) {
859 				if (kvm_read(kd, (u_long)so.so_pcb,
860 				    (char *)&inpcb, sizeof(struct inpcb))
861 				    != sizeof(struct inpcb)) {
862 					dprintf(stderr,
863 					    "can't read inpcb at %p\n",
864 					    (void *)so.so_pcb);
865 					goto bad;
866 				}
867 				printf(" %lx", (u_long)inpcb.inp_ppcb);
868 			}
869 		}
870 		else if (so.so_pcb)
871 			printf(" %lx", (u_long)so.so_pcb);
872 		break;
873 	case AF_UNIX:
874 		/* print address of pcb and connected pcb */
875 		if (so.so_pcb) {
876 			printf(" %lx", (u_long)so.so_pcb);
877 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&unpcb,
878 			    sizeof(struct unpcb)) != sizeof(struct unpcb)){
879 				dprintf(stderr, "can't read unpcb at %p\n",
880 				    (void *)so.so_pcb);
881 				goto bad;
882 			}
883 			if (unpcb.unp_conn) {
884 				char shoconn[4], *cp;
885 
886 				cp = shoconn;
887 				if (!(so.so_state & SS_CANTRCVMORE))
888 					*cp++ = '<';
889 				*cp++ = '-';
890 				if (!(so.so_state & SS_CANTSENDMORE))
891 					*cp++ = '>';
892 				*cp = '\0';
893 				printf(" %s %lx", shoconn,
894 				    (u_long)unpcb.unp_conn);
895 			}
896 		}
897 		break;
898 	default:
899 		/* print protocol number and socket address */
900 		printf(" %d %lx", proto.pr_protocol, (u_long)sock);
901 	}
902 	printf("\n");
903 	return;
904 bad:
905 	printf("* error\n");
906 }
907 
908 
909 /*
910  * Read the cdev structure in the kernel (as pointed to by a dev_t)
911  * in order to work out the associated udev_t
912  */
913 udev_t
914 dev2udev(void *dev)
915 {
916 	struct cdev si;
917 
918 	if (kread(dev, &si, sizeof si)) {
919 		if ((si.si_umajor & 0xffffff00) ||
920 		    (si.si_uminor & 0x0000ff00)) {
921 			return NOUDEV;
922 		}
923 		return((si.si_umajor << 8) | si.si_uminor);
924 	} else {
925 		dprintf(stderr, "can't convert dev_t %p to a udev_t\n", dev);
926 		return NOUDEV;
927 	}
928 }
929 
930 udev_t
931 makeudev(int x, int y)
932 {
933         if ((x & 0xffffff00) || (y & 0x0000ff00))
934 		return NOUDEV;
935 	return ((x << 8) | y);
936 }
937 
938 /*
939  * getinetproto --
940  *	print name of protocol number
941  */
942 void
943 getinetproto(int number)
944 {
945 	static int isopen;
946 	struct protoent *pe;
947 
948 	if (!isopen)
949 		setprotoent(++isopen);
950 	if ((pe = getprotobynumber(number)) != NULL)
951 		printf(" %s", pe->p_name);
952 	else
953 		printf(" %d", number);
954 }
955 
956 int
957 getfname(const char *filename)
958 {
959 	struct stat statbuf;
960 	DEVS *cur;
961 
962 	if (stat(filename, &statbuf)) {
963 		warn("%s", filename);
964 		return(0);
965 	}
966 	if ((cur = malloc(sizeof(DEVS))) == NULL)
967 		err(1, NULL);
968 	cur->next = devs;
969 	devs = cur;
970 
971 	cur->ino = statbuf.st_ino;
972 	cur->fsid = statbuf.st_dev;
973 	cur->name = filename;
974 	return(1);
975 }
976 
977 void
978 usage(void)
979 {
980 	(void)fprintf(stderr,
981  "usage: fstat [-fmnv] [-p pid] [-u user] [-N system] [-M core] [file ...]\n");
982 	exit(1);
983 }
984 
985 static
986 void
987 make_printable(char *buf, int len)
988 {
989     while (len > 0) {
990 	if (!isprint(*buf))
991 		*buf = '?';
992 	++buf;
993 	--len;
994     }
995 }
996 
997 ssize_t
998 kread(const void *kaddr, void *uaddr, size_t nbytes)
999 {
1000     if (nbytes > 0x10000000)
1001 	return(0);
1002 
1003     if (kvm_read(kd, (u_long)kaddr, (char *)uaddr, nbytes) == (ssize_t)nbytes)
1004 	return(1);
1005     else
1006 	return(0);
1007 }
1008 
1009