blob: 206d07ccd59c8091c179a4f35fbfef9928ec7e9a [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:
Bob Wilsona08e9ac2013-11-15 07:18:15 +000015// if (*Guard) {
Kostya Serebryany714c67c2014-01-17 11:00:30 +000016// __sanitizer_cov();
Bob Wilsona08e9ac2013-11-15 07:18:15 +000017// *Guard = 1;
18// }
Kostya Serebryany714c67c2014-01-17 11:00:30 +000019// It's fine to call __sanitizer_cov more than once for a given block.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000020//
21// Run-time:
Kostya Serebryany714c67c2014-01-17 11:00:30 +000022// - __sanitizer_cov(): record that we've executed the PC (GET_CALLER_PC).
Bob Wilsona08e9ac2013-11-15 07:18:15 +000023// - __sanitizer_cov_dump: dump the coverage data to disk.
24// For every module of the current process that has coverage data
25// this will create a file module_name.PID.sancov. The file format is simple:
26// it's just a sorted sequence of 4-byte offsets in the module.
27//
28// Eventually, this coverage implementation should be obsoleted by a more
29// powerful general purpose Clang/LLVM coverage instrumentation.
30// Consider this implementation as prototype.
31//
32// FIXME: support (or at least test with) dlclose.
33//===----------------------------------------------------------------------===//
34
35#include "sanitizer_allocator_internal.h"
36#include "sanitizer_common.h"
37#include "sanitizer_libc.h"
38#include "sanitizer_mutex.h"
39#include "sanitizer_procmaps.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000040#include "sanitizer_stacktrace.h"
Bob Wilsona08e9ac2013-11-15 07:18:15 +000041#include "sanitizer_flags.h"
42
Kostya Serebryany8b530e12014-04-30 10:40:48 +000043atomic_uint32_t dump_once_guard; // Ensure that CovDump runs only once.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000044
Kostya Serebryany8b530e12014-04-30 10:40:48 +000045// pc_array is the array containing the covered PCs.
Sergey Matveev6cb47a082014-05-19 12:53:03 +000046// To make the pc_array thread- and async-signal-safe it has to be large enough.
Kostya Serebryany8b530e12014-04-30 10:40:48 +000047// 128M counters "ought to be enough for anybody" (4M on 32-bit).
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000048
49// With coverage_direct=1 in ASAN_OPTIONS, pc_array memory is mapped to a file.
50// In this mode, __sanitizer_cov_dump does nothing, and CovUpdateMapping()
51// dump current memory layout to another file.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000052
Sergey Matveev6cb47a082014-05-19 12:53:03 +000053static bool cov_sandboxed = false;
54static int cov_fd = kInvalidFd;
55static unsigned int cov_max_block_size = 0;
56
Bob Wilsona08e9ac2013-11-15 07:18:15 +000057namespace __sanitizer {
58
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000059class CoverageData {
60 public:
61 void Init();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +000062 void BeforeFork();
63 void AfterFork(int child_pid);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000064 void Extend(uptr npcs);
65 void Add(uptr pc);
66
67 uptr *data();
68 uptr size();
69
70 private:
71 // Maximal size pc array may ever grow.
72 // We MmapNoReserve this space to ensure that the array is contiguous.
73 static const uptr kPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
74 // The amount file mapping for the pc array is grown by.
75 static const uptr kPcArrayMmapSize = 64 * 1024;
76
77 // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
78 // much RAM as it really needs.
79 uptr *pc_array;
80 // Index of the first available pc_array slot.
81 atomic_uintptr_t pc_array_index;
82 // Array size.
83 atomic_uintptr_t pc_array_size;
84 // Current file mapped size of the pc array.
85 uptr pc_array_mapped_size;
86 // Descriptor of the file mapped pc array.
87 int pc_fd;
88 StaticSpinMutex mu;
89
Evgeniy Stepanovce984522014-06-03 15:27:15 +000090 void DirectOpen();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +000091 void ReInit();
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000092};
93
94static CoverageData coverage_data;
95
Evgeniy Stepanovce984522014-06-03 15:27:15 +000096void CoverageData::DirectOpen() {
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +000097 InternalScopedString path(1024);
98 internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
99 common_flags()->coverage_dir, internal_getpid());
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000100 pc_fd = OpenFile(path.data(), true);
101 if (internal_iserror(pc_fd)) {
102 Report(" Coverage: failed to open %s for writing\n", path.data());
103 Die();
104 }
105
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000106 pc_array_mapped_size = 0;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000107 CovUpdateMapping();
108}
109
110void CoverageData::Init() {
111 pc_array = reinterpret_cast<uptr *>(
112 MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000113 pc_fd = kInvalidFd;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000114 if (common_flags()->coverage_direct) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000115 atomic_store(&pc_array_size, 0, memory_order_relaxed);
116 atomic_store(&pc_array_index, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000117 } else {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000118 atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000119 atomic_store(&pc_array_index, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000120 }
121}
122
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000123void CoverageData::ReInit() {
124 internal_munmap(pc_array, sizeof(uptr) * kPcArrayMaxSize);
125 if (pc_fd != kInvalidFd) internal_close(pc_fd);
126 if (common_flags()->coverage_direct) {
127 // In memory-mapped mode we must extend the new file to the known array
128 // size.
129 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
130 Init();
131 if (size) Extend(size);
132 } else {
133 Init();
134 }
135}
136
137void CoverageData::BeforeFork() {
138 mu.Lock();
139}
140
141void CoverageData::AfterFork(int child_pid) {
142 // We are single-threaded so it's OK to release the lock early.
143 mu.Unlock();
144 if (child_pid == 0) ReInit();
145}
146
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000147// Extend coverage PC array to fit additional npcs elements.
148void CoverageData::Extend(uptr npcs) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000149 if (!common_flags()->coverage_direct) return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000150 SpinMutexLock l(&mu);
151
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000152 if (pc_fd == kInvalidFd) DirectOpen();
153 CHECK_NE(pc_fd, kInvalidFd);
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000154
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000155 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
156 size += npcs * sizeof(uptr);
157
158 if (size > pc_array_mapped_size) {
159 uptr new_mapped_size = pc_array_mapped_size;
160 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
161
162 // Extend the file and map the new space at the end of pc_array.
163 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
164 int err;
165 if (internal_iserror(res, &err)) {
166 Printf("failed to extend raw coverage file: %d\n", err);
167 Die();
168 }
169 void *p = MapWritableFileToMemory(pc_array + pc_array_mapped_size,
170 new_mapped_size - pc_array_mapped_size,
171 pc_fd, pc_array_mapped_size);
172 CHECK_EQ(p, pc_array + pc_array_mapped_size);
173 pc_array_mapped_size = new_mapped_size;
174 }
175
176 atomic_store(&pc_array_size, size, memory_order_release);
Evgeniy Stepanovbb2fc7e2014-06-03 12:15:43 +0000177
178 if (SANITIZER_ANDROID) {
179 // dlopen/dlclose interceptors do not work on Android, so we rely on
180 // Extend() calls to update .sancov.map.
181 CovUpdateMapping();
182 }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000183}
184
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000185// Simply add the pc into the vector under lock. If the function is called more
186// than once for a given PC it will be inserted multiple times, which is fine.
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000187void CoverageData::Add(uptr pc) {
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000188 if (!pc_array) return;
189 uptr idx = atomic_fetch_add(&pc_array_index, 1, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000190 CHECK_LT(idx * sizeof(uptr),
191 atomic_load(&pc_array_size, memory_order_acquire));
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000192 pc_array[idx] = pc;
193}
194
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000195uptr *CoverageData::data() {
196 return pc_array;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000197}
198
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000199uptr CoverageData::size() {
200 return atomic_load(&pc_array_index, memory_order_relaxed);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000201}
202
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000203// Block layout for packed file format: header, followed by module name (no
204// trailing zero), followed by data blob.
205struct CovHeader {
206 int pid;
207 unsigned int module_name_length;
208 unsigned int data_length;
209};
210
211static void CovWritePacked(int pid, const char *module, const void *blob,
212 unsigned int blob_size) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000213 if (cov_fd < 0) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000214 unsigned module_name_length = internal_strlen(module);
215 CovHeader header = {pid, module_name_length, blob_size};
216
217 if (cov_max_block_size == 0) {
218 // Writing to a file. Just go ahead.
219 internal_write(cov_fd, &header, sizeof(header));
220 internal_write(cov_fd, module, module_name_length);
221 internal_write(cov_fd, blob, blob_size);
222 } else {
223 // Writing to a socket. We want to split the data into appropriately sized
224 // blocks.
225 InternalScopedBuffer<char> block(cov_max_block_size);
226 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
227 uptr header_size_with_module = sizeof(header) + module_name_length;
228 CHECK_LT(header_size_with_module, cov_max_block_size);
229 unsigned int max_payload_size =
230 cov_max_block_size - header_size_with_module;
231 char *block_pos = block.data();
232 internal_memcpy(block_pos, &header, sizeof(header));
233 block_pos += sizeof(header);
234 internal_memcpy(block_pos, module, module_name_length);
235 block_pos += module_name_length;
236 char *block_data_begin = block_pos;
237 char *blob_pos = (char *)blob;
238 while (blob_size > 0) {
239 unsigned int payload_size = Min(blob_size, max_payload_size);
240 blob_size -= payload_size;
241 internal_memcpy(block_data_begin, blob_pos, payload_size);
242 blob_pos += payload_size;
243 ((CovHeader *)block.data())->data_length = payload_size;
244 internal_write(cov_fd, block.data(),
245 header_size_with_module + payload_size);
246 }
247 }
248}
249
Sergey Matveev83f91e72014-05-21 13:43:52 +0000250// If packed = false: <name>.<pid>.<sancov> (name = module name).
251// If packed = true and name == 0: <pid>.<sancov>.<packed>.
252// If packed = true and name != 0: <name>.<sancov>.<packed> (name is
253// user-supplied).
254static int CovOpenFile(bool packed, const char* name) {
255 InternalScopedBuffer<char> path(1024);
256 if (!packed) {
257 CHECK(name);
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000258 Printf("%s\n", common_flags()->coverage_dir);
259 internal_snprintf((char *)path.data(), path.size(), "%s/%s.%zd.sancov",
260 common_flags()->coverage_dir, name, internal_getpid());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000261 } else {
262 if (!name)
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000263 internal_snprintf((char *)path.data(), path.size(),
264 "%s/%zd.sancov.packed", common_flags()->coverage_dir,
Sergey Matveev83f91e72014-05-21 13:43:52 +0000265 internal_getpid());
266 else
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000267 internal_snprintf((char *)path.data(), path.size(), "%s/%s.sancov.packed",
268 common_flags()->coverage_dir, name);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000269 }
270 uptr fd = OpenFile(path.data(), true);
271 if (internal_iserror(fd)) {
272 Report(" SanitizerCoverage: failed to open %s for writing\n", path.data());
273 return -1;
274 }
275 return fd;
276}
277
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000278// Dump the coverage on disk.
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000279static void CovDump() {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000280 if (!common_flags()->coverage || common_flags()->coverage_direct) return;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000281#if !SANITIZER_WINDOWS
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000282 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
283 return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000284 uptr size = coverage_data.size();
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000285 InternalMmapVector<u32> offsets(size);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000286 uptr *vb = coverage_data.data();
287 uptr *ve = vb + size;
288 SortArray(vb, size);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000289 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000290 uptr mb, me, off, prot;
291 InternalScopedBuffer<char> module(4096);
292 InternalScopedBuffer<char> path(4096 * 2);
293 for (int i = 0;
294 proc_maps.Next(&mb, &me, &off, module.data(), module.size(), &prot);
295 i++) {
296 if ((prot & MemoryMappingLayout::kProtectionExecute) == 0)
297 continue;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000298 while (vb < ve && *vb < mb) vb++;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000299 if (vb >= ve) break;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000300 if (*vb < me) {
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000301 offsets.clear();
302 const uptr *old_vb = vb;
303 CHECK_LE(off, *vb);
304 for (; vb < ve && *vb < me; vb++) {
305 uptr diff = *vb - (i ? mb : 0) + off;
306 CHECK_LE(diff, 0xffffffffU);
307 offsets.push_back(static_cast<u32>(diff));
308 }
309 char *module_name = StripModuleName(module.data());
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000310 if (cov_sandboxed) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000311 if (cov_fd >= 0) {
312 CovWritePacked(internal_getpid(), module_name, offsets.data(),
313 offsets.size() * sizeof(u32));
314 VReport(1, " CovDump: %zd PCs written to packed file\n", vb - old_vb);
315 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000316 } else {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000317 // One file per module per process.
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000318 internal_snprintf((char *)path.data(), path.size(), "%s/%s.%zd.sancov",
319 common_flags()->coverage_dir, module_name,
320 internal_getpid());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000321 int fd = CovOpenFile(false /* packed */, module_name);
322 if (fd > 0) {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000323 internal_write(fd, offsets.data(), offsets.size() * sizeof(u32));
324 internal_close(fd);
325 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(),
326 vb - old_vb);
327 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000328 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000329 InternalFree(module_name);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000330 }
331 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000332 if (cov_fd >= 0)
333 internal_close(cov_fd);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000334#endif // !SANITIZER_WINDOWS
335}
336
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000337void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
338 if (!args) return;
339 if (!common_flags()->coverage) return;
340 cov_sandboxed = args->coverage_sandboxed;
341 if (!cov_sandboxed) return;
342 cov_fd = args->coverage_fd;
343 cov_max_block_size = args->coverage_max_block_size;
344 if (cov_fd < 0)
345 // Pre-open the file now. The sandbox won't allow us to do it later.
Sergey Matveev83f91e72014-05-21 13:43:52 +0000346 cov_fd = CovOpenFile(true /* packed */, 0);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000347}
348
Sergey Matveev83f91e72014-05-21 13:43:52 +0000349int MaybeOpenCovFile(const char *name) {
350 CHECK(name);
351 if (!common_flags()->coverage) return -1;
352 return CovOpenFile(true /* packed */, name);
353}
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000354
355void CovBeforeFork() {
356 coverage_data.BeforeFork();
357}
358
359void CovAfterFork(int child_pid) {
360 coverage_data.AfterFork(child_pid);
361}
362
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000363} // namespace __sanitizer
364
365extern "C" {
Kostya Serebryany714c67c2014-01-17 11:00:30 +0000366SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov() {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000367 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()));
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000368}
369SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() { CovDump(); }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000370SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
371 coverage_data.Init();
372}
373SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_module_init(uptr npcs) {
374 coverage_data.Extend(npcs);
375}
Sergey Matveev83f91e72014-05-21 13:43:52 +0000376SANITIZER_INTERFACE_ATTRIBUTE
377sptr __sanitizer_maybe_open_cov_file(const char *name) {
378 return MaybeOpenCovFile(name);
379}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000380} // extern "C"