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