Wed Aug 7 14:43:51 1996 Philippe De Muyter <phdm@info.ucl.ac.be>
[platform/upstream/binutils.git] / gprof / core.c
1 #include "libiberty.h"
2 #include "gprof.h"
3 #include "core.h"
4 #include "symtab.h"
5
6 #ifndef MIN_INSN_SIZE
7 /* If not defined in MACHINE_H, assume smallest instruction is 1 byte
8    long.  THis is safe but may be needlessly slow on machines where
9    all instructions are longer.  */
10 #define MIN_INSN_SIZE 1
11 #endif
12
13 bfd *core_bfd;
14 int core_num_syms;
15 asymbol **core_syms;
16 asection *core_text_sect;
17 PTR core_text_space;
18
19 /* For mapping symbols to specific .o files during file ordering.  */
20 struct function_map {
21   char *function_name;
22   char *file_name;
23 };
24
25 struct function_map *symbol_map;
26 int symbol_map_count;
27
28 static void
29 DEFUN (read_function_mappings, (filename), const char *filename)
30 {
31   FILE *file = fopen (filename, "r");
32   char dummy[1024];
33   int count = 0;
34
35   if (!file)
36     {
37       fprintf (stderr, "%s: could not open %s.\n", whoami, filename);
38       done (1);
39     }
40
41   /* First parse the mapping file so we know how big we need to
42      make our tables.  We also do some sanity checks at this
43      time.  */
44   while (!feof (file))
45     {
46       int matches;
47
48       matches = fscanf (file, "%[^\n:]", dummy);
49       if (!matches)
50         {
51           fprintf (stderr, "%s: unable to parse mapping file %s.\n",
52                    whoami, filename);
53           done (1);
54         }
55
56       /* Just skip messages about files with no symbols.  */
57       if (!strncmp (dummy, "No symbols in ", 14))
58         {
59           fscanf (file, "\n");
60           continue;
61         }
62
63       /* Don't care what else is on this line at this point.  */
64       fscanf (file, "%[^\n]\n", dummy);
65       count++;
66     }
67
68   /* Now we know how big we need to make our table.  */
69   symbol_map = ((struct function_map *)
70                 xmalloc (count * sizeof (struct function_map)));
71
72   /* Rewind the input file so we can read it again.  */
73   rewind (file);
74
75   /* Read each entry and put it into the table.  */
76   count = 0;
77   while (!feof (file))
78     {
79       int matches;
80       char *tmp;
81
82       matches = fscanf (file, "%[^\n:]", dummy);
83       if (!matches)
84         {
85           fprintf (stderr, "%s: unable to parse mapping file %s.\n",
86                    whoami, filename);
87           done (1);
88         }
89
90       /* Just skip messages about files with no symbols.  */
91       if (!strncmp (dummy, "No symbols in ", 14))
92         {
93           fscanf (file, "\n");
94           continue;
95         }
96
97       /* dummy has the filename, go ahead and copy it.  */
98       symbol_map[count].file_name = xmalloc (strlen (dummy) + 1);
99       strcpy (symbol_map[count].file_name, dummy);
100
101       /* Now we need the function name.  */
102       fscanf (file, "%[^\n]\n", dummy);
103       tmp = strrchr (dummy, ' ') + 1;
104       symbol_map[count].function_name = xmalloc (strlen (tmp) + 1);
105       strcpy (symbol_map[count].function_name, tmp);
106       count++;
107     }
108
109   /* Record the size of the map table for future reference.  */
110   symbol_map_count = count;
111 }
112
113 void
114 DEFUN (core_init, (a_out_name), const char *a_out_name)
115 {
116   core_bfd = bfd_openr (a_out_name, 0);
117
118   if (!core_bfd)
119     {
120       perror (a_out_name);
121       done (1);
122     }
123
124   if (!bfd_check_format (core_bfd, bfd_object))
125     {
126       fprintf (stderr, "%s: %s: not in a.out format\n", whoami, a_out_name);
127       done (1);
128     }
129
130   /* get core's text section: */
131   core_text_sect = bfd_get_section_by_name (core_bfd, ".text");
132   if (!core_text_sect)
133     {
134       core_text_sect = bfd_get_section_by_name (core_bfd, "$CODE$");
135       if (!core_text_sect)
136         {
137           fprintf (stderr, "%s: can't find .text section in %s\n",
138                    whoami, a_out_name);
139           done (1);
140         }
141     }
142
143   /* read core's symbol table: */
144
145   /* this will probably give us more than we need, but that's ok:  */
146   core_num_syms = bfd_get_symtab_upper_bound (core_bfd);
147   if (core_num_syms < 0)
148     {
149       fprintf (stderr, "%s: %s: %s\n", whoami, a_out_name,
150                bfd_errmsg (bfd_get_error ()));
151       done (1);
152     }
153
154   core_syms = (asymbol **) xmalloc (core_num_syms);
155   core_num_syms = bfd_canonicalize_symtab (core_bfd, core_syms);
156   if (core_num_syms < 0)
157     {
158       fprintf (stderr, "%s: %s: %s\n", whoami, a_out_name,
159                bfd_errmsg (bfd_get_error ()));
160       done (1);
161     }
162
163   if (function_mapping_file)
164     read_function_mappings (function_mapping_file);
165 }
166
167
168 /*
169  * Read in the text space of an a.out file
170  */
171 void
172 DEFUN (core_get_text_space, (core_bfd), bfd * core_bfd)
173 {
174   core_text_space = (PTR) malloc (core_text_sect->_raw_size);
175
176   if (!core_text_space)
177     {
178       fprintf (stderr, "%s: ran out room for %ld bytes of text space\n",
179                whoami, core_text_sect->_raw_size);
180       done (1);
181     }
182   if (!bfd_get_section_contents (core_bfd, core_text_sect, core_text_space,
183                                  0, core_text_sect->_raw_size))
184     {
185       bfd_perror ("bfd_get_section_contents");
186       free (core_text_space);
187       core_text_space = 0;
188     }
189   if (!core_text_space)
190     {
191       fprintf (stderr, "%s: can't do -c\n", whoami);
192     }
193 }
194
195
196 /*
197  * Return class of symbol SYM.  The returned class can be any of:
198  *      0   -> symbol is not interesting to us
199  *      'T' -> symbol is a global name
200  *      't' -> symbol is a local (static) name
201  */
202 static int
203 DEFUN (core_sym_class, (sym), asymbol * sym)
204 {
205   symbol_info syminfo;
206   const char *name;
207   char sym_prefix;
208   int i;
209
210   if (sym->section == NULL || (sym->flags & BSF_DEBUGGING) != 0)
211     {
212       return 0;
213     }
214
215   /*
216    * Must be a text symbol, and static text symbols don't qualify if
217    * ignore_static_funcs set.
218    */
219   if (ignore_static_funcs && (sym->flags & BSF_LOCAL))
220     {
221       DBG (AOUTDEBUG, printf ("[core_sym_class] %s: not a function\n",
222                               sym->name));
223       return 0;
224     }
225
226   bfd_get_symbol_info (core_bfd, sym, &syminfo);
227   i = syminfo.type;
228
229   if (i == 'T')
230     {
231       return i;                 /* it's a global symbol */
232     }
233
234   if (i != 't')
235     {
236       /* not a static text symbol */
237       DBG (AOUTDEBUG, printf ("[core_sym_class] %s is of class %c\n",
238                               sym->name, i));
239       return 0;
240     }
241
242   /* do some more filtering on static function-names: */
243
244   if (ignore_static_funcs)
245     {
246       return 0;
247     }
248   /*
249    * Can't zero-length name or funny characters in name, where
250    * `funny' includes: `.' (.o file names) and `$' (Pascal labels).
251    */
252   if (!sym->name || sym->name[0] == '\0')
253     {
254       return 0;
255     }
256
257   for (name = sym->name; *name; ++name)
258     {
259       if (*name == '.' || *name == '$')
260         {
261           return 0;
262         }
263     }
264   /*
265    * On systems where the C compiler adds an underscore to all
266    * names, static names without underscores seem usually to be
267    * labels in hand written assembler in the library.  We don't want
268    * these names.  This is certainly necessary on a Sparc running
269    * SunOS 4.1 (try profiling a program that does a lot of
270    * division). I don't know whether it has harmful side effects on
271    * other systems.  Perhaps it should be made configurable.
272    */
273   sym_prefix = bfd_get_symbol_leading_char (core_bfd);
274   if ((sym_prefix && sym_prefix != sym->name[0])
275   /*
276    * GCC may add special symbols to help gdb figure out the file
277    * language.  We want to ignore these, since sometimes they mask
278    * the real function.  (dj@ctron)
279    */
280       || !strncmp (sym->name, "__gnu_compiled", 14)
281       || !strncmp (sym->name, "___gnu_compiled", 15))
282     {
283       return 0;
284     }
285
286   /* If the object file supports marking of function symbols, then we can
287      zap anything that doesn't have BSF_FUNCTION set.  */
288   if (ignore_non_functions && (sym->flags & BSF_FUNCTION) == 0)
289     return 0;
290
291   return 't';                   /* it's a static text symbol */
292 }
293
294
295 /*
296  * Get whatever source info we can get regarding address ADDR:
297  */
298 static bool
299 DEFUN (get_src_info, (addr, filename, name, line_num),
300        bfd_vma addr AND const char **filename AND const char **name
301        AND int *line_num)
302 {
303   const char *fname = 0, *func_name = 0;
304   int l = 0;
305
306   if (bfd_find_nearest_line (core_bfd, core_text_sect, core_syms,
307                              addr - core_text_sect->vma,
308                              &fname, &func_name, (unsigned int *) &l)
309       && fname && func_name && l)
310     {
311       DBG (AOUTDEBUG, printf ("[get_src_info] 0x%lx -> %s:%d (%s)\n",
312                               addr, fname, l, func_name));
313       *filename = fname;
314       *name = func_name;
315       *line_num = l;
316       return TRUE;
317     }
318   else
319     {
320       DBG (AOUTDEBUG, printf ("[get_src_info] no info for 0x%lx (%s:%d,%s)\n",
321                               (long) addr, fname ? fname : "<unknown>", l,
322                               func_name ? func_name : "<unknown>"));
323       return FALSE;
324     }
325 }
326
327
328 /*
329  * Read in symbol table from core.  One symbol per function is
330  * entered.
331  */
332 void
333 DEFUN (core_create_function_syms, (core_bfd), bfd * core_bfd)
334 {
335   bfd_vma min_vma = ~0, max_vma = 0;
336   int class;
337   long i, j, found, skip;
338
339   /* pass 1 - determine upper bound on number of function names: */
340   symtab.len = 0;
341   for (i = 0; i < core_num_syms; ++i)
342     {
343       if (!core_sym_class (core_syms[i]))
344         {
345           continue;
346         }
347
348       /* This should be replaced with a binary search or hashed
349          search.  Gross. 
350
351          Don't create a symtab entry for a function that has
352          a mapping to a file, unless it's the first function
353          in the file.  */
354       skip = 0;
355       for (j = 0; j < symbol_map_count; j++)
356         if (!strcmp (core_syms[i]->name, symbol_map[j].function_name))
357           {
358             if (j > 0 && ! strcmp (symbol_map [j].file_name,
359                                    symbol_map [j - 1].file_name))
360               skip = 1;
361             break;
362           }
363       if (!skip)
364         ++symtab.len;
365     }
366
367   if (symtab.len == 0)
368     {
369       fprintf (stderr, "%s: file `%s' has no symbols\n", whoami, a_out_name);
370       done (1);
371     }
372
373   /* the "+ 2" is for the sentinels: */
374   symtab.base = (Sym *) xmalloc ((symtab.len + 2) * sizeof (Sym));
375
376   /* pass 2 - create symbols: */
377
378   symtab.limit = symtab.base;
379   for (i = 0; i < core_num_syms; ++i)
380     {
381       class = core_sym_class (core_syms[i]);
382       if (!class)
383         {
384           DBG (AOUTDEBUG,
385                printf ("[core_create_function_syms] rejecting: 0x%lx %s\n",
386                        core_syms[i]->value, core_syms[i]->name));
387           continue;
388         }
389       /* This should be replaced with a binary search or hashed
390          search.  Gross.   */
391
392       skip = 0;
393       found = 0;
394       for (j = 0; j < symbol_map_count; j++)
395         if (!strcmp (core_syms[i]->name, symbol_map[j].function_name))
396           {
397             if (j > 0 && ! strcmp (symbol_map [j].file_name,
398                                    symbol_map [j - 1].file_name))
399               skip = 1;
400             else
401               found = j;
402             break;
403           }
404
405       if (skip)
406         continue;
407
408       sym_init (symtab.limit);
409
410       /* symbol offsets are always section-relative: */
411
412       symtab.limit->addr = core_syms[i]->value + core_syms[i]->section->vma;
413       if (symbol_map_count
414           && !strcmp (core_syms[i]->name, symbol_map[found].function_name))
415         {
416           symtab.limit->name = symbol_map[found].file_name;
417           symtab.limit->mapped = 1;
418         }
419       else
420         {
421           symtab.limit->name = core_syms[i]->name;
422           symtab.limit->mapped = 0;
423         }
424
425 #ifdef __osf__
426       /*
427        * Suppress symbols that are not function names.  This is
428        * useful to suppress code-labels and aliases.
429        *
430        * This is known to be useful under DEC's OSF/1.  Under SunOS 4.x,
431        * labels do not appear in the symbol table info, so this isn't
432        * necessary.
433        */
434       {
435         const char *filename, *func_name;
436         
437         if (get_src_info (symtab.limit->addr, &filename, &func_name,
438                           &symtab.limit->line_num))
439           {
440             symtab.limit->file = source_file_lookup_path (filename);
441
442             if (strcmp (symtab.limit->name, func_name) != 0)
443               {
444                 /*
445                  * The symbol's address maps to a different name, so
446                  * it can't be a function-entry point.  This happens
447                  * for labels, for example.
448                  */
449                 DBG (AOUTDEBUG,
450                      printf ("[core_create_function_syms: rej %s (maps to %s)\n",
451                              symtab.limit->name, func_name));
452                 continue;
453               }
454           }
455       }
456 #endif
457
458       symtab.limit->is_func = TRUE;
459       symtab.limit->is_bb_head = TRUE;
460       if (class == 't')
461         {
462           symtab.limit->is_static = TRUE;
463         }
464
465       min_vma = MIN (symtab.limit->addr, min_vma);
466       max_vma = MAX (symtab.limit->addr, max_vma);
467
468       /*
469        * If we see "main" without an initial '_', we assume names
470        * are *not* prefixed by '_'.
471        */
472       if (symtab.limit->name[0] == 'm' && discard_underscores
473           && strcmp (symtab.limit->name, "main") == 0)
474         {
475           discard_underscores = 0;
476         }
477
478       DBG (AOUTDEBUG, printf ("[core_create_function_syms] %ld %s 0x%lx\n",
479                               (long) (symtab.limit - symtab.base),
480                               symtab.limit->name, symtab.limit->addr));
481       ++symtab.limit;
482     }
483
484   /* create sentinels: */
485
486   sym_init (symtab.limit);
487   symtab.limit->name = "<locore>";
488   symtab.limit->addr = 0;
489   symtab.limit->end_addr = min_vma - 1;
490   ++symtab.limit;
491
492   sym_init (symtab.limit);
493   symtab.limit->name = "<hicore>";
494   symtab.limit->addr = max_vma + 1;
495   symtab.limit->end_addr = ~0;
496   ++symtab.limit;
497
498   symtab.len = symtab.limit - symtab.base;
499   symtab_finalize (&symtab);
500 }
501
502
503 /*
504  * Read in symbol table from core.  One symbol per line of source code
505  * is entered.
506  */
507 void
508 DEFUN (core_create_line_syms, (core_bfd), bfd * core_bfd)
509 {
510   char prev_name[PATH_MAX], prev_filename[PATH_MAX];
511   bfd_vma vma, min_vma = ~0, max_vma = 0;
512   bfd_vma offset, prev_offset, min_dist;
513   Sym *prev, dummy, *sentinel, *sym;
514   const char *filename;
515   int prev_line_num, i;
516   Sym_Table ltab;
517   /*
518    * Create symbols for functions as usual.  This is necessary in
519    * cases where parts of a program were not compiled with -g.  For
520    * those parts we still want to get info at the function level:
521    */
522   core_create_function_syms (core_bfd);
523
524   /* pass 1 - counter number of symbols: */
525
526   /*
527    * To find all line information, walk through all possible
528    * text-space addresses (one by one!) and get the debugging
529    * info for each address.  When the debugging info changes,
530    * it is time to create a new symbol.
531    *
532    * Of course, this is rather slow and it would be better if
533    * bfd would provide an iterator for enumerating all line
534    * infos, but for now, we try to speed up the second pass
535    * by determining what the minimum code distance between two
536    * lines is.
537    */
538   prev_name[0] = '\0';
539   ltab.len = 0;
540   min_dist = core_text_sect->_raw_size;
541   prev_offset = -min_dist;
542   prev_filename[0] = '\0';
543   prev_line_num = 0;
544   for (offset = 0; offset < core_text_sect->_raw_size; offset += MIN_INSN_SIZE)
545     {
546       vma = core_text_sect->vma + offset;
547       if (!get_src_info (vma, &filename, &dummy.name, &dummy.line_num)
548           || (prev_line_num == dummy.line_num &&
549               strcmp (prev_name, dummy.name) == 0
550               && strcmp (prev_filename, filename) == 0))
551         {
552           continue;
553         }
554
555       ++ltab.len;
556       prev_line_num = dummy.line_num;
557       strcpy (prev_name, dummy.name);
558       strcpy (prev_filename, filename);
559
560       if (offset - prev_offset < min_dist)
561         {
562           min_dist = offset - prev_offset;
563         }
564       prev_offset = offset;
565
566       min_vma = MIN (vma, min_vma);
567       max_vma = MAX (vma, max_vma);
568     }
569
570   DBG (AOUTDEBUG, printf ("[core_create_line_syms] min_dist=%lx\n", min_dist));
571
572   /* make room for function symbols, too: */
573   ltab.len += symtab.len;
574   ltab.base = (Sym *) xmalloc (ltab.len * sizeof (Sym));
575   ltab.limit = ltab.base;
576
577   /* pass 2 - create symbols: */
578
579   prev = 0;
580   for (offset = 0; offset < core_text_sect->_raw_size; offset += min_dist)
581     {
582       sym_init (ltab.limit);
583       if (!get_src_info (core_text_sect->vma + offset, &filename,
584                          &ltab.limit->name, &ltab.limit->line_num)
585           || (prev && prev->line_num == ltab.limit->line_num
586               && strcmp (prev->name, ltab.limit->name) == 0
587               && strcmp (prev->file->name, filename) == 0))
588         {
589           continue;
590         }
591
592       /* make name pointer a malloc'ed string: */
593       ltab.limit->name = xstrdup (ltab.limit->name);
594       ltab.limit->file = source_file_lookup_path (filename);
595
596       ltab.limit->addr = core_text_sect->vma + offset;
597       prev = ltab.limit;
598
599       /*
600        * If we see "main" without an initial '_', we assume names
601        * are *not* prefixed by '_'.
602        */
603       if (ltab.limit->name[0] == 'm' && discard_underscores
604           && strcmp (ltab.limit->name, "main") == 0)
605         {
606           discard_underscores = 0;
607         }
608
609       DBG (AOUTDEBUG, printf ("[core_create_line_syms] %d %s 0x%lx\n",
610                               ltab.len, ltab.limit->name,
611                               ltab.limit->addr));
612       ++ltab.limit;
613     }
614
615   /* update sentinels: */
616
617   sentinel = sym_lookup (&symtab, 0);
618   if (strcmp (sentinel->name, "<locore>") == 0
619       && min_vma <= sentinel->end_addr)
620     {
621       sentinel->end_addr = min_vma - 1;
622     }
623
624   sentinel = sym_lookup (&symtab, ~0);
625   if (strcmp (sentinel->name, "<hicore>") == 0 && max_vma >= sentinel->addr)
626     {
627       sentinel->addr = max_vma + 1;
628     }
629
630   /* copy in function symbols: */
631   memcpy (ltab.limit, symtab.base, symtab.len * sizeof (Sym));
632   ltab.limit += symtab.len;
633
634   if (ltab.limit - ltab.base != ltab.len)
635     {
636       fprintf (stderr,
637                "%s: somebody miscounted: ltab.len=%ld instead of %d\n",
638                whoami, (long) (ltab.limit - ltab.base), ltab.len);
639       done (1);
640     }
641
642   /* finalize ltab and make it symbol table: */
643
644   symtab_finalize (&ltab);
645   free (symtab.base);
646   symtab = ltab;
647
648   /* now go through all core symbols and set is_static accordingly: */
649
650   for (i = 0; i < core_num_syms; ++i)
651     {
652       if (core_sym_class (core_syms[i]) == 't')
653         {
654           sym = sym_lookup (&symtab, core_syms[i]->value
655                             + core_syms[i]->section->vma);
656           do
657             {
658               sym++->is_static = TRUE;
659             }
660           while (sym->file == sym[-1].file &&
661                  strcmp (sym->name, sym[-1].name) == 0);
662         }
663     }
664
665 }