1 //===-- sanitizer_coverage.cc ---------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Sanitizer Coverage.
11 // This file implements run-time support for a poor man's coverage tool.
13 // Compiler instrumentation:
14 // For every interesting basic block the compiler injects the following code:
16 // __sanitizer_cov(&Guard);
18 // At the module start up time __sanitizer_cov_module_init sets the guards
19 // to consecutive negative numbers (-1, -2, -3, ...).
20 // It's fine to call __sanitizer_cov more than once for a given block.
23 // - __sanitizer_cov(): record that we've executed the PC (GET_CALLER_PC).
24 // and atomically set Guard to -Guard.
25 // - __sanitizer_cov_dump: dump the coverage data to disk.
26 // For every module of the current process that has coverage data
27 // this will create a file module_name.PID.sancov.
29 // The file format is simple: the first 8 bytes is the magic,
30 // one of 0xC0BFFFFFFFFFFF64 and 0xC0BFFFFFFFFFFF32. The last byte of the
31 // magic defines the size of the following offsets.
32 // The rest of the data is the offsets in the module.
34 // Eventually, this coverage implementation should be obsoleted by a more
35 // powerful general purpose Clang/LLVM coverage instrumentation.
36 // Consider this implementation as prototype.
38 // FIXME: support (or at least test with) dlclose.
39 //===----------------------------------------------------------------------===//
41 #include "sanitizer_allocator_internal.h"
42 #include "sanitizer_common.h"
43 #include "sanitizer_libc.h"
44 #include "sanitizer_mutex.h"
45 #include "sanitizer_procmaps.h"
46 #include "sanitizer_stacktrace.h"
47 #include "sanitizer_symbolizer.h"
48 #include "sanitizer_flags.h"
50 using namespace __sanitizer;
52 static const u64 kMagic64 = 0xC0BFFFFFFFFFFF64ULL;
53 static const u64 kMagic32 = 0xC0BFFFFFFFFFFF32ULL;
54 static const uptr kNumWordsForMagic = SANITIZER_WORDSIZE == 64 ? 1 : 2;
55 static const u64 kMagic = SANITIZER_WORDSIZE == 64 ? kMagic64 : kMagic32;
57 static atomic_uint32_t dump_once_guard; // Ensure that CovDump runs only once.
59 static atomic_uintptr_t coverage_counter;
60 static atomic_uintptr_t caller_callee_counter;
62 static void ResetGlobalCounters() {
63 return atomic_store(&coverage_counter, 0, memory_order_relaxed);
64 return atomic_store(&caller_callee_counter, 0, memory_order_relaxed);
67 // pc_array is the array containing the covered PCs.
68 // To make the pc_array thread- and async-signal-safe it has to be large enough.
69 // 128M counters "ought to be enough for anybody" (4M on 32-bit).
71 // With coverage_direct=1 in ASAN_OPTIONS, pc_array memory is mapped to a file.
72 // In this mode, __sanitizer_cov_dump does nothing, and CovUpdateMapping()
73 // dump current memory layout to another file.
75 static bool cov_sandboxed = false;
76 static fd_t cov_fd = kInvalidFd;
77 static unsigned int cov_max_block_size = 0;
78 static bool coverage_enabled = false;
79 static const char *coverage_dir;
81 namespace __sanitizer {
90 void AfterFork(int child_pid);
91 void Extend(uptr npcs);
92 void Add(uptr pc, u32 *guard);
93 void IndirCall(uptr caller, uptr callee, uptr callee_cache[],
95 void DumpCallerCalleePairs();
103 void TraceBasicBlock(u32 *id);
105 void InitializeGuardArray(s32 *guards);
106 void InitializeGuards(s32 *guards, uptr n, const char *module_name,
108 void InitializeCounters(u8 *counters, uptr n);
109 void ReinitializeGuards();
110 uptr GetNumberOf8bitCounters();
111 uptr Update8bitCounterBitsetAndClearCounters(u8 *bitset);
117 struct NamedPcRange {
118 const char *copied_module_name;
119 uptr beg, end; // elements [beg,end) in pc_array.
123 void UpdateModuleNameVec(uptr caller_pc, uptr range_beg, uptr range_end);
124 void GetRangeOffsets(const NamedPcRange& r, Symbolizer* s,
125 InternalMmapVector<uptr>* offsets) const;
127 // Maximal size pc array may ever grow.
128 // We MmapNoReserve this space to ensure that the array is contiguous.
129 static const uptr kPcArrayMaxSize =
130 FIRST_32_SECOND_64(1 << (SANITIZER_ANDROID ? 24 : 26), 1 << 27);
131 // The amount file mapping for the pc array is grown by.
132 static const uptr kPcArrayMmapSize = 64 * 1024;
134 // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
135 // much RAM as it really needs.
137 // Index of the first available pc_array slot.
138 atomic_uintptr_t pc_array_index;
140 atomic_uintptr_t pc_array_size;
141 // Current file mapped size of the pc array.
142 uptr pc_array_mapped_size;
143 // Descriptor of the file mapped pc array.
146 // Vector of coverage guard arrays, protected by mu.
147 InternalMmapVectorNoCtor<s32*> guard_array_vec;
149 // Vector of module and compilation unit pc ranges.
150 InternalMmapVectorNoCtor<NamedPcRange> comp_unit_name_vec;
151 InternalMmapVectorNoCtor<NamedPcRange> module_name_vec;
153 struct CounterAndSize {
158 InternalMmapVectorNoCtor<CounterAndSize> counters_vec;
159 uptr num_8bit_counters;
161 // Caller-Callee (cc) array, size and current index.
162 static const uptr kCcArrayMaxSize = FIRST_32_SECOND_64(1 << 18, 1 << 24);
164 atomic_uintptr_t cc_array_index;
165 atomic_uintptr_t cc_array_size;
167 // Tracing event array, size and current pointer.
168 // We record all events (basic block entries) in a global buffer of u32
169 // values. Each such value is the index in pc_array.
170 // So far the tracing is highly experimental:
171 // - not thread-safe;
172 // - does not support long traces;
173 // - not tuned for performance.
174 static const uptr kTrEventArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 30);
176 uptr tr_event_array_size;
177 u32 *tr_event_pointer;
178 static const uptr kTrPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
183 static CoverageData coverage_data;
185 void CovUpdateMapping(const char *path, uptr caller_pc = 0);
187 void CoverageData::DirectOpen() {
188 InternalScopedString path(kMaxPathLength);
189 internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
190 coverage_dir, internal_getpid());
191 pc_fd = OpenFile(path.data(), RdWr);
192 if (pc_fd == kInvalidFd) {
193 Report("Coverage: failed to open %s for reading/writing\n", path.data());
197 pc_array_mapped_size = 0;
198 CovUpdateMapping(coverage_dir);
201 void CoverageData::Init() {
205 void CoverageData::Enable() {
208 pc_array = reinterpret_cast<uptr *>(
209 MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
210 atomic_store(&pc_array_index, 0, memory_order_relaxed);
211 if (common_flags()->coverage_direct) {
212 atomic_store(&pc_array_size, 0, memory_order_relaxed);
214 atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
217 cc_array = reinterpret_cast<uptr **>(MmapNoReserveOrDie(
218 sizeof(uptr *) * kCcArrayMaxSize, "CovInit::cc_array"));
219 atomic_store(&cc_array_size, kCcArrayMaxSize, memory_order_relaxed);
220 atomic_store(&cc_array_index, 0, memory_order_relaxed);
222 // Allocate tr_event_array with a guard page at the end.
223 tr_event_array = reinterpret_cast<u32 *>(MmapNoReserveOrDie(
224 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize + GetMmapGranularity(),
225 "CovInit::tr_event_array"));
227 reinterpret_cast<uptr>(&tr_event_array[kTrEventArrayMaxSize]),
228 GetMmapGranularity());
229 tr_event_array_size = kTrEventArrayMaxSize;
230 tr_event_pointer = tr_event_array;
232 num_8bit_counters = 0;
235 void CoverageData::InitializeGuardArray(s32 *guards) {
236 Enable(); // Make sure coverage is enabled at this point.
238 for (s32 j = 1; j <= n; j++) {
239 uptr idx = atomic_load_relaxed(&pc_array_index);
240 atomic_store_relaxed(&pc_array_index, idx + 1);
241 guards[j] = -static_cast<s32>(idx + 1);
245 void CoverageData::Disable() {
247 UnmapOrDie(pc_array, sizeof(uptr) * kPcArrayMaxSize);
251 UnmapOrDie(cc_array, sizeof(uptr *) * kCcArrayMaxSize);
254 if (tr_event_array) {
255 UnmapOrDie(tr_event_array,
256 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize +
257 GetMmapGranularity());
258 tr_event_array = nullptr;
259 tr_event_pointer = nullptr;
261 if (pc_fd != kInvalidFd) {
267 void CoverageData::ReinitializeGuards() {
268 // Assuming single thread.
269 atomic_store(&pc_array_index, 0, memory_order_relaxed);
270 for (uptr i = 0; i < guard_array_vec.size(); i++)
271 InitializeGuardArray(guard_array_vec[i]);
274 void CoverageData::ReInit() {
276 if (coverage_enabled) {
277 if (common_flags()->coverage_direct) {
278 // In memory-mapped mode we must extend the new file to the known array
280 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
281 uptr npcs = size / sizeof(uptr);
283 if (size) Extend(npcs);
284 if (coverage_enabled) CovUpdateMapping(coverage_dir);
289 // Re-initialize the guards.
290 // We are single-threaded now, no need to grab any lock.
291 CHECK_EQ(atomic_load(&pc_array_index, memory_order_relaxed), 0);
292 ReinitializeGuards();
295 void CoverageData::BeforeFork() {
299 void CoverageData::AfterFork(int child_pid) {
300 // We are single-threaded so it's OK to release the lock early.
302 if (child_pid == 0) ReInit();
305 // Extend coverage PC array to fit additional npcs elements.
306 void CoverageData::Extend(uptr npcs) {
307 if (!common_flags()->coverage_direct) return;
308 SpinMutexLock l(&mu);
310 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
311 size += npcs * sizeof(uptr);
313 if (coverage_enabled && size > pc_array_mapped_size) {
314 if (pc_fd == kInvalidFd) DirectOpen();
315 CHECK_NE(pc_fd, kInvalidFd);
317 uptr new_mapped_size = pc_array_mapped_size;
318 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
319 CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
321 // Extend the file and map the new space at the end of pc_array.
322 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
324 if (internal_iserror(res, &err)) {
325 Printf("failed to extend raw coverage file: %d\n", err);
329 uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
330 void *p = MapWritableFileToMemory((void *)next_map_base,
331 new_mapped_size - pc_array_mapped_size,
332 pc_fd, pc_array_mapped_size);
333 CHECK_EQ((uptr)p, next_map_base);
334 pc_array_mapped_size = new_mapped_size;
337 atomic_store(&pc_array_size, size, memory_order_release);
340 void CoverageData::InitializeCounters(u8 *counters, uptr n) {
341 if (!counters) return;
342 CHECK_EQ(reinterpret_cast<uptr>(counters) % 16, 0);
343 n = RoundUpTo(n, 16); // The compiler must ensure that counters is 16-aligned.
344 SpinMutexLock l(&mu);
345 counters_vec.push_back({counters, n});
346 num_8bit_counters += n;
349 void CoverageData::UpdateModuleNameVec(uptr caller_pc, uptr range_beg,
351 auto sym = Symbolizer::GetOrInit();
354 const char *module_name = sym->GetModuleNameForPc(caller_pc);
355 if (!module_name) return;
356 if (module_name_vec.empty() ||
357 module_name_vec.back().copied_module_name != module_name)
358 module_name_vec.push_back({module_name, range_beg, range_end});
360 module_name_vec.back().end = range_end;
363 void CoverageData::InitializeGuards(s32 *guards, uptr n,
364 const char *comp_unit_name,
366 // The array 'guards' has n+1 elements, we use the element zero
368 CHECK_LT(n, 1 << 30);
369 guards[0] = static_cast<s32>(n);
370 InitializeGuardArray(guards);
371 SpinMutexLock l(&mu);
372 uptr range_end = atomic_load(&pc_array_index, memory_order_relaxed);
373 uptr range_beg = range_end - n;
374 comp_unit_name_vec.push_back({comp_unit_name, range_beg, range_end});
375 guard_array_vec.push_back(guards);
376 UpdateModuleNameVec(caller_pc, range_beg, range_end);
379 static const uptr kBundleCounterBits = 16;
381 // When coverage_order_pcs==true and SANITIZER_WORDSIZE==64
382 // we insert the global counter into the first 16 bits of the PC.
383 uptr BundlePcAndCounter(uptr pc, uptr counter) {
384 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
386 static const uptr kMaxCounter = (1 << kBundleCounterBits) - 1;
387 if (counter > kMaxCounter)
388 counter = kMaxCounter;
389 CHECK_EQ(0, pc >> (SANITIZER_WORDSIZE - kBundleCounterBits));
390 return pc | (counter << (SANITIZER_WORDSIZE - kBundleCounterBits));
393 uptr UnbundlePc(uptr bundle) {
394 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
396 return (bundle << kBundleCounterBits) >> kBundleCounterBits;
399 uptr UnbundleCounter(uptr bundle) {
400 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
402 return bundle >> (SANITIZER_WORDSIZE - kBundleCounterBits);
405 // If guard is negative, atomically set it to -guard and store the PC in
407 void CoverageData::Add(uptr pc, u32 *guard) {
408 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
409 s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
410 if (guard_value >= 0) return;
412 atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
413 if (!pc_array) return;
415 uptr idx = -guard_value - 1;
416 if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
417 return; // May happen after fork when pc_array_index becomes 0.
418 CHECK_LT(idx * sizeof(uptr),
419 atomic_load(&pc_array_size, memory_order_acquire));
420 uptr counter = atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
421 pc_array[idx] = BundlePcAndCounter(pc, counter);
424 // Registers a pair caller=>callee.
425 // When a given caller is seen for the first time, the callee_cache is added
426 // to the global array cc_array, callee_cache[0] is set to caller and
427 // callee_cache[1] is set to cache_size.
428 // Then we are trying to add callee to callee_cache [2,cache_size) if it is
430 // If the cache is full we drop the callee (may want to fix this later).
431 void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
433 if (!cc_array) return;
434 atomic_uintptr_t *atomic_callee_cache =
435 reinterpret_cast<atomic_uintptr_t *>(callee_cache);
437 if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
438 memory_order_seq_cst)) {
439 uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
440 CHECK_LT(idx * sizeof(uptr),
441 atomic_load(&cc_array_size, memory_order_acquire));
442 callee_cache[1] = cache_size;
443 cc_array[idx] = callee_cache;
445 CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
446 for (uptr i = 2; i < cache_size; i++) {
448 if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
449 memory_order_seq_cst)) {
450 atomic_fetch_add(&caller_callee_counter, 1, memory_order_relaxed);
453 if (was == callee) // Already have this callee.
458 uptr CoverageData::GetNumberOf8bitCounters() {
459 return num_8bit_counters;
462 // Map every 8bit counter to a 8-bit bitset and clear the counter.
463 uptr CoverageData::Update8bitCounterBitsetAndClearCounters(u8 *bitset) {
464 uptr num_new_bits = 0;
466 // For better speed we map 8 counters to 8 bytes of bitset at once.
467 static const uptr kBatchSize = 8;
468 CHECK_EQ(reinterpret_cast<uptr>(bitset) % kBatchSize, 0);
469 for (uptr i = 0, len = counters_vec.size(); i < len; i++) {
470 u8 *c = counters_vec[i].counters;
471 uptr n = counters_vec[i].n;
473 CHECK_EQ(cur % kBatchSize, 0);
474 CHECK_EQ(reinterpret_cast<uptr>(c) % kBatchSize, 0);
476 internal_bzero_aligned16(c, n);
480 for (uptr j = 0; j < n; j += kBatchSize, cur += kBatchSize) {
481 CHECK_LT(cur, num_8bit_counters);
482 u64 *pc64 = reinterpret_cast<u64*>(c + j);
483 u64 *pb64 = reinterpret_cast<u64*>(bitset + cur);
485 u64 old_bits_64 = *pb64;
486 u64 new_bits_64 = old_bits_64;
489 for (uptr k = 0; k < kBatchSize; k++) {
490 u64 x = (c64 >> (8 * k)) & 0xff;
493 /**/ if (x >= 128) bit = 128;
494 else if (x >= 32) bit = 64;
495 else if (x >= 16) bit = 32;
496 else if (x >= 8) bit = 16;
497 else if (x >= 4) bit = 8;
498 else if (x >= 3) bit = 4;
499 else if (x >= 2) bit = 2;
500 else if (x >= 1) bit = 1;
501 u64 mask = bit << (8 * k);
502 if (!(new_bits_64 & mask)) {
512 CHECK_EQ(cur, num_8bit_counters);
516 uptr *CoverageData::data() {
520 uptr CoverageData::size() const {
521 return atomic_load(&pc_array_index, memory_order_relaxed);
524 // Block layout for packed file format: header, followed by module name (no
525 // trailing zero), followed by data blob.
528 unsigned int module_name_length;
529 unsigned int data_length;
532 static void CovWritePacked(int pid, const char *module, const void *blob,
533 unsigned int blob_size) {
534 if (cov_fd == kInvalidFd) return;
535 unsigned module_name_length = internal_strlen(module);
536 CovHeader header = {pid, module_name_length, blob_size};
538 if (cov_max_block_size == 0) {
539 // Writing to a file. Just go ahead.
540 WriteToFile(cov_fd, &header, sizeof(header));
541 WriteToFile(cov_fd, module, module_name_length);
542 WriteToFile(cov_fd, blob, blob_size);
544 // Writing to a socket. We want to split the data into appropriately sized
546 InternalScopedBuffer<char> block(cov_max_block_size);
547 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
548 uptr header_size_with_module = sizeof(header) + module_name_length;
549 CHECK_LT(header_size_with_module, cov_max_block_size);
550 unsigned int max_payload_size =
551 cov_max_block_size - header_size_with_module;
552 char *block_pos = block.data();
553 internal_memcpy(block_pos, &header, sizeof(header));
554 block_pos += sizeof(header);
555 internal_memcpy(block_pos, module, module_name_length);
556 block_pos += module_name_length;
557 char *block_data_begin = block_pos;
558 const char *blob_pos = (const char *)blob;
559 while (blob_size > 0) {
560 unsigned int payload_size = Min(blob_size, max_payload_size);
561 blob_size -= payload_size;
562 internal_memcpy(block_data_begin, blob_pos, payload_size);
563 blob_pos += payload_size;
564 ((CovHeader *)block.data())->data_length = payload_size;
565 WriteToFile(cov_fd, block.data(), header_size_with_module + payload_size);
570 // If packed = false: <name>.<pid>.<sancov> (name = module name).
571 // If packed = true and name == 0: <pid>.<sancov>.<packed>.
572 // If packed = true and name != 0: <name>.<sancov>.<packed> (name is
574 static fd_t CovOpenFile(InternalScopedString *path, bool packed,
575 const char *name, const char *extension = "sancov") {
579 path->append("%s/%s.%zd.%s", coverage_dir, name, internal_getpid(),
583 path->append("%s/%zd.%s.packed", coverage_dir, internal_getpid(),
586 path->append("%s/%s.%s.packed", coverage_dir, name, extension);
589 fd_t fd = OpenFile(path->data(), WrOnly, &err);
590 if (fd == kInvalidFd)
591 Report("SanitizerCoverage: failed to open %s for writing (reason: %d)\n",
596 // Dump trace PCs and trace events into two separate files.
597 void CoverageData::DumpTrace() {
598 uptr max_idx = tr_event_pointer - tr_event_array;
599 if (!max_idx) return;
600 auto sym = Symbolizer::GetOrInit();
603 InternalScopedString out(32 << 20);
604 for (uptr i = 0, n = size(); i < n; i++) {
605 const char *module_name = "<unknown>";
606 uptr module_address = 0;
607 sym->GetModuleNameAndOffsetForPC(UnbundlePc(pc_array[i]), &module_name,
609 out.append("%s 0x%zx\n", module_name, module_address);
611 InternalScopedString path(kMaxPathLength);
612 fd_t fd = CovOpenFile(&path, false, "trace-points");
613 if (fd == kInvalidFd) return;
614 WriteToFile(fd, out.data(), out.length());
617 fd = CovOpenFile(&path, false, "trace-compunits");
618 if (fd == kInvalidFd) return;
620 for (uptr i = 0; i < comp_unit_name_vec.size(); i++)
621 out.append("%s\n", comp_unit_name_vec[i].copied_module_name);
622 WriteToFile(fd, out.data(), out.length());
625 fd = CovOpenFile(&path, false, "trace-events");
626 if (fd == kInvalidFd) return;
627 uptr bytes_to_write = max_idx * sizeof(tr_event_array[0]);
628 u8 *event_bytes = reinterpret_cast<u8*>(tr_event_array);
629 // The trace file could be huge, and may not be written with a single syscall.
630 while (bytes_to_write) {
631 uptr actually_written;
632 if (WriteToFile(fd, event_bytes, bytes_to_write, &actually_written) &&
633 actually_written <= bytes_to_write) {
634 bytes_to_write -= actually_written;
635 event_bytes += actually_written;
641 VReport(1, " CovDump: Trace: %zd PCs written\n", size());
642 VReport(1, " CovDump: Trace: %zd Events written\n", max_idx);
645 // This function dumps the caller=>callee pairs into a file as a sequence of
646 // lines like "module_name offset".
647 void CoverageData::DumpCallerCalleePairs() {
648 uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
649 if (!max_idx) return;
650 auto sym = Symbolizer::GetOrInit();
653 InternalScopedString out(32 << 20);
655 for (uptr i = 0; i < max_idx; i++) {
656 uptr *cc_cache = cc_array[i];
658 uptr caller = cc_cache[0];
659 uptr n_callees = cc_cache[1];
660 const char *caller_module_name = "<unknown>";
661 uptr caller_module_address = 0;
662 sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
663 &caller_module_address);
664 for (uptr j = 2; j < n_callees; j++) {
665 uptr callee = cc_cache[j];
668 const char *callee_module_name = "<unknown>";
669 uptr callee_module_address = 0;
670 sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
671 &callee_module_address);
672 out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
673 caller_module_address, callee_module_name,
674 callee_module_address);
677 InternalScopedString path(kMaxPathLength);
678 fd_t fd = CovOpenFile(&path, false, "caller-callee");
679 if (fd == kInvalidFd) return;
680 WriteToFile(fd, out.data(), out.length());
682 VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
685 // Record the current PC into the event buffer.
686 // Every event is a u32 value (index in tr_pc_array_index) so we compute
687 // it once and then cache in the provided 'cache' storage.
689 // This function will eventually be inlined by the compiler.
690 void CoverageData::TraceBasicBlock(u32 *id) {
692 // 1. coverage is not enabled at run-time.
693 // 2. The array tr_event_array is full.
694 *tr_event_pointer = *id - 1;
698 void CoverageData::DumpCounters() {
699 if (!common_flags()->coverage_counters) return;
700 uptr n = coverage_data.GetNumberOf8bitCounters();
702 InternalScopedBuffer<u8> bitset(n);
703 coverage_data.Update8bitCounterBitsetAndClearCounters(bitset.data());
704 InternalScopedString path(kMaxPathLength);
706 for (uptr m = 0; m < module_name_vec.size(); m++) {
707 auto r = module_name_vec[m];
708 CHECK(r.copied_module_name);
709 CHECK_LE(r.beg, r.end);
710 CHECK_LE(r.end, size());
711 const char *base_name = StripModuleName(r.copied_module_name);
713 CovOpenFile(&path, /* packed */ false, base_name, "counters-sancov");
714 if (fd == kInvalidFd) return;
715 WriteToFile(fd, bitset.data() + r.beg, r.end - r.beg);
717 VReport(1, " CovDump: %zd counters written for '%s'\n", r.end - r.beg,
722 void CoverageData::DumpAsBitSet() {
723 if (!common_flags()->coverage_bitset) return;
725 InternalScopedBuffer<char> out(size());
726 InternalScopedString path(kMaxPathLength);
727 for (uptr m = 0; m < module_name_vec.size(); m++) {
729 auto r = module_name_vec[m];
730 CHECK(r.copied_module_name);
731 CHECK_LE(r.beg, r.end);
732 CHECK_LE(r.end, size());
733 for (uptr i = r.beg; i < r.end; i++) {
734 uptr pc = UnbundlePc(pc_array[i]);
735 out[i] = pc ? '1' : '0';
739 const char *base_name = StripModuleName(r.copied_module_name);
740 fd_t fd = CovOpenFile(&path, /* packed */false, base_name, "bitset-sancov");
741 if (fd == kInvalidFd) return;
742 WriteToFile(fd, out.data() + r.beg, r.end - r.beg);
745 " CovDump: bitset of %zd bits written for '%s', %zd bits are set\n",
746 r.end - r.beg, base_name, n_set_bits);
751 void CoverageData::GetRangeOffsets(const NamedPcRange& r, Symbolizer* sym,
752 InternalMmapVector<uptr>* offsets) const {
754 for (uptr i = 0; i < kNumWordsForMagic; i++)
755 offsets->push_back(0);
756 CHECK(r.copied_module_name);
757 CHECK_LE(r.beg, r.end);
758 CHECK_LE(r.end, size());
759 for (uptr i = r.beg; i < r.end; i++) {
760 uptr pc = UnbundlePc(pc_array[i]);
761 uptr counter = UnbundleCounter(pc_array[i]);
762 if (!pc) continue; // Not visited.
764 sym->GetModuleNameAndOffsetForPC(pc, nullptr, &offset);
765 offsets->push_back(BundlePcAndCounter(offset, counter));
768 CHECK_GE(offsets->size(), kNumWordsForMagic);
769 SortArray(offsets->data(), offsets->size());
770 for (uptr i = 0; i < offsets->size(); i++)
771 (*offsets)[i] = UnbundlePc((*offsets)[i]);
774 static void GenerateHtmlReport(const InternalMmapVector<char *> &cov_files) {
775 if (!common_flags()->html_cov_report) {
778 char *sancov_path = FindPathToBinary(common_flags()->sancov_path);
779 if (sancov_path == nullptr) {
783 InternalMmapVector<char *> sancov_argv(cov_files.size() * 2 + 3);
784 sancov_argv.push_back(sancov_path);
785 sancov_argv.push_back(internal_strdup("-html-report"));
786 auto argv_deleter = at_scope_exit([&] {
787 for (uptr i = 0; i < sancov_argv.size(); ++i) {
788 InternalFree(sancov_argv[i]);
792 for (const auto &cov_file : cov_files) {
793 sancov_argv.push_back(internal_strdup(cov_file));
797 ListOfModules modules;
799 for (const LoadedModule &module : modules) {
800 sancov_argv.push_back(internal_strdup(module.full_name()));
804 InternalScopedString report_path(kMaxPathLength);
806 CovOpenFile(&report_path, false /* packed */, GetProcessName(), "html");
807 int pid = StartSubprocess(sancov_argv[0], sancov_argv.data(),
808 kInvalidFd /* stdin */, report_fd /* std_out */);
810 int result = WaitForProcess(pid);
812 Printf("coverage report generated to %s\n", report_path.data());
816 void CoverageData::DumpOffsets() {
817 auto sym = Symbolizer::GetOrInit();
818 if (!common_flags()->coverage_pcs) return;
819 CHECK_NE(sym, nullptr);
820 InternalMmapVector<uptr> offsets(0);
821 InternalScopedString path(kMaxPathLength);
823 InternalMmapVector<char *> cov_files(module_name_vec.size());
824 auto cov_files_deleter = at_scope_exit([&] {
825 for (uptr i = 0; i < cov_files.size(); ++i) {
826 InternalFree(cov_files[i]);
830 for (uptr m = 0; m < module_name_vec.size(); m++) {
831 auto r = module_name_vec[m];
832 GetRangeOffsets(r, sym, &offsets);
834 uptr num_offsets = offsets.size() - kNumWordsForMagic;
835 u64 *magic_p = reinterpret_cast<u64*>(offsets.data());
836 CHECK_EQ(*magic_p, 0ULL);
837 // FIXME: we may want to write 32-bit offsets even in 64-mode
838 // if all the offsets are small enough.
841 const char *module_name = StripModuleName(r.copied_module_name);
843 if (cov_fd != kInvalidFd) {
844 CovWritePacked(internal_getpid(), module_name, offsets.data(),
845 offsets.size() * sizeof(offsets[0]));
846 VReport(1, " CovDump: %zd PCs written to packed file\n", num_offsets);
849 // One file per module per process.
850 fd_t fd = CovOpenFile(&path, false /* packed */, module_name);
851 if (fd == kInvalidFd) continue;
852 WriteToFile(fd, offsets.data(), offsets.size() * sizeof(offsets[0]));
854 cov_files.push_back(internal_strdup(path.data()));
855 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(), num_offsets);
858 if (cov_fd != kInvalidFd)
861 GenerateHtmlReport(cov_files);
864 void CoverageData::DumpAll() {
865 if (!coverage_enabled || common_flags()->coverage_direct) return;
866 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
872 DumpCallerCalleePairs();
875 void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
877 if (!coverage_enabled) return;
878 cov_sandboxed = args->coverage_sandboxed;
879 if (!cov_sandboxed) return;
880 cov_max_block_size = args->coverage_max_block_size;
881 if (args->coverage_fd >= 0) {
882 cov_fd = (fd_t)args->coverage_fd;
884 InternalScopedString path(kMaxPathLength);
885 // Pre-open the file now. The sandbox won't allow us to do it later.
886 cov_fd = CovOpenFile(&path, true /* packed */, nullptr);
890 fd_t MaybeOpenCovFile(const char *name) {
892 if (!coverage_enabled) return kInvalidFd;
893 InternalScopedString path(kMaxPathLength);
894 return CovOpenFile(&path, true /* packed */, name);
897 void CovBeforeFork() {
898 coverage_data.BeforeFork();
901 void CovAfterFork(int child_pid) {
902 coverage_data.AfterFork(child_pid);
905 static void MaybeDumpCoverage() {
906 if (common_flags()->coverage)
907 __sanitizer_cov_dump();
910 void InitializeCoverage(bool enabled, const char *dir) {
911 if (coverage_enabled)
912 return; // May happen if two sanitizer enable coverage in the same process.
913 coverage_enabled = enabled;
915 coverage_data.Init();
916 if (enabled) coverage_data.Enable();
917 if (!common_flags()->coverage_direct) Atexit(__sanitizer_cov_dump);
918 AddDieCallback(MaybeDumpCoverage);
921 void ReInitializeCoverage(bool enabled, const char *dir) {
922 coverage_enabled = enabled;
924 coverage_data.ReInit();
927 void CoverageUpdateMapping() {
928 if (coverage_enabled)
929 CovUpdateMapping(coverage_dir);
932 } // namespace __sanitizer
935 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
936 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
939 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_with_check(u32 *guard) {
940 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
941 if (static_cast<s32>(
942 __sanitizer::atomic_load(atomic_guard, memory_order_relaxed)) < 0)
943 __sanitizer_cov(guard);
945 SANITIZER_INTERFACE_ATTRIBUTE void
946 __sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
947 coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
948 callee, callee_cache16, 16);
950 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
951 coverage_enabled = true;
952 coverage_dir = common_flags()->coverage_dir;
953 coverage_data.Init();
955 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() {
956 coverage_data.DumpAll();
958 __sanitizer_dump_trace_pc_guard_coverage();
961 SANITIZER_INTERFACE_ATTRIBUTE void
962 __sanitizer_cov_module_init(s32 *guards, uptr npcs, u8 *counters,
963 const char *comp_unit_name) {
964 coverage_data.InitializeGuards(guards, npcs, comp_unit_name, GET_CALLER_PC());
965 coverage_data.InitializeCounters(counters, npcs);
966 if (!common_flags()->coverage_direct) return;
967 if (SANITIZER_ANDROID && coverage_enabled) {
968 // dlopen/dlclose interceptors do not work on Android, so we rely on
969 // Extend() calls to update .sancov.map.
970 CovUpdateMapping(coverage_dir, GET_CALLER_PC());
972 coverage_data.Extend(npcs);
974 SANITIZER_INTERFACE_ATTRIBUTE
975 sptr __sanitizer_maybe_open_cov_file(const char *name) {
976 return (sptr)MaybeOpenCovFile(name);
978 SANITIZER_INTERFACE_ATTRIBUTE
979 uptr __sanitizer_get_total_unique_coverage() {
980 return atomic_load(&coverage_counter, memory_order_relaxed);
983 SANITIZER_INTERFACE_ATTRIBUTE
984 uptr __sanitizer_get_total_unique_caller_callee_pairs() {
985 return atomic_load(&caller_callee_counter, memory_order_relaxed);
988 SANITIZER_INTERFACE_ATTRIBUTE
989 void __sanitizer_cov_trace_func_enter(u32 *id) {
990 __sanitizer_cov_with_check(id);
991 coverage_data.TraceBasicBlock(id);
993 SANITIZER_INTERFACE_ATTRIBUTE
994 void __sanitizer_cov_trace_basic_block(u32 *id) {
995 __sanitizer_cov_with_check(id);
996 coverage_data.TraceBasicBlock(id);
998 SANITIZER_INTERFACE_ATTRIBUTE
999 void __sanitizer_reset_coverage() {
1000 ResetGlobalCounters();
1001 coverage_data.ReinitializeGuards();
1002 internal_bzero_aligned16(
1003 coverage_data.data(),
1004 RoundUpTo(coverage_data.size() * sizeof(coverage_data.data()[0]), 16));
1006 SANITIZER_INTERFACE_ATTRIBUTE
1007 uptr __sanitizer_get_coverage_guards(uptr **data) {
1008 *data = coverage_data.data();
1009 return coverage_data.size();
1012 SANITIZER_INTERFACE_ATTRIBUTE
1013 uptr __sanitizer_get_number_of_counters() {
1014 return coverage_data.GetNumberOf8bitCounters();
1017 SANITIZER_INTERFACE_ATTRIBUTE
1018 uptr __sanitizer_update_counter_bitset_and_clear_counters(u8 *bitset) {
1019 return coverage_data.Update8bitCounterBitsetAndClearCounters(bitset);
1021 // Default empty implementations (weak). Users should redefine them.
1022 #if !SANITIZER_WINDOWS // weak does not work on Windows.
1023 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1024 void __sanitizer_cov_trace_cmp() {}
1025 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1026 void __sanitizer_cov_trace_cmp1() {}
1027 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1028 void __sanitizer_cov_trace_cmp2() {}
1029 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1030 void __sanitizer_cov_trace_cmp4() {}
1031 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1032 void __sanitizer_cov_trace_cmp8() {}
1033 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1034 void __sanitizer_cov_trace_switch() {}
1035 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1036 void __sanitizer_cov_trace_div4() {}
1037 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1038 void __sanitizer_cov_trace_div8() {}
1039 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1040 void __sanitizer_cov_trace_gep() {}
1041 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1042 void __sanitizer_cov_trace_pc_indir() {}
1043 #endif // !SANITIZER_WINDOWS