xref: /freebsd/usr.bin/gprof/gprof.c (revision a2aef24aa3c8458e4036735dd6928b4ef77294e5)
1 /*
2  * Copyright (c) 1983, 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  * 3. 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
31 static const char copyright[] =
32 "@(#) Copyright (c) 1983, 1993\n\
33 	The Regents of the University of California.  All rights reserved.\n";
34 #endif /* not lint */
35 
36 #if 0
37 #ifndef lint
38 static char sccsid[] = "@(#)gprof.c	8.1 (Berkeley) 6/6/93";
39 #endif /* not lint */
40 #endif
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include <err.h>
46 #include <limits.h>
47 #include <stdint.h>
48 #include <string.h>
49 
50 #include "gprof.h"
51 
52 static int valcmp(const void *, const void *);
53 
54 static struct gmonhdr	gmonhdr;
55 static int lflag;
56 static int Lflag;
57 
58 int
59 main(int argc, char **argv)
60 {
61     char	**sp;
62     nltype	**timesortnlp;
63     char	**defaultEs;
64 
65     --argc;
66     argv++;
67     debug = 0;
68     bflag = TRUE;
69     while ( *argv != 0 && **argv == '-' ) {
70 	(*argv)++;
71 	switch ( **argv ) {
72 	case 'a':
73 	    aflag = TRUE;
74 	    break;
75 	case 'b':
76 	    bflag = FALSE;
77 	    break;
78 	case 'C':
79 	    Cflag = TRUE;
80 	    cyclethreshold = atoi( *++argv );
81 	    break;
82 	case 'd':
83 	    dflag = TRUE;
84 	    setlinebuf(stdout);
85 	    debug |= atoi( *++argv );
86 	    debug |= ANYDEBUG;
87 #	    ifdef DEBUG
88 		printf("[main] debug = %d\n", debug);
89 #	    else /* not DEBUG */
90 		printf("gprof: -d ignored\n");
91 #	    endif /* DEBUG */
92 	    break;
93 	case 'E':
94 	    ++argv;
95 	    addlist( Elist , *argv );
96 	    Eflag = TRUE;
97 	    addlist( elist , *argv );
98 	    eflag = TRUE;
99 	    break;
100 	case 'e':
101 	    addlist( elist , *++argv );
102 	    eflag = TRUE;
103 	    break;
104 	case 'F':
105 	    ++argv;
106 	    addlist( Flist , *argv );
107 	    Fflag = TRUE;
108 	    addlist( flist , *argv );
109 	    fflag = TRUE;
110 	    break;
111 	case 'f':
112 	    addlist( flist , *++argv );
113 	    fflag = TRUE;
114 	    break;
115 	case 'k':
116 	    addlist( kfromlist , *++argv );
117 	    addlist( ktolist , *++argv );
118 	    kflag = TRUE;
119 	    break;
120 	case 'K':
121 	    Kflag = TRUE;
122 	    break;
123 	case 'l':
124 	    lflag = 1;
125 	    Lflag = 0;
126 	    break;
127 	case 'L':
128 	    Lflag = 1;
129 	    lflag = 0;
130 	    break;
131 	case 's':
132 	    sflag = TRUE;
133 	    break;
134 	case 'u':
135 	    uflag = TRUE;
136 	    break;
137 	case 'z':
138 	    zflag = TRUE;
139 	    break;
140 	}
141 	argv++;
142     }
143     if ( *argv != 0 ) {
144 	a_outname  = *argv;
145 	argv++;
146     } else {
147 	a_outname  = A_OUTNAME;
148     }
149     if ( *argv != 0 ) {
150 	gmonname = *argv;
151 	argv++;
152     } else {
153 	gmonname = (char *) malloc(strlen(a_outname)+6);
154 	strcpy(gmonname, a_outname);
155 	strcat(gmonname, ".gmon");
156     }
157 	/*
158 	 *	get information from the executable file.
159 	 */
160     if ((Kflag && kernel_getnfile(a_outname, &defaultEs) == -1) ||
161       (!Kflag && elf_getnfile(a_outname, &defaultEs) == -1 &&
162       aout_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