xref: /csrg-svn/usr.bin/gprof/gprof.c (revision 52650)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1983 Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)gprof.c	5.9 (Berkeley) 02/24/92";
16 #endif /* not lint */
17 
18 #include "gprof.h"
19 
20 char	*whoami = "gprof";
21 
22     /*
23      *	things which get -E excluded by default.
24      */
25 char	*defaultEs[] = { "mcount" , "__mcleanup" , 0 };
26 
27 main(argc, argv)
28     int argc;
29     char **argv;
30 {
31     char	**sp;
32     nltype	**timesortnlp;
33 
34     --argc;
35     argv++;
36     debug = 0;
37     bflag = TRUE;
38     while ( *argv != 0 && **argv == '-' ) {
39 	(*argv)++;
40 	switch ( **argv ) {
41 	case 'a':
42 	    aflag = TRUE;
43 	    break;
44 	case 'b':
45 	    bflag = FALSE;
46 	    break;
47 	case 'C':
48 	    Cflag = TRUE;
49 	    cyclethreshold = atoi( *++argv );
50 	    break;
51 	case 'c':
52 #if defined(vax) || defined(tahoe)
53 	    cflag = TRUE;
54 #else
55 	    fprintf(stderr, "gprof: -c isn't supported on this architecture yet\n");
56 	    exit(1);
57 #endif
58 	    break;
59 	case 'd':
60 	    dflag = TRUE;
61 	    debug |= atoi( *++argv );
62 	    debug |= ANYDEBUG;
63 #	    ifdef DEBUG
64 		printf("[main] debug = %d\n", debug);
65 #	    else not DEBUG
66 		printf("%s: -d ignored\n", whoami);
67 #	    endif DEBUG
68 	    break;
69 	case 'E':
70 	    ++argv;
71 	    addlist( Elist , *argv );
72 	    Eflag = TRUE;
73 	    addlist( elist , *argv );
74 	    eflag = TRUE;
75 	    break;
76 	case 'e':
77 	    addlist( elist , *++argv );
78 	    eflag = TRUE;
79 	    break;
80 	case 'F':
81 	    ++argv;
82 	    addlist( Flist , *argv );
83 	    Fflag = TRUE;
84 	    addlist( flist , *argv );
85 	    fflag = TRUE;
86 	    break;
87 	case 'f':
88 	    addlist( flist , *++argv );
89 	    fflag = TRUE;
90 	    break;
91 	case 'k':
92 	    addlist( kfromlist , *++argv );
93 	    addlist( ktolist , *++argv );
94 	    kflag = TRUE;
95 	    break;
96 	case 's':
97 	    sflag = TRUE;
98 	    break;
99 	case 'z':
100 	    zflag = TRUE;
101 	    break;
102 	}
103 	argv++;
104     }
105     if ( *argv != 0 ) {
106 	a_outname  = *argv;
107 	argv++;
108     } else {
109 	a_outname  = A_OUTNAME;
110     }
111     if ( *argv != 0 ) {
112 	gmonname = *argv;
113 	argv++;
114     } else {
115 	gmonname = GMONNAME;
116     }
117 	/*
118 	 *	turn off default functions
119 	 */
120     for ( sp = &defaultEs[0] ; *sp ; sp++ ) {
121 	Eflag = TRUE;
122 	addlist( Elist , *sp );
123 	eflag = TRUE;
124 	addlist( elist , *sp );
125     }
126 	/*
127 	 *	how many ticks per second?
128 	 *	if we can't tell, report time in ticks.
129 	 */
130     hz = hertz();
131     if (hz == 0) {
132 	hz = 1;
133 	fprintf(stderr, "time is in ticks, not seconds\n");
134     }
135 	/*
136 	 *	get information about a.out file.
137 	 */
138     getnfile();
139 	/*
140 	 *	get information about mon.out file(s).
141 	 */
142     do	{
143 	getpfile( gmonname );
144 	if ( *argv != 0 ) {
145 	    gmonname = *argv;
146 	}
147     } while ( *argv++ != 0 );
148 	/*
149 	 *	dump out a gmon.sum file if requested
150 	 */
151     if ( sflag ) {
152 	dumpsum( GMONSUM );
153     }
154 	/*
155 	 *	assign samples to procedures
156 	 */
157     asgnsamples();
158 	/*
159 	 *	assemble the dynamic profile
160 	 */
161     timesortnlp = doarcs();
162 	/*
163 	 *	print the dynamic profile
164 	 */
165     printgprof( timesortnlp );
166 	/*
167 	 *	print the flat profile
168 	 */
169     printprof();
170 	/*
171 	 *	print the index
172 	 */
173     printindex();
174     done();
175 }
176 
177     /*
178      * Set up string and symbol tables from a.out.
179      *	and optionally the text space.
180      * On return symbol table is sorted by value.
181      */
182 getnfile()
183 {
184     FILE	*nfile;
185     int		valcmp();
186 
187     nfile = fopen( a_outname ,"r");
188     if (nfile == NULL) {
189 	perror( a_outname );
190 	done();
191     }
192     fread(&xbuf, 1, sizeof(xbuf), nfile);
193     if (N_BADMAG(xbuf)) {
194 	fprintf(stderr, "%s: %s: bad format\n", whoami , a_outname );
195 	done();
196     }
197     getstrtab(nfile);
198     getsymtab(nfile);
199     gettextspace( nfile );
200     qsort(nl, nname, sizeof(nltype), valcmp);
201     fclose(nfile);
202 #   ifdef DEBUG
203 	if ( debug & AOUTDEBUG ) {
204 	    register int j;
205 
206 	    for (j = 0; j < nname; j++){
207 		printf("[getnfile] 0X%08x\t%s\n", nl[j].value, nl[j].name);
208 	    }
209 	}
210 #   endif DEBUG
211 }
212 
213 getstrtab(nfile)
214     FILE	*nfile;
215 {
216 
217     fseek(nfile, (long)(N_SYMOFF(xbuf) + xbuf.a_syms), 0);
218     if (fread(&ssiz, sizeof (ssiz), 1, nfile) == 0) {
219 	fprintf(stderr, "%s: %s: no string table (old format?)\n" ,
220 		whoami , a_outname );
221 	done();
222     }
223     strtab = (char *)calloc(ssiz, 1);
224     if (strtab == NULL) {
225 	fprintf(stderr, "%s: %s: no room for %d bytes of string table",
226 		whoami , a_outname , ssiz);
227 	done();
228     }
229     if (fread(strtab+sizeof(ssiz), ssiz-sizeof(ssiz), 1, nfile) != 1) {
230 	fprintf(stderr, "%s: %s: error reading string table\n",
231 		whoami , a_outname );
232 	done();
233     }
234 }
235 
236     /*
237      * Read in symbol table
238      */
239 getsymtab(nfile)
240     FILE	*nfile;
241 {
242     register long	i;
243     int			askfor;
244     struct nlist	nbuf;
245 
246     /* pass1 - count symbols */
247     fseek(nfile, (long)N_SYMOFF(xbuf), 0);
248     nname = 0;
249     for (i = xbuf.a_syms; i > 0; i -= sizeof(struct nlist)) {
250 	fread(&nbuf, sizeof(nbuf), 1, nfile);
251 	if ( ! funcsymbol( &nbuf ) ) {
252 	    continue;
253 	}
254 	nname++;
255     }
256     if (nname == 0) {
257 	fprintf(stderr, "%s: %s: no symbols\n", whoami , a_outname );
258 	done();
259     }
260     askfor = nname + 1;
261     nl = (nltype *) calloc( askfor , sizeof(nltype) );
262     if (nl == 0) {
263 	fprintf(stderr, "%s: No room for %d bytes of symbol table\n",
264 		whoami, askfor * sizeof(nltype) );
265 	done();
266     }
267 
268     /* pass2 - read symbols */
269     fseek(nfile, (long)N_SYMOFF(xbuf), 0);
270     npe = nl;
271     nname = 0;
272     for (i = xbuf.a_syms; i > 0; i -= sizeof(struct nlist)) {
273 	fread(&nbuf, sizeof(nbuf), 1, nfile);
274 	if ( ! funcsymbol( &nbuf ) ) {
275 #	    ifdef DEBUG
276 		if ( debug & AOUTDEBUG ) {
277 		    printf( "[getsymtab] rejecting: 0x%x %s\n" ,
278 			    nbuf.n_type , strtab + nbuf.n_un.n_strx );
279 		}
280 #	    endif DEBUG
281 	    continue;
282 	}
283 	npe->value = nbuf.n_value;
284 	npe->name = strtab+nbuf.n_un.n_strx;
285 #	ifdef DEBUG
286 	    if ( debug & AOUTDEBUG ) {
287 		printf( "[getsymtab] %d %s 0x%08x\n" ,
288 			nname , npe -> name , npe -> value );
289 	    }
290 #	endif DEBUG
291 	npe++;
292 	nname++;
293     }
294     npe->value = -1;
295 }
296 
297     /*
298      *	read in the text space of an a.out file
299      */
300 gettextspace( nfile )
301     FILE	*nfile;
302 {
303     char	*malloc();
304 
305     if ( cflag == 0 ) {
306 	return;
307     }
308     textspace = (u_char *) malloc( xbuf.a_text );
309     if ( textspace == 0 ) {
310 	fprintf( stderr , "%s: ran out room for %d bytes of text space:  " ,
311 			whoami , xbuf.a_text );
312 	fprintf( stderr , "can't do -c\n" );
313 	return;
314     }
315     (void) fseek( nfile , N_TXTOFF( xbuf ) , 0 );
316     if ( fread( textspace , 1 , xbuf.a_text , nfile ) != xbuf.a_text ) {
317 	fprintf( stderr , "%s: couldn't read text space:  " , whoami );
318 	fprintf( stderr , "can't do -c\n" );
319 	free( textspace );
320 	textspace = 0;
321 	return;
322     }
323 }
324     /*
325      *	information from a gmon.out file is in two parts:
326      *	an array of sampling hits within pc ranges,
327      *	and the arcs.
328      */
329 getpfile(filename)
330     char *filename;
331 {
332     FILE		*pfile;
333     FILE		*openpfile();
334     struct rawarc	arc;
335 
336     pfile = openpfile(filename);
337     readsamples(pfile);
338 	/*
339 	 *	the rest of the file consists of
340 	 *	a bunch of <from,self,count> tuples.
341 	 */
342     while ( fread( &arc , sizeof arc , 1 , pfile ) == 1 ) {
343 #	ifdef DEBUG
344 	    if ( debug & SAMPLEDEBUG ) {
345 		printf( "[getpfile] frompc 0x%x selfpc 0x%x count %d\n" ,
346 			arc.raw_frompc , arc.raw_selfpc , arc.raw_count );
347 	    }
348 #	endif DEBUG
349 	    /*
350 	     *	add this arc
351 	     */
352 	tally( &arc );
353     }
354     fclose(pfile);
355 }
356 
357 FILE *
358 openpfile(filename)
359     char *filename;
360 {
361     struct hdr	tmp;
362     FILE	*pfile;
363 
364     if((pfile = fopen(filename, "r")) == NULL) {
365 	perror(filename);
366 	done();
367     }
368     fread(&tmp, sizeof(struct hdr), 1, pfile);
369     if ( s_highpc != 0 && ( tmp.lowpc != h.lowpc ||
370 	 tmp.highpc != h.highpc || tmp.ncnt != h.ncnt ) ) {
371 	fprintf(stderr, "%s: incompatible with first gmon file\n", filename);
372 	done();
373     }
374     h = tmp;
375     s_lowpc = (unsigned long) h.lowpc;
376     s_highpc = (unsigned long) h.highpc;
377     lowpc = (unsigned long)h.lowpc / sizeof(UNIT);
378     highpc = (unsigned long)h.highpc / sizeof(UNIT);
379     sampbytes = h.ncnt - sizeof(struct hdr);
380     nsamples = sampbytes / sizeof (UNIT);
381 #   ifdef DEBUG
382 	if ( debug & SAMPLEDEBUG ) {
383 	    printf( "[openpfile] hdr.lowpc 0x%x hdr.highpc 0x%x hdr.ncnt %d\n",
384 		h.lowpc , h.highpc , h.ncnt );
385 	    printf( "[openpfile]   s_lowpc 0x%x   s_highpc 0x%x\n" ,
386 		s_lowpc , s_highpc );
387 	    printf( "[openpfile]     lowpc 0x%x     highpc 0x%x\n" ,
388 		lowpc , highpc );
389 	    printf( "[openpfile] sampbytes %d nsamples %d\n" ,
390 		sampbytes , nsamples );
391 	}
392 #   endif DEBUG
393     return(pfile);
394 }
395 
396 tally( rawp )
397     struct rawarc	*rawp;
398 {
399     nltype		*parentp;
400     nltype		*childp;
401 
402     parentp = nllookup( rawp -> raw_frompc );
403     childp = nllookup( rawp -> raw_selfpc );
404     if ( parentp == 0 || childp == 0 )
405 	return;
406     if ( kflag
407 	 && onlist( kfromlist , parentp -> name )
408 	 && onlist( ktolist , childp -> name ) ) {
409 	return;
410     }
411     childp -> ncall += rawp -> raw_count;
412 #   ifdef DEBUG
413 	if ( debug & TALLYDEBUG ) {
414 	    printf( "[tally] arc from %s to %s traversed %d times\n" ,
415 		    parentp -> name , childp -> name , rawp -> raw_count );
416 	}
417 #   endif DEBUG
418     addarc( parentp , childp , rawp -> raw_count );
419 }
420 
421 /*
422  * dump out the gmon.sum file
423  */
424 dumpsum( sumfile )
425     char *sumfile;
426 {
427     register nltype *nlp;
428     register arctype *arcp;
429     struct rawarc arc;
430     FILE *sfile;
431 
432     if ( ( sfile = fopen ( sumfile , "w" ) ) == NULL ) {
433 	perror( sumfile );
434 	done();
435     }
436     /*
437      * dump the header; use the last header read in
438      */
439     if ( fwrite( &h , sizeof h , 1 , sfile ) != 1 ) {
440 	perror( sumfile );
441 	done();
442     }
443     /*
444      * dump the samples
445      */
446     if (fwrite(samples, sizeof (UNIT), nsamples, sfile) != nsamples) {
447 	perror( sumfile );
448 	done();
449     }
450     /*
451      * dump the normalized raw arc information
452      */
453     for ( nlp = nl ; nlp < npe ; nlp++ ) {
454 	for ( arcp = nlp -> children ; arcp ; arcp = arcp -> arc_childlist ) {
455 	    arc.raw_frompc = arcp -> arc_parentp -> value;
456 	    arc.raw_selfpc = arcp -> arc_childp -> value;
457 	    arc.raw_count = arcp -> arc_count;
458 	    if ( fwrite ( &arc , sizeof arc , 1 , sfile ) != 1 ) {
459 		perror( sumfile );
460 		done();
461 	    }
462 #	    ifdef DEBUG
463 		if ( debug & SAMPLEDEBUG ) {
464 		    printf( "[dumpsum] frompc 0x%x selfpc 0x%x count %d\n" ,
465 			    arc.raw_frompc , arc.raw_selfpc , arc.raw_count );
466 		}
467 #	    endif DEBUG
468 	}
469     }
470     fclose( sfile );
471 }
472 
473 valcmp(p1, p2)
474     nltype *p1, *p2;
475 {
476     if ( p1 -> value < p2 -> value ) {
477 	return LESSTHAN;
478     }
479     if ( p1 -> value > p2 -> value ) {
480 	return GREATERTHAN;
481     }
482     return EQUALTO;
483 }
484 
485 readsamples(pfile)
486     FILE	*pfile;
487 {
488     register i;
489     UNIT	sample;
490 
491     if (samples == 0) {
492 	samples = (UNIT *) calloc(sampbytes, sizeof (UNIT));
493 	if (samples == 0) {
494 	    fprintf( stderr , "%s: No room for %d sample pc's\n",
495 		whoami , sampbytes / sizeof (UNIT));
496 	    done();
497 	}
498     }
499     for (i = 0; i < nsamples; i++) {
500 	fread(&sample, sizeof (UNIT), 1, pfile);
501 	if (feof(pfile))
502 		break;
503 	samples[i] += sample;
504     }
505     if (i != nsamples) {
506 	fprintf(stderr,
507 	    "%s: unexpected EOF after reading %d/%d samples\n",
508 		whoami , --i , nsamples );
509 	done();
510     }
511 }
512 
513 /*
514  *	Assign samples to the procedures to which they belong.
515  *
516  *	There are three cases as to where pcl and pch can be
517  *	with respect to the routine entry addresses svalue0 and svalue1
518  *	as shown in the following diagram.  overlap computes the
519  *	distance between the arrows, the fraction of the sample
520  *	that is to be credited to the routine which starts at svalue0.
521  *
522  *	    svalue0                                         svalue1
523  *	       |                                               |
524  *	       v                                               v
525  *
526  *	       +-----------------------------------------------+
527  *	       |					       |
528  *	  |  ->|    |<-		->|         |<-		->|    |<-  |
529  *	  |         |		  |         |		  |         |
530  *	  +---------+		  +---------+		  +---------+
531  *
532  *	  ^         ^		  ^         ^		  ^         ^
533  *	  |         |		  |         |		  |         |
534  *	 pcl       pch		 pcl       pch		 pcl       pch
535  *
536  *	For the vax we assert that samples will never fall in the first
537  *	two bytes of any routine, since that is the entry mask,
538  *	thus we give call alignentries() to adjust the entry points if
539  *	the entry mask falls in one bucket but the code for the routine
540  *	doesn't start until the next bucket.  In conjunction with the
541  *	alignment of routine addresses, this should allow us to have
542  *	only one sample for every four bytes of text space and never
543  *	have any overlap (the two end cases, above).
544  */
545 asgnsamples()
546 {
547     register int	j;
548     UNIT		ccnt;
549     double		time;
550     unsigned long	pcl, pch;
551     register int	i;
552     unsigned long	overlap;
553     unsigned long	svalue0, svalue1;
554 
555     /* read samples and assign to namelist symbols */
556     scale = highpc - lowpc;
557     scale /= nsamples;
558     alignentries();
559     for (i = 0, j = 1; i < nsamples; i++) {
560 	ccnt = samples[i];
561 	if (ccnt == 0)
562 		continue;
563 	pcl = lowpc + scale * i;
564 	pch = lowpc + scale * (i + 1);
565 	time = ccnt;
566 #	ifdef DEBUG
567 	    if ( debug & SAMPLEDEBUG ) {
568 		printf( "[asgnsamples] pcl 0x%x pch 0x%x ccnt %d\n" ,
569 			pcl , pch , ccnt );
570 	    }
571 #	endif DEBUG
572 	totime += time;
573 	for (j = j - 1; j < nname; j++) {
574 	    svalue0 = nl[j].svalue;
575 	    svalue1 = nl[j+1].svalue;
576 		/*
577 		 *	if high end of tick is below entry address,
578 		 *	go for next tick.
579 		 */
580 	    if (pch < svalue0)
581 		    break;
582 		/*
583 		 *	if low end of tick into next routine,
584 		 *	go for next routine.
585 		 */
586 	    if (pcl >= svalue1)
587 		    continue;
588 	    overlap = min(pch, svalue1) - max(pcl, svalue0);
589 	    if (overlap > 0) {
590 #		ifdef DEBUG
591 		    if (debug & SAMPLEDEBUG) {
592 			printf("[asgnsamples] (0x%x->0x%x-0x%x) %s gets %f ticks %d overlap\n",
593 				nl[j].value/sizeof(UNIT), svalue0, svalue1,
594 				nl[j].name,
595 				overlap * time / scale, overlap);
596 		    }
597 #		endif DEBUG
598 		nl[j].time += overlap * time / scale;
599 	    }
600 	}
601     }
602 #   ifdef DEBUG
603 	if (debug & SAMPLEDEBUG) {
604 	    printf("[asgnsamples] totime %f\n", totime);
605 	}
606 #   endif DEBUG
607 }
608 
609 
610 unsigned long
611 min(a, b)
612     unsigned long a,b;
613 {
614     if (a<b)
615 	return(a);
616     return(b);
617 }
618 
619 unsigned long
620 max(a, b)
621     unsigned long a,b;
622 {
623     if (a>b)
624 	return(a);
625     return(b);
626 }
627 
628     /*
629      *	calculate scaled entry point addresses (to save time in asgnsamples),
630      *	and possibly push the scaled entry points over the entry mask,
631      *	if it turns out that the entry point is in one bucket and the code
632      *	for a routine is in the next bucket.
633      */
634 alignentries()
635 {
636     register struct nl	*nlp;
637     unsigned long	bucket_of_entry;
638     unsigned long	bucket_of_code;
639 
640     for (nlp = nl; nlp < npe; nlp++) {
641 	nlp -> svalue = nlp -> value / sizeof(UNIT);
642 	bucket_of_entry = (nlp->svalue - lowpc) / scale;
643 	bucket_of_code = (nlp->svalue + UNITS_TO_CODE - lowpc) / scale;
644 	if (bucket_of_entry < bucket_of_code) {
645 #	    ifdef DEBUG
646 		if (debug & SAMPLEDEBUG) {
647 		    printf("[alignentries] pushing svalue 0x%x to 0x%x\n",
648 			    nlp->svalue, nlp->svalue + UNITS_TO_CODE);
649 		}
650 #	    endif DEBUG
651 	    nlp->svalue += UNITS_TO_CODE;
652 	}
653     }
654 }
655 
656 bool
657 funcsymbol( nlistp )
658     struct nlist	*nlistp;
659 {
660     extern char	*strtab;	/* string table from a.out */
661     extern int	aflag;		/* if static functions aren't desired */
662     char	*name;
663 
664 	/*
665 	 *	must be a text symbol,
666 	 *	and static text symbols don't qualify if aflag set.
667 	 */
668     if ( ! (  ( nlistp -> n_type == ( N_TEXT | N_EXT ) )
669 	   || ( ( nlistp -> n_type == N_TEXT ) && ( aflag == 0 ) ) ) ) {
670 	return FALSE;
671     }
672 	/*
673 	 *	can't have any `funny' characters in name,
674 	 *	where `funny' includes	`.', .o file names
675 	 *			and	`$', pascal labels.
676 	 */
677     for ( name = strtab + nlistp -> n_un.n_strx ; *name ; name += 1 ) {
678 	if ( *name == '.' || *name == '$' ) {
679 	    return FALSE;
680 	}
681     }
682     return TRUE;
683 }
684 
685 done()
686 {
687 
688     exit(0);
689 }
690