xref: /dragonfly/test/kvm/kvm_file/test_kvm_file.c (revision 33463a05)
1 #include <sys/types.h>
2 #define _KERNEL_STRUCTURES
3 #include <sys/file.h>
4 #include <sys/kinfo.h>
5 
6 #include <err.h>
7 #include <fcntl.h>
8 #include <kvm.h>
9 #include <limits.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 
14 static void
15 usage(const char *cmd)
16 {
17 	fprintf(stderr, "%s [-N kern] [-M core]\n", cmd);
18 	exit(1);
19 }
20 
21 static const char *
22 typestr(short type)
23 {
24 	static char buf[32];
25 
26 	switch (type) {
27 	case DTYPE_VNODE:
28 		return "file";
29 	case DTYPE_SOCKET:
30 		return "socket";
31 	case DTYPE_PIPE:
32 		return "pipe";
33 	case DTYPE_FIFO:
34 		return "fifo";
35 	case DTYPE_KQUEUE:
36 		return "kqueue";
37 	case DTYPE_CRYPTO:
38 		return "crypto";
39 	case DTYPE_SYSLINK:
40 		return "syslink";
41 	case DTYPE_MQUEUE:
42 		return "mqueue";
43 	default:
44 		snprintf(buf, sizeof(buf), "?%d", type);
45 		return buf;
46 	}
47 }
48 
49 int
50 main(int argc, char *argv[])
51 {
52 	const char *file, *core;
53 	char *errbuf;
54 	kvm_t *kd;
55 	int opt, kfile_cnt, i;
56 	struct kinfo_file *kfile;
57 
58 	file = NULL;
59 	core = NULL;
60 
61 	while ((opt = getopt(argc, argv, "M:N:")) != -1) {
62 		switch (opt) {
63 		case 'M':
64 			core = optarg;
65 			break;
66 
67 		case 'N':
68 			file = optarg;
69 			break;
70 
71 		default:
72 			usage(argv[0]);
73 		}
74 	}
75 
76 	errbuf = malloc(_POSIX2_LINE_MAX);
77 	if (errbuf == NULL)
78 		err(2, "malloc %d failed", _POSIX2_LINE_MAX);
79 
80 	kd = kvm_openfiles(file, core, NULL, O_RDONLY, errbuf);
81 	if (kd == NULL)
82 		errx(2, "%s", errbuf);
83 
84 	kfile = kvm_getfiles(kd, 0, 0, &kfile_cnt);
85 	if (kfile == NULL)
86 		errx(2, "kvm_getfiles failed %s", kvm_geterr(kd));
87 
88 	for (i = 0; i < kfile_cnt; ++i) {
89 		printf("pid %d, fd %d, type %s\n",
90 		    kfile[i].f_pid, kfile[i].f_fd, typestr(kfile[i].f_type));
91 	}
92 
93 	kvm_close(kd);
94 
95 	return 0;
96 }
97