blob: 0094c61b5464955276c4dc9dae0e0442380fea3c [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();
62 void Extend(uptr npcs);
63 void Add(uptr pc);
64
65 uptr *data();
66 uptr size();
67
68 private:
69 // Maximal size pc array may ever grow.
70 // We MmapNoReserve this space to ensure that the array is contiguous.
71 static const uptr kPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
72 // The amount file mapping for the pc array is grown by.
73 static const uptr kPcArrayMmapSize = 64 * 1024;
74
75 // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
76 // much RAM as it really needs.
77 uptr *pc_array;
78 // Index of the first available pc_array slot.
79 atomic_uintptr_t pc_array_index;
80 // Array size.
81 atomic_uintptr_t pc_array_size;
82 // Current file mapped size of the pc array.
83 uptr pc_array_mapped_size;
84 // Descriptor of the file mapped pc array.
85 int pc_fd;
86 StaticSpinMutex mu;
87
88 void DirectInit();
89};
90
91static CoverageData coverage_data;
92
93void CoverageData::DirectInit() {
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +000094 InternalScopedString path(1024);
95 internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
96 common_flags()->coverage_dir, internal_getpid());
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000097 pc_fd = OpenFile(path.data(), true);
98 if (internal_iserror(pc_fd)) {
99 Report(" Coverage: failed to open %s for writing\n", path.data());
100 Die();
101 }
102
103 atomic_store(&pc_array_size, 0, memory_order_relaxed);
104 pc_array_mapped_size = 0;
105
106 CovUpdateMapping();
107}
108
109void CoverageData::Init() {
110 pc_array = reinterpret_cast<uptr *>(
111 MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
112 if (common_flags()->coverage_direct) {
113 DirectInit();
114 } else {
115 pc_fd = 0;
116 atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
117 }
118}
119
120// Extend coverage PC array to fit additional npcs elements.
121void CoverageData::Extend(uptr npcs) {
122 // If pc_fd=0, pc array is a huge anonymous mapping that does not need to be
123 // resized.
124 if (!pc_fd) return;
125 SpinMutexLock l(&mu);
126
127 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
128 size += npcs * sizeof(uptr);
129
130 if (size > pc_array_mapped_size) {
131 uptr new_mapped_size = pc_array_mapped_size;
132 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
133
134 // Extend the file and map the new space at the end of pc_array.
135 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
136 int err;
137 if (internal_iserror(res, &err)) {
138 Printf("failed to extend raw coverage file: %d\n", err);
139 Die();
140 }
141 void *p = MapWritableFileToMemory(pc_array + pc_array_mapped_size,
142 new_mapped_size - pc_array_mapped_size,
143 pc_fd, pc_array_mapped_size);
144 CHECK_EQ(p, pc_array + pc_array_mapped_size);
145 pc_array_mapped_size = new_mapped_size;
146 }
147
148 atomic_store(&pc_array_size, size, memory_order_release);
Evgeniy Stepanovbb2fc7e2014-06-03 12:15:43 +0000149
150 if (SANITIZER_ANDROID) {
151 // dlopen/dlclose interceptors do not work on Android, so we rely on
152 // Extend() calls to update .sancov.map.
153 CovUpdateMapping();
154 }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000155}
156
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000157// Simply add the pc into the vector under lock. If the function is called more
158// than once for a given PC it will be inserted multiple times, which is fine.
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000159void CoverageData::Add(uptr pc) {
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000160 if (!pc_array) return;
161 uptr idx = atomic_fetch_add(&pc_array_index, 1, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000162 CHECK_LT(idx * sizeof(uptr),
163 atomic_load(&pc_array_size, memory_order_acquire));
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000164 pc_array[idx] = pc;
165}
166
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000167uptr *CoverageData::data() {
168 return pc_array;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000169}
170
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000171uptr CoverageData::size() {
172 return atomic_load(&pc_array_index, memory_order_relaxed);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000173}
174
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000175// Block layout for packed file format: header, followed by module name (no
176// trailing zero), followed by data blob.
177struct CovHeader {
178 int pid;
179 unsigned int module_name_length;
180 unsigned int data_length;
181};
182
183static void CovWritePacked(int pid, const char *module, const void *blob,
184 unsigned int blob_size) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000185 if (cov_fd < 0) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000186 unsigned module_name_length = internal_strlen(module);
187 CovHeader header = {pid, module_name_length, blob_size};
188
189 if (cov_max_block_size == 0) {
190 // Writing to a file. Just go ahead.
191 internal_write(cov_fd, &header, sizeof(header));
192 internal_write(cov_fd, module, module_name_length);
193 internal_write(cov_fd, blob, blob_size);
194 } else {
195 // Writing to a socket. We want to split the data into appropriately sized
196 // blocks.
197 InternalScopedBuffer<char> block(cov_max_block_size);
198 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
199 uptr header_size_with_module = sizeof(header) + module_name_length;
200 CHECK_LT(header_size_with_module, cov_max_block_size);
201 unsigned int max_payload_size =
202 cov_max_block_size - header_size_with_module;
203 char *block_pos = block.data();
204 internal_memcpy(block_pos, &header, sizeof(header));
205 block_pos += sizeof(header);
206 internal_memcpy(block_pos, module, module_name_length);
207 block_pos += module_name_length;
208 char *block_data_begin = block_pos;
209 char *blob_pos = (char *)blob;
210 while (blob_size > 0) {
211 unsigned int payload_size = Min(blob_size, max_payload_size);
212 blob_size -= payload_size;
213 internal_memcpy(block_data_begin, blob_pos, payload_size);
214 blob_pos += payload_size;
215 ((CovHeader *)block.data())->data_length = payload_size;
216 internal_write(cov_fd, block.data(),
217 header_size_with_module + payload_size);
218 }
219 }
220}
221
Sergey Matveev83f91e72014-05-21 13:43:52 +0000222// If packed = false: <name>.<pid>.<sancov> (name = module name).
223// If packed = true and name == 0: <pid>.<sancov>.<packed>.
224// If packed = true and name != 0: <name>.<sancov>.<packed> (name is
225// user-supplied).
226static int CovOpenFile(bool packed, const char* name) {
227 InternalScopedBuffer<char> path(1024);
228 if (!packed) {
229 CHECK(name);
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000230 Printf("%s\n", common_flags()->coverage_dir);
231 internal_snprintf((char *)path.data(), path.size(), "%s/%s.%zd.sancov",
232 common_flags()->coverage_dir, name, internal_getpid());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000233 } else {
234 if (!name)
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000235 internal_snprintf((char *)path.data(), path.size(),
236 "%s/%zd.sancov.packed", common_flags()->coverage_dir,
Sergey Matveev83f91e72014-05-21 13:43:52 +0000237 internal_getpid());
238 else
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000239 internal_snprintf((char *)path.data(), path.size(), "%s/%s.sancov.packed",
240 common_flags()->coverage_dir, name);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000241 }
242 uptr fd = OpenFile(path.data(), true);
243 if (internal_iserror(fd)) {
244 Report(" SanitizerCoverage: failed to open %s for writing\n", path.data());
245 return -1;
246 }
247 return fd;
248}
249
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000250// Dump the coverage on disk.
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000251static void CovDump() {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000252 if (!common_flags()->coverage || common_flags()->coverage_direct) return;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000253#if !SANITIZER_WINDOWS
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000254 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
255 return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000256 uptr size = coverage_data.size();
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000257 InternalMmapVector<u32> offsets(size);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000258 uptr *vb = coverage_data.data();
259 uptr *ve = vb + size;
260 SortArray(vb, size);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000261 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000262 uptr mb, me, off, prot;
263 InternalScopedBuffer<char> module(4096);
264 InternalScopedBuffer<char> path(4096 * 2);
265 for (int i = 0;
266 proc_maps.Next(&mb, &me, &off, module.data(), module.size(), &prot);
267 i++) {
268 if ((prot & MemoryMappingLayout::kProtectionExecute) == 0)
269 continue;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000270 while (vb < ve && *vb < mb) vb++;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000271 if (vb >= ve) break;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000272 if (*vb < me) {
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000273 offsets.clear();
274 const uptr *old_vb = vb;
275 CHECK_LE(off, *vb);
276 for (; vb < ve && *vb < me; vb++) {
277 uptr diff = *vb - (i ? mb : 0) + off;
278 CHECK_LE(diff, 0xffffffffU);
279 offsets.push_back(static_cast<u32>(diff));
280 }
281 char *module_name = StripModuleName(module.data());
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000282 if (cov_sandboxed) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000283 if (cov_fd >= 0) {
284 CovWritePacked(internal_getpid(), module_name, offsets.data(),
285 offsets.size() * sizeof(u32));
286 VReport(1, " CovDump: %zd PCs written to packed file\n", vb - old_vb);
287 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000288 } else {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000289 // One file per module per process.
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000290 internal_snprintf((char *)path.data(), path.size(), "%s/%s.%zd.sancov",
291 common_flags()->coverage_dir, module_name,
292 internal_getpid());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000293 int fd = CovOpenFile(false /* packed */, module_name);
294 if (fd > 0) {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000295 internal_write(fd, offsets.data(), offsets.size() * sizeof(u32));
296 internal_close(fd);
297 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(),
298 vb - old_vb);
299 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000300 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000301 InternalFree(module_name);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000302 }
303 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000304 if (cov_fd >= 0)
305 internal_close(cov_fd);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000306#endif // !SANITIZER_WINDOWS
307}
308
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000309void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
310 if (!args) return;
311 if (!common_flags()->coverage) return;
312 cov_sandboxed = args->coverage_sandboxed;
313 if (!cov_sandboxed) return;
314 cov_fd = args->coverage_fd;
315 cov_max_block_size = args->coverage_max_block_size;
316 if (cov_fd < 0)
317 // Pre-open the file now. The sandbox won't allow us to do it later.
Sergey Matveev83f91e72014-05-21 13:43:52 +0000318 cov_fd = CovOpenFile(true /* packed */, 0);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000319}
320
Sergey Matveev83f91e72014-05-21 13:43:52 +0000321int MaybeOpenCovFile(const char *name) {
322 CHECK(name);
323 if (!common_flags()->coverage) return -1;
324 return CovOpenFile(true /* packed */, name);
325}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000326} // namespace __sanitizer
327
328extern "C" {
Kostya Serebryany714c67c2014-01-17 11:00:30 +0000329SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov() {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000330 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()));
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000331}
332SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() { CovDump(); }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000333SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
334 coverage_data.Init();
335}
336SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_module_init(uptr npcs) {
337 coverage_data.Extend(npcs);
338}
Sergey Matveev83f91e72014-05-21 13:43:52 +0000339SANITIZER_INTERFACE_ATTRIBUTE
340sptr __sanitizer_maybe_open_cov_file(const char *name) {
341 return MaybeOpenCovFile(name);
342}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000343} // extern "C"