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