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 <locale.h>
29 #include <obstack.h>
30 #include <search.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <elf/ldsodefs.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_TEST        1
72
73 /* Definitions of arguments for argp functions.  */
74 static const struct argp_option options[] =
75 {
76   { NULL, 0, NULL, 0, N_("Output selection:") },
77   { "flat-profile", 'p', NULL, 0,
78     N_("generate flat profile with counts and ticks") },
79
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   FLAT_MODE = 1 << 0,
105
106   DEFAULT_MODE = FLAT_MODE
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
133 struct known_symbol
134 {
135   const char *name;
136   uintptr_t addr;
137   size_t size;
138
139   uintmax_t ticks;
140   uintmax_t calls;
141 };
142
143
144 struct shobj
145 {
146   const char *name;             /* User-provided name.  */
147
148   struct link_map *map;
149   const char *dynstrtab;        /* Dynamic string table of shared object.  */
150   const char *soname;           /* Soname of shared object.  */
151
152   uintptr_t lowpc;
153   uintptr_t highpc;
154   unsigned long int kcountsize;
155   size_t expected_size;         /* Expected size of profiling file.  */
156   size_t tossize;
157   size_t fromssize;
158   size_t fromlimit;
159   unsigned int hashfraction;
160   int s_scale;
161
162   void *symbol_map;
163   size_t symbol_mapsize;
164   const ElfW(Sym) *symtab;
165   size_t symtab_size;
166   const char *strtab;
167
168   struct obstack ob_str;
169   struct obstack ob_sym;
170 };
171
172
173 struct profdata
174 {
175   void *addr;
176   off_t size;
177
178   char *hist;
179   struct gmon_hist_hdr *hist_hdr;
180   uint16_t *kcount;
181   uint32_t narcs;               /* Number of arcs in toset.  */
182   struct here_cg_arc_record *data;
183   uint16_t *tos;
184   struct here_fromstruct *froms;
185 };
186
187 /* Search tree for symbols.  */
188 void *symroot;
189 static struct known_symbol **sortsym;
190 static size_t symidx;
191 static uintmax_t total_ticks;
192
193 /* Prototypes for local functions.  */
194 static struct shobj *load_shobj (const char *name);
195 static void unload_shobj (struct shobj *shobj);
196 static struct profdata *load_profdata (const char *name, struct shobj *shobj);
197 static void unload_profdata (struct profdata *profdata);
198 static void count_total_ticks (struct shobj *shobj, struct profdata *profdata);
199 static void count_calls (struct shobj *shobj, struct profdata *profdata);
200 static void read_symbols (struct shobj *shobj);
201 static void generate_flat_profile (struct profdata *profdata);
202
203
204 int
205 main (int argc, char *argv[])
206 {
207   const char *shobj;
208   const char *profdata;
209   struct shobj *shobj_handle;
210   struct profdata *profdata_handle;
211   int remaining;
212
213   setlocale (LC_ALL, "");
214
215   /* Initialize the message catalog.  */
216   textdomain (_libc_intl_domainname);
217
218   /* Parse and process arguments.  */
219   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
220
221   if (argc - remaining == 0 || argc - remaining > 2)
222     {
223       /* We need exactly two non-option parameter.  */
224       argp_help (&argp, stdout, ARGP_HELP_SEE | ARGP_HELP_EXIT_ERR,
225                  program_invocation_short_name);
226       exit (1);
227     }
228
229   /* Get parameters.  */
230   shobj = argv[remaining];
231   if (argc - remaining == 2)
232     profdata = argv[remaining + 1];
233   else
234     /* No filename for the profiling data given.  We will determine it
235        from the soname of the shobj, later.  */
236     profdata = NULL;
237
238   /* First see whether we can load the shared object.  */
239   shobj_handle = load_shobj (shobj);
240   if (shobj_handle == NULL)
241     exit (1);
242
243   /* We can now determine the filename for the profiling data, if
244      nececessary.  */
245   if (profdata == NULL)
246     {
247       char *newp;
248
249       if (shobj_handle->soname == NULL)
250         {
251           unload_shobj (shobj_handle);
252
253           error (EXIT_FAILURE, 0, _("\
254 no filename for profiling data given and shared object `%s' has no soname"),
255                  shobj);
256         }
257
258       newp = (char *) alloca (strlen (shobj_handle->soname)
259                               + sizeof ".profile");
260       stpcpy (stpcpy (newp, shobj_handle->soname), ".profile");
261       profdata = newp;
262     }
263
264   /* Now see whether the profiling data file matches the given object.   */
265   profdata_handle = load_profdata (profdata, shobj_handle);
266   if (profdata_handle == NULL)
267     {
268       unload_shobj (shobj_handle);
269
270       exit (1);
271     }
272
273   read_symbols (shobj_handle);
274
275   /* Count the ticks.  */
276   count_total_ticks (shobj_handle, profdata_handle);
277
278   /* Count the calls.  */
279   count_calls (shobj_handle, profdata_handle);
280
281   /* If no mode is specified fall back to the default mode.  */
282   if (mode == NONE)
283     mode = DEFAULT_MODE;
284
285   /* Do some work.  */
286   if (mode & FLAT_MODE)
287     generate_flat_profile (profdata_handle);
288
289   /* Free the resources.  */
290   unload_shobj (shobj_handle);
291   unload_profdata (profdata_handle);
292
293   return 0;
294 }
295
296
297 /* Handle program arguments.  */
298 static error_t
299 parse_opt (int key, char *arg, struct argp_state *state)
300 {
301   switch (key)
302     {
303     case OPT_TEST:
304       do_test = 1;
305       break;
306     default:
307       return ARGP_ERR_UNKNOWN;
308     }
309   return 0;
310 }
311
312
313 /* Print the version information.  */
314 static void
315 print_version (FILE *stream, struct argp_state *state)
316 {
317   fprintf (stream, "sprof (GNU %s) %s\n", PACKAGE, VERSION);
318   fprintf (stream, gettext ("\
319 Copyright (C) %s Free Software Foundation, Inc.\n\
320 This is free software; see the source for copying conditions.  There is NO\n\
321 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
322 "),
323            "1997, 1998");
324   fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
325 }
326
327
328 /* Note that we must not use `dlopen' etc.  The shobj object must not
329    be loaded for use.  */
330 static struct shobj *
331 load_shobj (const char *name)
332 {
333   struct link_map *map = NULL;
334   struct shobj *result;
335   ElfW(Addr) mapstart = ~((ElfW(Addr)) 0);
336   ElfW(Addr) mapend = 0;
337   const ElfW(Phdr) *ph;
338   size_t textsize;
339   unsigned int log_hashfraction;
340   ElfW(Ehdr) *ehdr;
341   int fd;
342   ElfW(Shdr) *shdr;
343   void *ptr;
344   size_t pagesize = getpagesize ();
345   const char *shstrtab;
346   int idx;
347   ElfW(Shdr) *symtab_entry;
348
349   /* Since we use dlopen() we must be prepared to work around the sometimes
350      strange lookup rules for the shared objects.  If we have a file foo.so
351      in the current directory and the user specfies foo.so on the command
352      line (without specifying a directory) we should load the file in the
353      current directory even if a normal dlopen() call would read the other
354      file.  We do this by adding a directory portion to the name.  */
355   if (strchr (name, '/') == NULL)
356     {
357       char *load_name = (char *) alloca (strlen (name) + 3);
358       stpcpy (stpcpy (load_name, "./"), name);
359
360       map = (struct link_map *) dlopen (load_name, RTLD_LAZY);
361     }
362   if (map == NULL)
363     {
364       map = (struct link_map *) dlopen (name, RTLD_LAZY);
365       if (map == NULL)
366         {
367           error (0, errno, _("failed to load shared object `%s'"), name);
368           return NULL;
369         }
370     }
371
372   /* Prepare the result.  */
373   result = (struct shobj *) calloc (1, sizeof (struct shobj));
374   if (result == NULL)
375     {
376       error (0, errno, _("cannot create internal descriptors"));
377       dlclose (map);
378       return NULL;
379     }
380   result->name = name;
381   result->map = map;
382
383   /* Compute the size of the sections which contain program code.
384      This must match the code in dl-profile.c (_dl_start_profile).  */
385   for (ph = map->l_phdr; ph < &map->l_phdr[map->l_phnum]; ++ph)
386     if (ph->p_type == PT_LOAD && (ph->p_flags & PF_X))
387       {
388         ElfW(Addr) start = (ph->p_vaddr & ~(pagesize - 1));
389         ElfW(Addr) end = ((ph->p_vaddr + ph->p_memsz + pagesize - 1)
390                           & ~(pagesize - 1));
391
392         if (start < mapstart)
393           mapstart = start;
394         if (end > mapend)
395           mapend = end;
396       }
397
398   result->lowpc = ROUNDDOWN ((uintptr_t) (mapstart + map->l_addr),
399                              HISTFRACTION * sizeof (HISTCOUNTER));
400   result->highpc = ROUNDUP ((uintptr_t) (mapend + map->l_addr),
401                             HISTFRACTION * sizeof (HISTCOUNTER));
402   if (do_test)
403     printf ("load addr: %0#*" PRIxPTR "\n"
404             "lower bound PC: %0#*" PRIxPTR "\n"
405             "upper bound PC: %0#*" PRIxPTR "\n",
406             __ELF_NATIVE_CLASS == 32 ? 10 : 18, map->l_addr,
407             __ELF_NATIVE_CLASS == 32 ? 10 : 18, result->lowpc,
408             __ELF_NATIVE_CLASS == 32 ? 10 : 18, result->highpc);
409
410   textsize = result->highpc - result->lowpc;
411   result->kcountsize = textsize / HISTFRACTION;
412   result->hashfraction = HASHFRACTION;
413   if ((HASHFRACTION & (HASHFRACTION - 1)) == 0)
414     /* If HASHFRACTION is a power of two, mcount can use shifting
415        instead of integer division.  Precompute shift amount.  */
416     log_hashfraction = __builtin_ffs (result->hashfraction
417                                       * sizeof (struct here_fromstruct)) - 1;
418   else
419     log_hashfraction = -1;
420   if (do_test)
421     printf ("hashfraction = %d\ndivider = %d\n",
422             result->hashfraction,
423             result->hashfraction * sizeof (struct here_fromstruct));
424   result->tossize = textsize / HASHFRACTION;
425   result->fromlimit = textsize * ARCDENSITY / 100;
426   if (result->fromlimit < MINARCS)
427     result->fromlimit = MINARCS;
428   if (result->fromlimit > MAXARCS)
429     result->fromlimit = MAXARCS;
430   result->fromssize = result->fromlimit * sizeof (struct here_fromstruct);
431
432   result->expected_size = (sizeof (struct gmon_hdr)
433                            + 4 + sizeof (struct gmon_hist_hdr)
434                            + result->kcountsize
435                            + 4 + 4
436                            + (result->fromssize
437                               * sizeof (struct here_cg_arc_record)));
438
439   if (do_test)
440     printf ("expected size: %Zd\n", result->expected_size);
441
442 #define SCALE_1_TO_1    0x10000L
443
444   if (result->kcountsize < result->highpc - result->lowpc)
445     {
446       size_t range = result->highpc - result->lowpc;
447       size_t quot = range / result->kcountsize;
448
449       if (quot >= SCALE_1_TO_1)
450         result->s_scale = 1;
451       else if (quot >= SCALE_1_TO_1 / 256)
452         result->s_scale = SCALE_1_TO_1 / quot;
453       else if (range > ULONG_MAX / 256)
454         result->s_scale = ((SCALE_1_TO_1 * 256)
455                            / (range / (result->kcountsize / 256)));
456       else
457         result->s_scale = ((SCALE_1_TO_1 * 256)
458                            / ((range * 256) / result->kcountsize));
459     }
460   else
461     result->s_scale = SCALE_1_TO_1;
462
463   if (do_test)
464     printf ("s_scale: %d\n", result->s_scale);
465
466   /* Determine the dynamic string table.  */
467   if (map->l_info[DT_STRTAB] == NULL)
468     result->dynstrtab = NULL;
469   else
470     result->dynstrtab = (const char *) (map->l_addr
471                                         + map->l_info[DT_STRTAB]->d_un.d_ptr);
472   if (do_test)
473     printf ("string table: %p\n", result->dynstrtab);
474
475   /* Determine the soname.  */
476   if (map->l_info[DT_SONAME] == NULL)
477     result->soname = NULL;
478   else
479     result->soname = result->dynstrtab + map->l_info[DT_SONAME]->d_un.d_val;
480   if (do_test)
481     printf ("soname: %s\n", result->soname);
482
483   /* Now we have to load the symbol table.
484
485      First load the section header table.  */
486   ehdr = (ElfW(Ehdr) *) map->l_addr;
487
488   /* Make sure we are on the right party.  */
489   if (ehdr->e_shentsize != sizeof (ElfW(Shdr)))
490     abort ();
491
492   /* And we need the shared object file descriptor again.  */
493   fd = open (map->l_name, O_RDONLY);
494   if (fd == -1)
495     /* Dooh, this really shouldn't happen.  We know the file is available.  */
496     error (EXIT_FAILURE, errno, _("Reopening shared object `%s' failed"));
497
498   /* Now map the section header.  */
499   ptr = mmap (NULL, (ehdr->e_shnum * sizeof (ElfW(Shdr))
500                      + (ehdr->e_shoff & (pagesize - 1))), PROT_READ,
501               MAP_SHARED|MAP_FILE, fd, ehdr->e_shoff & ~(pagesize - 1));
502   if (ptr == MAP_FAILED)
503     error (EXIT_FAILURE, errno, _("mapping of section headers failed"));
504   shdr = (ElfW(Shdr) *) ((char *) ptr + (ehdr->e_shoff & (pagesize - 1)));
505
506   /* Get the section header string table.  */
507   ptr = mmap (NULL, (shdr[ehdr->e_shstrndx].sh_size
508                      + (shdr[ehdr->e_shstrndx].sh_offset & (pagesize - 1))),
509               PROT_READ, MAP_SHARED|MAP_FILE, fd,
510               shdr[ehdr->e_shstrndx].sh_offset & ~(pagesize - 1));
511   if (ptr == MAP_FAILED)
512     error (EXIT_FAILURE, errno,
513            _("mapping of section header string table failed"));
514   shstrtab = ((const char *) ptr
515               + (shdr[ehdr->e_shstrndx].sh_offset & (pagesize - 1)));
516
517   /* Search for the ".symtab" section.  */
518   symtab_entry = NULL;
519   for (idx = 0; idx < ehdr->e_shnum; ++idx)
520     if (shdr[idx].sh_type == SHT_SYMTAB
521         && strcmp (shstrtab + shdr[idx].sh_name, ".symtab") == 0)
522       {
523         symtab_entry = &shdr[idx];
524         break;
525       }
526
527   /* We don't need the section header string table anymore.  */
528   munmap (ptr, (shdr[ehdr->e_shstrndx].sh_size
529                 + (shdr[ehdr->e_shstrndx].sh_offset & (pagesize - 1))));
530
531   if (symtab_entry == NULL)
532     {
533       fprintf (stderr, _("\
534 *** The file `%s' is stripped: no detailed analysis possible\n"),
535               name);
536       result->symtab = NULL;
537       result->strtab = NULL;
538     }
539   else
540     {
541       ElfW(Off) min_offset, max_offset;
542       ElfW(Shdr) *strtab_entry;
543
544       strtab_entry = &shdr[symtab_entry->sh_link];
545
546       /* Find the minimum and maximum offsets that include both the symbol
547          table and the string table.  */
548       if (symtab_entry->sh_offset < strtab_entry->sh_offset)
549         {
550           min_offset = symtab_entry->sh_offset & ~(pagesize - 1);
551           max_offset = strtab_entry->sh_offset + strtab_entry->sh_size;
552         }
553       else
554         {
555           min_offset = strtab_entry->sh_offset & ~(pagesize - 1);
556           max_offset = symtab_entry->sh_offset + symtab_entry->sh_size;
557         }
558
559       result->symbol_map = mmap (NULL, max_offset - min_offset,
560                                  PROT_READ, MAP_SHARED|MAP_FILE, fd,
561                                  min_offset);
562       if (result->symbol_map == NULL)
563         error (EXIT_FAILURE, errno, _("failed to load symbol data"));
564
565       result->symtab
566         = (const ElfW(Sym) *) ((const char *) result->symbol_map
567                                + (symtab_entry->sh_offset - min_offset));
568       result->symtab_size = symtab_entry->sh_size;
569       result->strtab = ((const char *) result->symbol_map
570                         + (strtab_entry->sh_offset - min_offset));
571       result->symbol_mapsize = max_offset - min_offset;
572     }
573
574   /* Now we also don't need the section header table anymore.  */
575   munmap ((char *) shdr - (ehdr->e_shoff & (pagesize - 1)),
576           (ehdr->e_phnum * sizeof (ElfW(Shdr))
577            + (ehdr->e_shoff & (pagesize - 1))));
578
579   /* Free the descriptor for the shared object.  */
580   close (fd);
581
582   return result;
583 }
584
585
586 static void
587 unload_shobj (struct shobj *shobj)
588 {
589   munmap (shobj->symbol_map, shobj->symbol_mapsize);
590   dlclose (shobj->map);
591 }
592
593
594 static struct profdata *
595 load_profdata (const char *name, struct shobj *shobj)
596 {
597   struct profdata *result;
598   int fd;
599   struct stat st;
600   void *addr;
601   struct gmon_hdr gmon_hdr;
602   struct gmon_hist_hdr hist_hdr;
603   uint32_t *narcsp;
604   size_t fromlimit;
605   struct here_cg_arc_record *data;
606   struct here_fromstruct *froms;
607   uint16_t *tos;
608   size_t fromidx;
609   size_t idx;
610
611   fd = open (name, O_RDONLY);
612   if (fd == -1)
613     {
614       char *ext_name;
615
616       if (errno != ENOENT || strchr (name, '/') != NULL)
617         /* The file exists but we are not allowed to read it or the
618            file does not exist and the name includes a path
619            specification..  */
620         return NULL;
621
622       /* A file with the given name does not exist in the current
623          directory, try it in the default location where the profiling
624          files are created.  */
625       ext_name = (char *) alloca (strlen (name) + sizeof "/var/tmp/");
626       stpcpy (stpcpy (ext_name, "/var/tmp/"), name);
627       name = ext_name;
628
629       fd = open (ext_name, O_RDONLY);
630       if (fd == -1)
631         {
632           /* Even this file does not exist.  */
633           error (0, errno, _("cannot load profiling data"));
634           return NULL;
635         }
636     }
637
638   /* We have found the file, now make sure it is the right one for the
639      data file.  */
640   if (fstat (fd, &st) < 0)
641     {
642       error (0, errno, _("while stat'ing profiling data file"));
643       close (fd);
644       return NULL;
645     }
646
647   if (st.st_size != shobj->expected_size)
648     {
649       error (0, 0, _("profiling data file `%s' does match shared object `%s'"),
650              name, shobj->name);
651       close (fd);
652       return NULL;
653     }
654
655   /* The data file is most probably the right one for our shared
656      object.  Map it now.  */
657   addr = mmap (NULL, st.st_size, PROT_READ, MAP_SHARED|MAP_FILE, fd, 0);
658   if (addr == MAP_FAILED)
659     {
660       error (0, errno, _("failed to mmap the profiling data file"));
661       close (fd);
662       return NULL;
663     }
664
665   /* We don't need the file desriptor anymore.  */
666   if (close (fd) < 0)
667     {
668       error (0, errno, _("error while closing the profiling data file"));
669       munmap (addr, st.st_size);
670       return NULL;
671     }
672
673   /* Prepare the result.  */
674   result = (struct profdata *) calloc (1, sizeof (struct profdata));
675   if (result == NULL)
676     {
677       error (0, errno, _("cannot create internal descriptor"));
678       munmap (addr, st.st_size);
679       return NULL;
680     }
681
682   /* Store the address and size so that we can later free the resources.  */
683   result->addr = addr;
684   result->size = st.st_size;
685
686   /* Pointer to data after the header.  */
687   result->hist = (char *) ((struct gmon_hdr *) addr + 1);
688   result->hist_hdr = (struct gmon_hist_hdr *) ((char *) result->hist
689                                                + sizeof (uint32_t));
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             *(char **) hist_hdr.low_pc, *(char **) 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_hdr, &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   size_t maxkidx = shobj->kcountsize;
779   size_t factor = 2 * (65536 / shobj->s_scale);
780   size_t kidx = 0;
781   size_t sidx = 0;
782
783   while (sidx < symidx)
784     {
785       uintptr_t start = sortsym[sidx]->addr;
786       uintptr_t end = start + sortsym[sidx]->size;
787
788       while (kidx < maxkidx && factor * kidx < start)
789         ++kidx;
790       if (kidx == maxkidx)
791         break;
792
793       while (kidx < maxkidx && factor * kidx < end)
794         sortsym[sidx]->ticks += kcount[kidx++];
795       if (kidx == maxkidx)
796         break;
797
798       total_ticks += sortsym[sidx++]->ticks;
799     }
800 }
801
802
803 static struct known_symbol *
804 find_symbol (uintptr_t addr)
805 {
806   size_t sidx = 0;
807
808   while (sidx < symidx)
809     {
810       uintptr_t start = sortsym[sidx]->addr;
811       uintptr_t end = start + sortsym[sidx]->size;
812
813       if (addr >= start && addr < end)
814         return sortsym[sidx];
815
816       if (addr < start)
817         break;
818
819       ++sidx;
820     }
821
822   return NULL;
823 }
824
825
826 static void
827 count_calls (struct shobj *shobj, struct profdata *profdata)
828 {
829   struct here_cg_arc_record *data = profdata->data;
830   uint32_t narcs = profdata->narcs;
831   uint32_t cnt;
832
833   for (cnt = 0; cnt < narcs; ++cnt)
834     {
835       uintptr_t here = data[cnt].self_pc;
836       struct known_symbol *symbol;
837
838       /* Find the symbol for this address.  */
839       symbol = find_symbol (here);
840       if (symbol != NULL)
841         symbol->calls += data[cnt].count;
842     }
843 }
844
845
846 static int
847 symorder (const void *o1, const void *o2)
848 {
849   const struct known_symbol *p1 = (struct known_symbol *) o1;
850   const struct known_symbol *p2 = (struct known_symbol *) o2;
851
852   return p1->addr - p2->addr;
853 }
854
855
856 static void
857 printsym (const void *node, VISIT value, int level)
858 {
859   if (value == leaf || value == postorder)
860     sortsym[symidx++] = *(struct known_symbol **) node;
861 }
862
863
864 static void
865 read_symbols (struct shobj *shobj)
866 {
867   void *load_addr = (void *) shobj->map->l_addr;
868   int n = 0;
869
870   /* Initialize the obstacks.  */
871 #define obstack_chunk_alloc malloc
872 #define obstack_chunk_free free
873   obstack_init (&shobj->ob_str);
874   obstack_init (&shobj->ob_sym);
875
876   /* Process the symbols.  */
877   if (shobj->symtab)
878     {
879       const ElfW(Sym) *sym = shobj->symtab;
880       const ElfW(Sym) *sym_end
881         = (const ElfW(Sym) *) ((const char *) sym + shobj->symtab_size);
882       for (; sym < sym_end; sym++)
883         if ((ELFW(ST_TYPE) (sym->st_info) == STT_FUNC
884              || ELFW(ST_TYPE) (sym->st_info) == STT_NOTYPE)
885             && sym->st_size != 0)
886           {
887             struct known_symbol **existp;
888             struct known_symbol *newsym
889               = (struct known_symbol *) obstack_alloc (&shobj->ob_sym,
890                                                        sizeof (*newsym));
891             if (newsym == NULL)
892               error (EXIT_FAILURE, errno, _("cannot allocate symbol data"));
893
894             newsym->name = &shobj->strtab[sym->st_name];
895             newsym->addr = sym->st_value;
896             newsym->size = sym->st_size;
897             newsym->ticks = 0;
898             newsym->calls = 0;
899
900             existp = tfind (newsym, &symroot, symorder);
901             if (existp == NULL)
902               {
903                 /* New function.  */
904                 tsearch (newsym, &symroot, symorder);
905                 ++n;
906               }
907             else
908               {
909                 /* The function is already defined.  See whether we have
910                    a better name here.  */
911                 if ((*existp)->name[0] == '_' && newsym->name[0] != '_')
912                   *existp = newsym;
913                 else
914                   /* We don't need the allocated memory.  */
915                   obstack_free (&shobj->ob_sym, newsym);
916               }
917           }
918     }
919   else
920     {
921       /* Blarg, the binary is stripped.  We have to rely on the
922          information contained in the dynamic section of the object.  */
923       const ElfW(Sym) *symtab = (load_addr
924                                  + shobj->map->l_info[DT_SYMTAB]->d_un.d_ptr);
925       const char *strtab = (load_addr
926                             + shobj->map->l_info[DT_STRTAB]->d_un.d_ptr);
927
928       /* We assume that the string table follows the symbol table,
929          because there is no way in ELF to know the size of the
930          dynamic symbol table!!  */
931       while ((void *) symtab < (void *) strtab)
932         {
933           if ((ELFW(ST_TYPE)(symtab->st_info) == STT_FUNC
934                || ELFW(ST_TYPE)(symtab->st_info) == STT_NOTYPE)
935               && symtab->st_size != 0)
936             {
937               struct known_symbol *newsym;
938               struct known_symbol **existp;
939
940               newsym =
941                 (struct known_symbol *) obstack_alloc (&shobj->ob_sym,
942                                                        sizeof (*newsym));
943               if (newsym == NULL)
944                 error (EXIT_FAILURE, errno, _("cannot allocate symbol data"));
945
946               newsym->name = &strtab[symtab->st_name];
947               newsym->addr = symtab->st_value;
948               newsym->size = symtab->st_size;
949               newsym->ticks = 0;
950
951               existp = tfind (newsym, &symroot, symorder);
952               if (existp == NULL)
953                 {
954                   /* New function.  */
955                   tsearch (newsym, &symroot, symorder);
956                   ++n;
957                 }
958               else
959                 {
960                   /* The function is already defined.  See whether we have
961                      a better name here.  */
962                   if ((*existp)->name[0] == '_' && newsym->name[0] != '_')
963                     *existp = newsym;
964                   else
965                     /* We don't need the allocated memory.  */
966                     obstack_free (&shobj->ob_sym, newsym);
967                 }
968             }
969         }
970
971       ++symtab;
972     }
973
974   sortsym = malloc (n * sizeof (struct known_symbol *));
975   if (sortsym == NULL)
976     abort ();
977
978   twalk (symroot, printsym);
979 }
980
981
982 static int
983 countorder (const void *p1, const void *p2)
984 {
985   struct known_symbol *s1 = (struct known_symbol *) p1;
986   struct known_symbol *s2 = (struct known_symbol *) p2;
987
988   if (s1->ticks != s2->ticks)
989     return (int) (s2->ticks - s1->ticks);
990
991   if (s1->calls != s2->calls)
992     return (int) (s2->calls - s1->calls);
993
994   return strcmp (s1->name, s2->name);
995 }
996
997
998 static double tick_unit;
999 static uintmax_t cumu_ticks;
1000
1001 static void
1002 printflat (const void *node, VISIT value, int level)
1003 {
1004   if (value == leaf || value == postorder)
1005     {
1006       struct known_symbol *s = *(struct known_symbol **) node;
1007
1008       cumu_ticks += s->ticks;
1009
1010       printf ("%6.2f%10.2f%9.2f%9" PRIdMAX "%9.2f%9.2f  %s\n",
1011               total_ticks ? (100.0 * s->ticks) / total_ticks : 0.0,
1012               tick_unit * cumu_ticks,
1013               tick_unit * s->ticks,
1014               s->calls,
1015               s->calls ? (s->ticks * 1000000) * tick_unit / s->calls : 0,
1016               0.0,      /* FIXME: don't know about called functions.  */
1017               s->name);
1018     }
1019 }
1020
1021
1022 /* ARGUSED */
1023 static void
1024 freenoop (void *p)
1025 {
1026 }
1027
1028
1029 static void
1030 generate_flat_profile (struct profdata *profdata)
1031 {
1032   size_t n;
1033   void *data = NULL;
1034
1035   tick_unit = 1.0 / *(uint32_t *) profdata->hist_hdr->prof_rate;
1036
1037   printf ("Flat profile:\n\n"
1038           "Each sample counts as %g %s.\n",
1039           tick_unit, profdata->hist_hdr->dimen);
1040   fputs ("  %   cumulative   self              self     total\n"
1041          " time   seconds   seconds    calls  us/call  us/call  name\n",
1042          stdout);
1043
1044   for (n = 0; n < symidx; ++n)
1045     if (sortsym[n]->calls != 0 || sortsym[n]->ticks != 0)
1046       tsearch (sortsym[n], &data, countorder);
1047
1048   twalk (data, printflat);
1049
1050   tdestroy (data, freenoop);
1051 }