]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/profile/GCDAProfiling.c
Update the device tree source files to a Linux 4.7-RC.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / profile / GCDAProfiling.c
1 /*===- GCDAProfiling.c - Support library for GCDA file emission -----------===*\
2 |*
3 |*                     The LLVM Compiler Infrastructure
4 |*
5 |* This file is distributed under the University of Illinois Open Source
6 |* License. See LICENSE.TXT for details.
7 |* 
8 |*===----------------------------------------------------------------------===*|
9 |* 
10 |* This file implements the call back routines for the gcov profiling
11 |* instrumentation pass. Link against this library when running code through
12 |* the -insert-gcov-profiling LLVM pass.
13 |*
14 |* We emit files in a corrupt version of GCOV's "gcda" file format. These files
15 |* are only close enough that LCOV will happily parse them. Anything that lcov
16 |* ignores is missing.
17 |*
18 |* TODO: gcov is multi-process safe by having each exit open the existing file
19 |* and append to it. We'd like to achieve that and be thread-safe too.
20 |*
21 \*===----------------------------------------------------------------------===*/
22
23 #include "InstrProfilingUtil.h"
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #if defined(_WIN32)
32 #include "WindowsMMap.h"
33 #else
34 #include <sys/mman.h>
35 #include <sys/file.h>
36 #endif
37
38 #define I386_FREEBSD (defined(__FreeBSD__) && defined(__i386__))
39
40 #if !defined(_MSC_VER) && !I386_FREEBSD
41 #include <stdint.h>
42 #endif
43
44 #if defined(_MSC_VER)
45 typedef unsigned char uint8_t;
46 typedef unsigned int uint32_t;
47 typedef unsigned long long uint64_t;
48 #elif I386_FREEBSD
49 /* System headers define 'size_t' incorrectly on x64 FreeBSD (prior to
50  * FreeBSD 10, r232261) when compiled in 32-bit mode.
51  */
52 typedef unsigned char uint8_t;
53 typedef unsigned int uint32_t;
54 typedef unsigned long long uint64_t;
55 #endif
56
57 /* #define DEBUG_GCDAPROFILING */
58
59 /*
60  * --- GCOV file format I/O primitives ---
61  */
62
63 /*
64  * The current file name we're outputting. Used primarily for error logging.
65  */
66 static char *filename = NULL;
67
68 /*
69  * The current file we're outputting.
70  */ 
71 static FILE *output_file = NULL;
72
73 /*
74  * Buffer that we write things into.
75  */
76 #define WRITE_BUFFER_SIZE (128 * 1024)
77 static char *write_buffer = NULL;
78 static uint64_t cur_buffer_size = 0;
79 static uint64_t cur_pos = 0;
80 static uint64_t file_size = 0;
81 static int new_file = 0;
82 static int fd = -1;
83
84 /*
85  * A list of functions to write out the data.
86  */
87 typedef void (*writeout_fn)();
88
89 struct writeout_fn_node {
90   writeout_fn fn;
91   struct writeout_fn_node *next;
92 };
93
94 static struct writeout_fn_node *writeout_fn_head = NULL;
95 static struct writeout_fn_node *writeout_fn_tail = NULL;
96
97 /*
98  *  A list of flush functions that our __gcov_flush() function should call.
99  */
100 typedef void (*flush_fn)();
101
102 struct flush_fn_node {
103   flush_fn fn;
104   struct flush_fn_node *next;
105 };
106
107 static struct flush_fn_node *flush_fn_head = NULL;
108 static struct flush_fn_node *flush_fn_tail = NULL;
109
110 static void resize_write_buffer(uint64_t size) {
111   if (!new_file) return;
112   size += cur_pos;
113   if (size <= cur_buffer_size) return;
114   size = (size - 1) / WRITE_BUFFER_SIZE + 1;
115   size *= WRITE_BUFFER_SIZE;
116   write_buffer = realloc(write_buffer, size);
117   cur_buffer_size = size;
118 }
119
120 static void write_bytes(const char *s, size_t len) {
121   resize_write_buffer(len);
122   memcpy(&write_buffer[cur_pos], s, len);
123   cur_pos += len;
124 }
125
126 static void write_32bit_value(uint32_t i) {
127   write_bytes((char*)&i, 4);
128 }
129
130 static void write_64bit_value(uint64_t i) {
131   write_bytes((char*)&i, 8);
132 }
133
134 static uint32_t length_of_string(const char *s) {
135   return (strlen(s) / 4) + 1;
136 }
137
138 static void write_string(const char *s) {
139   uint32_t len = length_of_string(s);
140   write_32bit_value(len);
141   write_bytes(s, strlen(s));
142   write_bytes("\0\0\0\0", 4 - (strlen(s) % 4));
143 }
144
145 static uint32_t read_32bit_value() {
146   uint32_t val;
147
148   if (new_file)
149     return (uint32_t)-1;
150
151   val = *(uint32_t*)&write_buffer[cur_pos];
152   cur_pos += 4;
153   return val;
154 }
155
156 static uint64_t read_64bit_value() {
157   uint64_t val;
158
159   if (new_file)
160     return (uint64_t)-1;
161
162   val = *(uint64_t*)&write_buffer[cur_pos];
163   cur_pos += 8;
164   return val;
165 }
166
167 static char *mangle_filename(const char *orig_filename) {
168   char *new_filename;
169   size_t filename_len, prefix_len;
170   int prefix_strip;
171   int level = 0;
172   const char *fname, *ptr;
173   const char *prefix = getenv("GCOV_PREFIX");
174   const char *prefix_strip_str = getenv("GCOV_PREFIX_STRIP");
175
176   if (prefix == NULL || prefix[0] == '\0')
177     return strdup(orig_filename);
178
179   if (prefix_strip_str) {
180     prefix_strip = atoi(prefix_strip_str);
181
182     /* Negative GCOV_PREFIX_STRIP values are ignored */
183     if (prefix_strip < 0)
184       prefix_strip = 0;
185   } else {
186     prefix_strip = 0;
187   }
188
189   fname = orig_filename;
190   for (level = 0, ptr = fname + 1; level < prefix_strip; ++ptr) {
191     if (*ptr == '\0')
192       break;
193     if (*ptr != '/')
194       continue;
195     fname = ptr;
196     ++level;
197   }
198
199   filename_len = strlen(fname);
200   prefix_len = strlen(prefix);
201   new_filename = malloc(prefix_len + 1 + filename_len + 1);
202   memcpy(new_filename, prefix, prefix_len);
203
204   if (prefix[prefix_len - 1] != '/')
205     new_filename[prefix_len++] = '/';
206   memcpy(new_filename + prefix_len, fname, filename_len + 1);
207
208   return new_filename;
209 }
210
211 static int map_file() {
212   fseek(output_file, 0L, SEEK_END);
213   file_size = ftell(output_file);
214
215   /* A size of 0 is invalid to `mmap'. Return a fail here, but don't issue an
216    * error message because it should "just work" for the user. */
217   if (file_size == 0)
218     return -1;
219
220   write_buffer = mmap(0, file_size, PROT_READ | PROT_WRITE,
221                       MAP_FILE | MAP_SHARED, fd, 0);
222   if (write_buffer == (void *)-1) {
223     int errnum = errno;
224     fprintf(stderr, "profiling: %s: cannot map: %s\n", filename,
225             strerror(errnum));
226     return -1;
227   }
228   return 0;
229 }
230
231 static void unmap_file() {
232   if (msync(write_buffer, file_size, MS_SYNC) == -1) {
233     int errnum = errno;
234     fprintf(stderr, "profiling: %s: cannot msync: %s\n", filename,
235             strerror(errnum));
236   }
237
238   /* We explicitly ignore errors from unmapping because at this point the data
239    * is written and we don't care.
240    */
241   (void)munmap(write_buffer, file_size);
242   write_buffer = NULL;
243   file_size = 0;
244 }
245
246 /*
247  * --- LLVM line counter API ---
248  */
249
250 /* A file in this case is a translation unit. Each .o file built with line
251  * profiling enabled will emit to a different file. Only one file may be
252  * started at a time.
253  */
254 void llvm_gcda_start_file(const char *orig_filename, const char version[4],
255                           uint32_t checksum) {
256   const char *mode = "r+b";
257   filename = mangle_filename(orig_filename);
258
259   /* Try just opening the file. */
260   new_file = 0;
261   fd = open(filename, O_RDWR);
262
263   if (fd == -1) {
264     /* Try opening the file, creating it if necessary. */
265     new_file = 1;
266     mode = "w+b";
267     fd = open(filename, O_RDWR | O_CREAT, 0644);
268     if (fd == -1) {
269       /* Try creating the directories first then opening the file. */
270       __llvm_profile_recursive_mkdir(filename);
271       fd = open(filename, O_RDWR | O_CREAT, 0644);
272       if (fd == -1) {
273         /* Bah! It's hopeless. */
274         int errnum = errno;
275         fprintf(stderr, "profiling: %s: cannot open: %s\n", filename,
276                 strerror(errnum));
277         return;
278       }
279     }
280   }
281
282   /* Try to flock the file to serialize concurrent processes writing out to the
283    * same GCDA. This can fail if the filesystem doesn't support it, but in that
284    * case we'll just carry on with the old racy behaviour and hope for the best.
285    */
286   flock(fd, LOCK_EX);
287   output_file = fdopen(fd, mode);
288
289   /* Initialize the write buffer. */
290   write_buffer = NULL;
291   cur_buffer_size = 0;
292   cur_pos = 0;
293
294   if (new_file) {
295     resize_write_buffer(WRITE_BUFFER_SIZE);
296     memset(write_buffer, 0, WRITE_BUFFER_SIZE);
297   } else {
298     if (map_file() == -1) {
299       /* mmap failed, try to recover by clobbering */
300       new_file = 1;
301       write_buffer = NULL;
302       cur_buffer_size = 0;
303       resize_write_buffer(WRITE_BUFFER_SIZE);
304       memset(write_buffer, 0, WRITE_BUFFER_SIZE);
305     }
306   }
307
308   /* gcda file, version, stamp checksum. */
309   write_bytes("adcg", 4);
310   write_bytes(version, 4);
311   write_32bit_value(checksum);
312
313 #ifdef DEBUG_GCDAPROFILING
314   fprintf(stderr, "llvmgcda: [%s]\n", orig_filename);
315 #endif
316 }
317
318 /* Given an array of pointers to counters (counters), increment the n-th one,
319  * where we're also given a pointer to n (predecessor).
320  */
321 void llvm_gcda_increment_indirect_counter(uint32_t *predecessor,
322                                           uint64_t **counters) {
323   uint64_t *counter;
324   uint32_t pred;
325
326   pred = *predecessor;
327   if (pred == 0xffffffff)
328     return;
329   counter = counters[pred];
330
331   /* Don't crash if the pred# is out of sync. This can happen due to threads,
332      or because of a TODO in GCOVProfiling.cpp buildEdgeLookupTable(). */
333   if (counter)
334     ++*counter;
335 #ifdef DEBUG_GCDAPROFILING
336   else
337     fprintf(stderr,
338             "llvmgcda: increment_indirect_counter counters=%08llx, pred=%u\n",
339             *counter, *predecessor);
340 #endif
341 }
342
343 void llvm_gcda_emit_function(uint32_t ident, const char *function_name,
344                              uint32_t func_checksum, uint8_t use_extra_checksum,
345                              uint32_t cfg_checksum) {
346   uint32_t len = 2;
347
348   if (use_extra_checksum)
349     len++;
350 #ifdef DEBUG_GCDAPROFILING
351   fprintf(stderr, "llvmgcda: function id=0x%08x name=%s\n", ident,
352           function_name ? function_name : "NULL");
353 #endif
354   if (!output_file) return;
355
356   /* function tag */
357   write_bytes("\0\0\0\1", 4);
358   if (function_name)
359     len += 1 + length_of_string(function_name);
360   write_32bit_value(len);
361   write_32bit_value(ident);
362   write_32bit_value(func_checksum);
363   if (use_extra_checksum)
364     write_32bit_value(cfg_checksum);
365   if (function_name)
366     write_string(function_name);
367 }
368
369 void llvm_gcda_emit_arcs(uint32_t num_counters, uint64_t *counters) {
370   uint32_t i;
371   uint64_t *old_ctrs = NULL;
372   uint32_t val = 0;
373   uint64_t save_cur_pos = cur_pos;
374
375   if (!output_file) return;
376
377   val = read_32bit_value();
378
379   if (val != (uint32_t)-1) {
380     /* There are counters present in the file. Merge them. */
381     if (val != 0x01a10000) {
382       fprintf(stderr, "profiling: %s: cannot merge previous GCDA file: "
383                       "corrupt arc tag (0x%08x)\n",
384               filename, val);
385       return;
386     }
387
388     val = read_32bit_value();
389     if (val == (uint32_t)-1 || val / 2 != num_counters) {
390       fprintf(stderr, "profiling: %s: cannot merge previous GCDA file: "
391                       "mismatched number of counters (%d)\n",
392               filename, val);
393       return;
394     }
395
396     old_ctrs = malloc(sizeof(uint64_t) * num_counters);
397     for (i = 0; i < num_counters; ++i)
398       old_ctrs[i] = read_64bit_value();
399   }
400
401   cur_pos = save_cur_pos;
402
403   /* Counter #1 (arcs) tag */
404   write_bytes("\0\0\xa1\1", 4);
405   write_32bit_value(num_counters * 2);
406   for (i = 0; i < num_counters; ++i) {
407     counters[i] += (old_ctrs ? old_ctrs[i] : 0);
408     write_64bit_value(counters[i]);
409   }
410
411   free(old_ctrs);
412
413 #ifdef DEBUG_GCDAPROFILING
414   fprintf(stderr, "llvmgcda:   %u arcs\n", num_counters);
415   for (i = 0; i < num_counters; ++i)
416     fprintf(stderr, "llvmgcda:   %llu\n", (unsigned long long)counters[i]);
417 #endif
418 }
419
420 void llvm_gcda_summary_info() {
421   const uint32_t obj_summary_len = 9; /* Length for gcov compatibility. */
422   uint32_t i;
423   uint32_t runs = 1;
424   uint32_t val = 0;
425   uint64_t save_cur_pos = cur_pos;
426
427   if (!output_file) return;
428
429   val = read_32bit_value();
430
431   if (val != (uint32_t)-1) {
432     /* There are counters present in the file. Merge them. */
433     if (val != 0xa1000000) {
434       fprintf(stderr, "profiling: %s: cannot merge previous run count: "
435                       "corrupt object tag (0x%08x)\n",
436               filename, val);
437       return;
438     }
439
440     val = read_32bit_value(); /* length */
441     if (val != obj_summary_len) {
442       fprintf(stderr, "profiling: %s: cannot merge previous run count: "
443                       "mismatched object length (%d)\n",
444               filename, val);
445       return;
446     }
447
448     read_32bit_value(); /* checksum, unused */
449     read_32bit_value(); /* num, unused */
450     runs += read_32bit_value(); /* Add previous run count to new counter. */
451   }
452
453   cur_pos = save_cur_pos;
454
455   /* Object summary tag */
456   write_bytes("\0\0\0\xa1", 4);
457   write_32bit_value(obj_summary_len);
458   write_32bit_value(0); /* checksum, unused */
459   write_32bit_value(0); /* num, unused */
460   write_32bit_value(runs);
461   for (i = 3; i < obj_summary_len; ++i)
462     write_32bit_value(0);
463
464   /* Program summary tag */
465   write_bytes("\0\0\0\xa3", 4); /* tag indicates 1 program */
466   write_32bit_value(0); /* 0 length */
467
468 #ifdef DEBUG_GCDAPROFILING
469   fprintf(stderr, "llvmgcda:   %u runs\n", runs);
470 #endif
471 }
472
473 void llvm_gcda_end_file() {
474   /* Write out EOF record. */
475   if (output_file) {
476     write_bytes("\0\0\0\0\0\0\0\0", 8);
477
478     if (new_file) {
479       fwrite(write_buffer, cur_pos, 1, output_file);
480       free(write_buffer);
481     } else {
482       unmap_file();
483     }
484
485     fclose(output_file);
486     flock(fd, LOCK_UN);
487     output_file = NULL;
488     write_buffer = NULL;
489   }
490   free(filename);
491
492 #ifdef DEBUG_GCDAPROFILING
493   fprintf(stderr, "llvmgcda: -----\n");
494 #endif
495 }
496
497 void llvm_register_writeout_function(writeout_fn fn) {
498   struct writeout_fn_node *new_node = malloc(sizeof(struct writeout_fn_node));
499   new_node->fn = fn;
500   new_node->next = NULL;
501
502   if (!writeout_fn_head) {
503     writeout_fn_head = writeout_fn_tail = new_node;
504   } else {
505     writeout_fn_tail->next = new_node;
506     writeout_fn_tail = new_node;
507   }
508 }
509
510 void llvm_writeout_files() {
511   struct writeout_fn_node *curr = writeout_fn_head;
512
513   while (curr) {
514     curr->fn();
515     curr = curr->next;
516   }
517 }
518
519 void llvm_delete_writeout_function_list() {
520   while (writeout_fn_head) {
521     struct writeout_fn_node *node = writeout_fn_head;
522     writeout_fn_head = writeout_fn_head->next;
523     free(node);
524   }
525   
526   writeout_fn_head = writeout_fn_tail = NULL;
527 }
528
529 void llvm_register_flush_function(flush_fn fn) {
530   struct flush_fn_node *new_node = malloc(sizeof(struct flush_fn_node));
531   new_node->fn = fn;
532   new_node->next = NULL;
533
534   if (!flush_fn_head) {
535     flush_fn_head = flush_fn_tail = new_node;
536   } else {
537     flush_fn_tail->next = new_node;
538     flush_fn_tail = new_node;
539   }
540 }
541
542 void __gcov_flush() {
543   struct flush_fn_node *curr = flush_fn_head;
544
545   while (curr) {
546     curr->fn();
547     curr = curr->next;
548   }
549 }
550
551 void llvm_delete_flush_function_list() {
552   while (flush_fn_head) {
553     struct flush_fn_node *node = flush_fn_head;
554     flush_fn_head = flush_fn_head->next;
555     free(node);
556   }
557
558   flush_fn_head = flush_fn_tail = NULL;
559 }
560
561 void llvm_gcov_init(writeout_fn wfn, flush_fn ffn) {
562   static int atexit_ran = 0;
563
564   if (wfn)
565     llvm_register_writeout_function(wfn);
566
567   if (ffn)
568     llvm_register_flush_function(ffn);
569
570   if (atexit_ran == 0) {
571     atexit_ran = 1;
572
573     /* Make sure we write out the data and delete the data structures. */
574     atexit(llvm_delete_flush_function_list);
575     atexit(llvm_delete_writeout_function_list);
576     atexit(llvm_writeout_files);
577   }
578 }