xref: /netbsd/lib/libc/gmon/gmon.c (revision bf9ec67e)
1 /*	$NetBSD: gmon.c,v 1.18 2002/04/26 16:39:52 christos 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. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #if !defined(lint) && defined(LIBC_SCCS)
38 #if 0
39 static char sccsid[] = "@(#)gmon.c	8.1 (Berkeley) 6/4/93";
40 #else
41 __RCSID("$NetBSD: gmon.c,v 1.18 2002/04/26 16:39:52 christos Exp $");
42 #endif
43 #endif
44 
45 #include "namespace.h"
46 #include <sys/param.h>
47 #include <sys/time.h>
48 #include <sys/gmon.h>
49 #include <sys/sysctl.h>
50 
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <fcntl.h>
54 #include <limits.h>
55 #include <unistd.h>
56 #include <err.h>
57 #include "extern.h"
58 
59 struct gmonparam _gmonparam = { GMON_PROF_OFF };
60 
61 static u_int	s_scale;
62 /* see profil(2) where this is describe (incorrectly) */
63 #define		SCALE_1_TO_1	0x10000L
64 
65 #define ERR(s) write(STDERR_FILENO, s, sizeof(s))
66 
67 void	moncontrol __P((int));
68 void	monstartup __P((u_long, u_long));
69 void	_mcleanup __P((void));
70 static int hertz __P((void));
71 
72 
73 void
74 monstartup(lowpc, highpc)
75 	u_long lowpc;
76 	u_long highpc;
77 {
78 	long o;
79 	char *cp;
80 	struct gmonparam *p = &_gmonparam;
81 
82 	/*
83 	 * round lowpc and highpc to multiples of the density we're using
84 	 * so the rest of the scaling (here and in gprof) stays in ints.
85 	 */
86 	p->lowpc = ROUNDDOWN(lowpc, HISTFRACTION * sizeof(HISTCOUNTER));
87 	p->highpc = ROUNDUP(highpc, HISTFRACTION * sizeof(HISTCOUNTER));
88 	p->textsize = p->highpc - p->lowpc;
89 	p->kcountsize = p->textsize / HISTFRACTION;
90 	p->hashfraction = HASHFRACTION;
91 	p->fromssize = p->textsize / p->hashfraction;
92 	p->tolimit = p->textsize * ARCDENSITY / 100;
93 	if (p->tolimit < MINARCS)
94 		p->tolimit = MINARCS;
95 	else if (p->tolimit > MAXARCS)
96 		p->tolimit = MAXARCS;
97 	p->tossize = p->tolimit * sizeof(struct tostruct);
98 
99 	cp = sbrk((intptr_t)(p->kcountsize + p->fromssize + p->tossize));
100 	if (cp == (char *)-1) {
101 		ERR("monstartup: out of memory\n");
102 		return;
103 	}
104 #ifdef notdef
105 	memset(cp, 0, p->kcountsize + p->fromssize + p->tossize);
106 #endif
107 	p->tos = (struct tostruct *)(void *)cp;
108 	cp += (size_t)p->tossize;
109 	p->kcount = (u_short *)(void *)cp;
110 	cp += (size_t)p->kcountsize;
111 	p->froms = (u_short *)(void *)cp;
112 
113 	__minbrk = sbrk((intptr_t)0);
114 	p->tos[0].link = 0;
115 
116 	o = p->highpc - p->lowpc;
117 	if (p->kcountsize < o) {
118 #ifndef notdef
119 		s_scale = ((float)p->kcountsize / o ) * SCALE_1_TO_1;
120 #else /* avoid floating point */
121 		int quot = o / p->kcountsize;
122 
123 		if (quot >= 0x10000)
124 			s_scale = 1;
125 		else if (quot >= 0x100)
126 			s_scale = 0x10000 / quot;
127 		else if (o >= 0x800000)
128 			s_scale = 0x1000000 / (o / (p->kcountsize >> 8));
129 		else
130 			s_scale = 0x1000000 / ((o << 8) / p->kcountsize);
131 #endif
132 	} else
133 		s_scale = SCALE_1_TO_1;
134 
135 	moncontrol(1);
136 }
137 
138 void
139 _mcleanup()
140 {
141 	int fd;
142 	int fromindex;
143 	int endfrom;
144 	u_long frompc;
145 	int toindex;
146 	struct rawarc rawarc;
147 	struct gmonparam *p = &_gmonparam;
148 	struct gmonhdr gmonhdr, *hdr;
149 	struct clockinfo clockinfo;
150 	int mib[2];
151 	size_t size;
152 	char *profdir;
153 	char *proffile;
154 	char  buf[PATH_MAX];
155 	int len = sizeof(buf) - 1;
156 #ifdef DEBUG
157 	int log, len;
158 	char buf2[200];
159 #endif
160 
161 	/*
162 	 * We disallow writing to the profiling file, if we are a
163 	 * set{u,g}id program and our effective {u,g}id does not match
164 	 * our real one.
165 	 */
166 	if (issetugid() && (geteuid() != getuid() || getegid() != getgid())) {
167 		warnx("mcount: Profiling of set{u,g}id binaries is not"
168 		    " allowed");
169 		return;
170 	}
171 
172 	if (p->state == GMON_PROF_ERROR)
173 		ERR("_mcleanup: tos overflow\n");
174 
175 	size = sizeof(clockinfo);
176 	mib[0] = CTL_KERN;
177 	mib[1] = KERN_CLOCKRATE;
178 	if (sysctl(mib, 2, &clockinfo, &size, NULL, 0) < 0) {
179 		/*
180 		 * Best guess
181 		 */
182 		clockinfo.profhz = hertz();
183 	} else if (clockinfo.profhz == 0) {
184 		if (clockinfo.hz != 0)
185 			clockinfo.profhz = clockinfo.hz;
186 		else
187 			clockinfo.profhz = hertz();
188 	}
189 
190 	moncontrol(0);
191 
192 	if ((profdir = getenv("PROFDIR")) != NULL) {
193 		const char *s;
194 		char *t;
195 		pid_t pid;
196 		long divisor;
197 
198 		/* If PROFDIR contains a null value, no profiling
199 		   output is produced */
200 		if (*profdir == '\0') {
201 			return;
202 		}
203 
204 		t = buf;
205 		s = profdir;
206 		while ((*t = *s) != '\0') {
207 			if (len-- == 0) {
208 				warnx("_mcleanup: internal buffer overflow, PROFDIR too long");
209 				return;
210 			}
211 			t++;
212 			s++;
213 		}
214 		*t++ = '/';
215 
216 		/*
217 		 * Copy and convert pid from a pid_t to a string.  For
218 		 * best performance, divisor should be initialized to
219 		 * the largest power of 10 less than PID_MAX.
220 		 */
221 		pid = getpid();
222 		divisor=10000;
223 		while (divisor > pid) divisor /= 10;	/* skip leading zeros */
224 		do {
225 			*t++ = (char)((pid/divisor) + '0');
226 			pid %= (pid_t)divisor;
227 		} while (divisor /= 10);
228 		*t++ = '.';
229 
230 		s = getprogname();
231 		while ((*t++ = *s++) != '\0')
232 			;
233 
234 		proffile = buf;
235 	} else {
236 		proffile = "gmon.out";
237 	}
238 
239 	fd = open(proffile , O_CREAT|O_TRUNC|O_WRONLY, 0666);
240 	if (fd < 0) {
241 		warn("mcount: Cannot open `%s'", proffile);
242 		return;
243 	}
244 #ifdef DEBUG
245 	log = open("gmon.log", O_CREAT|O_TRUNC|O_WRONLY, 0664);
246 	if (log < 0) {
247 		warn("mcount: Cannot open `gmon.log'");
248 		return;
249 	}
250 	len = snprintf(buf2, sizeof buf2, "[mcleanup1] kcount 0x%x ssiz %d\n",
251 	    p->kcount, p->kcountsize);
252 	write(log, buf2, len);
253 #endif
254 	hdr = (struct gmonhdr *)&gmonhdr;
255 	hdr->lpc = p->lowpc;
256 	hdr->hpc = p->highpc;
257 	hdr->ncnt = (int)(p->kcountsize + sizeof(gmonhdr));
258 	hdr->version = GMONVERSION;
259 	hdr->profrate = clockinfo.profhz;
260 	(void)write(fd, hdr, sizeof *hdr);
261 	(void)write(fd, p->kcount, (size_t)p->kcountsize);
262 	endfrom = (int)(p->fromssize / sizeof(*p->froms));
263 	for (fromindex = 0; fromindex < endfrom; fromindex++) {
264 		if (p->froms[fromindex] == 0)
265 			continue;
266 
267 		frompc = p->lowpc;
268 		frompc += fromindex * p->hashfraction * sizeof(*p->froms);
269 		for (toindex = p->froms[fromindex]; toindex != 0;
270 		     toindex = p->tos[toindex].link) {
271 #ifdef DEBUG
272 			len = snprintf(buf2, sizeof buf2,
273 			"[mcleanup2] frompc 0x%x selfpc 0x%x count %d\n" ,
274 				frompc, p->tos[toindex].selfpc,
275 				p->tos[toindex].count);
276 			write(log, buf2, len);
277 #endif
278 			rawarc.raw_frompc = frompc;
279 			rawarc.raw_selfpc = p->tos[toindex].selfpc;
280 			rawarc.raw_count = p->tos[toindex].count;
281 			write(fd, &rawarc, sizeof rawarc);
282 		}
283 	}
284 	close(fd);
285 }
286 
287 /*
288  * Control profiling
289  *	profiling is what mcount checks to see if
290  *	all the data structures are ready.
291  */
292 void
293 moncontrol(mode)
294 	int mode;
295 {
296 	struct gmonparam *p = &_gmonparam;
297 
298 	if (mode) {
299 		/* start */
300 		profil((char *)(void *)p->kcount, (size_t)p->kcountsize,
301 		    p->lowpc, s_scale);
302 		p->state = GMON_PROF_ON;
303 	} else {
304 		/* stop */
305 		profil(NULL, 0, (u_long)0, 0);
306 		p->state = GMON_PROF_OFF;
307 	}
308 }
309 
310 /*
311  * discover the tick frequency of the machine
312  * if something goes wrong, we return 0, an impossible hertz.
313  */
314 static int
315 hertz()
316 {
317 	struct itimerval tim;
318 
319 	tim.it_interval.tv_sec = 0;
320 	tim.it_interval.tv_usec = 1;
321 	tim.it_value.tv_sec = 0;
322 	tim.it_value.tv_usec = 0;
323 	setitimer(ITIMER_REAL, &tim, 0);
324 	setitimer(ITIMER_REAL, 0, &tim);
325 	if (tim.it_interval.tv_usec < 2)
326 		return(0);
327 	return (int)(1000000 / tim.it_interval.tv_usec);
328 }
329