OSDN Git Service

This patch addresses the bogus "Invocation mismatch" messages seen in parallel
[pf3gnuchains/gcc-fork.git] / libgcc / libgcov.c
1 /* Routines required for instrumenting a program.  */
2 /* Compile this one with gcc.  */
3 /* Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4    2000, 2001, 2002, 2003, 2004, 2005, 2008, 2009, 2010, 2011
5    Free Software Foundation, Inc.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 Under Section 7 of GPL version 3, you are granted additional
20 permissions described in the GCC Runtime Library Exception, version
21 3.1, as published by the Free Software Foundation.
22
23 You should have received a copy of the GNU General Public License and
24 a copy of the GCC Runtime Library Exception along with this program;
25 see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
26 <http://www.gnu.org/licenses/>.  */
27
28 #include "tconfig.h"
29 #include "tsystem.h"
30 #include "coretypes.h"
31 #include "tm.h"
32 #include "libgcc_tm.h"
33 #include "gthr.h"
34
35 #if defined(inhibit_libc)
36 #define IN_LIBGCOV (-1)
37 #else
38 #define IN_LIBGCOV 1
39 #if defined(L_gcov)
40 #define GCOV_LINKAGE /* nothing */
41 #endif
42 #endif
43 #include "gcov-io.h"
44
45 #if defined(inhibit_libc)
46 /* If libc and its header files are not available, provide dummy functions.  */
47
48 #ifdef L_gcov
49 void __gcov_init (struct gcov_info *p __attribute__ ((unused))) {}
50 void __gcov_flush (void) {}
51 #endif
52
53 #ifdef L_gcov_reset
54 void __gcov_reset (void) {}
55 #endif
56
57 #ifdef L_gcov_dump
58 void __gcov_dump (void) {}
59 #endif
60
61 #ifdef L_gcov_merge_add
62 void __gcov_merge_add (gcov_type *counters  __attribute__ ((unused)),
63                        unsigned n_counters __attribute__ ((unused))) {}
64 #endif
65
66 #ifdef L_gcov_merge_single
67 void __gcov_merge_single (gcov_type *counters  __attribute__ ((unused)),
68                           unsigned n_counters __attribute__ ((unused))) {}
69 #endif
70
71 #ifdef L_gcov_merge_delta
72 void __gcov_merge_delta (gcov_type *counters  __attribute__ ((unused)),
73                          unsigned n_counters __attribute__ ((unused))) {}
74 #endif
75
76 #else
77
78 #include <string.h>
79 #if GCOV_LOCKED
80 #include <fcntl.h>
81 #include <errno.h>
82 #include <sys/stat.h>
83 #endif
84
85 extern void gcov_clear (void) ATTRIBUTE_HIDDEN;
86 extern void gcov_exit (void) ATTRIBUTE_HIDDEN;
87 extern int gcov_dump_complete ATTRIBUTE_HIDDEN;
88
89 #ifdef L_gcov
90 #include "gcov-io.c"
91
92 struct gcov_fn_buffer
93 {
94   struct gcov_fn_buffer *next;
95   unsigned fn_ix;
96   struct gcov_fn_info info;
97   /* note gcov_fn_info ends in a trailing array.  */
98 };
99
100 struct gcov_summary_buffer
101 {
102   struct gcov_summary_buffer *next;
103   struct gcov_summary summary;
104 };
105
106 /* Chain of per-object gcov structures.  */
107 static struct gcov_info *gcov_list;
108
109 /* Size of the longest file name. */
110 static size_t gcov_max_filename = 0;
111
112 /* Flag when the profile has already been dumped via __gcov_dump().  */
113 int gcov_dump_complete = 0;
114
115 /* Make sure path component of the given FILENAME exists, create
116    missing directories. FILENAME must be writable.
117    Returns zero on success, or -1 if an error occurred.  */
118
119 static int
120 create_file_directory (char *filename)
121 {
122 #if !defined(TARGET_POSIX_IO) && !defined(_WIN32)
123   (void) filename;
124   return -1;
125 #else
126   char *s;
127
128   s = filename;
129
130   if (HAS_DRIVE_SPEC(s))
131     s += 2;
132   if (IS_DIR_SEPARATOR(*s))
133     ++s;
134   for (; *s != '\0'; s++)
135     if (IS_DIR_SEPARATOR(*s))
136       {
137         char sep = *s;
138         *s  = '\0';
139
140         /* Try to make directory if it doesn't already exist.  */
141         if (access (filename, F_OK) == -1
142 #ifdef TARGET_POSIX_IO
143             && mkdir (filename, 0755) == -1
144 #else
145             && mkdir (filename) == -1
146 #endif
147             /* The directory might have been made by another process.  */
148             && errno != EEXIST)
149           {
150             fprintf (stderr, "profiling:%s:Cannot create directory\n",
151                      filename);
152             *s = sep;
153             return -1;
154           };
155
156         *s = sep;
157       };
158   return 0;
159 #endif
160 }
161
162 static struct gcov_fn_buffer *
163 free_fn_data (const struct gcov_info *gi_ptr, struct gcov_fn_buffer *buffer,
164               unsigned limit)
165 {
166   struct gcov_fn_buffer *next;
167   unsigned ix, n_ctr = 0;
168   
169   if (!buffer)
170     return 0;
171   next = buffer->next;
172
173   for (ix = 0; ix != limit; ix++)
174     if (gi_ptr->merge[ix])
175       free (buffer->info.ctrs[n_ctr++].values);
176   free (buffer);
177   return next;
178 }
179   
180 static struct gcov_fn_buffer **
181 buffer_fn_data (const char *filename, const struct gcov_info *gi_ptr,
182                 struct gcov_fn_buffer **end_ptr, unsigned fn_ix)
183 {
184   unsigned n_ctrs = 0, ix = 0;
185   struct gcov_fn_buffer *fn_buffer;
186   unsigned len;
187
188   for (ix = GCOV_COUNTERS; ix--;)
189     if (gi_ptr->merge[ix])
190       n_ctrs++;
191
192   len = sizeof (*fn_buffer) + sizeof (fn_buffer->info.ctrs[0]) * n_ctrs;
193   fn_buffer = (struct gcov_fn_buffer *)malloc (len);
194
195   if (!fn_buffer)
196     goto fail;
197   
198   fn_buffer->next = 0;
199   fn_buffer->fn_ix = fn_ix;
200   fn_buffer->info.ident = gcov_read_unsigned ();
201   fn_buffer->info.lineno_checksum = gcov_read_unsigned ();
202   fn_buffer->info.cfg_checksum = gcov_read_unsigned ();
203
204   for (n_ctrs = ix = 0; ix != GCOV_COUNTERS; ix++)
205     {
206       gcov_unsigned_t length;
207       gcov_type *values;
208
209       if (!gi_ptr->merge[ix])
210         continue;
211       
212       if (gcov_read_unsigned () != GCOV_TAG_FOR_COUNTER (ix))
213         {
214           len = 0;
215           goto fail;
216         }
217
218       length = GCOV_TAG_COUNTER_NUM (gcov_read_unsigned ());
219       len = length * sizeof (gcov_type);
220       values = (gcov_type *)malloc (len);
221       if (!values)
222         goto fail;
223       
224       fn_buffer->info.ctrs[n_ctrs].num = length;
225       fn_buffer->info.ctrs[n_ctrs].values = values;
226
227       while (length--)
228         *values++ = gcov_read_counter ();
229       n_ctrs++;
230     }
231   
232   *end_ptr = fn_buffer;
233   return &fn_buffer->next;
234
235  fail:
236   fprintf (stderr, "profiling:%s:Function %u %s %u \n", filename, fn_ix,
237            len ? "cannot allocate" : "counter mismatch", len ? len : ix);
238
239   return (struct gcov_fn_buffer **)free_fn_data (gi_ptr, fn_buffer, ix);
240 }
241
242 /* Add an unsigned value to the current crc */
243
244 static gcov_unsigned_t
245 crc32_unsigned (gcov_unsigned_t crc32, gcov_unsigned_t value)
246 {
247   unsigned ix;
248
249   for (ix = 32; ix--; value <<= 1)
250     {
251       unsigned feedback;
252
253       feedback = (value ^ crc32) & 0x80000000 ? 0x04c11db7 : 0;
254       crc32 <<= 1;
255       crc32 ^= feedback;
256     }
257
258   return crc32;
259 }
260
261 /* Check if VERSION of the info block PTR matches libgcov one.
262    Return 1 on success, or zero in case of versions mismatch.
263    If FILENAME is not NULL, its value used for reporting purposes
264    instead of value from the info block.  */
265
266 static int
267 gcov_version (struct gcov_info *ptr, gcov_unsigned_t version,
268               const char *filename)
269 {
270   if (version != GCOV_VERSION)
271     {
272       char v[4], e[4];
273
274       GCOV_UNSIGNED2STRING (v, version);
275       GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
276
277       fprintf (stderr,
278                "profiling:%s:Version mismatch - expected %.4s got %.4s\n",
279                filename? filename : ptr->filename, e, v);
280       return 0;
281     }
282   return 1;
283 }
284
285 /* Insert counter VALUE into HISTOGRAM.  */
286
287 static void
288 gcov_histogram_insert(gcov_bucket_type *histogram, gcov_type value)
289 {
290   unsigned i;
291
292   i = gcov_histo_index(value);
293   histogram[i].num_counters++;
294   histogram[i].cum_value += value;
295   if (value < histogram[i].min_value)
296     histogram[i].min_value = value;
297 }
298
299 /* Computes a histogram of the arc counters to place in the summary SUM.  */
300
301 static void
302 gcov_compute_histogram (struct gcov_summary *sum)
303 {
304   struct gcov_info *gi_ptr;
305   const struct gcov_fn_info *gfi_ptr;
306   const struct gcov_ctr_info *ci_ptr;
307   struct gcov_ctr_summary *cs_ptr;
308   unsigned t_ix, f_ix, ctr_info_ix, ix;
309   int h_ix;
310
311   /* This currently only applies to arc counters.  */
312   t_ix = GCOV_COUNTER_ARCS;
313
314   /* First check if there are any counts recorded for this counter.  */
315   cs_ptr = &(sum->ctrs[t_ix]);
316   if (!cs_ptr->num)
317     return;
318
319   for (h_ix = 0; h_ix < GCOV_HISTOGRAM_SIZE; h_ix++)
320     {
321       cs_ptr->histogram[h_ix].num_counters = 0;
322       cs_ptr->histogram[h_ix].min_value = cs_ptr->run_max;
323       cs_ptr->histogram[h_ix].cum_value = 0;
324     }
325
326   /* Walk through all the per-object structures and record each of
327      the count values in histogram.  */
328   for (gi_ptr = gcov_list; gi_ptr; gi_ptr = gi_ptr->next)
329     {
330       if (!gi_ptr->merge[t_ix])
331         continue;
332
333       /* Find the appropriate index into the gcov_ctr_info array
334          for the counter we are currently working on based on the
335          existence of the merge function pointer for this object.  */
336       for (ix = 0, ctr_info_ix = 0; ix < t_ix; ix++)
337         {
338           if (gi_ptr->merge[ix])
339             ctr_info_ix++;
340         }
341       for (f_ix = 0; f_ix != gi_ptr->n_functions; f_ix++)
342         {
343           gfi_ptr = gi_ptr->functions[f_ix];
344
345           if (!gfi_ptr || gfi_ptr->key != gi_ptr)
346             continue;
347
348           ci_ptr = &gfi_ptr->ctrs[ctr_info_ix];
349           for (ix = 0; ix < ci_ptr->num; ix++)
350             gcov_histogram_insert (cs_ptr->histogram, ci_ptr->values[ix]);
351         }
352     }
353 }
354
355 /* Dump the coverage counts. We merge with existing counts when
356    possible, to avoid growing the .da files ad infinitum. We use this
357    program's checksum to make sure we only accumulate whole program
358    statistics to the correct summary. An object file might be embedded
359    in two separate programs, and we must keep the two program
360    summaries separate.  */
361
362 void
363 gcov_exit (void)
364 {
365   struct gcov_info *gi_ptr;
366   const struct gcov_fn_info *gfi_ptr;
367   struct gcov_summary this_prg; /* summary for program.  */
368 #if !GCOV_LOCKED
369   struct gcov_summary all_prg;  /* summary for all instances of program.  */
370 #endif
371   struct gcov_ctr_summary *cs_ptr;
372   const struct gcov_ctr_info *ci_ptr;
373   unsigned t_ix;
374   int f_ix;
375   gcov_unsigned_t c_num;
376   const char *gcov_prefix;
377   int gcov_prefix_strip = 0;
378   size_t prefix_length;
379   char *gi_filename, *gi_filename_up;
380   gcov_unsigned_t crc32 = 0;
381
382   /* Prevent the counters from being dumped a second time on exit when the
383      application already wrote out the profile using __gcov_dump().  */
384   if (gcov_dump_complete)
385     return;
386
387 #if !GCOV_LOCKED
388   memset (&all_prg, 0, sizeof (all_prg));
389 #endif
390   /* Find the totals for this execution.  */
391   memset (&this_prg, 0, sizeof (this_prg));
392   for (gi_ptr = gcov_list; gi_ptr; gi_ptr = gi_ptr->next)
393     {
394       crc32 = crc32_unsigned (crc32, gi_ptr->stamp);
395       crc32 = crc32_unsigned (crc32, gi_ptr->n_functions);
396       
397       for (f_ix = 0; (unsigned)f_ix != gi_ptr->n_functions; f_ix++)
398         {
399           gfi_ptr = gi_ptr->functions[f_ix];
400
401           if (gfi_ptr && gfi_ptr->key != gi_ptr)
402             gfi_ptr = 0;
403           
404           crc32 = crc32_unsigned (crc32, gfi_ptr ? gfi_ptr->cfg_checksum : 0);
405           crc32 = crc32_unsigned (crc32,
406                                   gfi_ptr ? gfi_ptr->lineno_checksum : 0);
407           if (!gfi_ptr)
408             continue;
409
410           ci_ptr = gfi_ptr->ctrs;
411           for (t_ix = 0; t_ix != GCOV_COUNTERS_SUMMABLE; t_ix++)
412             {
413               if (!gi_ptr->merge[t_ix])
414                 continue;
415
416               cs_ptr = &this_prg.ctrs[t_ix];
417               cs_ptr->num += ci_ptr->num;
418               crc32 = crc32_unsigned (crc32, ci_ptr->num);
419               
420               for (c_num = 0; c_num < ci_ptr->num; c_num++)
421                 {
422                   cs_ptr->sum_all += ci_ptr->values[c_num];
423                   if (cs_ptr->run_max < ci_ptr->values[c_num])
424                     cs_ptr->run_max = ci_ptr->values[c_num];
425                 }
426               ci_ptr++;
427             }
428         }
429     }
430   gcov_compute_histogram (&this_prg);
431
432   {
433     /* Check if the level of dirs to strip off specified. */
434     char *tmp = getenv("GCOV_PREFIX_STRIP");
435     if (tmp)
436       {
437         gcov_prefix_strip = atoi (tmp);
438         /* Do not consider negative values. */
439         if (gcov_prefix_strip < 0)
440           gcov_prefix_strip = 0;
441       }
442   }
443
444   /* Get file name relocation prefix.  Non-absolute values are ignored. */
445   gcov_prefix = getenv("GCOV_PREFIX");
446   if (gcov_prefix)
447     {
448       prefix_length = strlen(gcov_prefix);
449
450       /* Remove an unnecessary trailing '/' */
451       if (IS_DIR_SEPARATOR (gcov_prefix[prefix_length - 1]))
452         prefix_length--;
453     }
454   else
455     prefix_length = 0;
456
457   /* If no prefix was specified and a prefix stip, then we assume
458      relative.  */
459   if (gcov_prefix_strip != 0 && prefix_length == 0)
460     {
461       gcov_prefix = ".";
462       prefix_length = 1;
463     }
464   /* Allocate and initialize the filename scratch space plus one.  */
465   gi_filename = (char *) alloca (prefix_length + gcov_max_filename + 2);
466   if (prefix_length)
467     memcpy (gi_filename, gcov_prefix, prefix_length);
468   gi_filename_up = gi_filename + prefix_length;
469
470   /* Now merge each file.  */
471   for (gi_ptr = gcov_list; gi_ptr; gi_ptr = gi_ptr->next)
472     {
473       unsigned n_counts;
474       struct gcov_summary prg; /* summary for this object over all
475                                   program.  */
476       struct gcov_ctr_summary *cs_prg, *cs_tprg;
477 #if !GCOV_LOCKED
478       struct gcov_ctr_summary *cs_all;
479 #endif
480       int error = 0;
481       gcov_unsigned_t tag, length;
482       gcov_position_t summary_pos = 0;
483       gcov_position_t eof_pos = 0;
484       const char *fname, *s;
485       struct gcov_fn_buffer *fn_buffer = 0;
486       struct gcov_fn_buffer **fn_tail = &fn_buffer;
487       struct gcov_summary_buffer *next_sum_buffer, *sum_buffer = 0;
488       struct gcov_summary_buffer **sum_tail = &sum_buffer;
489
490       fname = gi_ptr->filename;
491
492       /* Avoid to add multiple drive letters into combined path.  */
493       if (prefix_length != 0 && HAS_DRIVE_SPEC(fname))
494         fname += 2;
495
496       /* Build relocated filename, stripping off leading
497          directories from the initial filename if requested. */
498       if (gcov_prefix_strip > 0)
499         {
500           int level = 0;
501           s = fname;
502           if (IS_DIR_SEPARATOR(*s))
503             ++s;
504
505           /* Skip selected directory levels. */
506           for (; (*s != '\0') && (level < gcov_prefix_strip); s++)
507             if (IS_DIR_SEPARATOR(*s))
508               {
509                 fname = s;
510                 level++;
511               }
512         }
513
514       /* Update complete filename with stripped original. */
515       if (prefix_length != 0 && !IS_DIR_SEPARATOR (*fname))
516         {
517           /* If prefix is given, add directory separator.  */
518           strcpy (gi_filename_up, "/");
519           strcpy (gi_filename_up + 1, fname);
520         }
521       else
522         strcpy (gi_filename_up, fname);
523
524       if (!gcov_open (gi_filename))
525         {
526           /* Open failed likely due to missed directory.
527              Create directory and retry to open file. */
528           if (create_file_directory (gi_filename))
529             {
530               fprintf (stderr, "profiling:%s:Skip\n", gi_filename);
531               continue;
532             }
533           if (!gcov_open (gi_filename))
534             {
535               fprintf (stderr, "profiling:%s:Cannot open\n", gi_filename);
536               continue;
537             }
538         }
539
540       tag = gcov_read_unsigned ();
541       if (tag)
542         {
543           /* Merge data from file.  */
544           if (tag != GCOV_DATA_MAGIC)
545             {
546               fprintf (stderr, "profiling:%s:Not a gcov data file\n",
547                        gi_filename);
548               goto read_fatal;
549             }
550           length = gcov_read_unsigned ();
551           if (!gcov_version (gi_ptr, length, gi_filename))
552             goto read_fatal;
553
554           length = gcov_read_unsigned ();
555           if (length != gi_ptr->stamp)
556             /* Read from a different compilation. Overwrite the file.  */
557             goto rewrite;
558
559           /* Look for program summary.  */
560           for (f_ix = 0;;)
561             {
562               struct gcov_summary tmp;
563               
564               eof_pos = gcov_position ();
565               tag = gcov_read_unsigned ();
566               if (tag != GCOV_TAG_PROGRAM_SUMMARY)
567                 break;
568
569               f_ix--;
570               length = gcov_read_unsigned ();
571               gcov_read_summary (&tmp);
572               if ((error = gcov_is_error ()))
573                 goto read_error;
574               if (summary_pos)
575                 {
576                   /* Save all summaries after the one that will be
577                      merged into below. These will need to be rewritten
578                      as histogram merging may change the number of non-zero
579                      histogram entries that will be emitted, and thus the
580                      size of the merged summary.  */
581                   (*sum_tail) = (struct gcov_summary_buffer *)
582                       malloc (sizeof(struct gcov_summary_buffer));
583                   (*sum_tail)->summary = tmp;
584                   (*sum_tail)->next = 0;
585                   sum_tail = &((*sum_tail)->next);
586                   goto next_summary;
587                 }
588               if (tmp.checksum != crc32)
589                 goto next_summary;
590               
591               for (t_ix = 0; t_ix != GCOV_COUNTERS_SUMMABLE; t_ix++)
592                 if (tmp.ctrs[t_ix].num != this_prg.ctrs[t_ix].num)
593                   goto next_summary;
594               prg = tmp;
595               summary_pos = eof_pos;
596
597             next_summary:;
598             }
599           
600           /* Merge execution counts for each function.  */
601           for (f_ix = 0; (unsigned)f_ix != gi_ptr->n_functions;
602                f_ix++, tag = gcov_read_unsigned ())
603             {
604               gfi_ptr = gi_ptr->functions[f_ix];
605
606               if (tag != GCOV_TAG_FUNCTION)
607                 goto read_mismatch;
608
609               length = gcov_read_unsigned ();
610               if (!length)
611                 /* This function did not appear in the other program.
612                    We have nothing to merge.  */
613                 continue;
614
615               if (length != GCOV_TAG_FUNCTION_LENGTH)
616                 goto read_mismatch;
617               
618               if (!gfi_ptr || gfi_ptr->key != gi_ptr)
619                 {
620                   /* This function appears in the other program.  We
621                      need to buffer the information in order to write
622                      it back out -- we'll be inserting data before
623                      this point, so cannot simply keep the data in the
624                      file.  */
625                   fn_tail = buffer_fn_data (gi_filename,
626                                             gi_ptr, fn_tail, f_ix);
627                   if (!fn_tail)
628                     goto read_mismatch;
629                   continue;
630                 }
631
632               length = gcov_read_unsigned ();
633               if (length != gfi_ptr->ident)
634                 goto read_mismatch;
635               
636               length = gcov_read_unsigned ();
637               if (length != gfi_ptr->lineno_checksum)
638                 goto read_mismatch;
639               
640               length = gcov_read_unsigned ();
641               if (length != gfi_ptr->cfg_checksum)
642                 goto read_mismatch;
643               
644               ci_ptr = gfi_ptr->ctrs;
645               for (t_ix = 0; t_ix < GCOV_COUNTERS; t_ix++)
646                 {
647                   gcov_merge_fn merge = gi_ptr->merge[t_ix];
648
649                   if (!merge)
650                     continue;
651
652                   tag = gcov_read_unsigned ();
653                   length = gcov_read_unsigned ();
654                   if (tag != GCOV_TAG_FOR_COUNTER (t_ix)
655                       || length != GCOV_TAG_COUNTER_LENGTH (ci_ptr->num))
656                     goto read_mismatch;
657                   (*merge) (ci_ptr->values, ci_ptr->num);
658                   ci_ptr++;
659                 }
660               if ((error = gcov_is_error ()))
661                 goto read_error;
662             }
663
664           if (tag)
665             {
666             read_mismatch:;
667               fprintf (stderr, "profiling:%s:Merge mismatch for %s %u\n",
668                        gi_filename, f_ix >= 0 ? "function" : "summary",
669                        f_ix < 0 ? -1 - f_ix : f_ix);
670               goto read_fatal;
671             }
672         }
673       goto rewrite;
674
675     read_error:;
676       fprintf (stderr, "profiling:%s:%s merging\n", gi_filename,
677                error < 0 ? "Overflow": "Error");
678
679       goto read_fatal;
680
681     rewrite:;
682       gcov_rewrite ();
683       if (!summary_pos)
684         {
685           memset (&prg, 0, sizeof (prg));
686           summary_pos = eof_pos;
687         }
688
689       /* Merge the summaries.  */
690       for (t_ix = 0; t_ix < GCOV_COUNTERS_SUMMABLE; t_ix++)
691         {
692           cs_prg = &prg.ctrs[t_ix];
693           cs_tprg = &this_prg.ctrs[t_ix];
694
695           if (gi_ptr->merge[t_ix])
696             {
697               if (!cs_prg->runs++)
698                 cs_prg->num = cs_tprg->num;
699               cs_prg->sum_all += cs_tprg->sum_all;
700               if (cs_prg->run_max < cs_tprg->run_max)
701                 cs_prg->run_max = cs_tprg->run_max;
702               cs_prg->sum_max += cs_tprg->run_max;
703               if (cs_prg->runs == 1)
704                 memcpy (cs_prg->histogram, cs_tprg->histogram,
705                         sizeof (gcov_bucket_type) * GCOV_HISTOGRAM_SIZE);
706               else
707                 gcov_histogram_merge (cs_prg->histogram, cs_tprg->histogram);
708             }
709           else if (cs_prg->runs)
710             goto read_mismatch;
711
712 #if !GCOV_LOCKED
713           cs_all = &all_prg.ctrs[t_ix];
714           if (!cs_all->runs && cs_prg->runs)
715             {
716               cs_all->num = cs_prg->num;
717               cs_all->runs = cs_prg->runs;
718               cs_all->sum_all = cs_prg->sum_all;
719               cs_all->run_max = cs_prg->run_max;
720               cs_all->sum_max = cs_prg->sum_max;
721             }
722           else if (!all_prg.checksum
723                    /* Don't compare the histograms, which may have slight
724                       variations depending on the order they were updated
725                       due to the truncating integer divides used in the
726                       merge.  */
727                    && (cs_all->num != cs_prg->num
728                        || cs_all->runs != cs_prg->runs
729                        || cs_all->sum_all != cs_prg->sum_all
730                        || cs_all->run_max != cs_prg->run_max
731                        || cs_all->sum_max != cs_prg->sum_max))
732             {
733               fprintf (stderr,
734                        "profiling:%s:Data file mismatch - some data files may "
735                        "have been concurrently updated without locking support\n",
736                        gi_filename);
737               all_prg.checksum = ~0u;
738             }
739 #endif
740         }
741
742       prg.checksum = crc32;
743
744       /* Write out the data.  */
745       if (!eof_pos)
746         {
747           gcov_write_tag_length (GCOV_DATA_MAGIC, GCOV_VERSION);
748           gcov_write_unsigned (gi_ptr->stamp);
749         }
750
751       if (summary_pos)
752         gcov_seek (summary_pos);
753
754       /* Generate whole program statistics.  */
755       gcov_write_summary (GCOV_TAG_PROGRAM_SUMMARY, &prg);
756
757       /* Rewrite all the summaries that were after the summary we merged
758          into. This is necessary as the merged summary may have a different
759          size due to the number of non-zero histogram entries changing after
760          merging.  */
761       
762       while (sum_buffer)
763         {
764           gcov_write_summary (GCOV_TAG_PROGRAM_SUMMARY, &sum_buffer->summary);
765           next_sum_buffer = sum_buffer->next;
766           free (sum_buffer);
767           sum_buffer = next_sum_buffer;
768         }
769
770       /* Write execution counts for each function.  */
771       for (f_ix = 0; (unsigned)f_ix != gi_ptr->n_functions; f_ix++)
772         {
773           unsigned buffered = 0;
774
775           if (fn_buffer && fn_buffer->fn_ix == (unsigned)f_ix)
776             {
777               /* Buffered data from another program.  */
778               buffered = 1;
779               gfi_ptr = &fn_buffer->info;
780               length = GCOV_TAG_FUNCTION_LENGTH;
781             }
782           else
783             {
784               gfi_ptr = gi_ptr->functions[f_ix];
785               if (gfi_ptr && gfi_ptr->key == gi_ptr)
786                 length = GCOV_TAG_FUNCTION_LENGTH;
787               else
788                 length = 0;
789             }
790           
791           gcov_write_tag_length (GCOV_TAG_FUNCTION, length);
792           if (!length)
793             continue;
794           
795           gcov_write_unsigned (gfi_ptr->ident);
796           gcov_write_unsigned (gfi_ptr->lineno_checksum);
797           gcov_write_unsigned (gfi_ptr->cfg_checksum);
798
799           ci_ptr = gfi_ptr->ctrs;
800           for (t_ix = 0; t_ix < GCOV_COUNTERS; t_ix++)
801             {
802               if (!gi_ptr->merge[t_ix])
803                 continue;
804
805               n_counts = ci_ptr->num;
806               gcov_write_tag_length (GCOV_TAG_FOR_COUNTER (t_ix),
807                                      GCOV_TAG_COUNTER_LENGTH (n_counts));
808               gcov_type *c_ptr = ci_ptr->values;
809               while (n_counts--)
810                 gcov_write_counter (*c_ptr++);
811               ci_ptr++;
812             }
813           if (buffered)
814             fn_buffer = free_fn_data (gi_ptr, fn_buffer, GCOV_COUNTERS);
815         }
816
817       gcov_write_unsigned (0);
818
819     read_fatal:;
820       while (fn_buffer)
821         fn_buffer = free_fn_data (gi_ptr, fn_buffer, GCOV_COUNTERS);
822
823       if ((error = gcov_close ()))
824           fprintf (stderr, error  < 0 ?
825                    "profiling:%s:Overflow writing\n" :
826                    "profiling:%s:Error writing\n",
827                    gi_filename);
828     }
829 }
830
831 /* Reset all counters to zero.  */
832
833 void
834 gcov_clear (void)
835 {
836   const struct gcov_info *gi_ptr;
837
838   for (gi_ptr = gcov_list; gi_ptr; gi_ptr = gi_ptr->next)
839     {
840       unsigned f_ix;
841
842       for (f_ix = 0; f_ix < gi_ptr->n_functions; f_ix++)
843         {
844           unsigned t_ix;
845           const struct gcov_fn_info *gfi_ptr = gi_ptr->functions[f_ix];
846
847           if (!gfi_ptr || gfi_ptr->key != gi_ptr)
848             continue;
849           const struct gcov_ctr_info *ci_ptr = gfi_ptr->ctrs;
850           for (t_ix = 0; t_ix != GCOV_COUNTERS; t_ix++)
851             {
852               if (!gi_ptr->merge[t_ix])
853                 continue;
854               
855               memset (ci_ptr->values, 0, sizeof (gcov_type) * ci_ptr->num);
856               ci_ptr++;
857             }
858         }
859     }
860 }
861
862 /* Add a new object file onto the bb chain.  Invoked automatically
863    when running an object file's global ctors.  */
864
865 void
866 __gcov_init (struct gcov_info *info)
867 {
868   if (!info->version || !info->n_functions)
869     return;
870   if (gcov_version (info, info->version, 0))
871     {
872       size_t filename_length = strlen(info->filename);
873
874       /* Refresh the longest file name information */
875       if (filename_length > gcov_max_filename)
876         gcov_max_filename = filename_length;
877
878       if (!gcov_list)
879         atexit (gcov_exit);
880
881       info->next = gcov_list;
882       gcov_list = info;
883     }
884   info->version = 0;
885 }
886
887 #ifdef __GTHREAD_MUTEX_INIT
888 ATTRIBUTE_HIDDEN __gthread_mutex_t __gcov_flush_mx = __GTHREAD_MUTEX_INIT;
889 #define init_mx_once()
890 #else
891 __gthread_mutex_t __gcov_flush_mx ATTRIBUTE_HIDDEN;
892
893 static void
894 init_mx (void)
895 {
896   __GTHREAD_MUTEX_INIT_FUNCTION (&__gcov_flush_mx);
897 }
898 static void
899 init_mx_once (void)
900 {
901   static __gthread_once_t once = __GTHREAD_ONCE_INIT;
902   __gthread_once (&once, init_mx);
903 }
904 #endif
905
906 /* Called before fork or exec - write out profile information gathered so
907    far and reset it to zero.  This avoids duplication or loss of the
908    profile information gathered so far.  */
909
910 void
911 __gcov_flush (void)
912 {
913   init_mx_once ();
914   __gthread_mutex_lock (&__gcov_flush_mx);
915
916   gcov_exit ();
917   gcov_clear ();
918
919   __gthread_mutex_unlock (&__gcov_flush_mx);
920 }
921
922 #endif /* L_gcov */
923
924 #ifdef L_gcov_reset
925
926 /* Function that can be called from application to reset counters to zero,
927    in order to collect profile in region of interest.  */
928
929 void
930 __gcov_reset (void)
931 {
932   gcov_clear ();
933   /* Re-enable dumping to support collecting profile in multiple regions
934      of interest.  */
935   gcov_dump_complete = 0;
936 }
937
938 #endif /* L_gcov_reset */
939
940 #ifdef L_gcov_dump
941
942 /* Function that can be called from application to write profile collected
943    so far, in order to collect profile in region of interest.  */
944
945 void
946 __gcov_dump (void)
947 {
948   gcov_exit ();
949   /* Prevent profile from being dumped a second time on application exit.  */
950   gcov_dump_complete = 1;
951 }
952
953 #endif /* L_gcov_dump */
954
955 #ifdef L_gcov_merge_add
956 /* The profile merging function that just adds the counters.  It is given
957    an array COUNTERS of N_COUNTERS old counters and it reads the same number
958    of counters from the gcov file.  */
959 void
960 __gcov_merge_add (gcov_type *counters, unsigned n_counters)
961 {
962   for (; n_counters; counters++, n_counters--)
963     *counters += gcov_read_counter ();
964 }
965 #endif /* L_gcov_merge_add */
966
967 #ifdef L_gcov_merge_ior
968 /* The profile merging function that just adds the counters.  It is given
969    an array COUNTERS of N_COUNTERS old counters and it reads the same number
970    of counters from the gcov file.  */
971 void
972 __gcov_merge_ior (gcov_type *counters, unsigned n_counters)
973 {
974   for (; n_counters; counters++, n_counters--)
975     *counters |= gcov_read_counter ();
976 }
977 #endif
978
979 #ifdef L_gcov_merge_single
980 /* The profile merging function for choosing the most common value.
981    It is given an array COUNTERS of N_COUNTERS old counters and it
982    reads the same number of counters from the gcov file.  The counters
983    are split into 3-tuples where the members of the tuple have
984    meanings:
985
986    -- the stored candidate on the most common value of the measured entity
987    -- counter
988    -- total number of evaluations of the value  */
989 void
990 __gcov_merge_single (gcov_type *counters, unsigned n_counters)
991 {
992   unsigned i, n_measures;
993   gcov_type value, counter, all;
994
995   gcc_assert (!(n_counters % 3));
996   n_measures = n_counters / 3;
997   for (i = 0; i < n_measures; i++, counters += 3)
998     {
999       value = gcov_read_counter ();
1000       counter = gcov_read_counter ();
1001       all = gcov_read_counter ();
1002
1003       if (counters[0] == value)
1004         counters[1] += counter;
1005       else if (counter > counters[1])
1006         {
1007           counters[0] = value;
1008           counters[1] = counter - counters[1];
1009         }
1010       else
1011         counters[1] -= counter;
1012       counters[2] += all;
1013     }
1014 }
1015 #endif /* L_gcov_merge_single */
1016
1017 #ifdef L_gcov_merge_delta
1018 /* The profile merging function for choosing the most common
1019    difference between two consecutive evaluations of the value.  It is
1020    given an array COUNTERS of N_COUNTERS old counters and it reads the
1021    same number of counters from the gcov file.  The counters are split
1022    into 4-tuples where the members of the tuple have meanings:
1023
1024    -- the last value of the measured entity
1025    -- the stored candidate on the most common difference
1026    -- counter
1027    -- total number of evaluations of the value  */
1028 void
1029 __gcov_merge_delta (gcov_type *counters, unsigned n_counters)
1030 {
1031   unsigned i, n_measures;
1032   gcov_type value, counter, all;
1033
1034   gcc_assert (!(n_counters % 4));
1035   n_measures = n_counters / 4;
1036   for (i = 0; i < n_measures; i++, counters += 4)
1037     {
1038       /* last = */ gcov_read_counter ();
1039       value = gcov_read_counter ();
1040       counter = gcov_read_counter ();
1041       all = gcov_read_counter ();
1042
1043       if (counters[1] == value)
1044         counters[2] += counter;
1045       else if (counter > counters[2])
1046         {
1047           counters[1] = value;
1048           counters[2] = counter - counters[2];
1049         }
1050       else
1051         counters[2] -= counter;
1052       counters[3] += all;
1053     }
1054 }
1055 #endif /* L_gcov_merge_delta */
1056
1057 #ifdef L_gcov_interval_profiler
1058 /* If VALUE is in interval <START, START + STEPS - 1>, then increases the
1059    corresponding counter in COUNTERS.  If the VALUE is above or below
1060    the interval, COUNTERS[STEPS] or COUNTERS[STEPS + 1] is increased
1061    instead.  */
1062
1063 void
1064 __gcov_interval_profiler (gcov_type *counters, gcov_type value,
1065                           int start, unsigned steps)
1066 {
1067   gcov_type delta = value - start;
1068   if (delta < 0)
1069     counters[steps + 1]++;
1070   else if (delta >= steps)
1071     counters[steps]++;
1072   else
1073     counters[delta]++;
1074 }
1075 #endif
1076
1077 #ifdef L_gcov_pow2_profiler
1078 /* If VALUE is a power of two, COUNTERS[1] is incremented.  Otherwise
1079    COUNTERS[0] is incremented.  */
1080
1081 void
1082 __gcov_pow2_profiler (gcov_type *counters, gcov_type value)
1083 {
1084   if (value & (value - 1))
1085     counters[0]++;
1086   else
1087     counters[1]++;
1088 }
1089 #endif
1090
1091 /* Tries to determine the most common value among its inputs.  Checks if the
1092    value stored in COUNTERS[0] matches VALUE.  If this is the case, COUNTERS[1]
1093    is incremented.  If this is not the case and COUNTERS[1] is not zero,
1094    COUNTERS[1] is decremented.  Otherwise COUNTERS[1] is set to one and
1095    VALUE is stored to COUNTERS[0].  This algorithm guarantees that if this
1096    function is called more than 50% of the time with one value, this value
1097    will be in COUNTERS[0] in the end.
1098
1099    In any case, COUNTERS[2] is incremented.  */
1100
1101 static inline void
1102 __gcov_one_value_profiler_body (gcov_type *counters, gcov_type value)
1103 {
1104   if (value == counters[0])
1105     counters[1]++;
1106   else if (counters[1] == 0)
1107     {
1108       counters[1] = 1;
1109       counters[0] = value;
1110     }
1111   else
1112     counters[1]--;
1113   counters[2]++;
1114 }
1115
1116 #ifdef L_gcov_one_value_profiler
1117 void
1118 __gcov_one_value_profiler (gcov_type *counters, gcov_type value)
1119 {
1120   __gcov_one_value_profiler_body (counters, value);
1121 }
1122 #endif
1123
1124 #ifdef L_gcov_indirect_call_profiler
1125
1126 /* By default, the C++ compiler will use function addresses in the
1127    vtable entries.  Setting TARGET_VTABLE_USES_DESCRIPTORS to nonzero
1128    tells the compiler to use function descriptors instead.  The value
1129    of this macro says how many words wide the descriptor is (normally 2),
1130    but it may be dependent on target flags.  Since we do not have access
1131    to the target flags here we just check to see if it is set and use
1132    that to set VTABLE_USES_DESCRIPTORS to 0 or 1.
1133
1134    It is assumed that the address of a function descriptor may be treated
1135    as a pointer to a function.  */
1136
1137 #ifdef TARGET_VTABLE_USES_DESCRIPTORS
1138 #define VTABLE_USES_DESCRIPTORS 1
1139 #else
1140 #define VTABLE_USES_DESCRIPTORS 0
1141 #endif
1142
1143 /* Tries to determine the most common value among its inputs. */
1144 void
1145 __gcov_indirect_call_profiler (gcov_type* counter, gcov_type value,
1146                                void* cur_func, void* callee_func)
1147 {
1148   /* If the C++ virtual tables contain function descriptors then one
1149      function may have multiple descriptors and we need to dereference
1150      the descriptors to see if they point to the same function.  */
1151   if (cur_func == callee_func
1152       || (VTABLE_USES_DESCRIPTORS && callee_func
1153           && *(void **) cur_func == *(void **) callee_func))
1154     __gcov_one_value_profiler_body (counter, value);
1155 }
1156 #endif
1157
1158
1159 #ifdef L_gcov_average_profiler
1160 /* Increase corresponding COUNTER by VALUE.  FIXME: Perhaps we want
1161    to saturate up.  */
1162
1163 void
1164 __gcov_average_profiler (gcov_type *counters, gcov_type value)
1165 {
1166   counters[0] += value;
1167   counters[1] ++;
1168 }
1169 #endif
1170
1171 #ifdef L_gcov_ior_profiler
1172 /* Bitwise-OR VALUE into COUNTER.  */
1173
1174 void
1175 __gcov_ior_profiler (gcov_type *counters, gcov_type value)
1176 {
1177   *counters |= value;
1178 }
1179 #endif
1180
1181 #ifdef L_gcov_fork
1182 /* A wrapper for the fork function.  Flushes the accumulated profiling data, so
1183    that they are not counted twice.  */
1184
1185 pid_t
1186 __gcov_fork (void)
1187 {
1188   pid_t pid;
1189   extern __gthread_mutex_t __gcov_flush_mx;
1190   __gcov_flush ();
1191   pid = fork ();
1192   if (pid == 0)
1193     __GTHREAD_MUTEX_INIT_FUNCTION (&__gcov_flush_mx);
1194   return pid;
1195 }
1196 #endif
1197
1198 #ifdef L_gcov_execl
1199 /* A wrapper for the execl function.  Flushes the accumulated profiling data, so
1200    that they are not lost.  */
1201
1202 int
1203 __gcov_execl (const char *path, char *arg, ...)
1204 {
1205   va_list ap, aq;
1206   unsigned i, length;
1207   char **args;
1208
1209   __gcov_flush ();
1210
1211   va_start (ap, arg);
1212   va_copy (aq, ap);
1213
1214   length = 2;
1215   while (va_arg (ap, char *))
1216     length++;
1217   va_end (ap);
1218
1219   args = (char **) alloca (length * sizeof (void *));
1220   args[0] = arg;
1221   for (i = 1; i < length; i++)
1222     args[i] = va_arg (aq, char *);
1223   va_end (aq);
1224
1225   return execv (path, args);
1226 }
1227 #endif
1228
1229 #ifdef L_gcov_execlp
1230 /* A wrapper for the execlp function.  Flushes the accumulated profiling data, so
1231    that they are not lost.  */
1232
1233 int
1234 __gcov_execlp (const char *path, char *arg, ...)
1235 {
1236   va_list ap, aq;
1237   unsigned i, length;
1238   char **args;
1239
1240   __gcov_flush ();
1241
1242   va_start (ap, arg);
1243   va_copy (aq, ap);
1244
1245   length = 2;
1246   while (va_arg (ap, char *))
1247     length++;
1248   va_end (ap);
1249
1250   args = (char **) alloca (length * sizeof (void *));
1251   args[0] = arg;
1252   for (i = 1; i < length; i++)
1253     args[i] = va_arg (aq, char *);
1254   va_end (aq);
1255
1256   return execvp (path, args);
1257 }
1258 #endif
1259
1260 #ifdef L_gcov_execle
1261 /* A wrapper for the execle function.  Flushes the accumulated profiling data, so
1262    that they are not lost.  */
1263
1264 int
1265 __gcov_execle (const char *path, char *arg, ...)
1266 {
1267   va_list ap, aq;
1268   unsigned i, length;
1269   char **args;
1270   char **envp;
1271
1272   __gcov_flush ();
1273
1274   va_start (ap, arg);
1275   va_copy (aq, ap);
1276
1277   length = 2;
1278   while (va_arg (ap, char *))
1279     length++;
1280   va_end (ap);
1281
1282   args = (char **) alloca (length * sizeof (void *));
1283   args[0] = arg;
1284   for (i = 1; i < length; i++)
1285     args[i] = va_arg (aq, char *);
1286   envp = va_arg (aq, char **);
1287   va_end (aq);
1288
1289   return execve (path, args, envp);
1290 }
1291 #endif
1292
1293 #ifdef L_gcov_execv
1294 /* A wrapper for the execv function.  Flushes the accumulated profiling data, so
1295    that they are not lost.  */
1296
1297 int
1298 __gcov_execv (const char *path, char *const argv[])
1299 {
1300   __gcov_flush ();
1301   return execv (path, argv);
1302 }
1303 #endif
1304
1305 #ifdef L_gcov_execvp
1306 /* A wrapper for the execvp function.  Flushes the accumulated profiling data, so
1307    that they are not lost.  */
1308
1309 int
1310 __gcov_execvp (const char *path, char *const argv[])
1311 {
1312   __gcov_flush ();
1313   return execvp (path, argv);
1314 }
1315 #endif
1316
1317 #ifdef L_gcov_execve
1318 /* A wrapper for the execve function.  Flushes the accumulated profiling data, so
1319    that they are not lost.  */
1320
1321 int
1322 __gcov_execve (const char *path, char *const argv[], char *const envp[])
1323 {
1324   __gcov_flush ();
1325   return execve (path, argv, envp);
1326 }
1327 #endif
1328 #endif /* inhibit_libc */