1 /*===- GCDAProfiling.c - Support library for GCDA file emission -----------===*\
3 |* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 |* See https://llvm.org/LICENSE.txt for license information.
5 |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 |*===----------------------------------------------------------------------===*|
9 |* This file implements the call back routines for the gcov profiling
10 |* instrumentation pass. Link against this library when running code through
11 |* the -insert-gcov-profiling LLVM pass.
13 |* We emit files in a corrupt version of GCOV's "gcda" file format. These files
14 |* are only close enough that LCOV will happily parse them. Anything that lcov
15 |* ignores is missing.
17 |* TODO: gcov is multi-process safe by having each exit open the existing file
18 |* and append to it. We'd like to achieve that and be thread-safe too.
20 \*===----------------------------------------------------------------------===*/
22 #if !defined(__Fuchsia__)
31 #define WIN32_LEAN_AND_MEAN
33 #include "WindowsMMap.h"
39 #if defined(__FreeBSD__) && defined(__i386__)
40 #define I386_FREEBSD 1
42 #define I386_FREEBSD 0
45 #if !defined(_MSC_VER) && !I386_FREEBSD
50 typedef unsigned char uint8_t;
51 typedef unsigned int uint32_t;
52 typedef unsigned long long uint64_t;
54 /* System headers define 'size_t' incorrectly on x64 FreeBSD (prior to
55 * FreeBSD 10, r232261) when compiled in 32-bit mode.
57 typedef unsigned char uint8_t;
58 typedef unsigned int uint32_t;
59 typedef unsigned long long uint64_t;
62 #include "InstrProfiling.h"
63 #include "InstrProfilingUtil.h"
67 static pthread_mutex_t gcov_flush_mutex = PTHREAD_MUTEX_INITIALIZER;
68 static __inline void gcov_flush_lock() {
69 pthread_mutex_lock(&gcov_flush_mutex);
71 static __inline void gcov_flush_unlock() {
72 pthread_mutex_unlock(&gcov_flush_mutex);
76 static SRWLOCK gcov_flush_mutex = SRWLOCK_INIT;
77 static __inline void gcov_flush_lock() {
78 AcquireSRWLockExclusive(&gcov_flush_mutex);
80 static __inline void gcov_flush_unlock() {
81 ReleaseSRWLockExclusive(&gcov_flush_mutex);
85 /* #define DEBUG_GCDAPROFILING */
87 * --- GCOV file format I/O primitives ---
91 * The current file name we're outputting. Used primarily for error logging.
93 static char *filename = NULL;
96 * The current file we're outputting.
98 static FILE *output_file = NULL;
101 * Buffer that we write things into.
103 #define WRITE_BUFFER_SIZE (128 * 1024)
104 static unsigned char *write_buffer = NULL;
105 static uint64_t cur_buffer_size = 0;
106 static uint64_t cur_pos = 0;
107 static uint64_t file_size = 0;
108 static int new_file = 0;
110 static HANDLE mmap_handle = NULL;
114 typedef void (*fn_ptr)();
116 typedef void* dynamic_object_id;
117 // The address of this variable identifies a given dynamic object.
118 static dynamic_object_id current_id;
119 #define CURRENT_ID (¤t_id)
122 dynamic_object_id id;
124 struct fn_node* next;
128 struct fn_node *head, *tail;
132 * A list of functions to write out the data, shared between all dynamic objects.
134 struct fn_list writeout_fn_list;
137 * A list of flush functions that our __gcov_flush() function should call, shared between all dynamic objects.
139 struct fn_list flush_fn_list;
141 static void fn_list_insert(struct fn_list* list, fn_ptr fn) {
142 struct fn_node* new_node = malloc(sizeof(struct fn_node));
144 new_node->next = NULL;
145 new_node->id = CURRENT_ID;
148 list->head = list->tail = new_node;
150 list->tail->next = new_node;
151 list->tail = new_node;
155 static void fn_list_remove(struct fn_list* list) {
156 struct fn_node* curr = list->head;
157 struct fn_node* prev = NULL;
158 struct fn_node* next = NULL;
163 if (curr->id == CURRENT_ID) {
164 if (curr == list->head) {
168 if (curr == list->tail) {
185 static void resize_write_buffer(uint64_t size) {
186 if (!new_file) return;
188 if (size <= cur_buffer_size) return;
189 size = (size - 1) / WRITE_BUFFER_SIZE + 1;
190 size *= WRITE_BUFFER_SIZE;
191 write_buffer = realloc(write_buffer, size);
192 cur_buffer_size = size;
195 static void write_bytes(const char *s, size_t len) {
196 resize_write_buffer(len);
197 memcpy(&write_buffer[cur_pos], s, len);
201 static void write_32bit_value(uint32_t i) {
202 write_bytes((char*)&i, 4);
205 static void write_64bit_value(uint64_t i) {
206 // GCOV uses a lo-/hi-word format even on big-endian systems.
207 // See also GCOVBuffer::readInt64 in LLVM.
208 uint32_t lo = (uint32_t) i;
209 uint32_t hi = (uint32_t) (i >> 32);
210 write_32bit_value(lo);
211 write_32bit_value(hi);
214 static uint32_t length_of_string(const char *s) {
215 return (strlen(s) / 4) + 1;
218 static void write_string(const char *s) {
219 uint32_t len = length_of_string(s);
220 write_32bit_value(len);
221 write_bytes(s, strlen(s));
222 write_bytes("\0\0\0\0", 4 - (strlen(s) % 4));
225 static uint32_t read_32bit_value() {
231 val = *(uint32_t*)&write_buffer[cur_pos];
236 static uint32_t read_le_32bit_value() {
243 for (i = 0; i < 4; i++)
244 val |= write_buffer[cur_pos++] << (8*i);
248 static uint64_t read_64bit_value() {
249 // GCOV uses a lo-/hi-word format even on big-endian systems.
250 // See also GCOVBuffer::readInt64 in LLVM.
251 uint32_t lo = read_32bit_value();
252 uint32_t hi = read_32bit_value();
253 return ((uint64_t)hi << 32) | ((uint64_t)lo);
256 static char *mangle_filename(const char *orig_filename) {
260 const char *prefix = lprofGetPathPrefix(&prefix_strip, &prefix_len);
263 return strdup(orig_filename);
265 new_filename = malloc(prefix_len + 1 + strlen(orig_filename) + 1);
266 lprofApplyPathPrefix(new_filename, orig_filename, prefix, prefix_len,
272 static int map_file() {
273 fseek(output_file, 0L, SEEK_END);
274 file_size = ftell(output_file);
276 /* A size of 0 is invalid to `mmap'. Return a fail here, but don't issue an
277 * error message because it should "just work" for the user. */
284 mmap_fd = INVALID_HANDLE_VALUE;
286 mmap_fd = (HANDLE)_get_osfhandle(fd);
288 mmap_handle = CreateFileMapping(mmap_fd, NULL, PAGE_READWRITE, DWORD_HI(file_size), DWORD_LO(file_size), NULL);
289 if (mmap_handle == NULL) {
290 fprintf(stderr, "profiling: %s: cannot create file mapping: %lu\n",
291 filename, GetLastError());
295 write_buffer = MapViewOfFile(mmap_handle, FILE_MAP_WRITE, 0, 0, file_size);
296 if (write_buffer == NULL) {
297 fprintf(stderr, "profiling: %s: cannot map: %lu\n", filename,
299 CloseHandle(mmap_handle);
303 write_buffer = mmap(0, file_size, PROT_READ | PROT_WRITE,
304 MAP_FILE | MAP_SHARED, fd, 0);
305 if (write_buffer == (void *)-1) {
307 fprintf(stderr, "profiling: %s: cannot map: %s\n", filename,
316 static void unmap_file() {
318 if (!FlushViewOfFile(write_buffer, file_size)) {
319 fprintf(stderr, "profiling: %s: cannot flush mapped view: %lu\n", filename,
323 if (!UnmapViewOfFile(write_buffer)) {
324 fprintf(stderr, "profiling: %s: cannot unmap mapped view: %lu\n", filename,
328 if (!CloseHandle(mmap_handle)) {
329 fprintf(stderr, "profiling: %s: cannot close file mapping handle: %lu\n",
330 filename, GetLastError());
335 if (msync(write_buffer, file_size, MS_SYNC) == -1) {
337 fprintf(stderr, "profiling: %s: cannot msync: %s\n", filename,
341 /* We explicitly ignore errors from unmapping because at this point the data
342 * is written and we don't care.
344 (void)munmap(write_buffer, file_size);
352 * --- LLVM line counter API ---
355 /* A file in this case is a translation unit. Each .o file built with line
356 * profiling enabled will emit to a different file. Only one file may be
359 COMPILER_RT_VISIBILITY
360 void llvm_gcda_start_file(const char *orig_filename, const char version[4],
362 const char *mode = "r+b";
363 filename = mangle_filename(orig_filename);
365 /* Try just opening the file. */
367 fd = open(filename, O_RDWR | O_BINARY);
370 /* Try opening the file, creating it if necessary. */
373 fd = open(filename, O_RDWR | O_CREAT | O_BINARY, 0644);
375 /* Try creating the directories first then opening the file. */
376 __llvm_profile_recursive_mkdir(filename);
377 fd = open(filename, O_RDWR | O_CREAT | O_BINARY, 0644);
379 /* Bah! It's hopeless. */
381 fprintf(stderr, "profiling: %s: cannot open: %s\n", filename,
388 /* Try to flock the file to serialize concurrent processes writing out to the
389 * same GCDA. This can fail if the filesystem doesn't support it, but in that
390 * case we'll just carry on with the old racy behaviour and hope for the best.
393 output_file = fdopen(fd, mode);
395 /* Initialize the write buffer. */
401 resize_write_buffer(WRITE_BUFFER_SIZE);
402 memset(write_buffer, 0, WRITE_BUFFER_SIZE);
404 if (map_file() == -1) {
405 /* mmap failed, try to recover by clobbering */
409 resize_write_buffer(WRITE_BUFFER_SIZE);
410 memset(write_buffer, 0, WRITE_BUFFER_SIZE);
414 /* gcda file, version, stamp checksum. */
415 write_bytes("adcg", 4);
416 write_bytes(version, 4);
417 write_32bit_value(checksum);
419 #ifdef DEBUG_GCDAPROFILING
420 fprintf(stderr, "llvmgcda: [%s]\n", orig_filename);
424 /* Given an array of pointers to counters (counters), increment the n-th one,
425 * where we're also given a pointer to n (predecessor).
427 COMPILER_RT_VISIBILITY
428 void llvm_gcda_increment_indirect_counter(uint32_t *predecessor,
429 uint64_t **counters) {
434 if (pred == 0xffffffff)
436 counter = counters[pred];
438 /* Don't crash if the pred# is out of sync. This can happen due to threads,
439 or because of a TODO in GCOVProfiling.cpp buildEdgeLookupTable(). */
442 #ifdef DEBUG_GCDAPROFILING
445 "llvmgcda: increment_indirect_counter counters=%08llx, pred=%u\n",
446 *counter, *predecessor);
450 COMPILER_RT_VISIBILITY
451 void llvm_gcda_emit_function(uint32_t ident, const char *function_name,
452 uint32_t func_checksum, uint8_t use_extra_checksum,
453 uint32_t cfg_checksum) {
456 if (use_extra_checksum)
458 #ifdef DEBUG_GCDAPROFILING
459 fprintf(stderr, "llvmgcda: function id=0x%08x name=%s\n", ident,
460 function_name ? function_name : "NULL");
462 if (!output_file) return;
465 write_bytes("\0\0\0\1", 4);
467 len += 1 + length_of_string(function_name);
468 write_32bit_value(len);
469 write_32bit_value(ident);
470 write_32bit_value(func_checksum);
471 if (use_extra_checksum)
472 write_32bit_value(cfg_checksum);
474 write_string(function_name);
477 COMPILER_RT_VISIBILITY
478 void llvm_gcda_emit_arcs(uint32_t num_counters, uint64_t *counters) {
480 uint64_t *old_ctrs = NULL;
482 uint64_t save_cur_pos = cur_pos;
484 if (!output_file) return;
486 val = read_le_32bit_value();
488 if (val != (uint32_t)-1) {
489 /* There are counters present in the file. Merge them. */
490 if (val != 0x01a10000) {
491 fprintf(stderr, "profiling: %s: cannot merge previous GCDA file: "
492 "corrupt arc tag (0x%08x)\n",
497 val = read_32bit_value();
498 if (val == (uint32_t)-1 || val / 2 != num_counters) {
499 fprintf(stderr, "profiling: %s: cannot merge previous GCDA file: "
500 "mismatched number of counters (%d)\n",
505 old_ctrs = malloc(sizeof(uint64_t) * num_counters);
506 for (i = 0; i < num_counters; ++i)
507 old_ctrs[i] = read_64bit_value();
510 cur_pos = save_cur_pos;
512 /* Counter #1 (arcs) tag */
513 write_bytes("\0\0\xa1\1", 4);
514 write_32bit_value(num_counters * 2);
515 for (i = 0; i < num_counters; ++i) {
516 counters[i] += (old_ctrs ? old_ctrs[i] : 0);
517 write_64bit_value(counters[i]);
522 #ifdef DEBUG_GCDAPROFILING
523 fprintf(stderr, "llvmgcda: %u arcs\n", num_counters);
524 for (i = 0; i < num_counters; ++i)
525 fprintf(stderr, "llvmgcda: %llu\n", (unsigned long long)counters[i]);
529 COMPILER_RT_VISIBILITY
530 void llvm_gcda_summary_info() {
531 const uint32_t obj_summary_len = 9; /* Length for gcov compatibility. */
534 static uint32_t run_counted = 0; // We only want to increase the run count once.
536 uint64_t save_cur_pos = cur_pos;
538 if (!output_file) return;
540 val = read_le_32bit_value();
542 if (val != (uint32_t)-1) {
543 /* There are counters present in the file. Merge them. */
544 if (val != 0xa1000000) {
545 fprintf(stderr, "profiling: %s: cannot merge previous run count: "
546 "corrupt object tag (0x%08x)\n",
551 val = read_32bit_value(); /* length */
552 if (val != obj_summary_len) {
553 fprintf(stderr, "profiling: %s: cannot merge previous run count: "
554 "mismatched object length (%d)\n",
559 read_32bit_value(); /* checksum, unused */
560 read_32bit_value(); /* num, unused */
561 uint32_t prev_runs = read_32bit_value();
562 /* Add previous run count to new counter, if not already counted before. */
563 runs = run_counted ? prev_runs : prev_runs + 1;
566 cur_pos = save_cur_pos;
568 /* Object summary tag */
569 write_bytes("\0\0\0\xa1", 4);
570 write_32bit_value(obj_summary_len);
571 write_32bit_value(0); /* checksum, unused */
572 write_32bit_value(0); /* num, unused */
573 write_32bit_value(runs);
574 for (i = 3; i < obj_summary_len; ++i)
575 write_32bit_value(0);
577 /* Program summary tag */
578 write_bytes("\0\0\0\xa3", 4); /* tag indicates 1 program */
579 write_32bit_value(0); /* 0 length */
583 #ifdef DEBUG_GCDAPROFILING
584 fprintf(stderr, "llvmgcda: %u runs\n", runs);
588 COMPILER_RT_VISIBILITY
589 void llvm_gcda_end_file() {
590 /* Write out EOF record. */
592 write_bytes("\0\0\0\0\0\0\0\0", 8);
595 fwrite(write_buffer, cur_pos, 1, output_file);
609 #ifdef DEBUG_GCDAPROFILING
610 fprintf(stderr, "llvmgcda: -----\n");
614 COMPILER_RT_VISIBILITY
615 void llvm_register_writeout_function(fn_ptr fn) {
616 fn_list_insert(&writeout_fn_list, fn);
619 COMPILER_RT_VISIBILITY
620 void llvm_writeout_files(void) {
621 struct fn_node *curr = writeout_fn_list.head;
624 if (curr->id == CURRENT_ID) {
631 COMPILER_RT_VISIBILITY
632 void llvm_delete_writeout_function_list(void) {
633 fn_list_remove(&writeout_fn_list);
636 COMPILER_RT_VISIBILITY
637 void llvm_register_flush_function(fn_ptr fn) {
638 fn_list_insert(&flush_fn_list, fn);
641 void __gcov_flush() {
644 struct fn_node* curr = flush_fn_list.head;
654 COMPILER_RT_VISIBILITY
655 void llvm_delete_flush_function_list(void) {
656 fn_list_remove(&flush_fn_list);
659 COMPILER_RT_VISIBILITY
660 void llvm_gcov_init(fn_ptr wfn, fn_ptr ffn) {
661 static int atexit_ran = 0;
664 llvm_register_writeout_function(wfn);
667 llvm_register_flush_function(ffn);
669 if (atexit_ran == 0) {
672 /* Make sure we write out the data and delete the data structures. */
673 atexit(llvm_delete_flush_function_list);
674 atexit(llvm_delete_writeout_function_list);
675 atexit(llvm_writeout_files);