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