blob: b9c194233cfe354ae2f2fba62d22aec8f95ec81a [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"
Dmitry Vyukovfce5bd42012-06-29 16:58:33 +000037#include "sanitizer_common/sanitizer_atomic.h"
Kostya Serebryany1e172b42011-11-30 01:07:02 +000038
Timur Iskhodzhanov8c505ef2012-05-21 14:25:36 +000039#if defined(_WIN32) && !defined(__clang__)
Kostya Serebryany85822082012-01-30 20:55:02 +000040#include <intrin.h>
41#endif
42
Kostya Serebryany1e172b42011-11-30 01:07:02 +000043namespace __asan {
44
Alexey Samsonov63201b12012-07-23 09:11:58 +000045#define REDZONE ((uptr)(flags()->redzone))
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000046static const uptr kMinAllocSize = REDZONE * 2;
Kostya Serebryanyee392552012-05-31 15:02:07 +000047static const u64 kMaxAvailableRam = 128ULL << 30; // 128G
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000048static const uptr kMaxThreadLocalQuarantine = 1 << 20; // 1M
Evgeniy Stepanov788e1d72012-02-16 13:35:11 +000049
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000050static const uptr kMinMmapSize = (ASAN_LOW_MEMORY) ? 4UL << 17 : 4UL << 20;
51static const uptr kMaxSizeForThreadLocalFreeList =
Evgeniy Stepanov8ae44ac2012-02-27 13:07:29 +000052 (ASAN_LOW_MEMORY) ? 1 << 15 : 1 << 17;
Kostya Serebryany1e172b42011-11-30 01:07:02 +000053
54// Size classes less than kMallocSizeClassStep are powers of two.
55// All other size classes are multiples of kMallocSizeClassStep.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000056static const uptr kMallocSizeClassStepLog = 26;
57static const uptr kMallocSizeClassStep = 1UL << kMallocSizeClassStepLog;
Kostya Serebryany1e172b42011-11-30 01:07:02 +000058
Kostya Serebryany9aead372012-05-31 14:11:07 +000059static const uptr kMaxAllowedMallocSize =
Evgeniy Stepanov8ae44ac2012-02-27 13:07:29 +000060 (__WORDSIZE == 32) ? 3UL << 30 : 8UL << 30;
Kostya Serebryany1e172b42011-11-30 01:07:02 +000061
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000062static inline bool IsAligned(uptr a, uptr alignment) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +000063 return (a & (alignment - 1)) == 0;
64}
65
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000066static inline uptr Log2(uptr x) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +000067 CHECK(IsPowerOfTwo(x));
Timur Iskhodzhanov8c505ef2012-05-21 14:25:36 +000068#if !defined(_WIN32) || defined(__clang__)
69 return __builtin_ctzl(x);
70#elif defined(_WIN64)
Alexander Potapenko6f045292012-01-27 15:15:04 +000071 unsigned long ret; // NOLINT
72 _BitScanForward64(&ret, x);
73 return ret;
Timur Iskhodzhanov8c505ef2012-05-21 14:25:36 +000074#else
Alexander Potapenko6f045292012-01-27 15:15:04 +000075 unsigned long ret; // NOLINT
76 _BitScanForward(&ret, x);
77 return ret;
Alexander Potapenko6f045292012-01-27 15:15:04 +000078#endif
79}
80
Kostya Serebryany3f4c3872012-05-31 14:35:53 +000081static inline uptr RoundUpToPowerOfTwo(uptr size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +000082 CHECK(size);
83 if (IsPowerOfTwo(size)) return size;
Alexander Potapenko6f045292012-01-27 15:15:04 +000084
Alexey Samsonovf927ddc2012-02-03 08:50:16 +000085 unsigned long up; // NOLINT
Timur Iskhodzhanov8c505ef2012-05-21 14:25:36 +000086#if !defined(_WIN32) || defined(__clang__)
Alexey Samsonovf927ddc2012-02-03 08:50:16 +000087 up = __WORDSIZE - 1 - __builtin_clzl(size);
Timur Iskhodzhanov8c505ef2012-05-21 14:25:36 +000088#elif defined(_WIN64)
89 _BitScanReverse64(&up, size);
90#else
91 _BitScanReverse(&up, size);
Alexey Samsonovf927ddc2012-02-03 08:50:16 +000092#endif
93 CHECK(size < (1ULL << (up + 1)));
94 CHECK(size > (1ULL << up));
95 return 1UL << (up + 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +000096}
97
Kostya Serebryanyee392552012-05-31 15:02:07 +000098static inline uptr SizeClassToSize(u8 size_class) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +000099 CHECK(size_class < kNumberOfSizeClasses);
100 if (size_class <= kMallocSizeClassStepLog) {
101 return 1UL << size_class;
102 } else {
103 return (size_class - kMallocSizeClassStepLog) * kMallocSizeClassStep;
104 }
105}
106
Kostya Serebryanyee392552012-05-31 15:02:07 +0000107static inline u8 SizeToSizeClass(uptr size) {
108 u8 res = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000109 if (size <= kMallocSizeClassStep) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000110 uptr rounded = RoundUpToPowerOfTwo(size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000111 res = Log2(rounded);
112 } else {
113 res = ((size + kMallocSizeClassStep - 1) / kMallocSizeClassStep)
114 + kMallocSizeClassStepLog;
115 }
116 CHECK(res < kNumberOfSizeClasses);
117 CHECK(size <= SizeClassToSize(res));
118 return res;
119}
120
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000121// Given REDZONE bytes, we need to mark first size bytes
122// as addressable and the rest REDZONE-size bytes as unaddressable.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000123static void PoisonHeapPartialRightRedzone(uptr mem, uptr size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000124 CHECK(size <= REDZONE);
125 CHECK(IsAligned(mem, REDZONE));
126 CHECK(IsPowerOfTwo(SHADOW_GRANULARITY));
127 CHECK(IsPowerOfTwo(REDZONE));
128 CHECK(REDZONE >= SHADOW_GRANULARITY);
Kostya Serebryany218a9b72011-11-30 18:50:23 +0000129 PoisonShadowPartialRightRedzone(mem, size, REDZONE,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000130 kAsanHeapRightRedzoneMagic);
131}
132
Kostya Serebryanyee392552012-05-31 15:02:07 +0000133static u8 *MmapNewPagesAndPoisonShadow(uptr size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000134 CHECK(IsAligned(size, kPageSize));
Alexey Samsonova25b3462012-06-06 16:15:07 +0000135 u8 *res = (u8*)MmapOrDie(size, __FUNCTION__);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000136 PoisonShadow((uptr)res, size, kAsanHeapLeftRedzoneMagic);
Alexey Samsonovcb8c4dc2012-07-09 14:36:04 +0000137 if (flags()->debug) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000138 Printf("ASAN_MMAP: [%p, %p)\n", res, res + size);
139 }
140 return res;
141}
142
143// Every chunk of memory allocated by this allocator can be in one of 3 states:
144// CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated.
145// CHUNK_ALLOCATED: the chunk is allocated and not yet freed.
146// CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone.
147//
148// The pseudo state CHUNK_MEMALIGN is used to mark that the address is not
Kostya Serebryany16071602012-06-06 16:58:21 +0000149// the beginning of a AsanChunk (in which the actual chunk resides at
150// this - this->used_size).
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000151//
152// The magic numbers for the enum values are taken randomly.
153enum {
Kostya Serebryany7ebac952012-06-06 14:46:38 +0000154 CHUNK_AVAILABLE = 0x57,
155 CHUNK_ALLOCATED = 0x32,
156 CHUNK_QUARANTINE = 0x19,
Alexey Samsonovb4fefa72012-06-28 08:27:24 +0000157 CHUNK_MEMALIGN = 0xDC
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000158};
159
160struct ChunkBase {
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000161 // First 8 bytes.
Kostya Serebryanyf4a4d5a2012-06-06 15:30:55 +0000162 uptr chunk_state : 8;
Kostya Serebryanyf4a4d5a2012-06-06 15:30:55 +0000163 uptr alloc_tid : 24;
Dmitry Vyukovfce5bd42012-06-29 16:58:33 +0000164 uptr size_class : 8;
Kostya Serebryanyf4a4d5a2012-06-06 15:30:55 +0000165 uptr free_tid : 24;
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000166
167 // Second 8 bytes.
168 uptr alignment_log : 8;
169 uptr used_size : FIRST_32_SECOND_64(32, 56); // Size requested by the user.
170
Kostya Serebryany16071602012-06-06 16:58:21 +0000171 // This field may overlap with the user area and thus should not
172 // be used while the chunk is in CHUNK_ALLOCATED state.
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000173 AsanChunk *next;
174
Kostya Serebryany6dc48dd2012-06-06 16:33:46 +0000175 // Typically the beginning of the user-accessible memory is 'this'+REDZONE
176 // and is also aligned by REDZONE. However, if the memory is allocated
177 // by memalign, the alignment might be higher and the user-accessible memory
Kostya Serebryany0334fc82012-06-07 09:15:48 +0000178 // starts at the first properly aligned address after 'this'.
179 uptr Beg() { return RoundUpTo((uptr)this + 1, 1 << alignment_log); }
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 Serebryanyee392552012-05-31 15:02:07 +0000186 return (u32*)((uptr)this + sizeof(ChunkBase));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000187 }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000188 u32 *compressed_free_stack() {
Alexey Samsonovcb8c4dc2012-07-09 14:36:04 +0000189 return (u32*)((uptr)this + Max((uptr)REDZONE, (uptr)sizeof(ChunkBase)));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000190 }
191
192 // The left redzone after the ChunkBase is given to the alloc stack trace.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000193 uptr compressed_alloc_stack_size() {
Kostya Serebryany0334fc82012-06-07 09:15:48 +0000194 if (REDZONE < sizeof(ChunkBase)) return 0;
Kostya Serebryanyee392552012-05-31 15:02:07 +0000195 return (REDZONE - sizeof(ChunkBase)) / sizeof(u32);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000196 }
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000197 uptr compressed_free_stack_size() {
Kostya Serebryany0334fc82012-06-07 09:15:48 +0000198 if (REDZONE < sizeof(ChunkBase)) return 0;
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) {
Kostya Serebryany16071602012-06-06 16:58:21 +0000249 m = (AsanChunk*)((uptr)m - m->used_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000250 }
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) {
Alexey Samsonovcb8c4dc2012-07-09 14:36:04 +0000342 CHECK(flags()->quarantine_size > 0);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000343 ScopedLock lock(&mu_);
344 AsanChunkFifoList *q = &x->quarantine_;
345 if (q->size() > 0) {
346 quarantine_.PushList(q);
Alexey Samsonov63201b12012-07-23 09:11:58 +0000347 while (quarantine_.size() > (uptr)flags()->quarantine_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000348 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
Alexander Potapenko531c7d92012-08-06 12:24:39 +0000380 // Make sure this is our chunk and |ptr| actually points to the beginning
381 // of the allocated memory.
382 AsanChunk *m = FindChunkByAddr(ptr);
383 if (!m || m->Beg() != ptr) return 0;
384
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000385 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) {
Dmitry Vyukovfce5bd42012-06-29 16:58:33 +0000425 int n = atomic_load(&n_page_groups_, memory_order_relaxed);
Kostya Serebryany25c71782012-03-10 01:30:01 +0000426 // 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));
Dmitry Vyukovfce5bd42012-06-29 16:58:33 +0000567 int idx = atomic_fetch_add(&n_page_groups_, 1, memory_order_relaxed);
568 CHECK(idx < (int)ASAN_ARRAY_SIZE(page_groups_));
569 page_groups_[idx] = pg;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000570 return res;
571 }
572
573 AsanChunk *free_lists_[kNumberOfSizeClasses];
574 AsanChunkFifoList quarantine_;
575 AsanLock mu_;
576
577 PageGroup *page_groups_[kMaxAvailableRam / kMinMmapSize];
Dmitry Vyukovfce5bd42012-06-29 16:58:33 +0000578 atomic_uint32_t n_page_groups_;
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
Alexey Samsonovcb8c4dc2012-07-09 14:36:04 +0000648 if (flags()->verbosity >= 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;
Kostya Serebryany0334fc82012-06-07 09:15:48 +0000683 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 }
Alexey Samsonov63201b12012-07-23 09:11:58 +0000708 if (size <= (uptr)(flags()->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
Alexey Samsonovcb8c4dc2012-07-09 14:36:04 +0000718 if (flags()->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.
Dmitry Vyukovfce5bd42012-06-29 16:58:33 +0000726 u8 old_chunk_state = atomic_exchange((atomic_uint8_t*)m, CHUNK_QUARANTINE,
727 memory_order_acq_rel);
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000728
729 if (old_chunk_state == CHUNK_QUARANTINE) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000730 AsanReport("ERROR: AddressSanitizer attempting double-free on %p:\n", ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000731 stack->PrintStack();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000732 Describe((uptr)ptr, 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000733 ShowStatsAndAbort();
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000734 } else if (old_chunk_state != CHUNK_ALLOCATED) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000735 AsanReport("ERROR: AddressSanitizer attempting free on address "
736 "which was not malloc()-ed: %p\n", ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000737 stack->PrintStack();
738 ShowStatsAndAbort();
739 }
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000740 CHECK(old_chunk_state == CHUNK_ALLOCATED);
Kostya Serebryany16071602012-06-06 16:58:21 +0000741 // With REDZONE==16 m->next is in the user area, otherwise it should be 0.
742 CHECK(REDZONE <= 16 || !m->next);
Kostya Serebryanye0cff0b2012-06-06 15:06:58 +0000743 CHECK(m->free_tid == kInvalidTid);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000744 CHECK(m->alloc_tid >= 0);
745 AsanThread *t = asanThreadRegistry().GetCurrent();
746 m->free_tid = t ? t->tid() : 0;
747 AsanStackTrace::CompressStack(stack, m->compressed_free_stack(),
748 m->compressed_free_stack_size());
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000749 uptr rounded_size = RoundUpTo(m->used_size, REDZONE);
750 PoisonShadow((uptr)ptr, rounded_size, kAsanHeapFreeMagic);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000751
Kostya Serebryany30743142011-12-05 19:17:53 +0000752 // Statistics.
753 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
754 thread_stats.frees++;
755 thread_stats.freed += m->used_size;
756 thread_stats.freed_by_size[m->SizeClass()]++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000757
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000758 CHECK(m->chunk_state == CHUNK_QUARANTINE);
Kostya Serebryany16071602012-06-06 16:58:21 +0000759
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000760 if (t) {
761 AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000762 ms->quarantine_.Push(m);
763
764 if (ms->quarantine_.size() > kMaxThreadLocalQuarantine) {
765 malloc_info.SwallowThreadLocalMallocStorage(ms, false);
766 }
767 } else {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000768 malloc_info.BypassThreadLocalQuarantine(m);
769 }
770}
771
Kostya Serebryanyee392552012-05-31 15:02:07 +0000772static u8 *Reallocate(u8 *old_ptr, uptr new_size,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000773 AsanStackTrace *stack) {
774 CHECK(old_ptr && new_size);
Kostya Serebryany30743142011-12-05 19:17:53 +0000775
776 // Statistics.
777 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
778 thread_stats.reallocs++;
779 thread_stats.realloced += new_size;
780
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000781 AsanChunk *m = PtrToChunk((uptr)old_ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000782 CHECK(m->chunk_state == CHUNK_ALLOCATED);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000783 uptr old_size = m->used_size;
784 uptr memcpy_size = Min(new_size, old_size);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000785 u8 *new_ptr = Allocate(0, new_size, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000786 if (new_ptr) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000787 CHECK(REAL(memcpy) != 0);
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000788 REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000789 Deallocate(old_ptr, stack);
790 }
791 return new_ptr;
792}
793
794} // namespace __asan
795
796// Malloc hooks declaration.
797// ASAN_NEW_HOOK(ptr, size) is called immediately after
798// allocation of "size" bytes, which returned "ptr".
799// ASAN_DELETE_HOOK(ptr) is called immediately before
800// deallocation of "ptr".
801// If ASAN_NEW_HOOK or ASAN_DELETE_HOOK is defined, user
802// program must provide implementation of this hook.
803// If macro is undefined, the hook is no-op.
804#ifdef ASAN_NEW_HOOK
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000805extern "C" void ASAN_NEW_HOOK(void *ptr, uptr size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000806#else
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000807static inline void ASAN_NEW_HOOK(void *ptr, uptr size) { }
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000808#endif
809
810#ifdef ASAN_DELETE_HOOK
811extern "C" void ASAN_DELETE_HOOK(void *ptr);
812#else
813static inline void ASAN_DELETE_HOOK(void *ptr) { }
814#endif
815
816namespace __asan {
817
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000818void *asan_memalign(uptr alignment, uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000819 void *ptr = (void*)Allocate(alignment, size, stack);
820 ASAN_NEW_HOOK(ptr, size);
821 return ptr;
822}
823
824void asan_free(void *ptr, AsanStackTrace *stack) {
825 ASAN_DELETE_HOOK(ptr);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000826 Deallocate((u8*)ptr, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000827}
828
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000829void *asan_malloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000830 void *ptr = (void*)Allocate(0, size, stack);
831 ASAN_NEW_HOOK(ptr, size);
832 return ptr;
833}
834
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000835void *asan_calloc(uptr nmemb, uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000836 void *ptr = (void*)Allocate(0, nmemb * size, stack);
837 if (ptr)
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000838 REAL(memset)(ptr, 0, nmemb * size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000839 ASAN_NEW_HOOK(ptr, nmemb * size);
840 return ptr;
841}
842
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000843void *asan_realloc(void *p, uptr size, AsanStackTrace *stack) {
844 if (p == 0) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000845 void *ptr = (void*)Allocate(0, size, stack);
846 ASAN_NEW_HOOK(ptr, size);
847 return ptr;
848 } else if (size == 0) {
849 ASAN_DELETE_HOOK(p);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000850 Deallocate((u8*)p, stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000851 return 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000852 }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000853 return Reallocate((u8*)p, size, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000854}
855
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000856void *asan_valloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000857 void *ptr = (void*)Allocate(kPageSize, size, stack);
858 ASAN_NEW_HOOK(ptr, size);
859 return ptr;
860}
861
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000862void *asan_pvalloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000863 size = RoundUpTo(size, kPageSize);
864 if (size == 0) {
865 // pvalloc(0) should allocate one page.
866 size = kPageSize;
867 }
868 void *ptr = (void*)Allocate(kPageSize, size, stack);
869 ASAN_NEW_HOOK(ptr, size);
870 return ptr;
871}
872
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000873int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000874 AsanStackTrace *stack) {
875 void *ptr = Allocate(alignment, size, stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000876 CHECK(IsAligned((uptr)ptr, alignment));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000877 ASAN_NEW_HOOK(ptr, size);
878 *memptr = ptr;
879 return 0;
880}
881
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000882uptr asan_malloc_usable_size(void *ptr, AsanStackTrace *stack) {
Alexey Samsonovca2278d2012-01-18 15:26:55 +0000883 CHECK(stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000884 if (ptr == 0) return 0;
885 uptr usable_size = malloc_info.AllocationSize((uptr)ptr);
Alexey Samsonovcb8c4dc2012-07-09 14:36:04 +0000886 if (flags()->check_malloc_usable_size && (usable_size == 0)) {
Alexey Samsonove9541012012-06-06 13:11:29 +0000887 AsanReport("ERROR: AddressSanitizer attempting to call "
888 "malloc_usable_size() for pointer which is "
889 "not owned: %p\n", ptr);
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000890 stack->PrintStack();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000891 Describe((uptr)ptr, 1);
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000892 ShowStatsAndAbort();
893 }
894 return usable_size;
895}
896
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000897uptr asan_mz_size(const void *ptr) {
898 return malloc_info.AllocationSize((uptr)ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000899}
900
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000901void DescribeHeapAddress(uptr addr, uptr access_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000902 Describe(addr, access_size);
903}
904
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000905void asan_mz_force_lock() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000906 malloc_info.ForceLock();
907}
908
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000909void asan_mz_force_unlock() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000910 malloc_info.ForceUnlock();
911}
912
913// ---------------------- Fake stack-------------------- {{{1
914FakeStack::FakeStack() {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000915 CHECK(REAL(memset) != 0);
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000916 REAL(memset)(this, 0, sizeof(*this));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000917}
918
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000919bool FakeStack::AddrIsInSizeClass(uptr addr, uptr size_class) {
920 uptr mem = allocated_size_classes_[size_class];
921 uptr size = ClassMmapSize(size_class);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000922 bool res = mem && addr >= mem && addr < mem + size;
923 return res;
924}
925
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000926uptr FakeStack::AddrIsInFakeStack(uptr addr) {
927 for (uptr i = 0; i < kNumberOfSizeClasses; i++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000928 if (AddrIsInSizeClass(addr, i)) return allocated_size_classes_[i];
929 }
930 return 0;
931}
932
933// We may want to compute this during compilation.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000934inline uptr FakeStack::ComputeSizeClass(uptr alloc_size) {
935 uptr rounded_size = RoundUpToPowerOfTwo(alloc_size);
936 uptr log = Log2(rounded_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000937 CHECK(alloc_size <= (1UL << log));
938 if (!(alloc_size > (1UL << (log-1)))) {
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000939 Printf("alloc_size %zu log %zu\n", alloc_size, log);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000940 }
941 CHECK(alloc_size > (1UL << (log-1)));
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000942 uptr res = log < kMinStackFrameSizeLog ? 0 : log - kMinStackFrameSizeLog;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000943 CHECK(res < kNumberOfSizeClasses);
944 CHECK(ClassSize(res) >= rounded_size);
945 return res;
946}
947
948void FakeFrameFifo::FifoPush(FakeFrame *node) {
949 CHECK(node);
950 node->next = 0;
951 if (first_ == 0 && last_ == 0) {
952 first_ = last_ = node;
953 } else {
954 CHECK(first_);
955 CHECK(last_);
956 last_->next = node;
957 last_ = node;
958 }
959}
960
961FakeFrame *FakeFrameFifo::FifoPop() {
962 CHECK(first_ && last_ && "Exhausted fake stack");
963 FakeFrame *res = 0;
964 if (first_ == last_) {
965 res = first_;
966 first_ = last_ = 0;
967 } else {
968 res = first_;
969 first_ = first_->next;
970 }
971 return res;
972}
973
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000974void FakeStack::Init(uptr stack_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000975 stack_size_ = stack_size;
976 alive_ = true;
977}
978
979void FakeStack::Cleanup() {
980 alive_ = false;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000981 for (uptr i = 0; i < kNumberOfSizeClasses; i++) {
982 uptr mem = allocated_size_classes_[i];
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000983 if (mem) {
984 PoisonShadow(mem, ClassMmapSize(i), 0);
985 allocated_size_classes_[i] = 0;
Alexey Samsonova25b3462012-06-06 16:15:07 +0000986 UnmapOrDie((void*)mem, ClassMmapSize(i));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000987 }
988 }
989}
990
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000991uptr FakeStack::ClassMmapSize(uptr size_class) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000992 return RoundUpToPowerOfTwo(stack_size_);
993}
994
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000995void FakeStack::AllocateOneSizeClass(uptr size_class) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000996 CHECK(ClassMmapSize(size_class) >= kPageSize);
Alexey Samsonova25b3462012-06-06 16:15:07 +0000997 uptr new_mem = (uptr)MmapOrDie(
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000998 ClassMmapSize(size_class), __FUNCTION__);
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000999 // Printf("T%d new_mem[%zu]: %p-%p mmap %zu\n",
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001000 // asanThreadRegistry().GetCurrent()->tid(),
1001 // size_class, new_mem, new_mem + ClassMmapSize(size_class),
1002 // ClassMmapSize(size_class));
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001003 uptr i;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001004 for (i = 0; i < ClassMmapSize(size_class);
1005 i += ClassSize(size_class)) {
1006 size_classes_[size_class].FifoPush((FakeFrame*)(new_mem + i));
1007 }
1008 CHECK(i == ClassMmapSize(size_class));
1009 allocated_size_classes_[size_class] = new_mem;
1010}
1011
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001012uptr FakeStack::AllocateStack(uptr size, uptr real_stack) {
Kostya Serebryanyc4b34d92011-12-09 01:49:31 +00001013 if (!alive_) return real_stack;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001014 CHECK(size <= kMaxStackMallocSize && size > 1);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001015 uptr size_class = ComputeSizeClass(size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001016 if (!allocated_size_classes_[size_class]) {
1017 AllocateOneSizeClass(size_class);
1018 }
1019 FakeFrame *fake_frame = size_classes_[size_class].FifoPop();
1020 CHECK(fake_frame);
1021 fake_frame->size_minus_one = size - 1;
1022 fake_frame->real_stack = real_stack;
1023 while (FakeFrame *top = call_stack_.top()) {
1024 if (top->real_stack > real_stack) break;
1025 call_stack_.LifoPop();
1026 DeallocateFrame(top);
1027 }
1028 call_stack_.LifoPush(fake_frame);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001029 uptr ptr = (uptr)fake_frame;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001030 PoisonShadow(ptr, size, 0);
1031 return ptr;
1032}
1033
1034void FakeStack::DeallocateFrame(FakeFrame *fake_frame) {
1035 CHECK(alive_);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001036 uptr size = fake_frame->size_minus_one + 1;
1037 uptr size_class = ComputeSizeClass(size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001038 CHECK(allocated_size_classes_[size_class]);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001039 uptr ptr = (uptr)fake_frame;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001040 CHECK(AddrIsInSizeClass(ptr, size_class));
1041 CHECK(AddrIsInSizeClass(ptr + size - 1, size_class));
1042 size_classes_[size_class].FifoPush(fake_frame);
1043}
1044
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001045void FakeStack::OnFree(uptr ptr, uptr size, uptr real_stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001046 FakeFrame *fake_frame = (FakeFrame*)ptr;
1047 CHECK(fake_frame->magic = kRetiredStackFrameMagic);
1048 CHECK(fake_frame->descr != 0);
1049 CHECK(fake_frame->size_minus_one == size - 1);
1050 PoisonShadow(ptr, size, kAsanStackAfterReturnMagic);
1051}
1052
1053} // namespace __asan
1054
1055// ---------------------- Interface ---------------- {{{1
1056using namespace __asan; // NOLINT
1057
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001058uptr __asan_stack_malloc(uptr size, uptr real_stack) {
Alexey Samsonovcb8c4dc2012-07-09 14:36:04 +00001059 if (!flags()->use_fake_stack) return real_stack;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001060 AsanThread *t = asanThreadRegistry().GetCurrent();
1061 if (!t) {
1062 // TSD is gone, use the real stack.
1063 return real_stack;
1064 }
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001065 uptr ptr = t->fake_stack().AllocateStack(size, real_stack);
Evgeniy Stepanov739eb792012-03-21 11:32:46 +00001066 // Printf("__asan_stack_malloc %p %zu %p\n", ptr, size, real_stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001067 return ptr;
1068}
1069
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001070void __asan_stack_free(uptr ptr, uptr size, uptr real_stack) {
Alexey Samsonovcb8c4dc2012-07-09 14:36:04 +00001071 if (!flags()->use_fake_stack) return;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001072 if (ptr != real_stack) {
1073 FakeStack::OnFree(ptr, size, real_stack);
1074 }
1075}
1076
1077// ASan allocator doesn't reserve extra bytes, so normally we would
1078// just return "size".
Kostya Serebryany9aead372012-05-31 14:11:07 +00001079uptr __asan_get_estimated_allocated_size(uptr size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001080 if (size == 0) return 1;
Kostya Serebryany2d8b3bd2011-12-02 18:42:04 +00001081 return Min(size, kMaxAllowedMallocSize);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001082}
1083
1084bool __asan_get_ownership(const void *p) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001085 return malloc_info.AllocationSize((uptr)p) > 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001086}
1087
Kostya Serebryany9aead372012-05-31 14:11:07 +00001088uptr __asan_get_allocated_size(const void *p) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001089 if (p == 0) return 0;
1090 uptr allocated_size = malloc_info.AllocationSize((uptr)p);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001091 // Die if p is not malloced or if it is already freed.
Alexey Samsonovca2278d2012-01-18 15:26:55 +00001092 if (allocated_size == 0) {
Alexey Samsonove9541012012-06-06 13:11:29 +00001093 AsanReport("ERROR: AddressSanitizer attempting to call "
1094 "__asan_get_allocated_size() for pointer which is "
1095 "not owned: %p\n", p);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001096 PRINT_CURRENT_STACK();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001097 Describe((uptr)p, 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001098 ShowStatsAndAbort();
1099 }
1100 return allocated_size;
1101}