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