xref: /freebsd/usr.bin/gprof/gprof.c (revision 031beb4e239bfce798af17f5fe8dba8bcaf13d99)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 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 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1983, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37 
38 #if 0
39 #ifndef lint
40 static char sccsid[] = "@(#)gprof.c	8.1 (Berkeley) 6/6/93";
41 #endif /* not lint */
42 #endif
43 
44 #include <sys/cdefs.h>
45 #include <err.h>
46 #include <limits.h>
47 #include <stdint.h>
48 #include <string.h>
49 
50 #define	EXTERN
51 #include "gprof.h"
52 
53 static int valcmp(const void *, const void *);
54 
55 static struct gmonhdr	gmonhdr;
56 static int lflag;
57 static int Lflag;
58 
59 int
60 main(int argc, char **argv)
61 {
62     char	**sp;
63     nltype	**timesortnlp;
64     char	**defaultEs;
65 
66     --argc;
67     argv++;
68     debug = 0;
69     bflag = TRUE;
70     while ( *argv != 0 && **argv == '-' ) {
71 	(*argv)++;
72 	switch ( **argv ) {
73 	case 'a':
74 	    aflag = TRUE;
75 	    break;
76 	case 'b':
77 	    bflag = FALSE;
78 	    break;
79 	case 'C':
80 	    Cflag = TRUE;
81 	    cyclethreshold = atoi( *++argv );
82 	    break;
83 	case 'd':
84 	    dflag = TRUE;
85 	    setlinebuf(stdout);
86 	    debug |= atoi( *++argv );
87 	    debug |= ANYDEBUG;
88 #	    ifdef DEBUG
89 		printf("[main] debug = %d\n", debug);
90 #	    else /* not DEBUG */
91 		printf("gprof: -d ignored\n");
92 #	    endif /* DEBUG */
93 	    break;
94 	case 'E':
95 	    ++argv;
96 	    addlist( Elist , *argv );
97 	    Eflag = TRUE;
98 	    addlist( elist , *argv );
99 	    eflag = TRUE;
100 	    break;
101 	case 'e':
102 	    addlist( elist , *++argv );
103 	    eflag = TRUE;
104 	    break;
105 	case 'F':
106 	    ++argv;
107 	    addlist( Flist , *argv );
108 	    Fflag = TRUE;
109 	    addlist( flist , *argv );
110 	    fflag = TRUE;
111 	    break;
112 	case 'f':
113 	    addlist( flist , *++argv );
114 	    fflag = TRUE;
115 	    break;
116 	case 'k':
117 	    addlist( kfromlist , *++argv );
118 	    addlist( ktolist , *++argv );
119 	    kflag = TRUE;
120 	    break;
121 	case 'K':
122 	    Kflag = TRUE;
123 	    break;
124 	case 'l':
125 	    lflag = 1;
126 	    Lflag = 0;
127 	    break;
128 	case 'L':
129 	    Lflag = 1;
130 	    lflag = 0;
131 	    break;
132 	case 's':
133 	    sflag = TRUE;
134 	    break;
135 	case 'u':
136 	    uflag = TRUE;
137 	    break;
138 	case 'z':
139 	    zflag = TRUE;
140 	    break;
141 	}
142 	argv++;
143     }
144     if ( *argv != 0 ) {
145 	a_outname  = *argv;
146 	argv++;
147     } else {
148 	a_outname  = A_OUTNAME;
149     }
150     if ( *argv != 0 ) {
151 	gmonname = *argv;
152 	argv++;
153     } else {
154 	gmonname = (char *) malloc(strlen(a_outname)+6);
155 	strcpy(gmonname, a_outname);
156 	strcat(gmonname, ".gmon");
157     }
158 	/*
159 	 *	get information from the executable file.
160 	 */
161     if ((Kflag && kernel_getnfile(a_outname, &defaultEs) == -1) ||
162       (!Kflag && elf_getnfile(a_outname, &defaultEs) == -1))
163 	errx(1, "%s: bad format", a_outname);
164 	/*
165 	 *	sort symbol table.
166 	 */
167     qsort(nl, nname, sizeof(nltype), valcmp);
168 	/*
169 	 *	turn off default functions
170 	 */
171     for ( sp = defaultEs ; *sp ; sp++ ) {
172 	Eflag = TRUE;
173 	addlist( Elist , *sp );
174 	eflag = TRUE;
175 	addlist( elist , *sp );
176     }
177 	/*
178 	 *	get information about mon.out file(s).
179 	 */
180     do	{
181 	getpfile( gmonname );
182 	if ( *argv != 0 ) {
183 	    gmonname = *argv;
184 	}
185     } while ( *argv++ != 0 );
186 	/*
187 	 *	how many ticks per second?
188 	 *	if we can't tell, report time in ticks.
189 	 */
190     if (hz == 0) {
191 	hz = 1;
192 	fprintf(stderr, "time is in ticks, not seconds\n");
193     }
194 	/*
195 	 *	dump out a gmon.sum file if requested
196 	 */
197     if ( sflag ) {
198 	dumpsum( GMONSUM );
199     }
200 	/*
201 	 *	assign samples to procedures
202 	 */
203     asgnsamples();
204 	/*
205 	 *	assemble the dynamic profile
206 	 */
207     timesortnlp = doarcs();
208 	/*
209 	 *	print the dynamic profile
210 	 */
211     if(!lflag) {
212 	    printgprof( timesortnlp );
213     }
214 	/*
215 	 *	print the flat profile
216 	 */
217     if(!Lflag) {
218 	    printprof();
219     }
220 	/*
221 	 *	print the index
222 	 */
223     printindex();
224     exit(0);
225 }
226 
227     /*
228      *	information from a gmon.out file is in two parts:
229      *	an array of sampling hits within pc ranges,
230      *	and the arcs.
231      */
232 void
233 getpfile(char *filename)
234 {
235     FILE		*pfile;
236     struct rawarc	arc;
237 
238     pfile = openpfile(filename);
239     readsamples(pfile);
240 	/*
241 	 *	the rest of the file consists of
242 	 *	a bunch of <from,self,count> tuples.
243 	 */
244     while ( fread( &arc , sizeof arc , 1 , pfile ) == 1 ) {
245 #	ifdef DEBUG
246 	    if ( debug & SAMPLEDEBUG ) {
247 		printf( "[getpfile] frompc 0x%lx selfpc 0x%lx count %ld\n" ,
248 			arc.raw_frompc , arc.raw_selfpc , arc.raw_count );
249 	    }
250 #	endif /* DEBUG */
251 	    /*
252 	     *	add this arc
253 	     */
254 	tally( &arc );
255     }
256     fclose(pfile);
257 }
258 
259 FILE *
260 openpfile(char *filename)
261 {
262     struct gmonhdr	tmp;
263     FILE		*pfile;
264     int			size;
265     int			rate;
266 
267     if((pfile = fopen(filename, "r")) == NULL)
268 	err(1, "%s", filename);
269     fread(&tmp, sizeof(struct gmonhdr), 1, pfile);
270     if ( s_highpc != 0 && ( tmp.lpc != gmonhdr.lpc ||
271 	 tmp.hpc != gmonhdr.hpc || tmp.ncnt != gmonhdr.ncnt ) )
272 	errx(1, "%s: incompatible with first gmon file", filename);
273     gmonhdr = tmp;
274     if ( gmonhdr.version == GMONVERSION ) {
275 	rate = gmonhdr.profrate;
276 	size = sizeof(struct gmonhdr);
277     } else {
278 	fseek(pfile, sizeof(struct ophdr), SEEK_SET);
279 	size = sizeof(struct ophdr);
280 	gmonhdr.profrate = rate = hertz();
281 	gmonhdr.version = GMONVERSION;
282     }
283     if (hz == 0) {
284 	hz = rate;
285     } else if (hz != rate)
286 	errx(0, "%s: profile clock rate (%d) %s (%ld) in first gmon file",
287 	    filename, rate, "incompatible with clock rate", hz);
288     if ( gmonhdr.histcounter_type == 0 ) {
289 	/* Historical case.  The type was u_short (2 bytes in practice). */
290 	histcounter_type = 16;
291 	histcounter_size = 2;
292     } else {
293 	histcounter_type = gmonhdr.histcounter_type;
294 	histcounter_size = abs(histcounter_type) / CHAR_BIT;
295     }
296     s_lowpc = (unsigned long) gmonhdr.lpc;
297     s_highpc = (unsigned long) gmonhdr.hpc;
298     lowpc = (unsigned long)gmonhdr.lpc / HISTORICAL_SCALE_2;
299     highpc = (unsigned long)gmonhdr.hpc / HISTORICAL_SCALE_2;
300     sampbytes = gmonhdr.ncnt - size;
301     nsamples = sampbytes / histcounter_size;
302 #   ifdef DEBUG
303 	if ( debug & SAMPLEDEBUG ) {
304 	    printf( "[openpfile] hdr.lpc 0x%lx hdr.hpc 0x%lx hdr.ncnt %d\n",
305 		gmonhdr.lpc , gmonhdr.hpc , gmonhdr.ncnt );
306 	    printf( "[openpfile]   s_lowpc 0x%lx   s_highpc 0x%lx\n" ,
307 		s_lowpc , s_highpc );
308 	    printf( "[openpfile]     lowpc 0x%lx     highpc 0x%lx\n" ,
309 		lowpc , highpc );
310 	    printf( "[openpfile] sampbytes %d nsamples %d\n" ,
311 		sampbytes , nsamples );
312 	    printf( "[openpfile] sample rate %ld\n" , hz );
313 	}
314 #   endif /* DEBUG */
315     return(pfile);
316 }
317 
318 void
319 tally(struct rawarc *rawp)
320 {
321     nltype		*parentp;
322     nltype		*childp;
323 
324     parentp = nllookup( rawp -> raw_frompc );
325     childp = nllookup( rawp -> raw_selfpc );
326     if ( parentp == 0 || childp == 0 )
327 	return;
328     if ( kflag
329 	 && onlist( kfromlist , parentp -> name )
330 	 && onlist( ktolist , childp -> name ) ) {
331 	return;
332     }
333     childp -> ncall += rawp -> raw_count;
334 #   ifdef DEBUG
335 	if ( debug & TALLYDEBUG ) {
336 	    printf( "[tally] arc from %s to %s traversed %ld times\n" ,
337 		    parentp -> name , childp -> name , rawp -> raw_count );
338 	}
339 #   endif /* DEBUG */
340     addarc( parentp , childp , rawp -> raw_count );
341 }
342 
343 /*
344  * dump out the gmon.sum file
345  */
346 void
347 dumpsum(const char *sumfile)
348 {
349     register nltype *nlp;
350     register arctype *arcp;
351     struct rawarc arc;
352     FILE *sfile;
353 
354     if ( ( sfile = fopen ( sumfile , "w" ) ) == NULL )
355 	err( 1 , "%s" , sumfile );
356     /*
357      * dump the header; use the last header read in
358      */
359     if ( fwrite( &gmonhdr , sizeof gmonhdr , 1 , sfile ) != 1 )
360 	err( 1 , "%s" , sumfile );
361     /*
362      * dump the samples
363      */
364     if (fwrite(samples, histcounter_size, nsamples, sfile) != nsamples)
365 	err( 1 , "%s" , sumfile );
366     /*
367      * dump the normalized raw arc information
368      */
369     for ( nlp = nl ; nlp < npe ; nlp++ ) {
370 	for ( arcp = nlp -> children ; arcp ; arcp = arcp -> arc_childlist ) {
371 	    arc.raw_frompc = arcp -> arc_parentp -> value;
372 	    arc.raw_selfpc = arcp -> arc_childp -> value;
373 	    arc.raw_count = arcp -> arc_count;
374 	    if ( fwrite ( &arc , sizeof arc , 1 , sfile ) != 1 )
375 		err( 1 , "%s" , sumfile );
376 #	    ifdef DEBUG
377 		if ( debug & SAMPLEDEBUG ) {
378 		    printf( "[dumpsum] frompc 0x%lx selfpc 0x%lx count %ld\n" ,
379 			    arc.raw_frompc , arc.raw_selfpc , arc.raw_count );
380 		}
381 #	    endif /* DEBUG */
382 	}
383     }
384     fclose( sfile );
385 }
386 
387 static int
388 valcmp(const void *v1, const void *v2)
389 {
390     const nltype *p1 = (const nltype *)v1;
391     const nltype *p2 = (const nltype *)v2;
392 
393     if ( p1 -> value < p2 -> value ) {
394 	return LESSTHAN;
395     }
396     if ( p1 -> value > p2 -> value ) {
397 	return GREATERTHAN;
398     }
399     return EQUALTO;
400 }
401 
402 void
403 readsamples(FILE *pfile)
404 {
405     int		i;
406     intmax_t	sample;
407 
408     if (samples == 0) {
409 	samples = (double *) calloc(nsamples, sizeof(double));
410 	if (samples == NULL)
411 	    errx(0, "no room for %d sample pc's", nsamples);
412     }
413     for (i = 0; i < nsamples; i++) {
414 	fread(&sample, histcounter_size, 1, pfile);
415 	if (feof(pfile))
416 		break;
417 	switch ( histcounter_type ) {
418 	case -8:
419 	    samples[i] += *(int8_t *)&sample;
420 	    break;
421 	case 8:
422 	    samples[i] += *(u_int8_t *)&sample;
423 	    break;
424 	case -16:
425 	    samples[i] += *(int16_t *)&sample;
426 	    break;
427 	case 16:
428 	    samples[i] += *(u_int16_t *)&sample;
429 	    break;
430 	case -32:
431 	    samples[i] += *(int32_t *)&sample;
432 	    break;
433 	case 32:
434 	    samples[i] += *(u_int32_t *)&sample;
435 	    break;
436 	case -64:
437 	    samples[i] += *(int64_t *)&sample;
438 	    break;
439 	case 64:
440 	    samples[i] += *(u_int64_t *)&sample;
441 	    break;
442 	default:
443 	    err(1, "unsupported histogram counter type %d", histcounter_type);
444 	}
445     }
446     if (i != nsamples)
447 	errx(1, "unexpected EOF after reading %d/%d samples", --i , nsamples );
448 }
449 
450 /*
451  *	Assign samples to the procedures to which they belong.
452  *
453  *	There are three cases as to where pcl and pch can be
454  *	with respect to the routine entry addresses svalue0 and svalue1
455  *	as shown in the following diagram.  overlap computes the
456  *	distance between the arrows, the fraction of the sample
457  *	that is to be credited to the routine which starts at svalue0.
458  *
459  *	    svalue0                                         svalue1
460  *	       |                                               |
461  *	       v                                               v
462  *
463  *	       +-----------------------------------------------+
464  *	       |					       |
465  *	  |  ->|    |<-		->|         |<-		->|    |<-  |
466  *	  |         |		  |         |		  |         |
467  *	  +---------+		  +---------+		  +---------+
468  *
469  *	  ^         ^		  ^         ^		  ^         ^
470  *	  |         |		  |         |		  |         |
471  *	 pcl       pch		 pcl       pch		 pcl       pch
472  *
473  *	For the vax we assert that samples will never fall in the first
474  *	two bytes of any routine, since that is the entry mask,
475  *	thus we give call alignentries() to adjust the entry points if
476  *	the entry mask falls in one bucket but the code for the routine
477  *	doesn't start until the next bucket.  In conjunction with the
478  *	alignment of routine addresses, this should allow us to have
479  *	only one sample for every four bytes of text space and never
480  *	have any overlap (the two end cases, above).
481  */
482 void
483 asgnsamples(void)
484 {
485     register int	j;
486     double		ccnt;
487     double		thetime;
488     unsigned long	pcl, pch;
489     register int	i;
490     unsigned long	overlap;
491     unsigned long	svalue0, svalue1;
492 
493     /* read samples and assign to namelist symbols */
494     scale = highpc - lowpc;
495     scale /= nsamples;
496     alignentries();
497     for (i = 0, j = 1; i < nsamples; i++) {
498 	ccnt = samples[i];
499 	if (ccnt == 0)
500 		continue;
501 	pcl = lowpc + (unsigned long)(scale * i);
502 	pch = lowpc + (unsigned long)(scale * (i + 1));
503 	thetime = ccnt;
504 #	ifdef DEBUG
505 	    if ( debug & SAMPLEDEBUG ) {
506 		printf( "[asgnsamples] pcl 0x%lx pch 0x%lx ccnt %.0f\n" ,
507 			pcl , pch , ccnt );
508 	    }
509 #	endif /* DEBUG */
510 	totime += thetime;
511 	for (j = j - 1; j < nname; j++) {
512 	    svalue0 = nl[j].svalue;
513 	    svalue1 = nl[j+1].svalue;
514 		/*
515 		 *	if high end of tick is below entry address,
516 		 *	go for next tick.
517 		 */
518 	    if (pch < svalue0)
519 		    break;
520 		/*
521 		 *	if low end of tick into next routine,
522 		 *	go for next routine.
523 		 */
524 	    if (pcl >= svalue1)
525 		    continue;
526 	    overlap = min(pch, svalue1) - max(pcl, svalue0);
527 	    if (overlap > 0) {
528 #		ifdef DEBUG
529 		    if (debug & SAMPLEDEBUG) {
530 			printf("[asgnsamples] (0x%lx->0x%lx-0x%lx) %s gets %f ticks %lu overlap\n",
531 				nl[j].value / HISTORICAL_SCALE_2,
532 				svalue0, svalue1, nl[j].name,
533 				overlap * thetime / scale, overlap);
534 		    }
535 #		endif /* DEBUG */
536 		nl[j].time += overlap * thetime / scale;
537 	    }
538 	}
539     }
540 #   ifdef DEBUG
541 	if (debug & SAMPLEDEBUG) {
542 	    printf("[asgnsamples] totime %f\n", totime);
543 	}
544 #   endif /* DEBUG */
545 }
546 
547 
548 unsigned long
549 min(unsigned long a, unsigned long b)
550 {
551     if (a<b)
552 	return(a);
553     return(b);
554 }
555 
556 unsigned long
557 max(unsigned long a, unsigned long b)
558 {
559     if (a>b)
560 	return(a);
561     return(b);
562 }
563 
564     /*
565      *	calculate scaled entry point addresses (to save time in asgnsamples),
566      *	and possibly push the scaled entry points over the entry mask,
567      *	if it turns out that the entry point is in one bucket and the code
568      *	for a routine is in the next bucket.
569      */
570 void
571 alignentries(void)
572 {
573     register struct nl	*nlp;
574     unsigned long	bucket_of_entry;
575     unsigned long	bucket_of_code;
576 
577     for (nlp = nl; nlp < npe; nlp++) {
578 	nlp -> svalue = nlp -> value / HISTORICAL_SCALE_2;
579 	bucket_of_entry = (nlp->svalue - lowpc) / scale;
580 	bucket_of_code = (nlp->svalue + OFFSET_OF_CODE / HISTORICAL_SCALE_2 -
581 	  lowpc) / scale;
582 	if (bucket_of_entry < bucket_of_code) {
583 #	    ifdef DEBUG
584 		if (debug & SAMPLEDEBUG) {
585 		    printf("[alignentries] pushing svalue 0x%lx to 0x%lx\n",
586 			    nlp->svalue,
587 			    nlp->svalue + OFFSET_OF_CODE / HISTORICAL_SCALE_2);
588 		}
589 #	    endif /* DEBUG */
590 	    nlp->svalue += OFFSET_OF_CODE / HISTORICAL_SCALE_2;
591 	}
592     }
593 }
594