Sort sysdeps/powerpc/fpu/libm-test-ulps
[glibc.git] / elf / dl-profile.c
blobf7e99a09e96ccfe303145c4a3bf362948d18e276
1 /* Profiling of shared libraries.
2 Copyright (C) 1997-2004, 2006, 2009 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
5 Based on the BSD mcount implementation.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; if not, see
19 <http://www.gnu.org/licenses/>. */
21 #include <assert.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <inttypes.h>
25 #include <limits.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <ldsodefs.h>
31 #include <sys/gmon.h>
32 #include <sys/gmon_out.h>
33 #include <sys/mman.h>
34 #include <sys/param.h>
35 #include <sys/stat.h>
36 #include <atomic.h>
38 /* The LD_PROFILE feature has to be implemented different to the
39 normal profiling using the gmon/ functions. The problem is that an
40 arbitrary amount of processes simulataneously can be run using
41 profiling and all write the results in the same file. To provide
42 this mechanism one could implement a complicated mechanism to merge
43 the content of two profiling runs or one could extend the file
44 format to allow more than one data set. For the second solution we
45 would have the problem that the file can grow in size beyond any
46 limit and both solutions have the problem that the concurrency of
47 writing the results is a big problem.
49 Another much simpler method is to use mmap to map the same file in
50 all using programs and modify the data in the mmap'ed area and so
51 also automatically on the disk. Using the MAP_SHARED option of
52 mmap(2) this can be done without big problems in more than one
53 file.
55 This approach is very different from the normal profiling. We have
56 to use the profiling data in exactly the way they are expected to
57 be written to disk. But the normal format used by gprof is not usable
58 to do this. It is optimized for size. It writes the tags as single
59 bytes but this means that the following 32/64 bit values are
60 unaligned.
62 Therefore we use a new format. This will look like this
64 0 1 2 3 <- byte is 32 bit word
65 0000 g m o n
66 0004 *version* <- GMON_SHOBJ_VERSION
67 0008 00 00 00 00
68 000c 00 00 00 00
69 0010 00 00 00 00
71 0014 *tag* <- GMON_TAG_TIME_HIST
72 0018 ?? ?? ?? ??
73 ?? ?? ?? ?? <- 32/64 bit LowPC
74 0018+A ?? ?? ?? ??
75 ?? ?? ?? ?? <- 32/64 bit HighPC
76 0018+2*A *histsize*
77 001c+2*A *profrate*
78 0020+2*A s e c o
79 0024+2*A n d s \0
80 0028+2*A \0 \0 \0 \0
81 002c+2*A \0 \0 \0
82 002f+2*A s
84 0030+2*A ?? ?? ?? ?? <- Count data
85 ... ...
86 0030+2*A+K ?? ?? ?? ??
88 0030+2*A+K *tag* <- GMON_TAG_CG_ARC
89 0034+2*A+K *lastused*
90 0038+2*A+K ?? ?? ?? ??
91 ?? ?? ?? ?? <- FromPC#1
92 0038+3*A+K ?? ?? ?? ??
93 ?? ?? ?? ?? <- ToPC#1
94 0038+4*A+K ?? ?? ?? ?? <- Count#1
95 ... ... ...
96 0038+(2*(CN-1)+2)*A+(CN-1)*4+K ?? ?? ?? ??
97 ?? ?? ?? ?? <- FromPC#CGN
98 0038+(2*(CN-1)+3)*A+(CN-1)*4+K ?? ?? ?? ??
99 ?? ?? ?? ?? <- ToPC#CGN
100 0038+(2*CN+2)*A+(CN-1)*4+K ?? ?? ?? ?? <- Count#CGN
102 We put (for now?) no basic block information in the file since this would
103 introduce rase conditions among all the processes who want to write them.
105 `K' is the number of count entries which is computed as
107 textsize / HISTFRACTION
109 `CG' in the above table is the number of call graph arcs. Normally,
110 the table is sparse and the profiling code writes out only the those
111 entries which are really used in the program run. But since we must
112 not extend this table (the profiling file) we'll keep them all here.
113 So CN can be executed in advance as
115 MINARCS <= textsize*(ARCDENSITY/100) <= MAXARCS
117 Now the remaining question is: how to build the data structures we can
118 work with from this data. We need the from set and must associate the
119 froms with all the associated tos. We will do this by constructing this
120 data structures at the program start. To do this we'll simply visit all
121 entries in the call graph table and add it to the appropriate list. */
123 extern int __profile_frequency (void);
124 libc_hidden_proto (__profile_frequency)
126 /* We define a special type to address the elements of the arc table.
127 This is basically the `gmon_cg_arc_record' format but it includes
128 the room for the tag and it uses real types. */
129 struct here_cg_arc_record
131 uintptr_t from_pc;
132 uintptr_t self_pc;
133 uint32_t count;
134 } __attribute__ ((packed));
136 static struct here_cg_arc_record *data;
138 /* Nonzero if profiling is under way. */
139 static int running;
141 /* This is the number of entry which have been incorporated in the toset. */
142 static uint32_t narcs;
143 /* This is a pointer to the object representing the number of entries
144 currently in the mmaped file. At no point of time this has to be the
145 same as NARCS. If it is equal all entries from the file are in our
146 lists. */
147 static volatile uint32_t *narcsp;
150 struct here_fromstruct
152 struct here_cg_arc_record volatile *here;
153 uint16_t link;
156 static volatile uint16_t *tos;
158 static struct here_fromstruct *froms;
159 static uint32_t fromlimit;
160 static volatile uint32_t fromidx;
162 static uintptr_t lowpc;
163 static size_t textsize;
164 static unsigned int log_hashfraction;
168 /* Set up profiling data to profile object desribed by MAP. The output
169 file is found (or created) in OUTPUT_DIR. */
170 void
171 internal_function
172 _dl_start_profile (void)
174 char *filename;
175 int fd;
176 struct stat64 st;
177 const ElfW(Phdr) *ph;
178 ElfW(Addr) mapstart = ~((ElfW(Addr)) 0);
179 ElfW(Addr) mapend = 0;
180 char *hist, *cp;
181 size_t idx;
182 size_t tossize;
183 size_t fromssize;
184 uintptr_t highpc;
185 uint16_t *kcount;
186 size_t kcountsize;
187 struct gmon_hdr *addr = NULL;
188 off_t expected_size;
189 /* See profil(2) where this is described. */
190 int s_scale;
191 #define SCALE_1_TO_1 0x10000L
192 const char *errstr = NULL;
194 /* Compute the size of the sections which contain program code. */
195 for (ph = GL(dl_profile_map)->l_phdr;
196 ph < &GL(dl_profile_map)->l_phdr[GL(dl_profile_map)->l_phnum]; ++ph)
197 if (ph->p_type == PT_LOAD && (ph->p_flags & PF_X))
199 ElfW(Addr) start = (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1));
200 ElfW(Addr) end = ((ph->p_vaddr + ph->p_memsz + GLRO(dl_pagesize) - 1)
201 & ~(GLRO(dl_pagesize) - 1));
203 if (start < mapstart)
204 mapstart = start;
205 if (end > mapend)
206 mapend = end;
209 /* Now we can compute the size of the profiling data. This is done
210 with the same formulars as in `monstartup' (see gmon.c). */
211 running = 0;
212 lowpc = ROUNDDOWN (mapstart + GL(dl_profile_map)->l_addr,
213 HISTFRACTION * sizeof (HISTCOUNTER));
214 highpc = ROUNDUP (mapend + GL(dl_profile_map)->l_addr,
215 HISTFRACTION * sizeof (HISTCOUNTER));
216 textsize = highpc - lowpc;
217 kcountsize = textsize / HISTFRACTION;
218 if ((HASHFRACTION & (HASHFRACTION - 1)) == 0)
220 /* If HASHFRACTION is a power of two, mcount can use shifting
221 instead of integer division. Precompute shift amount.
223 This is a constant but the compiler cannot compile the
224 expression away since the __ffs implementation is not known
225 to the compiler. Help the compiler by precomputing the
226 usual cases. */
227 assert (HASHFRACTION == 2);
229 if (sizeof (*froms) == 8)
230 log_hashfraction = 4;
231 else if (sizeof (*froms) == 16)
232 log_hashfraction = 5;
233 else
234 log_hashfraction = __ffs (HASHFRACTION * sizeof (*froms)) - 1;
236 else
237 log_hashfraction = -1;
238 tossize = textsize / HASHFRACTION;
239 fromlimit = textsize * ARCDENSITY / 100;
240 if (fromlimit < MINARCS)
241 fromlimit = MINARCS;
242 if (fromlimit > MAXARCS)
243 fromlimit = MAXARCS;
244 fromssize = fromlimit * sizeof (struct here_fromstruct);
246 expected_size = (sizeof (struct gmon_hdr)
247 + 4 + sizeof (struct gmon_hist_hdr) + kcountsize
248 + 4 + 4 + fromssize * sizeof (struct here_cg_arc_record));
250 /* Create the gmon_hdr we expect or write. */
251 struct real_gmon_hdr
253 char cookie[4];
254 int32_t version;
255 char spare[3 * 4];
256 } gmon_hdr;
257 if (sizeof (gmon_hdr) != sizeof (struct gmon_hdr)
258 || (offsetof (struct real_gmon_hdr, cookie)
259 != offsetof (struct gmon_hdr, cookie))
260 || (offsetof (struct real_gmon_hdr, version)
261 != offsetof (struct gmon_hdr, version)))
262 abort ();
264 memcpy (&gmon_hdr.cookie[0], GMON_MAGIC, sizeof (gmon_hdr.cookie));
265 gmon_hdr.version = GMON_SHOBJ_VERSION;
266 memset (gmon_hdr.spare, '\0', sizeof (gmon_hdr.spare));
268 /* Create the hist_hdr we expect or write. */
269 struct real_gmon_hist_hdr
271 char *low_pc;
272 char *high_pc;
273 int32_t hist_size;
274 int32_t prof_rate;
275 char dimen[15];
276 char dimen_abbrev;
277 } hist_hdr;
278 if (sizeof (hist_hdr) != sizeof (struct gmon_hist_hdr)
279 || (offsetof (struct real_gmon_hist_hdr, low_pc)
280 != offsetof (struct gmon_hist_hdr, low_pc))
281 || (offsetof (struct real_gmon_hist_hdr, high_pc)
282 != offsetof (struct gmon_hist_hdr, high_pc))
283 || (offsetof (struct real_gmon_hist_hdr, hist_size)
284 != offsetof (struct gmon_hist_hdr, hist_size))
285 || (offsetof (struct real_gmon_hist_hdr, prof_rate)
286 != offsetof (struct gmon_hist_hdr, prof_rate))
287 || (offsetof (struct real_gmon_hist_hdr, dimen)
288 != offsetof (struct gmon_hist_hdr, dimen))
289 || (offsetof (struct real_gmon_hist_hdr, dimen_abbrev)
290 != offsetof (struct gmon_hist_hdr, dimen_abbrev)))
291 abort ();
293 hist_hdr.low_pc = (char *) mapstart;
294 hist_hdr.high_pc = (char *) mapend;
295 hist_hdr.hist_size = kcountsize / sizeof (HISTCOUNTER);
296 hist_hdr.prof_rate = __profile_frequency ();
297 if (sizeof (hist_hdr.dimen) >= sizeof ("seconds"))
299 memcpy (hist_hdr.dimen, "seconds", sizeof ("seconds"));
300 memset (hist_hdr.dimen + sizeof ("seconds"), '\0',
301 sizeof (hist_hdr.dimen) - sizeof ("seconds"));
303 else
304 strncpy (hist_hdr.dimen, "seconds", sizeof (hist_hdr.dimen));
305 hist_hdr.dimen_abbrev = 's';
307 /* First determine the output name. We write in the directory
308 OUTPUT_DIR and the name is composed from the shared objects
309 soname (or the file name) and the ending ".profile". */
310 filename = (char *) alloca (strlen (GLRO(dl_profile_output)) + 1
311 + strlen (GLRO(dl_profile)) + sizeof ".profile");
312 cp = __stpcpy (filename, GLRO(dl_profile_output));
313 *cp++ = '/';
314 __stpcpy (__stpcpy (cp, GLRO(dl_profile)), ".profile");
316 #ifdef O_NOFOLLOW
317 # define EXTRA_FLAGS | O_NOFOLLOW
318 #else
319 # define EXTRA_FLAGS
320 #endif
321 fd = __open (filename, O_RDWR | O_CREAT EXTRA_FLAGS, DEFFILEMODE);
322 if (fd == -1)
324 char buf[400];
325 int errnum;
327 /* We cannot write the profiling data so don't do anything. */
328 errstr = "%s: cannot open file: %s\n";
329 print_error:
330 errnum = errno;
331 if (fd != -1)
332 __close (fd);
333 _dl_error_printf (errstr, filename,
334 __strerror_r (errnum, buf, sizeof buf));
335 return;
338 if (__fxstat64 (_STAT_VER, fd, &st) < 0 || !S_ISREG (st.st_mode))
340 /* Not stat'able or not a regular file => don't use it. */
341 errstr = "%s: cannot stat file: %s\n";
342 goto print_error;
345 /* Test the size. If it does not match what we expect from the size
346 values in the map MAP we don't use it and warn the user. */
347 if (st.st_size == 0)
349 /* We have to create the file. */
350 char buf[GLRO(dl_pagesize)];
352 memset (buf, '\0', GLRO(dl_pagesize));
354 if (__lseek (fd, expected_size & ~(GLRO(dl_pagesize) - 1), SEEK_SET) == -1)
356 cannot_create:
357 errstr = "%s: cannot create file: %s\n";
358 goto print_error;
361 if (TEMP_FAILURE_RETRY (__libc_write (fd, buf, (expected_size
362 & (GLRO(dl_pagesize)
363 - 1))))
364 < 0)
365 goto cannot_create;
367 else if (st.st_size != expected_size)
369 __close (fd);
370 wrong_format:
372 if (addr != NULL)
373 __munmap ((void *) addr, expected_size);
375 _dl_error_printf ("%s: file is no correct profile data file for `%s'\n",
376 filename, GLRO(dl_profile));
377 return;
380 addr = (struct gmon_hdr *) __mmap (NULL, expected_size, PROT_READ|PROT_WRITE,
381 MAP_SHARED|MAP_FILE, fd, 0);
382 if (addr == (struct gmon_hdr *) MAP_FAILED)
384 errstr = "%s: cannot map file: %s\n";
385 goto print_error;
388 /* We don't need the file descriptor anymore. */
389 __close (fd);
391 /* Pointer to data after the header. */
392 hist = (char *) (addr + 1);
393 kcount = (uint16_t *) ((char *) hist + sizeof (uint32_t)
394 + sizeof (struct gmon_hist_hdr));
396 /* Compute pointer to array of the arc information. */
397 narcsp = (uint32_t *) ((char *) kcount + kcountsize + sizeof (uint32_t));
398 data = (struct here_cg_arc_record *) ((char *) narcsp + sizeof (uint32_t));
400 if (st.st_size == 0)
402 /* Create the signature. */
403 memcpy (addr, &gmon_hdr, sizeof (struct gmon_hdr));
405 *(uint32_t *) hist = GMON_TAG_TIME_HIST;
406 memcpy (hist + sizeof (uint32_t), &hist_hdr,
407 sizeof (struct gmon_hist_hdr));
409 narcsp[-1] = GMON_TAG_CG_ARC;
411 else
413 /* Test the signature in the file. */
414 if (memcmp (addr, &gmon_hdr, sizeof (struct gmon_hdr)) != 0
415 || *(uint32_t *) hist != GMON_TAG_TIME_HIST
416 || memcmp (hist + sizeof (uint32_t), &hist_hdr,
417 sizeof (struct gmon_hist_hdr)) != 0
418 || narcsp[-1] != GMON_TAG_CG_ARC)
419 goto wrong_format;
422 /* Allocate memory for the froms data and the pointer to the tos records. */
423 tos = (uint16_t *) calloc (tossize + fromssize, 1);
424 if (tos == NULL)
426 __munmap ((void *) addr, expected_size);
427 _dl_fatal_printf ("Out of memory while initializing profiler\n");
428 /* NOTREACHED */
431 froms = (struct here_fromstruct *) ((char *) tos + tossize);
432 fromidx = 0;
434 /* Now we have to process all the arc count entries. BTW: it is
435 not critical whether the *NARCSP value changes meanwhile. Before
436 we enter a new entry in to toset we will check that everything is
437 available in TOS. This happens in _dl_mcount.
439 Loading the entries in reverse order should help to get the most
440 frequently used entries at the front of the list. */
441 for (idx = narcs = MIN (*narcsp, fromlimit); idx > 0; )
443 size_t to_index;
444 size_t newfromidx;
445 --idx;
446 to_index = (data[idx].self_pc / (HASHFRACTION * sizeof (*tos)));
447 newfromidx = fromidx++;
448 froms[newfromidx].here = &data[idx];
449 froms[newfromidx].link = tos[to_index];
450 tos[to_index] = newfromidx;
453 /* Setup counting data. */
454 if (kcountsize < highpc - lowpc)
456 #if 0
457 s_scale = ((double) kcountsize / (highpc - lowpc)) * SCALE_1_TO_1;
458 #else
459 size_t range = highpc - lowpc;
460 size_t quot = range / kcountsize;
462 if (quot >= SCALE_1_TO_1)
463 s_scale = 1;
464 else if (quot >= SCALE_1_TO_1 / 256)
465 s_scale = SCALE_1_TO_1 / quot;
466 else if (range > ULONG_MAX / 256)
467 s_scale = (SCALE_1_TO_1 * 256) / (range / (kcountsize / 256));
468 else
469 s_scale = (SCALE_1_TO_1 * 256) / ((range * 256) / kcountsize);
470 #endif
472 else
473 s_scale = SCALE_1_TO_1;
475 /* Start the profiler. */
476 __profil ((void *) kcount, kcountsize, lowpc, s_scale);
478 /* Turn on profiling. */
479 running = 1;
483 void
484 _dl_mcount (ElfW(Addr) frompc, ElfW(Addr) selfpc)
486 volatile uint16_t *topcindex;
487 size_t i, fromindex;
488 struct here_fromstruct *fromp;
490 if (! running)
491 return;
493 /* Compute relative addresses. The shared object can be loaded at
494 any address. The value of frompc could be anything. We cannot
495 restrict it in any way, just set to a fixed value (0) in case it
496 is outside the allowed range. These calls show up as calls from
497 <external> in the gprof output. */
498 frompc -= lowpc;
499 if (frompc >= textsize)
500 frompc = 0;
501 selfpc -= lowpc;
502 if (selfpc >= textsize)
503 goto done;
505 /* Getting here we now have to find out whether the location was
506 already used. If yes we are lucky and only have to increment a
507 counter (this also has to be atomic). If the entry is new things
508 are getting complicated... */
510 /* Avoid integer divide if possible. */
511 if ((HASHFRACTION & (HASHFRACTION - 1)) == 0)
512 i = selfpc >> log_hashfraction;
513 else
514 i = selfpc / (HASHFRACTION * sizeof (*tos));
516 topcindex = &tos[i];
517 fromindex = *topcindex;
519 if (fromindex == 0)
520 goto check_new_or_add;
522 fromp = &froms[fromindex];
524 /* We have to look through the chain of arcs whether there is already
525 an entry for our arc. */
526 while (fromp->here->from_pc != frompc)
528 if (fromp->link != 0)
530 fromp = &froms[fromp->link];
531 while (fromp->link != 0 && fromp->here->from_pc != frompc);
533 if (fromp->here->from_pc != frompc)
535 topcindex = &fromp->link;
537 check_new_or_add:
538 /* Our entry is not among the entries we read so far from the
539 data file. Now see whether we have to update the list. */
540 while (narcs != *narcsp && narcs < fromlimit)
542 size_t to_index;
543 size_t newfromidx;
544 to_index = (data[narcs].self_pc
545 / (HASHFRACTION * sizeof (*tos)));
546 newfromidx = catomic_exchange_and_add (&fromidx, 1) + 1;
547 froms[newfromidx].here = &data[narcs];
548 froms[newfromidx].link = tos[to_index];
549 tos[to_index] = newfromidx;
550 catomic_increment (&narcs);
553 /* If we still have no entry stop searching and insert. */
554 if (*topcindex == 0)
556 uint_fast32_t newarc = catomic_exchange_and_add (narcsp, 1);
558 /* In rare cases it could happen that all entries in FROMS are
559 occupied. So we cannot count this anymore. */
560 if (newarc >= fromlimit)
561 goto done;
563 *topcindex = catomic_exchange_and_add (&fromidx, 1) + 1;
564 fromp = &froms[*topcindex];
566 fromp->here = &data[newarc];
567 data[newarc].from_pc = frompc;
568 data[newarc].self_pc = selfpc;
569 data[newarc].count = 0;
570 fromp->link = 0;
571 catomic_increment (&narcs);
573 break;
576 fromp = &froms[*topcindex];
578 else
579 /* Found in. */
580 break;
583 /* Increment the counter. */
584 catomic_increment (&fromp->here->count);
586 done:
589 INTDEF(_dl_mcount)