Fix typo.
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_coverage_libcdep.cc
blobdd8620beaac0a9b945127e047b4000ef3baa89af
1 //===-- sanitizer_coverage.cc ---------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // Sanitizer Coverage.
9 // This file implements run-time support for a poor man's coverage tool.
11 // Compiler instrumentation:
12 // For every interesting basic block the compiler injects the following code:
13 // if (Guard < 0) {
14 // __sanitizer_cov(&Guard);
15 // }
16 // At the module start up time __sanitizer_cov_module_init sets the guards
17 // to consecutive negative numbers (-1, -2, -3, ...).
18 // It's fine to call __sanitizer_cov more than once for a given block.
20 // Run-time:
21 // - __sanitizer_cov(): record that we've executed the PC (GET_CALLER_PC).
22 // and atomically set Guard to -Guard.
23 // - __sanitizer_cov_dump: dump the coverage data to disk.
24 // For every module of the current process that has coverage data
25 // this will create a file module_name.PID.sancov.
27 // The file format is simple: the first 8 bytes is the magic,
28 // one of 0xC0BFFFFFFFFFFF64 and 0xC0BFFFFFFFFFFF32. The last byte of the
29 // magic defines the size of the following offsets.
30 // The rest of the data is the offsets in the module.
32 // Eventually, this coverage implementation should be obsoleted by a more
33 // powerful general purpose Clang/LLVM coverage instrumentation.
34 // Consider this implementation as prototype.
36 // FIXME: support (or at least test with) dlclose.
37 //===----------------------------------------------------------------------===//
39 #include "sanitizer_allocator_internal.h"
40 #include "sanitizer_common.h"
41 #include "sanitizer_libc.h"
42 #include "sanitizer_mutex.h"
43 #include "sanitizer_procmaps.h"
44 #include "sanitizer_stacktrace.h"
45 #include "sanitizer_symbolizer.h"
46 #include "sanitizer_flags.h"
48 using namespace __sanitizer;
50 static const u64 kMagic64 = 0xC0BFFFFFFFFFFF64ULL;
51 static const u64 kMagic32 = 0xC0BFFFFFFFFFFF32ULL;
52 static const uptr kNumWordsForMagic = SANITIZER_WORDSIZE == 64 ? 1 : 2;
53 static const u64 kMagic = SANITIZER_WORDSIZE == 64 ? kMagic64 : kMagic32;
55 static atomic_uint32_t dump_once_guard; // Ensure that CovDump runs only once.
57 static atomic_uintptr_t coverage_counter;
58 static atomic_uintptr_t caller_callee_counter;
60 static void ResetGlobalCounters() {
61 return atomic_store(&coverage_counter, 0, memory_order_relaxed);
62 return atomic_store(&caller_callee_counter, 0, memory_order_relaxed);
65 // pc_array is the array containing the covered PCs.
66 // To make the pc_array thread- and async-signal-safe it has to be large enough.
67 // 128M counters "ought to be enough for anybody" (4M on 32-bit).
69 // With coverage_direct=1 in ASAN_OPTIONS, pc_array memory is mapped to a file.
70 // In this mode, __sanitizer_cov_dump does nothing, and CovUpdateMapping()
71 // dump current memory layout to another file.
73 static bool cov_sandboxed = false;
74 static fd_t cov_fd = kInvalidFd;
75 static unsigned int cov_max_block_size = 0;
76 static bool coverage_enabled = false;
77 static const char *coverage_dir;
79 namespace __sanitizer {
81 class CoverageData {
82 public:
83 void Init();
84 void Enable();
85 void Disable();
86 void ReInit();
87 void BeforeFork();
88 void AfterFork(int child_pid);
89 void Extend(uptr npcs);
90 void Add(uptr pc, u32 *guard);
91 void IndirCall(uptr caller, uptr callee, uptr callee_cache[],
92 uptr cache_size);
93 void DumpCallerCalleePairs();
94 void DumpTrace();
95 void DumpAsBitSet();
96 void DumpCounters();
97 void DumpOffsets();
98 void DumpAll();
100 ALWAYS_INLINE
101 void TraceBasicBlock(u32 *id);
103 void InitializeGuardArray(s32 *guards);
104 void InitializeGuards(s32 *guards, uptr n, const char *module_name,
105 uptr caller_pc);
106 void InitializeCounters(u8 *counters, uptr n);
107 void ReinitializeGuards();
108 uptr GetNumberOf8bitCounters();
109 uptr Update8bitCounterBitsetAndClearCounters(u8 *bitset);
111 uptr *data();
112 uptr size() const;
114 private:
115 struct NamedPcRange {
116 const char *copied_module_name;
117 uptr beg, end; // elements [beg,end) in pc_array.
120 void DirectOpen();
121 void UpdateModuleNameVec(uptr caller_pc, uptr range_beg, uptr range_end);
122 void GetRangeOffsets(const NamedPcRange& r, Symbolizer* s,
123 InternalMmapVector<uptr>* offsets) const;
125 // Maximal size pc array may ever grow.
126 // We MmapNoReserve this space to ensure that the array is contiguous.
127 static const uptr kPcArrayMaxSize =
128 FIRST_32_SECOND_64(1 << (SANITIZER_ANDROID ? 24 : 26), 1 << 27);
129 // The amount file mapping for the pc array is grown by.
130 static const uptr kPcArrayMmapSize = 64 * 1024;
132 // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
133 // much RAM as it really needs.
134 uptr *pc_array;
135 // Index of the first available pc_array slot.
136 atomic_uintptr_t pc_array_index;
137 // Array size.
138 atomic_uintptr_t pc_array_size;
139 // Current file mapped size of the pc array.
140 uptr pc_array_mapped_size;
141 // Descriptor of the file mapped pc array.
142 fd_t pc_fd;
144 // Vector of coverage guard arrays, protected by mu.
145 InternalMmapVectorNoCtor<s32*> guard_array_vec;
147 // Vector of module and compilation unit pc ranges.
148 InternalMmapVectorNoCtor<NamedPcRange> comp_unit_name_vec;
149 InternalMmapVectorNoCtor<NamedPcRange> module_name_vec;
151 struct CounterAndSize {
152 u8 *counters;
153 uptr n;
156 InternalMmapVectorNoCtor<CounterAndSize> counters_vec;
157 uptr num_8bit_counters;
159 // Caller-Callee (cc) array, size and current index.
160 static const uptr kCcArrayMaxSize = FIRST_32_SECOND_64(1 << 18, 1 << 24);
161 uptr **cc_array;
162 atomic_uintptr_t cc_array_index;
163 atomic_uintptr_t cc_array_size;
165 // Tracing event array, size and current pointer.
166 // We record all events (basic block entries) in a global buffer of u32
167 // values. Each such value is the index in pc_array.
168 // So far the tracing is highly experimental:
169 // - not thread-safe;
170 // - does not support long traces;
171 // - not tuned for performance.
172 static const uptr kTrEventArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 30);
173 u32 *tr_event_array;
174 uptr tr_event_array_size;
175 u32 *tr_event_pointer;
176 static const uptr kTrPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
178 StaticSpinMutex mu;
181 static CoverageData coverage_data;
183 void CovUpdateMapping(const char *path, uptr caller_pc = 0);
185 void CoverageData::DirectOpen() {
186 InternalScopedString path(kMaxPathLength);
187 internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
188 coverage_dir, internal_getpid());
189 pc_fd = OpenFile(path.data(), RdWr);
190 if (pc_fd == kInvalidFd) {
191 Report("Coverage: failed to open %s for reading/writing\n", path.data());
192 Die();
195 pc_array_mapped_size = 0;
196 CovUpdateMapping(coverage_dir);
199 void CoverageData::Init() {
200 pc_fd = kInvalidFd;
203 void CoverageData::Enable() {
204 if (pc_array)
205 return;
206 pc_array = reinterpret_cast<uptr *>(
207 MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
208 atomic_store(&pc_array_index, 0, memory_order_relaxed);
209 if (common_flags()->coverage_direct) {
210 atomic_store(&pc_array_size, 0, memory_order_relaxed);
211 } else {
212 atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
215 cc_array = reinterpret_cast<uptr **>(MmapNoReserveOrDie(
216 sizeof(uptr *) * kCcArrayMaxSize, "CovInit::cc_array"));
217 atomic_store(&cc_array_size, kCcArrayMaxSize, memory_order_relaxed);
218 atomic_store(&cc_array_index, 0, memory_order_relaxed);
220 // Allocate tr_event_array with a guard page at the end.
221 tr_event_array = reinterpret_cast<u32 *>(MmapNoReserveOrDie(
222 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize + GetMmapGranularity(),
223 "CovInit::tr_event_array"));
224 MprotectNoAccess(
225 reinterpret_cast<uptr>(&tr_event_array[kTrEventArrayMaxSize]),
226 GetMmapGranularity());
227 tr_event_array_size = kTrEventArrayMaxSize;
228 tr_event_pointer = tr_event_array;
230 num_8bit_counters = 0;
233 void CoverageData::InitializeGuardArray(s32 *guards) {
234 Enable(); // Make sure coverage is enabled at this point.
235 s32 n = guards[0];
236 for (s32 j = 1; j <= n; j++) {
237 uptr idx = atomic_load_relaxed(&pc_array_index);
238 atomic_store_relaxed(&pc_array_index, idx + 1);
239 guards[j] = -static_cast<s32>(idx + 1);
243 void CoverageData::Disable() {
244 if (pc_array) {
245 UnmapOrDie(pc_array, sizeof(uptr) * kPcArrayMaxSize);
246 pc_array = nullptr;
248 if (cc_array) {
249 UnmapOrDie(cc_array, sizeof(uptr *) * kCcArrayMaxSize);
250 cc_array = nullptr;
252 if (tr_event_array) {
253 UnmapOrDie(tr_event_array,
254 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize +
255 GetMmapGranularity());
256 tr_event_array = nullptr;
257 tr_event_pointer = nullptr;
259 if (pc_fd != kInvalidFd) {
260 CloseFile(pc_fd);
261 pc_fd = kInvalidFd;
265 void CoverageData::ReinitializeGuards() {
266 // Assuming single thread.
267 atomic_store(&pc_array_index, 0, memory_order_relaxed);
268 for (uptr i = 0; i < guard_array_vec.size(); i++)
269 InitializeGuardArray(guard_array_vec[i]);
272 void CoverageData::ReInit() {
273 Disable();
274 if (coverage_enabled) {
275 if (common_flags()->coverage_direct) {
276 // In memory-mapped mode we must extend the new file to the known array
277 // size.
278 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
279 uptr npcs = size / sizeof(uptr);
280 Enable();
281 if (size) Extend(npcs);
282 if (coverage_enabled) CovUpdateMapping(coverage_dir);
283 } else {
284 Enable();
287 // Re-initialize the guards.
288 // We are single-threaded now, no need to grab any lock.
289 CHECK_EQ(atomic_load(&pc_array_index, memory_order_relaxed), 0);
290 ReinitializeGuards();
293 void CoverageData::BeforeFork() {
294 mu.Lock();
297 void CoverageData::AfterFork(int child_pid) {
298 // We are single-threaded so it's OK to release the lock early.
299 mu.Unlock();
300 if (child_pid == 0) ReInit();
303 // Extend coverage PC array to fit additional npcs elements.
304 void CoverageData::Extend(uptr npcs) {
305 if (!common_flags()->coverage_direct) return;
306 SpinMutexLock l(&mu);
308 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
309 size += npcs * sizeof(uptr);
311 if (coverage_enabled && size > pc_array_mapped_size) {
312 if (pc_fd == kInvalidFd) DirectOpen();
313 CHECK_NE(pc_fd, kInvalidFd);
315 uptr new_mapped_size = pc_array_mapped_size;
316 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
317 CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
319 // Extend the file and map the new space at the end of pc_array.
320 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
321 int err;
322 if (internal_iserror(res, &err)) {
323 Printf("failed to extend raw coverage file: %d\n", err);
324 Die();
327 uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
328 void *p = MapWritableFileToMemory((void *)next_map_base,
329 new_mapped_size - pc_array_mapped_size,
330 pc_fd, pc_array_mapped_size);
331 CHECK_EQ((uptr)p, next_map_base);
332 pc_array_mapped_size = new_mapped_size;
335 atomic_store(&pc_array_size, size, memory_order_release);
338 void CoverageData::InitializeCounters(u8 *counters, uptr n) {
339 if (!counters) return;
340 CHECK_EQ(reinterpret_cast<uptr>(counters) % 16, 0);
341 n = RoundUpTo(n, 16); // The compiler must ensure that counters is 16-aligned.
342 SpinMutexLock l(&mu);
343 counters_vec.push_back({counters, n});
344 num_8bit_counters += n;
347 void CoverageData::UpdateModuleNameVec(uptr caller_pc, uptr range_beg,
348 uptr range_end) {
349 auto sym = Symbolizer::GetOrInit();
350 if (!sym)
351 return;
352 const char *module_name = sym->GetModuleNameForPc(caller_pc);
353 if (!module_name) return;
354 if (module_name_vec.empty() ||
355 module_name_vec.back().copied_module_name != module_name)
356 module_name_vec.push_back({module_name, range_beg, range_end});
357 else
358 module_name_vec.back().end = range_end;
361 void CoverageData::InitializeGuards(s32 *guards, uptr n,
362 const char *comp_unit_name,
363 uptr caller_pc) {
364 // The array 'guards' has n+1 elements, we use the element zero
365 // to store 'n'.
366 CHECK_LT(n, 1 << 30);
367 guards[0] = static_cast<s32>(n);
368 InitializeGuardArray(guards);
369 SpinMutexLock l(&mu);
370 uptr range_end = atomic_load(&pc_array_index, memory_order_relaxed);
371 uptr range_beg = range_end - n;
372 comp_unit_name_vec.push_back({comp_unit_name, range_beg, range_end});
373 guard_array_vec.push_back(guards);
374 UpdateModuleNameVec(caller_pc, range_beg, range_end);
377 static const uptr kBundleCounterBits = 16;
379 // When coverage_order_pcs==true and SANITIZER_WORDSIZE==64
380 // we insert the global counter into the first 16 bits of the PC.
381 uptr BundlePcAndCounter(uptr pc, uptr counter) {
382 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
383 return pc;
384 static const uptr kMaxCounter = (1 << kBundleCounterBits) - 1;
385 if (counter > kMaxCounter)
386 counter = kMaxCounter;
387 CHECK_EQ(0, pc >> (SANITIZER_WORDSIZE - kBundleCounterBits));
388 return pc | (counter << (SANITIZER_WORDSIZE - kBundleCounterBits));
391 uptr UnbundlePc(uptr bundle) {
392 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
393 return bundle;
394 return (bundle << kBundleCounterBits) >> kBundleCounterBits;
397 uptr UnbundleCounter(uptr bundle) {
398 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
399 return 0;
400 return bundle >> (SANITIZER_WORDSIZE - kBundleCounterBits);
403 // If guard is negative, atomically set it to -guard and store the PC in
404 // pc_array.
405 void CoverageData::Add(uptr pc, u32 *guard) {
406 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
407 s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
408 if (guard_value >= 0) return;
410 atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
411 if (!pc_array) return;
413 uptr idx = -guard_value - 1;
414 if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
415 return; // May happen after fork when pc_array_index becomes 0.
416 CHECK_LT(idx * sizeof(uptr),
417 atomic_load(&pc_array_size, memory_order_acquire));
418 uptr counter = atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
419 pc_array[idx] = BundlePcAndCounter(pc, counter);
422 // Registers a pair caller=>callee.
423 // When a given caller is seen for the first time, the callee_cache is added
424 // to the global array cc_array, callee_cache[0] is set to caller and
425 // callee_cache[1] is set to cache_size.
426 // Then we are trying to add callee to callee_cache [2,cache_size) if it is
427 // not there yet.
428 // If the cache is full we drop the callee (may want to fix this later).
429 void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
430 uptr cache_size) {
431 if (!cc_array) return;
432 atomic_uintptr_t *atomic_callee_cache =
433 reinterpret_cast<atomic_uintptr_t *>(callee_cache);
434 uptr zero = 0;
435 if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
436 memory_order_seq_cst)) {
437 uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
438 CHECK_LT(idx * sizeof(uptr),
439 atomic_load(&cc_array_size, memory_order_acquire));
440 callee_cache[1] = cache_size;
441 cc_array[idx] = callee_cache;
443 CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
444 for (uptr i = 2; i < cache_size; i++) {
445 uptr was = 0;
446 if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
447 memory_order_seq_cst)) {
448 atomic_fetch_add(&caller_callee_counter, 1, memory_order_relaxed);
449 return;
451 if (was == callee) // Already have this callee.
452 return;
456 uptr CoverageData::GetNumberOf8bitCounters() {
457 return num_8bit_counters;
460 // Map every 8bit counter to a 8-bit bitset and clear the counter.
461 uptr CoverageData::Update8bitCounterBitsetAndClearCounters(u8 *bitset) {
462 uptr num_new_bits = 0;
463 uptr cur = 0;
464 // For better speed we map 8 counters to 8 bytes of bitset at once.
465 static const uptr kBatchSize = 8;
466 CHECK_EQ(reinterpret_cast<uptr>(bitset) % kBatchSize, 0);
467 for (uptr i = 0, len = counters_vec.size(); i < len; i++) {
468 u8 *c = counters_vec[i].counters;
469 uptr n = counters_vec[i].n;
470 CHECK_EQ(n % 16, 0);
471 CHECK_EQ(cur % kBatchSize, 0);
472 CHECK_EQ(reinterpret_cast<uptr>(c) % kBatchSize, 0);
473 if (!bitset) {
474 internal_bzero_aligned16(c, n);
475 cur += n;
476 continue;
478 for (uptr j = 0; j < n; j += kBatchSize, cur += kBatchSize) {
479 CHECK_LT(cur, num_8bit_counters);
480 u64 *pc64 = reinterpret_cast<u64*>(c + j);
481 u64 *pb64 = reinterpret_cast<u64*>(bitset + cur);
482 u64 c64 = *pc64;
483 u64 old_bits_64 = *pb64;
484 u64 new_bits_64 = old_bits_64;
485 if (c64) {
486 *pc64 = 0;
487 for (uptr k = 0; k < kBatchSize; k++) {
488 u64 x = (c64 >> (8 * k)) & 0xff;
489 if (x) {
490 u64 bit = 0;
491 /**/ if (x >= 128) bit = 128;
492 else if (x >= 32) bit = 64;
493 else if (x >= 16) bit = 32;
494 else if (x >= 8) bit = 16;
495 else if (x >= 4) bit = 8;
496 else if (x >= 3) bit = 4;
497 else if (x >= 2) bit = 2;
498 else if (x >= 1) bit = 1;
499 u64 mask = bit << (8 * k);
500 if (!(new_bits_64 & mask)) {
501 num_new_bits++;
502 new_bits_64 |= mask;
506 *pb64 = new_bits_64;
510 CHECK_EQ(cur, num_8bit_counters);
511 return num_new_bits;
514 uptr *CoverageData::data() {
515 return pc_array;
518 uptr CoverageData::size() const {
519 return atomic_load(&pc_array_index, memory_order_relaxed);
522 // Block layout for packed file format: header, followed by module name (no
523 // trailing zero), followed by data blob.
524 struct CovHeader {
525 int pid;
526 unsigned int module_name_length;
527 unsigned int data_length;
530 static void CovWritePacked(int pid, const char *module, const void *blob,
531 unsigned int blob_size) {
532 if (cov_fd == kInvalidFd) return;
533 unsigned module_name_length = internal_strlen(module);
534 CovHeader header = {pid, module_name_length, blob_size};
536 if (cov_max_block_size == 0) {
537 // Writing to a file. Just go ahead.
538 WriteToFile(cov_fd, &header, sizeof(header));
539 WriteToFile(cov_fd, module, module_name_length);
540 WriteToFile(cov_fd, blob, blob_size);
541 } else {
542 // Writing to a socket. We want to split the data into appropriately sized
543 // blocks.
544 InternalScopedBuffer<char> block(cov_max_block_size);
545 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
546 uptr header_size_with_module = sizeof(header) + module_name_length;
547 CHECK_LT(header_size_with_module, cov_max_block_size);
548 unsigned int max_payload_size =
549 cov_max_block_size - header_size_with_module;
550 char *block_pos = block.data();
551 internal_memcpy(block_pos, &header, sizeof(header));
552 block_pos += sizeof(header);
553 internal_memcpy(block_pos, module, module_name_length);
554 block_pos += module_name_length;
555 char *block_data_begin = block_pos;
556 const char *blob_pos = (const char *)blob;
557 while (blob_size > 0) {
558 unsigned int payload_size = Min(blob_size, max_payload_size);
559 blob_size -= payload_size;
560 internal_memcpy(block_data_begin, blob_pos, payload_size);
561 blob_pos += payload_size;
562 ((CovHeader *)block.data())->data_length = payload_size;
563 WriteToFile(cov_fd, block.data(), header_size_with_module + payload_size);
568 // If packed = false: <name>.<pid>.<sancov> (name = module name).
569 // If packed = true and name == 0: <pid>.<sancov>.<packed>.
570 // If packed = true and name != 0: <name>.<sancov>.<packed> (name is
571 // user-supplied).
572 static fd_t CovOpenFile(InternalScopedString *path, bool packed,
573 const char *name, const char *extension = "sancov") {
574 path->clear();
575 if (!packed) {
576 CHECK(name);
577 path->append("%s/%s.%zd.%s", coverage_dir, name, internal_getpid(),
578 extension);
579 } else {
580 if (!name)
581 path->append("%s/%zd.%s.packed", coverage_dir, internal_getpid(),
582 extension);
583 else
584 path->append("%s/%s.%s.packed", coverage_dir, name, extension);
586 error_t err;
587 fd_t fd = OpenFile(path->data(), WrOnly, &err);
588 if (fd == kInvalidFd)
589 Report("SanitizerCoverage: failed to open %s for writing (reason: %d)\n",
590 path->data(), err);
591 return fd;
594 // Dump trace PCs and trace events into two separate files.
595 void CoverageData::DumpTrace() {
596 uptr max_idx = tr_event_pointer - tr_event_array;
597 if (!max_idx) return;
598 auto sym = Symbolizer::GetOrInit();
599 if (!sym)
600 return;
601 InternalScopedString out(32 << 20);
602 for (uptr i = 0, n = size(); i < n; i++) {
603 const char *module_name = "<unknown>";
604 uptr module_address = 0;
605 sym->GetModuleNameAndOffsetForPC(UnbundlePc(pc_array[i]), &module_name,
606 &module_address);
607 out.append("%s 0x%zx\n", module_name, module_address);
609 InternalScopedString path(kMaxPathLength);
610 fd_t fd = CovOpenFile(&path, false, "trace-points");
611 if (fd == kInvalidFd) return;
612 WriteToFile(fd, out.data(), out.length());
613 CloseFile(fd);
615 fd = CovOpenFile(&path, false, "trace-compunits");
616 if (fd == kInvalidFd) return;
617 out.clear();
618 for (uptr i = 0; i < comp_unit_name_vec.size(); i++)
619 out.append("%s\n", comp_unit_name_vec[i].copied_module_name);
620 WriteToFile(fd, out.data(), out.length());
621 CloseFile(fd);
623 fd = CovOpenFile(&path, false, "trace-events");
624 if (fd == kInvalidFd) return;
625 uptr bytes_to_write = max_idx * sizeof(tr_event_array[0]);
626 u8 *event_bytes = reinterpret_cast<u8*>(tr_event_array);
627 // The trace file could be huge, and may not be written with a single syscall.
628 while (bytes_to_write) {
629 uptr actually_written;
630 if (WriteToFile(fd, event_bytes, bytes_to_write, &actually_written) &&
631 actually_written <= bytes_to_write) {
632 bytes_to_write -= actually_written;
633 event_bytes += actually_written;
634 } else {
635 break;
638 CloseFile(fd);
639 VReport(1, " CovDump: Trace: %zd PCs written\n", size());
640 VReport(1, " CovDump: Trace: %zd Events written\n", max_idx);
643 // This function dumps the caller=>callee pairs into a file as a sequence of
644 // lines like "module_name offset".
645 void CoverageData::DumpCallerCalleePairs() {
646 uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
647 if (!max_idx) return;
648 auto sym = Symbolizer::GetOrInit();
649 if (!sym)
650 return;
651 InternalScopedString out(32 << 20);
652 uptr total = 0;
653 for (uptr i = 0; i < max_idx; i++) {
654 uptr *cc_cache = cc_array[i];
655 CHECK(cc_cache);
656 uptr caller = cc_cache[0];
657 uptr n_callees = cc_cache[1];
658 const char *caller_module_name = "<unknown>";
659 uptr caller_module_address = 0;
660 sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
661 &caller_module_address);
662 for (uptr j = 2; j < n_callees; j++) {
663 uptr callee = cc_cache[j];
664 if (!callee) break;
665 total++;
666 const char *callee_module_name = "<unknown>";
667 uptr callee_module_address = 0;
668 sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
669 &callee_module_address);
670 out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
671 caller_module_address, callee_module_name,
672 callee_module_address);
675 InternalScopedString path(kMaxPathLength);
676 fd_t fd = CovOpenFile(&path, false, "caller-callee");
677 if (fd == kInvalidFd) return;
678 WriteToFile(fd, out.data(), out.length());
679 CloseFile(fd);
680 VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
683 // Record the current PC into the event buffer.
684 // Every event is a u32 value (index in tr_pc_array_index) so we compute
685 // it once and then cache in the provided 'cache' storage.
687 // This function will eventually be inlined by the compiler.
688 void CoverageData::TraceBasicBlock(u32 *id) {
689 // Will trap here if
690 // 1. coverage is not enabled at run-time.
691 // 2. The array tr_event_array is full.
692 *tr_event_pointer = *id - 1;
693 tr_event_pointer++;
696 void CoverageData::DumpCounters() {
697 if (!common_flags()->coverage_counters) return;
698 uptr n = coverage_data.GetNumberOf8bitCounters();
699 if (!n) return;
700 InternalScopedBuffer<u8> bitset(n);
701 coverage_data.Update8bitCounterBitsetAndClearCounters(bitset.data());
702 InternalScopedString path(kMaxPathLength);
704 for (uptr m = 0; m < module_name_vec.size(); m++) {
705 auto r = module_name_vec[m];
706 CHECK(r.copied_module_name);
707 CHECK_LE(r.beg, r.end);
708 CHECK_LE(r.end, size());
709 const char *base_name = StripModuleName(r.copied_module_name);
710 fd_t fd =
711 CovOpenFile(&path, /* packed */ false, base_name, "counters-sancov");
712 if (fd == kInvalidFd) return;
713 WriteToFile(fd, bitset.data() + r.beg, r.end - r.beg);
714 CloseFile(fd);
715 VReport(1, " CovDump: %zd counters written for '%s'\n", r.end - r.beg,
716 base_name);
720 void CoverageData::DumpAsBitSet() {
721 if (!common_flags()->coverage_bitset) return;
722 if (!size()) return;
723 InternalScopedBuffer<char> out(size());
724 InternalScopedString path(kMaxPathLength);
725 for (uptr m = 0; m < module_name_vec.size(); m++) {
726 uptr n_set_bits = 0;
727 auto r = module_name_vec[m];
728 CHECK(r.copied_module_name);
729 CHECK_LE(r.beg, r.end);
730 CHECK_LE(r.end, size());
731 for (uptr i = r.beg; i < r.end; i++) {
732 uptr pc = UnbundlePc(pc_array[i]);
733 out[i] = pc ? '1' : '0';
734 if (pc)
735 n_set_bits++;
737 const char *base_name = StripModuleName(r.copied_module_name);
738 fd_t fd = CovOpenFile(&path, /* packed */false, base_name, "bitset-sancov");
739 if (fd == kInvalidFd) return;
740 WriteToFile(fd, out.data() + r.beg, r.end - r.beg);
741 CloseFile(fd);
742 VReport(1,
743 " CovDump: bitset of %zd bits written for '%s', %zd bits are set\n",
744 r.end - r.beg, base_name, n_set_bits);
749 void CoverageData::GetRangeOffsets(const NamedPcRange& r, Symbolizer* sym,
750 InternalMmapVector<uptr>* offsets) const {
751 offsets->clear();
752 for (uptr i = 0; i < kNumWordsForMagic; i++)
753 offsets->push_back(0);
754 CHECK(r.copied_module_name);
755 CHECK_LE(r.beg, r.end);
756 CHECK_LE(r.end, size());
757 for (uptr i = r.beg; i < r.end; i++) {
758 uptr pc = UnbundlePc(pc_array[i]);
759 uptr counter = UnbundleCounter(pc_array[i]);
760 if (!pc) continue; // Not visited.
761 uptr offset = 0;
762 sym->GetModuleNameAndOffsetForPC(pc, nullptr, &offset);
763 offsets->push_back(BundlePcAndCounter(offset, counter));
766 CHECK_GE(offsets->size(), kNumWordsForMagic);
767 SortArray(offsets->data(), offsets->size());
768 for (uptr i = 0; i < offsets->size(); i++)
769 (*offsets)[i] = UnbundlePc((*offsets)[i]);
772 static void GenerateHtmlReport(const InternalMmapVector<char *> &cov_files) {
773 if (!common_flags()->html_cov_report) {
774 return;
776 char *sancov_path = FindPathToBinary(common_flags()->sancov_path);
777 if (sancov_path == nullptr) {
778 return;
781 InternalMmapVector<char *> sancov_argv(cov_files.size() * 2 + 3);
782 sancov_argv.push_back(sancov_path);
783 sancov_argv.push_back(internal_strdup("-html-report"));
784 auto argv_deleter = at_scope_exit([&] {
785 for (uptr i = 0; i < sancov_argv.size(); ++i) {
786 InternalFree(sancov_argv[i]);
790 for (const auto &cov_file : cov_files) {
791 sancov_argv.push_back(internal_strdup(cov_file));
795 ListOfModules modules;
796 modules.init();
797 for (const LoadedModule &module : modules) {
798 sancov_argv.push_back(internal_strdup(module.full_name()));
802 InternalScopedString report_path(kMaxPathLength);
803 fd_t report_fd =
804 CovOpenFile(&report_path, false /* packed */, GetProcessName(), "html");
805 int pid = StartSubprocess(sancov_argv[0], sancov_argv.data(),
806 kInvalidFd /* stdin */, report_fd /* std_out */);
807 if (pid > 0) {
808 int result = WaitForProcess(pid);
809 if (result == 0)
810 Printf("coverage report generated to %s\n", report_path.data());
814 void CoverageData::DumpOffsets() {
815 auto sym = Symbolizer::GetOrInit();
816 if (!common_flags()->coverage_pcs) return;
817 CHECK_NE(sym, nullptr);
818 InternalMmapVector<uptr> offsets(0);
819 InternalScopedString path(kMaxPathLength);
821 InternalMmapVector<char *> cov_files(module_name_vec.size());
822 auto cov_files_deleter = at_scope_exit([&] {
823 for (uptr i = 0; i < cov_files.size(); ++i) {
824 InternalFree(cov_files[i]);
828 for (uptr m = 0; m < module_name_vec.size(); m++) {
829 auto r = module_name_vec[m];
830 GetRangeOffsets(r, sym, &offsets);
832 uptr num_offsets = offsets.size() - kNumWordsForMagic;
833 u64 *magic_p = reinterpret_cast<u64*>(offsets.data());
834 CHECK_EQ(*magic_p, 0ULL);
835 // FIXME: we may want to write 32-bit offsets even in 64-mode
836 // if all the offsets are small enough.
837 *magic_p = kMagic;
839 const char *module_name = StripModuleName(r.copied_module_name);
840 if (cov_sandboxed) {
841 if (cov_fd != kInvalidFd) {
842 CovWritePacked(internal_getpid(), module_name, offsets.data(),
843 offsets.size() * sizeof(offsets[0]));
844 VReport(1, " CovDump: %zd PCs written to packed file\n", num_offsets);
846 } else {
847 // One file per module per process.
848 fd_t fd = CovOpenFile(&path, false /* packed */, module_name);
849 if (fd == kInvalidFd) continue;
850 WriteToFile(fd, offsets.data(), offsets.size() * sizeof(offsets[0]));
851 CloseFile(fd);
852 cov_files.push_back(internal_strdup(path.data()));
853 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(), num_offsets);
856 if (cov_fd != kInvalidFd)
857 CloseFile(cov_fd);
859 GenerateHtmlReport(cov_files);
862 void CoverageData::DumpAll() {
863 if (!coverage_enabled || common_flags()->coverage_direct) return;
864 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
865 return;
866 DumpAsBitSet();
867 DumpCounters();
868 DumpTrace();
869 DumpOffsets();
870 DumpCallerCalleePairs();
873 void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
874 if (!args) return;
875 if (!coverage_enabled) return;
876 cov_sandboxed = args->coverage_sandboxed;
877 if (!cov_sandboxed) return;
878 cov_max_block_size = args->coverage_max_block_size;
879 if (args->coverage_fd >= 0) {
880 cov_fd = (fd_t)args->coverage_fd;
881 } else {
882 InternalScopedString path(kMaxPathLength);
883 // Pre-open the file now. The sandbox won't allow us to do it later.
884 cov_fd = CovOpenFile(&path, true /* packed */, nullptr);
888 fd_t MaybeOpenCovFile(const char *name) {
889 CHECK(name);
890 if (!coverage_enabled) return kInvalidFd;
891 InternalScopedString path(kMaxPathLength);
892 return CovOpenFile(&path, true /* packed */, name);
895 void CovBeforeFork() {
896 coverage_data.BeforeFork();
899 void CovAfterFork(int child_pid) {
900 coverage_data.AfterFork(child_pid);
903 static void MaybeDumpCoverage() {
904 if (common_flags()->coverage)
905 __sanitizer_cov_dump();
908 void InitializeCoverage(bool enabled, const char *dir) {
909 if (coverage_enabled)
910 return; // May happen if two sanitizer enable coverage in the same process.
911 coverage_enabled = enabled;
912 coverage_dir = dir;
913 coverage_data.Init();
914 if (enabled) coverage_data.Enable();
915 if (!common_flags()->coverage_direct) Atexit(__sanitizer_cov_dump);
916 AddDieCallback(MaybeDumpCoverage);
919 void ReInitializeCoverage(bool enabled, const char *dir) {
920 coverage_enabled = enabled;
921 coverage_dir = dir;
922 coverage_data.ReInit();
925 void CoverageUpdateMapping() {
926 if (coverage_enabled)
927 CovUpdateMapping(coverage_dir);
930 } // namespace __sanitizer
932 extern "C" {
933 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
934 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
935 guard);
937 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_with_check(u32 *guard) {
938 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
939 if (static_cast<s32>(
940 __sanitizer::atomic_load(atomic_guard, memory_order_relaxed)) < 0)
941 __sanitizer_cov(guard);
943 SANITIZER_INTERFACE_ATTRIBUTE void
944 __sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
945 coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
946 callee, callee_cache16, 16);
948 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
949 coverage_enabled = true;
950 coverage_dir = common_flags()->coverage_dir;
951 coverage_data.Init();
953 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() {
954 coverage_data.DumpAll();
956 SANITIZER_INTERFACE_ATTRIBUTE void
957 __sanitizer_cov_module_init(s32 *guards, uptr npcs, u8 *counters,
958 const char *comp_unit_name) {
959 coverage_data.InitializeGuards(guards, npcs, comp_unit_name, GET_CALLER_PC());
960 coverage_data.InitializeCounters(counters, npcs);
961 if (!common_flags()->coverage_direct) return;
962 if (SANITIZER_ANDROID && coverage_enabled) {
963 // dlopen/dlclose interceptors do not work on Android, so we rely on
964 // Extend() calls to update .sancov.map.
965 CovUpdateMapping(coverage_dir, GET_CALLER_PC());
967 coverage_data.Extend(npcs);
969 SANITIZER_INTERFACE_ATTRIBUTE
970 sptr __sanitizer_maybe_open_cov_file(const char *name) {
971 return (sptr)MaybeOpenCovFile(name);
973 SANITIZER_INTERFACE_ATTRIBUTE
974 uptr __sanitizer_get_total_unique_coverage() {
975 return atomic_load(&coverage_counter, memory_order_relaxed);
978 SANITIZER_INTERFACE_ATTRIBUTE
979 uptr __sanitizer_get_total_unique_caller_callee_pairs() {
980 return atomic_load(&caller_callee_counter, memory_order_relaxed);
983 SANITIZER_INTERFACE_ATTRIBUTE
984 void __sanitizer_cov_trace_func_enter(u32 *id) {
985 __sanitizer_cov_with_check(id);
986 coverage_data.TraceBasicBlock(id);
988 SANITIZER_INTERFACE_ATTRIBUTE
989 void __sanitizer_cov_trace_basic_block(u32 *id) {
990 __sanitizer_cov_with_check(id);
991 coverage_data.TraceBasicBlock(id);
993 SANITIZER_INTERFACE_ATTRIBUTE
994 void __sanitizer_reset_coverage() {
995 ResetGlobalCounters();
996 coverage_data.ReinitializeGuards();
997 internal_bzero_aligned16(
998 coverage_data.data(),
999 RoundUpTo(coverage_data.size() * sizeof(coverage_data.data()[0]), 16));
1001 SANITIZER_INTERFACE_ATTRIBUTE
1002 uptr __sanitizer_get_coverage_guards(uptr **data) {
1003 *data = coverage_data.data();
1004 return coverage_data.size();
1007 SANITIZER_INTERFACE_ATTRIBUTE
1008 uptr __sanitizer_get_number_of_counters() {
1009 return coverage_data.GetNumberOf8bitCounters();
1012 SANITIZER_INTERFACE_ATTRIBUTE
1013 uptr __sanitizer_update_counter_bitset_and_clear_counters(u8 *bitset) {
1014 return coverage_data.Update8bitCounterBitsetAndClearCounters(bitset);
1016 // Default empty implementations (weak). Users should redefine them.
1017 #if !SANITIZER_WINDOWS // weak does not work on Windows.
1018 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1019 void __sanitizer_cov_trace_cmp() {}
1020 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1021 void __sanitizer_cov_trace_cmp1() {}
1022 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1023 void __sanitizer_cov_trace_cmp2() {}
1024 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1025 void __sanitizer_cov_trace_cmp4() {}
1026 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1027 void __sanitizer_cov_trace_cmp8() {}
1028 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1029 void __sanitizer_cov_trace_switch() {}
1030 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1031 void __sanitizer_cov_trace_div4() {}
1032 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1033 void __sanitizer_cov_trace_div8() {}
1034 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1035 void __sanitizer_cov_trace_gep() {}
1036 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1037 void __sanitizer_cov_trace_pc_guard() {}
1038 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1039 void __sanitizer_cov_trace_pc_indir() {}
1040 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1041 void __sanitizer_cov_trace_pc_guard_init() {}
1042 #endif // !SANITIZER_WINDOWS
1043 } // extern "C"