blob: eb79f4662d339a2dde56dd9d3f3d784067799e0f [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 Stepanovfe181022014-06-04 12:13:54 +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",
141 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 Stepanov567e5162014-05-27 12:37:52 +0000149 CovUpdateMapping();
150}
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() {
181 internal_munmap(pc_array, sizeof(uptr) * kPcArrayMaxSize);
182 if (pc_fd != kInvalidFd) internal_close(pc_fd);
183 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();
191 }
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 Stepanovfe181022014-06-04 12:13:54 +0000209 if (pc_fd == kInvalidFd) DirectOpen();
210 CHECK_NE(pc_fd, kInvalidFd);
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000211
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000212 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
213 size += npcs * sizeof(uptr);
214
215 if (size > pc_array_mapped_size) {
216 uptr new_mapped_size = pc_array_mapped_size;
217 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
218
219 // Extend the file and map the new space at the end of pc_array.
220 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
221 int err;
222 if (internal_iserror(res, &err)) {
223 Printf("failed to extend raw coverage file: %d\n", err);
224 Die();
225 }
226 void *p = MapWritableFileToMemory(pc_array + pc_array_mapped_size,
227 new_mapped_size - pc_array_mapped_size,
228 pc_fd, pc_array_mapped_size);
229 CHECK_EQ(p, pc_array + pc_array_mapped_size);
230 pc_array_mapped_size = new_mapped_size;
231 }
232
233 atomic_store(&pc_array_size, size, memory_order_release);
234}
235
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000236void CoverageData::InitializeGuards(s32 **guards, uptr n) {
237 for (uptr i = 0; i < n; i++) {
238 uptr idx = atomic_fetch_add(&pc_array_index, 1, memory_order_relaxed);
239 *guards[i] = -static_cast<s32>(idx + 1);
240 }
241}
242
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000243// Atomically add the pc to the vector. The atomically set the guard to 1.
244// If the function is called more than once for a given PC it will
245// be inserted multiple times, which is fine.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000246void CoverageData::Add(uptr pc, u32 *guard) {
247 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
248 s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
249 if (guard_value >= 0) return;
250
251 atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000252 if (!pc_array) return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000253
254 uptr idx = -guard_value - 1;
255 if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
256 return; // May happen after fork when pc_array_index becomes 0.
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000257 CHECK_LT(idx * sizeof(uptr),
258 atomic_load(&pc_array_size, memory_order_acquire));
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000259 pc_array[idx] = pc;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000260 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000261}
262
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000263// Registers a pair caller=>callee.
264// When a given caller is seen for the first time, the callee_cache is added
265// to the global array cc_array, callee_cache[0] is set to caller and
266// callee_cache[1] is set to cache_size.
267// Then we are trying to add callee to callee_cache [2,cache_size) if it is
268// not there yet.
269// If the cache is full we drop the callee (may want to fix this later).
270void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
271 uptr cache_size) {
272 if (!cc_array) return;
273 atomic_uintptr_t *atomic_callee_cache =
274 reinterpret_cast<atomic_uintptr_t *>(callee_cache);
275 uptr zero = 0;
276 if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
277 memory_order_seq_cst)) {
278 uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
279 CHECK_LT(idx * sizeof(uptr),
280 atomic_load(&cc_array_size, memory_order_acquire));
281 callee_cache[1] = cache_size;
282 cc_array[idx] = callee_cache;
283 }
284 CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
285 for (uptr i = 2; i < cache_size; i++) {
286 uptr was = 0;
287 if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000288 memory_order_seq_cst)) {
289 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000290 return;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000291 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000292 if (was == callee) // Already have this callee.
293 return;
294 }
295}
296
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000297uptr *CoverageData::data() {
298 return pc_array;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000299}
300
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000301uptr CoverageData::size() {
302 return atomic_load(&pc_array_index, memory_order_relaxed);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000303}
304
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000305// Block layout for packed file format: header, followed by module name (no
306// trailing zero), followed by data blob.
307struct CovHeader {
308 int pid;
309 unsigned int module_name_length;
310 unsigned int data_length;
311};
312
313static void CovWritePacked(int pid, const char *module, const void *blob,
314 unsigned int blob_size) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000315 if (cov_fd < 0) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000316 unsigned module_name_length = internal_strlen(module);
317 CovHeader header = {pid, module_name_length, blob_size};
318
319 if (cov_max_block_size == 0) {
320 // Writing to a file. Just go ahead.
321 internal_write(cov_fd, &header, sizeof(header));
322 internal_write(cov_fd, module, module_name_length);
323 internal_write(cov_fd, blob, blob_size);
324 } else {
325 // Writing to a socket. We want to split the data into appropriately sized
326 // blocks.
327 InternalScopedBuffer<char> block(cov_max_block_size);
328 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
329 uptr header_size_with_module = sizeof(header) + module_name_length;
330 CHECK_LT(header_size_with_module, cov_max_block_size);
331 unsigned int max_payload_size =
332 cov_max_block_size - header_size_with_module;
333 char *block_pos = block.data();
334 internal_memcpy(block_pos, &header, sizeof(header));
335 block_pos += sizeof(header);
336 internal_memcpy(block_pos, module, module_name_length);
337 block_pos += module_name_length;
338 char *block_data_begin = block_pos;
Alexey Samsonov4925fd42014-11-13 22:40:59 +0000339 const char *blob_pos = (const char *)blob;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000340 while (blob_size > 0) {
341 unsigned int payload_size = Min(blob_size, max_payload_size);
342 blob_size -= payload_size;
343 internal_memcpy(block_data_begin, blob_pos, payload_size);
344 blob_pos += payload_size;
345 ((CovHeader *)block.data())->data_length = payload_size;
346 internal_write(cov_fd, block.data(),
347 header_size_with_module + payload_size);
348 }
349 }
350}
351
Sergey Matveev83f91e72014-05-21 13:43:52 +0000352// If packed = false: <name>.<pid>.<sancov> (name = module name).
353// If packed = true and name == 0: <pid>.<sancov>.<packed>.
354// If packed = true and name != 0: <name>.<sancov>.<packed> (name is
355// user-supplied).
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000356static int CovOpenFile(bool packed, const char *name,
357 const char *extension = "sancov") {
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000358 InternalScopedString path(kMaxPathLength);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000359 if (!packed) {
360 CHECK(name);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000361 path.append("%s/%s.%zd.%s", common_flags()->coverage_dir, name,
362 internal_getpid(), extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000363 } else {
364 if (!name)
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000365 path.append("%s/%zd.%s.packed", common_flags()->coverage_dir,
366 internal_getpid(), extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000367 else
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000368 path.append("%s/%s.%s.packed", common_flags()->coverage_dir, name,
369 extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000370 }
371 uptr fd = OpenFile(path.data(), true);
372 if (internal_iserror(fd)) {
373 Report(" SanitizerCoverage: failed to open %s for writing\n", path.data());
374 return -1;
375 }
376 return fd;
377}
378
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000379// Dump trace PCs and trace events into two separate files.
380void CoverageData::DumpTrace() {
381 uptr max_idx = tr_event_array_index;
382 if (!max_idx) return;
383 auto sym = Symbolizer::GetOrInit();
384 if (!sym)
385 return;
386 InternalScopedString out(32 << 20);
387 for (uptr i = 0; i < max_idx; i++) {
388 u32 pc_idx = tr_event_array[i];
389 TracedPc *t = &tr_pc_array[pc_idx];
390 if (!t->module_name) {
391 const char *module_name = "<unknown>";
392 uptr module_address = 0;
393 sym->GetModuleNameAndOffsetForPC(t->pc, &module_name, &module_address);
394 t->module_name = internal_strdup(module_name);
395 t->module_offset = module_address;
396 out.append("%s 0x%zx\n", t->module_name, t->module_offset);
397 }
398 }
399 int fd = CovOpenFile(false, "trace-points");
400 if (fd < 0) return;
401 internal_write(fd, out.data(), out.length());
402 internal_close(fd);
403
404 fd = CovOpenFile(false, "trace-events");
405 if (fd < 0) return;
406 internal_write(fd, tr_event_array, max_idx * sizeof(tr_event_array[0]));
407 internal_close(fd);
408 VReport(1, " CovDump: Trace: %zd PCs written\n", tr_pc_array_index);
409 VReport(1, " CovDump: Trace: %zd Events written\n", tr_event_array_index);
410}
411
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000412// This function dumps the caller=>callee pairs into a file as a sequence of
413// lines like "module_name offset".
414void CoverageData::DumpCallerCalleePairs() {
415 uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
416 if (!max_idx) return;
417 auto sym = Symbolizer::GetOrInit();
418 if (!sym)
419 return;
Kostya Serebryany40aa4a22014-10-31 19:49:46 +0000420 InternalScopedString out(32 << 20);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000421 uptr total = 0;
422 for (uptr i = 0; i < max_idx; i++) {
423 uptr *cc_cache = cc_array[i];
424 CHECK(cc_cache);
425 uptr caller = cc_cache[0];
426 uptr n_callees = cc_cache[1];
427 const char *caller_module_name = "<unknown>";
428 uptr caller_module_address = 0;
429 sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
430 &caller_module_address);
431 for (uptr j = 2; j < n_callees; j++) {
432 uptr callee = cc_cache[j];
433 if (!callee) break;
434 total++;
435 const char *callee_module_name = "<unknown>";
436 uptr callee_module_address = 0;
437 sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
438 &callee_module_address);
439 out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
440 caller_module_address, callee_module_name,
441 callee_module_address);
442 }
443 }
444 int fd = CovOpenFile(false, "caller-callee");
445 if (fd < 0) return;
446 internal_write(fd, out.data(), out.length());
447 internal_close(fd);
448 VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
449}
450
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000451// Record the current PC into the event buffer.
452// Every event is a u32 value (index in tr_pc_array_index) so we compute
453// it once and then cache in the provided 'cache' storage.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000454void CoverageData::TraceBasicBlock(uptr *cache) {
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000455 CHECK(common_flags()->coverage);
456 uptr idx = *cache;
457 if (!idx) {
458 CHECK_LT(tr_pc_array_index, kTrPcArrayMaxSize);
459 idx = tr_pc_array_index++;
460 TracedPc *t = &tr_pc_array[idx];
461 t->pc = GET_CALLER_PC();
462 *cache = idx;
463 CHECK_LT(idx, 1U << 31);
464 }
465 CHECK_LT(tr_event_array_index, tr_event_array_size);
466 tr_event_array[tr_event_array_index] = static_cast<u32>(idx);
467 tr_event_array_index++;
468}
469
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000470static void CovDumpAsBitSet() {
471 if (!common_flags()->coverage_bitset) return;
472 if (!coverage_data.size()) return;
473 int fd = CovOpenFile(/* packed */false, "combined", "bitset-sancov");
474 if (fd < 0) return;
475 uptr n = coverage_data.size();
476 uptr n_set_bits = 0;
477 InternalScopedBuffer<char> out(n);
478 for (uptr i = 0; i < n; i++) {
479 uptr pc = coverage_data.data()[i];
480 out[i] = pc ? '1' : '0';
481 if (pc)
482 n_set_bits++;
483 }
484 internal_write(fd, out.data(), n);
485 internal_close(fd);
486 VReport(1, " CovDump: bitset of %zd bits written, %zd bits are set\n", n,
487 n_set_bits);
488}
489
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000490// Dump the coverage on disk.
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000491static void CovDump() {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000492 if (!common_flags()->coverage || common_flags()->coverage_direct) return;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000493#if !SANITIZER_WINDOWS
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000494 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
495 return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000496 CovDumpAsBitSet();
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000497 uptr size = coverage_data.size();
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000498 InternalMmapVector<u32> offsets(size);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000499 uptr *vb = coverage_data.data();
500 uptr *ve = vb + size;
501 SortArray(vb, size);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000502 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000503 uptr mb, me, off, prot;
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000504 InternalScopedString module(kMaxPathLength);
505 InternalScopedString path(kMaxPathLength);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000506 for (int i = 0;
507 proc_maps.Next(&mb, &me, &off, module.data(), module.size(), &prot);
508 i++) {
509 if ((prot & MemoryMappingLayout::kProtectionExecute) == 0)
510 continue;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000511 while (vb < ve && *vb < mb) vb++;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000512 if (vb >= ve) break;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000513 if (*vb < me) {
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000514 offsets.clear();
515 const uptr *old_vb = vb;
516 CHECK_LE(off, *vb);
517 for (; vb < ve && *vb < me; vb++) {
518 uptr diff = *vb - (i ? mb : 0) + off;
519 CHECK_LE(diff, 0xffffffffU);
520 offsets.push_back(static_cast<u32>(diff));
521 }
Alexey Samsonov26ca05a2014-11-04 19:34:29 +0000522 const char *module_name = StripModuleName(module.data());
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000523 if (cov_sandboxed) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000524 if (cov_fd >= 0) {
525 CovWritePacked(internal_getpid(), module_name, offsets.data(),
526 offsets.size() * sizeof(u32));
527 VReport(1, " CovDump: %zd PCs written to packed file\n", vb - old_vb);
528 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000529 } else {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000530 // One file per module per process.
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000531 path.clear();
532 path.append("%s/%s.%zd.sancov", common_flags()->coverage_dir,
533 module_name, internal_getpid());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000534 int fd = CovOpenFile(false /* packed */, module_name);
535 if (fd > 0) {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000536 internal_write(fd, offsets.data(), offsets.size() * sizeof(u32));
537 internal_close(fd);
538 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(),
539 vb - old_vb);
540 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000541 }
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000542 }
543 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000544 if (cov_fd >= 0)
545 internal_close(cov_fd);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000546 coverage_data.DumpCallerCalleePairs();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000547 coverage_data.DumpTrace();
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000548#endif // !SANITIZER_WINDOWS
549}
550
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000551void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
552 if (!args) return;
553 if (!common_flags()->coverage) return;
554 cov_sandboxed = args->coverage_sandboxed;
555 if (!cov_sandboxed) return;
556 cov_fd = args->coverage_fd;
557 cov_max_block_size = args->coverage_max_block_size;
558 if (cov_fd < 0)
559 // Pre-open the file now. The sandbox won't allow us to do it later.
Sergey Matveev83f91e72014-05-21 13:43:52 +0000560 cov_fd = CovOpenFile(true /* packed */, 0);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000561}
562
Sergey Matveev83f91e72014-05-21 13:43:52 +0000563int MaybeOpenCovFile(const char *name) {
564 CHECK(name);
565 if (!common_flags()->coverage) return -1;
566 return CovOpenFile(true /* packed */, name);
567}
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000568
569void CovBeforeFork() {
570 coverage_data.BeforeFork();
571}
572
573void CovAfterFork(int child_pid) {
574 coverage_data.AfterFork(child_pid);
575}
576
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000577} // namespace __sanitizer
578
579extern "C" {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000580SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000581 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
582 guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000583}
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000584SANITIZER_INTERFACE_ATTRIBUTE void
585__sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
586 coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
587 callee, callee_cache16, 16);
588}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000589SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() { CovDump(); }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000590SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
591 coverage_data.Init();
592}
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000593SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_module_init(s32 **guards,
594 uptr npcs) {
595 coverage_data.InitializeGuards(guards, npcs);
596 if (!common_flags()->coverage || !common_flags()->coverage_direct)
597 return;
Evgeniy Stepanovdfa54392014-06-11 15:11:26 +0000598 if (SANITIZER_ANDROID) {
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000599 // dlopen/dlclose interceptors do not work on Android, so we rely on
600 // Extend() calls to update .sancov.map.
601 CovUpdateMapping(GET_CALLER_PC());
602 }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000603 coverage_data.Extend(npcs);
604}
Sergey Matveev83f91e72014-05-21 13:43:52 +0000605SANITIZER_INTERFACE_ATTRIBUTE
606sptr __sanitizer_maybe_open_cov_file(const char *name) {
607 return MaybeOpenCovFile(name);
608}
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000609SANITIZER_INTERFACE_ATTRIBUTE
610uptr __sanitizer_get_total_unique_coverage() {
611 return atomic_load(&coverage_counter, memory_order_relaxed);
612}
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000613
614SANITIZER_INTERFACE_ATTRIBUTE
615void __sanitizer_cov_trace_func_enter(uptr *cache) {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000616 coverage_data.TraceBasicBlock(cache);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000617}
618SANITIZER_INTERFACE_ATTRIBUTE
619void __sanitizer_cov_trace_basic_block(uptr *cache) {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000620 coverage_data.TraceBasicBlock(cache);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000621}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000622} // extern "C"