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