GCDAProfiling.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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)(void);
  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(void) {
  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(void) {
  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(void) {
  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(void) {
  221. #if defined(_WIN32)
  222. if (!UnmapViewOfFile(write_buffer)) {
  223. fprintf(stderr, "profiling: %s: cannot unmap mapped view: %lu\n", filename,
  224. GetLastError());
  225. }
  226. if (!CloseHandle(mmap_handle)) {
  227. fprintf(stderr, "profiling: %s: cannot close file mapping handle: %lu\n",
  228. filename, GetLastError());
  229. }
  230. mmap_handle = NULL;
  231. #else
  232. if (munmap(write_buffer, file_size) == -1) {
  233. int errnum = errno;
  234. fprintf(stderr, "profiling: %s: cannot munmap: %s\n", filename,
  235. strerror(errnum));
  236. }
  237. #endif
  238. write_buffer = NULL;
  239. file_size = 0;
  240. }
  241. /*
  242. * --- LLVM line counter API ---
  243. */
  244. /* A file in this case is a translation unit. Each .o file built with line
  245. * profiling enabled will emit to a different file. Only one file may be
  246. * started at a time.
  247. */
  248. COMPILER_RT_VISIBILITY
  249. void llvm_gcda_start_file(const char *orig_filename, uint32_t version,
  250. uint32_t checksum) {
  251. const char *mode = "r+b";
  252. filename = mangle_filename(orig_filename);
  253. /* Try just opening the file. */
  254. fd = open(filename, O_RDWR | O_BINARY);
  255. if (fd == -1) {
  256. /* Try creating the file. */
  257. fd = open(filename, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0644);
  258. if (fd != -1) {
  259. mode = "w+b";
  260. } else {
  261. /* Try creating the directories first then opening the file. */
  262. __llvm_profile_recursive_mkdir(filename);
  263. fd = open(filename, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0644);
  264. if (fd != -1) {
  265. mode = "w+b";
  266. } else {
  267. /* Another process may have created the file just now.
  268. * Try opening it without O_CREAT and O_EXCL. */
  269. fd = open(filename, O_RDWR | O_BINARY);
  270. if (fd == -1) {
  271. /* Bah! It's hopeless. */
  272. int errnum = errno;
  273. fprintf(stderr, "profiling: %s: cannot open: %s\n", filename,
  274. strerror(errnum));
  275. return;
  276. }
  277. }
  278. }
  279. }
  280. /* Try to flock the file to serialize concurrent processes writing out to the
  281. * same GCDA. This can fail if the filesystem doesn't support it, but in that
  282. * case we'll just carry on with the old racy behaviour and hope for the best.
  283. */
  284. lprofLockFd(fd);
  285. output_file = fdopen(fd, mode);
  286. /* Initialize the write buffer. */
  287. new_file = 0;
  288. write_buffer = NULL;
  289. cur_buffer_size = 0;
  290. cur_pos = 0;
  291. if (map_file() == -1) {
  292. /* The file has been created just now (file_size == 0) or mmap failed
  293. * unexpectedly. In the latter case, try to recover by clobbering. */
  294. new_file = 1;
  295. write_buffer = NULL;
  296. resize_write_buffer(WRITE_BUFFER_SIZE);
  297. memset(write_buffer, 0, WRITE_BUFFER_SIZE);
  298. }
  299. /* gcda file, version, stamp checksum. */
  300. {
  301. uint8_t c3 = version >> 24;
  302. uint8_t c2 = (version >> 16) & 255;
  303. uint8_t c1 = (version >> 8) & 255;
  304. gcov_version = c3 >= 'A' ? (c3 - 'A') * 100 + (c2 - '0') * 10 + c1 - '0'
  305. : (c3 - '0') * 10 + c1 - '0';
  306. }
  307. write_32bit_value(GCOV_DATA_MAGIC);
  308. write_32bit_value(version);
  309. write_32bit_value(checksum);
  310. #ifdef DEBUG_GCDAPROFILING
  311. fprintf(stderr, "llvmgcda: [%s]\n", orig_filename);
  312. #endif
  313. }
  314. COMPILER_RT_VISIBILITY
  315. void llvm_gcda_emit_function(uint32_t ident, uint32_t func_checksum,
  316. uint32_t cfg_checksum) {
  317. uint32_t len = 2;
  318. int use_extra_checksum = gcov_version >= 47;
  319. if (use_extra_checksum)
  320. len++;
  321. #ifdef DEBUG_GCDAPROFILING
  322. fprintf(stderr, "llvmgcda: function id=0x%08x\n", ident);
  323. #endif
  324. if (!output_file) return;
  325. /* function tag */
  326. write_32bit_value(GCOV_TAG_FUNCTION);
  327. write_32bit_value(len);
  328. write_32bit_value(ident);
  329. write_32bit_value(func_checksum);
  330. if (use_extra_checksum)
  331. write_32bit_value(cfg_checksum);
  332. }
  333. COMPILER_RT_VISIBILITY
  334. void llvm_gcda_emit_arcs(uint32_t num_counters, uint64_t *counters) {
  335. uint32_t i;
  336. uint64_t *old_ctrs = NULL;
  337. uint32_t val = 0;
  338. uint64_t save_cur_pos = cur_pos;
  339. if (!output_file) return;
  340. val = read_32bit_value();
  341. if (val != (uint32_t)-1) {
  342. /* There are counters present in the file. Merge them. */
  343. if (val != GCOV_TAG_COUNTER_ARCS) {
  344. fprintf(stderr, "profiling: %s: cannot merge previous GCDA file: "
  345. "corrupt arc tag (0x%08x)\n",
  346. filename, val);
  347. return;
  348. }
  349. val = read_32bit_value();
  350. if (val == (uint32_t)-1 || val / 2 != num_counters) {
  351. fprintf(stderr, "profiling: %s: cannot merge previous GCDA file: "
  352. "mismatched number of counters (%d)\n",
  353. filename, val);
  354. return;
  355. }
  356. old_ctrs = malloc(sizeof(uint64_t) * num_counters);
  357. for (i = 0; i < num_counters; ++i)
  358. old_ctrs[i] = read_64bit_value();
  359. }
  360. cur_pos = save_cur_pos;
  361. /* Counter #1 (arcs) tag */
  362. write_32bit_value(GCOV_TAG_COUNTER_ARCS);
  363. write_32bit_value(num_counters * 2);
  364. for (i = 0; i < num_counters; ++i) {
  365. counters[i] += (old_ctrs ? old_ctrs[i] : 0);
  366. write_64bit_value(counters[i]);
  367. }
  368. free(old_ctrs);
  369. #ifdef DEBUG_GCDAPROFILING
  370. fprintf(stderr, "llvmgcda: %u arcs\n", num_counters);
  371. for (i = 0; i < num_counters; ++i)
  372. fprintf(stderr, "llvmgcda: %llu\n", (unsigned long long)counters[i]);
  373. #endif
  374. }
  375. COMPILER_RT_VISIBILITY
  376. void llvm_gcda_summary_info(void) {
  377. uint32_t runs = 1;
  378. static uint32_t run_counted = 0; // We only want to increase the run count once.
  379. uint32_t val = 0;
  380. uint64_t save_cur_pos = cur_pos;
  381. if (!output_file) return;
  382. val = read_32bit_value();
  383. if (val != (uint32_t)-1) {
  384. /* There are counters present in the file. Merge them. */
  385. uint32_t gcov_tag =
  386. gcov_version >= 90 ? GCOV_TAG_OBJECT_SUMMARY : GCOV_TAG_PROGRAM_SUMMARY;
  387. if (val != gcov_tag) {
  388. fprintf(stderr,
  389. "profiling: %s: cannot merge previous run count: "
  390. "corrupt object tag (0x%08x)\n",
  391. filename, val);
  392. return;
  393. }
  394. val = read_32bit_value(); /* length */
  395. uint32_t prev_runs;
  396. if (gcov_version < 90) {
  397. read_32bit_value();
  398. read_32bit_value();
  399. prev_runs = read_32bit_value();
  400. } else {
  401. prev_runs = read_32bit_value();
  402. read_32bit_value();
  403. }
  404. for (uint32_t i = gcov_version < 90 ? 3 : 2; i < val; ++i)
  405. read_32bit_value();
  406. /* Add previous run count to new counter, if not already counted before. */
  407. runs = run_counted ? prev_runs : prev_runs + 1;
  408. }
  409. cur_pos = save_cur_pos;
  410. if (gcov_version >= 90) {
  411. write_32bit_value(GCOV_TAG_OBJECT_SUMMARY);
  412. write_32bit_value(2);
  413. write_32bit_value(runs);
  414. write_32bit_value(0); // sum_max
  415. } else {
  416. // Before gcov 4.8 (r190952), GCOV_TAG_SUMMARY_LENGTH was 9. r190952 set
  417. // GCOV_TAG_SUMMARY_LENGTH to 22. We simply use the smallest length which
  418. // can make gcov read "Runs:".
  419. write_32bit_value(GCOV_TAG_PROGRAM_SUMMARY);
  420. write_32bit_value(3);
  421. write_32bit_value(0);
  422. write_32bit_value(0);
  423. write_32bit_value(runs);
  424. }
  425. run_counted = 1;
  426. #ifdef DEBUG_GCDAPROFILING
  427. fprintf(stderr, "llvmgcda: %u runs\n", runs);
  428. #endif
  429. }
  430. COMPILER_RT_VISIBILITY
  431. void llvm_gcda_end_file(void) {
  432. /* Write out EOF record. */
  433. if (output_file) {
  434. write_bytes("\0\0\0\0\0\0\0\0", 8);
  435. if (new_file) {
  436. fwrite(write_buffer, cur_pos, 1, output_file);
  437. free(write_buffer);
  438. } else {
  439. unmap_file();
  440. }
  441. fflush(output_file);
  442. lprofUnlockFd(fd);
  443. fclose(output_file);
  444. output_file = NULL;
  445. write_buffer = NULL;
  446. }
  447. free(filename);
  448. #ifdef DEBUG_GCDAPROFILING
  449. fprintf(stderr, "llvmgcda: -----\n");
  450. #endif
  451. }
  452. COMPILER_RT_VISIBILITY
  453. void llvm_register_writeout_function(fn_ptr fn) {
  454. fn_list_insert(&writeout_fn_list, fn);
  455. }
  456. COMPILER_RT_VISIBILITY
  457. void llvm_writeout_files(void) {
  458. struct fn_node *curr = writeout_fn_list.head;
  459. while (curr) {
  460. if (curr->id == CURRENT_ID) {
  461. curr->fn();
  462. }
  463. curr = curr->next;
  464. }
  465. }
  466. #ifndef _WIN32
  467. // __attribute__((destructor)) and destructors whose priorities are greater than
  468. // 100 run before this function and can thus be tracked. The priority is
  469. // compatible with GCC 7 onwards.
  470. #if __GNUC__ >= 9
  471. #pragma GCC diagnostic ignored "-Wprio-ctor-dtor"
  472. #endif
  473. __attribute__((destructor(100)))
  474. #endif
  475. static void llvm_writeout_and_clear(void) {
  476. llvm_writeout_files();
  477. fn_list_remove(&writeout_fn_list);
  478. }
  479. COMPILER_RT_VISIBILITY
  480. void llvm_register_reset_function(fn_ptr fn) {
  481. fn_list_insert(&reset_fn_list, fn);
  482. }
  483. COMPILER_RT_VISIBILITY
  484. void llvm_delete_reset_function_list(void) { fn_list_remove(&reset_fn_list); }
  485. COMPILER_RT_VISIBILITY
  486. void llvm_reset_counters(void) {
  487. struct fn_node *curr = reset_fn_list.head;
  488. while (curr) {
  489. if (curr->id == CURRENT_ID) {
  490. curr->fn();
  491. }
  492. curr = curr->next;
  493. }
  494. }
  495. #if !defined(_WIN32)
  496. COMPILER_RT_VISIBILITY
  497. pid_t __gcov_fork() {
  498. pid_t parent_pid = getpid();
  499. pid_t pid = fork();
  500. if (pid == 0) {
  501. pid_t child_pid = getpid();
  502. if (child_pid != parent_pid) {
  503. // The pid changed so we've a fork (one could have its own fork function)
  504. // Just reset the counters for this child process
  505. // threads.
  506. llvm_reset_counters();
  507. }
  508. }
  509. return pid;
  510. }
  511. #endif
  512. COMPILER_RT_VISIBILITY
  513. void llvm_gcov_init(fn_ptr wfn, fn_ptr rfn) {
  514. static int atexit_ran = 0;
  515. if (wfn)
  516. llvm_register_writeout_function(wfn);
  517. if (rfn)
  518. llvm_register_reset_function(rfn);
  519. if (atexit_ran == 0) {
  520. atexit_ran = 1;
  521. /* Make sure we write out the data and delete the data structures. */
  522. atexit(llvm_delete_reset_function_list);
  523. #ifdef _WIN32
  524. atexit(llvm_writeout_and_clear);
  525. #endif
  526. }
  527. }
  528. void __gcov_dump(void) {
  529. for (struct fn_node *f = writeout_fn_list.head; f; f = f->next)
  530. f->fn();
  531. }
  532. void __gcov_reset(void) {
  533. for (struct fn_node *f = reset_fn_list.head; f; f = f->next)
  534. f->fn();
  535. }
  536. #endif