GCDAProfiling.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. /*===- GCDAProfiling.c - Support library for GCDA file emission -----------===*\
  2. |*
  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
  6. |*
  7. |*===----------------------------------------------------------------------===*|
  8. |*
  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.
  12. |*
  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.
  16. |*
  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.
  19. |*
  20. \*===----------------------------------------------------------------------===*/
  21. #if !defined(__Fuchsia__)
  22. #include <errno.h>
  23. #include <fcntl.h>
  24. #include <stdint.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #if defined(_WIN32)
  29. #define WIN32_LEAN_AND_MEAN
  30. #include <windows.h>
  31. #include "WindowsMMap.h"
  32. #else
  33. #include <sys/file.h>
  34. #include <sys/mman.h>
  35. #include <sys/types.h>
  36. #include <unistd.h>
  37. #endif
  38. #include "InstrProfiling.h"
  39. #include "InstrProfilingUtil.h"
  40. /* #define DEBUG_GCDAPROFILING */
  41. enum {
  42. GCOV_DATA_MAGIC = 0x67636461, // "gcda"
  43. GCOV_TAG_FUNCTION = 0x01000000,
  44. GCOV_TAG_COUNTER_ARCS = 0x01a10000,
  45. // GCOV_TAG_OBJECT_SUMMARY superseded GCOV_TAG_PROGRAM_SUMMARY in GCC 9.
  46. GCOV_TAG_OBJECT_SUMMARY = 0xa1000000,
  47. GCOV_TAG_PROGRAM_SUMMARY = 0xa3000000,
  48. };
  49. /*
  50. * --- GCOV file format I/O primitives ---
  51. */
  52. /*
  53. * The current file name we're outputting. Used primarily for error logging.
  54. */
  55. static char *filename = NULL;
  56. /*
  57. * The current file we're outputting.
  58. */
  59. static FILE *output_file = NULL;
  60. /*
  61. * Buffer that we write things into.
  62. */
  63. #define WRITE_BUFFER_SIZE (128 * 1024)
  64. static unsigned char *write_buffer = NULL;
  65. static uint64_t cur_buffer_size = 0;
  66. static uint64_t cur_pos = 0;
  67. static uint64_t file_size = 0;
  68. static int new_file = 0;
  69. static int gcov_version;
  70. #if defined(_WIN32)
  71. static HANDLE mmap_handle = NULL;
  72. #endif
  73. static int fd = -1;
  74. typedef void (*fn_ptr)();
  75. typedef void* dynamic_object_id;
  76. // The address of this variable identifies a given dynamic object.
  77. static dynamic_object_id current_id;
  78. #define CURRENT_ID (&current_id)
  79. struct fn_node {
  80. dynamic_object_id id;
  81. fn_ptr fn;
  82. struct fn_node* next;
  83. };
  84. struct fn_list {
  85. struct fn_node *head, *tail;
  86. };
  87. /*
  88. * A list of functions to write out the data, shared between all dynamic objects.
  89. */
  90. struct fn_list writeout_fn_list;
  91. /*
  92. * A list of reset functions, shared between all dynamic objects.
  93. */
  94. struct fn_list reset_fn_list;
  95. static void fn_list_insert(struct fn_list* list, fn_ptr fn) {
  96. struct fn_node* new_node = malloc(sizeof(struct fn_node));
  97. new_node->fn = fn;
  98. new_node->next = NULL;
  99. new_node->id = CURRENT_ID;
  100. if (!list->head) {
  101. list->head = list->tail = new_node;
  102. } else {
  103. list->tail->next = new_node;
  104. list->tail = new_node;
  105. }
  106. }
  107. static void fn_list_remove(struct fn_list* list) {
  108. struct fn_node* curr = list->head;
  109. struct fn_node* prev = NULL;
  110. struct fn_node* next = NULL;
  111. while (curr) {
  112. next = curr->next;
  113. if (curr->id == CURRENT_ID) {
  114. if (curr == list->head) {
  115. list->head = next;
  116. }
  117. if (curr == list->tail) {
  118. list->tail = prev;
  119. }
  120. if (prev) {
  121. prev->next = next;
  122. }
  123. free(curr);
  124. } else {
  125. prev = curr;
  126. }
  127. curr = next;
  128. }
  129. }
  130. static void resize_write_buffer(uint64_t size) {
  131. if (!new_file) return;
  132. size += cur_pos;
  133. if (size <= cur_buffer_size) return;
  134. size = (size - 1) / WRITE_BUFFER_SIZE + 1;
  135. size *= WRITE_BUFFER_SIZE;
  136. write_buffer = realloc(write_buffer, size);
  137. cur_buffer_size = size;
  138. }
  139. static void write_bytes(const char *s, size_t len) {
  140. resize_write_buffer(len);
  141. memcpy(&write_buffer[cur_pos], s, len);
  142. cur_pos += len;
  143. }
  144. static void write_32bit_value(uint32_t i) {
  145. write_bytes((char*)&i, 4);
  146. }
  147. static void write_64bit_value(uint64_t i) {
  148. // GCOV uses a lo-/hi-word format even on big-endian systems.
  149. // See also GCOVBuffer::readInt64 in LLVM.
  150. uint32_t lo = (uint32_t) i;
  151. uint32_t hi = (uint32_t) (i >> 32);
  152. write_32bit_value(lo);
  153. write_32bit_value(hi);
  154. }
  155. static uint32_t read_32bit_value() {
  156. uint32_t val;
  157. if (new_file)
  158. return (uint32_t)-1;
  159. val = *(uint32_t*)&write_buffer[cur_pos];
  160. cur_pos += 4;
  161. return val;
  162. }
  163. static uint64_t read_64bit_value() {
  164. // GCOV uses a lo-/hi-word format even on big-endian systems.
  165. // See also GCOVBuffer::readInt64 in LLVM.
  166. uint32_t lo = read_32bit_value();
  167. uint32_t hi = read_32bit_value();
  168. return ((uint64_t)hi << 32) | ((uint64_t)lo);
  169. }
  170. static char *mangle_filename(const char *orig_filename) {
  171. char *new_filename;
  172. size_t prefix_len;
  173. int prefix_strip;
  174. const char *prefix = lprofGetPathPrefix(&prefix_strip, &prefix_len);
  175. if (prefix == NULL)
  176. return strdup(orig_filename);
  177. new_filename = malloc(prefix_len + 1 + strlen(orig_filename) + 1);
  178. lprofApplyPathPrefix(new_filename, orig_filename, prefix, prefix_len,
  179. prefix_strip);
  180. return new_filename;
  181. }
  182. static int map_file() {
  183. fseek(output_file, 0L, SEEK_END);
  184. file_size = ftell(output_file);
  185. /* A size of 0 means the file has been created just now (possibly by another
  186. * process in lock-after-open race condition). No need to mmap. */
  187. if (file_size == 0)
  188. return -1;
  189. #if defined(_WIN32)
  190. HANDLE mmap_fd;
  191. if (fd == -1)
  192. mmap_fd = INVALID_HANDLE_VALUE;
  193. else
  194. mmap_fd = (HANDLE)_get_osfhandle(fd);
  195. mmap_handle = CreateFileMapping(mmap_fd, NULL, PAGE_READWRITE, DWORD_HI(file_size), DWORD_LO(file_size), NULL);
  196. if (mmap_handle == NULL) {
  197. fprintf(stderr, "profiling: %s: cannot create file mapping: %lu\n",
  198. filename, GetLastError());
  199. return -1;
  200. }
  201. write_buffer = MapViewOfFile(mmap_handle, FILE_MAP_WRITE, 0, 0, file_size);
  202. if (write_buffer == NULL) {
  203. fprintf(stderr, "profiling: %s: cannot map: %lu\n", filename,
  204. GetLastError());
  205. CloseHandle(mmap_handle);
  206. return -1;
  207. }
  208. #else
  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. #endif
  218. return 0;
  219. }
  220. static void unmap_file() {
  221. #if defined(_WIN32)
  222. if (!FlushViewOfFile(write_buffer, file_size)) {
  223. fprintf(stderr, "profiling: %s: cannot flush mapped view: %lu\n", filename,
  224. GetLastError());
  225. }
  226. if (!UnmapViewOfFile(write_buffer)) {
  227. fprintf(stderr, "profiling: %s: cannot unmap mapped view: %lu\n", filename,
  228. GetLastError());
  229. }
  230. if (!CloseHandle(mmap_handle)) {
  231. fprintf(stderr, "profiling: %s: cannot close file mapping handle: %lu\n",
  232. filename, GetLastError());
  233. }
  234. mmap_handle = NULL;
  235. #else
  236. if (munmap(write_buffer, file_size) == -1) {
  237. int errnum = errno;
  238. fprintf(stderr, "profiling: %s: cannot munmap: %s\n", filename,
  239. strerror(errnum));
  240. }
  241. #endif
  242. write_buffer = NULL;
  243. file_size = 0;
  244. }
  245. /*
  246. * --- LLVM line counter API ---
  247. */
  248. /* A file in this case is a translation unit. Each .o file built with line
  249. * profiling enabled will emit to a different file. Only one file may be
  250. * started at a time.
  251. */
  252. COMPILER_RT_VISIBILITY
  253. void llvm_gcda_start_file(const char *orig_filename, uint32_t version,
  254. uint32_t checksum) {
  255. const char *mode = "r+b";
  256. filename = mangle_filename(orig_filename);
  257. /* Try just opening the file. */
  258. fd = open(filename, O_RDWR | O_BINARY);
  259. if (fd == -1) {
  260. /* Try creating the file. */
  261. fd = open(filename, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0644);
  262. if (fd != -1) {
  263. mode = "w+b";
  264. } else {
  265. /* Try creating the directories first then opening the file. */
  266. __llvm_profile_recursive_mkdir(filename);
  267. fd = open(filename, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0644);
  268. if (fd != -1) {
  269. mode = "w+b";
  270. } else {
  271. /* Another process may have created the file just now.
  272. * Try opening it without O_CREAT and O_EXCL. */
  273. fd = open(filename, O_RDWR | O_BINARY);
  274. if (fd == -1) {
  275. /* Bah! It's hopeless. */
  276. int errnum = errno;
  277. fprintf(stderr, "profiling: %s: cannot open: %s\n", filename,
  278. strerror(errnum));
  279. return;
  280. }
  281. }
  282. }
  283. }
  284. /* Try to flock the file to serialize concurrent processes writing out to the
  285. * same GCDA. This can fail if the filesystem doesn't support it, but in that
  286. * case we'll just carry on with the old racy behaviour and hope for the best.
  287. */
  288. lprofLockFd(fd);
  289. output_file = fdopen(fd, mode);
  290. /* Initialize the write buffer. */
  291. new_file = 0;
  292. write_buffer = NULL;
  293. cur_buffer_size = 0;
  294. cur_pos = 0;
  295. if (map_file() == -1) {
  296. /* The file has been created just now (file_size == 0) or mmap failed
  297. * unexpectedly. In the latter case, try to recover by clobbering. */
  298. new_file = 1;
  299. write_buffer = NULL;
  300. resize_write_buffer(WRITE_BUFFER_SIZE);
  301. memset(write_buffer, 0, WRITE_BUFFER_SIZE);
  302. }
  303. /* gcda file, version, stamp checksum. */
  304. {
  305. uint8_t c3 = version >> 24;
  306. uint8_t c2 = (version >> 16) & 255;
  307. uint8_t c1 = (version >> 8) & 255;
  308. gcov_version = c3 >= 'A' ? (c3 - 'A') * 100 + (c2 - '0') * 10 + c1 - '0'
  309. : (c3 - '0') * 10 + c1 - '0';
  310. }
  311. write_32bit_value(GCOV_DATA_MAGIC);
  312. write_32bit_value(version);
  313. write_32bit_value(checksum);
  314. #ifdef DEBUG_GCDAPROFILING
  315. fprintf(stderr, "llvmgcda: [%s]\n", orig_filename);
  316. #endif
  317. }
  318. COMPILER_RT_VISIBILITY
  319. void llvm_gcda_emit_function(uint32_t ident, uint32_t func_checksum,
  320. uint32_t cfg_checksum) {
  321. uint32_t len = 2;
  322. int use_extra_checksum = gcov_version >= 47;
  323. if (use_extra_checksum)
  324. len++;
  325. #ifdef DEBUG_GCDAPROFILING
  326. fprintf(stderr, "llvmgcda: function id=0x%08x\n", ident);
  327. #endif
  328. if (!output_file) return;
  329. /* function tag */
  330. write_32bit_value(GCOV_TAG_FUNCTION);
  331. write_32bit_value(len);
  332. write_32bit_value(ident);
  333. write_32bit_value(func_checksum);
  334. if (use_extra_checksum)
  335. write_32bit_value(cfg_checksum);
  336. }
  337. COMPILER_RT_VISIBILITY
  338. void llvm_gcda_emit_arcs(uint32_t num_counters, uint64_t *counters) {
  339. uint32_t i;
  340. uint64_t *old_ctrs = NULL;
  341. uint32_t val = 0;
  342. uint64_t save_cur_pos = cur_pos;
  343. if (!output_file) return;
  344. val = read_32bit_value();
  345. if (val != (uint32_t)-1) {
  346. /* There are counters present in the file. Merge them. */
  347. if (val != GCOV_TAG_COUNTER_ARCS) {
  348. fprintf(stderr, "profiling: %s: cannot merge previous GCDA file: "
  349. "corrupt arc tag (0x%08x)\n",
  350. filename, val);
  351. return;
  352. }
  353. val = read_32bit_value();
  354. if (val == (uint32_t)-1 || val / 2 != num_counters) {
  355. fprintf(stderr, "profiling: %s: cannot merge previous GCDA file: "
  356. "mismatched number of counters (%d)\n",
  357. filename, val);
  358. return;
  359. }
  360. old_ctrs = malloc(sizeof(uint64_t) * num_counters);
  361. for (i = 0; i < num_counters; ++i)
  362. old_ctrs[i] = read_64bit_value();
  363. }
  364. cur_pos = save_cur_pos;
  365. /* Counter #1 (arcs) tag */
  366. write_32bit_value(GCOV_TAG_COUNTER_ARCS);
  367. write_32bit_value(num_counters * 2);
  368. for (i = 0; i < num_counters; ++i) {
  369. counters[i] += (old_ctrs ? old_ctrs[i] : 0);
  370. write_64bit_value(counters[i]);
  371. }
  372. free(old_ctrs);
  373. #ifdef DEBUG_GCDAPROFILING
  374. fprintf(stderr, "llvmgcda: %u arcs\n", num_counters);
  375. for (i = 0; i < num_counters; ++i)
  376. fprintf(stderr, "llvmgcda: %llu\n", (unsigned long long)counters[i]);
  377. #endif
  378. }
  379. COMPILER_RT_VISIBILITY
  380. void llvm_gcda_summary_info() {
  381. uint32_t runs = 1;
  382. static uint32_t run_counted = 0; // We only want to increase the run count once.
  383. uint32_t val = 0;
  384. uint64_t save_cur_pos = cur_pos;
  385. if (!output_file) return;
  386. val = read_32bit_value();
  387. if (val != (uint32_t)-1) {
  388. /* There are counters present in the file. Merge them. */
  389. uint32_t gcov_tag =
  390. gcov_version >= 90 ? GCOV_TAG_OBJECT_SUMMARY : GCOV_TAG_PROGRAM_SUMMARY;
  391. if (val != gcov_tag) {
  392. fprintf(stderr,
  393. "profiling: %s: cannot merge previous run count: "
  394. "corrupt object tag (0x%08x)\n",
  395. filename, val);
  396. return;
  397. }
  398. val = read_32bit_value(); /* length */
  399. uint32_t prev_runs;
  400. if (gcov_version < 90) {
  401. read_32bit_value();
  402. read_32bit_value();
  403. prev_runs = read_32bit_value();
  404. } else {
  405. prev_runs = read_32bit_value();
  406. read_32bit_value();
  407. }
  408. for (uint32_t i = gcov_version < 90 ? 3 : 2; i < val; ++i)
  409. read_32bit_value();
  410. /* Add previous run count to new counter, if not already counted before. */
  411. runs = run_counted ? prev_runs : prev_runs + 1;
  412. }
  413. cur_pos = save_cur_pos;
  414. if (gcov_version >= 90) {
  415. write_32bit_value(GCOV_TAG_OBJECT_SUMMARY);
  416. write_32bit_value(2);
  417. write_32bit_value(runs);
  418. write_32bit_value(0); // sum_max
  419. } else {
  420. // Before gcov 4.8 (r190952), GCOV_TAG_SUMMARY_LENGTH was 9. r190952 set
  421. // GCOV_TAG_SUMMARY_LENGTH to 22. We simply use the smallest length which
  422. // can make gcov read "Runs:".
  423. write_32bit_value(GCOV_TAG_PROGRAM_SUMMARY);
  424. write_32bit_value(3);
  425. write_32bit_value(0);
  426. write_32bit_value(0);
  427. write_32bit_value(runs);
  428. }
  429. run_counted = 1;
  430. #ifdef DEBUG_GCDAPROFILING
  431. fprintf(stderr, "llvmgcda: %u runs\n", runs);
  432. #endif
  433. }
  434. COMPILER_RT_VISIBILITY
  435. void llvm_gcda_end_file() {
  436. /* Write out EOF record. */
  437. if (output_file) {
  438. write_bytes("\0\0\0\0\0\0\0\0", 8);
  439. if (new_file) {
  440. fwrite(write_buffer, cur_pos, 1, output_file);
  441. free(write_buffer);
  442. } else {
  443. unmap_file();
  444. }
  445. fflush(output_file);
  446. lprofUnlockFd(fd);
  447. fclose(output_file);
  448. output_file = NULL;
  449. write_buffer = NULL;
  450. }
  451. free(filename);
  452. #ifdef DEBUG_GCDAPROFILING
  453. fprintf(stderr, "llvmgcda: -----\n");
  454. #endif
  455. }
  456. COMPILER_RT_VISIBILITY
  457. void llvm_register_writeout_function(fn_ptr fn) {
  458. fn_list_insert(&writeout_fn_list, fn);
  459. }
  460. COMPILER_RT_VISIBILITY
  461. void llvm_writeout_files(void) {
  462. struct fn_node *curr = writeout_fn_list.head;
  463. while (curr) {
  464. if (curr->id == CURRENT_ID) {
  465. curr->fn();
  466. }
  467. curr = curr->next;
  468. }
  469. }
  470. #ifndef _WIN32
  471. // __attribute__((destructor)) and destructors whose priorities are greater than
  472. // 100 run before this function and can thus be tracked. The priority is
  473. // compatible with GCC 7 onwards.
  474. #if __GNUC__ >= 9
  475. #pragma GCC diagnostic ignored "-Wprio-ctor-dtor"
  476. #endif
  477. __attribute__((destructor(100)))
  478. #endif
  479. static void llvm_writeout_and_clear(void) {
  480. llvm_writeout_files();
  481. fn_list_remove(&writeout_fn_list);
  482. }
  483. COMPILER_RT_VISIBILITY
  484. void llvm_register_reset_function(fn_ptr fn) {
  485. fn_list_insert(&reset_fn_list, fn);
  486. }
  487. COMPILER_RT_VISIBILITY
  488. void llvm_delete_reset_function_list(void) { fn_list_remove(&reset_fn_list); }
  489. COMPILER_RT_VISIBILITY
  490. void llvm_reset_counters(void) {
  491. struct fn_node *curr = reset_fn_list.head;
  492. while (curr) {
  493. if (curr->id == CURRENT_ID) {
  494. curr->fn();
  495. }
  496. curr = curr->next;
  497. }
  498. }
  499. #if !defined(_WIN32)
  500. COMPILER_RT_VISIBILITY
  501. pid_t __gcov_fork() {
  502. pid_t parent_pid = getpid();
  503. pid_t pid = fork();
  504. if (pid == 0) {
  505. pid_t child_pid = getpid();
  506. if (child_pid != parent_pid) {
  507. // The pid changed so we've a fork (one could have its own fork function)
  508. // Just reset the counters for this child process
  509. // threads.
  510. llvm_reset_counters();
  511. }
  512. }
  513. return pid;
  514. }
  515. #endif
  516. COMPILER_RT_VISIBILITY
  517. void llvm_gcov_init(fn_ptr wfn, fn_ptr rfn) {
  518. static int atexit_ran = 0;
  519. if (wfn)
  520. llvm_register_writeout_function(wfn);
  521. if (rfn)
  522. llvm_register_reset_function(rfn);
  523. if (atexit_ran == 0) {
  524. atexit_ran = 1;
  525. /* Make sure we write out the data and delete the data structures. */
  526. atexit(llvm_delete_reset_function_list);
  527. #ifdef _WIN32
  528. atexit(llvm_writeout_and_clear);
  529. #endif
  530. }
  531. }
  532. void __gcov_dump(void) {
  533. for (struct fn_node *f = writeout_fn_list.head; f; f = f->next)
  534. f->fn();
  535. }
  536. void __gcov_reset(void) {
  537. for (struct fn_node *f = reset_fn_list.head; f; f = f->next)
  538. f->fn();
  539. }
  540. #endif