Update.
[platform/upstream/glibc.git] / elf / sprof.c
1 /* Read and display shared object profiling data.
2    Copyright (C) 1997, 1998 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
5
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Library General Public License as
8    published by the Free Software Foundation; either version 2 of the
9    License, or (at your option) any later version.
10
11    The GNU C Library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Library General Public License for more details.
15
16    You should have received a copy of the GNU Library General Public
17    License along with the GNU C Library; see the file COPYING.LIB.  If not,
18    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 #include <argp.h>
22 #include <dlfcn.h>
23 #include <elf.h>
24 #include <error.h>
25 #include <fcntl.h>
26 #include <inttypes.h>
27 #include <libintl.h>
28 #include <link.h>
29 #include <locale.h>
30 #include <obstack.h>
31 #include <search.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <sys/gmon.h>
37 #include <sys/gmon_out.h>
38 #include <sys/mman.h>
39 #include <sys/param.h>
40 #include <sys/stat.h>
41
42 /* Undefine the following line line in the production version.  */
43 /* #define _NDEBUG 1 */
44 #include <assert.h>
45
46 /* Get libc version number.  */
47 #include "../version.h"
48
49 #define PACKAGE _libc_intl_domainname
50
51
52 #include <endian.h>
53 #if BYTE_ORDER == BIG_ENDIAN
54 #define byteorder ELFDATA2MSB
55 #define byteorder_name "big-endian"
56 #elif BYTE_ORDER == LITTLE_ENDIAN
57 #define byteorder ELFDATA2LSB
58 #define byteorder_name "little-endian"
59 #else
60 #error "Unknown BYTE_ORDER " BYTE_ORDER
61 #define byteorder ELFDATANONE
62 #endif
63
64
65 extern int __profile_frequency __P ((void));
66
67 /* Name and version of program.  */
68 static void print_version (FILE *stream, struct argp_state *state);
69 void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
70
71 #define OPT_COUNT_TOTAL 1
72 #define OPT_TEST 2
73
74 /* Definitions of arguments for argp functions.  */
75 static const struct argp_option options[] =
76 {
77   { NULL, 0, NULL, 0, N_("Output selection:") },
78   { "count-total", OPT_COUNT_TOTAL, NULL, 0,
79     N_("print number of invocations for each function") },
80   { "test", OPT_TEST, NULL, OPTION_HIDDEN, NULL },
81   { NULL, 0, NULL, 0, NULL }
82 };
83
84 /* Short description of program.  */
85 static const char doc[] = N_("Read and display shared object profiling data");
86
87 /* Strings for arguments in help texts.  */
88 static const char args_doc[] = N_("SHOBJ [PROFDATA]");
89
90 /* Prototype for option handler.  */
91 static error_t parse_opt (int key, char *arg, struct argp_state *state);
92
93 /* Data structure to communicate with argp functions.  */
94 static struct argp argp =
95 {
96   options, parse_opt, args_doc, doc, NULL, NULL
97 };
98
99
100 /* Operation modes.  */
101 static enum
102 {
103   NONE = 0,
104   COUNT_TOTAL
105 } mode;
106
107 /* If nonzero the total number of invocations of a function is emitted.  */
108 int count_total;
109
110 /* Nozero for testing.  */
111 int do_test;
112
113 /* Strcuture describing calls.  */
114 struct here_fromstruct
115   {
116     struct here_cg_arc_record volatile *here;
117     uint16_t link;
118   };
119
120 /* We define a special type to address the elements of the arc table.
121    This is basically the `gmon_cg_arc_record' format but it includes
122    the room for the tag and it uses real types.  */
123 struct here_cg_arc_record
124   {
125     uintptr_t from_pc;
126     uintptr_t self_pc;
127     uint32_t count;
128   } __attribute__ ((packed));
129
130
131 struct known_symbol
132 {
133   const char *name;
134   uintptr_t addr;
135   size_t size;
136
137   uintmax_t ticks;
138 };
139
140
141 struct shobj
142 {
143   const char *name;             /* User-provided name.  */
144
145   struct link_map *map;
146   const char *dynstrtab;        /* Dynamic string table of shared object.  */
147   const char *soname;           /* Soname of shared object.  */
148
149   uintptr_t lowpc;
150   uintptr_t highpc;
151   unsigned long int kcountsize;
152   size_t expected_size;         /* Expected size of profiling file.  */
153   size_t tossize;
154   size_t fromssize;
155   size_t fromlimit;
156   unsigned int hashfraction;
157   int s_scale;
158
159   void *symbol_map;
160   size_t symbol_mapsize;
161   const ElfW(Sym) *symtab;
162   size_t symtab_size;
163   const char *strtab;
164
165   struct obstack ob_str;
166   struct obstack ob_sym;
167 };
168
169
170 struct profdata
171 {
172   void *addr;
173   off_t size;
174
175   char *hist;
176   uint16_t *kcount;
177   uint32_t narcs;               /* Number of arcs in toset.  */
178   struct here_cg_arc_record *data;
179   uint16_t *tos;
180   struct here_fromstruct *froms;
181 };
182
183 /* Search tree for symbols.  */
184 void *symroot;
185 static struct known_symbol **sortsym;
186 static size_t symidx;
187 static uintmax_t total_ticks;
188
189 /* Prototypes for local functions.  */
190 static struct shobj *load_shobj (const char *name);
191 static void unload_shobj (struct shobj *shobj);
192 static struct profdata *load_profdata (const char *name, struct shobj *shobj);
193 static void unload_profdata (struct profdata *profdata);
194 static void count_total_ticks (struct shobj *shobj, struct profdata *profdata);
195 static void read_symbols (struct shobj *shobj);
196
197
198 int
199 main (int argc, char *argv[])
200 {
201   const char *shobj;
202   const char *profdata;
203   struct shobj *shobj_handle;
204   struct profdata *profdata_handle;
205   int remaining;
206
207   setlocale (LC_ALL, "");
208
209   /* Initialize the message catalog.  */
210   textdomain (_libc_intl_domainname);
211
212   /* Parse and process arguments.  */
213   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
214
215   if (argc - remaining == 0 || argc - remaining > 2)
216     {
217       /* We need exactly two non-option parameter.  */
218       argp_help (&argp, stdout, ARGP_HELP_SEE | ARGP_HELP_EXIT_ERR,
219                  program_invocation_short_name);
220       exit (1);
221     }
222
223   /* Get parameters.  */
224   shobj = argv[remaining];
225   if (argc - remaining == 2)
226     profdata = argv[remaining + 1];
227   else
228     /* No filename for the profiling data given.  We will determine it
229        from the soname of the shobj, later.  */
230     profdata = NULL;
231
232   /* First see whether we can load the shared object.  */
233   shobj_handle = load_shobj (shobj);
234   if (shobj_handle == NULL)
235     exit (1);
236
237   /* We can now determine the filename for the profiling data, if
238      nececessary.  */
239   if (profdata == NULL)
240     {
241       char *newp;
242
243       if (shobj_handle->soname == NULL)
244         {
245           unload_shobj (shobj_handle);
246
247           error (EXIT_FAILURE, 0, _("\
248 no filename for profiling data given and shared object `%s' has no soname"),
249                  shobj);
250         }
251
252       newp = (char *) alloca (strlen (shobj_handle->soname)
253                               + sizeof ".profile");
254       stpcpy (stpcpy (newp, shobj_handle->soname), ".profile");
255       profdata = newp;
256     }
257
258   /* Now see whether the profiling data file matches the given object.   */
259   profdata_handle = load_profdata (profdata, shobj_handle);
260   if (profdata_handle == NULL)
261     {
262       unload_shobj (shobj_handle);
263
264       exit (1);
265     }
266
267   read_symbols (shobj_handle);
268
269   /* Do some work.  */
270   switch (mode)
271     {
272     case COUNT_TOTAL:
273       count_total_ticks (shobj_handle, profdata_handle);
274       {
275         size_t n;
276         for (n = 0; n < symidx; ++n)
277           if (sortsym[n]->ticks != 0)
278             printf ("Name: %-30s, Ticks: %" PRIdMAX "\n", sortsym[n]->name,
279                     sortsym[n]->ticks);
280         printf ("Total ticks: %" PRIdMAX "\n", total_ticks);
281       }
282       break;
283     case NONE:
284       /* Do nothing.  */
285       break;
286     default:
287       assert (! "Internal error");
288     }
289
290   /* Free the resources.  */
291   unload_shobj (shobj_handle);
292   unload_profdata (profdata_handle);
293
294   return 0;
295 }
296
297
298 /* Handle program arguments.  */
299 static error_t
300 parse_opt (int key, char *arg, struct argp_state *state)
301 {
302   switch (key)
303     {
304     case OPT_COUNT_TOTAL:
305       mode = COUNT_TOTAL;
306       break;
307     case OPT_TEST:
308       do_test = 1;
309       break;
310     default:
311       return ARGP_ERR_UNKNOWN;
312     }
313   return 0;
314 }
315
316
317 /* Print the version information.  */
318 static void
319 print_version (FILE *stream, struct argp_state *state)
320 {
321   fprintf (stream, "sprof (GNU %s) %s\n", PACKAGE, VERSION);
322   fprintf (stream, gettext ("\
323 Copyright (C) %s Free Software Foundation, Inc.\n\
324 This is free software; see the source for copying conditions.  There is NO\n\
325 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
326 "),
327            "1997, 1998");
328   fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
329 }
330
331
332 /* Note that we must not use `dlopen' etc.  The shobj object must not
333    be loaded for use.  */
334 static struct shobj *
335 load_shobj (const char *name)
336 {
337   struct link_map *map = NULL;
338   struct shobj *result;
339   ElfW(Addr) mapstart = ~((ElfW(Addr)) 0);
340   ElfW(Addr) mapend = 0;
341   const ElfW(Phdr) *ph;
342   size_t textsize;
343   unsigned int log_hashfraction;
344   ElfW(Ehdr) *ehdr;
345   int fd;
346   ElfW(Shdr) *shdr;
347   void *ptr;
348   size_t pagesize = getpagesize ();
349   const char *shstrtab;
350   int idx;
351   ElfW(Shdr) *symtab_entry;
352
353   /* Since we use dlopen() we must be prepared to work around the sometimes
354      strange lookup rules for the shared objects.  If we have a file foo.so
355      in the current directory and the user specfies foo.so on the command
356      line (without specifying a directory) we should load the file in the
357      current directory even if a normal dlopen() call would read the other
358      file.  We do this by adding a directory portion to the name.  */
359   if (strchr (name, '/') == NULL)
360     {
361       char *load_name = (char *) alloca (strlen (name) + 3);
362       stpcpy (stpcpy (load_name, "./"), name);
363
364       map = (struct link_map *) dlopen (load_name, RTLD_LAZY);
365     }
366   if (map == NULL)
367     {
368       map = (struct link_map *) dlopen (name, RTLD_LAZY);
369       if (map == NULL)
370         {
371           error (0, errno, _("failed to load shared object `%s'"), name);
372           return NULL;
373         }
374     }
375
376   /* Prepare the result.  */
377   result = (struct shobj *) calloc (1, sizeof (struct shobj));
378   if (result == NULL)
379     {
380       error (0, errno, _("cannot create internal descriptors"));
381       dlclose (map);
382       return NULL;
383     }
384   result->name = name;
385   result->map = map;
386
387   /* Compute the size of the sections which contain program code.
388      This must match the code in dl-profile.c (_dl_start_profile).  */
389   for (ph = map->l_phdr; ph < &map->l_phdr[map->l_phnum]; ++ph)
390     if (ph->p_type == PT_LOAD && (ph->p_flags & PF_X))
391       {
392         ElfW(Addr) start = (ph->p_vaddr & ~(pagesize - 1));
393         ElfW(Addr) end = ((ph->p_vaddr + ph->p_memsz + pagesize - 1)
394                           & ~(pagesize - 1));
395
396         if (start < mapstart)
397           mapstart = start;
398         if (end > mapend)
399           mapend = end;
400       }
401
402   result->lowpc = ROUNDDOWN ((uintptr_t) (mapstart + map->l_addr),
403                              HISTFRACTION * sizeof (HISTCOUNTER));
404   result->highpc = ROUNDUP ((uintptr_t) (mapend + map->l_addr),
405                             HISTFRACTION * sizeof (HISTCOUNTER));
406   if (do_test)
407     printf ("load addr: %0#*" PRIxPTR "\n"
408             "lower bound PC: %0#*" PRIxPTR "\n"
409             "upper bound PC: %0#*" PRIxPTR "\n",
410             __ELF_NATIVE_CLASS == 32 ? 10 : 18, map->l_addr,
411             __ELF_NATIVE_CLASS == 32 ? 10 : 18, result->lowpc,
412             __ELF_NATIVE_CLASS == 32 ? 10 : 18, result->highpc);
413
414   textsize = result->highpc - result->lowpc;
415   result->kcountsize = textsize / HISTFRACTION;
416   result->hashfraction = HASHFRACTION;
417   if ((HASHFRACTION & (HASHFRACTION - 1)) == 0)
418     /* If HASHFRACTION is a power of two, mcount can use shifting
419        instead of integer division.  Precompute shift amount.  */
420     log_hashfraction = __builtin_ffs (result->hashfraction
421                                       * sizeof (struct here_fromstruct)) - 1;
422   else
423     log_hashfraction = -1;
424   if (do_test)
425     printf ("hashfraction = %d\ndivider = %d\n",
426             result->hashfraction,
427             result->hashfraction * sizeof (struct here_fromstruct));
428   result->tossize = textsize / HASHFRACTION;
429   result->fromlimit = textsize * ARCDENSITY / 100;
430   if (result->fromlimit < MINARCS)
431     result->fromlimit = MINARCS;
432   if (result->fromlimit > MAXARCS)
433     result->fromlimit = MAXARCS;
434   result->fromssize = result->fromlimit * sizeof (struct here_fromstruct);
435
436   result->expected_size = (sizeof (struct gmon_hdr)
437                            + 4 + sizeof (struct gmon_hist_hdr)
438                            + result->kcountsize
439                            + 4 + 4
440                            + (result->fromssize
441                               * sizeof (struct here_cg_arc_record)));
442
443   if (do_test)
444     printf ("expected size: %Zd\n", result->expected_size);
445
446 #define SCALE_1_TO_1    0x10000L
447
448   if (result->kcountsize < result->highpc - result->lowpc)
449     {
450       size_t range = result->highpc - result->lowpc;
451       size_t quot = range / result->kcountsize;
452
453       if (quot >= SCALE_1_TO_1)
454         result->s_scale = 1;
455       else if (quot >= SCALE_1_TO_1 / 256)
456         result->s_scale = SCALE_1_TO_1 / quot;
457       else if (range > ULONG_MAX / 256)
458         result->s_scale = ((SCALE_1_TO_1 * 256)
459                            / (range / (result->kcountsize / 256)));
460       else
461         result->s_scale = ((SCALE_1_TO_1 * 256)
462                            / ((range * 256) / result->kcountsize));
463     }
464   else
465     result->s_scale = SCALE_1_TO_1;
466
467   if (do_test)
468     printf ("s_scale: %d\n", result->s_scale);
469
470   /* Determine the dynamic string table.  */
471   if (map->l_info[DT_STRTAB] == NULL)
472     result->dynstrtab = NULL;
473   else
474     result->dynstrtab = (const char *) (map->l_addr
475                                         + map->l_info[DT_STRTAB]->d_un.d_ptr);
476   if (do_test)
477     printf ("string table: %p\n", result->dynstrtab);
478
479   /* Determine the soname.  */
480   if (map->l_info[DT_SONAME] == NULL)
481     result->soname = NULL;
482   else
483     result->soname = result->dynstrtab + map->l_info[DT_SONAME]->d_un.d_val;
484   if (do_test)
485     printf ("soname: %s\n", result->soname);
486
487   /* Now we have to load the symbol table.
488
489      First load the section header table.  */
490   ehdr = (ElfW(Ehdr) *) map->l_addr;
491
492   /* Make sure we are on the right party.  */
493   if (ehdr->e_shentsize != sizeof (ElfW(Shdr)))
494     abort ();
495
496   /* And we need the shared object file descriptor again.  */
497   fd = open (map->l_name, O_RDONLY);
498   if (fd == -1)
499     /* Dooh, this really shouldn't happen.  We know the file is available.  */
500     error (EXIT_FAILURE, errno, _("Reopening shared object `%s' failed"));
501
502   /* Now map the section header.  */
503   ptr = mmap (NULL, (ehdr->e_shnum * sizeof (ElfW(Shdr))
504                      + (ehdr->e_shoff & (pagesize - 1))), PROT_READ,
505               MAP_SHARED|MAP_FILE, fd, ehdr->e_shoff & ~(pagesize - 1));
506   if (ptr == MAP_FAILED)
507     error (EXIT_FAILURE, errno, _("mapping of section headers failed"));
508   shdr = (ElfW(Shdr) *) ((char *) ptr + (ehdr->e_shoff & (pagesize - 1)));
509
510   /* Get the section header string table.  */
511   ptr = mmap (NULL, (shdr[ehdr->e_shstrndx].sh_size
512                      + (shdr[ehdr->e_shstrndx].sh_offset & (pagesize - 1))),
513               PROT_READ, MAP_SHARED|MAP_FILE, fd,
514               shdr[ehdr->e_shstrndx].sh_offset & ~(pagesize - 1));
515   if (ptr == MAP_FAILED)
516     error (EXIT_FAILURE, errno,
517            _("mapping of section header string table failed"));
518   shstrtab = ((const char *) ptr
519               + (shdr[ehdr->e_shstrndx].sh_offset & (pagesize - 1)));
520
521   /* Search for the ".symtab" section.  */
522   symtab_entry = NULL;
523   for (idx = 0; idx < ehdr->e_shnum; ++idx)
524     if (shdr[idx].sh_type == SHT_SYMTAB
525         && strcmp (shstrtab + shdr[idx].sh_name, ".symtab") == 0)
526       {
527         symtab_entry = &shdr[idx];
528         break;
529       }
530
531   /* We don't need the section header string table anymore.  */
532   munmap (ptr, (shdr[ehdr->e_shstrndx].sh_size
533                 + (shdr[ehdr->e_shstrndx].sh_offset & (pagesize - 1))));
534
535   if (symtab_entry == NULL)
536     {
537       fprintf (stderr, _("\
538 *** The file `%s' is stripped: no detailed analysis possible\n"),
539               name);
540       result->symtab = NULL;
541       result->strtab = NULL;
542     }
543   else
544     {
545       ElfW(Off) min_offset, max_offset;
546       ElfW(Shdr) *strtab_entry;
547
548       strtab_entry = &shdr[symtab_entry->sh_link];
549
550       /* Find the minimum and maximum offsets that include both the symbol
551          table and the string table.  */
552       if (symtab_entry->sh_offset < strtab_entry->sh_offset)
553         {
554           min_offset = symtab_entry->sh_offset & ~(pagesize - 1);
555           max_offset = strtab_entry->sh_offset + strtab_entry->sh_size;
556         }
557       else
558         {
559           min_offset = strtab_entry->sh_offset & ~(pagesize - 1);
560           max_offset = symtab_entry->sh_offset + symtab_entry->sh_size;
561         }
562
563       result->symbol_map = mmap (NULL, max_offset - min_offset,
564                                  PROT_READ, MAP_SHARED|MAP_FILE, fd,
565                                  min_offset);
566       if (result->symbol_map == NULL)
567         error (EXIT_FAILURE, errno, _("failed to load symbol data"));
568
569       result->symtab
570         = (const ElfW(Sym) *) ((const char *) result->symbol_map
571                                + (symtab_entry->sh_offset - min_offset));
572       result->symtab_size = symtab_entry->sh_size;
573       result->strtab = ((const char *) result->symbol_map
574                         + (strtab_entry->sh_offset - min_offset));
575       result->symbol_mapsize = max_offset - min_offset;
576     }
577
578   /* Now we also don't need the section header table anymore.  */
579   munmap ((char *) shdr - (ehdr->e_shoff & (pagesize - 1)),
580           (ehdr->e_phnum * sizeof (ElfW(Shdr))
581            + (ehdr->e_shoff & (pagesize - 1))));
582
583   /* Free the descriptor for the shared object.  */
584   close (fd);
585
586   return result;
587 }
588
589
590 static void
591 unload_shobj (struct shobj *shobj)
592 {
593   munmap (shobj->symbol_map, shobj->symbol_mapsize);
594   dlclose (shobj->map);
595 }
596
597
598 static struct profdata *
599 load_profdata (const char *name, struct shobj *shobj)
600 {
601   struct profdata *result;
602   int fd;
603   struct stat st;
604   void *addr;
605   struct gmon_hdr gmon_hdr;
606   struct gmon_hist_hdr hist_hdr;
607   uint32_t *narcsp;
608   size_t fromlimit;
609   struct here_cg_arc_record *data;
610   struct here_fromstruct *froms;
611   uint16_t *tos;
612   size_t fromidx;
613   size_t idx;
614
615   fd = open (name, O_RDONLY);
616   if (fd == -1)
617     {
618       char *ext_name;
619
620       if (errno != ENOENT || strchr (name, '/') != NULL)
621         /* The file exists but we are not allowed to read it or the
622            file does not exist and the name includes a path
623            specification..  */
624         return NULL;
625
626       /* A file with the given name does not exist in the current
627          directory, try it in the default location where the profiling
628          files are created.  */
629       ext_name = (char *) alloca (strlen (name) + sizeof "/var/tmp/");
630       stpcpy (stpcpy (ext_name, "/var/tmp/"), name);
631       name = ext_name;
632
633       fd = open (ext_name, O_RDONLY);
634       if (fd == -1)
635         {
636           /* Even this file does not exist.  */
637           error (0, errno, _("cannot load profiling data"));
638           return NULL;
639         }
640     }
641
642   /* We have found the file, now make sure it is the right one for the
643      data file.  */
644   if (fstat (fd, &st) < 0)
645     {
646       error (0, errno, _("while stat'ing profiling data file"));
647       close (fd);
648       return NULL;
649     }
650
651   if (st.st_size != shobj->expected_size)
652     {
653       error (0, 0, _("profiling data file `%s' does match shared object `%s'"),
654              name, shobj->name);
655       close (fd);
656       return NULL;
657     }
658
659   /* The data file is most probably the right one for our shared
660      object.  Map it now.  */
661   addr = mmap (NULL, st.st_size, PROT_READ, MAP_SHARED|MAP_FILE, fd, 0);
662   if (addr == MAP_FAILED)
663     {
664       error (0, errno, _("failed to mmap the profiling data file"));
665       close (fd);
666       return NULL;
667     }
668
669   /* We don't need the file desriptor anymore.  */
670   if (close (fd) < 0)
671     {
672       error (0, errno, _("error while closing the profiling data file"));
673       munmap (addr, st.st_size);
674       return NULL;
675     }
676
677   /* Prepare the result.  */
678   result = (struct profdata *) calloc (1, sizeof (struct profdata));
679   if (result == NULL)
680     {
681       error (0, errno, _("cannot create internal descriptor"));
682       munmap (addr, st.st_size);
683       return NULL;
684     }
685
686   /* Store the address and size so that we can later free the resources.  */
687   result->addr = addr;
688   result->size = st.st_size;
689
690   /* Pointer to data after the header.  */
691   result->hist = (char *) ((struct gmon_hdr *) addr + 1);
692   result->kcount = (uint16_t *) ((char *) result->hist + sizeof (uint32_t)
693                                  + sizeof (struct gmon_hist_hdr));
694
695   /* Compute pointer to array of the arc information.  */
696   narcsp = (uint32_t *) ((char *) result->kcount + shobj->kcountsize
697                          + sizeof (uint32_t));
698   result->narcs = *narcsp;
699   result->data = (struct here_cg_arc_record *) ((char *) narcsp
700                                                 + sizeof (uint32_t));
701
702   /* Create the gmon_hdr we expect or write.  */
703   memset (&gmon_hdr, '\0', sizeof (struct gmon_hdr));
704   memcpy (&gmon_hdr.cookie[0], GMON_MAGIC, sizeof (gmon_hdr.cookie));
705   *(int32_t *) gmon_hdr.version = GMON_SHOBJ_VERSION;
706
707   /* Create the hist_hdr we expect or write.  */
708   *(char **) hist_hdr.low_pc = (char *) shobj->lowpc - shobj->map->l_addr;
709   *(char **) hist_hdr.high_pc = (char *) shobj->highpc - shobj->map->l_addr;
710   if (do_test)
711     printf ("low_pc = %p\nhigh_pc = %p\n",
712             hist_hdr.low_pc, hist_hdr.high_pc);
713   *(int32_t *) hist_hdr.hist_size = shobj->kcountsize / sizeof (HISTCOUNTER);
714   *(int32_t *) hist_hdr.prof_rate = __profile_frequency ();
715   strncpy (hist_hdr.dimen, "seconds", sizeof (hist_hdr.dimen));
716   hist_hdr.dimen_abbrev = 's';
717
718   /* Test whether the header of the profiling data is ok.  */
719   if (memcmp (addr, &gmon_hdr, sizeof (struct gmon_hdr)) != 0
720       || *(uint32_t *) result->hist != GMON_TAG_TIME_HIST
721       || memcmp (result->hist + sizeof (uint32_t), &hist_hdr,
722                  sizeof (struct gmon_hist_hdr)) != 0
723       || narcsp[-1] != GMON_TAG_CG_ARC)
724     {
725       free (result);
726       error (0, 0, _("`%s' is no correct profile data file for `%s'"),
727              name, shobj->name);
728       munmap (addr, st.st_size);
729       return NULL;
730     }
731
732   /* We are pretty sure now that this is a correct input file.  Set up
733      the remaining information in the result structure and return.  */
734   result->tos = (uint16_t *) calloc (shobj->tossize + shobj->fromssize, 1);
735   if (result->tos == NULL)
736     {
737       error (0, errno, _("cannot create internal descriptor"));
738       munmap (addr, st.st_size);
739       free (result);
740       return NULL;
741     }
742
743   result->froms = (struct here_fromstruct *) ((char *) result->tos
744                                               + shobj->tossize);
745   fromidx = 0;
746
747   /* Now we have to process all the arc count entries.  */
748   fromlimit = shobj->fromlimit;
749   data = result->data;
750   froms = result->froms;
751   tos = result->tos;
752   for (idx = 0; idx < MIN (*narcsp, fromlimit); ++idx)
753     {
754       size_t to_index;
755       size_t newfromidx;
756       to_index = (data[idx].self_pc / (shobj->hashfraction * sizeof (*tos)));
757       newfromidx = fromidx++;
758       froms[newfromidx].here = &data[idx];
759       froms[newfromidx].link = tos[to_index];
760       tos[to_index] = newfromidx;
761     }
762
763   return result;
764 }
765
766
767 static void
768 unload_profdata (struct profdata *profdata)
769 {
770   free (profdata->tos);
771   munmap (profdata->addr, profdata->size);
772   free (profdata);
773 }
774
775
776 static void
777 count_total_ticks (struct shobj *shobj, struct profdata *profdata)
778 {
779   volatile uint16_t *kcount = profdata->kcount;
780   size_t maxkidx = shobj->kcountsize;
781   size_t factor = 2 * (65536 / shobj->s_scale);
782   size_t kidx = 0;
783   size_t sidx = 0;
784
785   while (sidx < symidx)
786     {
787       uintptr_t start = sortsym[sidx]->addr;
788       uintptr_t end = start + sortsym[sidx]->size;
789
790       while (kidx < maxkidx && factor * kidx < start)
791         ++kidx;
792       if (kidx == maxkidx)
793         break;
794
795       while (kidx < maxkidx && factor * kidx < end)
796         sortsym[sidx]->ticks += kcount[kidx++];
797       if (kidx == maxkidx)
798         break;
799
800       total_ticks += sortsym[sidx++]->ticks;
801     }
802 }
803
804
805 static int
806 symorder (const void *o1, const void *o2)
807 {
808   const struct known_symbol *p1 = (struct known_symbol *) o1;
809   const struct known_symbol *p2 = (struct known_symbol *) o2;
810
811   return p1->addr - p2->addr;
812 }
813
814
815 static void
816 printsym (const void *node, VISIT value, int level)
817 {
818   if (value == leaf || value == postorder)
819     sortsym[symidx++] = *(struct known_symbol **) node;
820 }
821
822
823 static void
824 read_symbols (struct shobj *shobj)
825 {
826   void *load_addr = (void *) shobj->map->l_addr;
827   int n = 0;
828
829   /* Initialize the obstacks.  */
830 #define obstack_chunk_alloc malloc
831 #define obstack_chunk_free free
832   obstack_init (&shobj->ob_str);
833   obstack_init (&shobj->ob_sym);
834
835   /* Process the symbols.  */
836   if (shobj->symtab)
837     {
838       const ElfW(Sym) *sym = shobj->symtab;
839       const ElfW(Sym) *sym_end
840         = (const ElfW(Sym) *) ((const char *) sym + shobj->symtab_size);
841       for (; sym < sym_end; sym++)
842         if ((ELFW(ST_TYPE) (sym->st_info) == STT_FUNC
843              || ELFW(ST_TYPE) (sym->st_info) == STT_NOTYPE)
844             && sym->st_size != 0)
845           {
846             struct known_symbol *newsym
847               = (struct known_symbol *) obstack_alloc (&shobj->ob_sym,
848                                                        sizeof (*newsym));
849             if (newsym == NULL)
850               error (EXIT_FAILURE, errno, _("cannot allocate symbol data"));
851
852             newsym->name = &shobj->strtab[sym->st_name];
853             newsym->addr = sym->st_value;
854             newsym->size = sym->st_size;
855             newsym->ticks = 0;
856
857             tsearch (newsym, &symroot, symorder);
858             ++n;
859           }
860     }
861   else
862     {
863       /* Blarg, the binary is stripped.  We have to rely on the
864          information contained in the dynamic section of the object.  */
865       const ElfW(Sym) *symtab = (load_addr
866                                  + shobj->map->l_info[DT_SYMTAB]->d_un.d_ptr);
867       const char *strtab = (load_addr
868                             + shobj->map->l_info[DT_STRTAB]->d_un.d_ptr);
869
870       /* We assume that the string table follows the symbol table,
871          because there is no way in ELF to know the size of the
872          dynamic symbol table!!  */
873       while ((void *) symtab < (void *) strtab)
874         {
875           if (/*(ELFW(ST_TYPE)(symtab->st_info) == STT_FUNC
876                 || ELFW(ST_TYPE)(symtab->st_info) == STT_NOTYPE)
877                 &&*/ symtab->st_size != 0)
878             {
879               struct known_symbol *newsym;
880
881               newsym =
882                 (struct known_symbol *) obstack_alloc (&shobj->ob_sym,
883                                                        sizeof (*newsym));
884               if (newsym == NULL)
885                 error (EXIT_FAILURE, errno, _("cannot allocate symbol data"));
886
887               newsym->name = &strtab[symtab->st_name];
888               newsym->addr = symtab->st_value;
889               newsym->size = symtab->st_size;
890               newsym->ticks = 0;
891
892               tsearch (newsym, &symroot, symorder);
893               ++n;
894             }
895         }
896
897       ++symtab;
898     }
899
900   sortsym = malloc (n * sizeof (struct known_symbol *));
901   if (sortsym == NULL)
902     abort ();
903
904   twalk (symroot, printsym);
905 }