xref: /freebsd/lib/libutil/kinfo_getvmmap.c (revision 6be3386466ab79a84b48429ae66244f21526d3df)
1 #include <sys/cdefs.h>
2 __FBSDID("$FreeBSD$");
3 
4 #include <sys/param.h>
5 #include <sys/sysctl.h>
6 #include <sys/user.h>
7 #include <stdlib.h>
8 #include <string.h>
9 
10 #include "libutil.h"
11 
12 struct kinfo_vmentry *
13 kinfo_getvmmap(pid_t pid, int *cntp)
14 {
15 	int mib[4];
16 	int error;
17 	int cnt;
18 	size_t len;
19 	char *buf, *bp, *eb;
20 	struct kinfo_vmentry *kiv, *kp, *kv;
21 
22 	*cntp = 0;
23 	len = 0;
24 	mib[0] = CTL_KERN;
25 	mib[1] = KERN_PROC;
26 	mib[2] = KERN_PROC_VMMAP;
27 	mib[3] = pid;
28 
29 	error = sysctl(mib, nitems(mib), NULL, &len, NULL, 0);
30 	if (error)
31 		return (NULL);
32 	len = len * 4 / 3;
33 	buf = malloc(len);
34 	if (buf == NULL)
35 		return (NULL);
36 	error = sysctl(mib, nitems(mib), buf, &len, NULL, 0);
37 	if (error) {
38 		free(buf);
39 		return (NULL);
40 	}
41 	/* Pass 1: count items */
42 	cnt = 0;
43 	bp = buf;
44 	eb = buf + len;
45 	while (bp < eb) {
46 		kv = (struct kinfo_vmentry *)(uintptr_t)bp;
47 		if (kv->kve_structsize == 0)
48 			break;
49 		bp += kv->kve_structsize;
50 		cnt++;
51 	}
52 
53 	kiv = calloc(cnt, sizeof(*kiv));
54 	if (kiv == NULL) {
55 		free(buf);
56 		return (NULL);
57 	}
58 	bp = buf;
59 	eb = buf + len;
60 	kp = kiv;
61 	/* Pass 2: unpack */
62 	while (bp < eb) {
63 		kv = (struct kinfo_vmentry *)(uintptr_t)bp;
64 		if (kv->kve_structsize == 0)
65 			break;
66 		/* Copy/expand into pre-zeroed buffer */
67 		memcpy(kp, kv, kv->kve_structsize);
68 		/* Advance to next packed record */
69 		bp += kv->kve_structsize;
70 		/* Set field size to fixed length, advance */
71 		kp->kve_structsize = sizeof(*kp);
72 		kp++;
73 	}
74 	free(buf);
75 	*cntp = cnt;
76 	return (kiv);	/* Caller must free() return value */
77 }
78