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