blob: 314ed835aa775687fd37c414340ba76b3b1d4668 [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));
Kostya Serebryanyee392552012-05-31 15:02:07 +0000134 u8 *res = (u8*)AsanMmapSomewhereOrDie(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 {
153 CHUNK_AVAILABLE = 0x573B,
154 CHUNK_ALLOCATED = 0x3204,
155 CHUNK_QUARANTINE = 0x1978,
156 CHUNK_MEMALIGN = 0xDC68,
157};
158
159struct ChunkBase {
Kostya Serebryanyee392552012-05-31 15:02:07 +0000160 u16 chunk_state;
161 u8 size_class;
162 u32 offset; // User-visible memory starts at this+offset (beg()).
163 s32 alloc_tid;
164 s32 free_tid;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000165 uptr used_size; // Size requested by the user.
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000166 AsanChunk *next;
167
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000168 uptr beg() { return (uptr)this + offset; }
169 uptr Size() { return SizeClassToSize(size_class); }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000170 u8 SizeClass() { return size_class; }
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000171};
172
173struct AsanChunk: public ChunkBase {
Kostya Serebryanyee392552012-05-31 15:02:07 +0000174 u32 *compressed_alloc_stack() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000175 CHECK(REDZONE >= sizeof(ChunkBase));
Kostya Serebryanyee392552012-05-31 15:02:07 +0000176 return (u32*)((uptr)this + sizeof(ChunkBase));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000177 }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000178 u32 *compressed_free_stack() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000179 CHECK(REDZONE >= sizeof(ChunkBase));
Kostya Serebryanyee392552012-05-31 15:02:07 +0000180 return (u32*)((uptr)this + REDZONE);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000181 }
182
183 // The left redzone after the ChunkBase is given to the alloc stack trace.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000184 uptr compressed_alloc_stack_size() {
Kostya Serebryanyee392552012-05-31 15:02:07 +0000185 return (REDZONE - sizeof(ChunkBase)) / sizeof(u32);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000186 }
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000187 uptr compressed_free_stack_size() {
Kostya Serebryanyee392552012-05-31 15:02:07 +0000188 return (REDZONE) / sizeof(u32);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000189 }
190
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000191 bool AddrIsInside(uptr addr, uptr access_size, uptr *offset) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000192 if (addr >= beg() && (addr + access_size) <= (beg() + used_size)) {
193 *offset = addr - beg();
194 return true;
195 }
196 return false;
197 }
198
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000199 bool AddrIsAtLeft(uptr addr, uptr access_size, uptr *offset) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000200 if (addr < beg()) {
201 *offset = beg() - addr;
202 return true;
203 }
204 return false;
205 }
206
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000207 bool AddrIsAtRight(uptr addr, uptr access_size, uptr *offset) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000208 if (addr + access_size >= beg() + used_size) {
209 if (addr <= beg() + used_size)
210 *offset = 0;
211 else
212 *offset = addr - (beg() + used_size);
213 return true;
214 }
215 return false;
216 }
217
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000218 void DescribeAddress(uptr addr, uptr access_size) {
219 uptr offset;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000220 Printf("%p is located ", addr);
221 if (AddrIsInside(addr, access_size, &offset)) {
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000222 Printf("%zu bytes inside of", offset);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000223 } else if (AddrIsAtLeft(addr, access_size, &offset)) {
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000224 Printf("%zu bytes to the left of", offset);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000225 } else if (AddrIsAtRight(addr, access_size, &offset)) {
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000226 Printf("%zu bytes to the right of", offset);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000227 } else {
228 Printf(" somewhere around (this is AddressSanitizer bug!)");
229 }
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000230 Printf(" %zu-byte region [%p,%p)\n",
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000231 used_size, beg(), beg() + used_size);
232 }
233};
234
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000235static AsanChunk *PtrToChunk(uptr ptr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000236 AsanChunk *m = (AsanChunk*)(ptr - REDZONE);
237 if (m->chunk_state == CHUNK_MEMALIGN) {
238 m = m->next;
239 }
240 return m;
241}
242
243
244void AsanChunkFifoList::PushList(AsanChunkFifoList *q) {
Alexey Samsonove0460662012-02-27 09:06:10 +0000245 CHECK(q->size() > 0);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000246 if (last_) {
247 CHECK(first_);
248 CHECK(!last_->next);
249 last_->next = q->first_;
250 last_ = q->last_;
251 } else {
252 CHECK(!first_);
253 last_ = q->last_;
254 first_ = q->first_;
Alexey Samsonove0460662012-02-27 09:06:10 +0000255 CHECK(first_);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000256 }
Alexey Samsonove0460662012-02-27 09:06:10 +0000257 CHECK(last_);
258 CHECK(!last_->next);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000259 size_ += q->size();
260 q->clear();
261}
262
263void AsanChunkFifoList::Push(AsanChunk *n) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000264 CHECK(n->next == 0);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000265 if (last_) {
266 CHECK(first_);
267 CHECK(!last_->next);
268 last_->next = n;
269 last_ = n;
270 } else {
271 CHECK(!first_);
272 last_ = first_ = n;
273 }
274 size_ += n->Size();
275}
276
277// Interesting performance observation: this function takes up to 15% of overal
278// allocator time. That's because *first_ has been evicted from cache long time
279// ago. Not sure if we can or want to do anything with this.
280AsanChunk *AsanChunkFifoList::Pop() {
281 CHECK(first_);
282 AsanChunk *res = first_;
283 first_ = first_->next;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000284 if (first_ == 0)
285 last_ = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000286 CHECK(size_ >= res->Size());
287 size_ -= res->Size();
288 if (last_) {
289 CHECK(!last_->next);
290 }
291 return res;
292}
293
294// All pages we ever allocated.
295struct PageGroup {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000296 uptr beg;
297 uptr end;
298 uptr size_of_chunk;
299 uptr last_chunk;
300 bool InRange(uptr addr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000301 return addr >= beg && addr < end;
302 }
303};
304
305class MallocInfo {
306 public:
307
308 explicit MallocInfo(LinkerInitialized x) : mu_(x) { }
309
Kostya Serebryanyee392552012-05-31 15:02:07 +0000310 AsanChunk *AllocateChunks(u8 size_class, uptr n_chunks) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000311 AsanChunk *m = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000312 AsanChunk **fl = &free_lists_[size_class];
313 {
314 ScopedLock lock(&mu_);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000315 for (uptr i = 0; i < n_chunks; i++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000316 if (!(*fl)) {
317 *fl = GetNewChunks(size_class);
318 }
319 AsanChunk *t = *fl;
320 *fl = t->next;
321 t->next = m;
322 CHECK(t->chunk_state == CHUNK_AVAILABLE);
323 m = t;
324 }
325 }
326 return m;
327 }
328
329 void SwallowThreadLocalMallocStorage(AsanThreadLocalMallocStorage *x,
330 bool eat_free_lists) {
331 CHECK(FLAG_quarantine_size > 0);
332 ScopedLock lock(&mu_);
333 AsanChunkFifoList *q = &x->quarantine_;
334 if (q->size() > 0) {
335 quarantine_.PushList(q);
336 while (quarantine_.size() > FLAG_quarantine_size) {
337 QuarantinePop();
338 }
339 }
340 if (eat_free_lists) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000341 for (uptr size_class = 0; size_class < kNumberOfSizeClasses;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000342 size_class++) {
343 AsanChunk *m = x->free_lists_[size_class];
344 while (m) {
345 AsanChunk *t = m->next;
346 m->next = free_lists_[size_class];
347 free_lists_[size_class] = m;
348 m = t;
349 }
350 x->free_lists_[size_class] = 0;
351 }
352 }
353 }
354
355 void BypassThreadLocalQuarantine(AsanChunk *chunk) {
356 ScopedLock lock(&mu_);
357 quarantine_.Push(chunk);
358 }
359
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000360 AsanChunk *FindMallocedOrFreed(uptr addr, uptr access_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000361 ScopedLock lock(&mu_);
362 return FindChunkByAddr(addr);
363 }
364
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000365 uptr AllocationSize(uptr ptr) {
Alexey Samsonovca2278d2012-01-18 15:26:55 +0000366 if (!ptr) return 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000367 ScopedLock lock(&mu_);
368
369 // first, check if this is our memory
370 PageGroup *g = FindPageGroupUnlocked(ptr);
371 if (!g) return 0;
372 AsanChunk *m = PtrToChunk(ptr);
373 if (m->chunk_state == CHUNK_ALLOCATED) {
374 return m->used_size;
375 } else {
376 return 0;
377 }
378 }
379
380 void ForceLock() {
381 mu_.Lock();
382 }
383
384 void ForceUnlock() {
385 mu_.Unlock();
386 }
387
388 void PrintStatus() {
389 ScopedLock lock(&mu_);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000390 uptr malloced = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000391
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000392 Printf(" MallocInfo: in quarantine: %zu malloced: %zu; ",
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000393 quarantine_.size() >> 20, malloced >> 20);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000394 for (uptr j = 1; j < kNumberOfSizeClasses; j++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000395 AsanChunk *i = free_lists_[j];
396 if (!i) continue;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000397 uptr t = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000398 for (; i; i = i->next) {
399 t += i->Size();
400 }
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000401 Printf("%zu:%zu ", j, t >> 20);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000402 }
403 Printf("\n");
404 }
405
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000406 PageGroup *FindPageGroup(uptr addr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000407 ScopedLock lock(&mu_);
408 return FindPageGroupUnlocked(addr);
409 }
410
411 private:
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000412 PageGroup *FindPageGroupUnlocked(uptr addr) {
Kostya Serebryany25c71782012-03-10 01:30:01 +0000413 int n = n_page_groups_;
414 // If the page groups are not sorted yet, sort them.
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000415 if (n_sorted_page_groups_ < n) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000416 SortArray((uptr*)page_groups_, n);
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000417 n_sorted_page_groups_ = n;
Kostya Serebryany25c71782012-03-10 01:30:01 +0000418 }
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000419 // Binary search over the page groups.
Kostya Serebryany25c71782012-03-10 01:30:01 +0000420 int beg = 0, end = n;
421 while (beg < end) {
422 int med = (beg + end) / 2;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000423 uptr g = (uptr)page_groups_[med];
Kostya Serebryany25c71782012-03-10 01:30:01 +0000424 if (addr > g) {
425 // 'g' points to the end of the group, so 'addr'
426 // may not belong to page_groups_[med] or any previous group.
427 beg = med + 1;
428 } else {
429 // 'addr' may belong to page_groups_[med] or a previous group.
430 end = med;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000431 }
432 }
Kostya Serebryany25c71782012-03-10 01:30:01 +0000433 if (beg >= n)
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000434 return 0;
Kostya Serebryany25c71782012-03-10 01:30:01 +0000435 PageGroup *g = page_groups_[beg];
436 CHECK(g);
437 if (g->InRange(addr))
438 return g;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000439 return 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000440 }
441
442 // We have an address between two chunks, and we want to report just one.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000443 AsanChunk *ChooseChunk(uptr addr,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000444 AsanChunk *left_chunk, AsanChunk *right_chunk) {
445 // Prefer an allocated chunk or a chunk from quarantine.
446 if (left_chunk->chunk_state == CHUNK_AVAILABLE &&
447 right_chunk->chunk_state != CHUNK_AVAILABLE)
448 return right_chunk;
449 if (right_chunk->chunk_state == CHUNK_AVAILABLE &&
450 left_chunk->chunk_state != CHUNK_AVAILABLE)
451 return left_chunk;
452 // Choose based on offset.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000453 uptr l_offset = 0, r_offset = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000454 CHECK(left_chunk->AddrIsAtRight(addr, 1, &l_offset));
455 CHECK(right_chunk->AddrIsAtLeft(addr, 1, &r_offset));
456 if (l_offset < r_offset)
457 return left_chunk;
458 return right_chunk;
459 }
460
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000461 AsanChunk *FindChunkByAddr(uptr addr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000462 PageGroup *g = FindPageGroupUnlocked(addr);
463 if (!g) return 0;
464 CHECK(g->size_of_chunk);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000465 uptr offset_from_beg = addr - g->beg;
466 uptr this_chunk_addr = g->beg +
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000467 (offset_from_beg / g->size_of_chunk) * g->size_of_chunk;
468 CHECK(g->InRange(this_chunk_addr));
469 AsanChunk *m = (AsanChunk*)this_chunk_addr;
470 CHECK(m->chunk_state == CHUNK_ALLOCATED ||
471 m->chunk_state == CHUNK_AVAILABLE ||
472 m->chunk_state == CHUNK_QUARANTINE);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000473 uptr offset = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000474 if (m->AddrIsInside(addr, 1, &offset))
475 return m;
476
477 if (m->AddrIsAtRight(addr, 1, &offset)) {
478 if (this_chunk_addr == g->last_chunk) // rightmost chunk
479 return m;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000480 uptr right_chunk_addr = this_chunk_addr + g->size_of_chunk;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000481 CHECK(g->InRange(right_chunk_addr));
482 return ChooseChunk(addr, m, (AsanChunk*)right_chunk_addr);
483 } else {
484 CHECK(m->AddrIsAtLeft(addr, 1, &offset));
485 if (this_chunk_addr == g->beg) // leftmost chunk
486 return m;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000487 uptr left_chunk_addr = this_chunk_addr - g->size_of_chunk;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000488 CHECK(g->InRange(left_chunk_addr));
489 return ChooseChunk(addr, (AsanChunk*)left_chunk_addr, m);
490 }
491 }
492
493 void QuarantinePop() {
494 CHECK(quarantine_.size() > 0);
495 AsanChunk *m = quarantine_.Pop();
496 CHECK(m);
497 // if (F_v >= 2) Printf("MallocInfo::pop %p\n", m);
498
499 CHECK(m->chunk_state == CHUNK_QUARANTINE);
500 m->chunk_state = CHUNK_AVAILABLE;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000501 PoisonShadow((uptr)m, m->Size(), kAsanHeapLeftRedzoneMagic);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000502 CHECK(m->alloc_tid >= 0);
503 CHECK(m->free_tid >= 0);
504
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000505 uptr size_class = m->SizeClass();
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000506 m->next = free_lists_[size_class];
507 free_lists_[size_class] = m;
508
Kostya Serebryany30743142011-12-05 19:17:53 +0000509 // Statistics.
510 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
511 thread_stats.real_frees++;
512 thread_stats.really_freed += m->used_size;
513 thread_stats.really_freed_redzones += m->Size() - m->used_size;
514 thread_stats.really_freed_by_size[m->SizeClass()]++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000515 }
516
517 // Get a list of newly allocated chunks.
Kostya Serebryanyee392552012-05-31 15:02:07 +0000518 AsanChunk *GetNewChunks(u8 size_class) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000519 uptr size = SizeClassToSize(size_class);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000520 CHECK(IsPowerOfTwo(kMinMmapSize));
521 CHECK(size < kMinMmapSize || (size % kMinMmapSize) == 0);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000522 uptr mmap_size = Max(size, kMinMmapSize);
523 uptr n_chunks = mmap_size / size;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000524 CHECK(n_chunks * size == mmap_size);
525 if (size < kPageSize) {
526 // Size is small, just poison the last chunk.
527 n_chunks--;
528 } else {
529 // Size is large, allocate an extra page at right and poison it.
530 mmap_size += kPageSize;
531 }
532 CHECK(n_chunks > 0);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000533 u8 *mem = MmapNewPagesAndPoisonShadow(mmap_size);
Kostya Serebryany30743142011-12-05 19:17:53 +0000534
535 // Statistics.
536 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
537 thread_stats.mmaps++;
538 thread_stats.mmaped += mmap_size;
539 thread_stats.mmaped_by_size[size_class] += n_chunks;
540
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000541 AsanChunk *res = 0;
542 for (uptr i = 0; i < n_chunks; i++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000543 AsanChunk *m = (AsanChunk*)(mem + i * size);
544 m->chunk_state = CHUNK_AVAILABLE;
545 m->size_class = size_class;
546 m->next = res;
547 res = m;
548 }
549 PageGroup *pg = (PageGroup*)(mem + n_chunks * size);
550 // This memory is already poisoned, no need to poison it again.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000551 pg->beg = (uptr)mem;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000552 pg->end = pg->beg + mmap_size;
553 pg->size_of_chunk = size;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000554 pg->last_chunk = (uptr)(mem + size * (n_chunks - 1));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000555 int page_group_idx = AtomicInc(&n_page_groups_) - 1;
556 CHECK(page_group_idx < (int)ASAN_ARRAY_SIZE(page_groups_));
557 page_groups_[page_group_idx] = pg;
558 return res;
559 }
560
561 AsanChunk *free_lists_[kNumberOfSizeClasses];
562 AsanChunkFifoList quarantine_;
563 AsanLock mu_;
564
565 PageGroup *page_groups_[kMaxAvailableRam / kMinMmapSize];
566 int n_page_groups_; // atomic
Alexey Samsonov9bdf0652012-03-13 06:46:32 +0000567 int n_sorted_page_groups_;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000568};
569
570static MallocInfo malloc_info(LINKER_INITIALIZED);
571
572void AsanThreadLocalMallocStorage::CommitBack() {
573 malloc_info.SwallowThreadLocalMallocStorage(this, true);
574}
575
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000576static void Describe(uptr addr, uptr access_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000577 AsanChunk *m = malloc_info.FindMallocedOrFreed(addr, access_size);
578 if (!m) return;
579 m->DescribeAddress(addr, access_size);
580 CHECK(m->alloc_tid >= 0);
581 AsanThreadSummary *alloc_thread =
582 asanThreadRegistry().FindByTid(m->alloc_tid);
583 AsanStackTrace alloc_stack;
584 AsanStackTrace::UncompressStack(&alloc_stack, m->compressed_alloc_stack(),
585 m->compressed_alloc_stack_size());
586 AsanThread *t = asanThreadRegistry().GetCurrent();
587 CHECK(t);
588 if (m->free_tid >= 0) {
589 AsanThreadSummary *free_thread =
590 asanThreadRegistry().FindByTid(m->free_tid);
591 Printf("freed by thread T%d here:\n", free_thread->tid());
592 AsanStackTrace free_stack;
593 AsanStackTrace::UncompressStack(&free_stack, m->compressed_free_stack(),
594 m->compressed_free_stack_size());
595 free_stack.PrintStack();
596 Printf("previously allocated by thread T%d here:\n",
597 alloc_thread->tid());
598
599 alloc_stack.PrintStack();
600 t->summary()->Announce();
601 free_thread->Announce();
602 alloc_thread->Announce();
603 } else {
604 Printf("allocated by thread T%d here:\n", alloc_thread->tid());
605 alloc_stack.PrintStack();
606 t->summary()->Announce();
607 alloc_thread->Announce();
608 }
609}
610
Kostya Serebryanyee392552012-05-31 15:02:07 +0000611static u8 *Allocate(uptr alignment, uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000612 __asan_init();
613 CHECK(stack);
614 if (size == 0) {
615 size = 1; // TODO(kcc): do something smarter
616 }
617 CHECK(IsPowerOfTwo(alignment));
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000618 uptr rounded_size = RoundUpTo(size, REDZONE);
619 uptr needed_size = rounded_size + REDZONE;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000620 if (alignment > REDZONE) {
621 needed_size += alignment;
622 }
623 CHECK(IsAligned(needed_size, REDZONE));
624 if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) {
625 Report("WARNING: AddressSanitizer failed to allocate %p bytes\n", size);
626 return 0;
627 }
628
Kostya Serebryanyee392552012-05-31 15:02:07 +0000629 u8 size_class = SizeToSizeClass(needed_size);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000630 uptr size_to_allocate = SizeClassToSize(size_class);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000631 CHECK(size_to_allocate >= kMinAllocSize);
632 CHECK(size_to_allocate >= needed_size);
633 CHECK(IsAligned(size_to_allocate, REDZONE));
634
Alexander Potapenko108a2372012-03-27 16:37:16 +0000635 if (FLAG_v >= 3) {
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000636 Printf("Allocate align: %zu size: %zu class: %u real: %zu\n",
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000637 alignment, size, size_class, size_to_allocate);
638 }
639
640 AsanThread *t = asanThreadRegistry().GetCurrent();
641 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
Kostya Serebryany30743142011-12-05 19:17:53 +0000642 // Statistics
643 thread_stats.mallocs++;
644 thread_stats.malloced += size;
645 thread_stats.malloced_redzones += size_to_allocate - size;
646 thread_stats.malloced_by_size[size_class]++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000647
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000648 AsanChunk *m = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000649 if (!t || size_to_allocate >= kMaxSizeForThreadLocalFreeList) {
650 // get directly from global storage.
651 m = malloc_info.AllocateChunks(size_class, 1);
Kostya Serebryany30743142011-12-05 19:17:53 +0000652 thread_stats.malloc_large++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000653 } else {
654 // get from the thread-local storage.
655 AsanChunk **fl = &t->malloc_storage().free_lists_[size_class];
656 if (!*fl) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000657 uptr n_new_chunks = kMaxSizeForThreadLocalFreeList / size_to_allocate;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000658 *fl = malloc_info.AllocateChunks(size_class, n_new_chunks);
Kostya Serebryany30743142011-12-05 19:17:53 +0000659 thread_stats.malloc_small_slow++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000660 }
661 m = *fl;
662 *fl = (*fl)->next;
663 }
664 CHECK(m);
665 CHECK(m->chunk_state == CHUNK_AVAILABLE);
666 m->chunk_state = CHUNK_ALLOCATED;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000667 m->next = 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000668 CHECK(m->Size() == size_to_allocate);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000669 uptr addr = (uptr)m + REDZONE;
670 CHECK(addr == (uptr)m->compressed_free_stack());
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000671
672 if (alignment > REDZONE && (addr & (alignment - 1))) {
673 addr = RoundUpTo(addr, alignment);
674 CHECK((addr & (alignment - 1)) == 0);
675 AsanChunk *p = (AsanChunk*)(addr - REDZONE);
676 p->chunk_state = CHUNK_MEMALIGN;
677 p->next = m;
678 }
679 CHECK(m == PtrToChunk(addr));
680 m->used_size = size;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000681 m->offset = addr - (uptr)m;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000682 CHECK(m->beg() == addr);
683 m->alloc_tid = t ? t->tid() : 0;
684 m->free_tid = AsanThread::kInvalidTid;
685 AsanStackTrace::CompressStack(stack, m->compressed_alloc_stack(),
686 m->compressed_alloc_stack_size());
687 PoisonShadow(addr, rounded_size, 0);
688 if (size < rounded_size) {
Kostya Serebryany218a9b72011-11-30 18:50:23 +0000689 PoisonHeapPartialRightRedzone(addr + rounded_size - REDZONE,
690 size & (REDZONE - 1));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000691 }
692 if (size <= FLAG_max_malloc_fill_size) {
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000693 REAL(memset)((void*)addr, 0, rounded_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000694 }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000695 return (u8*)addr;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000696}
697
Kostya Serebryanyee392552012-05-31 15:02:07 +0000698static void Deallocate(u8 *ptr, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000699 if (!ptr) return;
700 CHECK(stack);
701
702 if (FLAG_debug) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000703 CHECK(malloc_info.FindPageGroup((uptr)ptr));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000704 }
705
706 // Printf("Deallocate %p\n", ptr);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000707 AsanChunk *m = PtrToChunk((uptr)ptr);
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000708
709 // Flip the state atomically to avoid race on double-free.
Kostya Serebryanyee392552012-05-31 15:02:07 +0000710 u16 old_chunk_state = AtomicExchange(&m->chunk_state, CHUNK_QUARANTINE);
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000711
712 if (old_chunk_state == CHUNK_QUARANTINE) {
Kostya Serebryanyc1620132011-12-13 19:16:36 +0000713 Report("ERROR: AddressSanitizer attempting double-free on %p:\n", ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000714 stack->PrintStack();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000715 Describe((uptr)ptr, 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000716 ShowStatsAndAbort();
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000717 } else if (old_chunk_state != CHUNK_ALLOCATED) {
Kostya Serebryanyc1620132011-12-13 19:16:36 +0000718 Report("ERROR: AddressSanitizer attempting free on address which was not"
719 " malloc()-ed: %p\n", ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000720 stack->PrintStack();
721 ShowStatsAndAbort();
722 }
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000723 CHECK(old_chunk_state == CHUNK_ALLOCATED);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000724 CHECK(m->free_tid == AsanThread::kInvalidTid);
725 CHECK(m->alloc_tid >= 0);
726 AsanThread *t = asanThreadRegistry().GetCurrent();
727 m->free_tid = t ? t->tid() : 0;
728 AsanStackTrace::CompressStack(stack, m->compressed_free_stack(),
729 m->compressed_free_stack_size());
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000730 uptr rounded_size = RoundUpTo(m->used_size, REDZONE);
731 PoisonShadow((uptr)ptr, rounded_size, kAsanHeapFreeMagic);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000732
Kostya Serebryany30743142011-12-05 19:17:53 +0000733 // Statistics.
734 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
735 thread_stats.frees++;
736 thread_stats.freed += m->used_size;
737 thread_stats.freed_by_size[m->SizeClass()]++;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000738
Kostya Serebryanyf1e82b82012-04-05 15:55:09 +0000739 CHECK(m->chunk_state == CHUNK_QUARANTINE);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000740 if (t) {
741 AsanThreadLocalMallocStorage *ms = &t->malloc_storage();
742 CHECK(!m->next);
743 ms->quarantine_.Push(m);
744
745 if (ms->quarantine_.size() > kMaxThreadLocalQuarantine) {
746 malloc_info.SwallowThreadLocalMallocStorage(ms, false);
747 }
748 } else {
749 CHECK(!m->next);
750 malloc_info.BypassThreadLocalQuarantine(m);
751 }
752}
753
Kostya Serebryanyee392552012-05-31 15:02:07 +0000754static u8 *Reallocate(u8 *old_ptr, uptr new_size,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000755 AsanStackTrace *stack) {
756 CHECK(old_ptr && new_size);
Kostya Serebryany30743142011-12-05 19:17:53 +0000757
758 // Statistics.
759 AsanStats &thread_stats = asanThreadRegistry().GetCurrentThreadStats();
760 thread_stats.reallocs++;
761 thread_stats.realloced += new_size;
762
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000763 AsanChunk *m = PtrToChunk((uptr)old_ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000764 CHECK(m->chunk_state == CHUNK_ALLOCATED);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000765 uptr old_size = m->used_size;
766 uptr memcpy_size = Min(new_size, old_size);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000767 u8 *new_ptr = Allocate(0, new_size, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000768 if (new_ptr) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000769 CHECK(REAL(memcpy) != 0);
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000770 REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000771 Deallocate(old_ptr, stack);
772 }
773 return new_ptr;
774}
775
776} // namespace __asan
777
778// Malloc hooks declaration.
779// ASAN_NEW_HOOK(ptr, size) is called immediately after
780// allocation of "size" bytes, which returned "ptr".
781// ASAN_DELETE_HOOK(ptr) is called immediately before
782// deallocation of "ptr".
783// If ASAN_NEW_HOOK or ASAN_DELETE_HOOK is defined, user
784// program must provide implementation of this hook.
785// If macro is undefined, the hook is no-op.
786#ifdef ASAN_NEW_HOOK
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000787extern "C" void ASAN_NEW_HOOK(void *ptr, uptr size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000788#else
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000789static inline void ASAN_NEW_HOOK(void *ptr, uptr size) { }
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000790#endif
791
792#ifdef ASAN_DELETE_HOOK
793extern "C" void ASAN_DELETE_HOOK(void *ptr);
794#else
795static inline void ASAN_DELETE_HOOK(void *ptr) { }
796#endif
797
798namespace __asan {
799
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000800void *asan_memalign(uptr alignment, uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000801 void *ptr = (void*)Allocate(alignment, size, stack);
802 ASAN_NEW_HOOK(ptr, size);
803 return ptr;
804}
805
806void asan_free(void *ptr, AsanStackTrace *stack) {
807 ASAN_DELETE_HOOK(ptr);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000808 Deallocate((u8*)ptr, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000809}
810
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000811void *asan_malloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000812 void *ptr = (void*)Allocate(0, size, stack);
813 ASAN_NEW_HOOK(ptr, size);
814 return ptr;
815}
816
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000817void *asan_calloc(uptr nmemb, uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000818 void *ptr = (void*)Allocate(0, nmemb * size, stack);
819 if (ptr)
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000820 REAL(memset)(ptr, 0, nmemb * size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000821 ASAN_NEW_HOOK(ptr, nmemb * size);
822 return ptr;
823}
824
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000825void *asan_realloc(void *p, uptr size, AsanStackTrace *stack) {
826 if (p == 0) {
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 } else if (size == 0) {
831 ASAN_DELETE_HOOK(p);
Kostya Serebryanyee392552012-05-31 15:02:07 +0000832 Deallocate((u8*)p, stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000833 return 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000834 }
Kostya Serebryanyee392552012-05-31 15:02:07 +0000835 return Reallocate((u8*)p, size, stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000836}
837
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000838void *asan_valloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000839 void *ptr = (void*)Allocate(kPageSize, size, stack);
840 ASAN_NEW_HOOK(ptr, size);
841 return ptr;
842}
843
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000844void *asan_pvalloc(uptr size, AsanStackTrace *stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000845 size = RoundUpTo(size, kPageSize);
846 if (size == 0) {
847 // pvalloc(0) should allocate one page.
848 size = kPageSize;
849 }
850 void *ptr = (void*)Allocate(kPageSize, size, stack);
851 ASAN_NEW_HOOK(ptr, size);
852 return ptr;
853}
854
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000855int asan_posix_memalign(void **memptr, uptr alignment, uptr size,
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000856 AsanStackTrace *stack) {
857 void *ptr = Allocate(alignment, size, stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000858 CHECK(IsAligned((uptr)ptr, alignment));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000859 ASAN_NEW_HOOK(ptr, size);
860 *memptr = ptr;
861 return 0;
862}
863
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000864uptr asan_malloc_usable_size(void *ptr, AsanStackTrace *stack) {
Alexey Samsonovca2278d2012-01-18 15:26:55 +0000865 CHECK(stack);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000866 if (ptr == 0) return 0;
867 uptr usable_size = malloc_info.AllocationSize((uptr)ptr);
Alexander Potapenko37931232012-05-25 15:20:13 +0000868 if (FLAG_check_malloc_usable_size && (usable_size == 0)) {
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000869 Report("ERROR: AddressSanitizer attempting to call malloc_usable_size() "
870 "for pointer which is not owned: %p\n", ptr);
871 stack->PrintStack();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000872 Describe((uptr)ptr, 1);
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000873 ShowStatsAndAbort();
874 }
875 return usable_size;
876}
877
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000878uptr asan_mz_size(const void *ptr) {
879 return malloc_info.AllocationSize((uptr)ptr);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000880}
881
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000882void DescribeHeapAddress(uptr addr, uptr access_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000883 Describe(addr, access_size);
884}
885
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000886void asan_mz_force_lock() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000887 malloc_info.ForceLock();
888}
889
Alexey Samsonov4fd95f12012-01-17 06:39:10 +0000890void asan_mz_force_unlock() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000891 malloc_info.ForceUnlock();
892}
893
894// ---------------------- Fake stack-------------------- {{{1
895FakeStack::FakeStack() {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000896 CHECK(REAL(memset) != 0);
Alexey Samsonov09672ca2012-02-08 13:45:31 +0000897 REAL(memset)(this, 0, sizeof(*this));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000898}
899
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000900bool FakeStack::AddrIsInSizeClass(uptr addr, uptr size_class) {
901 uptr mem = allocated_size_classes_[size_class];
902 uptr size = ClassMmapSize(size_class);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000903 bool res = mem && addr >= mem && addr < mem + size;
904 return res;
905}
906
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000907uptr FakeStack::AddrIsInFakeStack(uptr addr) {
908 for (uptr i = 0; i < kNumberOfSizeClasses; i++) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000909 if (AddrIsInSizeClass(addr, i)) return allocated_size_classes_[i];
910 }
911 return 0;
912}
913
914// We may want to compute this during compilation.
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000915inline uptr FakeStack::ComputeSizeClass(uptr alloc_size) {
916 uptr rounded_size = RoundUpToPowerOfTwo(alloc_size);
917 uptr log = Log2(rounded_size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000918 CHECK(alloc_size <= (1UL << log));
919 if (!(alloc_size > (1UL << (log-1)))) {
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000920 Printf("alloc_size %zu log %zu\n", alloc_size, log);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000921 }
922 CHECK(alloc_size > (1UL << (log-1)));
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000923 uptr res = log < kMinStackFrameSizeLog ? 0 : log - kMinStackFrameSizeLog;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000924 CHECK(res < kNumberOfSizeClasses);
925 CHECK(ClassSize(res) >= rounded_size);
926 return res;
927}
928
929void FakeFrameFifo::FifoPush(FakeFrame *node) {
930 CHECK(node);
931 node->next = 0;
932 if (first_ == 0 && last_ == 0) {
933 first_ = last_ = node;
934 } else {
935 CHECK(first_);
936 CHECK(last_);
937 last_->next = node;
938 last_ = node;
939 }
940}
941
942FakeFrame *FakeFrameFifo::FifoPop() {
943 CHECK(first_ && last_ && "Exhausted fake stack");
944 FakeFrame *res = 0;
945 if (first_ == last_) {
946 res = first_;
947 first_ = last_ = 0;
948 } else {
949 res = first_;
950 first_ = first_->next;
951 }
952 return res;
953}
954
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000955void FakeStack::Init(uptr stack_size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000956 stack_size_ = stack_size;
957 alive_ = true;
958}
959
960void FakeStack::Cleanup() {
961 alive_ = false;
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000962 for (uptr i = 0; i < kNumberOfSizeClasses; i++) {
963 uptr mem = allocated_size_classes_[i];
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000964 if (mem) {
965 PoisonShadow(mem, ClassMmapSize(i), 0);
966 allocated_size_classes_[i] = 0;
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000967 AsanUnmapOrDie((void*)mem, ClassMmapSize(i));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000968 }
969 }
970}
971
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000972uptr FakeStack::ClassMmapSize(uptr size_class) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000973 return RoundUpToPowerOfTwo(stack_size_);
974}
975
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000976void FakeStack::AllocateOneSizeClass(uptr size_class) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000977 CHECK(ClassMmapSize(size_class) >= kPageSize);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000978 uptr new_mem = (uptr)AsanMmapSomewhereOrDie(
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000979 ClassMmapSize(size_class), __FUNCTION__);
Evgeniy Stepanov739eb792012-03-21 11:32:46 +0000980 // Printf("T%d new_mem[%zu]: %p-%p mmap %zu\n",
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000981 // asanThreadRegistry().GetCurrent()->tid(),
982 // size_class, new_mem, new_mem + ClassMmapSize(size_class),
983 // ClassMmapSize(size_class));
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000984 uptr i;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000985 for (i = 0; i < ClassMmapSize(size_class);
986 i += ClassSize(size_class)) {
987 size_classes_[size_class].FifoPush((FakeFrame*)(new_mem + i));
988 }
989 CHECK(i == ClassMmapSize(size_class));
990 allocated_size_classes_[size_class] = new_mem;
991}
992
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000993uptr FakeStack::AllocateStack(uptr size, uptr real_stack) {
Kostya Serebryanyc4b34d92011-12-09 01:49:31 +0000994 if (!alive_) return real_stack;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000995 CHECK(size <= kMaxStackMallocSize && size > 1);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +0000996 uptr size_class = ComputeSizeClass(size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000997 if (!allocated_size_classes_[size_class]) {
998 AllocateOneSizeClass(size_class);
999 }
1000 FakeFrame *fake_frame = size_classes_[size_class].FifoPop();
1001 CHECK(fake_frame);
1002 fake_frame->size_minus_one = size - 1;
1003 fake_frame->real_stack = real_stack;
1004 while (FakeFrame *top = call_stack_.top()) {
1005 if (top->real_stack > real_stack) break;
1006 call_stack_.LifoPop();
1007 DeallocateFrame(top);
1008 }
1009 call_stack_.LifoPush(fake_frame);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001010 uptr ptr = (uptr)fake_frame;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001011 PoisonShadow(ptr, size, 0);
1012 return ptr;
1013}
1014
1015void FakeStack::DeallocateFrame(FakeFrame *fake_frame) {
1016 CHECK(alive_);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001017 uptr size = fake_frame->size_minus_one + 1;
1018 uptr size_class = ComputeSizeClass(size);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001019 CHECK(allocated_size_classes_[size_class]);
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001020 uptr ptr = (uptr)fake_frame;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001021 CHECK(AddrIsInSizeClass(ptr, size_class));
1022 CHECK(AddrIsInSizeClass(ptr + size - 1, size_class));
1023 size_classes_[size_class].FifoPush(fake_frame);
1024}
1025
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001026void FakeStack::OnFree(uptr ptr, uptr size, uptr real_stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001027 FakeFrame *fake_frame = (FakeFrame*)ptr;
1028 CHECK(fake_frame->magic = kRetiredStackFrameMagic);
1029 CHECK(fake_frame->descr != 0);
1030 CHECK(fake_frame->size_minus_one == size - 1);
1031 PoisonShadow(ptr, size, kAsanStackAfterReturnMagic);
1032}
1033
1034} // namespace __asan
1035
1036// ---------------------- Interface ---------------- {{{1
1037using namespace __asan; // NOLINT
1038
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001039uptr __asan_stack_malloc(uptr size, uptr real_stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001040 if (!FLAG_use_fake_stack) return real_stack;
1041 AsanThread *t = asanThreadRegistry().GetCurrent();
1042 if (!t) {
1043 // TSD is gone, use the real stack.
1044 return real_stack;
1045 }
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001046 uptr ptr = t->fake_stack().AllocateStack(size, real_stack);
Evgeniy Stepanov739eb792012-03-21 11:32:46 +00001047 // Printf("__asan_stack_malloc %p %zu %p\n", ptr, size, real_stack);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001048 return ptr;
1049}
1050
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001051void __asan_stack_free(uptr ptr, uptr size, uptr real_stack) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001052 if (!FLAG_use_fake_stack) return;
1053 if (ptr != real_stack) {
1054 FakeStack::OnFree(ptr, size, real_stack);
1055 }
1056}
1057
1058// ASan allocator doesn't reserve extra bytes, so normally we would
1059// just return "size".
Kostya Serebryany9aead372012-05-31 14:11:07 +00001060uptr __asan_get_estimated_allocated_size(uptr size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001061 if (size == 0) return 1;
Kostya Serebryany2d8b3bd2011-12-02 18:42:04 +00001062 return Min(size, kMaxAllowedMallocSize);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001063}
1064
1065bool __asan_get_ownership(const void *p) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001066 return malloc_info.AllocationSize((uptr)p) > 0;
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001067}
1068
Kostya Serebryany9aead372012-05-31 14:11:07 +00001069uptr __asan_get_allocated_size(const void *p) {
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001070 if (p == 0) return 0;
1071 uptr allocated_size = malloc_info.AllocationSize((uptr)p);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001072 // Die if p is not malloced or if it is already freed.
Alexey Samsonovca2278d2012-01-18 15:26:55 +00001073 if (allocated_size == 0) {
Alexey Samsonov4fd95f12012-01-17 06:39:10 +00001074 Report("ERROR: AddressSanitizer attempting to call "
1075 "__asan_get_allocated_size() for pointer which is "
1076 "not owned: %p\n", p);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001077 PRINT_CURRENT_STACK();
Kostya Serebryany3f4c3872012-05-31 14:35:53 +00001078 Describe((uptr)p, 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001079 ShowStatsAndAbort();
1080 }
1081 return allocated_size;
1082}