blob: 30c07d994a09963fdbfe66ed988f188f8800a623 [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;
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +000066static fd_t cov_fd = kInvalidFd;
Sergey Matveev6cb47a082014-05-19 12:53:03 +000067static 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);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +000098 void InitializeCounters(u8 *counters, uptr n);
Kostya Serebryany21a1a232015-01-28 22:39:44 +000099 void ReinitializeGuards();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000100 uptr GetNumberOf8bitCounters();
101 uptr Update8bitCounterBitsetAndClearCounters(u8 *bitset);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000102
103 uptr *data();
104 uptr size();
105
106 private:
Timur Iskhodzhanov3e8d3922015-03-25 20:19:51 +0000107 void DirectOpen();
108 void UpdateModuleNameVec(uptr caller_pc, uptr range_beg, uptr range_end);
109
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000110 // Maximal size pc array may ever grow.
111 // We MmapNoReserve this space to ensure that the array is contiguous.
Timur Iskhodzhanovaac51932015-04-24 21:24:51 +0000112 static const uptr kPcArrayMaxSize = FIRST_32_SECOND_64(
113 1 << (SANITIZER_ANDROID ? 24 : (SANITIZER_WINDOWS ? 27 : 26)),
114 1 << 27);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000115 // The amount file mapping for the pc array is grown by.
116 static const uptr kPcArrayMmapSize = 64 * 1024;
117
118 // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
119 // much RAM as it really needs.
120 uptr *pc_array;
121 // Index of the first available pc_array slot.
122 atomic_uintptr_t pc_array_index;
123 // Array size.
124 atomic_uintptr_t pc_array_size;
125 // Current file mapped size of the pc array.
126 uptr pc_array_mapped_size;
127 // Descriptor of the file mapped pc array.
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000128 fd_t pc_fd;
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000129
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000130 // Vector of coverage guard arrays, protected by mu.
131 InternalMmapVectorNoCtor<s32*> guard_array_vec;
132
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000133 struct NamedPcRange {
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000134 const char *copied_module_name;
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000135 uptr beg, end; // elements [beg,end) in pc_array.
136 };
137
138 // Vector of module and compilation unit pc ranges.
139 InternalMmapVectorNoCtor<NamedPcRange> comp_unit_name_vec;
140 InternalMmapVectorNoCtor<NamedPcRange> module_name_vec;
Kostya Serebryany88599462015-02-20 00:30:44 +0000141
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000142 struct CounterAndSize {
143 u8 *counters;
144 uptr n;
145 };
146
147 InternalMmapVectorNoCtor<CounterAndSize> counters_vec;
148 uptr num_8bit_counters;
149
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000150 // Caller-Callee (cc) array, size and current index.
151 static const uptr kCcArrayMaxSize = FIRST_32_SECOND_64(1 << 18, 1 << 24);
152 uptr **cc_array;
153 atomic_uintptr_t cc_array_index;
154 atomic_uintptr_t cc_array_size;
155
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000156 // Tracing event array, size and current pointer.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000157 // We record all events (basic block entries) in a global buffer of u32
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000158 // values. Each such value is the index in pc_array.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000159 // So far the tracing is highly experimental:
160 // - not thread-safe;
161 // - does not support long traces;
162 // - not tuned for performance.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000163 static const uptr kTrEventArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 30);
164 u32 *tr_event_array;
165 uptr tr_event_array_size;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000166 u32 *tr_event_pointer;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000167 static const uptr kTrPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000168
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000169 StaticSpinMutex mu;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000170};
171
172static CoverageData coverage_data;
173
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000174void CovUpdateMapping(const char *path, uptr caller_pc = 0);
175
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000176void CoverageData::DirectOpen() {
Alexey Samsonov4cc76cb2014-11-26 01:48:39 +0000177 InternalScopedString path(kMaxPathLength);
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000178 internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000179 coverage_dir, internal_getpid());
Alexander Potapenko141e4202015-03-23 10:10:46 +0000180 pc_fd = OpenFile(path.data(), RdWr);
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000181 if (pc_fd == kInvalidFd) {
Alexey Samsonovc4ed5482015-03-31 18:16:42 +0000182 Report("Coverage: failed to open %s for reading/writing\n", path.data());
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000183 Die();
184 }
185
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000186 pc_array_mapped_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000187 CovUpdateMapping(coverage_dir);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000188}
189
190void CoverageData::Init() {
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000191 pc_fd = kInvalidFd;
192}
193
194void CoverageData::Enable() {
Viktor Kutuzov7891c8c2015-02-02 09:38:10 +0000195 if (pc_array)
196 return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000197 pc_array = reinterpret_cast<uptr *>(
198 MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000199 atomic_store(&pc_array_index, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000200 if (common_flags()->coverage_direct) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000201 atomic_store(&pc_array_size, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000202 } else {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000203 atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
204 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000205
206 cc_array = reinterpret_cast<uptr **>(MmapNoReserveOrDie(
207 sizeof(uptr *) * kCcArrayMaxSize, "CovInit::cc_array"));
208 atomic_store(&cc_array_size, kCcArrayMaxSize, memory_order_relaxed);
209 atomic_store(&cc_array_index, 0, memory_order_relaxed);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000210
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000211 // Allocate tr_event_array with a guard page at the end.
212 tr_event_array = reinterpret_cast<u32 *>(MmapNoReserveOrDie(
213 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize + GetMmapGranularity(),
214 "CovInit::tr_event_array"));
Timur Iskhodzhanovea1f3322015-04-10 15:02:19 +0000215 MprotectNoAccess(
216 reinterpret_cast<uptr>(&tr_event_array[kTrEventArrayMaxSize]),
217 GetMmapGranularity());
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000218 tr_event_array_size = kTrEventArrayMaxSize;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000219 tr_event_pointer = tr_event_array;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000220
221 num_8bit_counters = 0;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000222}
223
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000224void CoverageData::InitializeGuardArray(s32 *guards) {
Viktor Kutuzov7891c8c2015-02-02 09:38:10 +0000225 Enable(); // Make sure coverage is enabled at this point.
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000226 s32 n = guards[0];
227 for (s32 j = 1; j <= n; j++) {
228 uptr idx = atomic_fetch_add(&pc_array_index, 1, memory_order_relaxed);
229 guards[j] = -static_cast<s32>(idx + 1);
230 }
231}
232
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000233void CoverageData::Disable() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000234 if (pc_array) {
Timur Iskhodzhanov37453032015-04-08 17:08:24 +0000235 UnmapOrDie(pc_array, sizeof(uptr) * kPcArrayMaxSize);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000236 pc_array = nullptr;
237 }
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000238 if (cc_array) {
Timur Iskhodzhanov37453032015-04-08 17:08:24 +0000239 UnmapOrDie(cc_array, sizeof(uptr *) * kCcArrayMaxSize);
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000240 cc_array = nullptr;
241 }
242 if (tr_event_array) {
Timur Iskhodzhanov37453032015-04-08 17:08:24 +0000243 UnmapOrDie(tr_event_array,
244 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize +
245 GetMmapGranularity());
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000246 tr_event_array = nullptr;
247 tr_event_pointer = nullptr;
248 }
249 if (pc_fd != kInvalidFd) {
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000250 CloseFile(pc_fd);
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000251 pc_fd = kInvalidFd;
252 }
253}
254
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000255void CoverageData::ReinitializeGuards() {
256 // Assuming single thread.
257 atomic_store(&pc_array_index, 0, memory_order_relaxed);
258 for (uptr i = 0; i < guard_array_vec.size(); i++)
259 InitializeGuardArray(guard_array_vec[i]);
260}
261
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000262void CoverageData::ReInit() {
263 Disable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000264 if (coverage_enabled) {
265 if (common_flags()->coverage_direct) {
266 // In memory-mapped mode we must extend the new file to the known array
267 // size.
268 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
Evgeniy Stepanovb0707832015-05-01 00:40:42 +0000269 uptr npcs = size / sizeof(uptr);
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000270 Enable();
Evgeniy Stepanovb0707832015-05-01 00:40:42 +0000271 if (size) Extend(npcs);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000272 if (coverage_enabled) CovUpdateMapping(coverage_dir);
273 } else {
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000274 Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000275 }
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000276 }
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000277 // Re-initialize the guards.
278 // We are single-threaded now, no need to grab any lock.
279 CHECK_EQ(atomic_load(&pc_array_index, memory_order_relaxed), 0);
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000280 ReinitializeGuards();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000281}
282
283void CoverageData::BeforeFork() {
284 mu.Lock();
285}
286
287void CoverageData::AfterFork(int child_pid) {
288 // We are single-threaded so it's OK to release the lock early.
289 mu.Unlock();
290 if (child_pid == 0) ReInit();
291}
292
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000293// Extend coverage PC array to fit additional npcs elements.
294void CoverageData::Extend(uptr npcs) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000295 if (!common_flags()->coverage_direct) return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000296 SpinMutexLock l(&mu);
297
298 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
299 size += npcs * sizeof(uptr);
300
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000301 if (coverage_enabled && size > pc_array_mapped_size) {
302 if (pc_fd == kInvalidFd) DirectOpen();
303 CHECK_NE(pc_fd, kInvalidFd);
304
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000305 uptr new_mapped_size = pc_array_mapped_size;
306 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000307 CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000308
309 // Extend the file and map the new space at the end of pc_array.
310 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
311 int err;
312 if (internal_iserror(res, &err)) {
313 Printf("failed to extend raw coverage file: %d\n", err);
314 Die();
315 }
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000316
317 uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
318 void *p = MapWritableFileToMemory((void *)next_map_base,
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000319 new_mapped_size - pc_array_mapped_size,
320 pc_fd, pc_array_mapped_size);
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000321 CHECK_EQ((uptr)p, next_map_base);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000322 pc_array_mapped_size = new_mapped_size;
323 }
324
325 atomic_store(&pc_array_size, size, memory_order_release);
326}
327
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000328void CoverageData::InitializeCounters(u8 *counters, uptr n) {
329 if (!counters) return;
330 CHECK_EQ(reinterpret_cast<uptr>(counters) % 16, 0);
331 n = RoundUpTo(n, 16); // The compiler must ensure that counters is 16-aligned.
332 SpinMutexLock l(&mu);
333 counters_vec.push_back({counters, n});
334 num_8bit_counters += n;
335}
336
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000337void CoverageData::UpdateModuleNameVec(uptr caller_pc, uptr range_beg,
338 uptr range_end) {
339 auto sym = Symbolizer::GetOrInit();
340 if (!sym)
341 return;
342 const char *module_name = sym->GetModuleNameForPc(caller_pc);
343 if (!module_name) return;
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000344 if (module_name_vec.empty() ||
Timur Iskhodzhanov6c66ad02015-03-31 12:50:05 +0000345 module_name_vec.back().copied_module_name != module_name)
346 module_name_vec.push_back({module_name, range_beg, range_end});
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000347 else
348 module_name_vec.back().end = range_end;
349}
350
Kostya Serebryany88599462015-02-20 00:30:44 +0000351void CoverageData::InitializeGuards(s32 *guards, uptr n,
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000352 const char *comp_unit_name,
353 uptr caller_pc) {
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000354 // The array 'guards' has n+1 elements, we use the element zero
355 // to store 'n'.
356 CHECK_LT(n, 1 << 30);
357 guards[0] = static_cast<s32>(n);
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000358 InitializeGuardArray(guards);
359 SpinMutexLock l(&mu);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000360 uptr range_end = atomic_load(&pc_array_index, memory_order_relaxed);
361 uptr range_beg = range_end - n;
362 comp_unit_name_vec.push_back({comp_unit_name, range_beg, range_end});
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000363 guard_array_vec.push_back(guards);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000364 UpdateModuleNameVec(caller_pc, range_beg, range_end);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000365}
366
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000367static const uptr kBundleCounterBits = 16;
368
369// When coverage_order_pcs==true and SANITIZER_WORDSIZE==64
370// we insert the global counter into the first 16 bits of the PC.
371uptr BundlePcAndCounter(uptr pc, uptr counter) {
372 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
373 return pc;
374 static const uptr kMaxCounter = (1 << kBundleCounterBits) - 1;
375 if (counter > kMaxCounter)
376 counter = kMaxCounter;
377 CHECK_EQ(0, pc >> (SANITIZER_WORDSIZE - kBundleCounterBits));
378 return pc | (counter << (SANITIZER_WORDSIZE - kBundleCounterBits));
379}
380
381uptr UnbundlePc(uptr bundle) {
382 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
383 return bundle;
384 return (bundle << kBundleCounterBits) >> kBundleCounterBits;
385}
386
387uptr UnbundleCounter(uptr bundle) {
388 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
389 return 0;
390 return bundle >> (SANITIZER_WORDSIZE - kBundleCounterBits);
391}
392
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000393// If guard is negative, atomically set it to -guard and store the PC in
394// pc_array.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000395void CoverageData::Add(uptr pc, u32 *guard) {
396 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
397 s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
398 if (guard_value >= 0) return;
399
400 atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000401 if (!pc_array) return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000402
403 uptr idx = -guard_value - 1;
404 if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
405 return; // May happen after fork when pc_array_index becomes 0.
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000406 CHECK_LT(idx * sizeof(uptr),
407 atomic_load(&pc_array_size, memory_order_acquire));
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000408 uptr counter = atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
409 pc_array[idx] = BundlePcAndCounter(pc, counter);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000410}
411
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000412// Registers a pair caller=>callee.
413// When a given caller is seen for the first time, the callee_cache is added
414// to the global array cc_array, callee_cache[0] is set to caller and
415// callee_cache[1] is set to cache_size.
416// Then we are trying to add callee to callee_cache [2,cache_size) if it is
417// not there yet.
418// If the cache is full we drop the callee (may want to fix this later).
419void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
420 uptr cache_size) {
421 if (!cc_array) return;
422 atomic_uintptr_t *atomic_callee_cache =
423 reinterpret_cast<atomic_uintptr_t *>(callee_cache);
424 uptr zero = 0;
425 if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
426 memory_order_seq_cst)) {
427 uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
428 CHECK_LT(idx * sizeof(uptr),
429 atomic_load(&cc_array_size, memory_order_acquire));
430 callee_cache[1] = cache_size;
431 cc_array[idx] = callee_cache;
432 }
433 CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
434 for (uptr i = 2; i < cache_size; i++) {
435 uptr was = 0;
436 if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000437 memory_order_seq_cst)) {
438 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000439 return;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000440 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000441 if (was == callee) // Already have this callee.
442 return;
443 }
444}
445
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000446uptr CoverageData::GetNumberOf8bitCounters() {
447 return num_8bit_counters;
448}
449
450// Map every 8bit counter to a 8-bit bitset and clear the counter.
451uptr CoverageData::Update8bitCounterBitsetAndClearCounters(u8 *bitset) {
452 uptr num_new_bits = 0;
453 uptr cur = 0;
454 // For better speed we map 8 counters to 8 bytes of bitset at once.
455 static const uptr kBatchSize = 8;
456 CHECK_EQ(reinterpret_cast<uptr>(bitset) % kBatchSize, 0);
457 for (uptr i = 0, len = counters_vec.size(); i < len; i++) {
458 u8 *c = counters_vec[i].counters;
459 uptr n = counters_vec[i].n;
460 CHECK_EQ(n % 16, 0);
461 CHECK_EQ(cur % kBatchSize, 0);
462 CHECK_EQ(reinterpret_cast<uptr>(c) % kBatchSize, 0);
463 if (!bitset) {
464 internal_bzero_aligned16(c, n);
465 cur += n;
466 continue;
467 }
468 for (uptr j = 0; j < n; j += kBatchSize, cur += kBatchSize) {
469 CHECK_LT(cur, num_8bit_counters);
470 u64 *pc64 = reinterpret_cast<u64*>(c + j);
471 u64 *pb64 = reinterpret_cast<u64*>(bitset + cur);
472 u64 c64 = *pc64;
473 u64 old_bits_64 = *pb64;
474 u64 new_bits_64 = old_bits_64;
475 if (c64) {
476 *pc64 = 0;
477 for (uptr k = 0; k < kBatchSize; k++) {
478 u64 x = (c64 >> (8 * k)) & 0xff;
479 if (x) {
480 u64 bit = 0;
481 /**/ if (x >= 128) bit = 128;
482 else if (x >= 32) bit = 64;
483 else if (x >= 16) bit = 32;
484 else if (x >= 8) bit = 16;
485 else if (x >= 4) bit = 8;
486 else if (x >= 3) bit = 4;
487 else if (x >= 2) bit = 2;
488 else if (x >= 1) bit = 1;
489 u64 mask = bit << (8 * k);
490 if (!(new_bits_64 & mask)) {
491 num_new_bits++;
492 new_bits_64 |= mask;
493 }
494 }
495 }
496 *pb64 = new_bits_64;
497 }
498 }
499 }
500 CHECK_EQ(cur, num_8bit_counters);
501 return num_new_bits;
502}
503
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000504uptr *CoverageData::data() {
505 return pc_array;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000506}
507
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000508uptr CoverageData::size() {
509 return atomic_load(&pc_array_index, memory_order_relaxed);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000510}
511
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000512// Block layout for packed file format: header, followed by module name (no
513// trailing zero), followed by data blob.
514struct CovHeader {
515 int pid;
516 unsigned int module_name_length;
517 unsigned int data_length;
518};
519
520static void CovWritePacked(int pid, const char *module, const void *blob,
521 unsigned int blob_size) {
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000522 if (cov_fd == kInvalidFd) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000523 unsigned module_name_length = internal_strlen(module);
524 CovHeader header = {pid, module_name_length, blob_size};
525
526 if (cov_max_block_size == 0) {
527 // Writing to a file. Just go ahead.
Timur Iskhodzhanove8a6fbb2015-04-09 14:11:25 +0000528 WriteToFile(cov_fd, &header, sizeof(header));
529 WriteToFile(cov_fd, module, module_name_length);
530 WriteToFile(cov_fd, blob, blob_size);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000531 } else {
532 // Writing to a socket. We want to split the data into appropriately sized
533 // blocks.
534 InternalScopedBuffer<char> block(cov_max_block_size);
535 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
536 uptr header_size_with_module = sizeof(header) + module_name_length;
537 CHECK_LT(header_size_with_module, cov_max_block_size);
538 unsigned int max_payload_size =
539 cov_max_block_size - header_size_with_module;
540 char *block_pos = block.data();
541 internal_memcpy(block_pos, &header, sizeof(header));
542 block_pos += sizeof(header);
543 internal_memcpy(block_pos, module, module_name_length);
544 block_pos += module_name_length;
545 char *block_data_begin = block_pos;
Alexey Samsonov4925fd42014-11-13 22:40:59 +0000546 const char *blob_pos = (const char *)blob;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000547 while (blob_size > 0) {
548 unsigned int payload_size = Min(blob_size, max_payload_size);
549 blob_size -= payload_size;
550 internal_memcpy(block_data_begin, blob_pos, payload_size);
551 blob_pos += payload_size;
552 ((CovHeader *)block.data())->data_length = payload_size;
Timur Iskhodzhanove8a6fbb2015-04-09 14:11:25 +0000553 WriteToFile(cov_fd, block.data(), header_size_with_module + payload_size);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000554 }
555 }
556}
557
Sergey Matveev83f91e72014-05-21 13:43:52 +0000558// If packed = false: <name>.<pid>.<sancov> (name = module name).
559// If packed = true and name == 0: <pid>.<sancov>.<packed>.
560// If packed = true and name != 0: <name>.<sancov>.<packed> (name is
561// user-supplied).
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000562static fd_t CovOpenFile(InternalScopedString *path, bool packed,
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000563 const char *name, const char *extension = "sancov") {
564 path->clear();
Sergey Matveev83f91e72014-05-21 13:43:52 +0000565 if (!packed) {
566 CHECK(name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000567 path->append("%s/%s.%zd.%s", coverage_dir, name, internal_getpid(),
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000568 extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000569 } else {
570 if (!name)
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000571 path->append("%s/%zd.%s.packed", coverage_dir, internal_getpid(),
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000572 extension);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000573 else
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000574 path->append("%s/%s.%s.packed", coverage_dir, name, extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000575 }
Timur Iskhodzhanovac990bf2015-04-23 13:18:50 +0000576 error_t err;
577 fd_t fd = OpenFile(path->data(), WrOnly, &err);
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000578 if (fd == kInvalidFd)
Timur Iskhodzhanovac990bf2015-04-23 13:18:50 +0000579 Report("SanitizerCoverage: failed to open %s for writing (reason: %d)\n",
580 path->data(), err);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000581 return fd;
582}
583
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000584// Dump trace PCs and trace events into two separate files.
585void CoverageData::DumpTrace() {
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000586 uptr max_idx = tr_event_pointer - tr_event_array;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000587 if (!max_idx) return;
588 auto sym = Symbolizer::GetOrInit();
589 if (!sym)
590 return;
591 InternalScopedString out(32 << 20);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000592 for (uptr i = 0, n = size(); i < n; i++) {
593 const char *module_name = "<unknown>";
594 uptr module_address = 0;
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000595 sym->GetModuleNameAndOffsetForPC(UnbundlePc(pc_array[i]), &module_name,
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000596 &module_address);
597 out.append("%s 0x%zx\n", module_name, module_address);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000598 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000599 InternalScopedString path(kMaxPathLength);
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000600 fd_t fd = CovOpenFile(&path, false, "trace-points");
601 if (fd == kInvalidFd) return;
Timur Iskhodzhanove8a6fbb2015-04-09 14:11:25 +0000602 WriteToFile(fd, out.data(), out.length());
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000603 CloseFile(fd);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000604
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000605 fd = CovOpenFile(&path, false, "trace-compunits");
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000606 if (fd == kInvalidFd) return;
Kostya Serebryany88599462015-02-20 00:30:44 +0000607 out.clear();
608 for (uptr i = 0; i < comp_unit_name_vec.size(); i++)
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000609 out.append("%s\n", comp_unit_name_vec[i].copied_module_name);
Timur Iskhodzhanove8a6fbb2015-04-09 14:11:25 +0000610 WriteToFile(fd, out.data(), out.length());
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000611 CloseFile(fd);
Kostya Serebryany88599462015-02-20 00:30:44 +0000612
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000613 fd = CovOpenFile(&path, false, "trace-events");
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000614 if (fd == kInvalidFd) return;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000615 uptr bytes_to_write = max_idx * sizeof(tr_event_array[0]);
616 u8 *event_bytes = reinterpret_cast<u8*>(tr_event_array);
617 // The trace file could be huge, and may not be written with a single syscall.
618 while (bytes_to_write) {
Timur Iskhodzhanove8a6fbb2015-04-09 14:11:25 +0000619 uptr actually_written;
620 if (WriteToFile(fd, event_bytes, bytes_to_write, &actually_written) &&
621 actually_written <= bytes_to_write) {
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000622 bytes_to_write -= actually_written;
623 event_bytes += actually_written;
624 } else {
625 break;
626 }
627 }
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000628 CloseFile(fd);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000629 VReport(1, " CovDump: Trace: %zd PCs written\n", size());
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000630 VReport(1, " CovDump: Trace: %zd Events written\n", max_idx);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000631}
632
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000633// This function dumps the caller=>callee pairs into a file as a sequence of
634// lines like "module_name offset".
635void CoverageData::DumpCallerCalleePairs() {
636 uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
637 if (!max_idx) return;
638 auto sym = Symbolizer::GetOrInit();
639 if (!sym)
640 return;
Kostya Serebryany40aa4a22014-10-31 19:49:46 +0000641 InternalScopedString out(32 << 20);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000642 uptr total = 0;
643 for (uptr i = 0; i < max_idx; i++) {
644 uptr *cc_cache = cc_array[i];
645 CHECK(cc_cache);
646 uptr caller = cc_cache[0];
647 uptr n_callees = cc_cache[1];
648 const char *caller_module_name = "<unknown>";
649 uptr caller_module_address = 0;
650 sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
651 &caller_module_address);
652 for (uptr j = 2; j < n_callees; j++) {
653 uptr callee = cc_cache[j];
654 if (!callee) break;
655 total++;
656 const char *callee_module_name = "<unknown>";
657 uptr callee_module_address = 0;
658 sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
659 &callee_module_address);
660 out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
661 caller_module_address, callee_module_name,
662 callee_module_address);
663 }
664 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000665 InternalScopedString path(kMaxPathLength);
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000666 fd_t fd = CovOpenFile(&path, false, "caller-callee");
667 if (fd == kInvalidFd) return;
Timur Iskhodzhanove8a6fbb2015-04-09 14:11:25 +0000668 WriteToFile(fd, out.data(), out.length());
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000669 CloseFile(fd);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000670 VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
671}
672
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000673// Record the current PC into the event buffer.
674// Every event is a u32 value (index in tr_pc_array_index) so we compute
675// it once and then cache in the provided 'cache' storage.
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000676//
677// This function will eventually be inlined by the compiler.
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000678void CoverageData::TraceBasicBlock(s32 *id) {
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000679 // Will trap here if
680 // 1. coverage is not enabled at run-time.
681 // 2. The array tr_event_array is full.
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000682 *tr_event_pointer = static_cast<u32>(*id - 1);
683 tr_event_pointer++;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000684}
685
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000686void CoverageData::DumpCounters() {
687 if (!common_flags()->coverage_counters) return;
688 uptr n = coverage_data.GetNumberOf8bitCounters();
689 if (!n) return;
690 InternalScopedBuffer<u8> bitset(n);
691 coverage_data.Update8bitCounterBitsetAndClearCounters(bitset.data());
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000692 InternalScopedString path(kMaxPathLength);
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000693
694 for (uptr m = 0; m < module_name_vec.size(); m++) {
695 auto r = module_name_vec[m];
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000696 CHECK(r.copied_module_name);
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000697 CHECK_LE(r.beg, r.end);
698 CHECK_LE(r.end, size());
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000699 const char *base_name = StripModuleName(r.copied_module_name);
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000700 fd_t fd =
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000701 CovOpenFile(&path, /* packed */ false, base_name, "counters-sancov");
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000702 if (fd == kInvalidFd) return;
Timur Iskhodzhanove8a6fbb2015-04-09 14:11:25 +0000703 WriteToFile(fd, bitset.data() + r.beg, r.end - r.beg);
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000704 CloseFile(fd);
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000705 VReport(1, " CovDump: %zd counters written for '%s'\n", r.end - r.beg,
706 base_name);
707 }
708}
709
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000710void CoverageData::DumpAsBitSet() {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000711 if (!common_flags()->coverage_bitset) return;
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000712 if (!size()) return;
713 InternalScopedBuffer<char> out(size());
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000714 InternalScopedString path(kMaxPathLength);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000715 for (uptr m = 0; m < module_name_vec.size(); m++) {
716 uptr n_set_bits = 0;
717 auto r = module_name_vec[m];
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000718 CHECK(r.copied_module_name);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000719 CHECK_LE(r.beg, r.end);
720 CHECK_LE(r.end, size());
721 for (uptr i = r.beg; i < r.end; i++) {
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000722 uptr pc = UnbundlePc(pc_array[i]);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000723 out[i] = pc ? '1' : '0';
724 if (pc)
725 n_set_bits++;
726 }
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000727 const char *base_name = StripModuleName(r.copied_module_name);
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000728 fd_t fd = CovOpenFile(&path, /* packed */false, base_name, "bitset-sancov");
729 if (fd == kInvalidFd) return;
Timur Iskhodzhanove8a6fbb2015-04-09 14:11:25 +0000730 WriteToFile(fd, out.data() + r.beg, r.end - r.beg);
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000731 CloseFile(fd);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000732 VReport(1,
733 " CovDump: bitset of %zd bits written for '%s', %zd bits are set\n",
734 r.end - r.beg, base_name, n_set_bits);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000735 }
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000736}
737
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000738void CoverageData::DumpOffsets() {
739 auto sym = Symbolizer::GetOrInit();
Kostya Serebryanya7ee2732014-12-30 19:55:04 +0000740 if (!common_flags()->coverage_pcs) return;
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000741 CHECK_NE(sym, nullptr);
Kostya Serebryany9f1243e2015-03-17 22:09:19 +0000742 InternalMmapVector<uptr> offsets(0);
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000743 InternalScopedString path(kMaxPathLength);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000744 for (uptr m = 0; m < module_name_vec.size(); m++) {
745 offsets.clear();
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000746 uptr num_words_for_magic = SANITIZER_WORDSIZE == 64 ? 1 : 2;
747 for (uptr i = 0; i < num_words_for_magic; i++)
748 offsets.push_back(0);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000749 auto r = module_name_vec[m];
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000750 CHECK(r.copied_module_name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000751 CHECK_LE(r.beg, r.end);
752 CHECK_LE(r.end, size());
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000753 for (uptr i = r.beg; i < r.end; i++) {
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000754 uptr pc = UnbundlePc(pc_array[i]);
755 uptr counter = UnbundleCounter(pc_array[i]);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000756 if (!pc) continue; // Not visited.
757 uptr offset = 0;
Timur Iskhodzhanov6c66ad02015-03-31 12:50:05 +0000758 sym->GetModuleNameAndOffsetForPC(pc, nullptr, &offset);
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000759 offsets.push_back(BundlePcAndCounter(offset, counter));
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000760 }
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000761
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000762 CHECK_GE(offsets.size(), num_words_for_magic);
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000763 SortArray(offsets.data(), offsets.size());
764 for (uptr i = 0; i < offsets.size(); i++)
765 offsets[i] = UnbundlePc(offsets[i]);
766
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000767 uptr num_offsets = offsets.size() - num_words_for_magic;
768 u64 *magic_p = reinterpret_cast<u64*>(offsets.data());
769 CHECK_EQ(*magic_p, 0ULL);
770 // FIXME: we may want to write 32-bit offsets even in 64-mode
771 // if all the offsets are small enough.
772 *magic_p = SANITIZER_WORDSIZE == 64 ? kMagic64 : kMagic32;
773
Timur Iskhodzhanov3e8d3922015-03-25 20:19:51 +0000774 const char *module_name = StripModuleName(r.copied_module_name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000775 if (cov_sandboxed) {
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000776 if (cov_fd != kInvalidFd) {
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000777 CovWritePacked(internal_getpid(), module_name, offsets.data(),
Kostya Serebryany9f1243e2015-03-17 22:09:19 +0000778 offsets.size() * sizeof(offsets[0]));
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000779 VReport(1, " CovDump: %zd PCs written to packed file\n", num_offsets);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000780 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000781 } else {
782 // One file per module per process.
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000783 fd_t fd = CovOpenFile(&path, false /* packed */, module_name);
784 if (fd == kInvalidFd) continue;
Timur Iskhodzhanove8a6fbb2015-04-09 14:11:25 +0000785 WriteToFile(fd, offsets.data(), offsets.size() * sizeof(offsets[0]));
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000786 CloseFile(fd);
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000787 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(), num_offsets);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000788 }
789 }
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000790 if (cov_fd != kInvalidFd)
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000791 CloseFile(cov_fd);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000792}
793
794void CoverageData::DumpAll() {
795 if (!coverage_enabled || common_flags()->coverage_direct) return;
796 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
797 return;
798 DumpAsBitSet();
799 DumpCounters();
800 DumpTrace();
801 DumpOffsets();
802 DumpCallerCalleePairs();
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000803}
804
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000805void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
806 if (!args) return;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000807 if (!coverage_enabled) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000808 cov_sandboxed = args->coverage_sandboxed;
809 if (!cov_sandboxed) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000810 cov_max_block_size = args->coverage_max_block_size;
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000811 if (args->coverage_fd >= 0) {
Timur Iskhodzhanov007435c2015-04-09 15:25:21 +0000812 cov_fd = (fd_t)args->coverage_fd;
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000813 } else {
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000814 InternalScopedString path(kMaxPathLength);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000815 // Pre-open the file now. The sandbox won't allow us to do it later.
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000816 cov_fd = CovOpenFile(&path, true /* packed */, 0);
817 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000818}
819
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000820fd_t MaybeOpenCovFile(const char *name) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000821 CHECK(name);
Timur Iskhodzhanov1b2ff682015-04-09 12:20:02 +0000822 if (!coverage_enabled) return kInvalidFd;
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000823 InternalScopedString path(kMaxPathLength);
824 return CovOpenFile(&path, true /* packed */, name);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000825}
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000826
827void CovBeforeFork() {
828 coverage_data.BeforeFork();
829}
830
831void CovAfterFork(int child_pid) {
832 coverage_data.AfterFork(child_pid);
833}
834
Alexey Samsonovab229c12015-08-24 22:21:47 +0000835static void MaybeDumpCoverage() {
836 if (common_flags()->coverage)
837 __sanitizer_cov_dump();
838}
839
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000840void InitializeCoverage(bool enabled, const char *dir) {
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000841 if (coverage_enabled)
842 return; // May happen if two sanitizer enable coverage in the same process.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000843 coverage_enabled = enabled;
844 coverage_dir = dir;
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000845 coverage_data.Init();
846 if (enabled) coverage_data.Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000847 if (!common_flags()->coverage_direct) Atexit(__sanitizer_cov_dump);
Alexey Samsonovab229c12015-08-24 22:21:47 +0000848 AddDieCallback(MaybeDumpCoverage);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000849}
850
851void ReInitializeCoverage(bool enabled, const char *dir) {
852 coverage_enabled = enabled;
853 coverage_dir = dir;
854 coverage_data.ReInit();
855}
856
857void CoverageUpdateMapping() {
858 if (coverage_enabled)
859 CovUpdateMapping(coverage_dir);
860}
861
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000862} // namespace __sanitizer
863
864extern "C" {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000865SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000866 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
867 guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000868}
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000869SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_with_check(u32 *guard) {
870 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000871 if (static_cast<s32>(
872 __sanitizer::atomic_load(atomic_guard, memory_order_relaxed)) < 0)
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000873 __sanitizer_cov(guard);
874}
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000875SANITIZER_INTERFACE_ATTRIBUTE void
876__sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
877 coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
878 callee, callee_cache16, 16);
879}
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000880SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000881 coverage_enabled = true;
882 coverage_dir = common_flags()->coverage_dir;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000883 coverage_data.Init();
884}
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000885SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() {
Alexey Samsonov4369a3f2015-08-22 05:15:55 +0000886 coverage_data.DumpAll();
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000887}
Kostya Serebryany88599462015-02-20 00:30:44 +0000888SANITIZER_INTERFACE_ATTRIBUTE void
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000889__sanitizer_cov_module_init(s32 *guards, uptr npcs, u8 *counters,
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000890 const char *comp_unit_name) {
891 coverage_data.InitializeGuards(guards, npcs, comp_unit_name, GET_CALLER_PC());
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000892 coverage_data.InitializeCounters(counters, npcs);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000893 if (!common_flags()->coverage_direct) return;
894 if (SANITIZER_ANDROID && coverage_enabled) {
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000895 // dlopen/dlclose interceptors do not work on Android, so we rely on
896 // Extend() calls to update .sancov.map.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000897 CovUpdateMapping(coverage_dir, GET_CALLER_PC());
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000898 }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000899 coverage_data.Extend(npcs);
900}
Sergey Matveev83f91e72014-05-21 13:43:52 +0000901SANITIZER_INTERFACE_ATTRIBUTE
902sptr __sanitizer_maybe_open_cov_file(const char *name) {
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000903 return (sptr)MaybeOpenCovFile(name);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000904}
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000905SANITIZER_INTERFACE_ATTRIBUTE
906uptr __sanitizer_get_total_unique_coverage() {
907 return atomic_load(&coverage_counter, memory_order_relaxed);
908}
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000909
910SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000911void __sanitizer_cov_trace_func_enter(s32 *id) {
912 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000913}
914SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000915void __sanitizer_cov_trace_basic_block(s32 *id) {
916 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000917}
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000918SANITIZER_INTERFACE_ATTRIBUTE
919void __sanitizer_reset_coverage() {
920 coverage_data.ReinitializeGuards();
921 internal_bzero_aligned16(
922 coverage_data.data(),
923 RoundUpTo(coverage_data.size() * sizeof(coverage_data.data()[0]), 16));
924}
925SANITIZER_INTERFACE_ATTRIBUTE
926uptr __sanitizer_get_coverage_guards(uptr **data) {
927 *data = coverage_data.data();
928 return coverage_data.size();
929}
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000930
931SANITIZER_INTERFACE_ATTRIBUTE
932uptr __sanitizer_get_number_of_counters() {
933 return coverage_data.GetNumberOf8bitCounters();
934}
935
936SANITIZER_INTERFACE_ATTRIBUTE
937uptr __sanitizer_update_counter_bitset_and_clear_counters(u8 *bitset) {
938 return coverage_data.Update8bitCounterBitsetAndClearCounters(bitset);
939}
Kostya Serebryany4fca6e82015-07-31 01:07:12 +0000940// Default empty implementations (weak). Users should redefine them.
Kostya Serebryany8fd66a72015-05-08 21:32:03 +0000941SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
942void __sanitizer_cov_trace_cmp() {}
Kostya Serebryany4fca6e82015-07-31 01:07:12 +0000943SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
944void __sanitizer_cov_trace_switch() {}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000945} // extern "C"