blob: 8d827e6340ddfb307c04e431a45f77fddf541ed1 [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
Kostya Serebryany2d56aba2015-03-18 22:03:39 +000027// this will create a file module_name.PID.sancov.
28//
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.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000033//
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.
37//
38// FIXME: support (or at least test with) dlclose.
39//===----------------------------------------------------------------------===//
40
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"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000046#include "sanitizer_stacktrace.h"
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000047#include "sanitizer_symbolizer.h"
Bob Wilsona08e9ac2013-11-15 07:18:15 +000048#include "sanitizer_flags.h"
49
Kostya Serebryany2d56aba2015-03-18 22:03:39 +000050static const u64 kMagic64 = 0xC0BFFFFFFFFFFF64ULL;
51static const u64 kMagic32 = 0xC0BFFFFFFFFFFF32ULL;
52
Kostya Serebryany183cb6e2014-11-14 23:15:55 +000053static atomic_uint32_t dump_once_guard; // Ensure that CovDump runs only once.
54
55static atomic_uintptr_t coverage_counter;
Bob Wilsona08e9ac2013-11-15 07:18:15 +000056
Kostya Serebryany8b530e12014-04-30 10:40:48 +000057// pc_array is the array containing the covered PCs.
Sergey Matveev6cb47a082014-05-19 12:53:03 +000058// To make the pc_array thread- and async-signal-safe it has to be large enough.
Kostya Serebryany8b530e12014-04-30 10:40:48 +000059// 128M counters "ought to be enough for anybody" (4M on 32-bit).
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000060
61// With coverage_direct=1 in ASAN_OPTIONS, pc_array memory is mapped to a file.
62// In this mode, __sanitizer_cov_dump does nothing, and CovUpdateMapping()
63// dump current memory layout to another file.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000064
Sergey Matveev6cb47a082014-05-19 12:53:03 +000065static bool cov_sandboxed = false;
66static int cov_fd = kInvalidFd;
67static unsigned int cov_max_block_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +000068static bool coverage_enabled = false;
69static const char *coverage_dir;
Sergey Matveev6cb47a082014-05-19 12:53:03 +000070
Bob Wilsona08e9ac2013-11-15 07:18:15 +000071namespace __sanitizer {
72
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000073class CoverageData {
74 public:
75 void Init();
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +000076 void Enable();
77 void Disable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +000078 void ReInit();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +000079 void BeforeFork();
80 void AfterFork(int child_pid);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000081 void Extend(uptr npcs);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000082 void Add(uptr pc, u32 *guard);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000083 void IndirCall(uptr caller, uptr callee, uptr callee_cache[],
84 uptr cache_size);
85 void DumpCallerCalleePairs();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +000086 void DumpTrace();
Kostya Serebryany07aee9c2015-03-04 23:41:55 +000087 void DumpAsBitSet();
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +000088 void DumpCounters();
Kostya Serebryany769ddaa2015-03-05 22:19:25 +000089 void DumpOffsets();
90 void DumpAll();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +000091
92 ALWAYS_INLINE
Kostya Serebryanyd421db02015-01-03 00:54:43 +000093 void TraceBasicBlock(s32 *id);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000094
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +000095 void InitializeGuardArray(s32 *guards);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +000096 void InitializeGuards(s32 *guards, uptr n, const char *module_name,
97 uptr caller_pc);
98 void UpdateModuleNameVec(uptr caller_pc, uptr range_beg, uptr range_end);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +000099 void InitializeCounters(u8 *counters, uptr n);
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000100 void ReinitializeGuards();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000101 uptr GetNumberOf8bitCounters();
102 uptr Update8bitCounterBitsetAndClearCounters(u8 *bitset);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000103
104 uptr *data();
105 uptr size();
106
107 private:
108 // Maximal size pc array may ever grow.
109 // We MmapNoReserve this space to ensure that the array is contiguous.
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000110 static const uptr kPcArrayMaxSize = FIRST_32_SECOND_64(1 << 26, 1 << 27);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000111 // The amount file mapping for the pc array is grown by.
112 static const uptr kPcArrayMmapSize = 64 * 1024;
113
114 // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
115 // much RAM as it really needs.
116 uptr *pc_array;
117 // Index of the first available pc_array slot.
118 atomic_uintptr_t pc_array_index;
119 // Array size.
120 atomic_uintptr_t pc_array_size;
121 // Current file mapped size of the pc array.
122 uptr pc_array_mapped_size;
123 // Descriptor of the file mapped pc array.
124 int pc_fd;
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000125
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000126 // Vector of coverage guard arrays, protected by mu.
127 InternalMmapVectorNoCtor<s32*> guard_array_vec;
128
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000129 struct NamedPcRange {
130 const char *name;
131 uptr beg, end; // elements [beg,end) in pc_array.
132 };
133
134 // Vector of module and compilation unit pc ranges.
135 InternalMmapVectorNoCtor<NamedPcRange> comp_unit_name_vec;
136 InternalMmapVectorNoCtor<NamedPcRange> module_name_vec;
Kostya Serebryany88599462015-02-20 00:30:44 +0000137
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000138 struct CounterAndSize {
139 u8 *counters;
140 uptr n;
141 };
142
143 InternalMmapVectorNoCtor<CounterAndSize> counters_vec;
144 uptr num_8bit_counters;
145
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000146 // Caller-Callee (cc) array, size and current index.
147 static const uptr kCcArrayMaxSize = FIRST_32_SECOND_64(1 << 18, 1 << 24);
148 uptr **cc_array;
149 atomic_uintptr_t cc_array_index;
150 atomic_uintptr_t cc_array_size;
151
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000152 // Tracing event array, size and current pointer.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000153 // We record all events (basic block entries) in a global buffer of u32
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000154 // values. Each such value is the index in pc_array.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000155 // So far the tracing is highly experimental:
156 // - not thread-safe;
157 // - does not support long traces;
158 // - not tuned for performance.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000159 static const uptr kTrEventArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 30);
160 u32 *tr_event_array;
161 uptr tr_event_array_size;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000162 u32 *tr_event_pointer;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000163 static const uptr kTrPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000164
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000165 StaticSpinMutex mu;
166
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000167 void DirectOpen();
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000168};
169
170static CoverageData coverage_data;
171
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000172void CovUpdateMapping(const char *path, uptr caller_pc = 0);
173
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000174void CoverageData::DirectOpen() {
Alexey Samsonov4cc76cb2014-11-26 01:48:39 +0000175 InternalScopedString path(kMaxPathLength);
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000176 internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000177 coverage_dir, internal_getpid());
Alexander Potapenko141e4202015-03-23 10:10:46 +0000178 pc_fd = OpenFile(path.data(), RdWr);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000179 if (internal_iserror(pc_fd)) {
Alexander Potapenko141e4202015-03-23 10:10:46 +0000180 Report(" Coverage: failed to open %s for reading/writing\n", path.data());
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000181 Die();
182 }
183
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000184 pc_array_mapped_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000185 CovUpdateMapping(coverage_dir);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000186}
187
188void CoverageData::Init() {
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000189 pc_fd = kInvalidFd;
190}
191
192void CoverageData::Enable() {
Viktor Kutuzov7891c8c2015-02-02 09:38:10 +0000193 if (pc_array)
194 return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000195 pc_array = reinterpret_cast<uptr *>(
196 MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000197 atomic_store(&pc_array_index, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000198 if (common_flags()->coverage_direct) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000199 atomic_store(&pc_array_size, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000200 } else {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000201 atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
202 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000203
204 cc_array = reinterpret_cast<uptr **>(MmapNoReserveOrDie(
205 sizeof(uptr *) * kCcArrayMaxSize, "CovInit::cc_array"));
206 atomic_store(&cc_array_size, kCcArrayMaxSize, memory_order_relaxed);
207 atomic_store(&cc_array_index, 0, memory_order_relaxed);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000208
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000209 // Allocate tr_event_array with a guard page at the end.
210 tr_event_array = reinterpret_cast<u32 *>(MmapNoReserveOrDie(
211 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize + GetMmapGranularity(),
212 "CovInit::tr_event_array"));
213 Mprotect(reinterpret_cast<uptr>(&tr_event_array[kTrEventArrayMaxSize]),
214 GetMmapGranularity());
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000215 tr_event_array_size = kTrEventArrayMaxSize;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000216 tr_event_pointer = tr_event_array;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000217
218 num_8bit_counters = 0;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000219}
220
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000221void CoverageData::InitializeGuardArray(s32 *guards) {
Viktor Kutuzov7891c8c2015-02-02 09:38:10 +0000222 Enable(); // Make sure coverage is enabled at this point.
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000223 s32 n = guards[0];
224 for (s32 j = 1; j <= n; j++) {
225 uptr idx = atomic_fetch_add(&pc_array_index, 1, memory_order_relaxed);
226 guards[j] = -static_cast<s32>(idx + 1);
227 }
228}
229
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000230void CoverageData::Disable() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000231 if (pc_array) {
232 internal_munmap(pc_array, sizeof(uptr) * kPcArrayMaxSize);
233 pc_array = nullptr;
234 }
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000235 if (cc_array) {
236 internal_munmap(cc_array, sizeof(uptr *) * kCcArrayMaxSize);
237 cc_array = nullptr;
238 }
239 if (tr_event_array) {
240 internal_munmap(tr_event_array,
241 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize +
242 GetMmapGranularity());
243 tr_event_array = nullptr;
244 tr_event_pointer = nullptr;
245 }
246 if (pc_fd != kInvalidFd) {
247 internal_close(pc_fd);
248 pc_fd = kInvalidFd;
249 }
250}
251
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000252void CoverageData::ReinitializeGuards() {
253 // Assuming single thread.
254 atomic_store(&pc_array_index, 0, memory_order_relaxed);
255 for (uptr i = 0; i < guard_array_vec.size(); i++)
256 InitializeGuardArray(guard_array_vec[i]);
257}
258
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000259void CoverageData::ReInit() {
260 Disable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000261 if (coverage_enabled) {
262 if (common_flags()->coverage_direct) {
263 // In memory-mapped mode we must extend the new file to the known array
264 // size.
265 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000266 Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000267 if (size) Extend(size);
268 if (coverage_enabled) CovUpdateMapping(coverage_dir);
269 } else {
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000270 Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000271 }
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000272 }
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000273 // Re-initialize the guards.
274 // We are single-threaded now, no need to grab any lock.
275 CHECK_EQ(atomic_load(&pc_array_index, memory_order_relaxed), 0);
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000276 ReinitializeGuards();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000277}
278
279void CoverageData::BeforeFork() {
280 mu.Lock();
281}
282
283void CoverageData::AfterFork(int child_pid) {
284 // We are single-threaded so it's OK to release the lock early.
285 mu.Unlock();
286 if (child_pid == 0) ReInit();
287}
288
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000289// Extend coverage PC array to fit additional npcs elements.
290void CoverageData::Extend(uptr npcs) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000291 if (!common_flags()->coverage_direct) return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000292 SpinMutexLock l(&mu);
293
294 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
295 size += npcs * sizeof(uptr);
296
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000297 if (coverage_enabled && size > pc_array_mapped_size) {
298 if (pc_fd == kInvalidFd) DirectOpen();
299 CHECK_NE(pc_fd, kInvalidFd);
300
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000301 uptr new_mapped_size = pc_array_mapped_size;
302 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000303 CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000304
305 // Extend the file and map the new space at the end of pc_array.
306 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
307 int err;
308 if (internal_iserror(res, &err)) {
309 Printf("failed to extend raw coverage file: %d\n", err);
310 Die();
311 }
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000312
313 uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
314 void *p = MapWritableFileToMemory((void *)next_map_base,
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000315 new_mapped_size - pc_array_mapped_size,
316 pc_fd, pc_array_mapped_size);
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000317 CHECK_EQ((uptr)p, next_map_base);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000318 pc_array_mapped_size = new_mapped_size;
319 }
320
321 atomic_store(&pc_array_size, size, memory_order_release);
322}
323
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000324void CoverageData::InitializeCounters(u8 *counters, uptr n) {
325 if (!counters) return;
326 CHECK_EQ(reinterpret_cast<uptr>(counters) % 16, 0);
327 n = RoundUpTo(n, 16); // The compiler must ensure that counters is 16-aligned.
328 SpinMutexLock l(&mu);
329 counters_vec.push_back({counters, n});
330 num_8bit_counters += n;
331}
332
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000333void CoverageData::UpdateModuleNameVec(uptr caller_pc, uptr range_beg,
334 uptr range_end) {
335 auto sym = Symbolizer::GetOrInit();
336 if (!sym)
337 return;
338 const char *module_name = sym->GetModuleNameForPc(caller_pc);
339 if (!module_name) return;
340 if (module_name_vec.empty() || module_name_vec.back().name != module_name)
341 module_name_vec.push_back({module_name, range_beg, range_end});
342 else
343 module_name_vec.back().end = range_end;
344}
345
Kostya Serebryany88599462015-02-20 00:30:44 +0000346void CoverageData::InitializeGuards(s32 *guards, uptr n,
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000347 const char *comp_unit_name,
348 uptr caller_pc) {
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000349 // The array 'guards' has n+1 elements, we use the element zero
350 // to store 'n'.
351 CHECK_LT(n, 1 << 30);
352 guards[0] = static_cast<s32>(n);
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000353 InitializeGuardArray(guards);
354 SpinMutexLock l(&mu);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000355 uptr range_end = atomic_load(&pc_array_index, memory_order_relaxed);
356 uptr range_beg = range_end - n;
357 comp_unit_name_vec.push_back({comp_unit_name, range_beg, range_end});
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000358 guard_array_vec.push_back(guards);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000359 UpdateModuleNameVec(caller_pc, range_beg, range_end);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000360}
361
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000362static const uptr kBundleCounterBits = 16;
363
364// When coverage_order_pcs==true and SANITIZER_WORDSIZE==64
365// we insert the global counter into the first 16 bits of the PC.
366uptr BundlePcAndCounter(uptr pc, uptr counter) {
367 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
368 return pc;
369 static const uptr kMaxCounter = (1 << kBundleCounterBits) - 1;
370 if (counter > kMaxCounter)
371 counter = kMaxCounter;
372 CHECK_EQ(0, pc >> (SANITIZER_WORDSIZE - kBundleCounterBits));
373 return pc | (counter << (SANITIZER_WORDSIZE - kBundleCounterBits));
374}
375
376uptr UnbundlePc(uptr bundle) {
377 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
378 return bundle;
379 return (bundle << kBundleCounterBits) >> kBundleCounterBits;
380}
381
382uptr UnbundleCounter(uptr bundle) {
383 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
384 return 0;
385 return bundle >> (SANITIZER_WORDSIZE - kBundleCounterBits);
386}
387
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000388// If guard is negative, atomically set it to -guard and store the PC in
389// pc_array.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000390void CoverageData::Add(uptr pc, u32 *guard) {
391 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
392 s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
393 if (guard_value >= 0) return;
394
395 atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000396 if (!pc_array) return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000397
398 uptr idx = -guard_value - 1;
399 if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
400 return; // May happen after fork when pc_array_index becomes 0.
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000401 CHECK_LT(idx * sizeof(uptr),
402 atomic_load(&pc_array_size, memory_order_acquire));
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000403 uptr counter = atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
404 pc_array[idx] = BundlePcAndCounter(pc, counter);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000405}
406
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000407// Registers a pair caller=>callee.
408// When a given caller is seen for the first time, the callee_cache is added
409// to the global array cc_array, callee_cache[0] is set to caller and
410// callee_cache[1] is set to cache_size.
411// Then we are trying to add callee to callee_cache [2,cache_size) if it is
412// not there yet.
413// If the cache is full we drop the callee (may want to fix this later).
414void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
415 uptr cache_size) {
416 if (!cc_array) return;
417 atomic_uintptr_t *atomic_callee_cache =
418 reinterpret_cast<atomic_uintptr_t *>(callee_cache);
419 uptr zero = 0;
420 if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
421 memory_order_seq_cst)) {
422 uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
423 CHECK_LT(idx * sizeof(uptr),
424 atomic_load(&cc_array_size, memory_order_acquire));
425 callee_cache[1] = cache_size;
426 cc_array[idx] = callee_cache;
427 }
428 CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
429 for (uptr i = 2; i < cache_size; i++) {
430 uptr was = 0;
431 if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000432 memory_order_seq_cst)) {
433 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000434 return;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000435 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000436 if (was == callee) // Already have this callee.
437 return;
438 }
439}
440
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000441uptr CoverageData::GetNumberOf8bitCounters() {
442 return num_8bit_counters;
443}
444
445// Map every 8bit counter to a 8-bit bitset and clear the counter.
446uptr CoverageData::Update8bitCounterBitsetAndClearCounters(u8 *bitset) {
447 uptr num_new_bits = 0;
448 uptr cur = 0;
449 // For better speed we map 8 counters to 8 bytes of bitset at once.
450 static const uptr kBatchSize = 8;
451 CHECK_EQ(reinterpret_cast<uptr>(bitset) % kBatchSize, 0);
452 for (uptr i = 0, len = counters_vec.size(); i < len; i++) {
453 u8 *c = counters_vec[i].counters;
454 uptr n = counters_vec[i].n;
455 CHECK_EQ(n % 16, 0);
456 CHECK_EQ(cur % kBatchSize, 0);
457 CHECK_EQ(reinterpret_cast<uptr>(c) % kBatchSize, 0);
458 if (!bitset) {
459 internal_bzero_aligned16(c, n);
460 cur += n;
461 continue;
462 }
463 for (uptr j = 0; j < n; j += kBatchSize, cur += kBatchSize) {
464 CHECK_LT(cur, num_8bit_counters);
465 u64 *pc64 = reinterpret_cast<u64*>(c + j);
466 u64 *pb64 = reinterpret_cast<u64*>(bitset + cur);
467 u64 c64 = *pc64;
468 u64 old_bits_64 = *pb64;
469 u64 new_bits_64 = old_bits_64;
470 if (c64) {
471 *pc64 = 0;
472 for (uptr k = 0; k < kBatchSize; k++) {
473 u64 x = (c64 >> (8 * k)) & 0xff;
474 if (x) {
475 u64 bit = 0;
476 /**/ if (x >= 128) bit = 128;
477 else if (x >= 32) bit = 64;
478 else if (x >= 16) bit = 32;
479 else if (x >= 8) bit = 16;
480 else if (x >= 4) bit = 8;
481 else if (x >= 3) bit = 4;
482 else if (x >= 2) bit = 2;
483 else if (x >= 1) bit = 1;
484 u64 mask = bit << (8 * k);
485 if (!(new_bits_64 & mask)) {
486 num_new_bits++;
487 new_bits_64 |= mask;
488 }
489 }
490 }
491 *pb64 = new_bits_64;
492 }
493 }
494 }
495 CHECK_EQ(cur, num_8bit_counters);
496 return num_new_bits;
497}
498
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000499uptr *CoverageData::data() {
500 return pc_array;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000501}
502
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000503uptr CoverageData::size() {
504 return atomic_load(&pc_array_index, memory_order_relaxed);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000505}
506
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000507// Block layout for packed file format: header, followed by module name (no
508// trailing zero), followed by data blob.
509struct CovHeader {
510 int pid;
511 unsigned int module_name_length;
512 unsigned int data_length;
513};
514
515static void CovWritePacked(int pid, const char *module, const void *blob,
516 unsigned int blob_size) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000517 if (cov_fd < 0) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000518 unsigned module_name_length = internal_strlen(module);
519 CovHeader header = {pid, module_name_length, blob_size};
520
521 if (cov_max_block_size == 0) {
522 // Writing to a file. Just go ahead.
523 internal_write(cov_fd, &header, sizeof(header));
524 internal_write(cov_fd, module, module_name_length);
525 internal_write(cov_fd, blob, blob_size);
526 } else {
527 // Writing to a socket. We want to split the data into appropriately sized
528 // blocks.
529 InternalScopedBuffer<char> block(cov_max_block_size);
530 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
531 uptr header_size_with_module = sizeof(header) + module_name_length;
532 CHECK_LT(header_size_with_module, cov_max_block_size);
533 unsigned int max_payload_size =
534 cov_max_block_size - header_size_with_module;
535 char *block_pos = block.data();
536 internal_memcpy(block_pos, &header, sizeof(header));
537 block_pos += sizeof(header);
538 internal_memcpy(block_pos, module, module_name_length);
539 block_pos += module_name_length;
540 char *block_data_begin = block_pos;
Alexey Samsonov4925fd42014-11-13 22:40:59 +0000541 const char *blob_pos = (const char *)blob;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000542 while (blob_size > 0) {
543 unsigned int payload_size = Min(blob_size, max_payload_size);
544 blob_size -= payload_size;
545 internal_memcpy(block_data_begin, blob_pos, payload_size);
546 blob_pos += payload_size;
547 ((CovHeader *)block.data())->data_length = payload_size;
548 internal_write(cov_fd, block.data(),
549 header_size_with_module + payload_size);
550 }
551 }
552}
553
Sergey Matveev83f91e72014-05-21 13:43:52 +0000554// If packed = false: <name>.<pid>.<sancov> (name = module name).
555// If packed = true and name == 0: <pid>.<sancov>.<packed>.
556// If packed = true and name != 0: <name>.<sancov>.<packed> (name is
557// user-supplied).
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000558static int CovOpenFile(InternalScopedString *path, bool packed,
559 const char *name, const char *extension = "sancov") {
560 path->clear();
Sergey Matveev83f91e72014-05-21 13:43:52 +0000561 if (!packed) {
562 CHECK(name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000563 path->append("%s/%s.%zd.%s", coverage_dir, name, internal_getpid(),
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000564 extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000565 } else {
566 if (!name)
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000567 path->append("%s/%zd.%s.packed", coverage_dir, internal_getpid(),
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000568 extension);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000569 else
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000570 path->append("%s/%s.%s.packed", coverage_dir, name, extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000571 }
Alexander Potapenko141e4202015-03-23 10:10:46 +0000572 uptr fd = OpenFile(path->data(), WrOnly);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000573 if (internal_iserror(fd)) {
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000574 Report(" SanitizerCoverage: failed to open %s for writing\n", path->data());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000575 return -1;
576 }
577 return fd;
578}
579
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000580// Dump trace PCs and trace events into two separate files.
581void CoverageData::DumpTrace() {
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000582 uptr max_idx = tr_event_pointer - tr_event_array;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000583 if (!max_idx) return;
584 auto sym = Symbolizer::GetOrInit();
585 if (!sym)
586 return;
587 InternalScopedString out(32 << 20);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000588 for (uptr i = 0, n = size(); i < n; i++) {
589 const char *module_name = "<unknown>";
590 uptr module_address = 0;
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000591 sym->GetModuleNameAndOffsetForPC(UnbundlePc(pc_array[i]), &module_name,
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000592 &module_address);
593 out.append("%s 0x%zx\n", module_name, module_address);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000594 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000595 InternalScopedString path(kMaxPathLength);
596 int fd = CovOpenFile(&path, false, "trace-points");
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000597 if (fd < 0) return;
598 internal_write(fd, out.data(), out.length());
599 internal_close(fd);
600
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000601 fd = CovOpenFile(&path, false, "trace-compunits");
Kostya Serebryany88599462015-02-20 00:30:44 +0000602 if (fd < 0) return;
603 out.clear();
604 for (uptr i = 0; i < comp_unit_name_vec.size(); i++)
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000605 out.append("%s\n", comp_unit_name_vec[i].name);
Kostya Serebryany88599462015-02-20 00:30:44 +0000606 internal_write(fd, out.data(), out.length());
607 internal_close(fd);
608
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000609 fd = CovOpenFile(&path, false, "trace-events");
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000610 if (fd < 0) return;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000611 uptr bytes_to_write = max_idx * sizeof(tr_event_array[0]);
612 u8 *event_bytes = reinterpret_cast<u8*>(tr_event_array);
613 // The trace file could be huge, and may not be written with a single syscall.
614 while (bytes_to_write) {
615 uptr actually_written = internal_write(fd, event_bytes, bytes_to_write);
616 if (actually_written <= bytes_to_write) {
617 bytes_to_write -= actually_written;
618 event_bytes += actually_written;
619 } else {
620 break;
621 }
622 }
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000623 internal_close(fd);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000624 VReport(1, " CovDump: Trace: %zd PCs written\n", size());
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000625 VReport(1, " CovDump: Trace: %zd Events written\n", max_idx);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000626}
627
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000628// This function dumps the caller=>callee pairs into a file as a sequence of
629// lines like "module_name offset".
630void CoverageData::DumpCallerCalleePairs() {
631 uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
632 if (!max_idx) return;
633 auto sym = Symbolizer::GetOrInit();
634 if (!sym)
635 return;
Kostya Serebryany40aa4a22014-10-31 19:49:46 +0000636 InternalScopedString out(32 << 20);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000637 uptr total = 0;
638 for (uptr i = 0; i < max_idx; i++) {
639 uptr *cc_cache = cc_array[i];
640 CHECK(cc_cache);
641 uptr caller = cc_cache[0];
642 uptr n_callees = cc_cache[1];
643 const char *caller_module_name = "<unknown>";
644 uptr caller_module_address = 0;
645 sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
646 &caller_module_address);
647 for (uptr j = 2; j < n_callees; j++) {
648 uptr callee = cc_cache[j];
649 if (!callee) break;
650 total++;
651 const char *callee_module_name = "<unknown>";
652 uptr callee_module_address = 0;
653 sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
654 &callee_module_address);
655 out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
656 caller_module_address, callee_module_name,
657 callee_module_address);
658 }
659 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000660 InternalScopedString path(kMaxPathLength);
661 int fd = CovOpenFile(&path, false, "caller-callee");
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000662 if (fd < 0) return;
663 internal_write(fd, out.data(), out.length());
664 internal_close(fd);
665 VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
666}
667
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000668// Record the current PC into the event buffer.
669// Every event is a u32 value (index in tr_pc_array_index) so we compute
670// it once and then cache in the provided 'cache' storage.
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000671//
672// This function will eventually be inlined by the compiler.
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000673void CoverageData::TraceBasicBlock(s32 *id) {
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000674 // Will trap here if
675 // 1. coverage is not enabled at run-time.
676 // 2. The array tr_event_array is full.
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000677 *tr_event_pointer = static_cast<u32>(*id - 1);
678 tr_event_pointer++;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000679}
680
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000681void CoverageData::DumpCounters() {
682 if (!common_flags()->coverage_counters) return;
683 uptr n = coverage_data.GetNumberOf8bitCounters();
684 if (!n) return;
685 InternalScopedBuffer<u8> bitset(n);
686 coverage_data.Update8bitCounterBitsetAndClearCounters(bitset.data());
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000687 InternalScopedString path(kMaxPathLength);
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000688
689 for (uptr m = 0; m < module_name_vec.size(); m++) {
690 auto r = module_name_vec[m];
691 CHECK(r.name);
692 CHECK_LE(r.beg, r.end);
693 CHECK_LE(r.end, size());
694 const char *base_name = StripModuleName(r.name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000695 int fd =
696 CovOpenFile(&path, /* packed */ false, base_name, "counters-sancov");
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000697 if (fd < 0) return;
698 internal_write(fd, bitset.data() + r.beg, r.end - r.beg);
699 internal_close(fd);
700 VReport(1, " CovDump: %zd counters written for '%s'\n", r.end - r.beg,
701 base_name);
702 }
703}
704
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000705void CoverageData::DumpAsBitSet() {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000706 if (!common_flags()->coverage_bitset) return;
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000707 if (!size()) return;
708 InternalScopedBuffer<char> out(size());
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000709 InternalScopedString path(kMaxPathLength);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000710 for (uptr m = 0; m < module_name_vec.size(); m++) {
711 uptr n_set_bits = 0;
712 auto r = module_name_vec[m];
713 CHECK(r.name);
714 CHECK_LE(r.beg, r.end);
715 CHECK_LE(r.end, size());
716 for (uptr i = r.beg; i < r.end; i++) {
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000717 uptr pc = UnbundlePc(pc_array[i]);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000718 out[i] = pc ? '1' : '0';
719 if (pc)
720 n_set_bits++;
721 }
722 const char *base_name = StripModuleName(r.name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000723 int fd = CovOpenFile(&path, /* packed */ false, base_name, "bitset-sancov");
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000724 if (fd < 0) return;
725 internal_write(fd, out.data() + r.beg, r.end - r.beg);
726 internal_close(fd);
727 VReport(1,
728 " CovDump: bitset of %zd bits written for '%s', %zd bits are set\n",
729 r.end - r.beg, base_name, n_set_bits);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000730 }
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000731}
732
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000733void CoverageData::DumpOffsets() {
734 auto sym = Symbolizer::GetOrInit();
Kostya Serebryanya7ee2732014-12-30 19:55:04 +0000735 if (!common_flags()->coverage_pcs) return;
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000736 CHECK_NE(sym, nullptr);
Kostya Serebryany9f1243e2015-03-17 22:09:19 +0000737 InternalMmapVector<uptr> offsets(0);
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000738 InternalScopedString path(kMaxPathLength);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000739 for (uptr m = 0; m < module_name_vec.size(); m++) {
740 offsets.clear();
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000741 uptr num_words_for_magic = SANITIZER_WORDSIZE == 64 ? 1 : 2;
742 for (uptr i = 0; i < num_words_for_magic; i++)
743 offsets.push_back(0);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000744 auto r = module_name_vec[m];
745 CHECK(r.name);
746 CHECK_LE(r.beg, r.end);
747 CHECK_LE(r.end, size());
748 const char *module_name = "<unknown>";
749 for (uptr i = r.beg; i < r.end; i++) {
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000750 uptr pc = UnbundlePc(pc_array[i]);
751 uptr counter = UnbundleCounter(pc_array[i]);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000752 if (!pc) continue; // Not visited.
753 uptr offset = 0;
754 sym->GetModuleNameAndOffsetForPC(pc, &module_name, &offset);
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000755 offsets.push_back(BundlePcAndCounter(offset, counter));
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000756 }
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000757
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000758 CHECK_GE(offsets.size(), num_words_for_magic);
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000759 SortArray(offsets.data(), offsets.size());
760 for (uptr i = 0; i < offsets.size(); i++)
761 offsets[i] = UnbundlePc(offsets[i]);
762
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000763 uptr num_offsets = offsets.size() - num_words_for_magic;
764 u64 *magic_p = reinterpret_cast<u64*>(offsets.data());
765 CHECK_EQ(*magic_p, 0ULL);
766 // FIXME: we may want to write 32-bit offsets even in 64-mode
767 // if all the offsets are small enough.
768 *magic_p = SANITIZER_WORDSIZE == 64 ? kMagic64 : kMagic32;
769
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000770 module_name = StripModuleName(r.name);
771 if (cov_sandboxed) {
772 if (cov_fd >= 0) {
773 CovWritePacked(internal_getpid(), module_name, offsets.data(),
Kostya Serebryany9f1243e2015-03-17 22:09:19 +0000774 offsets.size() * sizeof(offsets[0]));
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000775 VReport(1, " CovDump: %zd PCs written to packed file\n", num_offsets);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000776 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000777 } else {
778 // One file per module per process.
779 int fd = CovOpenFile(&path, false /* packed */, module_name);
780 if (fd < 0) continue;
Kostya Serebryany9f1243e2015-03-17 22:09:19 +0000781 internal_write(fd, offsets.data(), offsets.size() * sizeof(offsets[0]));
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000782 internal_close(fd);
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000783 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(), num_offsets);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000784 }
785 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000786 if (cov_fd >= 0)
787 internal_close(cov_fd);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000788}
789
790void CoverageData::DumpAll() {
791 if (!coverage_enabled || common_flags()->coverage_direct) return;
792 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
793 return;
794 DumpAsBitSet();
795 DumpCounters();
796 DumpTrace();
797 DumpOffsets();
798 DumpCallerCalleePairs();
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000799}
800
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000801void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
802 if (!args) return;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000803 if (!coverage_enabled) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000804 cov_sandboxed = args->coverage_sandboxed;
805 if (!cov_sandboxed) return;
806 cov_fd = args->coverage_fd;
807 cov_max_block_size = args->coverage_max_block_size;
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000808 if (cov_fd < 0) {
809 InternalScopedString path(kMaxPathLength);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000810 // Pre-open the file now. The sandbox won't allow us to do it later.
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000811 cov_fd = CovOpenFile(&path, true /* packed */, 0);
812 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000813}
814
Sergey Matveev83f91e72014-05-21 13:43:52 +0000815int MaybeOpenCovFile(const char *name) {
816 CHECK(name);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000817 if (!coverage_enabled) return -1;
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000818 InternalScopedString path(kMaxPathLength);
819 return CovOpenFile(&path, true /* packed */, name);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000820}
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000821
822void CovBeforeFork() {
823 coverage_data.BeforeFork();
824}
825
826void CovAfterFork(int child_pid) {
827 coverage_data.AfterFork(child_pid);
828}
829
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000830void InitializeCoverage(bool enabled, const char *dir) {
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000831 if (coverage_enabled)
832 return; // May happen if two sanitizer enable coverage in the same process.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000833 coverage_enabled = enabled;
834 coverage_dir = dir;
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000835 coverage_data.Init();
836 if (enabled) coverage_data.Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000837#if !SANITIZER_WINDOWS
838 if (!common_flags()->coverage_direct) Atexit(__sanitizer_cov_dump);
839#endif
840}
841
842void ReInitializeCoverage(bool enabled, const char *dir) {
843 coverage_enabled = enabled;
844 coverage_dir = dir;
845 coverage_data.ReInit();
846}
847
848void CoverageUpdateMapping() {
849 if (coverage_enabled)
850 CovUpdateMapping(coverage_dir);
851}
852
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000853} // namespace __sanitizer
854
855extern "C" {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000856SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000857 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
858 guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000859}
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000860SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_with_check(u32 *guard) {
861 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000862 if (static_cast<s32>(
863 __sanitizer::atomic_load(atomic_guard, memory_order_relaxed)) < 0)
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000864 __sanitizer_cov(guard);
865}
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000866SANITIZER_INTERFACE_ATTRIBUTE void
867__sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
868 coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
869 callee, callee_cache16, 16);
870}
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000871SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000872 coverage_enabled = true;
873 coverage_dir = common_flags()->coverage_dir;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000874 coverage_data.Init();
875}
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000876SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() {
877 coverage_data.DumpAll();
878}
Kostya Serebryany88599462015-02-20 00:30:44 +0000879SANITIZER_INTERFACE_ATTRIBUTE void
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000880__sanitizer_cov_module_init(s32 *guards, uptr npcs, u8 *counters,
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000881 const char *comp_unit_name) {
882 coverage_data.InitializeGuards(guards, npcs, comp_unit_name, GET_CALLER_PC());
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000883 coverage_data.InitializeCounters(counters, npcs);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000884 if (!common_flags()->coverage_direct) return;
885 if (SANITIZER_ANDROID && coverage_enabled) {
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000886 // dlopen/dlclose interceptors do not work on Android, so we rely on
887 // Extend() calls to update .sancov.map.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000888 CovUpdateMapping(coverage_dir, GET_CALLER_PC());
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000889 }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000890 coverage_data.Extend(npcs);
891}
Sergey Matveev83f91e72014-05-21 13:43:52 +0000892SANITIZER_INTERFACE_ATTRIBUTE
893sptr __sanitizer_maybe_open_cov_file(const char *name) {
894 return MaybeOpenCovFile(name);
895}
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000896SANITIZER_INTERFACE_ATTRIBUTE
897uptr __sanitizer_get_total_unique_coverage() {
898 return atomic_load(&coverage_counter, memory_order_relaxed);
899}
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000900
901SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000902void __sanitizer_cov_trace_func_enter(s32 *id) {
903 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000904}
905SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000906void __sanitizer_cov_trace_basic_block(s32 *id) {
907 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000908}
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000909SANITIZER_INTERFACE_ATTRIBUTE
910void __sanitizer_reset_coverage() {
911 coverage_data.ReinitializeGuards();
912 internal_bzero_aligned16(
913 coverage_data.data(),
914 RoundUpTo(coverage_data.size() * sizeof(coverage_data.data()[0]), 16));
915}
916SANITIZER_INTERFACE_ATTRIBUTE
917uptr __sanitizer_get_coverage_guards(uptr **data) {
918 *data = coverage_data.data();
919 return coverage_data.size();
920}
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000921
922SANITIZER_INTERFACE_ATTRIBUTE
923uptr __sanitizer_get_number_of_counters() {
924 return coverage_data.GetNumberOf8bitCounters();
925}
926
927SANITIZER_INTERFACE_ATTRIBUTE
928uptr __sanitizer_update_counter_bitset_and_clear_counters(u8 *bitset) {
929 return coverage_data.Update8bitCounterBitsetAndClearCounters(bitset);
930}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000931} // extern "C"