blob: 6ef8bf487547e63bf21b3e280c11588444d02b2d [file] [log] [blame]
Bob Wilsona08e9ac2013-11-15 07:18:15 +00001//===-- sanitizer_coverage.cc ---------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Sanitizer Coverage.
11// This file implements run-time support for a poor man's coverage tool.
12//
13// Compiler instrumentation:
Kostya Serebryany714c67c2014-01-17 11:00:30 +000014// For every interesting basic block the compiler injects the following code:
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000015// if (Guard < 0) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +000016// __sanitizer_cov(&Guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +000017// }
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000018// At the module start up time __sanitizer_cov_module_init sets the guards
19// to consecutive negative numbers (-1, -2, -3, ...).
Kostya Serebryany714c67c2014-01-17 11:00:30 +000020// It's fine to call __sanitizer_cov more than once for a given block.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000021//
22// Run-time:
Kostya Serebryany714c67c2014-01-17 11:00:30 +000023// - __sanitizer_cov(): record that we've executed the PC (GET_CALLER_PC).
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000024// and atomically set Guard to -Guard.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000025// - __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. The file format is simple:
28// it's just a sorted sequence of 4-byte offsets in the module.
29//
30// Eventually, this coverage implementation should be obsoleted by a more
31// powerful general purpose Clang/LLVM coverage instrumentation.
32// Consider this implementation as prototype.
33//
34// FIXME: support (or at least test with) dlclose.
35//===----------------------------------------------------------------------===//
36
37#include "sanitizer_allocator_internal.h"
38#include "sanitizer_common.h"
39#include "sanitizer_libc.h"
40#include "sanitizer_mutex.h"
41#include "sanitizer_procmaps.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000042#include "sanitizer_stacktrace.h"
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000043#include "sanitizer_symbolizer.h"
Bob Wilsona08e9ac2013-11-15 07:18:15 +000044#include "sanitizer_flags.h"
45
Kostya Serebryany183cb6e2014-11-14 23:15:55 +000046static atomic_uint32_t dump_once_guard; // Ensure that CovDump runs only once.
47
48static atomic_uintptr_t coverage_counter;
Bob Wilsona08e9ac2013-11-15 07:18:15 +000049
Kostya Serebryany8b530e12014-04-30 10:40:48 +000050// pc_array is the array containing the covered PCs.
Sergey Matveev6cb47a082014-05-19 12:53:03 +000051// To make the pc_array thread- and async-signal-safe it has to be large enough.
Kostya Serebryany8b530e12014-04-30 10:40:48 +000052// 128M counters "ought to be enough for anybody" (4M on 32-bit).
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000053
54// With coverage_direct=1 in ASAN_OPTIONS, pc_array memory is mapped to a file.
55// In this mode, __sanitizer_cov_dump does nothing, and CovUpdateMapping()
56// dump current memory layout to another file.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000057
Sergey Matveev6cb47a082014-05-19 12:53:03 +000058static bool cov_sandboxed = false;
59static int cov_fd = kInvalidFd;
60static unsigned int cov_max_block_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +000061static bool coverage_enabled = false;
62static const char *coverage_dir;
Sergey Matveev6cb47a082014-05-19 12:53:03 +000063
Bob Wilsona08e9ac2013-11-15 07:18:15 +000064namespace __sanitizer {
65
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000066class CoverageData {
67 public:
68 void Init();
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +000069 void Enable();
70 void Disable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +000071 void ReInit();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +000072 void BeforeFork();
73 void AfterFork(int child_pid);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000074 void Extend(uptr npcs);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000075 void Add(uptr pc, u32 *guard);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000076 void IndirCall(uptr caller, uptr callee, uptr callee_cache[],
77 uptr cache_size);
78 void DumpCallerCalleePairs();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +000079 void DumpTrace();
Kostya Serebryany07aee9c2015-03-04 23:41:55 +000080 void DumpAsBitSet();
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +000081 void DumpCounters();
Kostya Serebryany769ddaa2015-03-05 22:19:25 +000082 void DumpOffsets();
83 void DumpAll();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +000084
85 ALWAYS_INLINE
Kostya Serebryanyd421db02015-01-03 00:54:43 +000086 void TraceBasicBlock(s32 *id);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000087
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +000088 void InitializeGuardArray(s32 *guards);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +000089 void InitializeGuards(s32 *guards, uptr n, const char *module_name,
90 uptr caller_pc);
91 void UpdateModuleNameVec(uptr caller_pc, uptr range_beg, uptr range_end);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +000092 void InitializeCounters(u8 *counters, uptr n);
Kostya Serebryany21a1a232015-01-28 22:39:44 +000093 void ReinitializeGuards();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +000094 uptr GetNumberOf8bitCounters();
95 uptr Update8bitCounterBitsetAndClearCounters(u8 *bitset);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000096
97 uptr *data();
98 uptr size();
99
100 private:
101 // Maximal size pc array may ever grow.
102 // We MmapNoReserve this space to ensure that the array is contiguous.
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000103 static const uptr kPcArrayMaxSize = FIRST_32_SECOND_64(1 << 26, 1 << 27);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000104 // The amount file mapping for the pc array is grown by.
105 static const uptr kPcArrayMmapSize = 64 * 1024;
106
107 // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
108 // much RAM as it really needs.
109 uptr *pc_array;
110 // Index of the first available pc_array slot.
111 atomic_uintptr_t pc_array_index;
112 // Array size.
113 atomic_uintptr_t pc_array_size;
114 // Current file mapped size of the pc array.
115 uptr pc_array_mapped_size;
116 // Descriptor of the file mapped pc array.
117 int pc_fd;
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000118
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000119 // Vector of coverage guard arrays, protected by mu.
120 InternalMmapVectorNoCtor<s32*> guard_array_vec;
121
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000122 struct NamedPcRange {
123 const char *name;
124 uptr beg, end; // elements [beg,end) in pc_array.
125 };
126
127 // Vector of module and compilation unit pc ranges.
128 InternalMmapVectorNoCtor<NamedPcRange> comp_unit_name_vec;
129 InternalMmapVectorNoCtor<NamedPcRange> module_name_vec;
Kostya Serebryany88599462015-02-20 00:30:44 +0000130
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000131 struct CounterAndSize {
132 u8 *counters;
133 uptr n;
134 };
135
136 InternalMmapVectorNoCtor<CounterAndSize> counters_vec;
137 uptr num_8bit_counters;
138
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000139 // Caller-Callee (cc) array, size and current index.
140 static const uptr kCcArrayMaxSize = FIRST_32_SECOND_64(1 << 18, 1 << 24);
141 uptr **cc_array;
142 atomic_uintptr_t cc_array_index;
143 atomic_uintptr_t cc_array_size;
144
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000145 // Tracing event array, size and current pointer.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000146 // We record all events (basic block entries) in a global buffer of u32
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000147 // values. Each such value is the index in pc_array.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000148 // So far the tracing is highly experimental:
149 // - not thread-safe;
150 // - does not support long traces;
151 // - not tuned for performance.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000152 static const uptr kTrEventArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 30);
153 u32 *tr_event_array;
154 uptr tr_event_array_size;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000155 u32 *tr_event_pointer;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000156 static const uptr kTrPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000157
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000158 StaticSpinMutex mu;
159
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000160 void DirectOpen();
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000161};
162
163static CoverageData coverage_data;
164
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000165void CovUpdateMapping(const char *path, uptr caller_pc = 0);
166
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000167void CoverageData::DirectOpen() {
Alexey Samsonov4cc76cb2014-11-26 01:48:39 +0000168 InternalScopedString path(kMaxPathLength);
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000169 internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000170 coverage_dir, internal_getpid());
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000171 pc_fd = OpenFile(path.data(), true);
172 if (internal_iserror(pc_fd)) {
173 Report(" Coverage: failed to open %s for writing\n", path.data());
174 Die();
175 }
176
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000177 pc_array_mapped_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000178 CovUpdateMapping(coverage_dir);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000179}
180
181void CoverageData::Init() {
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000182 pc_fd = kInvalidFd;
183}
184
185void CoverageData::Enable() {
Viktor Kutuzov7891c8c2015-02-02 09:38:10 +0000186 if (pc_array)
187 return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000188 pc_array = reinterpret_cast<uptr *>(
189 MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000190 atomic_store(&pc_array_index, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000191 if (common_flags()->coverage_direct) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000192 atomic_store(&pc_array_size, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000193 } else {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000194 atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
195 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000196
197 cc_array = reinterpret_cast<uptr **>(MmapNoReserveOrDie(
198 sizeof(uptr *) * kCcArrayMaxSize, "CovInit::cc_array"));
199 atomic_store(&cc_array_size, kCcArrayMaxSize, memory_order_relaxed);
200 atomic_store(&cc_array_index, 0, memory_order_relaxed);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000201
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000202 // Allocate tr_event_array with a guard page at the end.
203 tr_event_array = reinterpret_cast<u32 *>(MmapNoReserveOrDie(
204 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize + GetMmapGranularity(),
205 "CovInit::tr_event_array"));
206 Mprotect(reinterpret_cast<uptr>(&tr_event_array[kTrEventArrayMaxSize]),
207 GetMmapGranularity());
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000208 tr_event_array_size = kTrEventArrayMaxSize;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000209 tr_event_pointer = tr_event_array;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000210
211 num_8bit_counters = 0;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000212}
213
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000214void CoverageData::InitializeGuardArray(s32 *guards) {
Viktor Kutuzov7891c8c2015-02-02 09:38:10 +0000215 Enable(); // Make sure coverage is enabled at this point.
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000216 s32 n = guards[0];
217 for (s32 j = 1; j <= n; j++) {
218 uptr idx = atomic_fetch_add(&pc_array_index, 1, memory_order_relaxed);
219 guards[j] = -static_cast<s32>(idx + 1);
220 }
221}
222
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000223void CoverageData::Disable() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000224 if (pc_array) {
225 internal_munmap(pc_array, sizeof(uptr) * kPcArrayMaxSize);
226 pc_array = nullptr;
227 }
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000228 if (cc_array) {
229 internal_munmap(cc_array, sizeof(uptr *) * kCcArrayMaxSize);
230 cc_array = nullptr;
231 }
232 if (tr_event_array) {
233 internal_munmap(tr_event_array,
234 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize +
235 GetMmapGranularity());
236 tr_event_array = nullptr;
237 tr_event_pointer = nullptr;
238 }
239 if (pc_fd != kInvalidFd) {
240 internal_close(pc_fd);
241 pc_fd = kInvalidFd;
242 }
243}
244
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000245void CoverageData::ReinitializeGuards() {
246 // Assuming single thread.
247 atomic_store(&pc_array_index, 0, memory_order_relaxed);
248 for (uptr i = 0; i < guard_array_vec.size(); i++)
249 InitializeGuardArray(guard_array_vec[i]);
250}
251
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000252void CoverageData::ReInit() {
253 Disable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000254 if (coverage_enabled) {
255 if (common_flags()->coverage_direct) {
256 // In memory-mapped mode we must extend the new file to the known array
257 // size.
258 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000259 Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000260 if (size) Extend(size);
261 if (coverage_enabled) CovUpdateMapping(coverage_dir);
262 } else {
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000263 Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000264 }
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000265 }
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000266 // Re-initialize the guards.
267 // We are single-threaded now, no need to grab any lock.
268 CHECK_EQ(atomic_load(&pc_array_index, memory_order_relaxed), 0);
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000269 ReinitializeGuards();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000270}
271
272void CoverageData::BeforeFork() {
273 mu.Lock();
274}
275
276void CoverageData::AfterFork(int child_pid) {
277 // We are single-threaded so it's OK to release the lock early.
278 mu.Unlock();
279 if (child_pid == 0) ReInit();
280}
281
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000282// Extend coverage PC array to fit additional npcs elements.
283void CoverageData::Extend(uptr npcs) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000284 if (!common_flags()->coverage_direct) return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000285 SpinMutexLock l(&mu);
286
287 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
288 size += npcs * sizeof(uptr);
289
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000290 if (coverage_enabled && size > pc_array_mapped_size) {
291 if (pc_fd == kInvalidFd) DirectOpen();
292 CHECK_NE(pc_fd, kInvalidFd);
293
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000294 uptr new_mapped_size = pc_array_mapped_size;
295 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000296 CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000297
298 // Extend the file and map the new space at the end of pc_array.
299 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
300 int err;
301 if (internal_iserror(res, &err)) {
302 Printf("failed to extend raw coverage file: %d\n", err);
303 Die();
304 }
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000305
306 uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
307 void *p = MapWritableFileToMemory((void *)next_map_base,
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000308 new_mapped_size - pc_array_mapped_size,
309 pc_fd, pc_array_mapped_size);
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000310 CHECK_EQ((uptr)p, next_map_base);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000311 pc_array_mapped_size = new_mapped_size;
312 }
313
314 atomic_store(&pc_array_size, size, memory_order_release);
315}
316
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000317void CoverageData::InitializeCounters(u8 *counters, uptr n) {
318 if (!counters) return;
319 CHECK_EQ(reinterpret_cast<uptr>(counters) % 16, 0);
320 n = RoundUpTo(n, 16); // The compiler must ensure that counters is 16-aligned.
321 SpinMutexLock l(&mu);
322 counters_vec.push_back({counters, n});
323 num_8bit_counters += n;
324}
325
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000326void CoverageData::UpdateModuleNameVec(uptr caller_pc, uptr range_beg,
327 uptr range_end) {
328 auto sym = Symbolizer::GetOrInit();
329 if (!sym)
330 return;
331 const char *module_name = sym->GetModuleNameForPc(caller_pc);
332 if (!module_name) return;
333 if (module_name_vec.empty() || module_name_vec.back().name != module_name)
334 module_name_vec.push_back({module_name, range_beg, range_end});
335 else
336 module_name_vec.back().end = range_end;
337}
338
Kostya Serebryany88599462015-02-20 00:30:44 +0000339void CoverageData::InitializeGuards(s32 *guards, uptr n,
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000340 const char *comp_unit_name,
341 uptr caller_pc) {
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000342 // The array 'guards' has n+1 elements, we use the element zero
343 // to store 'n'.
344 CHECK_LT(n, 1 << 30);
345 guards[0] = static_cast<s32>(n);
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000346 InitializeGuardArray(guards);
347 SpinMutexLock l(&mu);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000348 uptr range_end = atomic_load(&pc_array_index, memory_order_relaxed);
349 uptr range_beg = range_end - n;
350 comp_unit_name_vec.push_back({comp_unit_name, range_beg, range_end});
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000351 guard_array_vec.push_back(guards);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000352 UpdateModuleNameVec(caller_pc, range_beg, range_end);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000353}
354
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000355static const uptr kBundleCounterBits = 16;
356
357// When coverage_order_pcs==true and SANITIZER_WORDSIZE==64
358// we insert the global counter into the first 16 bits of the PC.
359uptr BundlePcAndCounter(uptr pc, uptr counter) {
360 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
361 return pc;
362 static const uptr kMaxCounter = (1 << kBundleCounterBits) - 1;
363 if (counter > kMaxCounter)
364 counter = kMaxCounter;
365 CHECK_EQ(0, pc >> (SANITIZER_WORDSIZE - kBundleCounterBits));
366 return pc | (counter << (SANITIZER_WORDSIZE - kBundleCounterBits));
367}
368
369uptr UnbundlePc(uptr bundle) {
370 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
371 return bundle;
372 return (bundle << kBundleCounterBits) >> kBundleCounterBits;
373}
374
375uptr UnbundleCounter(uptr bundle) {
376 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
377 return 0;
378 return bundle >> (SANITIZER_WORDSIZE - kBundleCounterBits);
379}
380
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000381// If guard is negative, atomically set it to -guard and store the PC in
382// pc_array.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000383void CoverageData::Add(uptr pc, u32 *guard) {
384 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
385 s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
386 if (guard_value >= 0) return;
387
388 atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000389 if (!pc_array) return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000390
391 uptr idx = -guard_value - 1;
392 if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
393 return; // May happen after fork when pc_array_index becomes 0.
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000394 CHECK_LT(idx * sizeof(uptr),
395 atomic_load(&pc_array_size, memory_order_acquire));
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000396 uptr counter = atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
397 pc_array[idx] = BundlePcAndCounter(pc, counter);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000398}
399
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000400// Registers a pair caller=>callee.
401// When a given caller is seen for the first time, the callee_cache is added
402// to the global array cc_array, callee_cache[0] is set to caller and
403// callee_cache[1] is set to cache_size.
404// Then we are trying to add callee to callee_cache [2,cache_size) if it is
405// not there yet.
406// If the cache is full we drop the callee (may want to fix this later).
407void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
408 uptr cache_size) {
409 if (!cc_array) return;
410 atomic_uintptr_t *atomic_callee_cache =
411 reinterpret_cast<atomic_uintptr_t *>(callee_cache);
412 uptr zero = 0;
413 if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
414 memory_order_seq_cst)) {
415 uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
416 CHECK_LT(idx * sizeof(uptr),
417 atomic_load(&cc_array_size, memory_order_acquire));
418 callee_cache[1] = cache_size;
419 cc_array[idx] = callee_cache;
420 }
421 CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
422 for (uptr i = 2; i < cache_size; i++) {
423 uptr was = 0;
424 if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000425 memory_order_seq_cst)) {
426 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000427 return;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000428 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000429 if (was == callee) // Already have this callee.
430 return;
431 }
432}
433
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000434uptr CoverageData::GetNumberOf8bitCounters() {
435 return num_8bit_counters;
436}
437
438// Map every 8bit counter to a 8-bit bitset and clear the counter.
439uptr CoverageData::Update8bitCounterBitsetAndClearCounters(u8 *bitset) {
440 uptr num_new_bits = 0;
441 uptr cur = 0;
442 // For better speed we map 8 counters to 8 bytes of bitset at once.
443 static const uptr kBatchSize = 8;
444 CHECK_EQ(reinterpret_cast<uptr>(bitset) % kBatchSize, 0);
445 for (uptr i = 0, len = counters_vec.size(); i < len; i++) {
446 u8 *c = counters_vec[i].counters;
447 uptr n = counters_vec[i].n;
448 CHECK_EQ(n % 16, 0);
449 CHECK_EQ(cur % kBatchSize, 0);
450 CHECK_EQ(reinterpret_cast<uptr>(c) % kBatchSize, 0);
451 if (!bitset) {
452 internal_bzero_aligned16(c, n);
453 cur += n;
454 continue;
455 }
456 for (uptr j = 0; j < n; j += kBatchSize, cur += kBatchSize) {
457 CHECK_LT(cur, num_8bit_counters);
458 u64 *pc64 = reinterpret_cast<u64*>(c + j);
459 u64 *pb64 = reinterpret_cast<u64*>(bitset + cur);
460 u64 c64 = *pc64;
461 u64 old_bits_64 = *pb64;
462 u64 new_bits_64 = old_bits_64;
463 if (c64) {
464 *pc64 = 0;
465 for (uptr k = 0; k < kBatchSize; k++) {
466 u64 x = (c64 >> (8 * k)) & 0xff;
467 if (x) {
468 u64 bit = 0;
469 /**/ if (x >= 128) bit = 128;
470 else if (x >= 32) bit = 64;
471 else if (x >= 16) bit = 32;
472 else if (x >= 8) bit = 16;
473 else if (x >= 4) bit = 8;
474 else if (x >= 3) bit = 4;
475 else if (x >= 2) bit = 2;
476 else if (x >= 1) bit = 1;
477 u64 mask = bit << (8 * k);
478 if (!(new_bits_64 & mask)) {
479 num_new_bits++;
480 new_bits_64 |= mask;
481 }
482 }
483 }
484 *pb64 = new_bits_64;
485 }
486 }
487 }
488 CHECK_EQ(cur, num_8bit_counters);
489 return num_new_bits;
490}
491
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000492uptr *CoverageData::data() {
493 return pc_array;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000494}
495
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000496uptr CoverageData::size() {
497 return atomic_load(&pc_array_index, memory_order_relaxed);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000498}
499
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000500// Block layout for packed file format: header, followed by module name (no
501// trailing zero), followed by data blob.
502struct CovHeader {
503 int pid;
504 unsigned int module_name_length;
505 unsigned int data_length;
506};
507
508static void CovWritePacked(int pid, const char *module, const void *blob,
509 unsigned int blob_size) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000510 if (cov_fd < 0) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000511 unsigned module_name_length = internal_strlen(module);
512 CovHeader header = {pid, module_name_length, blob_size};
513
514 if (cov_max_block_size == 0) {
515 // Writing to a file. Just go ahead.
516 internal_write(cov_fd, &header, sizeof(header));
517 internal_write(cov_fd, module, module_name_length);
518 internal_write(cov_fd, blob, blob_size);
519 } else {
520 // Writing to a socket. We want to split the data into appropriately sized
521 // blocks.
522 InternalScopedBuffer<char> block(cov_max_block_size);
523 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
524 uptr header_size_with_module = sizeof(header) + module_name_length;
525 CHECK_LT(header_size_with_module, cov_max_block_size);
526 unsigned int max_payload_size =
527 cov_max_block_size - header_size_with_module;
528 char *block_pos = block.data();
529 internal_memcpy(block_pos, &header, sizeof(header));
530 block_pos += sizeof(header);
531 internal_memcpy(block_pos, module, module_name_length);
532 block_pos += module_name_length;
533 char *block_data_begin = block_pos;
Alexey Samsonov4925fd42014-11-13 22:40:59 +0000534 const char *blob_pos = (const char *)blob;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000535 while (blob_size > 0) {
536 unsigned int payload_size = Min(blob_size, max_payload_size);
537 blob_size -= payload_size;
538 internal_memcpy(block_data_begin, blob_pos, payload_size);
539 blob_pos += payload_size;
540 ((CovHeader *)block.data())->data_length = payload_size;
541 internal_write(cov_fd, block.data(),
542 header_size_with_module + payload_size);
543 }
544 }
545}
546
Sergey Matveev83f91e72014-05-21 13:43:52 +0000547// If packed = false: <name>.<pid>.<sancov> (name = module name).
548// If packed = true and name == 0: <pid>.<sancov>.<packed>.
549// If packed = true and name != 0: <name>.<sancov>.<packed> (name is
550// user-supplied).
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000551static int CovOpenFile(InternalScopedString *path, bool packed,
552 const char *name, const char *extension = "sancov") {
553 path->clear();
Sergey Matveev83f91e72014-05-21 13:43:52 +0000554 if (!packed) {
555 CHECK(name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000556 path->append("%s/%s.%zd.%s", coverage_dir, name, internal_getpid(),
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000557 extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000558 } else {
559 if (!name)
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000560 path->append("%s/%zd.%s.packed", coverage_dir, internal_getpid(),
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000561 extension);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000562 else
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000563 path->append("%s/%s.%s.packed", coverage_dir, name, extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000564 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000565 uptr fd = OpenFile(path->data(), true);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000566 if (internal_iserror(fd)) {
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000567 Report(" SanitizerCoverage: failed to open %s for writing\n", path->data());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000568 return -1;
569 }
570 return fd;
571}
572
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000573// Dump trace PCs and trace events into two separate files.
574void CoverageData::DumpTrace() {
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000575 uptr max_idx = tr_event_pointer - tr_event_array;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000576 if (!max_idx) return;
577 auto sym = Symbolizer::GetOrInit();
578 if (!sym)
579 return;
580 InternalScopedString out(32 << 20);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000581 for (uptr i = 0, n = size(); i < n; i++) {
582 const char *module_name = "<unknown>";
583 uptr module_address = 0;
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000584 sym->GetModuleNameAndOffsetForPC(UnbundlePc(pc_array[i]), &module_name,
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000585 &module_address);
586 out.append("%s 0x%zx\n", module_name, module_address);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000587 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000588 InternalScopedString path(kMaxPathLength);
589 int fd = CovOpenFile(&path, false, "trace-points");
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000590 if (fd < 0) return;
591 internal_write(fd, out.data(), out.length());
592 internal_close(fd);
593
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000594 fd = CovOpenFile(&path, false, "trace-compunits");
Kostya Serebryany88599462015-02-20 00:30:44 +0000595 if (fd < 0) return;
596 out.clear();
597 for (uptr i = 0; i < comp_unit_name_vec.size(); i++)
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000598 out.append("%s\n", comp_unit_name_vec[i].name);
Kostya Serebryany88599462015-02-20 00:30:44 +0000599 internal_write(fd, out.data(), out.length());
600 internal_close(fd);
601
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000602 fd = CovOpenFile(&path, false, "trace-events");
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000603 if (fd < 0) return;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000604 uptr bytes_to_write = max_idx * sizeof(tr_event_array[0]);
605 u8 *event_bytes = reinterpret_cast<u8*>(tr_event_array);
606 // The trace file could be huge, and may not be written with a single syscall.
607 while (bytes_to_write) {
608 uptr actually_written = internal_write(fd, event_bytes, bytes_to_write);
609 if (actually_written <= bytes_to_write) {
610 bytes_to_write -= actually_written;
611 event_bytes += actually_written;
612 } else {
613 break;
614 }
615 }
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000616 internal_close(fd);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000617 VReport(1, " CovDump: Trace: %zd PCs written\n", size());
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000618 VReport(1, " CovDump: Trace: %zd Events written\n", max_idx);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000619}
620
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000621// This function dumps the caller=>callee pairs into a file as a sequence of
622// lines like "module_name offset".
623void CoverageData::DumpCallerCalleePairs() {
624 uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
625 if (!max_idx) return;
626 auto sym = Symbolizer::GetOrInit();
627 if (!sym)
628 return;
Kostya Serebryany40aa4a22014-10-31 19:49:46 +0000629 InternalScopedString out(32 << 20);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000630 uptr total = 0;
631 for (uptr i = 0; i < max_idx; i++) {
632 uptr *cc_cache = cc_array[i];
633 CHECK(cc_cache);
634 uptr caller = cc_cache[0];
635 uptr n_callees = cc_cache[1];
636 const char *caller_module_name = "<unknown>";
637 uptr caller_module_address = 0;
638 sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
639 &caller_module_address);
640 for (uptr j = 2; j < n_callees; j++) {
641 uptr callee = cc_cache[j];
642 if (!callee) break;
643 total++;
644 const char *callee_module_name = "<unknown>";
645 uptr callee_module_address = 0;
646 sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
647 &callee_module_address);
648 out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
649 caller_module_address, callee_module_name,
650 callee_module_address);
651 }
652 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000653 InternalScopedString path(kMaxPathLength);
654 int fd = CovOpenFile(&path, false, "caller-callee");
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000655 if (fd < 0) return;
656 internal_write(fd, out.data(), out.length());
657 internal_close(fd);
658 VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
659}
660
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000661// Record the current PC into the event buffer.
662// Every event is a u32 value (index in tr_pc_array_index) so we compute
663// it once and then cache in the provided 'cache' storage.
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000664//
665// This function will eventually be inlined by the compiler.
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000666void CoverageData::TraceBasicBlock(s32 *id) {
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000667 // Will trap here if
668 // 1. coverage is not enabled at run-time.
669 // 2. The array tr_event_array is full.
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000670 *tr_event_pointer = static_cast<u32>(*id - 1);
671 tr_event_pointer++;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000672}
673
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000674void CoverageData::DumpCounters() {
675 if (!common_flags()->coverage_counters) return;
676 uptr n = coverage_data.GetNumberOf8bitCounters();
677 if (!n) return;
678 InternalScopedBuffer<u8> bitset(n);
679 coverage_data.Update8bitCounterBitsetAndClearCounters(bitset.data());
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000680 InternalScopedString path(kMaxPathLength);
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000681
682 for (uptr m = 0; m < module_name_vec.size(); m++) {
683 auto r = module_name_vec[m];
684 CHECK(r.name);
685 CHECK_LE(r.beg, r.end);
686 CHECK_LE(r.end, size());
687 const char *base_name = StripModuleName(r.name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000688 int fd =
689 CovOpenFile(&path, /* packed */ false, base_name, "counters-sancov");
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000690 if (fd < 0) return;
691 internal_write(fd, bitset.data() + r.beg, r.end - r.beg);
692 internal_close(fd);
693 VReport(1, " CovDump: %zd counters written for '%s'\n", r.end - r.beg,
694 base_name);
695 }
696}
697
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000698void CoverageData::DumpAsBitSet() {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000699 if (!common_flags()->coverage_bitset) return;
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000700 if (!size()) return;
701 InternalScopedBuffer<char> out(size());
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000702 InternalScopedString path(kMaxPathLength);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000703 for (uptr m = 0; m < module_name_vec.size(); m++) {
704 uptr n_set_bits = 0;
705 auto r = module_name_vec[m];
706 CHECK(r.name);
707 CHECK_LE(r.beg, r.end);
708 CHECK_LE(r.end, size());
709 for (uptr i = r.beg; i < r.end; i++) {
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000710 uptr pc = UnbundlePc(pc_array[i]);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000711 out[i] = pc ? '1' : '0';
712 if (pc)
713 n_set_bits++;
714 }
715 const char *base_name = StripModuleName(r.name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000716 int fd = CovOpenFile(&path, /* packed */ false, base_name, "bitset-sancov");
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000717 if (fd < 0) return;
718 internal_write(fd, out.data() + r.beg, r.end - r.beg);
719 internal_close(fd);
720 VReport(1,
721 " CovDump: bitset of %zd bits written for '%s', %zd bits are set\n",
722 r.end - r.beg, base_name, n_set_bits);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000723 }
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000724}
725
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000726void CoverageData::DumpOffsets() {
727 auto sym = Symbolizer::GetOrInit();
Kostya Serebryanya7ee2732014-12-30 19:55:04 +0000728 if (!common_flags()->coverage_pcs) return;
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000729 CHECK_NE(sym, nullptr);
Kostya Serebryany9f1243e2015-03-17 22:09:19 +0000730 InternalMmapVector<uptr> offsets(0);
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000731 InternalScopedString path(kMaxPathLength);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000732 for (uptr m = 0; m < module_name_vec.size(); m++) {
733 offsets.clear();
734 auto r = module_name_vec[m];
735 CHECK(r.name);
736 CHECK_LE(r.beg, r.end);
737 CHECK_LE(r.end, size());
738 const char *module_name = "<unknown>";
739 for (uptr i = r.beg; i < r.end; i++) {
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000740 uptr pc = UnbundlePc(pc_array[i]);
741 uptr counter = UnbundleCounter(pc_array[i]);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000742 if (!pc) continue; // Not visited.
743 uptr offset = 0;
744 sym->GetModuleNameAndOffsetForPC(pc, &module_name, &offset);
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000745 offsets.push_back(BundlePcAndCounter(offset, counter));
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000746 }
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000747
748 SortArray(offsets.data(), offsets.size());
749 for (uptr i = 0; i < offsets.size(); i++)
750 offsets[i] = UnbundlePc(offsets[i]);
751
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000752 module_name = StripModuleName(r.name);
753 if (cov_sandboxed) {
754 if (cov_fd >= 0) {
755 CovWritePacked(internal_getpid(), module_name, offsets.data(),
Kostya Serebryany9f1243e2015-03-17 22:09:19 +0000756 offsets.size() * sizeof(offsets[0]));
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000757 VReport(1, " CovDump: %zd PCs written to packed file\n",
758 offsets.size());
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000759 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000760 } else {
761 // One file per module per process.
762 int fd = CovOpenFile(&path, false /* packed */, module_name);
763 if (fd < 0) continue;
Kostya Serebryany9f1243e2015-03-17 22:09:19 +0000764 internal_write(fd, offsets.data(), offsets.size() * sizeof(offsets[0]));
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000765 internal_close(fd);
766 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(),
767 offsets.size());
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000768 }
769 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000770 if (cov_fd >= 0)
771 internal_close(cov_fd);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000772}
773
774void CoverageData::DumpAll() {
775 if (!coverage_enabled || common_flags()->coverage_direct) return;
776 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
777 return;
778 DumpAsBitSet();
779 DumpCounters();
780 DumpTrace();
781 DumpOffsets();
782 DumpCallerCalleePairs();
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000783}
784
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000785void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
786 if (!args) return;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000787 if (!coverage_enabled) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000788 cov_sandboxed = args->coverage_sandboxed;
789 if (!cov_sandboxed) return;
790 cov_fd = args->coverage_fd;
791 cov_max_block_size = args->coverage_max_block_size;
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000792 if (cov_fd < 0) {
793 InternalScopedString path(kMaxPathLength);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000794 // Pre-open the file now. The sandbox won't allow us to do it later.
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000795 cov_fd = CovOpenFile(&path, true /* packed */, 0);
796 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000797}
798
Sergey Matveev83f91e72014-05-21 13:43:52 +0000799int MaybeOpenCovFile(const char *name) {
800 CHECK(name);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000801 if (!coverage_enabled) return -1;
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000802 InternalScopedString path(kMaxPathLength);
803 return CovOpenFile(&path, true /* packed */, name);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000804}
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000805
806void CovBeforeFork() {
807 coverage_data.BeforeFork();
808}
809
810void CovAfterFork(int child_pid) {
811 coverage_data.AfterFork(child_pid);
812}
813
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000814void InitializeCoverage(bool enabled, const char *dir) {
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000815 if (coverage_enabled)
816 return; // May happen if two sanitizer enable coverage in the same process.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000817 coverage_enabled = enabled;
818 coverage_dir = dir;
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000819 coverage_data.Init();
820 if (enabled) coverage_data.Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000821#if !SANITIZER_WINDOWS
822 if (!common_flags()->coverage_direct) Atexit(__sanitizer_cov_dump);
823#endif
824}
825
826void ReInitializeCoverage(bool enabled, const char *dir) {
827 coverage_enabled = enabled;
828 coverage_dir = dir;
829 coverage_data.ReInit();
830}
831
832void CoverageUpdateMapping() {
833 if (coverage_enabled)
834 CovUpdateMapping(coverage_dir);
835}
836
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000837} // namespace __sanitizer
838
839extern "C" {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000840SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000841 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
842 guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000843}
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000844SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_with_check(u32 *guard) {
845 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000846 if (static_cast<s32>(
847 __sanitizer::atomic_load(atomic_guard, memory_order_relaxed)) < 0)
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000848 __sanitizer_cov(guard);
849}
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000850SANITIZER_INTERFACE_ATTRIBUTE void
851__sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
852 coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
853 callee, callee_cache16, 16);
854}
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000855SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000856 coverage_enabled = true;
857 coverage_dir = common_flags()->coverage_dir;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000858 coverage_data.Init();
859}
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000860SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() {
861 coverage_data.DumpAll();
862}
Kostya Serebryany88599462015-02-20 00:30:44 +0000863SANITIZER_INTERFACE_ATTRIBUTE void
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000864__sanitizer_cov_module_init(s32 *guards, uptr npcs, u8 *counters,
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000865 const char *comp_unit_name) {
866 coverage_data.InitializeGuards(guards, npcs, comp_unit_name, GET_CALLER_PC());
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000867 coverage_data.InitializeCounters(counters, npcs);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000868 if (!common_flags()->coverage_direct) return;
869 if (SANITIZER_ANDROID && coverage_enabled) {
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000870 // dlopen/dlclose interceptors do not work on Android, so we rely on
871 // Extend() calls to update .sancov.map.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000872 CovUpdateMapping(coverage_dir, GET_CALLER_PC());
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000873 }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000874 coverage_data.Extend(npcs);
875}
Sergey Matveev83f91e72014-05-21 13:43:52 +0000876SANITIZER_INTERFACE_ATTRIBUTE
877sptr __sanitizer_maybe_open_cov_file(const char *name) {
878 return MaybeOpenCovFile(name);
879}
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000880SANITIZER_INTERFACE_ATTRIBUTE
881uptr __sanitizer_get_total_unique_coverage() {
882 return atomic_load(&coverage_counter, memory_order_relaxed);
883}
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000884
885SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000886void __sanitizer_cov_trace_func_enter(s32 *id) {
887 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000888}
889SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000890void __sanitizer_cov_trace_basic_block(s32 *id) {
891 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000892}
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000893SANITIZER_INTERFACE_ATTRIBUTE
894void __sanitizer_reset_coverage() {
895 coverage_data.ReinitializeGuards();
896 internal_bzero_aligned16(
897 coverage_data.data(),
898 RoundUpTo(coverage_data.size() * sizeof(coverage_data.data()[0]), 16));
899}
900SANITIZER_INTERFACE_ATTRIBUTE
901uptr __sanitizer_get_coverage_guards(uptr **data) {
902 *data = coverage_data.data();
903 return coverage_data.size();
904}
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000905
906SANITIZER_INTERFACE_ATTRIBUTE
907uptr __sanitizer_get_number_of_counters() {
908 return coverage_data.GetNumberOf8bitCounters();
909}
910
911SANITIZER_INTERFACE_ATTRIBUTE
912uptr __sanitizer_update_counter_bitset_and_clear_counters(u8 *bitset) {
913 return coverage_data.Update8bitCounterBitsetAndClearCounters(bitset);
914}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000915} // extern "C"