xref: /openbsd/usr.sbin/kgmon/kgmon.c (revision 3d8817e4)
1 /*	$OpenBSD: kgmon.c,v 1.15 2009/10/27 23:59:51 deraadt Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1992, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/param.h>
33 #include <sys/file.h>
34 #include <sys/sysctl.h>
35 #include <sys/gmon.h>
36 #include <errno.h>
37 #include <err.h>
38 #include <kvm.h>
39 #include <limits.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <unistd.h>
43 #include <string.h>
44 #include <nlist.h>
45 #include <ctype.h>
46 #include <paths.h>
47 
48 struct nlist nl[] = {
49 #define	N_GMONPARAM	0
50 	{ "__gmonparam" },
51 #define	N_PROFHZ	1
52 	{ "_profhz" },
53 	{ NULL }
54 };
55 
56 struct kvmvars {
57 	kvm_t	*kd;
58 	struct gmonparam gpm;
59 };
60 
61 int	bflag, hflag, kflag, rflag, pflag;
62 int	debug = 0;
63 void	setprof(struct kvmvars *, int);
64 void	dumpstate(struct kvmvars *);
65 void	reset(struct kvmvars *);
66 void	kern_readonly(int);
67 int	getprof(struct kvmvars *);
68 int	getprofhz(struct kvmvars *);
69 int	openfiles(char *, char *, struct kvmvars *);
70 
71 int
72 main(int argc, char **argv)
73 {
74 	extern char *__progname;
75 	int ch, mode, disp, accessmode;
76 	struct kvmvars kvmvars;
77 	char *sys, *kmemf;
78 
79 	seteuid(getuid());
80 	kmemf = NULL;
81 	sys = NULL;
82 	while ((ch = getopt(argc, argv, "M:N:bhpr")) != -1) {
83 		switch((char)ch) {
84 
85 		case 'M':
86 			kmemf = optarg;
87 			kflag = 1;
88 			break;
89 
90 		case 'N':
91 			sys = optarg;
92 			break;
93 
94 		case 'b':
95 			bflag = 1;
96 			break;
97 
98 		case 'h':
99 			hflag = 1;
100 			break;
101 
102 		case 'p':
103 			pflag = 1;
104 			break;
105 
106 		case 'r':
107 			rflag = 1;
108 			break;
109 
110 		default:
111 			fprintf(stderr,
112 			    "usage: %s [-bhpr] [-M core] [-N system]\n",
113 			    __progname);
114 			exit(1);
115 		}
116 	}
117 	argc -= optind;
118 	argv += optind;
119 
120 #define BACKWARD_COMPATIBILITY
121 #ifdef	BACKWARD_COMPATIBILITY
122 	if (*argv) {
123 		sys = *argv;
124 		if (*++argv) {
125 			kmemf = *argv;
126 			++kflag;
127 		}
128 	}
129 #endif
130 	accessmode = openfiles(sys, kmemf, &kvmvars);
131 	mode = getprof(&kvmvars);
132 	if (hflag)
133 		disp = GMON_PROF_OFF;
134 	else if (bflag)
135 		disp = GMON_PROF_ON;
136 	else
137 		disp = mode;
138 	if (pflag)
139 		dumpstate(&kvmvars);
140 	if (rflag)
141 		reset(&kvmvars);
142 	if (accessmode == O_RDWR)
143 		setprof(&kvmvars, disp);
144 	printf("%s: kernel profiling is %s.\n", __progname,
145 	    disp == GMON_PROF_OFF ? "off" : "running");
146 	return (0);
147 }
148 
149 /*
150  * Check that profiling is enabled and open any ncessary files.
151  */
152 int
153 openfiles(char *sys, char *kmemf, struct kvmvars *kvp)
154 {
155 	int mib[3], state, openmode;
156 	size_t size;
157 	char errbuf[_POSIX2_LINE_MAX];
158 
159 	if (!kflag) {
160 		mib[0] = CTL_KERN;
161 		mib[1] = KERN_PROF;
162 		mib[2] = GPROF_STATE;
163 		size = sizeof state;
164 		if (sysctl(mib, 3, &state, &size, NULL, 0) < 0)
165 			errx(20, "profiling not defined in kernel.");
166 		if (!(bflag || hflag || rflag ||
167 		    (pflag && state == GMON_PROF_ON)))
168 			return (O_RDONLY);
169 		(void)seteuid(0);
170 		if (sysctl(mib, 3, NULL, NULL, &state, size) >= 0)
171 			return (O_RDWR);
172 		(void)seteuid(getuid());
173 		kern_readonly(state);
174 		return (O_RDONLY);
175 	}
176 	openmode = (bflag || hflag || pflag || rflag) ? O_RDWR : O_RDONLY;
177 	kvp->kd = kvm_openfiles(sys, kmemf, NULL, openmode, errbuf);
178 	if (kvp->kd == NULL) {
179 		if (openmode == O_RDWR) {
180 			openmode = O_RDONLY;
181 			kvp->kd = kvm_openfiles(sys, kmemf, NULL, O_RDONLY,
182 			    errbuf);
183 		}
184 		if (kvp->kd == NULL)
185 			errx(2, "kvm_openfiles: %s", errbuf);
186 		kern_readonly(GMON_PROF_ON);
187 	}
188 	if (kvm_nlist(kvp->kd, nl) < 0)
189 		errx(3, "%s: no namelist", sys ? sys : _PATH_UNIX);
190 	if (!nl[N_GMONPARAM].n_value)
191 		errx(20, "profiling not defined in kernel.");
192 	return (openmode);
193 }
194 
195 /*
196  * Suppress options that require a writable kernel.
197  */
198 void
199 kern_readonly(int mode)
200 {
201 	extern char *__progname;
202 
203 	(void)fprintf(stderr, "%s: kernel read-only: ", __progname);
204 	if (pflag && mode == GMON_PROF_ON)
205 		(void)fprintf(stderr, "data may be inconsistent\n");
206 	if (rflag)
207 		(void)fprintf(stderr, "-r suppressed\n");
208 	if (bflag)
209 		(void)fprintf(stderr, "-b suppressed\n");
210 	if (hflag)
211 		(void)fprintf(stderr, "-h suppressed\n");
212 	rflag = bflag = hflag = 0;
213 }
214 
215 /*
216  * Get the state of kernel profiling.
217  */
218 int
219 getprof(struct kvmvars *kvp)
220 {
221 	int mib[3];
222 	size_t size;
223 
224 	if (kflag) {
225 		size = kvm_read(kvp->kd, nl[N_GMONPARAM].n_value, &kvp->gpm,
226 		    sizeof kvp->gpm);
227 	} else {
228 		mib[0] = CTL_KERN;
229 		mib[1] = KERN_PROF;
230 		mib[2] = GPROF_GMONPARAM;
231 		size = sizeof kvp->gpm;
232 		if (sysctl(mib, 3, &kvp->gpm, &size, NULL, 0) < 0)
233 			size = 0;
234 	}
235 	if (size != sizeof kvp->gpm)
236 		errx(4, "cannot get gmonparam: %s",
237 		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
238 	return (kvp->gpm.state);
239 }
240 
241 /*
242  * Enable or disable kernel profiling according to the state variable.
243  */
244 void
245 setprof(struct kvmvars *kvp, int state)
246 {
247 	struct gmonparam *p = (struct gmonparam *)nl[N_GMONPARAM].n_value;
248 	int mib[3], oldstate;
249 	size_t sz;
250 
251 	sz = sizeof(state);
252 	if (!kflag) {
253 		mib[0] = CTL_KERN;
254 		mib[1] = KERN_PROF;
255 		mib[2] = GPROF_STATE;
256 		if (sysctl(mib, 3, &oldstate, &sz, NULL, 0) < 0)
257 			goto bad;
258 		if (oldstate == state)
259 			return;
260 		(void)seteuid(0);
261 		if (sysctl(mib, 3, NULL, NULL, &state, sz) >= 0) {
262 			(void)seteuid(getuid());
263 			return;
264 		}
265 		(void)seteuid(getuid());
266 	} else if (kvm_write(kvp->kd, (u_long)&p->state, (void *)&state, sz)
267 	    == sz)
268 		return;
269 bad:
270 	warnx("warning: cannot turn profiling %s",
271 	    state == GMON_PROF_OFF ? "off" : "on");
272 }
273 
274 /*
275  * Build the gmon.out file.
276  */
277 void
278 dumpstate(struct kvmvars *kvp)
279 {
280 	FILE *fp;
281 	struct rawarc rawarc;
282 	struct tostruct *tos;
283 	u_long frompc;
284 	u_short *froms, *tickbuf;
285 	int mib[3];
286 	size_t i;
287 	struct gmonhdr h;
288 	int fromindex, endfrom, toindex;
289 
290 	setprof(kvp, GMON_PROF_OFF);
291 	fp = fopen("gmon.out", "w");
292 	if (fp == 0) {
293 		perror("gmon.out");
294 		return;
295 	}
296 
297 	/*
298 	 * Build the gmon header and write it to a file.
299 	 */
300 	bzero(&h, sizeof(h));
301 	h.lpc = kvp->gpm.lowpc;
302 	h.hpc = kvp->gpm.highpc;
303 	h.ncnt = kvp->gpm.kcountsize + sizeof(h);
304 	h.version = GMONVERSION;
305 	h.profrate = getprofhz(kvp);
306 	fwrite((char *)&h, sizeof(h), 1, fp);
307 
308 	/*
309 	 * Write out the tick buffer.
310 	 */
311 	mib[0] = CTL_KERN;
312 	mib[1] = KERN_PROF;
313 	if ((tickbuf = (u_short *)malloc(kvp->gpm.kcountsize)) == NULL)
314 		errx(5, "cannot allocate kcount space");
315 	if (kflag) {
316 		i = kvm_read(kvp->kd, (u_long)kvp->gpm.kcount, (void *)tickbuf,
317 		    kvp->gpm.kcountsize);
318 	} else {
319 		mib[2] = GPROF_COUNT;
320 		i = kvp->gpm.kcountsize;
321 		if (sysctl(mib, 3, tickbuf, &i, NULL, 0) < 0)
322 			i = 0;
323 	}
324 	if (i != kvp->gpm.kcountsize)
325 		errx(6, "read ticks: read %lu, got %zu: %s",
326 		    kvp->gpm.kcountsize, i,
327 		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
328 	if ((fwrite(tickbuf, kvp->gpm.kcountsize, 1, fp)) != 1)
329 		err(7, "writing tocks to gmon.out");
330 	free(tickbuf);
331 
332 	/*
333 	 * Write out the arc info.
334 	 */
335 	if ((froms = (u_short *)malloc(kvp->gpm.fromssize)) == NULL)
336 		errx(8, "cannot allocate froms space");
337 	if (kflag) {
338 		i = kvm_read(kvp->kd, (u_long)kvp->gpm.froms, (void *)froms,
339 		    kvp->gpm.fromssize);
340 	} else {
341 		mib[2] = GPROF_FROMS;
342 		i = kvp->gpm.fromssize;
343 		if (sysctl(mib, 3, froms, &i, NULL, 0) < 0)
344 			i = 0;
345 	}
346 	if (i != kvp->gpm.fromssize)
347 		errx(9, "read froms: read %lu, got %zu: %s",
348 		    kvp->gpm.fromssize, i,
349 		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
350 	if ((tos = (struct tostruct *)malloc(kvp->gpm.tossize)) == NULL)
351 		errx(10, "cannot allocate tos space");
352 	if (kflag) {
353 		i = kvm_read(kvp->kd, (u_long)kvp->gpm.tos, (void *)tos,
354 		    kvp->gpm.tossize);
355 	} else {
356 		mib[2] = GPROF_TOS;
357 		i = kvp->gpm.tossize;
358 		if (sysctl(mib, 3, tos, &i, NULL, 0) < 0)
359 			i = 0;
360 	}
361 	if (i != kvp->gpm.tossize)
362 		errx(11, "read tos: read %lu, got %zu: %s",
363 		    kvp->gpm.tossize, i,
364 		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
365 	if (debug)
366 		warnx("lowpc 0x%lx, textsize 0x%lx",
367 		    kvp->gpm.lowpc, kvp->gpm.textsize);
368 	endfrom = kvp->gpm.fromssize / sizeof(*froms);
369 	for (fromindex = 0; fromindex < endfrom; ++fromindex) {
370 		if (froms[fromindex] == 0)
371 			continue;
372 		frompc = (u_long)kvp->gpm.lowpc +
373 		    (fromindex * kvp->gpm.hashfraction * sizeof(*froms));
374 		for (toindex = froms[fromindex]; toindex != 0;
375 		   toindex = tos[toindex].link) {
376 			if (debug)
377 			  warnx("[mcleanup] frompc 0x%lx selfpc 0x%lx count %ld",
378 			    frompc, tos[toindex].selfpc, tos[toindex].count);
379 			rawarc.raw_frompc = frompc;
380 			rawarc.raw_selfpc = (u_long)tos[toindex].selfpc;
381 			rawarc.raw_count = tos[toindex].count;
382 			fwrite((char *)&rawarc, sizeof(rawarc), 1, fp);
383 		}
384 	}
385 	fclose(fp);
386 }
387 
388 /*
389  * Get the profiling rate.
390  */
391 int
392 getprofhz(struct kvmvars *kvp)
393 {
394 	int mib[2], profrate;
395 	size_t size;
396 	struct clockinfo clockrate;
397 
398 	if (kflag) {
399 		profrate = 1;
400 		if (kvm_read(kvp->kd, nl[N_PROFHZ].n_value, &profrate,
401 		    sizeof profrate) != sizeof profrate)
402 			warnx("get clockrate: %s", kvm_geterr(kvp->kd));
403 		return (profrate);
404 	}
405 	mib[0] = CTL_KERN;
406 	mib[1] = KERN_CLOCKRATE;
407 	clockrate.profhz = 1;
408 	size = sizeof clockrate;
409 	if (sysctl(mib, 2, &clockrate, &size, NULL, 0) < 0)
410 		warn("get clockrate");
411 	return (clockrate.profhz);
412 }
413 
414 /*
415  * Reset the kernel profiling date structures.
416  */
417 void
418 reset(struct kvmvars *kvp)
419 {
420 	char *zbuf;
421 	u_long biggest;
422 	int mib[3];
423 
424 	setprof(kvp, GMON_PROF_OFF);
425 
426 	biggest = kvp->gpm.kcountsize;
427 	if (kvp->gpm.fromssize > biggest)
428 		biggest = kvp->gpm.fromssize;
429 	if (kvp->gpm.tossize > biggest)
430 		biggest = kvp->gpm.tossize;
431 	if ((zbuf = (char *)malloc(biggest)) == NULL)
432 		errx(12, "cannot allocate zbuf space");
433 	bzero(zbuf, biggest);
434 	if (kflag) {
435 		if (kvm_write(kvp->kd, (u_long)kvp->gpm.kcount, zbuf,
436 		    kvp->gpm.kcountsize) != kvp->gpm.kcountsize)
437 			errx(13, "tickbuf zero: %s", kvm_geterr(kvp->kd));
438 		if (kvm_write(kvp->kd, (u_long)kvp->gpm.froms, zbuf,
439 		    kvp->gpm.fromssize) != kvp->gpm.fromssize)
440 			errx(14, "froms zero: %s", kvm_geterr(kvp->kd));
441 		if (kvm_write(kvp->kd, (u_long)kvp->gpm.tos, zbuf,
442 		    kvp->gpm.tossize) != kvp->gpm.tossize)
443 			errx(15, "tos zero: %s", kvm_geterr(kvp->kd));
444 		return;
445 	}
446 	(void)seteuid(0);
447 	mib[0] = CTL_KERN;
448 	mib[1] = KERN_PROF;
449 	mib[2] = GPROF_COUNT;
450 	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.kcountsize) < 0)
451 		err(13, "tickbuf zero");
452 	mib[2] = GPROF_FROMS;
453 	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.fromssize) < 0)
454 		err(14, "froms zero");
455 	mib[2] = GPROF_TOS;
456 	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.tossize) < 0)
457 		err(15, "tos zero");
458 	(void)seteuid(getuid());
459 	free(zbuf);
460 }
461