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"
65 /* #define DEBUG_GCDAPROFILING */
68 * --- GCOV file format I/O primitives ---
72 * The current file name we're outputting. Used primarily for error logging.
74 static char *filename = NULL;
77 * The current file we're outputting.
79 static FILE *output_file = NULL;
82 * Buffer that we write things into.
84 #define WRITE_BUFFER_SIZE (128 * 1024)
85 static unsigned char *write_buffer = NULL;
86 static uint64_t cur_buffer_size = 0;
87 static uint64_t cur_pos = 0;
88 static uint64_t file_size = 0;
89 static int new_file = 0;
91 static HANDLE mmap_handle = NULL;
95 typedef void (*fn_ptr)();
97 typedef void* dynamic_object_id;
98 // The address of this variable identifies a given dynamic object.
99 static dynamic_object_id current_id;
100 #define CURRENT_ID (¤t_id)
103 dynamic_object_id id;
105 struct fn_node* next;
109 struct fn_node *head, *tail;
113 * A list of functions to write out the data, shared between all dynamic objects.
115 struct fn_list writeout_fn_list;
118 * A list of flush functions that our __gcov_flush() function should call, shared between all dynamic objects.
120 struct fn_list flush_fn_list;
122 static void fn_list_insert(struct fn_list* list, fn_ptr fn) {
123 struct fn_node* new_node = malloc(sizeof(struct fn_node));
125 new_node->next = NULL;
126 new_node->id = CURRENT_ID;
129 list->head = list->tail = new_node;
131 list->tail->next = new_node;
132 list->tail = new_node;
136 static void fn_list_remove(struct fn_list* list) {
137 struct fn_node* curr = list->head;
138 struct fn_node* prev = NULL;
139 struct fn_node* next = NULL;
144 if (curr->id == CURRENT_ID) {
145 if (curr == list->head) {
149 if (curr == list->tail) {
166 static void resize_write_buffer(uint64_t size) {
167 if (!new_file) return;
169 if (size <= cur_buffer_size) return;
170 size = (size - 1) / WRITE_BUFFER_SIZE + 1;
171 size *= WRITE_BUFFER_SIZE;
172 write_buffer = realloc(write_buffer, size);
173 cur_buffer_size = size;
176 static void write_bytes(const char *s, size_t len) {
177 resize_write_buffer(len);
178 memcpy(&write_buffer[cur_pos], s, len);
182 static void write_32bit_value(uint32_t i) {
183 write_bytes((char*)&i, 4);
186 static void write_64bit_value(uint64_t i) {
187 // GCOV uses a lo-/hi-word format even on big-endian systems.
188 // See also GCOVBuffer::readInt64 in LLVM.
189 uint32_t lo = (uint32_t) i;
190 uint32_t hi = (uint32_t) (i >> 32);
191 write_32bit_value(lo);
192 write_32bit_value(hi);
195 static uint32_t length_of_string(const char *s) {
196 return (strlen(s) / 4) + 1;
199 static void write_string(const char *s) {
200 uint32_t len = length_of_string(s);
201 write_32bit_value(len);
202 write_bytes(s, strlen(s));
203 write_bytes("\0\0\0\0", 4 - (strlen(s) % 4));
206 static uint32_t read_32bit_value() {
212 val = *(uint32_t*)&write_buffer[cur_pos];
217 static uint32_t read_le_32bit_value() {
224 for (i = 0; i < 4; i++)
225 val |= write_buffer[cur_pos++] << (8*i);
229 static uint64_t read_64bit_value() {
230 // GCOV uses a lo-/hi-word format even on big-endian systems.
231 // See also GCOVBuffer::readInt64 in LLVM.
232 uint32_t lo = read_32bit_value();
233 uint32_t hi = read_32bit_value();
234 return ((uint64_t)hi << 32) | ((uint64_t)lo);
237 static char *mangle_filename(const char *orig_filename) {
241 const char *prefix = lprofGetPathPrefix(&prefix_strip, &prefix_len);
244 return strdup(orig_filename);
246 new_filename = malloc(prefix_len + 1 + strlen(orig_filename) + 1);
247 lprofApplyPathPrefix(new_filename, orig_filename, prefix, prefix_len,
253 static int map_file() {
254 fseek(output_file, 0L, SEEK_END);
255 file_size = ftell(output_file);
257 /* A size of 0 is invalid to `mmap'. Return a fail here, but don't issue an
258 * error message because it should "just work" for the user. */
265 mmap_fd = INVALID_HANDLE_VALUE;
267 mmap_fd = (HANDLE)_get_osfhandle(fd);
269 mmap_handle = CreateFileMapping(mmap_fd, NULL, PAGE_READWRITE, DWORD_HI(file_size), DWORD_LO(file_size), NULL);
270 if (mmap_handle == NULL) {
271 fprintf(stderr, "profiling: %s: cannot create file mapping: %lu\n",
272 filename, GetLastError());
276 write_buffer = MapViewOfFile(mmap_handle, FILE_MAP_WRITE, 0, 0, file_size);
277 if (write_buffer == NULL) {
278 fprintf(stderr, "profiling: %s: cannot map: %lu\n", filename,
280 CloseHandle(mmap_handle);
284 write_buffer = mmap(0, file_size, PROT_READ | PROT_WRITE,
285 MAP_FILE | MAP_SHARED, fd, 0);
286 if (write_buffer == (void *)-1) {
288 fprintf(stderr, "profiling: %s: cannot map: %s\n", filename,
297 static void unmap_file() {
299 if (!FlushViewOfFile(write_buffer, file_size)) {
300 fprintf(stderr, "profiling: %s: cannot flush mapped view: %lu\n", filename,
304 if (!UnmapViewOfFile(write_buffer)) {
305 fprintf(stderr, "profiling: %s: cannot unmap mapped view: %lu\n", filename,
309 if (!CloseHandle(mmap_handle)) {
310 fprintf(stderr, "profiling: %s: cannot close file mapping handle: %lu\n",
311 filename, GetLastError());
316 if (msync(write_buffer, file_size, MS_SYNC) == -1) {
318 fprintf(stderr, "profiling: %s: cannot msync: %s\n", filename,
322 /* We explicitly ignore errors from unmapping because at this point the data
323 * is written and we don't care.
325 (void)munmap(write_buffer, file_size);
333 * --- LLVM line counter API ---
336 /* A file in this case is a translation unit. Each .o file built with line
337 * profiling enabled will emit to a different file. Only one file may be
340 COMPILER_RT_VISIBILITY
341 void llvm_gcda_start_file(const char *orig_filename, const char version[4],
343 const char *mode = "r+b";
344 filename = mangle_filename(orig_filename);
346 /* Try just opening the file. */
348 fd = open(filename, O_RDWR | O_BINARY);
351 /* Try opening the file, creating it if necessary. */
354 fd = open(filename, O_RDWR | O_CREAT | O_BINARY, 0644);
356 /* Try creating the directories first then opening the file. */
357 __llvm_profile_recursive_mkdir(filename);
358 fd = open(filename, O_RDWR | O_CREAT | O_BINARY, 0644);
360 /* Bah! It's hopeless. */
362 fprintf(stderr, "profiling: %s: cannot open: %s\n", filename,
369 /* Try to flock the file to serialize concurrent processes writing out to the
370 * same GCDA. This can fail if the filesystem doesn't support it, but in that
371 * case we'll just carry on with the old racy behaviour and hope for the best.
374 output_file = fdopen(fd, mode);
376 /* Initialize the write buffer. */
382 resize_write_buffer(WRITE_BUFFER_SIZE);
383 memset(write_buffer, 0, WRITE_BUFFER_SIZE);
385 if (map_file() == -1) {
386 /* mmap failed, try to recover by clobbering */
390 resize_write_buffer(WRITE_BUFFER_SIZE);
391 memset(write_buffer, 0, WRITE_BUFFER_SIZE);
395 /* gcda file, version, stamp checksum. */
396 write_bytes("adcg", 4);
397 write_bytes(version, 4);
398 write_32bit_value(checksum);
400 #ifdef DEBUG_GCDAPROFILING
401 fprintf(stderr, "llvmgcda: [%s]\n", orig_filename);
405 /* Given an array of pointers to counters (counters), increment the n-th one,
406 * where we're also given a pointer to n (predecessor).
408 COMPILER_RT_VISIBILITY
409 void llvm_gcda_increment_indirect_counter(uint32_t *predecessor,
410 uint64_t **counters) {
415 if (pred == 0xffffffff)
417 counter = counters[pred];
419 /* Don't crash if the pred# is out of sync. This can happen due to threads,
420 or because of a TODO in GCOVProfiling.cpp buildEdgeLookupTable(). */
423 #ifdef DEBUG_GCDAPROFILING
426 "llvmgcda: increment_indirect_counter counters=%08llx, pred=%u\n",
427 *counter, *predecessor);
431 COMPILER_RT_VISIBILITY
432 void llvm_gcda_emit_function(uint32_t ident, const char *function_name,
433 uint32_t func_checksum, uint8_t use_extra_checksum,
434 uint32_t cfg_checksum) {
437 if (use_extra_checksum)
439 #ifdef DEBUG_GCDAPROFILING
440 fprintf(stderr, "llvmgcda: function id=0x%08x name=%s\n", ident,
441 function_name ? function_name : "NULL");
443 if (!output_file) return;
446 write_bytes("\0\0\0\1", 4);
448 len += 1 + length_of_string(function_name);
449 write_32bit_value(len);
450 write_32bit_value(ident);
451 write_32bit_value(func_checksum);
452 if (use_extra_checksum)
453 write_32bit_value(cfg_checksum);
455 write_string(function_name);
458 COMPILER_RT_VISIBILITY
459 void llvm_gcda_emit_arcs(uint32_t num_counters, uint64_t *counters) {
461 uint64_t *old_ctrs = NULL;
463 uint64_t save_cur_pos = cur_pos;
465 if (!output_file) return;
467 val = read_le_32bit_value();
469 if (val != (uint32_t)-1) {
470 /* There are counters present in the file. Merge them. */
471 if (val != 0x01a10000) {
472 fprintf(stderr, "profiling: %s: cannot merge previous GCDA file: "
473 "corrupt arc tag (0x%08x)\n",
478 val = read_32bit_value();
479 if (val == (uint32_t)-1 || val / 2 != num_counters) {
480 fprintf(stderr, "profiling: %s: cannot merge previous GCDA file: "
481 "mismatched number of counters (%d)\n",
486 old_ctrs = malloc(sizeof(uint64_t) * num_counters);
487 for (i = 0; i < num_counters; ++i)
488 old_ctrs[i] = read_64bit_value();
491 cur_pos = save_cur_pos;
493 /* Counter #1 (arcs) tag */
494 write_bytes("\0\0\xa1\1", 4);
495 write_32bit_value(num_counters * 2);
496 for (i = 0; i < num_counters; ++i) {
497 counters[i] += (old_ctrs ? old_ctrs[i] : 0);
498 write_64bit_value(counters[i]);
503 #ifdef DEBUG_GCDAPROFILING
504 fprintf(stderr, "llvmgcda: %u arcs\n", num_counters);
505 for (i = 0; i < num_counters; ++i)
506 fprintf(stderr, "llvmgcda: %llu\n", (unsigned long long)counters[i]);
510 COMPILER_RT_VISIBILITY
511 void llvm_gcda_summary_info() {
512 const uint32_t obj_summary_len = 9; /* Length for gcov compatibility. */
515 static uint32_t run_counted = 0; // We only want to increase the run count once.
517 uint64_t save_cur_pos = cur_pos;
519 if (!output_file) return;
521 val = read_le_32bit_value();
523 if (val != (uint32_t)-1) {
524 /* There are counters present in the file. Merge them. */
525 if (val != 0xa1000000) {
526 fprintf(stderr, "profiling: %s: cannot merge previous run count: "
527 "corrupt object tag (0x%08x)\n",
532 val = read_32bit_value(); /* length */
533 if (val != obj_summary_len) {
534 fprintf(stderr, "profiling: %s: cannot merge previous run count: "
535 "mismatched object length (%d)\n",
540 read_32bit_value(); /* checksum, unused */
541 read_32bit_value(); /* num, unused */
542 uint32_t prev_runs = read_32bit_value();
543 /* Add previous run count to new counter, if not already counted before. */
544 runs = run_counted ? prev_runs : prev_runs + 1;
547 cur_pos = save_cur_pos;
549 /* Object summary tag */
550 write_bytes("\0\0\0\xa1", 4);
551 write_32bit_value(obj_summary_len);
552 write_32bit_value(0); /* checksum, unused */
553 write_32bit_value(0); /* num, unused */
554 write_32bit_value(runs);
555 for (i = 3; i < obj_summary_len; ++i)
556 write_32bit_value(0);
558 /* Program summary tag */
559 write_bytes("\0\0\0\xa3", 4); /* tag indicates 1 program */
560 write_32bit_value(0); /* 0 length */
564 #ifdef DEBUG_GCDAPROFILING
565 fprintf(stderr, "llvmgcda: %u runs\n", runs);
569 COMPILER_RT_VISIBILITY
570 void llvm_gcda_end_file() {
571 /* Write out EOF record. */
573 write_bytes("\0\0\0\0\0\0\0\0", 8);
576 fwrite(write_buffer, cur_pos, 1, output_file);
590 #ifdef DEBUG_GCDAPROFILING
591 fprintf(stderr, "llvmgcda: -----\n");
595 COMPILER_RT_VISIBILITY
596 void llvm_register_writeout_function(fn_ptr fn) {
597 fn_list_insert(&writeout_fn_list, fn);
600 COMPILER_RT_VISIBILITY
601 void llvm_writeout_files(void) {
602 struct fn_node *curr = writeout_fn_list.head;
605 if (curr->id == CURRENT_ID) {
612 COMPILER_RT_VISIBILITY
613 void llvm_delete_writeout_function_list(void) {
614 fn_list_remove(&writeout_fn_list);
617 COMPILER_RT_VISIBILITY
618 void llvm_register_flush_function(fn_ptr fn) {
619 fn_list_insert(&flush_fn_list, fn);
622 void __gcov_flush() {
623 struct fn_node* curr = flush_fn_list.head;
631 COMPILER_RT_VISIBILITY
632 void llvm_delete_flush_function_list(void) {
633 fn_list_remove(&flush_fn_list);
636 COMPILER_RT_VISIBILITY
637 void llvm_gcov_init(fn_ptr wfn, fn_ptr ffn) {
638 static int atexit_ran = 0;
641 llvm_register_writeout_function(wfn);
644 llvm_register_flush_function(ffn);
646 if (atexit_ran == 0) {
649 /* Make sure we write out the data and delete the data structures. */
650 atexit(llvm_delete_flush_function_list);
651 atexit(llvm_delete_writeout_function_list);
652 atexit(llvm_writeout_files);