1/*
2 * Copyright (c) 1983, 1992, 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 * 4. 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
30#ifndef lint
31static const char copyright[] =
32"@(#) Copyright (c) 1983, 1992, 1993\n\
33	The Regents of the University of California.  All rights reserved.\n";
34#endif /* not lint */
35
36#ifndef lint
37#if 0
38static char sccsid[] = "@(#)kgmon.c	8.1 (Berkeley) 6/6/93";
39#endif
40static const char rcsid[] =
41  "$FreeBSD$";
42#endif /* not lint */
43
44#include <sys/param.h>
45#include <sys/file.h>
46#include <sys/time.h>
47#include <sys/sysctl.h>
48#include <sys/gmon.h>
49#include <ctype.h>
50#include <err.h>
51#include <errno.h>
52#include <kvm.h>
53#include <limits.h>
54#include <nlist.h>
55#include <paths.h>
56#include <stddef.h>
57#include <stdio.h>
58#include <stdlib.h>
59#include <string.h>
60#include <unistd.h>
61
62struct nlist nl[] = {
63#define	N_GMONPARAM	0
64	{ "__gmonparam" },
65#define	N_PROFHZ	1
66	{ "_profhz" },
67	{ NULL },
68};
69
70struct kvmvars {
71	kvm_t	*kd;
72	struct gmonparam gpm;
73};
74
75int	Bflag, bflag, hflag, kflag, rflag, pflag;
76int	debug = 0;
77int	getprof(struct kvmvars *);
78int	getprofhz(struct kvmvars *);
79void	kern_readonly(int);
80int	openfiles(char *, char *, struct kvmvars *);
81void	setprof(struct kvmvars *kvp, int state);
82void	dumpstate(struct kvmvars *kvp);
83void	reset(struct kvmvars *kvp);
84static void usage(void);
85
86int
87main(int argc, char **argv)
88{
89	int ch, mode, disp, accessmode;
90	struct kvmvars kvmvars;
91	char *system, *kmemf;
92
93	if (seteuid(getuid()) != 0) {
94		err(1, "seteuid failed\n");
95	}
96	kmemf = NULL;
97	system = NULL;
98	while ((ch = getopt(argc, argv, "M:N:Bbhpr")) != -1) {
99		switch((char)ch) {
100
101		case 'M':
102			kmemf = optarg;
103			kflag = 1;
104			break;
105
106		case 'N':
107			system = optarg;
108			break;
109
110		case 'B':
111			Bflag = 1;
112			break;
113
114		case 'b':
115			bflag = 1;
116			break;
117
118		case 'h':
119			hflag = 1;
120			break;
121
122		case 'p':
123			pflag = 1;
124			break;
125
126		case 'r':
127			rflag = 1;
128			break;
129
130		default:
131			usage();
132		}
133	}
134	argc -= optind;
135	argv += optind;
136
137#define BACKWARD_COMPATIBILITY
138#ifdef	BACKWARD_COMPATIBILITY
139	if (*argv) {
140		system = *argv;
141		if (*++argv) {
142			kmemf = *argv;
143			++kflag;
144		}
145	}
146#endif
147	if (system == NULL)
148		system = (char *)getbootfile();
149	accessmode = openfiles(system, kmemf, &kvmvars);
150	mode = getprof(&kvmvars);
151	if (hflag)
152		disp = GMON_PROF_OFF;
153	else if (Bflag)
154		disp = GMON_PROF_HIRES;
155	else if (bflag)
156		disp = GMON_PROF_ON;
157	else
158		disp = mode;
159	if (pflag)
160		dumpstate(&kvmvars);
161	if (rflag)
162		reset(&kvmvars);
163	if (accessmode == O_RDWR)
164		setprof(&kvmvars, disp);
165	(void)fprintf(stdout, "kgmon: kernel profiling is %s.\n",
166		      disp == GMON_PROF_OFF ? "off" :
167		      disp == GMON_PROF_HIRES ? "running (high resolution)" :
168		      disp == GMON_PROF_ON ? "running" :
169		      disp == GMON_PROF_BUSY ? "busy" :
170		      disp == GMON_PROF_ERROR ? "off (error)" :
171		      "in an unknown state");
172	return (0);
173}
174
175static void
176usage()
177{
178	fprintf(stderr, "usage: kgmon [-Bbhrp] [-M core] [-N system]\n");
179	exit(1);
180}
181
182/*
183 * Check that profiling is enabled and open any necessary files.
184 */
185int
186openfiles(system, kmemf, kvp)
187	char *system;
188	char *kmemf;
189	struct kvmvars *kvp;
190{
191	size_t size;
192	int mib[3], state, openmode;
193	char errbuf[_POSIX2_LINE_MAX];
194
195	if (!kflag) {
196		mib[0] = CTL_KERN;
197		mib[1] = KERN_PROF;
198		mib[2] = GPROF_STATE;
199		size = sizeof state;
200		if (sysctl(mib, 3, &state, &size, NULL, 0) < 0)
201			errx(20, "profiling not defined in kernel");
202		if (!(Bflag || bflag || hflag || rflag ||
203		    (pflag &&
204		     (state == GMON_PROF_HIRES || state == GMON_PROF_ON))))
205			return (O_RDONLY);
206		(void)seteuid(0);
207		if (sysctl(mib, 3, NULL, NULL, &state, size) >= 0)
208			return (O_RDWR);
209		(void)seteuid(getuid());
210		kern_readonly(state);
211		return (O_RDONLY);
212	}
213	openmode = (Bflag || bflag || hflag || pflag || rflag)
214		   ? O_RDWR : O_RDONLY;
215	kvp->kd = kvm_openfiles(system, kmemf, NULL, openmode, errbuf);
216	if (kvp->kd == NULL) {
217		if (openmode == O_RDWR) {
218			openmode = O_RDONLY;
219			kvp->kd = kvm_openfiles(system, kmemf, NULL, O_RDONLY,
220			    errbuf);
221		}
222		if (kvp->kd == NULL)
223			errx(2, "kvm_openfiles: %s", errbuf);
224		kern_readonly(GMON_PROF_ON);
225	}
226	if (kvm_nlist(kvp->kd, nl) < 0)
227		errx(3, "%s: no namelist", system);
228	if (!nl[N_GMONPARAM].n_value)
229		errx(20, "profiling not defined in kernel");
230	return (openmode);
231}
232
233/*
234 * Suppress options that require a writable kernel.
235 */
236void
237kern_readonly(mode)
238	int mode;
239{
240
241	(void)fprintf(stderr, "kgmon: kernel read-only: ");
242	if (pflag && (mode == GMON_PROF_HIRES || mode == GMON_PROF_ON))
243		(void)fprintf(stderr, "data may be inconsistent\n");
244	if (rflag)
245		(void)fprintf(stderr, "-r supressed\n");
246	if (Bflag)
247		(void)fprintf(stderr, "-B supressed\n");
248	if (bflag)
249		(void)fprintf(stderr, "-b supressed\n");
250	if (hflag)
251		(void)fprintf(stderr, "-h supressed\n");
252	rflag = Bflag = bflag = hflag = 0;
253}
254
255/*
256 * Get the state of kernel profiling.
257 */
258int
259getprof(kvp)
260	struct kvmvars *kvp;
261{
262	size_t size;
263	int mib[3];
264
265	if (kflag) {
266		size = kvm_read(kvp->kd, nl[N_GMONPARAM].n_value, &kvp->gpm,
267		    sizeof kvp->gpm);
268	} else {
269		mib[0] = CTL_KERN;
270		mib[1] = KERN_PROF;
271		mib[2] = GPROF_GMONPARAM;
272		size = sizeof kvp->gpm;
273		if (sysctl(mib, 3, &kvp->gpm, &size, NULL, 0) < 0)
274			size = 0;
275	}
276
277	/*
278	 * Accept certain undersized "structs" from old kernels.  We need
279	 * everything up to hashfraction, and want profrate and
280	 * histcounter_type.  Assume that the kernel doesn't put garbage
281	 * in any padding that is returned instead of profrate and
282	 * histcounter_type.  This is a bad assumption for dead kernels,
283	 * since kvm_read() will normally return garbage for bytes beyond
284	 * the end of the actual kernel struct, if any.
285	 */
286	if (size < offsetof(struct gmonparam, hashfraction) +
287	    sizeof(kvp->gpm.hashfraction) || size > sizeof(kvp->gpm))
288		errx(4, "cannot get gmonparam: %s",
289		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
290	bzero((char *)&kvp->gpm + size, sizeof(kvp->gpm) - size);
291	if (kvp->gpm.profrate == 0)
292		kvp->gpm.profrate = getprofhz(kvp);
293#ifdef __i386__
294	if (kvp->gpm.histcounter_type == 0) {
295		/*
296		 * This fixup only works for not-so-old i386 kernels.  The
297		 * magic 16 is the kernel FUNCTION_ALIGNMENT.  64-bit
298		 * counters are signed; smaller counters are unsigned.
299		 */
300		kvp->gpm.histcounter_type = 16 /
301		    (kvp->gpm.textsize / kvp->gpm.kcountsize) * CHAR_BIT;
302		if (kvp->gpm.histcounter_type == 64)
303			kvp->gpm.histcounter_type = -64;
304	}
305#endif
306
307	return (kvp->gpm.state);
308}
309
310/*
311 * Enable or disable kernel profiling according to the state variable.
312 */
313void
314setprof(kvp, state)
315	struct kvmvars *kvp;
316	int state;
317{
318	struct gmonparam *p = (struct gmonparam *)nl[N_GMONPARAM].n_value;
319	size_t sz;
320	int mib[3], oldstate;
321
322	sz = sizeof(state);
323	if (!kflag) {
324		mib[0] = CTL_KERN;
325		mib[1] = KERN_PROF;
326		mib[2] = GPROF_STATE;
327		if (sysctl(mib, 3, &oldstate, &sz, NULL, 0) < 0)
328			goto bad;
329		if (oldstate == state)
330			return;
331		(void)seteuid(0);
332		if (sysctl(mib, 3, NULL, NULL, &state, sz) >= 0) {
333			(void)seteuid(getuid());
334			return;
335		}
336		(void)seteuid(getuid());
337	} else if (kvm_write(kvp->kd, (u_long)&p->state, (void *)&state, sz)
338	    == sz)
339		return;
340bad:
341	warnx("warning: cannot turn profiling %s",
342	    state == GMON_PROF_OFF ? "off" : "on");
343}
344
345/*
346 * Build the gmon.out file.
347 */
348void
349dumpstate(kvp)
350	struct kvmvars *kvp;
351{
352	register FILE *fp;
353	struct rawarc rawarc;
354	struct tostruct *tos;
355	u_long frompc;
356	u_short *froms, *tickbuf;
357	size_t i;
358	int mib[3];
359	struct gmonhdr h;
360	int fromindex, endfrom, toindex;
361
362	setprof(kvp, GMON_PROF_OFF);
363	fp = fopen("gmon.out", "w");
364	if (fp == 0) {
365		warn("gmon.out");
366		return;
367	}
368
369	/*
370	 * Build the gmon header and write it to a file.
371	 */
372	bzero(&h, sizeof(h));
373	h.lpc = kvp->gpm.lowpc;
374	h.hpc = kvp->gpm.highpc;
375	h.ncnt = kvp->gpm.kcountsize + sizeof(h);
376	h.version = GMONVERSION;
377	h.profrate = kvp->gpm.profrate;
378	h.histcounter_type = kvp->gpm.histcounter_type;
379	fwrite((char *)&h, sizeof(h), 1, fp);
380
381	/*
382	 * Write out the tick buffer.
383	 */
384	mib[0] = CTL_KERN;
385	mib[1] = KERN_PROF;
386	if ((tickbuf = (u_short *)malloc(kvp->gpm.kcountsize)) == NULL)
387		errx(5, "cannot allocate kcount space");
388	if (kflag) {
389		i = kvm_read(kvp->kd, (u_long)kvp->gpm.kcount, (void *)tickbuf,
390		    kvp->gpm.kcountsize);
391	} else {
392		mib[2] = GPROF_COUNT;
393		i = kvp->gpm.kcountsize;
394		if (sysctl(mib, 3, tickbuf, &i, NULL, 0) < 0)
395			i = 0;
396	}
397	if (i != kvp->gpm.kcountsize)
398		errx(6, "read ticks: read %lu, got %ld: %s",
399		    kvp->gpm.kcountsize, (long)i,
400		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
401	if ((fwrite(tickbuf, kvp->gpm.kcountsize, 1, fp)) != 1)
402		err(7, "writing tocks to gmon.out");
403	free(tickbuf);
404
405	/*
406	 * Write out the arc info.
407	 */
408	if ((froms = (u_short *)malloc(kvp->gpm.fromssize)) == NULL)
409		errx(8, "cannot allocate froms space");
410	if (kflag) {
411		i = kvm_read(kvp->kd, (u_long)kvp->gpm.froms, (void *)froms,
412		    kvp->gpm.fromssize);
413	} else {
414		mib[2] = GPROF_FROMS;
415		i = kvp->gpm.fromssize;
416		if (sysctl(mib, 3, froms, &i, NULL, 0) < 0)
417			i = 0;
418	}
419	if (i != kvp->gpm.fromssize)
420		errx(9, "read froms: read %lu, got %ld: %s",
421		    kvp->gpm.fromssize, (long)i,
422		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
423	if ((tos = (struct tostruct *)malloc(kvp->gpm.tossize)) == NULL)
424		errx(10, "cannot allocate tos space");
425	if (kflag) {
426		i = kvm_read(kvp->kd, (u_long)kvp->gpm.tos, (void *)tos,
427		    kvp->gpm.tossize);
428	} else {
429		mib[2] = GPROF_TOS;
430		i = kvp->gpm.tossize;
431		if (sysctl(mib, 3, tos, &i, NULL, 0) < 0)
432			i = 0;
433	}
434	if (i != kvp->gpm.tossize)
435		errx(11, "read tos: read %lu, got %ld: %s",
436		    kvp->gpm.tossize, (long)i,
437		    kflag ? kvm_geterr(kvp->kd) : strerror(errno));
438	if (debug)
439		warnx("lowpc 0x%lx, textsize 0x%lx",
440		    (unsigned long)kvp->gpm.lowpc, kvp->gpm.textsize);
441	endfrom = kvp->gpm.fromssize / sizeof(*froms);
442	for (fromindex = 0; fromindex < endfrom; ++fromindex) {
443		if (froms[fromindex] == 0)
444			continue;
445		frompc = (u_long)kvp->gpm.lowpc +
446		    (fromindex * kvp->gpm.hashfraction * sizeof(*froms));
447		for (toindex = froms[fromindex]; toindex != 0;
448		     toindex = tos[toindex].link) {
449			if (debug)
450				warnx("[mcleanup] frompc 0x%lx selfpc 0x%lx "
451				    "count %ld", frompc, tos[toindex].selfpc,
452				    tos[toindex].count);
453			rawarc.raw_frompc = frompc;
454			rawarc.raw_selfpc = (u_long)tos[toindex].selfpc;
455			rawarc.raw_count = tos[toindex].count;
456			fwrite((char *)&rawarc, sizeof(rawarc), 1, fp);
457		}
458	}
459	fclose(fp);
460}
461
462/*
463 * Get the profiling rate.
464 */
465int
466getprofhz(kvp)
467	struct kvmvars *kvp;
468{
469	size_t size;
470	int mib[2], profrate;
471	struct clockinfo clockrate;
472
473	if (kflag) {
474		profrate = 1;
475		if (kvm_read(kvp->kd, nl[N_PROFHZ].n_value, &profrate,
476		    sizeof profrate) != sizeof profrate)
477			warnx("get clockrate: %s", kvm_geterr(kvp->kd));
478		return (profrate);
479	}
480	mib[0] = CTL_KERN;
481	mib[1] = KERN_CLOCKRATE;
482	clockrate.profhz = 1;
483	size = sizeof clockrate;
484	if (sysctl(mib, 2, &clockrate, &size, NULL, 0) < 0)
485		warn("get clockrate");
486	return (clockrate.profhz);
487}
488
489/*
490 * Reset the kernel profiling date structures.
491 */
492void
493reset(kvp)
494	struct kvmvars *kvp;
495{
496	char *zbuf;
497	u_long biggest;
498	int mib[3];
499
500	setprof(kvp, GMON_PROF_OFF);
501
502	biggest = kvp->gpm.kcountsize;
503	if (kvp->gpm.fromssize > biggest)
504		biggest = kvp->gpm.fromssize;
505	if (kvp->gpm.tossize > biggest)
506		biggest = kvp->gpm.tossize;
507	if ((zbuf = (char *)malloc(biggest)) == NULL)
508		errx(12, "cannot allocate zbuf space");
509	bzero(zbuf, biggest);
510	if (kflag) {
511		if (kvm_write(kvp->kd, (u_long)kvp->gpm.kcount, zbuf,
512		    kvp->gpm.kcountsize) != kvp->gpm.kcountsize)
513			errx(13, "tickbuf zero: %s", kvm_geterr(kvp->kd));
514		if (kvm_write(kvp->kd, (u_long)kvp->gpm.froms, zbuf,
515		    kvp->gpm.fromssize) != kvp->gpm.fromssize)
516			errx(14, "froms zero: %s", kvm_geterr(kvp->kd));
517		if (kvm_write(kvp->kd, (u_long)kvp->gpm.tos, zbuf,
518		    kvp->gpm.tossize) != kvp->gpm.tossize)
519			errx(15, "tos zero: %s", kvm_geterr(kvp->kd));
520		return;
521	}
522	(void)seteuid(0);
523	mib[0] = CTL_KERN;
524	mib[1] = KERN_PROF;
525	mib[2] = GPROF_COUNT;
526	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.kcountsize) < 0)
527		err(13, "tickbuf zero");
528	mib[2] = GPROF_FROMS;
529	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.fromssize) < 0)
530		err(14, "froms zero");
531	mib[2] = GPROF_TOS;
532	if (sysctl(mib, 3, NULL, NULL, zbuf, kvp->gpm.tossize) < 0)
533		err(15, "tos zero");
534	(void)seteuid(getuid());
535	free(zbuf);
536}
537