blob: 8f0076f2c062f4baf565124b85053aa5f5a20d32 [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;
61
Bob Wilsona08e9ac2013-11-15 07:18:15 +000062namespace __sanitizer {
63
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000064class CoverageData {
65 public:
66 void Init();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +000067 void BeforeFork();
68 void AfterFork(int child_pid);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000069 void Extend(uptr npcs);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000070 void Add(uptr pc, u32 *guard);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000071 void IndirCall(uptr caller, uptr callee, uptr callee_cache[],
72 uptr cache_size);
73 void DumpCallerCalleePairs();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +000074 void DumpTrace();
75
76 ALWAYS_INLINE
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000077 void TraceBasicBlock(uptr *cache);
78
79 void InitializeGuards(s32 **guards, uptr n);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000080
81 uptr *data();
82 uptr size();
83
84 private:
85 // Maximal size pc array may ever grow.
86 // We MmapNoReserve this space to ensure that the array is contiguous.
87 static const uptr kPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
88 // The amount file mapping for the pc array is grown by.
89 static const uptr kPcArrayMmapSize = 64 * 1024;
90
91 // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
92 // much RAM as it really needs.
93 uptr *pc_array;
94 // Index of the first available pc_array slot.
95 atomic_uintptr_t pc_array_index;
96 // Array size.
97 atomic_uintptr_t pc_array_size;
98 // Current file mapped size of the pc array.
99 uptr pc_array_mapped_size;
100 // Descriptor of the file mapped pc array.
101 int pc_fd;
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000102
103 // Caller-Callee (cc) array, size and current index.
104 static const uptr kCcArrayMaxSize = FIRST_32_SECOND_64(1 << 18, 1 << 24);
105 uptr **cc_array;
106 atomic_uintptr_t cc_array_index;
107 atomic_uintptr_t cc_array_size;
108
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000109 // Tracing (tr) pc and event arrays, their size and current index.
110 // We record all events (basic block entries) in a global buffer of u32
111 // values. Each such value is an index in the table of TracedPc objects.
112 // So far the tracing is highly experimental:
113 // - not thread-safe;
114 // - does not support long traces;
115 // - not tuned for performance.
116 struct TracedPc {
117 uptr pc;
118 const char *module_name;
119 uptr module_offset;
120 };
121 static const uptr kTrEventArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 30);
122 u32 *tr_event_array;
123 uptr tr_event_array_size;
124 uptr tr_event_array_index;
125 static const uptr kTrPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
126 TracedPc *tr_pc_array;
127 uptr tr_pc_array_size;
128 uptr tr_pc_array_index;
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000129
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000130 StaticSpinMutex mu;
131
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000132 void DirectOpen();
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000133 void ReInit();
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000134};
135
136static CoverageData coverage_data;
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 Stepanovf8c7e252014-12-26 10:19:56 +0000141 common_flags()->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 Stepanovf8c7e252014-12-26 10:19:56 +0000149 CovUpdateMapping();
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;
173
174 tr_pc_array = reinterpret_cast<TracedPc *>(MmapNoReserveOrDie(
175 sizeof(tr_pc_array[0]) * kTrEventArrayMaxSize, "CovInit::tr_pc_array"));
176 tr_pc_array_size = kTrEventArrayMaxSize;
177 tr_pc_array_index = 0;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000178}
179
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000180void CoverageData::ReInit() {
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000181 internal_munmap(pc_array, sizeof(uptr) * kPcArrayMaxSize);
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000182 if (pc_fd != kInvalidFd) internal_close(pc_fd);
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000183 if (common_flags()->coverage_direct) {
184 // In memory-mapped mode we must extend the new file to the known array
185 // size.
186 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
187 Init();
188 if (size) Extend(size);
189 } else {
190 Init();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000191 }
192}
193
194void CoverageData::BeforeFork() {
195 mu.Lock();
196}
197
198void CoverageData::AfterFork(int child_pid) {
199 // We are single-threaded so it's OK to release the lock early.
200 mu.Unlock();
201 if (child_pid == 0) ReInit();
202}
203
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000204// Extend coverage PC array to fit additional npcs elements.
205void CoverageData::Extend(uptr npcs) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000206 if (!common_flags()->coverage_direct) return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000207 SpinMutexLock l(&mu);
208
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000209 if (pc_fd == kInvalidFd) DirectOpen();
210 CHECK_NE(pc_fd, kInvalidFd);
211
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000212 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
213 size += npcs * sizeof(uptr);
214
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000215 if (size > pc_array_mapped_size) {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000216 uptr new_mapped_size = pc_array_mapped_size;
217 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000218 CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000219
220 // Extend the file and map the new space at the end of pc_array.
221 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
222 int err;
223 if (internal_iserror(res, &err)) {
224 Printf("failed to extend raw coverage file: %d\n", err);
225 Die();
226 }
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000227
228 uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
229 void *p = MapWritableFileToMemory((void *)next_map_base,
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000230 new_mapped_size - pc_array_mapped_size,
231 pc_fd, pc_array_mapped_size);
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000232 CHECK_EQ((uptr)p, next_map_base);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000233 pc_array_mapped_size = new_mapped_size;
234 }
235
236 atomic_store(&pc_array_size, size, memory_order_release);
237}
238
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000239void CoverageData::InitializeGuards(s32 **guards, uptr n) {
240 for (uptr i = 0; i < n; i++) {
241 uptr idx = atomic_fetch_add(&pc_array_index, 1, memory_order_relaxed);
242 *guards[i] = -static_cast<s32>(idx + 1);
243 }
244}
245
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000246// Atomically add the pc to the vector. The atomically set the guard to 1.
247// If the function is called more than once for a given PC it will
248// be inserted multiple times, which is fine.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000249void CoverageData::Add(uptr pc, u32 *guard) {
250 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
251 s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
252 if (guard_value >= 0) return;
253
254 atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000255 if (!pc_array) return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000256
257 uptr idx = -guard_value - 1;
258 if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
259 return; // May happen after fork when pc_array_index becomes 0.
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000260 CHECK_LT(idx * sizeof(uptr),
261 atomic_load(&pc_array_size, memory_order_acquire));
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000262 pc_array[idx] = pc;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000263 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000264}
265
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000266// Registers a pair caller=>callee.
267// When a given caller is seen for the first time, the callee_cache is added
268// to the global array cc_array, callee_cache[0] is set to caller and
269// callee_cache[1] is set to cache_size.
270// Then we are trying to add callee to callee_cache [2,cache_size) if it is
271// not there yet.
272// If the cache is full we drop the callee (may want to fix this later).
273void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
274 uptr cache_size) {
275 if (!cc_array) return;
276 atomic_uintptr_t *atomic_callee_cache =
277 reinterpret_cast<atomic_uintptr_t *>(callee_cache);
278 uptr zero = 0;
279 if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
280 memory_order_seq_cst)) {
281 uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
282 CHECK_LT(idx * sizeof(uptr),
283 atomic_load(&cc_array_size, memory_order_acquire));
284 callee_cache[1] = cache_size;
285 cc_array[idx] = callee_cache;
286 }
287 CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
288 for (uptr i = 2; i < cache_size; i++) {
289 uptr was = 0;
290 if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000291 memory_order_seq_cst)) {
292 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000293 return;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000294 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000295 if (was == callee) // Already have this callee.
296 return;
297 }
298}
299
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000300uptr *CoverageData::data() {
301 return pc_array;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000302}
303
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000304uptr CoverageData::size() {
305 return atomic_load(&pc_array_index, memory_order_relaxed);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000306}
307
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000308// Block layout for packed file format: header, followed by module name (no
309// trailing zero), followed by data blob.
310struct CovHeader {
311 int pid;
312 unsigned int module_name_length;
313 unsigned int data_length;
314};
315
316static void CovWritePacked(int pid, const char *module, const void *blob,
317 unsigned int blob_size) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000318 if (cov_fd < 0) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000319 unsigned module_name_length = internal_strlen(module);
320 CovHeader header = {pid, module_name_length, blob_size};
321
322 if (cov_max_block_size == 0) {
323 // Writing to a file. Just go ahead.
324 internal_write(cov_fd, &header, sizeof(header));
325 internal_write(cov_fd, module, module_name_length);
326 internal_write(cov_fd, blob, blob_size);
327 } else {
328 // Writing to a socket. We want to split the data into appropriately sized
329 // blocks.
330 InternalScopedBuffer<char> block(cov_max_block_size);
331 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
332 uptr header_size_with_module = sizeof(header) + module_name_length;
333 CHECK_LT(header_size_with_module, cov_max_block_size);
334 unsigned int max_payload_size =
335 cov_max_block_size - header_size_with_module;
336 char *block_pos = block.data();
337 internal_memcpy(block_pos, &header, sizeof(header));
338 block_pos += sizeof(header);
339 internal_memcpy(block_pos, module, module_name_length);
340 block_pos += module_name_length;
341 char *block_data_begin = block_pos;
Alexey Samsonov4925fd42014-11-13 22:40:59 +0000342 const char *blob_pos = (const char *)blob;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000343 while (blob_size > 0) {
344 unsigned int payload_size = Min(blob_size, max_payload_size);
345 blob_size -= payload_size;
346 internal_memcpy(block_data_begin, blob_pos, payload_size);
347 blob_pos += payload_size;
348 ((CovHeader *)block.data())->data_length = payload_size;
349 internal_write(cov_fd, block.data(),
350 header_size_with_module + payload_size);
351 }
352 }
353}
354
Sergey Matveev83f91e72014-05-21 13:43:52 +0000355// If packed = false: <name>.<pid>.<sancov> (name = module name).
356// If packed = true and name == 0: <pid>.<sancov>.<packed>.
357// If packed = true and name != 0: <name>.<sancov>.<packed> (name is
358// user-supplied).
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000359static int CovOpenFile(bool packed, const char *name,
360 const char *extension = "sancov") {
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000361 InternalScopedString path(kMaxPathLength);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000362 if (!packed) {
363 CHECK(name);
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000364 path.append("%s/%s.%zd.%s", common_flags()->coverage_dir, name,
365 internal_getpid(), extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000366 } else {
367 if (!name)
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000368 path.append("%s/%zd.%s.packed", common_flags()->coverage_dir,
369 internal_getpid(), extension);
Evgeniy Stepanovbe9a53f2014-12-25 14:26:45 +0000370 else
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000371 path.append("%s/%s.%s.packed", common_flags()->coverage_dir, name,
372 extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000373 }
374 uptr fd = OpenFile(path.data(), true);
375 if (internal_iserror(fd)) {
376 Report(" SanitizerCoverage: failed to open %s for writing\n", path.data());
377 return -1;
378 }
379 return fd;
380}
381
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000382// Dump trace PCs and trace events into two separate files.
383void CoverageData::DumpTrace() {
384 uptr max_idx = tr_event_array_index;
385 if (!max_idx) return;
386 auto sym = Symbolizer::GetOrInit();
387 if (!sym)
388 return;
389 InternalScopedString out(32 << 20);
390 for (uptr i = 0; i < max_idx; i++) {
391 u32 pc_idx = tr_event_array[i];
392 TracedPc *t = &tr_pc_array[pc_idx];
393 if (!t->module_name) {
394 const char *module_name = "<unknown>";
395 uptr module_address = 0;
396 sym->GetModuleNameAndOffsetForPC(t->pc, &module_name, &module_address);
397 t->module_name = internal_strdup(module_name);
398 t->module_offset = module_address;
399 out.append("%s 0x%zx\n", t->module_name, t->module_offset);
400 }
401 }
402 int fd = CovOpenFile(false, "trace-points");
403 if (fd < 0) return;
404 internal_write(fd, out.data(), out.length());
405 internal_close(fd);
406
407 fd = CovOpenFile(false, "trace-events");
408 if (fd < 0) return;
409 internal_write(fd, tr_event_array, max_idx * sizeof(tr_event_array[0]));
410 internal_close(fd);
411 VReport(1, " CovDump: Trace: %zd PCs written\n", tr_pc_array_index);
412 VReport(1, " CovDump: Trace: %zd Events written\n", tr_event_array_index);
413}
414
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000415// This function dumps the caller=>callee pairs into a file as a sequence of
416// lines like "module_name offset".
417void CoverageData::DumpCallerCalleePairs() {
418 uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
419 if (!max_idx) return;
420 auto sym = Symbolizer::GetOrInit();
421 if (!sym)
422 return;
Kostya Serebryany40aa4a22014-10-31 19:49:46 +0000423 InternalScopedString out(32 << 20);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000424 uptr total = 0;
425 for (uptr i = 0; i < max_idx; i++) {
426 uptr *cc_cache = cc_array[i];
427 CHECK(cc_cache);
428 uptr caller = cc_cache[0];
429 uptr n_callees = cc_cache[1];
430 const char *caller_module_name = "<unknown>";
431 uptr caller_module_address = 0;
432 sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
433 &caller_module_address);
434 for (uptr j = 2; j < n_callees; j++) {
435 uptr callee = cc_cache[j];
436 if (!callee) break;
437 total++;
438 const char *callee_module_name = "<unknown>";
439 uptr callee_module_address = 0;
440 sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
441 &callee_module_address);
442 out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
443 caller_module_address, callee_module_name,
444 callee_module_address);
445 }
446 }
447 int fd = CovOpenFile(false, "caller-callee");
448 if (fd < 0) return;
449 internal_write(fd, out.data(), out.length());
450 internal_close(fd);
451 VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
452}
453
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000454// Record the current PC into the event buffer.
455// Every event is a u32 value (index in tr_pc_array_index) so we compute
456// it once and then cache in the provided 'cache' storage.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000457void CoverageData::TraceBasicBlock(uptr *cache) {
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000458 CHECK(common_flags()->coverage);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000459 uptr idx = *cache;
460 if (!idx) {
461 CHECK_LT(tr_pc_array_index, kTrPcArrayMaxSize);
462 idx = tr_pc_array_index++;
463 TracedPc *t = &tr_pc_array[idx];
464 t->pc = GET_CALLER_PC();
465 *cache = idx;
466 CHECK_LT(idx, 1U << 31);
467 }
468 CHECK_LT(tr_event_array_index, tr_event_array_size);
469 tr_event_array[tr_event_array_index] = static_cast<u32>(idx);
470 tr_event_array_index++;
471}
472
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000473static void CovDumpAsBitSet() {
474 if (!common_flags()->coverage_bitset) return;
475 if (!coverage_data.size()) return;
476 int fd = CovOpenFile(/* packed */false, "combined", "bitset-sancov");
477 if (fd < 0) return;
478 uptr n = coverage_data.size();
479 uptr n_set_bits = 0;
480 InternalScopedBuffer<char> out(n);
481 for (uptr i = 0; i < n; i++) {
482 uptr pc = coverage_data.data()[i];
483 out[i] = pc ? '1' : '0';
484 if (pc)
485 n_set_bits++;
486 }
487 internal_write(fd, out.data(), n);
488 internal_close(fd);
489 VReport(1, " CovDump: bitset of %zd bits written, %zd bits are set\n", n,
490 n_set_bits);
491}
492
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000493// Dump the coverage on disk.
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000494static void CovDump() {
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000495 if (!common_flags()->coverage || common_flags()->coverage_direct) return;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000496#if !SANITIZER_WINDOWS
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000497 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
498 return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000499 CovDumpAsBitSet();
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000500 uptr size = coverage_data.size();
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000501 InternalMmapVector<u32> offsets(size);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000502 uptr *vb = coverage_data.data();
503 uptr *ve = vb + size;
504 SortArray(vb, size);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000505 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000506 uptr mb, me, off, prot;
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000507 InternalScopedString module(kMaxPathLength);
508 InternalScopedString path(kMaxPathLength);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000509 for (int i = 0;
510 proc_maps.Next(&mb, &me, &off, module.data(), module.size(), &prot);
511 i++) {
512 if ((prot & MemoryMappingLayout::kProtectionExecute) == 0)
513 continue;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000514 while (vb < ve && *vb < mb) vb++;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000515 if (vb >= ve) break;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000516 if (*vb < me) {
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000517 offsets.clear();
518 const uptr *old_vb = vb;
519 CHECK_LE(off, *vb);
520 for (; vb < ve && *vb < me; vb++) {
521 uptr diff = *vb - (i ? mb : 0) + off;
522 CHECK_LE(diff, 0xffffffffU);
523 offsets.push_back(static_cast<u32>(diff));
524 }
Alexey Samsonov26ca05a2014-11-04 19:34:29 +0000525 const char *module_name = StripModuleName(module.data());
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000526 if (cov_sandboxed) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000527 if (cov_fd >= 0) {
528 CovWritePacked(internal_getpid(), module_name, offsets.data(),
529 offsets.size() * sizeof(u32));
530 VReport(1, " CovDump: %zd PCs written to packed file\n", vb - old_vb);
531 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000532 } else {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000533 // One file per module per process.
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000534 path.clear();
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000535 path.append("%s/%s.%zd.sancov", common_flags()->coverage_dir,
536 module_name, internal_getpid());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000537 int fd = CovOpenFile(false /* packed */, module_name);
538 if (fd > 0) {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000539 internal_write(fd, offsets.data(), offsets.size() * sizeof(u32));
540 internal_close(fd);
541 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(),
542 vb - old_vb);
543 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000544 }
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000545 }
546 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000547 if (cov_fd >= 0)
548 internal_close(cov_fd);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000549 coverage_data.DumpCallerCalleePairs();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000550 coverage_data.DumpTrace();
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000551#endif // !SANITIZER_WINDOWS
552}
553
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000554void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
555 if (!args) return;
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000556 if (!common_flags()->coverage) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000557 cov_sandboxed = args->coverage_sandboxed;
558 if (!cov_sandboxed) return;
559 cov_fd = args->coverage_fd;
560 cov_max_block_size = args->coverage_max_block_size;
561 if (cov_fd < 0)
562 // Pre-open the file now. The sandbox won't allow us to do it later.
Sergey Matveev83f91e72014-05-21 13:43:52 +0000563 cov_fd = CovOpenFile(true /* packed */, 0);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000564}
565
Sergey Matveev83f91e72014-05-21 13:43:52 +0000566int MaybeOpenCovFile(const char *name) {
567 CHECK(name);
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000568 if (!common_flags()->coverage) return -1;
Sergey Matveev83f91e72014-05-21 13:43:52 +0000569 return CovOpenFile(true /* packed */, name);
570}
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000571
572void CovBeforeFork() {
573 coverage_data.BeforeFork();
574}
575
576void CovAfterFork(int child_pid) {
577 coverage_data.AfterFork(child_pid);
578}
579
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000580} // namespace __sanitizer
581
582extern "C" {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000583SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000584 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
585 guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000586}
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000587SANITIZER_INTERFACE_ATTRIBUTE void
588__sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
589 coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
590 callee, callee_cache16, 16);
591}
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000592SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() { CovDump(); }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000593SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
594 coverage_data.Init();
595}
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000596SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_module_init(s32 **guards,
597 uptr npcs) {
598 coverage_data.InitializeGuards(guards, npcs);
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000599 if (!common_flags()->coverage || !common_flags()->coverage_direct)
600 return;
601 if (SANITIZER_ANDROID) {
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000602 // dlopen/dlclose interceptors do not work on Android, so we rely on
603 // Extend() calls to update .sancov.map.
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000604 CovUpdateMapping(GET_CALLER_PC());
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000605 }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000606 coverage_data.Extend(npcs);
607}
Sergey Matveev83f91e72014-05-21 13:43:52 +0000608SANITIZER_INTERFACE_ATTRIBUTE
609sptr __sanitizer_maybe_open_cov_file(const char *name) {
610 return MaybeOpenCovFile(name);
611}
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000612SANITIZER_INTERFACE_ATTRIBUTE
613uptr __sanitizer_get_total_unique_coverage() {
614 return atomic_load(&coverage_counter, memory_order_relaxed);
615}
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000616
617SANITIZER_INTERFACE_ATTRIBUTE
618void __sanitizer_cov_trace_func_enter(uptr *cache) {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000619 coverage_data.TraceBasicBlock(cache);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000620}
621SANITIZER_INTERFACE_ATTRIBUTE
622void __sanitizer_cov_trace_basic_block(uptr *cache) {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000623 coverage_data.TraceBasicBlock(cache);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000624}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000625} // extern "C"