blob: ffea321e495d4ec40f845f23ec3ac6423ddf367f [file] [log] [blame]
Bob Wilsona08e9ac2013-11-15 07:18:15 +00001//===-- sanitizer_coverage.cc ---------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Sanitizer Coverage.
11// This file implements run-time support for a poor man's coverage tool.
12//
13// Compiler instrumentation:
Kostya Serebryany714c67c2014-01-17 11:00:30 +000014// For every interesting basic block the compiler injects the following code:
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000015// if (Guard < 0) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +000016// __sanitizer_cov(&Guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +000017// }
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000018// At the module start up time __sanitizer_cov_module_init sets the guards
19// to consecutive negative numbers (-1, -2, -3, ...).
Kostya Serebryany714c67c2014-01-17 11:00:30 +000020// It's fine to call __sanitizer_cov more than once for a given block.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000021//
22// Run-time:
Kostya Serebryany714c67c2014-01-17 11:00:30 +000023// - __sanitizer_cov(): record that we've executed the PC (GET_CALLER_PC).
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000024// and atomically set Guard to -Guard.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000025// - __sanitizer_cov_dump: dump the coverage data to disk.
26// For every module of the current process that has coverage data
27// this will create a file module_name.PID.sancov. The file format is simple:
28// it's just a sorted sequence of 4-byte offsets in the module.
29//
30// Eventually, this coverage implementation should be obsoleted by a more
31// powerful general purpose Clang/LLVM coverage instrumentation.
32// Consider this implementation as prototype.
33//
34// FIXME: support (or at least test with) dlclose.
35//===----------------------------------------------------------------------===//
36
37#include "sanitizer_allocator_internal.h"
38#include "sanitizer_common.h"
39#include "sanitizer_libc.h"
40#include "sanitizer_mutex.h"
41#include "sanitizer_procmaps.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000042#include "sanitizer_stacktrace.h"
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000043#include "sanitizer_symbolizer.h"
Bob Wilsona08e9ac2013-11-15 07:18:15 +000044#include "sanitizer_flags.h"
45
Kostya Serebryany183cb6e2014-11-14 23:15:55 +000046static atomic_uint32_t dump_once_guard; // Ensure that CovDump runs only once.
47
48static atomic_uintptr_t coverage_counter;
Bob Wilsona08e9ac2013-11-15 07:18:15 +000049
Kostya Serebryany8b530e12014-04-30 10:40:48 +000050// pc_array is the array containing the covered PCs.
Sergey Matveev6cb47a082014-05-19 12:53:03 +000051// To make the pc_array thread- and async-signal-safe it has to be large enough.
Kostya Serebryany8b530e12014-04-30 10:40:48 +000052// 128M counters "ought to be enough for anybody" (4M on 32-bit).
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000053
54// With coverage_direct=1 in ASAN_OPTIONS, pc_array memory is mapped to a file.
55// In this mode, __sanitizer_cov_dump does nothing, and CovUpdateMapping()
56// dump current memory layout to another file.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000057
Sergey Matveev6cb47a082014-05-19 12:53:03 +000058static bool cov_sandboxed = false;
59static int cov_fd = kInvalidFd;
60static unsigned int cov_max_block_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +000061static bool coverage_enabled = false;
62static const char *coverage_dir;
Sergey Matveev6cb47a082014-05-19 12:53:03 +000063
Bob Wilsona08e9ac2013-11-15 07:18:15 +000064namespace __sanitizer {
65
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000066class CoverageData {
67 public:
68 void Init();
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +000069 void Enable();
70 void Disable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +000071 void ReInit();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +000072 void BeforeFork();
73 void AfterFork(int child_pid);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000074 void Extend(uptr npcs);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000075 void Add(uptr pc, u32 *guard);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000076 void IndirCall(uptr caller, uptr callee, uptr callee_cache[],
77 uptr cache_size);
78 void DumpCallerCalleePairs();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +000079 void DumpTrace();
80
81 ALWAYS_INLINE
Kostya Serebryanyd421db02015-01-03 00:54:43 +000082 void TraceBasicBlock(s32 *id);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000083
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +000084 void InitializeGuardArray(s32 *guards);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +000085 void InitializeGuards(s32 *guards, uptr n);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000086
87 uptr *data();
88 uptr size();
89
90 private:
91 // Maximal size pc array may ever grow.
92 // We MmapNoReserve this space to ensure that the array is contiguous.
Evgeniy Stepanov10308462014-12-26 13:54:11 +000093 static const uptr kPcArrayMaxSize = FIRST_32_SECOND_64(1 << 24, 1 << 27);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000094 // The amount file mapping for the pc array is grown by.
95 static const uptr kPcArrayMmapSize = 64 * 1024;
96
97 // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
98 // much RAM as it really needs.
99 uptr *pc_array;
100 // Index of the first available pc_array slot.
101 atomic_uintptr_t pc_array_index;
102 // Array size.
103 atomic_uintptr_t pc_array_size;
104 // Current file mapped size of the pc array.
105 uptr pc_array_mapped_size;
106 // Descriptor of the file mapped pc array.
107 int pc_fd;
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000108
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000109 // Vector of coverage guard arrays, protected by mu.
110 InternalMmapVectorNoCtor<s32*> guard_array_vec;
111
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000112 // Caller-Callee (cc) array, size and current index.
113 static const uptr kCcArrayMaxSize = FIRST_32_SECOND_64(1 << 18, 1 << 24);
114 uptr **cc_array;
115 atomic_uintptr_t cc_array_index;
116 atomic_uintptr_t cc_array_size;
117
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000118 // Tracing event array, size and current pointer.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000119 // We record all events (basic block entries) in a global buffer of u32
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000120 // values. Each such value is the index in pc_array.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000121 // So far the tracing is highly experimental:
122 // - not thread-safe;
123 // - does not support long traces;
124 // - not tuned for performance.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000125 static const uptr kTrEventArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 30);
126 u32 *tr_event_array;
127 uptr tr_event_array_size;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000128 u32 *tr_event_pointer;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000129 static const uptr kTrPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000130
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000131 StaticSpinMutex mu;
132
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000133 void DirectOpen();
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000134};
135
136static CoverageData coverage_data;
137
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000138void CovUpdateMapping(const char *path, uptr caller_pc = 0);
139
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000140void CoverageData::DirectOpen() {
Alexey Samsonov4cc76cb2014-11-26 01:48:39 +0000141 InternalScopedString path(kMaxPathLength);
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000142 internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000143 coverage_dir, internal_getpid());
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000144 pc_fd = OpenFile(path.data(), true);
145 if (internal_iserror(pc_fd)) {
146 Report(" Coverage: failed to open %s for writing\n", path.data());
147 Die();
148 }
149
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000150 pc_array_mapped_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000151 CovUpdateMapping(coverage_dir);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000152}
153
154void CoverageData::Init() {
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000155 pc_fd = kInvalidFd;
156}
157
158void CoverageData::Enable() {
Viktor Kutuzovabfacbd2015-01-19 09:41:52 +0000159 if (pc_array)
160 return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000161 pc_array = reinterpret_cast<uptr *>(
162 MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000163 atomic_store(&pc_array_index, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000164 if (common_flags()->coverage_direct) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000165 atomic_store(&pc_array_size, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000166 } else {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000167 atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
168 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000169
170 cc_array = reinterpret_cast<uptr **>(MmapNoReserveOrDie(
171 sizeof(uptr *) * kCcArrayMaxSize, "CovInit::cc_array"));
172 atomic_store(&cc_array_size, kCcArrayMaxSize, memory_order_relaxed);
173 atomic_store(&cc_array_index, 0, memory_order_relaxed);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000174
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000175 // Allocate tr_event_array with a guard page at the end.
176 tr_event_array = reinterpret_cast<u32 *>(MmapNoReserveOrDie(
177 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize + GetMmapGranularity(),
178 "CovInit::tr_event_array"));
179 Mprotect(reinterpret_cast<uptr>(&tr_event_array[kTrEventArrayMaxSize]),
180 GetMmapGranularity());
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000181 tr_event_array_size = kTrEventArrayMaxSize;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000182 tr_event_pointer = tr_event_array;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000183}
184
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000185void CoverageData::InitializeGuardArray(s32 *guards) {
Viktor Kutuzovabfacbd2015-01-19 09:41:52 +0000186 Enable(); // Make sure coverage is enabled at this point.
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000187 s32 n = guards[0];
188 for (s32 j = 1; j <= n; j++) {
189 uptr idx = atomic_fetch_add(&pc_array_index, 1, memory_order_relaxed);
190 guards[j] = -static_cast<s32>(idx + 1);
191 }
192}
193
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000194void CoverageData::Disable() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000195 if (pc_array) {
196 internal_munmap(pc_array, sizeof(uptr) * kPcArrayMaxSize);
197 pc_array = nullptr;
198 }
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000199 if (cc_array) {
200 internal_munmap(cc_array, sizeof(uptr *) * kCcArrayMaxSize);
201 cc_array = nullptr;
202 }
203 if (tr_event_array) {
204 internal_munmap(tr_event_array,
205 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize +
206 GetMmapGranularity());
207 tr_event_array = nullptr;
208 tr_event_pointer = nullptr;
209 }
210 if (pc_fd != kInvalidFd) {
211 internal_close(pc_fd);
212 pc_fd = kInvalidFd;
213 }
214}
215
216void CoverageData::ReInit() {
217 Disable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000218 if (coverage_enabled) {
219 if (common_flags()->coverage_direct) {
220 // In memory-mapped mode we must extend the new file to the known array
221 // size.
222 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000223 Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000224 if (size) Extend(size);
225 if (coverage_enabled) CovUpdateMapping(coverage_dir);
226 } else {
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000227 Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000228 }
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000229 }
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000230 // Re-initialize the guards.
231 // We are single-threaded now, no need to grab any lock.
232 CHECK_EQ(atomic_load(&pc_array_index, memory_order_relaxed), 0);
233 for (uptr i = 0; i < guard_array_vec.size(); i++)
234 InitializeGuardArray(guard_array_vec[i]);
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000235}
236
237void CoverageData::BeforeFork() {
238 mu.Lock();
239}
240
241void CoverageData::AfterFork(int child_pid) {
242 // We are single-threaded so it's OK to release the lock early.
243 mu.Unlock();
244 if (child_pid == 0) ReInit();
245}
246
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000247// Extend coverage PC array to fit additional npcs elements.
248void CoverageData::Extend(uptr npcs) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000249 if (!common_flags()->coverage_direct) return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000250 SpinMutexLock l(&mu);
251
252 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
253 size += npcs * sizeof(uptr);
254
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000255 if (coverage_enabled && size > pc_array_mapped_size) {
256 if (pc_fd == kInvalidFd) DirectOpen();
257 CHECK_NE(pc_fd, kInvalidFd);
258
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000259 uptr new_mapped_size = pc_array_mapped_size;
260 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000261 CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000262
263 // Extend the file and map the new space at the end of pc_array.
264 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
265 int err;
266 if (internal_iserror(res, &err)) {
267 Printf("failed to extend raw coverage file: %d\n", err);
268 Die();
269 }
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000270
271 uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
272 void *p = MapWritableFileToMemory((void *)next_map_base,
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000273 new_mapped_size - pc_array_mapped_size,
274 pc_fd, pc_array_mapped_size);
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000275 CHECK_EQ((uptr)p, next_map_base);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000276 pc_array_mapped_size = new_mapped_size;
277 }
278
279 atomic_store(&pc_array_size, size, memory_order_release);
280}
281
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000282void CoverageData::InitializeGuards(s32 *guards, uptr n) {
283 // The array 'guards' has n+1 elements, we use the element zero
284 // to store 'n'.
285 CHECK_LT(n, 1 << 30);
286 guards[0] = static_cast<s32>(n);
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000287 InitializeGuardArray(guards);
288 SpinMutexLock l(&mu);
289 guard_array_vec.push_back(guards);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000290}
291
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000292// If guard is negative, atomically set it to -guard and store the PC in
293// pc_array.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000294void CoverageData::Add(uptr pc, u32 *guard) {
295 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
296 s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
297 if (guard_value >= 0) return;
298
299 atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000300 if (!pc_array) return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000301
302 uptr idx = -guard_value - 1;
303 if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
304 return; // May happen after fork when pc_array_index becomes 0.
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000305 CHECK_LT(idx * sizeof(uptr),
306 atomic_load(&pc_array_size, memory_order_acquire));
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000307 pc_array[idx] = pc;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000308 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000309}
310
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000311// Registers a pair caller=>callee.
312// When a given caller is seen for the first time, the callee_cache is added
313// to the global array cc_array, callee_cache[0] is set to caller and
314// callee_cache[1] is set to cache_size.
315// Then we are trying to add callee to callee_cache [2,cache_size) if it is
316// not there yet.
317// If the cache is full we drop the callee (may want to fix this later).
318void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
319 uptr cache_size) {
320 if (!cc_array) return;
321 atomic_uintptr_t *atomic_callee_cache =
322 reinterpret_cast<atomic_uintptr_t *>(callee_cache);
323 uptr zero = 0;
324 if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
325 memory_order_seq_cst)) {
326 uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
327 CHECK_LT(idx * sizeof(uptr),
328 atomic_load(&cc_array_size, memory_order_acquire));
329 callee_cache[1] = cache_size;
330 cc_array[idx] = callee_cache;
331 }
332 CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
333 for (uptr i = 2; i < cache_size; i++) {
334 uptr was = 0;
335 if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000336 memory_order_seq_cst)) {
337 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000338 return;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000339 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000340 if (was == callee) // Already have this callee.
341 return;
342 }
343}
344
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000345uptr *CoverageData::data() {
346 return pc_array;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000347}
348
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000349uptr CoverageData::size() {
350 return atomic_load(&pc_array_index, memory_order_relaxed);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000351}
352
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000353// Block layout for packed file format: header, followed by module name (no
354// trailing zero), followed by data blob.
355struct CovHeader {
356 int pid;
357 unsigned int module_name_length;
358 unsigned int data_length;
359};
360
361static void CovWritePacked(int pid, const char *module, const void *blob,
362 unsigned int blob_size) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000363 if (cov_fd < 0) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000364 unsigned module_name_length = internal_strlen(module);
365 CovHeader header = {pid, module_name_length, blob_size};
366
367 if (cov_max_block_size == 0) {
368 // Writing to a file. Just go ahead.
369 internal_write(cov_fd, &header, sizeof(header));
370 internal_write(cov_fd, module, module_name_length);
371 internal_write(cov_fd, blob, blob_size);
372 } else {
373 // Writing to a socket. We want to split the data into appropriately sized
374 // blocks.
375 InternalScopedBuffer<char> block(cov_max_block_size);
376 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
377 uptr header_size_with_module = sizeof(header) + module_name_length;
378 CHECK_LT(header_size_with_module, cov_max_block_size);
379 unsigned int max_payload_size =
380 cov_max_block_size - header_size_with_module;
381 char *block_pos = block.data();
382 internal_memcpy(block_pos, &header, sizeof(header));
383 block_pos += sizeof(header);
384 internal_memcpy(block_pos, module, module_name_length);
385 block_pos += module_name_length;
386 char *block_data_begin = block_pos;
Alexey Samsonov4925fd42014-11-13 22:40:59 +0000387 const char *blob_pos = (const char *)blob;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000388 while (blob_size > 0) {
389 unsigned int payload_size = Min(blob_size, max_payload_size);
390 blob_size -= payload_size;
391 internal_memcpy(block_data_begin, blob_pos, payload_size);
392 blob_pos += payload_size;
393 ((CovHeader *)block.data())->data_length = payload_size;
394 internal_write(cov_fd, block.data(),
395 header_size_with_module + payload_size);
396 }
397 }
398}
399
Sergey Matveev83f91e72014-05-21 13:43:52 +0000400// If packed = false: <name>.<pid>.<sancov> (name = module name).
401// If packed = true and name == 0: <pid>.<sancov>.<packed>.
402// If packed = true and name != 0: <name>.<sancov>.<packed> (name is
403// user-supplied).
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000404static int CovOpenFile(bool packed, const char *name,
405 const char *extension = "sancov") {
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000406 InternalScopedString path(kMaxPathLength);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000407 if (!packed) {
408 CHECK(name);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000409 path.append("%s/%s.%zd.%s", coverage_dir, name, internal_getpid(),
410 extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000411 } else {
412 if (!name)
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000413 path.append("%s/%zd.%s.packed", coverage_dir, internal_getpid(),
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000414 extension);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000415 else
416 path.append("%s/%s.%s.packed", coverage_dir, name, extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000417 }
418 uptr fd = OpenFile(path.data(), true);
419 if (internal_iserror(fd)) {
420 Report(" SanitizerCoverage: failed to open %s for writing\n", path.data());
421 return -1;
422 }
423 return fd;
424}
425
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000426// Dump trace PCs and trace events into two separate files.
427void CoverageData::DumpTrace() {
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000428 uptr max_idx = tr_event_pointer - tr_event_array;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000429 if (!max_idx) return;
430 auto sym = Symbolizer::GetOrInit();
431 if (!sym)
432 return;
433 InternalScopedString out(32 << 20);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000434 for (uptr i = 0, n = size(); i < n; i++) {
435 const char *module_name = "<unknown>";
436 uptr module_address = 0;
437 sym->GetModuleNameAndOffsetForPC(pc_array[i], &module_name,
438 &module_address);
439 out.append("%s 0x%zx\n", module_name, module_address);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000440 }
441 int fd = CovOpenFile(false, "trace-points");
442 if (fd < 0) return;
443 internal_write(fd, out.data(), out.length());
444 internal_close(fd);
445
446 fd = CovOpenFile(false, "trace-events");
447 if (fd < 0) return;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000448 uptr bytes_to_write = max_idx * sizeof(tr_event_array[0]);
449 u8 *event_bytes = reinterpret_cast<u8*>(tr_event_array);
450 // The trace file could be huge, and may not be written with a single syscall.
451 while (bytes_to_write) {
452 uptr actually_written = internal_write(fd, event_bytes, bytes_to_write);
453 if (actually_written <= bytes_to_write) {
454 bytes_to_write -= actually_written;
455 event_bytes += actually_written;
456 } else {
457 break;
458 }
459 }
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000460 internal_close(fd);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000461 VReport(1, " CovDump: Trace: %zd PCs written\n", size());
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000462 VReport(1, " CovDump: Trace: %zd Events written\n", max_idx);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000463}
464
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000465// This function dumps the caller=>callee pairs into a file as a sequence of
466// lines like "module_name offset".
467void CoverageData::DumpCallerCalleePairs() {
468 uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
469 if (!max_idx) return;
470 auto sym = Symbolizer::GetOrInit();
471 if (!sym)
472 return;
Kostya Serebryany40aa4a22014-10-31 19:49:46 +0000473 InternalScopedString out(32 << 20);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000474 uptr total = 0;
475 for (uptr i = 0; i < max_idx; i++) {
476 uptr *cc_cache = cc_array[i];
477 CHECK(cc_cache);
478 uptr caller = cc_cache[0];
479 uptr n_callees = cc_cache[1];
480 const char *caller_module_name = "<unknown>";
481 uptr caller_module_address = 0;
482 sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
483 &caller_module_address);
484 for (uptr j = 2; j < n_callees; j++) {
485 uptr callee = cc_cache[j];
486 if (!callee) break;
487 total++;
488 const char *callee_module_name = "<unknown>";
489 uptr callee_module_address = 0;
490 sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
491 &callee_module_address);
492 out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
493 caller_module_address, callee_module_name,
494 callee_module_address);
495 }
496 }
497 int fd = CovOpenFile(false, "caller-callee");
498 if (fd < 0) return;
499 internal_write(fd, out.data(), out.length());
500 internal_close(fd);
501 VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
502}
503
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000504// Record the current PC into the event buffer.
505// Every event is a u32 value (index in tr_pc_array_index) so we compute
506// it once and then cache in the provided 'cache' storage.
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000507//
508// This function will eventually be inlined by the compiler.
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000509void CoverageData::TraceBasicBlock(s32 *id) {
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000510 // Will trap here if
511 // 1. coverage is not enabled at run-time.
512 // 2. The array tr_event_array is full.
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000513 *tr_event_pointer = static_cast<u32>(*id - 1);
514 tr_event_pointer++;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000515}
516
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000517static void CovDumpAsBitSet() {
518 if (!common_flags()->coverage_bitset) return;
519 if (!coverage_data.size()) return;
520 int fd = CovOpenFile(/* packed */false, "combined", "bitset-sancov");
521 if (fd < 0) return;
522 uptr n = coverage_data.size();
523 uptr n_set_bits = 0;
524 InternalScopedBuffer<char> out(n);
525 for (uptr i = 0; i < n; i++) {
526 uptr pc = coverage_data.data()[i];
527 out[i] = pc ? '1' : '0';
528 if (pc)
529 n_set_bits++;
530 }
531 internal_write(fd, out.data(), n);
532 internal_close(fd);
533 VReport(1, " CovDump: bitset of %zd bits written, %zd bits are set\n", n,
534 n_set_bits);
535}
536
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000537// Dump the coverage on disk.
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000538static void CovDump() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000539 if (!coverage_enabled || common_flags()->coverage_direct) return;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000540#if !SANITIZER_WINDOWS
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000541 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
542 return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000543 CovDumpAsBitSet();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000544 coverage_data.DumpTrace();
Kostya Serebryanya7ee2732014-12-30 19:55:04 +0000545 if (!common_flags()->coverage_pcs) return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000546 uptr size = coverage_data.size();
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000547 InternalMmapVector<u32> offsets(size);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000548 uptr *vb = coverage_data.data();
549 uptr *ve = vb + size;
550 SortArray(vb, size);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000551 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000552 uptr mb, me, off, prot;
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000553 InternalScopedString module(kMaxPathLength);
554 InternalScopedString path(kMaxPathLength);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000555 for (int i = 0;
556 proc_maps.Next(&mb, &me, &off, module.data(), module.size(), &prot);
557 i++) {
558 if ((prot & MemoryMappingLayout::kProtectionExecute) == 0)
559 continue;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000560 while (vb < ve && *vb < mb) vb++;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000561 if (vb >= ve) break;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000562 if (*vb < me) {
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000563 offsets.clear();
564 const uptr *old_vb = vb;
565 CHECK_LE(off, *vb);
566 for (; vb < ve && *vb < me; vb++) {
567 uptr diff = *vb - (i ? mb : 0) + off;
568 CHECK_LE(diff, 0xffffffffU);
569 offsets.push_back(static_cast<u32>(diff));
570 }
Alexey Samsonov26ca05a2014-11-04 19:34:29 +0000571 const char *module_name = StripModuleName(module.data());
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000572 if (cov_sandboxed) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000573 if (cov_fd >= 0) {
574 CovWritePacked(internal_getpid(), module_name, offsets.data(),
575 offsets.size() * sizeof(u32));
576 VReport(1, " CovDump: %zd PCs written to packed file\n", vb - old_vb);
577 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000578 } else {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000579 // One file per module per process.
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000580 path.clear();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000581 path.append("%s/%s.%zd.sancov", coverage_dir, module_name,
582 internal_getpid());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000583 int fd = CovOpenFile(false /* packed */, module_name);
584 if (fd > 0) {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000585 internal_write(fd, offsets.data(), offsets.size() * sizeof(u32));
586 internal_close(fd);
587 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(),
588 vb - old_vb);
589 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000590 }
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000591 }
592 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000593 if (cov_fd >= 0)
594 internal_close(cov_fd);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000595 coverage_data.DumpCallerCalleePairs();
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000596#endif // !SANITIZER_WINDOWS
597}
598
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000599void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
600 if (!args) return;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000601 if (!coverage_enabled) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000602 cov_sandboxed = args->coverage_sandboxed;
603 if (!cov_sandboxed) return;
604 cov_fd = args->coverage_fd;
605 cov_max_block_size = args->coverage_max_block_size;
606 if (cov_fd < 0)
607 // Pre-open the file now. The sandbox won't allow us to do it later.
Sergey Matveev83f91e72014-05-21 13:43:52 +0000608 cov_fd = CovOpenFile(true /* packed */, 0);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000609}
610
Sergey Matveev83f91e72014-05-21 13:43:52 +0000611int MaybeOpenCovFile(const char *name) {
612 CHECK(name);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000613 if (!coverage_enabled) return -1;
Sergey Matveev83f91e72014-05-21 13:43:52 +0000614 return CovOpenFile(true /* packed */, name);
615}
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000616
617void CovBeforeFork() {
618 coverage_data.BeforeFork();
619}
620
621void CovAfterFork(int child_pid) {
622 coverage_data.AfterFork(child_pid);
623}
624
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000625void InitializeCoverage(bool enabled, const char *dir) {
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000626 if (coverage_enabled)
627 return; // May happen if two sanitizer enable coverage in the same process.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000628 coverage_enabled = enabled;
629 coverage_dir = dir;
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000630 coverage_data.Init();
631 if (enabled) coverage_data.Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000632#if !SANITIZER_WINDOWS
633 if (!common_flags()->coverage_direct) Atexit(__sanitizer_cov_dump);
634#endif
635}
636
637void ReInitializeCoverage(bool enabled, const char *dir) {
638 coverage_enabled = enabled;
639 coverage_dir = dir;
640 coverage_data.ReInit();
641}
642
643void CoverageUpdateMapping() {
644 if (coverage_enabled)
645 CovUpdateMapping(coverage_dir);
646}
647
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000648} // namespace __sanitizer
649
650extern "C" {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000651SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000652 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
653 guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000654}
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000655SANITIZER_INTERFACE_ATTRIBUTE void
656__sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
657 coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
658 callee, callee_cache16, 16);
659}
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000660SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000661 coverage_enabled = true;
662 coverage_dir = common_flags()->coverage_dir;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000663 coverage_data.Init();
664}
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000665SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() { CovDump(); }
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000666SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_module_init(s32 *guards,
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000667 uptr npcs) {
668 coverage_data.InitializeGuards(guards, npcs);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000669 if (!common_flags()->coverage_direct) return;
670 if (SANITIZER_ANDROID && coverage_enabled) {
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000671 // dlopen/dlclose interceptors do not work on Android, so we rely on
672 // Extend() calls to update .sancov.map.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000673 CovUpdateMapping(coverage_dir, GET_CALLER_PC());
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000674 }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000675 coverage_data.Extend(npcs);
676}
Sergey Matveev83f91e72014-05-21 13:43:52 +0000677SANITIZER_INTERFACE_ATTRIBUTE
678sptr __sanitizer_maybe_open_cov_file(const char *name) {
679 return MaybeOpenCovFile(name);
680}
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000681SANITIZER_INTERFACE_ATTRIBUTE
682uptr __sanitizer_get_total_unique_coverage() {
683 return atomic_load(&coverage_counter, memory_order_relaxed);
684}
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000685
686SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000687void __sanitizer_cov_trace_func_enter(s32 *id) {
688 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000689}
690SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000691void __sanitizer_cov_trace_basic_block(s32 *id) {
692 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000693}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000694} // extern "C"