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