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