blob: 0639dc0909f9afa71dc7050cf59470492f047413 [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 Stepanov05dc4be2014-12-26 12:32:32 +000069 void ReInit();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +000070 void BeforeFork();
71 void AfterFork(int child_pid);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000072 void Extend(uptr npcs);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000073 void Add(uptr pc, u32 *guard);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000074 void IndirCall(uptr caller, uptr callee, uptr callee_cache[],
75 uptr cache_size);
76 void DumpCallerCalleePairs();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +000077 void DumpTrace();
78
79 ALWAYS_INLINE
Kostya Serebryanyd421db02015-01-03 00:54:43 +000080 void TraceBasicBlock(s32 *id);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000081
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +000082 void InitializeGuardArray(s32 *guards);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +000083 void InitializeGuards(s32 *guards, uptr n);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000084
85 uptr *data();
86 uptr size();
87
88 private:
89 // Maximal size pc array may ever grow.
90 // We MmapNoReserve this space to ensure that the array is contiguous.
Evgeniy Stepanov10308462014-12-26 13:54:11 +000091 static const uptr kPcArrayMaxSize = FIRST_32_SECOND_64(1 << 24, 1 << 27);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000092 // The amount file mapping for the pc array is grown by.
93 static const uptr kPcArrayMmapSize = 64 * 1024;
94
95 // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
96 // much RAM as it really needs.
97 uptr *pc_array;
98 // Index of the first available pc_array slot.
99 atomic_uintptr_t pc_array_index;
100 // Array size.
101 atomic_uintptr_t pc_array_size;
102 // Current file mapped size of the pc array.
103 uptr pc_array_mapped_size;
104 // Descriptor of the file mapped pc array.
105 int pc_fd;
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000106
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000107 // Vector of coverage guard arrays, protected by mu.
108 InternalMmapVectorNoCtor<s32*> guard_array_vec;
109
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000110 // Caller-Callee (cc) array, size and current index.
111 static const uptr kCcArrayMaxSize = FIRST_32_SECOND_64(1 << 18, 1 << 24);
112 uptr **cc_array;
113 atomic_uintptr_t cc_array_index;
114 atomic_uintptr_t cc_array_size;
115
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000116 // Tracing event array, size and current index.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000117 // We record all events (basic block entries) in a global buffer of u32
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000118 // values. Each such value is the index in pc_array (incremented by one).
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000119 // So far the tracing is highly experimental:
120 // - not thread-safe;
121 // - does not support long traces;
122 // - not tuned for performance.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000123 static const uptr kTrEventArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 30);
124 u32 *tr_event_array;
125 uptr tr_event_array_size;
126 uptr tr_event_array_index;
127 static const uptr kTrPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000128
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000129 StaticSpinMutex mu;
130
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000131 void DirectOpen();
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000132};
133
134static CoverageData coverage_data;
135
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000136void CovUpdateMapping(const char *path, uptr caller_pc = 0);
137
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000138void CoverageData::DirectOpen() {
Alexey Samsonov4cc76cb2014-11-26 01:48:39 +0000139 InternalScopedString path(kMaxPathLength);
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000140 internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000141 coverage_dir, internal_getpid());
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000142 pc_fd = OpenFile(path.data(), true);
143 if (internal_iserror(pc_fd)) {
144 Report(" Coverage: failed to open %s for writing\n", path.data());
145 Die();
146 }
147
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000148 pc_array_mapped_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000149 CovUpdateMapping(coverage_dir);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000150}
151
152void CoverageData::Init() {
153 pc_array = reinterpret_cast<uptr *>(
154 MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000155 pc_fd = kInvalidFd;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000156 atomic_store(&pc_array_index, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000157 if (common_flags()->coverage_direct) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000158 atomic_store(&pc_array_size, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000159 } else {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000160 atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
161 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000162
163 cc_array = reinterpret_cast<uptr **>(MmapNoReserveOrDie(
164 sizeof(uptr *) * kCcArrayMaxSize, "CovInit::cc_array"));
165 atomic_store(&cc_array_size, kCcArrayMaxSize, memory_order_relaxed);
166 atomic_store(&cc_array_index, 0, memory_order_relaxed);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000167
168 tr_event_array = reinterpret_cast<u32 *>(
169 MmapNoReserveOrDie(sizeof(tr_event_array[0]) * kTrEventArrayMaxSize,
170 "CovInit::tr_event_array"));
171 tr_event_array_size = kTrEventArrayMaxSize;
172 tr_event_array_index = 0;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000173}
174
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000175void CoverageData::InitializeGuardArray(s32 *guards) {
176 s32 n = guards[0];
177 for (s32 j = 1; j <= n; j++) {
178 uptr idx = atomic_fetch_add(&pc_array_index, 1, memory_order_relaxed);
179 guards[j] = -static_cast<s32>(idx + 1);
180 }
181}
182
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000183void CoverageData::ReInit() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000184 if (pc_array) {
185 internal_munmap(pc_array, sizeof(uptr) * kPcArrayMaxSize);
186 pc_array = nullptr;
187 }
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000188 if (pc_fd != kInvalidFd) internal_close(pc_fd);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000189 if (coverage_enabled) {
190 if (common_flags()->coverage_direct) {
191 // In memory-mapped mode we must extend the new file to the known array
192 // size.
193 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
194 Init();
195 if (size) Extend(size);
196 if (coverage_enabled) CovUpdateMapping(coverage_dir);
197 } else {
198 Init();
199 }
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000200 }
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000201 // Re-initialize the guards.
202 // We are single-threaded now, no need to grab any lock.
203 CHECK_EQ(atomic_load(&pc_array_index, memory_order_relaxed), 0);
204 for (uptr i = 0; i < guard_array_vec.size(); i++)
205 InitializeGuardArray(guard_array_vec[i]);
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000206}
207
208void CoverageData::BeforeFork() {
209 mu.Lock();
210}
211
212void CoverageData::AfterFork(int child_pid) {
213 // We are single-threaded so it's OK to release the lock early.
214 mu.Unlock();
215 if (child_pid == 0) ReInit();
216}
217
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000218// Extend coverage PC array to fit additional npcs elements.
219void CoverageData::Extend(uptr npcs) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000220 if (!common_flags()->coverage_direct) return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000221 SpinMutexLock l(&mu);
222
223 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
224 size += npcs * sizeof(uptr);
225
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000226 if (coverage_enabled && size > pc_array_mapped_size) {
227 if (pc_fd == kInvalidFd) DirectOpen();
228 CHECK_NE(pc_fd, kInvalidFd);
229
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000230 uptr new_mapped_size = pc_array_mapped_size;
231 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000232 CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000233
234 // Extend the file and map the new space at the end of pc_array.
235 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
236 int err;
237 if (internal_iserror(res, &err)) {
238 Printf("failed to extend raw coverage file: %d\n", err);
239 Die();
240 }
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000241
242 uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
243 void *p = MapWritableFileToMemory((void *)next_map_base,
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000244 new_mapped_size - pc_array_mapped_size,
245 pc_fd, pc_array_mapped_size);
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000246 CHECK_EQ((uptr)p, next_map_base);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000247 pc_array_mapped_size = new_mapped_size;
248 }
249
250 atomic_store(&pc_array_size, size, memory_order_release);
251}
252
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000253void CoverageData::InitializeGuards(s32 *guards, uptr n) {
254 // The array 'guards' has n+1 elements, we use the element zero
255 // to store 'n'.
256 CHECK_LT(n, 1 << 30);
257 guards[0] = static_cast<s32>(n);
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000258 InitializeGuardArray(guards);
259 SpinMutexLock l(&mu);
260 guard_array_vec.push_back(guards);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000261}
262
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000263// If guard is negative, atomically set it to -guard and store the PC in
264// pc_array.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000265void CoverageData::Add(uptr pc, u32 *guard) {
266 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
267 s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
268 if (guard_value >= 0) return;
269
270 atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000271 if (!pc_array) return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000272
273 uptr idx = -guard_value - 1;
274 if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
275 return; // May happen after fork when pc_array_index becomes 0.
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000276 CHECK_LT(idx * sizeof(uptr),
277 atomic_load(&pc_array_size, memory_order_acquire));
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000278 pc_array[idx] = pc;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000279 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000280}
281
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000282// Registers a pair caller=>callee.
283// When a given caller is seen for the first time, the callee_cache is added
284// to the global array cc_array, callee_cache[0] is set to caller and
285// callee_cache[1] is set to cache_size.
286// Then we are trying to add callee to callee_cache [2,cache_size) if it is
287// not there yet.
288// If the cache is full we drop the callee (may want to fix this later).
289void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
290 uptr cache_size) {
291 if (!cc_array) return;
292 atomic_uintptr_t *atomic_callee_cache =
293 reinterpret_cast<atomic_uintptr_t *>(callee_cache);
294 uptr zero = 0;
295 if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
296 memory_order_seq_cst)) {
297 uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
298 CHECK_LT(idx * sizeof(uptr),
299 atomic_load(&cc_array_size, memory_order_acquire));
300 callee_cache[1] = cache_size;
301 cc_array[idx] = callee_cache;
302 }
303 CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
304 for (uptr i = 2; i < cache_size; i++) {
305 uptr was = 0;
306 if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000307 memory_order_seq_cst)) {
308 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000309 return;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000310 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000311 if (was == callee) // Already have this callee.
312 return;
313 }
314}
315
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000316uptr *CoverageData::data() {
317 return pc_array;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000318}
319
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000320uptr CoverageData::size() {
321 return atomic_load(&pc_array_index, memory_order_relaxed);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000322}
323
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000324// Block layout for packed file format: header, followed by module name (no
325// trailing zero), followed by data blob.
326struct CovHeader {
327 int pid;
328 unsigned int module_name_length;
329 unsigned int data_length;
330};
331
332static void CovWritePacked(int pid, const char *module, const void *blob,
333 unsigned int blob_size) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000334 if (cov_fd < 0) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000335 unsigned module_name_length = internal_strlen(module);
336 CovHeader header = {pid, module_name_length, blob_size};
337
338 if (cov_max_block_size == 0) {
339 // Writing to a file. Just go ahead.
340 internal_write(cov_fd, &header, sizeof(header));
341 internal_write(cov_fd, module, module_name_length);
342 internal_write(cov_fd, blob, blob_size);
343 } else {
344 // Writing to a socket. We want to split the data into appropriately sized
345 // blocks.
346 InternalScopedBuffer<char> block(cov_max_block_size);
347 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
348 uptr header_size_with_module = sizeof(header) + module_name_length;
349 CHECK_LT(header_size_with_module, cov_max_block_size);
350 unsigned int max_payload_size =
351 cov_max_block_size - header_size_with_module;
352 char *block_pos = block.data();
353 internal_memcpy(block_pos, &header, sizeof(header));
354 block_pos += sizeof(header);
355 internal_memcpy(block_pos, module, module_name_length);
356 block_pos += module_name_length;
357 char *block_data_begin = block_pos;
Alexey Samsonov4925fd42014-11-13 22:40:59 +0000358 const char *blob_pos = (const char *)blob;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000359 while (blob_size > 0) {
360 unsigned int payload_size = Min(blob_size, max_payload_size);
361 blob_size -= payload_size;
362 internal_memcpy(block_data_begin, blob_pos, payload_size);
363 blob_pos += payload_size;
364 ((CovHeader *)block.data())->data_length = payload_size;
365 internal_write(cov_fd, block.data(),
366 header_size_with_module + payload_size);
367 }
368 }
369}
370
Sergey Matveev83f91e72014-05-21 13:43:52 +0000371// If packed = false: <name>.<pid>.<sancov> (name = module name).
372// If packed = true and name == 0: <pid>.<sancov>.<packed>.
373// If packed = true and name != 0: <name>.<sancov>.<packed> (name is
374// user-supplied).
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000375static int CovOpenFile(bool packed, const char *name,
376 const char *extension = "sancov") {
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000377 InternalScopedString path(kMaxPathLength);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000378 if (!packed) {
379 CHECK(name);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000380 path.append("%s/%s.%zd.%s", coverage_dir, name, internal_getpid(),
381 extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000382 } else {
383 if (!name)
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000384 path.append("%s/%zd.%s.packed", coverage_dir, internal_getpid(),
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000385 extension);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000386 else
387 path.append("%s/%s.%s.packed", coverage_dir, name, extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000388 }
389 uptr fd = OpenFile(path.data(), true);
390 if (internal_iserror(fd)) {
391 Report(" SanitizerCoverage: failed to open %s for writing\n", path.data());
392 return -1;
393 }
394 return fd;
395}
396
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000397// Dump trace PCs and trace events into two separate files.
398void CoverageData::DumpTrace() {
399 uptr max_idx = tr_event_array_index;
400 if (!max_idx) return;
401 auto sym = Symbolizer::GetOrInit();
402 if (!sym)
403 return;
404 InternalScopedString out(32 << 20);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000405 for (uptr i = 0, n = size(); i < n; i++) {
406 const char *module_name = "<unknown>";
407 uptr module_address = 0;
408 sym->GetModuleNameAndOffsetForPC(pc_array[i], &module_name,
409 &module_address);
410 out.append("%s 0x%zx\n", module_name, module_address);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000411 }
412 int fd = CovOpenFile(false, "trace-points");
413 if (fd < 0) return;
414 internal_write(fd, out.data(), out.length());
415 internal_close(fd);
416
417 fd = CovOpenFile(false, "trace-events");
418 if (fd < 0) return;
419 internal_write(fd, tr_event_array, max_idx * sizeof(tr_event_array[0]));
420 internal_close(fd);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000421 VReport(1, " CovDump: Trace: %zd PCs written\n", size());
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000422 VReport(1, " CovDump: Trace: %zd Events written\n", tr_event_array_index);
423}
424
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000425// This function dumps the caller=>callee pairs into a file as a sequence of
426// lines like "module_name offset".
427void CoverageData::DumpCallerCalleePairs() {
428 uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
429 if (!max_idx) return;
430 auto sym = Symbolizer::GetOrInit();
431 if (!sym)
432 return;
Kostya Serebryany40aa4a22014-10-31 19:49:46 +0000433 InternalScopedString out(32 << 20);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000434 uptr total = 0;
435 for (uptr i = 0; i < max_idx; i++) {
436 uptr *cc_cache = cc_array[i];
437 CHECK(cc_cache);
438 uptr caller = cc_cache[0];
439 uptr n_callees = cc_cache[1];
440 const char *caller_module_name = "<unknown>";
441 uptr caller_module_address = 0;
442 sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
443 &caller_module_address);
444 for (uptr j = 2; j < n_callees; j++) {
445 uptr callee = cc_cache[j];
446 if (!callee) break;
447 total++;
448 const char *callee_module_name = "<unknown>";
449 uptr callee_module_address = 0;
450 sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
451 &callee_module_address);
452 out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
453 caller_module_address, callee_module_name,
454 callee_module_address);
455 }
456 }
457 int fd = CovOpenFile(false, "caller-callee");
458 if (fd < 0) return;
459 internal_write(fd, out.data(), out.length());
460 internal_close(fd);
461 VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
462}
463
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000464// Record the current PC into the event buffer.
465// Every event is a u32 value (index in tr_pc_array_index) so we compute
466// it once and then cache in the provided 'cache' storage.
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000467void CoverageData::TraceBasicBlock(s32 *id) {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000468 CHECK(coverage_enabled);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000469 uptr idx = *id;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000470 CHECK_LT(tr_event_array_index, tr_event_array_size);
471 tr_event_array[tr_event_array_index] = static_cast<u32>(idx);
472 tr_event_array_index++;
473}
474
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000475static void CovDumpAsBitSet() {
476 if (!common_flags()->coverage_bitset) return;
477 if (!coverage_data.size()) return;
478 int fd = CovOpenFile(/* packed */false, "combined", "bitset-sancov");
479 if (fd < 0) return;
480 uptr n = coverage_data.size();
481 uptr n_set_bits = 0;
482 InternalScopedBuffer<char> out(n);
483 for (uptr i = 0; i < n; i++) {
484 uptr pc = coverage_data.data()[i];
485 out[i] = pc ? '1' : '0';
486 if (pc)
487 n_set_bits++;
488 }
489 internal_write(fd, out.data(), n);
490 internal_close(fd);
491 VReport(1, " CovDump: bitset of %zd bits written, %zd bits are set\n", n,
492 n_set_bits);
493}
494
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000495// Dump the coverage on disk.
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000496static void CovDump() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000497 if (!coverage_enabled || common_flags()->coverage_direct) return;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000498#if !SANITIZER_WINDOWS
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000499 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
500 return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000501 CovDumpAsBitSet();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000502 coverage_data.DumpTrace();
Kostya Serebryanya7ee2732014-12-30 19:55:04 +0000503 if (!common_flags()->coverage_pcs) return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000504 uptr size = coverage_data.size();
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000505 InternalMmapVector<u32> offsets(size);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000506 uptr *vb = coverage_data.data();
507 uptr *ve = vb + size;
508 SortArray(vb, size);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000509 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000510 uptr mb, me, off, prot;
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000511 InternalScopedString module(kMaxPathLength);
512 InternalScopedString path(kMaxPathLength);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000513 for (int i = 0;
514 proc_maps.Next(&mb, &me, &off, module.data(), module.size(), &prot);
515 i++) {
516 if ((prot & MemoryMappingLayout::kProtectionExecute) == 0)
517 continue;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000518 while (vb < ve && *vb < mb) vb++;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000519 if (vb >= ve) break;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000520 if (*vb < me) {
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000521 offsets.clear();
522 const uptr *old_vb = vb;
523 CHECK_LE(off, *vb);
524 for (; vb < ve && *vb < me; vb++) {
525 uptr diff = *vb - (i ? mb : 0) + off;
526 CHECK_LE(diff, 0xffffffffU);
527 offsets.push_back(static_cast<u32>(diff));
528 }
Alexey Samsonov26ca05a2014-11-04 19:34:29 +0000529 const char *module_name = StripModuleName(module.data());
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000530 if (cov_sandboxed) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000531 if (cov_fd >= 0) {
532 CovWritePacked(internal_getpid(), module_name, offsets.data(),
533 offsets.size() * sizeof(u32));
534 VReport(1, " CovDump: %zd PCs written to packed file\n", vb - old_vb);
535 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000536 } else {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000537 // One file per module per process.
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000538 path.clear();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000539 path.append("%s/%s.%zd.sancov", coverage_dir, module_name,
540 internal_getpid());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000541 int fd = CovOpenFile(false /* packed */, module_name);
542 if (fd > 0) {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000543 internal_write(fd, offsets.data(), offsets.size() * sizeof(u32));
544 internal_close(fd);
545 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(),
546 vb - old_vb);
547 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000548 }
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000549 }
550 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000551 if (cov_fd >= 0)
552 internal_close(cov_fd);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000553 coverage_data.DumpCallerCalleePairs();
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000554#endif // !SANITIZER_WINDOWS
555}
556
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000557void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
558 if (!args) return;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000559 if (!coverage_enabled) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000560 cov_sandboxed = args->coverage_sandboxed;
561 if (!cov_sandboxed) return;
562 cov_fd = args->coverage_fd;
563 cov_max_block_size = args->coverage_max_block_size;
564 if (cov_fd < 0)
565 // Pre-open the file now. The sandbox won't allow us to do it later.
Sergey Matveev83f91e72014-05-21 13:43:52 +0000566 cov_fd = CovOpenFile(true /* packed */, 0);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000567}
568
Sergey Matveev83f91e72014-05-21 13:43:52 +0000569int MaybeOpenCovFile(const char *name) {
570 CHECK(name);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000571 if (!coverage_enabled) return -1;
Sergey Matveev83f91e72014-05-21 13:43:52 +0000572 return CovOpenFile(true /* packed */, name);
573}
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000574
575void CovBeforeFork() {
576 coverage_data.BeforeFork();
577}
578
579void CovAfterFork(int child_pid) {
580 coverage_data.AfterFork(child_pid);
581}
582
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000583void InitializeCoverage(bool enabled, const char *dir) {
584 coverage_enabled = enabled;
585 coverage_dir = dir;
586 if (enabled) coverage_data.Init();
587#if !SANITIZER_WINDOWS
588 if (!common_flags()->coverage_direct) Atexit(__sanitizer_cov_dump);
589#endif
590}
591
592void ReInitializeCoverage(bool enabled, const char *dir) {
593 coverage_enabled = enabled;
594 coverage_dir = dir;
595 coverage_data.ReInit();
596}
597
598void CoverageUpdateMapping() {
599 if (coverage_enabled)
600 CovUpdateMapping(coverage_dir);
601}
602
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000603} // namespace __sanitizer
604
605extern "C" {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000606SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000607 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
608 guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000609}
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000610SANITIZER_INTERFACE_ATTRIBUTE void
611__sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
612 coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
613 callee, callee_cache16, 16);
614}
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000615SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000616 coverage_enabled = true;
617 coverage_dir = common_flags()->coverage_dir;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000618 coverage_data.Init();
619}
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000620SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() { CovDump(); }
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000621SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_module_init(s32 *guards,
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000622 uptr npcs) {
623 coverage_data.InitializeGuards(guards, npcs);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000624 if (!common_flags()->coverage_direct) return;
625 if (SANITIZER_ANDROID && coverage_enabled) {
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000626 // dlopen/dlclose interceptors do not work on Android, so we rely on
627 // Extend() calls to update .sancov.map.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000628 CovUpdateMapping(coverage_dir, GET_CALLER_PC());
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000629 }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000630 coverage_data.Extend(npcs);
631}
Sergey Matveev83f91e72014-05-21 13:43:52 +0000632SANITIZER_INTERFACE_ATTRIBUTE
633sptr __sanitizer_maybe_open_cov_file(const char *name) {
634 return MaybeOpenCovFile(name);
635}
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000636SANITIZER_INTERFACE_ATTRIBUTE
637uptr __sanitizer_get_total_unique_coverage() {
638 return atomic_load(&coverage_counter, memory_order_relaxed);
639}
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000640
641SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000642void __sanitizer_cov_trace_func_enter(s32 *id) {
643 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000644}
645SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000646void __sanitizer_cov_trace_basic_block(s32 *id) {
647 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000648}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000649} // extern "C"