xref: /dragonfly/usr.bin/fstat/fstat.c (revision c8860c9a)
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 <vfs/nfs/nfsproto.h>
57 #include <vfs/nfs/rpcv2.h>
58 #include <vfs/nfs/nfs.h>
59 #include <vfs/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 = 9;
115 
116 const char *Uname;
117 char	*Comm;
118 int	Pid;
119 
120 struct fdnode *ofiles; 	/* buffer of pointers to file structures */
121 int maxfiles;
122 
123 #define ALLOC_OFILES(d)	\
124 	if ((d) > maxfiles) { \
125 		free(ofiles); \
126 		ofiles = malloc((d) * sizeof(struct fdnode)); \
127 		if (ofiles == NULL) { \
128 			err(1, NULL); \
129 		} \
130 		maxfiles = (d); \
131 	}
132 
133 kvm_t *kd;
134 
135 static void dofiles(struct kinfo_proc *, struct proc *);
136 static void dommap(struct proc *);
137 static void vtrans_reset(void);
138 static void vtrans(struct vnode *, struct nchandle *, int, int, off_t);
139 static int  ufs_filestat(struct vnode *, struct filestat *);
140 static int  nfs_filestat(struct vnode *, struct filestat *);
141 static int  devfs_filestat(struct vnode *, struct filestat *);
142 static char *getmnton(struct mount *, struct namecache_list *, struct nchandle *);
143 static void pipetrans(struct pipe *, int, int);
144 static void socktrans(struct socket *, int);
145 static void getinetproto(int);
146 static int  getfname(const char *);
147 static void usage(void) __dead2;
148 
149 
150 int
151 main(int argc, char **argv)
152 {
153 	struct passwd *passwd;
154 	struct kinfo_proc *p, *plast;
155 	struct proc proc;
156 	int arg, ch, what;
157 	char *memf, *nlistf;
158 	char buf[_POSIX2_LINE_MAX];
159 	int cnt;
160 
161 	arg = 0;
162 	what = KERN_PROC_ALL;
163 	nlistf = memf = NULL;
164 	while ((ch = getopt(argc, argv, "fmnp:u:vwN:M:")) != -1)
165 		switch((char)ch) {
166 		case 'f':
167 			fsflg = 1;
168 			break;
169 		case 'M':
170 			memf = optarg;
171 			break;
172 		case 'N':
173 			nlistf = optarg;
174 			break;
175 		case 'm':
176 			mflg = 1;
177 			break;
178 		case 'n':
179 			nflg = 1;
180 			break;
181 		case 'p':
182 			if (pflg++)
183 				usage();
184 			if (!isdigit(*optarg)) {
185 				warnx("-p requires a process id");
186 				usage();
187 			}
188 			what = KERN_PROC_PID;
189 			arg = atoi(optarg);
190 			break;
191 		case 'u':
192 			if (uflg++)
193 				usage();
194 			if (!(passwd = getpwnam(optarg)))
195 				errx(1, "%s: unknown uid", optarg);
196 			what = KERN_PROC_UID;
197 			arg = passwd->pw_uid;
198 			break;
199 		case 'v':
200 			vflg = 1;
201 			break;
202 		case 'w':
203 			wflg_mnt = 40;
204 			wflg_cmd = 16;
205 			break;
206 		case '?':
207 		default:
208 			usage();
209 		}
210 
211 	if (*(argv += optind)) {
212 		for (; *argv; ++argv) {
213 			if (getfname(*argv))
214 				checkfile = 1;
215 		}
216 		if (!checkfile)	/* file(s) specified, but none accessable */
217 			exit(1);
218 	}
219 
220 	ALLOC_OFILES(256);	/* reserve space for file pointers */
221 
222 	if (fsflg && !checkfile) {
223 		/* -f with no files means use wd */
224 		if (getfname(".") == 0)
225 			exit(1);
226 		checkfile = 1;
227 	}
228 
229 	/*
230 	 * Discard setgid privileges if not the running kernel so that bad
231 	 * guys can't print interesting stuff from kernel memory.
232 	 */
233 	if (nlistf != NULL || memf != NULL)
234 		setgid(getgid());
235 
236 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == NULL)
237 		errx(1, "%s", buf);
238 #ifdef notdef
239 	if (kvm_nlist(kd, nl) != 0)
240 		errx(1, "no namelist: %s", kvm_geterr(kd));
241 #endif
242 	if ((p = kvm_getprocs(kd, what, arg, &cnt)) == NULL)
243 		errx(1, "%s", kvm_geterr(kd));
244 	if (nflg)
245 		printf("USER     %-*.*s %*.*s   FD DEV              %*.*s MODE   SZ|DV R/W",
246 			wflg_cmd, wflg_cmd, "CMD",
247 			pid_width, pid_width, "PID",
248 			ino_width, ino_width, "INUM");
249 	else
250 		printf("USER     %-*.*s %*.*s   FD %-*.*s %*.*s MODE           SZ|DV R/W",
251 			wflg_cmd, wflg_cmd, "CMD",
252 			pid_width, pid_width, "PID",
253 			wflg_mnt, wflg_mnt, "PATH",
254 			ino_width, ino_width, "INUM");
255 	if (checkfile && fsflg == 0)
256 		printf(" NAME\n");
257 	else
258 		putchar('\n');
259 
260 	for (plast = &p[cnt]; p < plast; ++p) {
261 		if (p->kp_stat == SZOMB)
262 			continue;
263 		if (!kread((void *)p->kp_paddr, &proc, sizeof(proc))) {
264 			dprintf(stderr, "can't read proc at %p for pid %d\n",
265 			    (void *)p->kp_paddr, Pid);
266 			continue;
267 		}
268 		dofiles(p, &proc);
269 		if (mflg)
270 			dommap(&proc);
271 	}
272 	exit(0);
273 }
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 static 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 	vtrans_reset();
323 
324 	/*
325 	 * root directory vnode, if one
326 	 */
327 	if (filed.fd_rdir)
328 		vtrans(filed.fd_rdir, &filed.fd_nrdir, RDIR, FREAD, 0);
329 	/*
330 	 * current working directory vnode
331 	 */
332 	vtrans(filed.fd_cdir, &filed.fd_ncdir, CDIR, FREAD, 0);
333 	/*
334 	 * ktrace vnode, if one
335 	 */
336 	if (p->p_tracenode) {
337 		if (kread(p->p_tracenode, &ktrace_node, sizeof (ktrace_node)))
338 			vtrans(ktrace_node.kn_vp, NULL, TRACE, FREAD|FWRITE, 0);
339 	}
340 	/*
341 	 * text vnode, if one
342 	 */
343 	if (p->p_textvp)
344 		vtrans(p->p_textvp, NULL, TEXT, FREAD, 0);
345 	/*
346 	 * open files
347 	 */
348 	ALLOC_OFILES(filed.fd_lastfile+1);
349 	if (!kread(filed.fd_files, ofiles,
350 	    (filed.fd_lastfile+1) * sizeof(struct fdnode))) {
351 		dprintf(stderr,
352 		    "can't read file structures at %p for pid %d\n",
353 		    (void *)filed.fd_files, Pid);
354 		return;
355 	}
356 	for (i = 0; i <= filed.fd_lastfile; i++) {
357 		if (ofiles[i].fp == NULL)
358 			continue;
359 		if (!kread(ofiles[i].fp, &file, sizeof (struct file))) {
360 			dprintf(stderr, "can't read file %d at %p for pid %d\n",
361 			    i, (void *)ofiles[i].fp, Pid);
362 			continue;
363 		}
364 		if (file.f_type == DTYPE_VNODE) {
365 			vtrans((struct vnode *)file.f_data, &file.f_nchandle,
366 				i, file.f_flag, file.f_offset);
367 		} else if (file.f_type == DTYPE_SOCKET) {
368 			if (checkfile == 0)
369 				socktrans((struct socket *)file.f_data, i);
370 		}
371 #ifdef DTYPE_PIPE
372 		else if (file.f_type == DTYPE_PIPE) {
373 			if (checkfile == 0)
374 				pipetrans((struct pipe *)file.f_data, i,
375 				    file.f_flag);
376 		}
377 #endif
378 #ifdef DTYPE_FIFO
379 		else if (file.f_type == DTYPE_FIFO) {
380 			if (checkfile == 0)
381 				vtrans((struct vnode *)file.f_data,
382 					&file.f_nchandle,
383 					i, file.f_flag, file.f_offset);
384 		}
385 #endif
386 		else {
387 			dprintf(stderr,
388 			    "unknown file type %d for file %d of pid %d\n",
389 			    file.f_type, i, Pid);
390 		}
391 	}
392 }
393 
394 static void
395 dommap(struct proc *p)
396 {
397 	struct vmspace vmspace;
398 	vm_map_t map;
399 	struct vm_map_entry entry;
400 	vm_map_entry_t ken;
401 	struct vm_object object;
402 	struct vm_map_backing ba;
403 	vm_object_t objp;
404 	int prot, fflags;
405 
406 	if (!kread(p->p_vmspace, &vmspace, sizeof(vmspace))) {
407 		dprintf(stderr, "can't read vmspace at %p for pid %d\n",
408 		    (void *)p->p_vmspace, Pid);
409 		return;
410 	}
411 
412 	map = &vmspace.vm_map;
413 	for (ken = kvm_vm_map_entry_first(kd, map, &entry);
414 	     ken; ken = kvm_vm_map_entry_next(kd, ken, &entry)) {
415 		if (entry.maptype == VM_MAPTYPE_SUBMAP)
416 			continue;
417 
418 		if (entry.ba.object == NULL)
419 			continue;
420 		ba = entry.ba;
421 		for (;;) {
422 			if ((objp = entry.ba.object) != NULL) {
423 				if (!kread(objp, &object, sizeof(object))) {
424 					dprintf(stderr,
425 					    "can't read vm_object at %p "
426 					    "for pid %d\n",
427 					    (void *)objp, Pid);
428 					return;
429 				}
430 			}
431 			if (ba.backing_ba == NULL)
432 				break;
433 			if (!kread(ba.backing_ba, &ba, sizeof(ba))) {
434 				dprintf(stderr,
435 				    "can't read map_backing at %p "
436 				    "for pid %d\n",
437 				    (void *)ba.backing_ba, Pid);
438 				return;
439 			}
440 		}
441 
442 		prot = entry.protection;
443 		fflags = (prot & VM_PROT_READ ? FREAD : 0) |
444 			 (prot & VM_PROT_WRITE ? FWRITE : 0);
445 
446 		switch (object.type) {
447 		case OBJT_VNODE:
448 			vtrans((struct vnode *)object.handle, NULL,
449 				MMAP, fflags, 0);
450 			break;
451 		default:
452 			break;
453 		}
454 	}
455 }
456 
457 static int last_name_width;
458 
459 static void
460 vtrans_reset(void)
461 {
462 	last_name_width = 0;
463 }
464 
465 static void
466 vtrans(struct vnode *vp, struct nchandle *ncr, int i, int flag, off_t off)
467 {
468 	struct vnode vn;
469 	struct filestat fst;
470 	char rw[3], mode[15];
471 	const char *badtype = NULL, *filename;
472 	char *name;
473 	int len;
474 	int extra_space;
475 
476 	fst.offset = off;
477 	filename = badtype = NULL;
478 	if (!kread(vp, &vn, sizeof (struct vnode))) {
479 		dprintf(stderr, "can't read vnode at %p for pid %d\n",
480 		    (void *)vp, Pid);
481 		return;
482 	}
483 	if (vn.v_type == VNON || vn.v_tag == VT_NON) {
484 		badtype = "none";
485 	} else if (vn.v_type == VBAD) {
486 		badtype = "bad";
487 	} else {
488 		switch (vn.v_tag) {
489 		case VT_HAMMER:
490 			if (!hammer_filestat(&vn, &fst))
491 				badtype = "error";
492 			break;
493 		case VT_HAMMER2:
494 			if (!hammer2_filestat(&vn, &fst))
495 				badtype = "error";
496 			break;
497 		case VT_TMPFS:
498 			if (!tmpfs_filestat(&vn, &fst))
499 				badtype = "error";
500 			break;
501 		case VT_UFS:
502 			if (!ufs_filestat(&vn, &fst))
503 				badtype = "error";
504 			break;
505 		case VT_MFS:
506 			if (!ufs_filestat(&vn, &fst))
507 				badtype = "error";
508 			break;
509 		case VT_NFS:
510 			if (!nfs_filestat(&vn, &fst))
511 				badtype = "error";
512 			break;
513 		case VT_NTFS:
514 			if (!ntfs_filestat(&vn, &fst))
515 				badtype = "error";
516 			break;
517 		case VT_EXT2FS:
518 			if (!ext2fs_filestat(&vn, &fst))
519 				badtype = "error";
520 			break;
521 
522 		case VT_MSDOSFS:
523 			if (!msdosfs_filestat(&vn, &fst))
524 				badtype = "error";
525 			break;
526 
527 		case VT_ISOFS:
528 			if (!isofs_filestat(&vn, &fst))
529 				badtype = "error";
530 			break;
531 
532 		case VT_DEVFS:
533 			if (!devfs_filestat(&vn, &fst))
534 				badtype = "error";
535 			break;
536 
537 		default:
538 			{
539 				static char unknown[10];
540 
541 				sprintf(unknown, "?(%x)", vn.v_tag);
542 				badtype = unknown;
543 				break;
544 			}
545 		}
546 	}
547 	if (checkfile) {
548 		int fsmatch = 0;
549 		DEVS *d;
550 
551 		if (badtype)
552 			return;
553 		for (d = devs; d != NULL; d = d->next)
554 			if (d->fsid == fst.fsid) {
555 				fsmatch = 1;
556 				if (d->ino == (ino_t)fst.fileid) {
557 					filename = d->name;
558 					break;
559 				}
560 			}
561 		if (fsmatch == 0 || (filename == NULL && fsflg == 0))
562 			return;
563 	}
564 	PREFIX(i);
565 
566 	/*
567 	 * Retrieve variable-length file path and try to make
568 	 * indentation human-readable.
569 	 */
570 	if (badtype) {
571 		asprintf(&name, "%s",
572 			 getmnton(vn.v_mount, &vn.v_namecache, ncr));
573 	} else if (nflg) {
574 		asprintf(&name, "%3u,%-9u",
575 		         major(fst.fsid), minor(fst.fsid));
576 	} else {
577 		asprintf(&name, "%s",
578 		         getmnton(vn.v_mount, &vn.v_namecache, ncr));
579 	}
580 	len = (int)strlen(name);
581 
582 	/*
583 	 * Nominal extra-space indented in multiples of 4
584 	 */
585 	extra_space = wflg_mnt - len;
586 	if (extra_space < 0)
587 		extra_space = 4 - -extra_space % 4;
588 
589 	if (len + extra_space < last_name_width)
590 		extra_space = last_name_width - len;
591 	last_name_width = len + extra_space;
592 
593 	printf(" %s%*.*s ", name, extra_space, extra_space, "");
594 	free(name);
595 	name = NULL;
596 
597 	/*
598 	 * Remaining sections
599 	 */
600 	if (badtype) {
601 		printf("%10s    %8s:%jd\n",
602 		       badtype, "offset", (intmax_t)off);
603 		return;
604 	}
605 
606 	if (nflg) {
607 		sprintf(mode, "%06o", fst.mode);
608 		printf("%*ld %s", ino_width, fst.fileid, mode);
609 	} else {
610 		strmode(fst.mode, mode);
611 		printf("%*ld %10s", ino_width, fst.fileid, mode);
612 	}
613 
614 	switch (vn.v_type) {
615 	case VBLK:
616 	case VCHR:
617 		if (nflg ||
618 		    ((name = devname(fst.rdev, vn.v_type == VCHR ?
619 				      S_IFCHR : S_IFBLK)) == NULL)) {
620 			printf(" %3u,%-4u", major(fst.rdev), minor(fst.rdev));
621 		} else {
622 			printf(" %8s", name);
623 		}
624 		printf(":%jd", (intmax_t)fst.offset);
625 		break;
626 	case VREG:
627 		printf(" %8s:%ju", "offset", (intmax_t)fst.offset);
628 		break;
629 	default:
630 		printf(" %8s:%ju", "offset", (uintmax_t)fst.size);
631 	}
632 	rw[0] = '\0';
633 	if (flag & FREAD)
634 		strcat(rw, "r");
635 	if (flag & FWRITE)
636 		strcat(rw, "w");
637 	printf(" %2s", rw);
638 	if (filename && !fsflg)
639 		printf("  %s", filename);
640 	putchar('\n');
641 }
642 
643 static int
644 ufs_filestat(struct vnode *vp, struct filestat *fsp)
645 {
646 	struct inode inode;
647 
648 	if (!kread(VTOI(vp), &inode, sizeof (inode))) {
649 		dprintf(stderr, "can't read inode at %p for pid %d\n",
650 		    (void *)VTOI(vp), Pid);
651 		return 0;
652 	}
653 	/*
654 	 * The st_dev from stat(2) is a dev_t. These kernel structures
655 	 * contain cdev_t structures. We need to convert to udev to make
656 	 * comparisons
657 	 */
658 	fsp->fsid = fstat_dev2udev(inode.i_dev);
659 	fsp->fileid = (long)inode.i_number;
660 	fsp->mode = (mode_t)inode.i_mode;
661 	fsp->size = inode.i_size;
662 	fsp->rdev = inode.i_rdev;
663 
664 	return 1;
665 }
666 
667 static int
668 nfs_filestat(struct vnode *vp, struct filestat *fsp)
669 {
670 	struct nfsnode nfsnode;
671 
672 	if (!kread(VTONFS(vp), &nfsnode, sizeof (nfsnode))) {
673 		dprintf(stderr, "can't read nfsnode at %p for pid %d\n",
674 		    (void *)VTONFS(vp), Pid);
675 		return 0;
676 	}
677 	fsp->fsid = nfsnode.n_vattr.va_fsid;
678 	fsp->fileid = nfsnode.n_vattr.va_fileid;
679 	fsp->size = nfsnode.n_size;
680 	fsp->rdev = makeudev(nfsnode.n_vattr.va_rmajor,
681 			     nfsnode.n_vattr.va_rminor);
682 	fsp->mode = nfsnode.n_vattr.va_mode | mtrans(vp->v_type);
683 
684 	return 1;
685 }
686 
687 static int
688 devfs_filestat(struct vnode *vp, struct filestat *fsp)
689 {
690 	struct devfs_node devfs_node;
691 
692 	if (!kread(vp->v_data, &devfs_node, sizeof (devfs_node))) {
693 		dprintf(stderr, "can't read devfs_node at %p for pid %d\n",
694 		    (void *)vp->v_data, Pid);
695 		return 0;
696 	}
697 	fsp->fsid = fsp->rdev = fstat_dev2udev(vp->v_rdev);
698 	fsp->fileid = devfs_node.d_dir.d_ino;
699 	fsp->mode = (devfs_node.mode & ~S_IFMT) | S_IFCHR;
700 	fsp->size = 0;
701 
702 	return 1;
703 }
704 
705 static char *
706 getmnton(struct mount *m, struct namecache_list *ncplist, struct nchandle *ncr)
707 {
708 	static struct mount mount_l;
709 	static struct mtab {
710 		struct mtab *next;
711 		struct mount *m;
712 		char mntonname[MNAMELEN];
713 	} *mhead = NULL;
714 	struct mtab *mt;
715 	struct namecache *ncp;
716 	struct namecache ncp_copy;
717 	static char path[1024];
718 	int i;
719 
720 	/*
721 	 * If no ncp is passed try to find one via ncplist.  Make sure
722 	 * we are using the correct mount pointer or the matching code
723 	 * will not know how to transition mount points properly.
724 	 */
725 	if (ncr == NULL || ncr->ncp == NULL) {
726 		ncp = ncplist->tqh_first;
727 	} else {
728 		ncp = ncr->ncp;
729 		if (ncr->mount)
730 			m = ncr->mount;
731 	}
732 
733 	/*
734 	 * If we have an ncp, traceback the path.  This is a kvm pointer.
735 	 */
736 	if (ncp) {
737 		if (!kread(m, &mount_l, sizeof(struct mount))) {
738 			warnx("can't read mount table at %p", (void *)m);
739 			return (NULL);
740 		}
741 		i = sizeof(path) - 1;
742 		path[i] = 0;
743 		while (ncp) {
744 			/*
745 			 * If this is the root of the mount then traverse
746 			 * to the parent mount.
747 			 */
748 			if (ncp == mount_l.mnt_ncmountpt.ncp) {
749 				ncp = mount_l.mnt_ncmounton.ncp;
750 				if (ncp == NULL)
751 					break;
752 				m = mount_l.mnt_ncmounton.mount;
753 				if (!kread(m, &mount_l, sizeof(struct mount))) {
754 					warnx("can't read mount table at %p", (void *)m);
755 					return (NULL);
756 				}
757 			}
758 
759 			/*
760 			 * Ok, pull out the ncp and extract the name
761 			 */
762 			if (!kread(ncp, &ncp_copy, sizeof(ncp_copy))) {
763 				warnx("can't read ncp at %p", ncp);
764 				return (NULL);
765 			}
766 			if (i <= ncp_copy.nc_nlen)
767 				break;
768 			i -= ncp_copy.nc_nlen;
769 			if (!kread(ncp_copy.nc_name, path + i, ncp_copy.nc_nlen)) {
770 				warnx("can't read ncp %p path component at %p", ncp, ncp_copy.nc_name);
771 				return (NULL);
772 			}
773 			make_printable(path + i, ncp_copy.nc_nlen);
774 			path[--i] = '/';
775 			ncp = ncp_copy.nc_parent;
776 		}
777 		if (i == sizeof(path) - 1)
778 			path[--i] = '/';
779 		return(path + i);
780 	}
781 
782 	/*
783 	 * If all else fails print out the mount point path
784 	 */
785 	for (mt = mhead; mt != NULL; mt = mt->next) {
786 		if (m == mt->m)
787 			return (mt->mntonname);
788 	}
789 	if (!kread(m, &mount_l, sizeof(struct mount))) {
790 		warnx("can't read mount table at %p", (void *)m);
791 		return (NULL);
792 	}
793 	if ((mt = malloc(sizeof (struct mtab))) == NULL)
794 		err(1, NULL);
795 	mt->m = m;
796 	bcopy(&mount_l.mnt_stat.f_mntonname[0], &mt->mntonname[0], MNAMELEN);
797 	mt->next = mhead;
798 	mhead = mt;
799 	return (mt->mntonname);
800 }
801 
802 static void
803 pipetrans(struct pipe *pi, int i, int flag)
804 {
805 	struct pipe pip;
806 	struct pipebuf *b1;
807 	struct pipebuf *b2;
808 	char rw[3];
809 	char side1;
810 	char side2;
811 
812 	PREFIX(i);
813 	if ((intptr_t)pi & 1) {
814 		side1 = 'B';
815 		side2 = 'A';
816 		b1 = &pip.bufferB;
817 		b2 = &pip.bufferA;
818 	} else {
819 		side1 = 'A';
820 		side2 = 'B';
821 		b1 = &pip.bufferA;
822 		b2 = &pip.bufferB;
823 	}
824 	pi = (void *)((intptr_t)pi & ~(intptr_t)1);
825 
826 	/* fill in socket */
827 	if (!kread(pi, &pip, sizeof(struct pipe))) {
828 		dprintf(stderr, "can't read pipe at %p\n", (void *)pi);
829 		goto bad;
830 	}
831 
832 	printf("* pipe %8lx (%c<->%c)", (u_long)pi, side1, side2);
833 	printf(" ravail %-zu wavail %-zu",
834 	       b1->windex - b1->rindex,
835 	       b2->windex - b2->rindex);
836 	rw[0] = '\0';
837 	if (flag & FREAD)
838 		strcat(rw, "r");
839 	if (flag & FWRITE)
840 		strcat(rw, "w");
841 	printf(" %2s", rw);
842 	putchar('\n');
843 	return;
844 
845 bad:
846 	printf("* error\n");
847 }
848 
849 static void
850 socktrans(struct socket *sock, int i)
851 {
852 	static const char *stypename[] = {
853 		"unused",	/* 0 */
854 		"stream", 	/* 1 */
855 		"dgram ",	/* 2 */
856 		"raw   ",	/* 3 */
857 		"rdm   ",	/* 4 */
858 		"seqpak"	/* 5 */
859 	};
860 #define	STYPEMAX 5
861 	struct socket	so;
862 	struct protosw	proto;
863 	struct domain	dom;
864 	struct inpcb	inpcb;
865 	struct unpcb	unpcb;
866 	int len;
867 	char dname[32];
868 
869 	PREFIX(i);
870 
871 	/* fill in socket */
872 	if (!kread(sock, &so, sizeof(struct socket))) {
873 		dprintf(stderr, "can't read sock at %p\n", (void *)sock);
874 		goto bad;
875 	}
876 
877 	/* fill in protosw entry */
878 	if (!kread(so.so_proto, &proto, sizeof(struct protosw))) {
879 		dprintf(stderr, "can't read protosw at %p",
880 		    (void *)so.so_proto);
881 		goto bad;
882 	}
883 
884 	/* fill in domain */
885 	if (!kread(proto.pr_domain, &dom, sizeof(struct domain))) {
886 		dprintf(stderr, "can't read domain at %p\n",
887 		    (const void *)proto.pr_domain);
888 		goto bad;
889 	}
890 
891 	if ((len = kvm_read(kd, (u_long)dom.dom_name, dname,
892 	    sizeof(dname) - 1)) < 0) {
893 		dprintf(stderr, "can't read domain name at %p\n",
894 		    (void *)dom.dom_name);
895 		dname[0] = '\0';
896 	}
897 	else
898 		dname[len] = '\0';
899 
900 	if ((u_short)so.so_type > STYPEMAX)
901 		printf("* %-9s ?%d", dname, so.so_type);
902 	else
903 		printf("* %-9s %s", dname, stypename[so.so_type]);
904 
905 	/*
906 	 * protocol specific formatting
907 	 *
908 	 * Try to find interesting things to print.  For tcp, the interesting
909 	 * thing is the address of the tcpcb, for udp and others, just the
910 	 * inpcb (socket pcb).  For unix domain, its the address of the socket
911 	 * pcb and the address of the connected pcb (if connected).  Otherwise
912 	 * just print the protocol number and address of the socket itself.
913 	 * The idea is not to duplicate netstat, but to make available enough
914 	 * information for further analysis.
915 	 */
916 	switch(dom.dom_family) {
917 	case AF_INET:
918 	case AF_INET6:
919 		getinetproto(proto.pr_protocol);
920 		if (proto.pr_protocol == IPPROTO_TCP ) {
921 			if (so.so_pcb) {
922 				if (kvm_read(kd, (u_long)so.so_pcb,
923 				    (char *)&inpcb, sizeof(struct inpcb))
924 				    != sizeof(struct inpcb)) {
925 					dprintf(stderr,
926 					    "can't read inpcb at %p\n",
927 					    (void *)so.so_pcb);
928 					goto bad;
929 				}
930 				printf(" %lx", (u_long)inpcb.inp_ppcb);
931 			}
932 		}
933 		else if (so.so_pcb)
934 			printf(" %lx", (u_long)so.so_pcb);
935 		break;
936 	case AF_UNIX:
937 		/* print address of pcb and connected pcb */
938 		if (so.so_pcb) {
939 			printf(" %lx", (u_long)so.so_pcb);
940 			if (kvm_read(kd, (u_long)so.so_pcb, (char *)&unpcb,
941 			    sizeof(struct unpcb)) != sizeof(struct unpcb)){
942 				dprintf(stderr, "can't read unpcb at %p\n",
943 				    (void *)so.so_pcb);
944 				goto bad;
945 			}
946 			if (unpcb.unp_conn) {
947 				char shoconn[4], *cp;
948 
949 				cp = shoconn;
950 				if (!(so.so_state & SS_CANTRCVMORE))
951 					*cp++ = '<';
952 				*cp++ = '-';
953 				if (!(so.so_state & SS_CANTSENDMORE))
954 					*cp++ = '>';
955 				*cp = '\0';
956 				printf(" %s %lx", shoconn,
957 				    (u_long)unpcb.unp_conn);
958 			}
959 		}
960 		break;
961 	default:
962 		/* print protocol number and socket address */
963 		printf(" %d %lx", proto.pr_protocol, (u_long)sock);
964 	}
965 	printf("\n");
966 	return;
967 bad:
968 	printf("* error\n");
969 }
970 
971 
972 /*
973  * Read the cdev structure in the kernel (as pointed to by a cdev_t)
974  * in order to work out the associated dev_t
975  */
976 dev_t
977 fstat_dev2udev(cdev_t dev)
978 {
979 	struct cdev si;
980 
981 	if (kread(dev, &si, sizeof si)) {
982 		if ((si.si_umajor & 0xffffff00) ||
983 		    (si.si_uminor & 0x0000ff00)) {
984 			return NOUDEV;
985 		}
986 		return((si.si_umajor << 8) | si.si_uminor);
987 	} else {
988 		dprintf(stderr, "can't convert cdev_t %p to a dev_t\n", dev);
989 		return NOUDEV;
990 	}
991 }
992 
993 dev_t
994 makeudev(int x, int y)
995 {
996         if ((x & 0xffffff00) || (y & 0x0000ff00))
997 		return NOUDEV;
998 	return ((x << 8) | y);
999 }
1000 
1001 /*
1002  * getinetproto --
1003  *	print name of protocol number
1004  */
1005 static void
1006 getinetproto(int number)
1007 {
1008 	static int isopen;
1009 	struct protoent *pe;
1010 
1011 	if (!isopen)
1012 		setprotoent(++isopen);
1013 	if ((pe = getprotobynumber(number)) != NULL)
1014 		printf(" %s", pe->p_name);
1015 	else
1016 		printf(" %d", number);
1017 }
1018 
1019 static int
1020 getfname(const char *filename)
1021 {
1022 	struct stat statbuf;
1023 	DEVS *cur;
1024 
1025 	if (stat(filename, &statbuf)) {
1026 		warn("%s", filename);
1027 		return(0);
1028 	}
1029 	if ((cur = malloc(sizeof(DEVS))) == NULL)
1030 		err(1, NULL);
1031 	cur->next = devs;
1032 	devs = cur;
1033 
1034 	cur->ino = statbuf.st_ino;
1035 	cur->fsid = statbuf.st_dev;
1036 	cur->name = filename;
1037 	return(1);
1038 }
1039 
1040 static void
1041 usage(void)
1042 {
1043 	(void)fprintf(stderr,
1044  "usage: fstat [-fmnv] [-p pid] [-u user] [-N system] [-M core] [file ...]\n");
1045 	exit(1);
1046 }
1047 
1048 static
1049 void
1050 make_printable(char *buf, int len)
1051 {
1052     while (len > 0) {
1053 	if (!isprint(*buf))
1054 		*buf = '?';
1055 	++buf;
1056 	--len;
1057     }
1058 }
1059 
1060 ssize_t
1061 kread(const void *kaddr, void *uaddr, size_t nbytes)
1062 {
1063     if (nbytes > 0x10000000)
1064 	return(0);
1065 
1066     if (kvm_read(kd, (u_long)kaddr, (char *)uaddr, nbytes) == (ssize_t)nbytes)
1067 	return(1);
1068     else
1069 	return(0);
1070 }
1071