blob: 16fb900e7ba2d459826e7e030d739285655937e3 [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
148// the beginning of a AsanChunk (in which case 'next' contains the address
149// of the AsanChunk).
150//
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
170 // The rest.
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000171 AsanChunk *next;
172
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000173 // Typically the beginning of the user-accessible memory is 'this'+REDZONE
174 // and is also aligned by REDZONE. However, if the memory is allocated
175 // by memalign, the alignment might be higher and the user-accessible memory
176 // starts at the first properly aligned address after the end of 'this'.
177 uptr Beg() {
178 return RoundUpTo((uptr)this + sizeof(ChunkBase), 1 << alignment_log);
179 }
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000180 uptr Size() { return SizeClassToSize(size_class); }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000181 u8 SizeClass() { return size_class; }
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000182};
183
184struct AsanChunk: public ChunkBase {
Kostya Serebryanyee392552012-05-31 15:02:07 +0000185 u32 *compressed_alloc_stack() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000186 CHECK(REDZONE >= sizeof(ChunkBase));
Kostya Serebryanyee392552012-05-31 15:02:07 +0000187 return (u32*)((uptr)this + sizeof(ChunkBase));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000188 }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000189 u32 *compressed_free_stack() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000190 CHECK(REDZONE >= sizeof(ChunkBase));
Kostya Serebryanyee392552012-05-31 15:02:07 +0000191 return (u32*)((uptr)this + REDZONE);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000192 }
193
194 // The left redzone after the ChunkBase is given to the alloc stack trace.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000195 uptr compressed_alloc_stack_size() {
Kostya Serebryanyee392552012-05-31 15:02:07 +0000196 return (REDZONE - sizeof(ChunkBase)) / sizeof(u32);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000197 }
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000198 uptr compressed_free_stack_size() {
Kostya Serebryanyee392552012-05-31 15:02:07 +0000199 return (REDZONE) / sizeof(u32);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000200 }
201
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000202 bool AddrIsInside(uptr addr, uptr access_size, uptr *offset) {
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000203 if (addr >= Beg() && (addr + access_size) <= (Beg() + used_size)) {
204 *offset = addr - Beg();
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000205 return true;
206 }
207 return false;
208 }
209
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000210 bool AddrIsAtLeft(uptr addr, uptr access_size, uptr *offset) {
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000211 if (addr < Beg()) {
212 *offset = Beg() - addr;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000213 return true;
214 }
215 return false;
216 }
217
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000218 bool AddrIsAtRight(uptr addr, uptr access_size, uptr *offset) {
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000219 if (addr + access_size >= Beg() + used_size) {
220 if (addr <= Beg() + used_size)
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000221 *offset = 0;
222 else
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000223 *offset = addr - (Beg() + used_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000224 return true;
225 }
226 return false;
227 }
228
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000229 void DescribeAddress(uptr addr, uptr access_size) {
230 uptr offset;
Alexey Samsonove9541012012-06-06 13:11:29 +0000231 AsanPrintf("%p is located ", (void*)addr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000232 if (AddrIsInside(addr, access_size, &offset)) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000233 AsanPrintf("%zu bytes inside of", offset);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000234 } else if (AddrIsAtLeft(addr, access_size, &offset)) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000235 AsanPrintf("%zu bytes to the left of", offset);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000236 } else if (AddrIsAtRight(addr, access_size, &offset)) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000237 AsanPrintf("%zu bytes to the right of", offset);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000238 } else {
Alexey Samsonove9541012012-06-06 13:11:29 +0000239 AsanPrintf(" somewhere around (this is AddressSanitizer bug!)");
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000240 }
Alexey Samsonove9541012012-06-06 13:11:29 +0000241 AsanPrintf(" %zu-byte region [%p,%p)\n",
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000242 used_size, (void*)Beg(), (void*)(Beg() + used_size));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000243 }
244};
245
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000246static AsanChunk *PtrToChunk(uptr ptr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000247 AsanChunk *m = (AsanChunk*)(ptr - REDZONE);
248 if (m->chunk_state == CHUNK_MEMALIGN) {
249 m = m->next;
250 }
251 return m;
252}
253
254
255void AsanChunkFifoList::PushList(AsanChunkFifoList *q) {
Alexey Samsonove0460662012-02-27 09:06:10 +0000256 CHECK(q->size() > 0);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000257 if (last_) {
258 CHECK(first_);
259 CHECK(!last_->next);
260 last_->next = q->first_;
261 last_ = q->last_;
262 } else {
263 CHECK(!first_);
264 last_ = q->last_;
265 first_ = q->first_;
Alexey Samsonove0460662012-02-27 09:06:10 +0000266 CHECK(first_);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000267 }
Alexey Samsonove0460662012-02-27 09:06:10 +0000268 CHECK(last_);
269 CHECK(!last_->next);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000270 size_ += q->size();
271 q->clear();
272}
273
274void AsanChunkFifoList::Push(AsanChunk *n) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000275 CHECK(n->next == 0);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000276 if (last_) {
277 CHECK(first_);
278 CHECK(!last_->next);
279 last_->next = n;
280 last_ = n;
281 } else {
282 CHECK(!first_);
283 last_ = first_ = n;
284 }
285 size_ += n->Size();
286}
287
288// Interesting performance observation: this function takes up to 15% of overal
289// allocator time. That's because *first_ has been evicted from cache long time
290// ago. Not sure if we can or want to do anything with this.
291AsanChunk *AsanChunkFifoList::Pop() {
292 CHECK(first_);
293 AsanChunk *res = first_;
294 first_ = first_->next;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000295 if (first_ == 0)
296 last_ = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000297 CHECK(size_ >= res->Size());
298 size_ -= res->Size();
299 if (last_) {
300 CHECK(!last_->next);
301 }
302 return res;
303}
304
305// All pages we ever allocated.
306struct PageGroup {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000307 uptr beg;
308 uptr end;
309 uptr size_of_chunk;
310 uptr last_chunk;
311 bool InRange(uptr addr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000312 return addr >= beg && addr < end;
313 }
314};
315
316class MallocInfo {
317 public:
318
319 explicit MallocInfo(LinkerInitialized x) : mu_(x) { }
320
Kostya Serebryanyee392552012-05-31 15:02:07 +0000321 AsanChunk *AllocateChunks(u8 size_class, uptr n_chunks) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000322 AsanChunk *m = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000323 AsanChunk **fl = &free_lists_[size_class];
324 {
325 ScopedLock lock(&mu_);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000326 for (uptr i = 0; i < n_chunks; i++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000327 if (!(*fl)) {
328 *fl = GetNewChunks(size_class);
329 }
330 AsanChunk *t = *fl;
331 *fl = t->next;
332 t->next = m;
333 CHECK(t->chunk_state == CHUNK_AVAILABLE);
334 m = t;
335 }
336 }
337 return m;
338 }
339
340 void SwallowThreadLocalMallocStorage(AsanThreadLocalMallocStorage *x,
341 bool eat_free_lists) {
342 CHECK(FLAG_quarantine_size > 0);
343 ScopedLock lock(&mu_);
344 AsanChunkFifoList *q = &x->quarantine_;
345 if (q->size() > 0) {
346 quarantine_.PushList(q);
347 while (quarantine_.size() > FLAG_quarantine_size) {
348 QuarantinePop();
349 }
350 }
351 if (eat_free_lists) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000352 for (uptr size_class = 0; size_class < kNumberOfSizeClasses;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000353 size_class++) {
354 AsanChunk *m = x->free_lists_[size_class];
355 while (m) {
356 AsanChunk *t = m->next;
357 m->next = free_lists_[size_class];
358 free_lists_[size_class] = m;
359 m = t;
360 }
361 x->free_lists_[size_class] = 0;
362 }
363 }
364 }
365
366 void BypassThreadLocalQuarantine(AsanChunk *chunk) {
367 ScopedLock lock(&mu_);
368 quarantine_.Push(chunk);
369 }
370
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000371 AsanChunk *FindMallocedOrFreed(uptr addr, uptr access_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000372 ScopedLock lock(&mu_);
373 return FindChunkByAddr(addr);
374 }
375
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000376 uptr AllocationSize(uptr ptr) {
Alexey Samsonovca2278d2012-01-18 15:26:55 +0000377 if (!ptr) return 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000378 ScopedLock lock(&mu_);
379
380 // first, check if this is our memory
381 PageGroup *g = FindPageGroupUnlocked(ptr);
382 if (!g) return 0;
383 AsanChunk *m = PtrToChunk(ptr);
384 if (m->chunk_state == CHUNK_ALLOCATED) {
385 return m->used_size;
386 } else {
387 return 0;
388 }
389 }
390
391 void ForceLock() {
392 mu_.Lock();
393 }
394
395 void ForceUnlock() {
396 mu_.Unlock();
397 }
398
399 void PrintStatus() {
400 ScopedLock lock(&mu_);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000401 uptr malloced = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000402
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000403 Printf(" MallocInfo: in quarantine: %zu malloced: %zu; ",
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000404 quarantine_.size() >> 20, malloced >> 20);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000405 for (uptr j = 1; j < kNumberOfSizeClasses; j++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000406 AsanChunk *i = free_lists_[j];
407 if (!i) continue;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000408 uptr t = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000409 for (; i; i = i->next) {
410 t += i->Size();
411 }
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000412 Printf("%zu:%zu ", j, t >> 20);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000413 }
414 Printf("\n");
415 }
416
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000417 PageGroup *FindPageGroup(uptr addr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000418 ScopedLock lock(&mu_);
419 return FindPageGroupUnlocked(addr);
420 }
421
422 private:
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000423 PageGroup *FindPageGroupUnlocked(uptr addr) {
Kostya Serebryany25c71782012-03-10 01:30:01 +0000424 int n = n_page_groups_;
425 // If the page groups are not sorted yet, sort them.
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000426 if (n_sorted_page_groups_ < n) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000427 SortArray((uptr*)page_groups_, n);
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000428 n_sorted_page_groups_ = n;
Kostya Serebryany25c71782012-03-10 01:30:01 +0000429 }
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000430 // Binary search over the page groups.
Kostya Serebryany25c71782012-03-10 01:30:01 +0000431 int beg = 0, end = n;
432 while (beg < end) {
433 int med = (beg + end) / 2;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000434 uptr g = (uptr)page_groups_[med];
Kostya Serebryany25c71782012-03-10 01:30:01 +0000435 if (addr > g) {
436 // 'g' points to the end of the group, so 'addr'
437 // may not belong to page_groups_[med] or any previous group.
438 beg = med + 1;
439 } else {
440 // 'addr' may belong to page_groups_[med] or a previous group.
441 end = med;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000442 }
443 }
Kostya Serebryany25c71782012-03-10 01:30:01 +0000444 if (beg >= n)
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000445 return 0;
Kostya Serebryany25c71782012-03-10 01:30:01 +0000446 PageGroup *g = page_groups_[beg];
447 CHECK(g);
448 if (g->InRange(addr))
449 return g;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000450 return 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000451 }
452
453 // We have an address between two chunks, and we want to report just one.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000454 AsanChunk *ChooseChunk(uptr addr,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000455 AsanChunk *left_chunk, AsanChunk *right_chunk) {
456 // Prefer an allocated chunk or a chunk from quarantine.
457 if (left_chunk->chunk_state == CHUNK_AVAILABLE &&
458 right_chunk->chunk_state != CHUNK_AVAILABLE)
459 return right_chunk;
460 if (right_chunk->chunk_state == CHUNK_AVAILABLE &&
461 left_chunk->chunk_state != CHUNK_AVAILABLE)
462 return left_chunk;
463 // Choose based on offset.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000464 uptr l_offset = 0, r_offset = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000465 CHECK(left_chunk->AddrIsAtRight(addr, 1, &l_offset));
466 CHECK(right_chunk->AddrIsAtLeft(addr, 1, &r_offset));
467 if (l_offset < r_offset)
468 return left_chunk;
469 return right_chunk;
470 }
471
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000472 AsanChunk *FindChunkByAddr(uptr addr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000473 PageGroup *g = FindPageGroupUnlocked(addr);
474 if (!g) return 0;
475 CHECK(g->size_of_chunk);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000476 uptr offset_from_beg = addr - g->beg;
477 uptr this_chunk_addr = g->beg +
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000478 (offset_from_beg / g->size_of_chunk) * g->size_of_chunk;
479 CHECK(g->InRange(this_chunk_addr));
480 AsanChunk *m = (AsanChunk*)this_chunk_addr;
481 CHECK(m->chunk_state == CHUNK_ALLOCATED ||
482 m->chunk_state == CHUNK_AVAILABLE ||
483 m->chunk_state == CHUNK_QUARANTINE);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000484 uptr offset = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000485 if (m->AddrIsInside(addr, 1, &offset))
486 return m;
487
488 if (m->AddrIsAtRight(addr, 1, &offset)) {
489 if (this_chunk_addr == g->last_chunk) // rightmost chunk
490 return m;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000491 uptr right_chunk_addr = this_chunk_addr + g->size_of_chunk;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000492 CHECK(g->InRange(right_chunk_addr));
493 return ChooseChunk(addr, m, (AsanChunk*)right_chunk_addr);
494 } else {
495 CHECK(m->AddrIsAtLeft(addr, 1, &offset));
496 if (this_chunk_addr == g->beg) // leftmost chunk
497 return m;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000498 uptr left_chunk_addr = this_chunk_addr - g->size_of_chunk;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000499 CHECK(g->InRange(left_chunk_addr));
500 return ChooseChunk(addr, (AsanChunk*)left_chunk_addr, m);
501 }
502 }
503
504 void QuarantinePop() {
505 CHECK(quarantine_.size() > 0);
506 AsanChunk *m = quarantine_.Pop();
507 CHECK(m);
508 // if (F_v >= 2) Printf("MallocInfo::pop %p\n", m);
509
510 CHECK(m->chunk_state == CHUNK_QUARANTINE);
511 m->chunk_state = CHUNK_AVAILABLE;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000512 PoisonShadow((uptr)m, m->Size(), kAsanHeapLeftRedzoneMagic);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000513 CHECK(m->alloc_tid >= 0);
514 CHECK(m->free_tid >= 0);
515
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000516 uptr size_class = m->SizeClass();
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000517 m->next = free_lists_[size_class];
518 free_lists_[size_class] = m;
519
Kostya Serebryany30743142011-12-05 19:17:53 +0000520 // Statistics.
521 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
522 thread_stats.real_frees++;
523 thread_stats.really_freed += m->used_size;
524 thread_stats.really_freed_redzones += m->Size() - m->used_size;
525 thread_stats.really_freed_by_size[m->SizeClass()]++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000526 }
527
528 // Get a list of newly allocated chunks.
Kostya Serebryanyee392552012-05-31 15:02:07 +0000529 AsanChunk *GetNewChunks(u8 size_class) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000530 uptr size = SizeClassToSize(size_class);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000531 CHECK(IsPowerOfTwo(kMinMmapSize));
532 CHECK(size < kMinMmapSize || (size % kMinMmapSize) == 0);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000533 uptr mmap_size = Max(size, kMinMmapSize);
534 uptr n_chunks = mmap_size / size;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000535 CHECK(n_chunks * size == mmap_size);
536 if (size < kPageSize) {
537 // Size is small, just poison the last chunk.
538 n_chunks--;
539 } else {
540 // Size is large, allocate an extra page at right and poison it.
541 mmap_size += kPageSize;
542 }
543 CHECK(n_chunks > 0);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000544 u8 *mem = MmapNewPagesAndPoisonShadow(mmap_size);
Kostya Serebryany30743142011-12-05 19:17:53 +0000545
546 // Statistics.
547 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
548 thread_stats.mmaps++;
549 thread_stats.mmaped += mmap_size;
550 thread_stats.mmaped_by_size[size_class] += n_chunks;
551
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000552 AsanChunk *res = 0;
553 for (uptr i = 0; i < n_chunks; i++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000554 AsanChunk *m = (AsanChunk*)(mem + i * size);
555 m->chunk_state = CHUNK_AVAILABLE;
556 m->size_class = size_class;
557 m->next = res;
558 res = m;
559 }
560 PageGroup *pg = (PageGroup*)(mem + n_chunks * size);
561 // This memory is already poisoned, no need to poison it again.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000562 pg->beg = (uptr)mem;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000563 pg->end = pg->beg + mmap_size;
564 pg->size_of_chunk = size;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000565 pg->last_chunk = (uptr)(mem + size * (n_chunks - 1));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000566 int page_group_idx = AtomicInc(&n_page_groups_) - 1;
567 CHECK(page_group_idx < (int)ASAN_ARRAY_SIZE(page_groups_));
568 page_groups_[page_group_idx] = pg;
569 return res;
570 }
571
572 AsanChunk *free_lists_[kNumberOfSizeClasses];
573 AsanChunkFifoList quarantine_;
574 AsanLock mu_;
575
576 PageGroup *page_groups_[kMaxAvailableRam / kMinMmapSize];
577 int n_page_groups_; // atomic
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000578 int n_sorted_page_groups_;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000579};
580
581static MallocInfo malloc_info(LINKER_INITIALIZED);
582
583void AsanThreadLocalMallocStorage::CommitBack() {
584 malloc_info.SwallowThreadLocalMallocStorage(this, true);
585}
586
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000587static void Describe(uptr addr, uptr access_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000588 AsanChunk *m = malloc_info.FindMallocedOrFreed(addr, access_size);
589 if (!m) return;
590 m->DescribeAddress(addr, access_size);
591 CHECK(m->alloc_tid >= 0);
592 AsanThreadSummary *alloc_thread =
593 asanThreadRegistry().FindByTid(m->alloc_tid);
594 AsanStackTrace alloc_stack;
595 AsanStackTrace::UncompressStack(&alloc_stack, m->compressed_alloc_stack(),
596 m->compressed_alloc_stack_size());
597 AsanThread *t = asanThreadRegistry().GetCurrent();
598 CHECK(t);
Kostya Serebryanye0cff0b2012-06-06 15:06:58 +0000599 if (m->free_tid != kInvalidTid) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000600 AsanThreadSummary *free_thread =
601 asanThreadRegistry().FindByTid(m->free_tid);
Alexey Samsonove9541012012-06-06 13:11:29 +0000602 AsanPrintf("freed by thread T%d here:\n", free_thread->tid());
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000603 AsanStackTrace free_stack;
604 AsanStackTrace::UncompressStack(&free_stack, m->compressed_free_stack(),
605 m->compressed_free_stack_size());
606 free_stack.PrintStack();
Alexey Samsonove9541012012-06-06 13:11:29 +0000607 AsanPrintf("previously allocated by thread T%d here:\n",
608 alloc_thread->tid());
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000609
610 alloc_stack.PrintStack();
611 t->summary()->Announce();
612 free_thread->Announce();
613 alloc_thread->Announce();
614 } else {
Alexey Samsonove9541012012-06-06 13:11:29 +0000615 AsanPrintf("allocated by thread T%d here:\n", alloc_thread->tid());
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000616 alloc_stack.PrintStack();
617 t->summary()->Announce();
618 alloc_thread->Announce();
619 }
620}
621
Kostya Serebryanyee392552012-05-31 15:02:07 +0000622static u8 *Allocate(uptr alignment, uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000623 __asan_init();
624 CHECK(stack);
625 if (size == 0) {
626 size = 1; // TODO(kcc): do something smarter
627 }
628 CHECK(IsPowerOfTwo(alignment));
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000629 uptr rounded_size = RoundUpTo(size, REDZONE);
630 uptr needed_size = rounded_size + REDZONE;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000631 if (alignment > REDZONE) {
632 needed_size += alignment;
633 }
634 CHECK(IsAligned(needed_size, REDZONE));
635 if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) {
Alexey Samsonov5bcca4e2012-06-06 10:46:00 +0000636 Report("WARNING: AddressSanitizer failed to allocate %p bytes\n",
637 (void*)size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000638 return 0;
639 }
640
Kostya Serebryanyee392552012-05-31 15:02:07 +0000641 u8 size_class = SizeToSizeClass(needed_size);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000642 uptr size_to_allocate = SizeClassToSize(size_class);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000643 CHECK(size_to_allocate >= kMinAllocSize);
644 CHECK(size_to_allocate >= needed_size);
645 CHECK(IsAligned(size_to_allocate, REDZONE));
646
Alexander Potapenko108a2372012-03-27 16:37:16 +0000647 if (FLAG_v >= 3) {
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000648 Printf("Allocate align: %zu size: %zu class: %u real: %zu\n",
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000649 alignment, size, size_class, size_to_allocate);
650 }
651
652 AsanThread *t = asanThreadRegistry().GetCurrent();
653 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
Kostya Serebryany30743142011-12-05 19:17:53 +0000654 // Statistics
655 thread_stats.mallocs++;
656 thread_stats.malloced += size;
657 thread_stats.malloced_redzones += size_to_allocate - size;
658 thread_stats.malloced_by_size[size_class]++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000659
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000660 AsanChunk *m = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000661 if (!t || size_to_allocate >= kMaxSizeForThreadLocalFreeList) {
662 // get directly from global storage.
663 m = malloc_info.AllocateChunks(size_class, 1);
Kostya Serebryany30743142011-12-05 19:17:53 +0000664 thread_stats.malloc_large++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000665 } else {
666 // get from the thread-local storage.
667 AsanChunk **fl = &t->malloc_storage().free_lists_[size_class];
668 if (!*fl) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000669 uptr n_new_chunks = kMaxSizeForThreadLocalFreeList / size_to_allocate;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000670 *fl = malloc_info.AllocateChunks(size_class, n_new_chunks);
Kostya Serebryany30743142011-12-05 19:17:53 +0000671 thread_stats.malloc_small_slow++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000672 }
673 m = *fl;
674 *fl = (*fl)->next;
675 }
676 CHECK(m);
677 CHECK(m->chunk_state == CHUNK_AVAILABLE);
678 m->chunk_state = CHUNK_ALLOCATED;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000679 m->next = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000680 CHECK(m->Size() == size_to_allocate);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000681 uptr addr = (uptr)m + REDZONE;
682 CHECK(addr == (uptr)m->compressed_free_stack());
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000683
684 if (alignment > REDZONE && (addr & (alignment - 1))) {
685 addr = RoundUpTo(addr, alignment);
686 CHECK((addr & (alignment - 1)) == 0);
687 AsanChunk *p = (AsanChunk*)(addr - REDZONE);
688 p->chunk_state = CHUNK_MEMALIGN;
689 p->next = m;
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000690 m->alignment_log = Log2(alignment);
691 CHECK(m->Beg() == addr);
692 } else {
693 m->alignment_log = Log2(REDZONE);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000694 }
695 CHECK(m == PtrToChunk(addr));
696 m->used_size = size;
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000697 CHECK(m->Beg() == addr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000698 m->alloc_tid = t ? t->tid() : 0;
Kostya Serebryanye0cff0b2012-06-06 15:06:58 +0000699 m->free_tid = kInvalidTid;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000700 AsanStackTrace::CompressStack(stack, m->compressed_alloc_stack(),
701 m->compressed_alloc_stack_size());
702 PoisonShadow(addr, rounded_size, 0);
703 if (size < rounded_size) {
Kostya Serebryany218a9b72011-11-30 18:50:23 +0000704 PoisonHeapPartialRightRedzone(addr + rounded_size - REDZONE,
705 size & (REDZONE - 1));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000706 }
707 if (size <= FLAG_max_malloc_fill_size) {
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000708 REAL(memset)((void*)addr, 0, rounded_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000709 }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000710 return (u8*)addr;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000711}
712
Kostya Serebryanyee392552012-05-31 15:02:07 +0000713static void Deallocate(u8 *ptr, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000714 if (!ptr) return;
715 CHECK(stack);
716
717 if (FLAG_debug) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000718 CHECK(malloc_info.FindPageGroup((uptr)ptr));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000719 }
720
721 // Printf("Deallocate %p\n", ptr);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000722 AsanChunk *m = PtrToChunk((uptr)ptr);
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000723
Kostya Serebryanyf4a4d5a2012-06-06 15:30:55 +0000724 // Flip the chunk_state atomically to avoid race on double-free.
725 u8 old_chunk_state = AtomicExchange((u8*)m, CHUNK_QUARANTINE);
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000726
727 if (old_chunk_state == CHUNK_QUARANTINE) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000728 AsanReport("ERROR: AddressSanitizer attempting double-free on %p:\n", ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000729 stack->PrintStack();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000730 Describe((uptr)ptr, 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000731 ShowStatsAndAbort();
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000732 } else if (old_chunk_state != CHUNK_ALLOCATED) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000733 AsanReport("ERROR: AddressSanitizer attempting free on address "
734 "which was not malloc()-ed: %p\n", ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000735 stack->PrintStack();
736 ShowStatsAndAbort();
737 }
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000738 CHECK(old_chunk_state == CHUNK_ALLOCATED);
Kostya Serebryanye0cff0b2012-06-06 15:06:58 +0000739 CHECK(m->free_tid == kInvalidTid);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000740 CHECK(m->alloc_tid >= 0);
741 AsanThread *t = asanThreadRegistry().GetCurrent();
742 m->free_tid = t ? t->tid() : 0;
743 AsanStackTrace::CompressStack(stack, m->compressed_free_stack(),
744 m->compressed_free_stack_size());
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000745 uptr rounded_size = RoundUpTo(m->used_size, REDZONE);
746 PoisonShadow((uptr)ptr, rounded_size, kAsanHeapFreeMagic);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000747
Kostya Serebryany30743142011-12-05 19:17:53 +0000748 // Statistics.
749 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
750 thread_stats.frees++;
751 thread_stats.freed += m->used_size;
752 thread_stats.freed_by_size[m->SizeClass()]++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000753
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000754 CHECK(m->chunk_state == CHUNK_QUARANTINE);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000755 if (t) {
756 AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
757 CHECK(!m->next);
758 ms->quarantine_.Push(m);
759
760 if (ms->quarantine_.size() > kMaxThreadLocalQuarantine) {
761 malloc_info.SwallowThreadLocalMallocStorage(ms, false);
762 }
763 } else {
764 CHECK(!m->next);
765 malloc_info.BypassThreadLocalQuarantine(m);
766 }
767}
768
Kostya Serebryanyee392552012-05-31 15:02:07 +0000769static u8 *Reallocate(u8 *old_ptr, uptr new_size,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000770 AsanStackTrace *stack) {
771 CHECK(old_ptr && new_size);
Kostya Serebryany30743142011-12-05 19:17:53 +0000772
773 // Statistics.
774 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
775 thread_stats.reallocs++;
776 thread_stats.realloced += new_size;
777
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000778 AsanChunk *m = PtrToChunk((uptr)old_ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000779 CHECK(m->chunk_state == CHUNK_ALLOCATED);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000780 uptr old_size = m->used_size;
781 uptr memcpy_size = Min(new_size, old_size);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000782 u8 *new_ptr = Allocate(0, new_size, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000783 if (new_ptr) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000784 CHECK(REAL(memcpy) != 0);
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000785 REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000786 Deallocate(old_ptr, stack);
787 }
788 return new_ptr;
789}
790
791} // namespace __asan
792
793// Malloc hooks declaration.
794// ASAN_NEW_HOOK(ptr, size) is called immediately after
795// allocation of "size" bytes, which returned "ptr".
796// ASAN_DELETE_HOOK(ptr) is called immediately before
797// deallocation of "ptr".
798// If ASAN_NEW_HOOK or ASAN_DELETE_HOOK is defined, user
799// program must provide implementation of this hook.
800// If macro is undefined, the hook is no-op.
801#ifdef ASAN_NEW_HOOK
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000802extern "C" void ASAN_NEW_HOOK(void *ptr, uptr size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000803#else
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000804static inline void ASAN_NEW_HOOK(void *ptr, uptr size) { }
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000805#endif
806
807#ifdef ASAN_DELETE_HOOK
808extern "C" void ASAN_DELETE_HOOK(void *ptr);
809#else
810static inline void ASAN_DELETE_HOOK(void *ptr) { }
811#endif
812
813namespace __asan {
814
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000815void *asan_memalign(uptr alignment, uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000816 void *ptr = (void*)Allocate(alignment, size, stack);
817 ASAN_NEW_HOOK(ptr, size);
818 return ptr;
819}
820
821void asan_free(void *ptr, AsanStackTrace *stack) {
822 ASAN_DELETE_HOOK(ptr);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000823 Deallocate((u8*)ptr, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000824}
825
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000826void *asan_malloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000827 void *ptr = (void*)Allocate(0, size, stack);
828 ASAN_NEW_HOOK(ptr, size);
829 return ptr;
830}
831
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000832void *asan_calloc(uptr nmemb, uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000833 void *ptr = (void*)Allocate(0, nmemb * size, stack);
834 if (ptr)
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000835 REAL(memset)(ptr, 0, nmemb * size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000836 ASAN_NEW_HOOK(ptr, nmemb * size);
837 return ptr;
838}
839
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000840void *asan_realloc(void *p, uptr size, AsanStackTrace *stack) {
841 if (p == 0) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000842 void *ptr = (void*)Allocate(0, size, stack);
843 ASAN_NEW_HOOK(ptr, size);
844 return ptr;
845 } else if (size == 0) {
846 ASAN_DELETE_HOOK(p);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000847 Deallocate((u8*)p, stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000848 return 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000849 }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000850 return Reallocate((u8*)p, size, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000851}
852
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000853void *asan_valloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000854 void *ptr = (void*)Allocate(kPageSize, size, stack);
855 ASAN_NEW_HOOK(ptr, size);
856 return ptr;
857}
858
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000859void *asan_pvalloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000860 size = RoundUpTo(size, kPageSize);
861 if (size == 0) {
862 // pvalloc(0) should allocate one page.
863 size = kPageSize;
864 }
865 void *ptr = (void*)Allocate(kPageSize, size, stack);
866 ASAN_NEW_HOOK(ptr, size);
867 return ptr;
868}
869
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000870int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000871 AsanStackTrace *stack) {
872 void *ptr = Allocate(alignment, size, stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000873 CHECK(IsAligned((uptr)ptr, alignment));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000874 ASAN_NEW_HOOK(ptr, size);
875 *memptr = ptr;
876 return 0;
877}
878
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000879uptr asan_malloc_usable_size(void *ptr, AsanStackTrace *stack) {
Alexey Samsonovca2278d2012-01-18 15:26:55 +0000880 CHECK(stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000881 if (ptr == 0) return 0;
882 uptr usable_size = malloc_info.AllocationSize((uptr)ptr);
Alexander Potapenko37931232012-05-25 15:20:13 +0000883 if (FLAG_check_malloc_usable_size && (usable_size == 0)) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000884 AsanReport("ERROR: AddressSanitizer attempting to call "
885 "malloc_usable_size() for pointer which is "
886 "not owned: %p\n", ptr);
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000887 stack->PrintStack();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000888 Describe((uptr)ptr, 1);
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000889 ShowStatsAndAbort();
890 }
891 return usable_size;
892}
893
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000894uptr asan_mz_size(const void *ptr) {
895 return malloc_info.AllocationSize((uptr)ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000896}
897
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000898void DescribeHeapAddress(uptr addr, uptr access_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000899 Describe(addr, access_size);
900}
901
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000902void asan_mz_force_lock() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000903 malloc_info.ForceLock();
904}
905
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000906void asan_mz_force_unlock() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000907 malloc_info.ForceUnlock();
908}
909
910// ---------------------- Fake stack-------------------- {{{1
911FakeStack::FakeStack() {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000912 CHECK(REAL(memset) != 0);
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000913 REAL(memset)(this, 0, sizeof(*this));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000914}
915
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000916bool FakeStack::AddrIsInSizeClass(uptr addr, uptr size_class) {
917 uptr mem = allocated_size_classes_[size_class];
918 uptr size = ClassMmapSize(size_class);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000919 bool res = mem && addr >= mem && addr < mem + size;
920 return res;
921}
922
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000923uptr FakeStack::AddrIsInFakeStack(uptr addr) {
924 for (uptr i = 0; i < kNumberOfSizeClasses; i++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000925 if (AddrIsInSizeClass(addr, i)) return allocated_size_classes_[i];
926 }
927 return 0;
928}
929
930// We may want to compute this during compilation.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000931inline uptr FakeStack::ComputeSizeClass(uptr alloc_size) {
932 uptr rounded_size = RoundUpToPowerOfTwo(alloc_size);
933 uptr log = Log2(rounded_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000934 CHECK(alloc_size <= (1UL << log));
935 if (!(alloc_size > (1UL << (log-1)))) {
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000936 Printf("alloc_size %zu log %zu\n", alloc_size, log);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000937 }
938 CHECK(alloc_size > (1UL << (log-1)));
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000939 uptr res = log < kMinStackFrameSizeLog ? 0 : log - kMinStackFrameSizeLog;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000940 CHECK(res < kNumberOfSizeClasses);
941 CHECK(ClassSize(res) >= rounded_size);
942 return res;
943}
944
945void FakeFrameFifo::FifoPush(FakeFrame *node) {
946 CHECK(node);
947 node->next = 0;
948 if (first_ == 0 && last_ == 0) {
949 first_ = last_ = node;
950 } else {
951 CHECK(first_);
952 CHECK(last_);
953 last_->next = node;
954 last_ = node;
955 }
956}
957
958FakeFrame *FakeFrameFifo::FifoPop() {
959 CHECK(first_ && last_ && "Exhausted fake stack");
960 FakeFrame *res = 0;
961 if (first_ == last_) {
962 res = first_;
963 first_ = last_ = 0;
964 } else {
965 res = first_;
966 first_ = first_->next;
967 }
968 return res;
969}
970
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000971void FakeStack::Init(uptr stack_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000972 stack_size_ = stack_size;
973 alive_ = true;
974}
975
976void FakeStack::Cleanup() {
977 alive_ = false;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000978 for (uptr i = 0; i < kNumberOfSizeClasses; i++) {
979 uptr mem = allocated_size_classes_[i];
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000980 if (mem) {
981 PoisonShadow(mem, ClassMmapSize(i), 0);
982 allocated_size_classes_[i] = 0;
Alexey Samsonova25b3462012-06-06 16:15:07 +0000983 UnmapOrDie((void*)mem, ClassMmapSize(i));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000984 }
985 }
986}
987
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000988uptr FakeStack::ClassMmapSize(uptr size_class) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000989 return RoundUpToPowerOfTwo(stack_size_);
990}
991
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000992void FakeStack::AllocateOneSizeClass(uptr size_class) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000993 CHECK(ClassMmapSize(size_class) >= kPageSize);
Alexey Samsonova25b3462012-06-06 16:15:07 +0000994 uptr new_mem = (uptr)MmapOrDie(
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000995 ClassMmapSize(size_class), __FUNCTION__);
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000996 // Printf("T%d new_mem[%zu]: %p-%p mmap %zu\n",
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000997 // asanThreadRegistry().GetCurrent()->tid(),
998 // size_class, new_mem, new_mem + ClassMmapSize(size_class),
999 // ClassMmapSize(size_class));
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001000 uptr i;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001001 for (i = 0; i < ClassMmapSize(size_class);
1002 i += ClassSize(size_class)) {
1003 size_classes_[size_class].FifoPush((FakeFrame*)(new_mem + i));
1004 }
1005 CHECK(i == ClassMmapSize(size_class));
1006 allocated_size_classes_[size_class] = new_mem;
1007}
1008
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001009uptr FakeStack::AllocateStack(uptr size, uptr real_stack) {
Kostya Serebryanyc4b34d92011-12-09 01:49:31 +00001010 if (!alive_) return real_stack;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001011 CHECK(size <= kMaxStackMallocSize && size > 1);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001012 uptr size_class = ComputeSizeClass(size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001013 if (!allocated_size_classes_[size_class]) {
1014 AllocateOneSizeClass(size_class);
1015 }
1016 FakeFrame *fake_frame = size_classes_[size_class].FifoPop();
1017 CHECK(fake_frame);
1018 fake_frame->size_minus_one = size - 1;
1019 fake_frame->real_stack = real_stack;
1020 while (FakeFrame *top = call_stack_.top()) {
1021 if (top->real_stack > real_stack) break;
1022 call_stack_.LifoPop();
1023 DeallocateFrame(top);
1024 }
1025 call_stack_.LifoPush(fake_frame);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001026 uptr ptr = (uptr)fake_frame;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001027 PoisonShadow(ptr, size, 0);
1028 return ptr;
1029}
1030
1031void FakeStack::DeallocateFrame(FakeFrame *fake_frame) {
1032 CHECK(alive_);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001033 uptr size = fake_frame->size_minus_one + 1;
1034 uptr size_class = ComputeSizeClass(size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001035 CHECK(allocated_size_classes_[size_class]);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001036 uptr ptr = (uptr)fake_frame;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001037 CHECK(AddrIsInSizeClass(ptr, size_class));
1038 CHECK(AddrIsInSizeClass(ptr + size - 1, size_class));
1039 size_classes_[size_class].FifoPush(fake_frame);
1040}
1041
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001042void FakeStack::OnFree(uptr ptr, uptr size, uptr real_stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001043 FakeFrame *fake_frame = (FakeFrame*)ptr;
1044 CHECK(fake_frame->magic = kRetiredStackFrameMagic);
1045 CHECK(fake_frame->descr != 0);
1046 CHECK(fake_frame->size_minus_one == size - 1);
1047 PoisonShadow(ptr, size, kAsanStackAfterReturnMagic);
1048}
1049
1050} // namespace __asan
1051
1052// ---------------------- Interface ---------------- {{{1
1053using namespace __asan; // NOLINT
1054
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001055uptr __asan_stack_malloc(uptr size, uptr real_stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001056 if (!FLAG_use_fake_stack) return real_stack;
1057 AsanThread *t = asanThreadRegistry().GetCurrent();
1058 if (!t) {
1059 // TSD is gone, use the real stack.
1060 return real_stack;
1061 }
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001062 uptr ptr = t->fake_stack().AllocateStack(size, real_stack);
Evgeniy Stepanov739eb792012-03-21 11:32:46 +00001063 // Printf("__asan_stack_malloc %p %zu %p\n", ptr, size, real_stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001064 return ptr;
1065}
1066
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001067void __asan_stack_free(uptr ptr, uptr size, uptr real_stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001068 if (!FLAG_use_fake_stack) return;
1069 if (ptr != real_stack) {
1070 FakeStack::OnFree(ptr, size, real_stack);
1071 }
1072}
1073
1074// ASan allocator doesn't reserve extra bytes, so normally we would
1075// just return "size".
Kostya Serebryany9aead372012-05-31 14:11:07 +00001076uptr __asan_get_estimated_allocated_size(uptr size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001077 if (size == 0) return 1;
Kostya Serebryany2d8b3bd2011-12-02 18:42:04 +00001078 return Min(size, kMaxAllowedMallocSize);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001079}
1080
1081bool __asan_get_ownership(const void *p) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001082 return malloc_info.AllocationSize((uptr)p) > 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001083}
1084
Kostya Serebryany9aead372012-05-31 14:11:07 +00001085uptr __asan_get_allocated_size(const void *p) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001086 if (p == 0) return 0;
1087 uptr allocated_size = malloc_info.AllocationSize((uptr)p);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001088 // Die if p is not malloced or if it is already freed.
Alexey Samsonovca2278d2012-01-18 15:26:55 +00001089 if (allocated_size == 0) {
Alexey Samsonove9541012012-06-06 13:11:29 +00001090 AsanReport("ERROR: AddressSanitizer attempting to call "
1091 "__asan_get_allocated_size() for pointer which is "
1092 "not owned: %p\n", p);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001093 PRINT_CURRENT_STACK();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001094 Describe((uptr)p, 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001095 ShowStatsAndAbort();
1096 }
1097 return allocated_size;
1098}