blob: 19f147f42d4e311b630ca0542ea61725b2cd878c [file] [log] [blame]
Alexey Samsonove5f58952012-06-04 13:50:10 +00001//===-- asan_allocator.cc -------------------------------------------------===//
Kostya Serebryany1e172b42011-11-30 01:07:02 +00002//
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// This file is a part of AddressSanitizer, an address sanity checker.
11//
12// Implementation of ASan's memory allocator.
13// Evey piece of memory (AsanChunk) allocated by the allocator
14// has a left redzone of REDZONE bytes and
15// a right redzone such that the end of the chunk is aligned by REDZONE
16// (i.e. the right redzone is between 0 and REDZONE-1).
17// The left redzone is always poisoned.
18// The right redzone is poisoned on malloc, the body is poisoned on free.
19// Once freed, a chunk is moved to a quarantine (fifo list).
20// After quarantine, a chunk is returned to freelists.
21//
22// The left redzone contains ASan's internal data and the stack trace of
23// the malloc call.
24// Once freed, the body of the chunk contains the stack trace of the free call.
25//
26//===----------------------------------------------------------------------===//
27
28#include "asan_allocator.h"
29#include "asan_interceptors.h"
30#include "asan_interface.h"
31#include "asan_internal.h"
32#include "asan_lock.h"
33#include "asan_mapping.h"
34#include "asan_stats.h"
35#include "asan_thread.h"
36#include "asan_thread_registry.h"
37
Timur Iskhodzhanov8c505ef2012-05-21 14:25:36 +000038#if defined(_WIN32) && !defined(__clang__)
Kostya Serebryany85822082012-01-30 20:55:02 +000039#include <intrin.h>
40#endif
41
Kostya Serebryany1e172b42011-11-30 01:07:02 +000042namespace __asan {
43
44#define REDZONE FLAG_redzone
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000045static const uptr kMinAllocSize = REDZONE * 2;
Kostya Serebryanyee392552012-05-31 15:02:07 +000046static const u64 kMaxAvailableRam = 128ULL << 30; // 128G
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000047static const uptr kMaxThreadLocalQuarantine = 1 << 20; // 1M
Evgeniy Stepanov788e1d72012-02-16 13:35:11 +000048
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000049static const uptr kMinMmapSize = (ASAN_LOW_MEMORY) ? 4UL << 17 : 4UL << 20;
50static const uptr kMaxSizeForThreadLocalFreeList =
Evgeniy Stepanov8ae44ac2012-02-27 13:07:29 +000051 (ASAN_LOW_MEMORY) ? 1 << 15 : 1 << 17;
Kostya Serebryany1e172b42011-11-30 01:07:02 +000052
53// Size classes less than kMallocSizeClassStep are powers of two.
54// All other size classes are multiples of kMallocSizeClassStep.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000055static const uptr kMallocSizeClassStepLog = 26;
56static const uptr kMallocSizeClassStep = 1UL << kMallocSizeClassStepLog;
Kostya Serebryany1e172b42011-11-30 01:07:02 +000057
Kostya Serebryany9aead372012-05-31 14:11:07 +000058static const uptr kMaxAllowedMallocSize =
Evgeniy Stepanov8ae44ac2012-02-27 13:07:29 +000059 (__WORDSIZE == 32) ? 3UL << 30 : 8UL << 30;
Kostya Serebryany1e172b42011-11-30 01:07:02 +000060
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000061static inline bool IsAligned(uptr a, uptr alignment) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +000062 return (a & (alignment - 1)) == 0;
63}
64
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000065static inline uptr Log2(uptr x) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +000066 CHECK(IsPowerOfTwo(x));
Timur Iskhodzhanov8c505ef2012-05-21 14:25:36 +000067#if !defined(_WIN32) || defined(__clang__)
68 return __builtin_ctzl(x);
69#elif defined(_WIN64)
Alexander Potapenko6f045292012-01-27 15:15:04 +000070 unsigned long ret; // NOLINT
71 _BitScanForward64(&ret, x);
72 return ret;
Timur Iskhodzhanov8c505ef2012-05-21 14:25:36 +000073#else
Alexander Potapenko6f045292012-01-27 15:15:04 +000074 unsigned long ret; // NOLINT
75 _BitScanForward(&ret, x);
76 return ret;
Alexander Potapenko6f045292012-01-27 15:15:04 +000077#endif
78}
79
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000080static inline uptr RoundUpToPowerOfTwo(uptr size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +000081 CHECK(size);
82 if (IsPowerOfTwo(size)) return size;
Alexander Potapenko6f045292012-01-27 15:15:04 +000083
Alexey Samsonovf927ddc2012-02-03 08:50:16 +000084 unsigned long up; // NOLINT
Timur Iskhodzhanov8c505ef2012-05-21 14:25:36 +000085#if !defined(_WIN32) || defined(__clang__)
Alexey Samsonovf927ddc2012-02-03 08:50:16 +000086 up = __WORDSIZE - 1 - __builtin_clzl(size);
Timur Iskhodzhanov8c505ef2012-05-21 14:25:36 +000087#elif defined(_WIN64)
88 _BitScanReverse64(&up, size);
89#else
90 _BitScanReverse(&up, size);
Alexey Samsonovf927ddc2012-02-03 08:50:16 +000091#endif
92 CHECK(size < (1ULL << (up + 1)));
93 CHECK(size > (1ULL << up));
94 return 1UL << (up + 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +000095}
96
Kostya Serebryanyee392552012-05-31 15:02:07 +000097static inline uptr SizeClassToSize(u8 size_class) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +000098 CHECK(size_class < kNumberOfSizeClasses);
99 if (size_class <= kMallocSizeClassStepLog) {
100 return 1UL << size_class;
101 } else {
102 return (size_class - kMallocSizeClassStepLog) * kMallocSizeClassStep;
103 }
104}
105
Kostya Serebryanyee392552012-05-31 15:02:07 +0000106static inline u8 SizeToSizeClass(uptr size) {
107 u8 res = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000108 if (size <= kMallocSizeClassStep) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000109 uptr rounded = RoundUpToPowerOfTwo(size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000110 res = Log2(rounded);
111 } else {
112 res = ((size + kMallocSizeClassStep - 1) / kMallocSizeClassStep)
113 + kMallocSizeClassStepLog;
114 }
115 CHECK(res < kNumberOfSizeClasses);
116 CHECK(size <= SizeClassToSize(res));
117 return res;
118}
119
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000120// Given REDZONE bytes, we need to mark first size bytes
121// as addressable and the rest REDZONE-size bytes as unaddressable.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000122static void PoisonHeapPartialRightRedzone(uptr mem, uptr size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000123 CHECK(size <= REDZONE);
124 CHECK(IsAligned(mem, REDZONE));
125 CHECK(IsPowerOfTwo(SHADOW_GRANULARITY));
126 CHECK(IsPowerOfTwo(REDZONE));
127 CHECK(REDZONE >= SHADOW_GRANULARITY);
Kostya Serebryany218a9b72011-11-30 18:50:23 +0000128 PoisonShadowPartialRightRedzone(mem, size, REDZONE,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000129 kAsanHeapRightRedzoneMagic);
130}
131
Kostya Serebryanyee392552012-05-31 15:02:07 +0000132static u8 *MmapNewPagesAndPoisonShadow(uptr size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000133 CHECK(IsAligned(size, kPageSize));
Alexey Samsonova25b3462012-06-06 16:15:07 +0000134 u8 *res = (u8*)MmapOrDie(size, __FUNCTION__);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000135 PoisonShadow((uptr)res, size, kAsanHeapLeftRedzoneMagic);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000136 if (FLAG_debug) {
137 Printf("ASAN_MMAP: [%p, %p)\n", res, res + size);
138 }
139 return res;
140}
141
142// Every chunk of memory allocated by this allocator can be in one of 3 states:
143// CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated.
144// CHUNK_ALLOCATED: the chunk is allocated and not yet freed.
145// CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone.
146//
147// The pseudo state CHUNK_MEMALIGN is used to mark that the address is not
Kostya Serebryany16071602012-06-06 16:58:21 +0000148// the beginning of a AsanChunk (in which the actual chunk resides at
149// this - this->used_size).
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000150//
151// The magic numbers for the enum values are taken randomly.
152enum {
Kostya Serebryany7ebac952012-06-06 14:46:38 +0000153 CHUNK_AVAILABLE = 0x57,
154 CHUNK_ALLOCATED = 0x32,
155 CHUNK_QUARANTINE = 0x19,
156 CHUNK_MEMALIGN = 0xDC,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000157};
158
159struct ChunkBase {
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000160 // First 8 bytes.
Kostya Serebryanyf4a4d5a2012-06-06 15:30:55 +0000161 uptr chunk_state : 8;
162 uptr size_class : 8;
163 uptr alloc_tid : 24;
164 uptr free_tid : 24;
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000165
166 // Second 8 bytes.
167 uptr alignment_log : 8;
168 uptr used_size : FIRST_32_SECOND_64(32, 56); // Size requested by the user.
169
Kostya Serebryany16071602012-06-06 16:58:21 +0000170 // This field may overlap with the user area and thus should not
171 // be used while the chunk is in CHUNK_ALLOCATED state.
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000172 AsanChunk *next;
173
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000174 // Typically the beginning of the user-accessible memory is 'this'+REDZONE
175 // and is also aligned by REDZONE. However, if the memory is allocated
176 // by memalign, the alignment might be higher and the user-accessible memory
177 // starts at the first properly aligned address after the end of 'this'.
178 uptr Beg() {
179 return RoundUpTo((uptr)this + sizeof(ChunkBase), 1 << alignment_log);
180 }
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000181 uptr Size() { return SizeClassToSize(size_class); }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000182 u8 SizeClass() { return size_class; }
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000183};
184
185struct AsanChunk: public ChunkBase {
Kostya Serebryanyee392552012-05-31 15:02:07 +0000186 u32 *compressed_alloc_stack() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000187 CHECK(REDZONE >= sizeof(ChunkBase));
Kostya Serebryanyee392552012-05-31 15:02:07 +0000188 return (u32*)((uptr)this + sizeof(ChunkBase));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000189 }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000190 u32 *compressed_free_stack() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000191 CHECK(REDZONE >= sizeof(ChunkBase));
Kostya Serebryanyee392552012-05-31 15:02:07 +0000192 return (u32*)((uptr)this + REDZONE);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000193 }
194
195 // The left redzone after the ChunkBase is given to the alloc stack trace.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000196 uptr compressed_alloc_stack_size() {
Kostya Serebryanyee392552012-05-31 15:02:07 +0000197 return (REDZONE - sizeof(ChunkBase)) / sizeof(u32);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000198 }
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000199 uptr compressed_free_stack_size() {
Kostya Serebryanyee392552012-05-31 15:02:07 +0000200 return (REDZONE) / sizeof(u32);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000201 }
202
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000203 bool AddrIsInside(uptr addr, uptr access_size, uptr *offset) {
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000204 if (addr >= Beg() && (addr + access_size) <= (Beg() + used_size)) {
205 *offset = addr - Beg();
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000206 return true;
207 }
208 return false;
209 }
210
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000211 bool AddrIsAtLeft(uptr addr, uptr access_size, uptr *offset) {
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000212 if (addr < Beg()) {
213 *offset = Beg() - addr;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000214 return true;
215 }
216 return false;
217 }
218
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000219 bool AddrIsAtRight(uptr addr, uptr access_size, uptr *offset) {
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000220 if (addr + access_size >= Beg() + used_size) {
221 if (addr <= Beg() + used_size)
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000222 *offset = 0;
223 else
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000224 *offset = addr - (Beg() + used_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000225 return true;
226 }
227 return false;
228 }
229
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000230 void DescribeAddress(uptr addr, uptr access_size) {
231 uptr offset;
Alexey Samsonove9541012012-06-06 13:11:29 +0000232 AsanPrintf("%p is located ", (void*)addr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000233 if (AddrIsInside(addr, access_size, &offset)) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000234 AsanPrintf("%zu bytes inside of", offset);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000235 } else if (AddrIsAtLeft(addr, access_size, &offset)) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000236 AsanPrintf("%zu bytes to the left of", offset);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000237 } else if (AddrIsAtRight(addr, access_size, &offset)) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000238 AsanPrintf("%zu bytes to the right of", offset);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000239 } else {
Alexey Samsonove9541012012-06-06 13:11:29 +0000240 AsanPrintf(" somewhere around (this is AddressSanitizer bug!)");
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000241 }
Alexey Samsonove9541012012-06-06 13:11:29 +0000242 AsanPrintf(" %zu-byte region [%p,%p)\n",
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000243 used_size, (void*)Beg(), (void*)(Beg() + used_size));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000244 }
245};
246
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000247static AsanChunk *PtrToChunk(uptr ptr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000248 AsanChunk *m = (AsanChunk*)(ptr - REDZONE);
249 if (m->chunk_state == CHUNK_MEMALIGN) {
Kostya Serebryany16071602012-06-06 16:58:21 +0000250 m = (AsanChunk*)((uptr)m - m->used_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000251 }
252 return m;
253}
254
255
256void AsanChunkFifoList::PushList(AsanChunkFifoList *q) {
Alexey Samsonove0460662012-02-27 09:06:10 +0000257 CHECK(q->size() > 0);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000258 if (last_) {
259 CHECK(first_);
260 CHECK(!last_->next);
261 last_->next = q->first_;
262 last_ = q->last_;
263 } else {
264 CHECK(!first_);
265 last_ = q->last_;
266 first_ = q->first_;
Alexey Samsonove0460662012-02-27 09:06:10 +0000267 CHECK(first_);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000268 }
Alexey Samsonove0460662012-02-27 09:06:10 +0000269 CHECK(last_);
270 CHECK(!last_->next);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000271 size_ += q->size();
272 q->clear();
273}
274
275void AsanChunkFifoList::Push(AsanChunk *n) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000276 CHECK(n->next == 0);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000277 if (last_) {
278 CHECK(first_);
279 CHECK(!last_->next);
280 last_->next = n;
281 last_ = n;
282 } else {
283 CHECK(!first_);
284 last_ = first_ = n;
285 }
286 size_ += n->Size();
287}
288
289// Interesting performance observation: this function takes up to 15% of overal
290// allocator time. That's because *first_ has been evicted from cache long time
291// ago. Not sure if we can or want to do anything with this.
292AsanChunk *AsanChunkFifoList::Pop() {
293 CHECK(first_);
294 AsanChunk *res = first_;
295 first_ = first_->next;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000296 if (first_ == 0)
297 last_ = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000298 CHECK(size_ >= res->Size());
299 size_ -= res->Size();
300 if (last_) {
301 CHECK(!last_->next);
302 }
303 return res;
304}
305
306// All pages we ever allocated.
307struct PageGroup {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000308 uptr beg;
309 uptr end;
310 uptr size_of_chunk;
311 uptr last_chunk;
312 bool InRange(uptr addr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000313 return addr >= beg && addr < end;
314 }
315};
316
317class MallocInfo {
318 public:
319
320 explicit MallocInfo(LinkerInitialized x) : mu_(x) { }
321
Kostya Serebryanyee392552012-05-31 15:02:07 +0000322 AsanChunk *AllocateChunks(u8 size_class, uptr n_chunks) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000323 AsanChunk *m = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000324 AsanChunk **fl = &free_lists_[size_class];
325 {
326 ScopedLock lock(&mu_);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000327 for (uptr i = 0; i < n_chunks; i++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000328 if (!(*fl)) {
329 *fl = GetNewChunks(size_class);
330 }
331 AsanChunk *t = *fl;
332 *fl = t->next;
333 t->next = m;
334 CHECK(t->chunk_state == CHUNK_AVAILABLE);
335 m = t;
336 }
337 }
338 return m;
339 }
340
341 void SwallowThreadLocalMallocStorage(AsanThreadLocalMallocStorage *x,
342 bool eat_free_lists) {
343 CHECK(FLAG_quarantine_size > 0);
344 ScopedLock lock(&mu_);
345 AsanChunkFifoList *q = &x->quarantine_;
346 if (q->size() > 0) {
347 quarantine_.PushList(q);
348 while (quarantine_.size() > FLAG_quarantine_size) {
349 QuarantinePop();
350 }
351 }
352 if (eat_free_lists) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000353 for (uptr size_class = 0; size_class < kNumberOfSizeClasses;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000354 size_class++) {
355 AsanChunk *m = x->free_lists_[size_class];
356 while (m) {
357 AsanChunk *t = m->next;
358 m->next = free_lists_[size_class];
359 free_lists_[size_class] = m;
360 m = t;
361 }
362 x->free_lists_[size_class] = 0;
363 }
364 }
365 }
366
367 void BypassThreadLocalQuarantine(AsanChunk *chunk) {
368 ScopedLock lock(&mu_);
369 quarantine_.Push(chunk);
370 }
371
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000372 AsanChunk *FindMallocedOrFreed(uptr addr, uptr access_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000373 ScopedLock lock(&mu_);
374 return FindChunkByAddr(addr);
375 }
376
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000377 uptr AllocationSize(uptr ptr) {
Alexey Samsonovca2278d2012-01-18 15:26:55 +0000378 if (!ptr) return 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000379 ScopedLock lock(&mu_);
380
381 // first, check if this is our memory
382 PageGroup *g = FindPageGroupUnlocked(ptr);
383 if (!g) return 0;
384 AsanChunk *m = PtrToChunk(ptr);
385 if (m->chunk_state == CHUNK_ALLOCATED) {
386 return m->used_size;
387 } else {
388 return 0;
389 }
390 }
391
392 void ForceLock() {
393 mu_.Lock();
394 }
395
396 void ForceUnlock() {
397 mu_.Unlock();
398 }
399
400 void PrintStatus() {
401 ScopedLock lock(&mu_);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000402 uptr malloced = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000403
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000404 Printf(" MallocInfo: in quarantine: %zu malloced: %zu; ",
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000405 quarantine_.size() >> 20, malloced >> 20);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000406 for (uptr j = 1; j < kNumberOfSizeClasses; j++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000407 AsanChunk *i = free_lists_[j];
408 if (!i) continue;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000409 uptr t = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000410 for (; i; i = i->next) {
411 t += i->Size();
412 }
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000413 Printf("%zu:%zu ", j, t >> 20);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000414 }
415 Printf("\n");
416 }
417
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000418 PageGroup *FindPageGroup(uptr addr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000419 ScopedLock lock(&mu_);
420 return FindPageGroupUnlocked(addr);
421 }
422
423 private:
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000424 PageGroup *FindPageGroupUnlocked(uptr addr) {
Kostya Serebryany25c71782012-03-10 01:30:01 +0000425 int n = n_page_groups_;
426 // If the page groups are not sorted yet, sort them.
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000427 if (n_sorted_page_groups_ < n) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000428 SortArray((uptr*)page_groups_, n);
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000429 n_sorted_page_groups_ = n;
Kostya Serebryany25c71782012-03-10 01:30:01 +0000430 }
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000431 // Binary search over the page groups.
Kostya Serebryany25c71782012-03-10 01:30:01 +0000432 int beg = 0, end = n;
433 while (beg < end) {
434 int med = (beg + end) / 2;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000435 uptr g = (uptr)page_groups_[med];
Kostya Serebryany25c71782012-03-10 01:30:01 +0000436 if (addr > g) {
437 // 'g' points to the end of the group, so 'addr'
438 // may not belong to page_groups_[med] or any previous group.
439 beg = med + 1;
440 } else {
441 // 'addr' may belong to page_groups_[med] or a previous group.
442 end = med;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000443 }
444 }
Kostya Serebryany25c71782012-03-10 01:30:01 +0000445 if (beg >= n)
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000446 return 0;
Kostya Serebryany25c71782012-03-10 01:30:01 +0000447 PageGroup *g = page_groups_[beg];
448 CHECK(g);
449 if (g->InRange(addr))
450 return g;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000451 return 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000452 }
453
454 // We have an address between two chunks, and we want to report just one.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000455 AsanChunk *ChooseChunk(uptr addr,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000456 AsanChunk *left_chunk, AsanChunk *right_chunk) {
457 // Prefer an allocated chunk or a chunk from quarantine.
458 if (left_chunk->chunk_state == CHUNK_AVAILABLE &&
459 right_chunk->chunk_state != CHUNK_AVAILABLE)
460 return right_chunk;
461 if (right_chunk->chunk_state == CHUNK_AVAILABLE &&
462 left_chunk->chunk_state != CHUNK_AVAILABLE)
463 return left_chunk;
464 // Choose based on offset.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000465 uptr l_offset = 0, r_offset = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000466 CHECK(left_chunk->AddrIsAtRight(addr, 1, &l_offset));
467 CHECK(right_chunk->AddrIsAtLeft(addr, 1, &r_offset));
468 if (l_offset < r_offset)
469 return left_chunk;
470 return right_chunk;
471 }
472
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000473 AsanChunk *FindChunkByAddr(uptr addr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000474 PageGroup *g = FindPageGroupUnlocked(addr);
475 if (!g) return 0;
476 CHECK(g->size_of_chunk);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000477 uptr offset_from_beg = addr - g->beg;
478 uptr this_chunk_addr = g->beg +
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000479 (offset_from_beg / g->size_of_chunk) * g->size_of_chunk;
480 CHECK(g->InRange(this_chunk_addr));
481 AsanChunk *m = (AsanChunk*)this_chunk_addr;
482 CHECK(m->chunk_state == CHUNK_ALLOCATED ||
483 m->chunk_state == CHUNK_AVAILABLE ||
484 m->chunk_state == CHUNK_QUARANTINE);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000485 uptr offset = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000486 if (m->AddrIsInside(addr, 1, &offset))
487 return m;
488
489 if (m->AddrIsAtRight(addr, 1, &offset)) {
490 if (this_chunk_addr == g->last_chunk) // rightmost chunk
491 return m;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000492 uptr right_chunk_addr = this_chunk_addr + g->size_of_chunk;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000493 CHECK(g->InRange(right_chunk_addr));
494 return ChooseChunk(addr, m, (AsanChunk*)right_chunk_addr);
495 } else {
496 CHECK(m->AddrIsAtLeft(addr, 1, &offset));
497 if (this_chunk_addr == g->beg) // leftmost chunk
498 return m;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000499 uptr left_chunk_addr = this_chunk_addr - g->size_of_chunk;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000500 CHECK(g->InRange(left_chunk_addr));
501 return ChooseChunk(addr, (AsanChunk*)left_chunk_addr, m);
502 }
503 }
504
505 void QuarantinePop() {
506 CHECK(quarantine_.size() > 0);
507 AsanChunk *m = quarantine_.Pop();
508 CHECK(m);
509 // if (F_v >= 2) Printf("MallocInfo::pop %p\n", m);
510
511 CHECK(m->chunk_state == CHUNK_QUARANTINE);
512 m->chunk_state = CHUNK_AVAILABLE;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000513 PoisonShadow((uptr)m, m->Size(), kAsanHeapLeftRedzoneMagic);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000514 CHECK(m->alloc_tid >= 0);
515 CHECK(m->free_tid >= 0);
516
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000517 uptr size_class = m->SizeClass();
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000518 m->next = free_lists_[size_class];
519 free_lists_[size_class] = m;
520
Kostya Serebryany30743142011-12-05 19:17:53 +0000521 // Statistics.
522 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
523 thread_stats.real_frees++;
524 thread_stats.really_freed += m->used_size;
525 thread_stats.really_freed_redzones += m->Size() - m->used_size;
526 thread_stats.really_freed_by_size[m->SizeClass()]++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000527 }
528
529 // Get a list of newly allocated chunks.
Kostya Serebryanyee392552012-05-31 15:02:07 +0000530 AsanChunk *GetNewChunks(u8 size_class) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000531 uptr size = SizeClassToSize(size_class);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000532 CHECK(IsPowerOfTwo(kMinMmapSize));
533 CHECK(size < kMinMmapSize || (size % kMinMmapSize) == 0);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000534 uptr mmap_size = Max(size, kMinMmapSize);
535 uptr n_chunks = mmap_size / size;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000536 CHECK(n_chunks * size == mmap_size);
537 if (size < kPageSize) {
538 // Size is small, just poison the last chunk.
539 n_chunks--;
540 } else {
541 // Size is large, allocate an extra page at right and poison it.
542 mmap_size += kPageSize;
543 }
544 CHECK(n_chunks > 0);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000545 u8 *mem = MmapNewPagesAndPoisonShadow(mmap_size);
Kostya Serebryany30743142011-12-05 19:17:53 +0000546
547 // Statistics.
548 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
549 thread_stats.mmaps++;
550 thread_stats.mmaped += mmap_size;
551 thread_stats.mmaped_by_size[size_class] += n_chunks;
552
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000553 AsanChunk *res = 0;
554 for (uptr i = 0; i < n_chunks; i++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000555 AsanChunk *m = (AsanChunk*)(mem + i * size);
556 m->chunk_state = CHUNK_AVAILABLE;
557 m->size_class = size_class;
558 m->next = res;
559 res = m;
560 }
561 PageGroup *pg = (PageGroup*)(mem + n_chunks * size);
562 // This memory is already poisoned, no need to poison it again.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000563 pg->beg = (uptr)mem;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000564 pg->end = pg->beg + mmap_size;
565 pg->size_of_chunk = size;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000566 pg->last_chunk = (uptr)(mem + size * (n_chunks - 1));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000567 int page_group_idx = AtomicInc(&n_page_groups_) - 1;
568 CHECK(page_group_idx < (int)ASAN_ARRAY_SIZE(page_groups_));
569 page_groups_[page_group_idx] = pg;
570 return res;
571 }
572
573 AsanChunk *free_lists_[kNumberOfSizeClasses];
574 AsanChunkFifoList quarantine_;
575 AsanLock mu_;
576
577 PageGroup *page_groups_[kMaxAvailableRam / kMinMmapSize];
578 int n_page_groups_; // atomic
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000579 int n_sorted_page_groups_;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000580};
581
582static MallocInfo malloc_info(LINKER_INITIALIZED);
583
584void AsanThreadLocalMallocStorage::CommitBack() {
585 malloc_info.SwallowThreadLocalMallocStorage(this, true);
586}
587
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000588static void Describe(uptr addr, uptr access_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000589 AsanChunk *m = malloc_info.FindMallocedOrFreed(addr, access_size);
590 if (!m) return;
591 m->DescribeAddress(addr, access_size);
592 CHECK(m->alloc_tid >= 0);
593 AsanThreadSummary *alloc_thread =
594 asanThreadRegistry().FindByTid(m->alloc_tid);
595 AsanStackTrace alloc_stack;
596 AsanStackTrace::UncompressStack(&alloc_stack, m->compressed_alloc_stack(),
597 m->compressed_alloc_stack_size());
598 AsanThread *t = asanThreadRegistry().GetCurrent();
599 CHECK(t);
Kostya Serebryanye0cff0b2012-06-06 15:06:58 +0000600 if (m->free_tid != kInvalidTid) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000601 AsanThreadSummary *free_thread =
602 asanThreadRegistry().FindByTid(m->free_tid);
Alexey Samsonove9541012012-06-06 13:11:29 +0000603 AsanPrintf("freed by thread T%d here:\n", free_thread->tid());
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000604 AsanStackTrace free_stack;
605 AsanStackTrace::UncompressStack(&free_stack, m->compressed_free_stack(),
606 m->compressed_free_stack_size());
607 free_stack.PrintStack();
Alexey Samsonove9541012012-06-06 13:11:29 +0000608 AsanPrintf("previously allocated by thread T%d here:\n",
609 alloc_thread->tid());
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000610
611 alloc_stack.PrintStack();
612 t->summary()->Announce();
613 free_thread->Announce();
614 alloc_thread->Announce();
615 } else {
Alexey Samsonove9541012012-06-06 13:11:29 +0000616 AsanPrintf("allocated by thread T%d here:\n", alloc_thread->tid());
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000617 alloc_stack.PrintStack();
618 t->summary()->Announce();
619 alloc_thread->Announce();
620 }
621}
622
Kostya Serebryanyee392552012-05-31 15:02:07 +0000623static u8 *Allocate(uptr alignment, uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000624 __asan_init();
625 CHECK(stack);
626 if (size == 0) {
627 size = 1; // TODO(kcc): do something smarter
628 }
629 CHECK(IsPowerOfTwo(alignment));
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000630 uptr rounded_size = RoundUpTo(size, REDZONE);
631 uptr needed_size = rounded_size + REDZONE;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000632 if (alignment > REDZONE) {
633 needed_size += alignment;
634 }
635 CHECK(IsAligned(needed_size, REDZONE));
636 if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) {
Alexey Samsonov5bcca4e2012-06-06 10:46:00 +0000637 Report("WARNING: AddressSanitizer failed to allocate %p bytes\n",
638 (void*)size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000639 return 0;
640 }
641
Kostya Serebryanyee392552012-05-31 15:02:07 +0000642 u8 size_class = SizeToSizeClass(needed_size);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000643 uptr size_to_allocate = SizeClassToSize(size_class);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000644 CHECK(size_to_allocate >= kMinAllocSize);
645 CHECK(size_to_allocate >= needed_size);
646 CHECK(IsAligned(size_to_allocate, REDZONE));
647
Alexander Potapenko108a2372012-03-27 16:37:16 +0000648 if (FLAG_v >= 3) {
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000649 Printf("Allocate align: %zu size: %zu class: %u real: %zu\n",
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000650 alignment, size, size_class, size_to_allocate);
651 }
652
653 AsanThread *t = asanThreadRegistry().GetCurrent();
654 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
Kostya Serebryany30743142011-12-05 19:17:53 +0000655 // Statistics
656 thread_stats.mallocs++;
657 thread_stats.malloced += size;
658 thread_stats.malloced_redzones += size_to_allocate - size;
659 thread_stats.malloced_by_size[size_class]++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000660
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000661 AsanChunk *m = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000662 if (!t || size_to_allocate >= kMaxSizeForThreadLocalFreeList) {
663 // get directly from global storage.
664 m = malloc_info.AllocateChunks(size_class, 1);
Kostya Serebryany30743142011-12-05 19:17:53 +0000665 thread_stats.malloc_large++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000666 } else {
667 // get from the thread-local storage.
668 AsanChunk **fl = &t->malloc_storage().free_lists_[size_class];
669 if (!*fl) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000670 uptr n_new_chunks = kMaxSizeForThreadLocalFreeList / size_to_allocate;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000671 *fl = malloc_info.AllocateChunks(size_class, n_new_chunks);
Kostya Serebryany30743142011-12-05 19:17:53 +0000672 thread_stats.malloc_small_slow++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000673 }
674 m = *fl;
675 *fl = (*fl)->next;
676 }
677 CHECK(m);
678 CHECK(m->chunk_state == CHUNK_AVAILABLE);
679 m->chunk_state = CHUNK_ALLOCATED;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000680 m->next = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000681 CHECK(m->Size() == size_to_allocate);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000682 uptr addr = (uptr)m + REDZONE;
683 CHECK(addr == (uptr)m->compressed_free_stack());
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000684
685 if (alignment > REDZONE && (addr & (alignment - 1))) {
686 addr = RoundUpTo(addr, alignment);
687 CHECK((addr & (alignment - 1)) == 0);
688 AsanChunk *p = (AsanChunk*)(addr - REDZONE);
689 p->chunk_state = CHUNK_MEMALIGN;
Kostya Serebryany16071602012-06-06 16:58:21 +0000690 p->used_size = (uptr)p - (uptr)m;
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000691 m->alignment_log = Log2(alignment);
692 CHECK(m->Beg() == addr);
693 } else {
694 m->alignment_log = Log2(REDZONE);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000695 }
696 CHECK(m == PtrToChunk(addr));
697 m->used_size = size;
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000698 CHECK(m->Beg() == addr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000699 m->alloc_tid = t ? t->tid() : 0;
Kostya Serebryanye0cff0b2012-06-06 15:06:58 +0000700 m->free_tid = kInvalidTid;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000701 AsanStackTrace::CompressStack(stack, m->compressed_alloc_stack(),
702 m->compressed_alloc_stack_size());
703 PoisonShadow(addr, rounded_size, 0);
704 if (size < rounded_size) {
Kostya Serebryany218a9b72011-11-30 18:50:23 +0000705 PoisonHeapPartialRightRedzone(addr + rounded_size - REDZONE,
706 size & (REDZONE - 1));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000707 }
708 if (size <= FLAG_max_malloc_fill_size) {
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000709 REAL(memset)((void*)addr, 0, rounded_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000710 }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000711 return (u8*)addr;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000712}
713
Kostya Serebryanyee392552012-05-31 15:02:07 +0000714static void Deallocate(u8 *ptr, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000715 if (!ptr) return;
716 CHECK(stack);
717
718 if (FLAG_debug) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000719 CHECK(malloc_info.FindPageGroup((uptr)ptr));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000720 }
721
722 // Printf("Deallocate %p\n", ptr);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000723 AsanChunk *m = PtrToChunk((uptr)ptr);
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000724
Kostya Serebryanyf4a4d5a2012-06-06 15:30:55 +0000725 // Flip the chunk_state atomically to avoid race on double-free.
726 u8 old_chunk_state = AtomicExchange((u8*)m, CHUNK_QUARANTINE);
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000727
728 if (old_chunk_state == CHUNK_QUARANTINE) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000729 AsanReport("ERROR: AddressSanitizer attempting double-free on %p:\n", ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000730 stack->PrintStack();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000731 Describe((uptr)ptr, 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000732 ShowStatsAndAbort();
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000733 } else if (old_chunk_state != CHUNK_ALLOCATED) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000734 AsanReport("ERROR: AddressSanitizer attempting free on address "
735 "which was not malloc()-ed: %p\n", ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000736 stack->PrintStack();
737 ShowStatsAndAbort();
738 }
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000739 CHECK(old_chunk_state == CHUNK_ALLOCATED);
Kostya Serebryany16071602012-06-06 16:58:21 +0000740 // With REDZONE==16 m->next is in the user area, otherwise it should be 0.
741 CHECK(REDZONE <= 16 || !m->next);
Kostya Serebryanye0cff0b2012-06-06 15:06:58 +0000742 CHECK(m->free_tid == kInvalidTid);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000743 CHECK(m->alloc_tid >= 0);
744 AsanThread *t = asanThreadRegistry().GetCurrent();
745 m->free_tid = t ? t->tid() : 0;
746 AsanStackTrace::CompressStack(stack, m->compressed_free_stack(),
747 m->compressed_free_stack_size());
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000748 uptr rounded_size = RoundUpTo(m->used_size, REDZONE);
749 PoisonShadow((uptr)ptr, rounded_size, kAsanHeapFreeMagic);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000750
Kostya Serebryany30743142011-12-05 19:17:53 +0000751 // Statistics.
752 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
753 thread_stats.frees++;
754 thread_stats.freed += m->used_size;
755 thread_stats.freed_by_size[m->SizeClass()]++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000756
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000757 CHECK(m->chunk_state == CHUNK_QUARANTINE);
Kostya Serebryany16071602012-06-06 16:58:21 +0000758
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000759 if (t) {
760 AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000761 ms->quarantine_.Push(m);
762
763 if (ms->quarantine_.size() > kMaxThreadLocalQuarantine) {
764 malloc_info.SwallowThreadLocalMallocStorage(ms, false);
765 }
766 } else {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000767 malloc_info.BypassThreadLocalQuarantine(m);
768 }
769}
770
Kostya Serebryanyee392552012-05-31 15:02:07 +0000771static u8 *Reallocate(u8 *old_ptr, uptr new_size,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000772 AsanStackTrace *stack) {
773 CHECK(old_ptr && new_size);
Kostya Serebryany30743142011-12-05 19:17:53 +0000774
775 // Statistics.
776 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
777 thread_stats.reallocs++;
778 thread_stats.realloced += new_size;
779
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000780 AsanChunk *m = PtrToChunk((uptr)old_ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000781 CHECK(m->chunk_state == CHUNK_ALLOCATED);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000782 uptr old_size = m->used_size;
783 uptr memcpy_size = Min(new_size, old_size);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000784 u8 *new_ptr = Allocate(0, new_size, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000785 if (new_ptr) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000786 CHECK(REAL(memcpy) != 0);
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000787 REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000788 Deallocate(old_ptr, stack);
789 }
790 return new_ptr;
791}
792
793} // namespace __asan
794
795// Malloc hooks declaration.
796// ASAN_NEW_HOOK(ptr, size) is called immediately after
797// allocation of "size" bytes, which returned "ptr".
798// ASAN_DELETE_HOOK(ptr) is called immediately before
799// deallocation of "ptr".
800// If ASAN_NEW_HOOK or ASAN_DELETE_HOOK is defined, user
801// program must provide implementation of this hook.
802// If macro is undefined, the hook is no-op.
803#ifdef ASAN_NEW_HOOK
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000804extern "C" void ASAN_NEW_HOOK(void *ptr, uptr size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000805#else
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000806static inline void ASAN_NEW_HOOK(void *ptr, uptr size) { }
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000807#endif
808
809#ifdef ASAN_DELETE_HOOK
810extern "C" void ASAN_DELETE_HOOK(void *ptr);
811#else
812static inline void ASAN_DELETE_HOOK(void *ptr) { }
813#endif
814
815namespace __asan {
816
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000817void *asan_memalign(uptr alignment, uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000818 void *ptr = (void*)Allocate(alignment, size, stack);
819 ASAN_NEW_HOOK(ptr, size);
820 return ptr;
821}
822
823void asan_free(void *ptr, AsanStackTrace *stack) {
824 ASAN_DELETE_HOOK(ptr);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000825 Deallocate((u8*)ptr, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000826}
827
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000828void *asan_malloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000829 void *ptr = (void*)Allocate(0, size, stack);
830 ASAN_NEW_HOOK(ptr, size);
831 return ptr;
832}
833
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000834void *asan_calloc(uptr nmemb, uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000835 void *ptr = (void*)Allocate(0, nmemb * size, stack);
836 if (ptr)
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000837 REAL(memset)(ptr, 0, nmemb * size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000838 ASAN_NEW_HOOK(ptr, nmemb * size);
839 return ptr;
840}
841
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000842void *asan_realloc(void *p, uptr size, AsanStackTrace *stack) {
843 if (p == 0) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000844 void *ptr = (void*)Allocate(0, size, stack);
845 ASAN_NEW_HOOK(ptr, size);
846 return ptr;
847 } else if (size == 0) {
848 ASAN_DELETE_HOOK(p);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000849 Deallocate((u8*)p, stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000850 return 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000851 }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000852 return Reallocate((u8*)p, size, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000853}
854
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000855void *asan_valloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000856 void *ptr = (void*)Allocate(kPageSize, size, stack);
857 ASAN_NEW_HOOK(ptr, size);
858 return ptr;
859}
860
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000861void *asan_pvalloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000862 size = RoundUpTo(size, kPageSize);
863 if (size == 0) {
864 // pvalloc(0) should allocate one page.
865 size = kPageSize;
866 }
867 void *ptr = (void*)Allocate(kPageSize, size, stack);
868 ASAN_NEW_HOOK(ptr, size);
869 return ptr;
870}
871
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000872int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000873 AsanStackTrace *stack) {
874 void *ptr = Allocate(alignment, size, stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000875 CHECK(IsAligned((uptr)ptr, alignment));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000876 ASAN_NEW_HOOK(ptr, size);
877 *memptr = ptr;
878 return 0;
879}
880
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000881uptr asan_malloc_usable_size(void *ptr, AsanStackTrace *stack) {
Alexey Samsonovca2278d2012-01-18 15:26:55 +0000882 CHECK(stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000883 if (ptr == 0) return 0;
884 uptr usable_size = malloc_info.AllocationSize((uptr)ptr);
Alexander Potapenko37931232012-05-25 15:20:13 +0000885 if (FLAG_check_malloc_usable_size && (usable_size == 0)) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000886 AsanReport("ERROR: AddressSanitizer attempting to call "
887 "malloc_usable_size() for pointer which is "
888 "not owned: %p\n", ptr);
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000889 stack->PrintStack();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000890 Describe((uptr)ptr, 1);
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000891 ShowStatsAndAbort();
892 }
893 return usable_size;
894}
895
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000896uptr asan_mz_size(const void *ptr) {
897 return malloc_info.AllocationSize((uptr)ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000898}
899
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000900void DescribeHeapAddress(uptr addr, uptr access_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000901 Describe(addr, access_size);
902}
903
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000904void asan_mz_force_lock() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000905 malloc_info.ForceLock();
906}
907
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000908void asan_mz_force_unlock() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000909 malloc_info.ForceUnlock();
910}
911
912// ---------------------- Fake stack-------------------- {{{1
913FakeStack::FakeStack() {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000914 CHECK(REAL(memset) != 0);
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000915 REAL(memset)(this, 0, sizeof(*this));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000916}
917
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000918bool FakeStack::AddrIsInSizeClass(uptr addr, uptr size_class) {
919 uptr mem = allocated_size_classes_[size_class];
920 uptr size = ClassMmapSize(size_class);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000921 bool res = mem && addr >= mem && addr < mem + size;
922 return res;
923}
924
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000925uptr FakeStack::AddrIsInFakeStack(uptr addr) {
926 for (uptr i = 0; i < kNumberOfSizeClasses; i++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000927 if (AddrIsInSizeClass(addr, i)) return allocated_size_classes_[i];
928 }
929 return 0;
930}
931
932// We may want to compute this during compilation.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000933inline uptr FakeStack::ComputeSizeClass(uptr alloc_size) {
934 uptr rounded_size = RoundUpToPowerOfTwo(alloc_size);
935 uptr log = Log2(rounded_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000936 CHECK(alloc_size <= (1UL << log));
937 if (!(alloc_size > (1UL << (log-1)))) {
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000938 Printf("alloc_size %zu log %zu\n", alloc_size, log);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000939 }
940 CHECK(alloc_size > (1UL << (log-1)));
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000941 uptr res = log < kMinStackFrameSizeLog ? 0 : log - kMinStackFrameSizeLog;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000942 CHECK(res < kNumberOfSizeClasses);
943 CHECK(ClassSize(res) >= rounded_size);
944 return res;
945}
946
947void FakeFrameFifo::FifoPush(FakeFrame *node) {
948 CHECK(node);
949 node->next = 0;
950 if (first_ == 0 && last_ == 0) {
951 first_ = last_ = node;
952 } else {
953 CHECK(first_);
954 CHECK(last_);
955 last_->next = node;
956 last_ = node;
957 }
958}
959
960FakeFrame *FakeFrameFifo::FifoPop() {
961 CHECK(first_ && last_ && "Exhausted fake stack");
962 FakeFrame *res = 0;
963 if (first_ == last_) {
964 res = first_;
965 first_ = last_ = 0;
966 } else {
967 res = first_;
968 first_ = first_->next;
969 }
970 return res;
971}
972
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000973void FakeStack::Init(uptr stack_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000974 stack_size_ = stack_size;
975 alive_ = true;
976}
977
978void FakeStack::Cleanup() {
979 alive_ = false;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000980 for (uptr i = 0; i < kNumberOfSizeClasses; i++) {
981 uptr mem = allocated_size_classes_[i];
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000982 if (mem) {
983 PoisonShadow(mem, ClassMmapSize(i), 0);
984 allocated_size_classes_[i] = 0;
Alexey Samsonova25b3462012-06-06 16:15:07 +0000985 UnmapOrDie((void*)mem, ClassMmapSize(i));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000986 }
987 }
988}
989
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000990uptr FakeStack::ClassMmapSize(uptr size_class) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000991 return RoundUpToPowerOfTwo(stack_size_);
992}
993
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000994void FakeStack::AllocateOneSizeClass(uptr size_class) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000995 CHECK(ClassMmapSize(size_class) >= kPageSize);
Alexey Samsonova25b3462012-06-06 16:15:07 +0000996 uptr new_mem = (uptr)MmapOrDie(
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000997 ClassMmapSize(size_class), __FUNCTION__);
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000998 // Printf("T%d new_mem[%zu]: %p-%p mmap %zu\n",
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000999 // asanThreadRegistry().GetCurrent()->tid(),
1000 // size_class, new_mem, new_mem + ClassMmapSize(size_class),
1001 // ClassMmapSize(size_class));
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001002 uptr i;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001003 for (i = 0; i < ClassMmapSize(size_class);
1004 i += ClassSize(size_class)) {
1005 size_classes_[size_class].FifoPush((FakeFrame*)(new_mem + i));
1006 }
1007 CHECK(i == ClassMmapSize(size_class));
1008 allocated_size_classes_[size_class] = new_mem;
1009}
1010
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001011uptr FakeStack::AllocateStack(uptr size, uptr real_stack) {
Kostya Serebryanyc4b34d92011-12-09 01:49:31 +00001012 if (!alive_) return real_stack;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001013 CHECK(size <= kMaxStackMallocSize && size > 1);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001014 uptr size_class = ComputeSizeClass(size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001015 if (!allocated_size_classes_[size_class]) {
1016 AllocateOneSizeClass(size_class);
1017 }
1018 FakeFrame *fake_frame = size_classes_[size_class].FifoPop();
1019 CHECK(fake_frame);
1020 fake_frame->size_minus_one = size - 1;
1021 fake_frame->real_stack = real_stack;
1022 while (FakeFrame *top = call_stack_.top()) {
1023 if (top->real_stack > real_stack) break;
1024 call_stack_.LifoPop();
1025 DeallocateFrame(top);
1026 }
1027 call_stack_.LifoPush(fake_frame);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001028 uptr ptr = (uptr)fake_frame;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001029 PoisonShadow(ptr, size, 0);
1030 return ptr;
1031}
1032
1033void FakeStack::DeallocateFrame(FakeFrame *fake_frame) {
1034 CHECK(alive_);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001035 uptr size = fake_frame->size_minus_one + 1;
1036 uptr size_class = ComputeSizeClass(size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001037 CHECK(allocated_size_classes_[size_class]);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001038 uptr ptr = (uptr)fake_frame;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001039 CHECK(AddrIsInSizeClass(ptr, size_class));
1040 CHECK(AddrIsInSizeClass(ptr + size - 1, size_class));
1041 size_classes_[size_class].FifoPush(fake_frame);
1042}
1043
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001044void FakeStack::OnFree(uptr ptr, uptr size, uptr real_stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001045 FakeFrame *fake_frame = (FakeFrame*)ptr;
1046 CHECK(fake_frame->magic = kRetiredStackFrameMagic);
1047 CHECK(fake_frame->descr != 0);
1048 CHECK(fake_frame->size_minus_one == size - 1);
1049 PoisonShadow(ptr, size, kAsanStackAfterReturnMagic);
1050}
1051
1052} // namespace __asan
1053
1054// ---------------------- Interface ---------------- {{{1
1055using namespace __asan; // NOLINT
1056
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001057uptr __asan_stack_malloc(uptr size, uptr real_stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001058 if (!FLAG_use_fake_stack) return real_stack;
1059 AsanThread *t = asanThreadRegistry().GetCurrent();
1060 if (!t) {
1061 // TSD is gone, use the real stack.
1062 return real_stack;
1063 }
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001064 uptr ptr = t->fake_stack().AllocateStack(size, real_stack);
Evgeniy Stepanov739eb792012-03-21 11:32:46 +00001065 // Printf("__asan_stack_malloc %p %zu %p\n", ptr, size, real_stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001066 return ptr;
1067}
1068
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001069void __asan_stack_free(uptr ptr, uptr size, uptr real_stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001070 if (!FLAG_use_fake_stack) return;
1071 if (ptr != real_stack) {
1072 FakeStack::OnFree(ptr, size, real_stack);
1073 }
1074}
1075
1076// ASan allocator doesn't reserve extra bytes, so normally we would
1077// just return "size".
Kostya Serebryany9aead372012-05-31 14:11:07 +00001078uptr __asan_get_estimated_allocated_size(uptr size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001079 if (size == 0) return 1;
Kostya Serebryany2d8b3bd2011-12-02 18:42:04 +00001080 return Min(size, kMaxAllowedMallocSize);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001081}
1082
1083bool __asan_get_ownership(const void *p) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001084 return malloc_info.AllocationSize((uptr)p) > 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001085}
1086
Kostya Serebryany9aead372012-05-31 14:11:07 +00001087uptr __asan_get_allocated_size(const void *p) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001088 if (p == 0) return 0;
1089 uptr allocated_size = malloc_info.AllocationSize((uptr)p);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001090 // Die if p is not malloced or if it is already freed.
Alexey Samsonovca2278d2012-01-18 15:26:55 +00001091 if (allocated_size == 0) {
Alexey Samsonove9541012012-06-06 13:11:29 +00001092 AsanReport("ERROR: AddressSanitizer attempting to call "
1093 "__asan_get_allocated_size() for pointer which is "
1094 "not owned: %p\n", p);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001095 PRINT_CURRENT_STACK();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001096 Describe((uptr)p, 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001097 ShowStatsAndAbort();
1098 }
1099 return allocated_size;
1100}