xref: /minix3/sys/external/bsd/compiler_rt/dist/lib/profile/GCDAProfiling.c (revision 5ba302fdeaa9e153d58b5dcaef42d660aedee92e)
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 <errno.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <sys/mman.h>
30 #include <sys/types.h>
31 #ifdef _WIN32
32 #include <direct.h>
33 #endif
34 
35 #ifndef _MSC_VER
36 #include <stdint.h>
37 #else
38 typedef unsigned int uint32_t;
39 typedef unsigned int uint64_t;
40 #endif
41 
42 /* #define DEBUG_GCDAPROFILING */
43 
44 /*
45  * --- GCOV file format I/O primitives ---
46  */
47 
48 /*
49  * The current file name we're outputting. Used primarily for error logging.
50  */
51 static char *filename = NULL;
52 
53 /*
54  * The current file we're outputting.
55  */
56 static FILE *output_file = NULL;
57 
58 /*
59  * Buffer that we write things into.
60  */
61 #define WRITE_BUFFER_SIZE (128 * 1024)
62 static char *write_buffer = NULL;
63 static uint64_t cur_buffer_size = 0;
64 static uint64_t cur_pos = 0;
65 static uint64_t file_size = 0;
66 static int new_file = 0;
67 static int fd = -1;
68 
69 /*
70  * A list of functions to write out the data.
71  */
72 typedef void (*writeout_fn)();
73 
74 struct writeout_fn_node {
75   writeout_fn fn;
76   struct writeout_fn_node *next;
77 };
78 
79 static struct writeout_fn_node *writeout_fn_head = NULL;
80 static struct writeout_fn_node *writeout_fn_tail = NULL;
81 
82 /*
83  *  A list of flush functions that our __gcov_flush() function should call.
84  */
85 typedef void (*flush_fn)();
86 
87 struct flush_fn_node {
88   flush_fn fn;
89   struct flush_fn_node *next;
90 };
91 
92 static struct flush_fn_node *flush_fn_head = NULL;
93 static struct flush_fn_node *flush_fn_tail = NULL;
94 
95 static void resize_write_buffer(uint64_t size) {
96   if (!new_file) return;
97   size += cur_pos;
98   if (size <= cur_buffer_size) return;
99   size = (size - 1) / WRITE_BUFFER_SIZE + 1;
100   size *= WRITE_BUFFER_SIZE;
101   write_buffer = realloc(write_buffer, size);
102   cur_buffer_size = size;
103 }
104 
105 static void write_bytes(const char *s, size_t len) {
106   resize_write_buffer(len);
107   memcpy(&write_buffer[cur_pos], s, len);
108   cur_pos += len;
109 }
110 
111 static void write_32bit_value(uint32_t i) {
112   write_bytes((char*)&i, 4);
113 }
114 
115 static void write_64bit_value(uint64_t i) {
116   write_bytes((char*)&i, 8);
117 }
118 
119 static uint32_t length_of_string(const char *s) {
120   return (strlen(s) / 4) + 1;
121 }
122 
123 static void write_string(const char *s) {
124   uint32_t len = length_of_string(s);
125   write_32bit_value(len);
126   write_bytes(s, strlen(s));
127   write_bytes("\0\0\0\0", 4 - (strlen(s) % 4));
128 }
129 
130 static uint32_t read_32bit_value() {
131   uint32_t val;
132 
133   if (new_file)
134     return (uint32_t)-1;
135 
136   val = *(uint32_t*)&write_buffer[cur_pos];
137   cur_pos += 4;
138   return val;
139 }
140 
141 static uint64_t read_64bit_value() {
142   uint64_t val;
143 
144   if (new_file)
145     return (uint64_t)-1;
146 
147   val = *(uint64_t*)&write_buffer[cur_pos];
148   cur_pos += 8;
149   return val;
150 }
151 
152 static char *mangle_filename(const char *orig_filename) {
153   char *filename = 0;
154   int prefix_len = 0;
155   int prefix_strip = 0;
156   int level = 0;
157   const char *fname = orig_filename, *ptr = NULL;
158   const char *prefix = getenv("GCOV_PREFIX");
159   const char *prefix_strip_str = getenv("GCOV_PREFIX_STRIP");
160 
161   if (!prefix)
162     return strdup(orig_filename);
163 
164   if (prefix_strip_str) {
165     prefix_strip = atoi(prefix_strip_str);
166 
167     /* Negative GCOV_PREFIX_STRIP values are ignored */
168     if (prefix_strip < 0)
169       prefix_strip = 0;
170   }
171 
172   prefix_len = strlen(prefix);
173   filename = malloc(prefix_len + 1 + strlen(orig_filename) + 1);
174   strcpy(filename, prefix);
175 
176   if (prefix[prefix_len - 1] != '/')
177     strcat(filename, "/");
178 
179   for (ptr = fname + 1; *ptr != '\0' && level < prefix_strip; ++ptr) {
180     if (*ptr != '/') continue;
181     fname = ptr;
182     ++level;
183   }
184 
185   strcat(filename, fname);
186 
187   return filename;
188 }
189 
190 static void recursive_mkdir(char *filename) {
191   int i;
192 
193   for (i = 1; filename[i] != '\0'; ++i) {
194     if (filename[i] != '/') continue;
195     filename[i] = '\0';
196 #ifdef _WIN32
197     _mkdir(filename);
198 #else
199     mkdir(filename, 0755);  /* Some of these will fail, ignore it. */
200 #endif
201     filename[i] = '/';
202   }
203 }
204 
205 static int map_file() {
206   fseek(output_file, 0L, SEEK_END);
207   file_size = ftell(output_file);
208 
209   write_buffer = mmap(0, file_size, PROT_READ | PROT_WRITE,
210                       MAP_FILE | MAP_SHARED, fd, 0);
211   if (write_buffer == (void *)-1) {
212     int errnum = errno;
213     fprintf(stderr, "profiling: %s: cannot map: %s\n", filename,
214             strerror(errnum));
215     return -1;
216   }
217   return 0;
218 }
219 
220 static void unmap_file() {
221   if (msync(write_buffer, file_size, MS_SYNC) == -1) {
222     int errnum = errno;
223     fprintf(stderr, "profiling: %s: cannot msync: %s\n", filename,
224             strerror(errnum));
225   }
226 
227   /* We explicitly ignore errors from unmapping because at this point the data
228    * is written and we don't care.
229    */
230   (void)munmap(write_buffer, file_size);
231   write_buffer = NULL;
232   file_size = 0;
233 }
234 
235 /*
236  * --- LLVM line counter API ---
237  */
238 
239 /* A file in this case is a translation unit. Each .o file built with line
240  * profiling enabled will emit to a different file. Only one file may be
241  * started at a time.
242  */
243 void llvm_gcda_start_file(const char *orig_filename, const char version[4]) {
244   const char *mode = "r+b";
245   filename = mangle_filename(orig_filename);
246 
247   /* Try just opening the file. */
248   new_file = 0;
249   fd = open(filename, O_RDWR);
250 
251   if (fd == -1) {
252     /* Try opening the file, creating it if necessary. */
253     new_file = 1;
254     mode = "w+b";
255     fd = open(filename, O_RDWR | O_CREAT, 0644);
256     if (fd == -1) {
257       /* Try creating the directories first then opening the file. */
258       recursive_mkdir(filename);
259       fd = open(filename, O_RDWR | O_CREAT, 0644);
260       if (fd == -1) {
261         /* Bah! It's hopeless. */
262         int errnum = errno;
263         fprintf(stderr, "profiling: %s: cannot open: %s\n", filename,
264                 strerror(errnum));
265         return;
266       }
267     }
268   }
269 
270   output_file = fdopen(fd, mode);
271 
272   /* Initialize the write buffer. */
273   write_buffer = NULL;
274   cur_buffer_size = 0;
275   cur_pos = 0;
276 
277   if (new_file) {
278     resize_write_buffer(WRITE_BUFFER_SIZE);
279     memset(write_buffer, 0, WRITE_BUFFER_SIZE);
280   } else {
281     if (map_file() == -1) {
282       /* mmap failed, try to recover by clobbering */
283       new_file = 1;
284       write_buffer = NULL;
285       cur_buffer_size = 0;
286       resize_write_buffer(WRITE_BUFFER_SIZE);
287       memset(write_buffer, 0, WRITE_BUFFER_SIZE);
288     }
289   }
290 
291   /* gcda file, version, stamp LLVM. */
292   write_bytes("adcg", 4);
293   write_bytes(version, 4);
294   write_bytes("MVLL", 4);
295 
296 #ifdef DEBUG_GCDAPROFILING
297   fprintf(stderr, "llvmgcda: [%s]\n", orig_filename);
298 #endif
299 }
300 
301 /* Given an array of pointers to counters (counters), increment the n-th one,
302  * where we're also given a pointer to n (predecessor).
303  */
304 void llvm_gcda_increment_indirect_counter(uint32_t *predecessor,
305                                           uint64_t **counters) {
306   uint64_t *counter;
307   uint32_t pred;
308 
309   pred = *predecessor;
310   if (pred == 0xffffffff)
311     return;
312   counter = counters[pred];
313 
314   /* Don't crash if the pred# is out of sync. This can happen due to threads,
315      or because of a TODO in GCOVProfiling.cpp buildEdgeLookupTable(). */
316   if (counter)
317     ++*counter;
318 #ifdef DEBUG_GCDAPROFILING
319   else
320     fprintf(stderr,
321             "llvmgcda: increment_indirect_counter counters=%08llx, pred=%u\n",
322             *counter, *predecessor);
323 #endif
324 }
325 
326 void llvm_gcda_emit_function(uint32_t ident, const char *function_name,
327                              uint8_t use_extra_checksum) {
328   uint32_t len = 2;
329 
330   if (use_extra_checksum)
331     len++;
332 #ifdef DEBUG_GCDAPROFILING
333   fprintf(stderr, "llvmgcda: function id=0x%08x name=%s\n", ident,
334           function_name ? function_name : "NULL");
335 #endif
336   if (!output_file) return;
337 
338   /* function tag */
339   write_bytes("\0\0\0\1", 4);
340   if (function_name)
341     len += 1 + length_of_string(function_name);
342   write_32bit_value(len);
343   write_32bit_value(ident);
344   write_32bit_value(0);
345   if (use_extra_checksum)
346     write_32bit_value(0);
347   if (function_name)
348     write_string(function_name);
349 }
350 
351 void llvm_gcda_emit_arcs(uint32_t num_counters, uint64_t *counters) {
352   uint32_t i;
353   uint64_t *old_ctrs = NULL;
354   uint32_t val = 0;
355   uint64_t save_cur_pos = cur_pos;
356 
357   if (!output_file) return;
358 
359   val = read_32bit_value();
360 
361   if (val != (uint32_t)-1) {
362     /* There are counters present in the file. Merge them. */
363     if (val != 0x01a10000) {
364       fprintf(stderr, "profiling:invalid magic number (0x%08x)\n", val);
365       return;
366     }
367 
368     val = read_32bit_value();
369     if (val == (uint32_t)-1 || val / 2 != num_counters) {
370       fprintf(stderr, "profiling:invalid number of counters (%d)\n", 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_end_file() {
399   /* Write out EOF record. */
400   if (output_file) {
401     write_bytes("\0\0\0\0\0\0\0\0", 8);
402 
403     if (new_file) {
404       fwrite(write_buffer, cur_pos, 1, output_file);
405       free(write_buffer);
406     } else {
407       unmap_file();
408     }
409 
410     fclose(output_file);
411     output_file = NULL;
412     write_buffer = NULL;
413   }
414   free(filename);
415 
416 #ifdef DEBUG_GCDAPROFILING
417   fprintf(stderr, "llvmgcda: -----\n");
418 #endif
419 }
420 
421 void llvm_register_writeout_function(writeout_fn fn) {
422   struct writeout_fn_node *new_node = malloc(sizeof(struct writeout_fn_node));
423   new_node->fn = fn;
424   new_node->next = NULL;
425 
426   if (!writeout_fn_head) {
427     writeout_fn_head = writeout_fn_tail = new_node;
428   } else {
429     writeout_fn_tail->next = new_node;
430     writeout_fn_tail = new_node;
431   }
432 }
433 
434 void llvm_writeout_files() {
435   struct writeout_fn_node *curr = writeout_fn_head;
436 
437   while (curr) {
438     curr->fn();
439     curr = curr->next;
440   }
441 }
442 
443 void llvm_delete_writeout_function_list() {
444   while (writeout_fn_head) {
445     struct writeout_fn_node *node = writeout_fn_head;
446     writeout_fn_head = writeout_fn_head->next;
447     free(node);
448   }
449 
450   writeout_fn_head = writeout_fn_tail = NULL;
451 }
452 
453 void llvm_register_flush_function(flush_fn fn) {
454   struct flush_fn_node *new_node = malloc(sizeof(struct flush_fn_node));
455   new_node->fn = fn;
456   new_node->next = NULL;
457 
458   if (!flush_fn_head) {
459     flush_fn_head = flush_fn_tail = new_node;
460   } else {
461     flush_fn_tail->next = new_node;
462     flush_fn_tail = new_node;
463   }
464 }
465 
466 void __gcov_flush() {
467   struct flush_fn_node *curr = flush_fn_head;
468 
469   while (curr) {
470     curr->fn();
471     curr = curr->next;
472   }
473 }
474 
475 void llvm_delete_flush_function_list() {
476   while (flush_fn_head) {
477     struct flush_fn_node *node = flush_fn_head;
478     flush_fn_head = flush_fn_head->next;
479     free(node);
480   }
481 
482   flush_fn_head = flush_fn_tail = NULL;
483 }
484 
485 void llvm_gcov_init(writeout_fn wfn, flush_fn ffn) {
486   static int atexit_ran = 0;
487 
488   if (wfn)
489     llvm_register_writeout_function(wfn);
490 
491   if (ffn)
492     llvm_register_flush_function(ffn);
493 
494   if (atexit_ran == 0) {
495     atexit_ran = 1;
496 
497     /* Make sure we write out the data and delete the data structures. */
498     atexit(llvm_delete_flush_function_list);
499     atexit(llvm_delete_writeout_function_list);
500     atexit(llvm_writeout_files);
501   }
502 }
503