asan_malloc_mac.cc revision f67ec2b6e8d2ae328c27de0b026eea2d6667836e
1//===-- asan_malloc_mac.cc ------------------------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file is a part of AddressSanitizer, an address sanity checker. 11// 12// Mac-specific malloc interception. 13//===----------------------------------------------------------------------===// 14 15#ifdef __APPLE__ 16 17#include <AvailabilityMacros.h> 18#include <CoreFoundation/CFBase.h> 19#include <dlfcn.h> 20#include <malloc/malloc.h> 21 22#include "asan_allocator.h" 23#include "asan_interceptors.h" 24#include "asan_internal.h" 25#include "asan_mac.h" 26#include "asan_report.h" 27#include "asan_stack.h" 28#include "asan_stats.h" 29#include "asan_thread_registry.h" 30 31// Similar code is used in Google Perftools, 32// http://code.google.com/p/google-perftools. 33 34// ---------------------- Replacement functions ---------------- {{{1 35using namespace __asan; // NOLINT 36 37// TODO(glider): do we need both zones? 38static malloc_zone_t *system_malloc_zone = 0; 39static malloc_zone_t *system_purgeable_zone = 0; 40static malloc_zone_t asan_zone; 41CFAllocatorRef cf_asan = 0; 42 43// _CFRuntimeCreateInstance() checks whether the supplied allocator is 44// kCFAllocatorSystemDefault and, if it is not, stores the allocator reference 45// at the beginning of the allocated memory and returns the pointer to the 46// allocated memory plus sizeof(CFAllocatorRef). See 47// http://www.opensource.apple.com/source/CF/CF-635.21/CFRuntime.c 48// Pointers returned by _CFRuntimeCreateInstance() can then be passed directly 49// to free() or CFAllocatorDeallocate(), which leads to false invalid free 50// reports. 51// The corresponding rdar bug is http://openradar.appspot.com/radar?id=1796404. 52void* ALWAYS_INLINE get_saved_cfallocator_ref(void *ptr) { 53 if (flags()->replace_cfallocator) { 54 // Make sure we're not hitting the previous page. This may be incorrect 55 // if ASan's malloc returns an address ending with 0xFF8, which will be 56 // then padded to a page boundary with a CFAllocatorRef. 57 uptr arith_ptr = (uptr)ptr; 58 if ((arith_ptr & 0xFFF) > sizeof(CFAllocatorRef)) { 59 CFAllocatorRef *saved = 60 (CFAllocatorRef*)(arith_ptr - sizeof(CFAllocatorRef)); 61 if ((*saved == cf_asan) && asan_mz_size(saved)) ptr = (void*)saved; 62 } 63 } 64 return ptr; 65} 66 67// The free() implementation provided by OS X calls malloc_zone_from_ptr() 68// to find the owner of |ptr|. If the result is 0, an invalid free() is 69// reported. Our implementation falls back to asan_free() in this case 70// in order to print an ASan-style report. 71// 72// For the objects created by _CFRuntimeCreateInstance a CFAllocatorRef is 73// placed at the beginning of the allocated chunk and the pointer returned by 74// our allocator is off by sizeof(CFAllocatorRef). This pointer can be then 75// passed directly to free(), which will lead to errors. 76// To overcome this we're checking whether |ptr-sizeof(CFAllocatorRef)| 77// contains a pointer to our CFAllocator (assuming no other allocator is used). 78// See http://code.google.com/p/address-sanitizer/issues/detail?id=70 for more 79// info. 80INTERCEPTOR(void, free, void *ptr) { 81 malloc_zone_t *zone = malloc_zone_from_ptr(ptr); 82 if (zone) { 83#if defined(MAC_OS_X_VERSION_10_6) && \ 84 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 85 if ((zone->version >= 6) && (zone->free_definite_size)) { 86 zone->free_definite_size(zone, ptr, malloc_size(ptr)); 87 } else { 88 malloc_zone_free(zone, ptr); 89 } 90#else 91 malloc_zone_free(zone, ptr); 92#endif 93 } else { 94 if (!asan_mz_size(ptr)) ptr = get_saved_cfallocator_ref(ptr); 95 GET_STACK_TRACE_HERE_FOR_FREE(ptr); 96 asan_free(ptr, &stack); 97 } 98} 99 100// We can't always replace the default CFAllocator with cf_asan right in 101// ReplaceSystemMalloc(), because it is sometimes called before 102// __CFInitialize(), when the default allocator is invalid and replacing it may 103// crash the program. Instead we wait for the allocator to initialize and jump 104// in just after __CFInitialize(). Nobody is going to allocate memory using 105// CFAllocators before that, so we won't miss anything. 106// 107// See http://code.google.com/p/address-sanitizer/issues/detail?id=87 108// and http://opensource.apple.com/source/CF/CF-550.43/CFRuntime.c 109INTERCEPTOR(void, __CFInitialize, void) { 110 // If the runtime is built as dynamic library, __CFInitialize wrapper may be 111 // called before __asan_init. 112#if !MAC_INTERPOSE_FUNCTIONS 113 CHECK(flags()->replace_cfallocator); 114 CHECK(asan_inited); 115#endif 116 REAL(__CFInitialize)(); 117 if (!cf_asan && asan_inited) MaybeReplaceCFAllocator(); 118} 119 120namespace { 121 122// TODO(glider): the mz_* functions should be united with the Linux wrappers, 123// as they are basically copied from there. 124size_t mz_size(malloc_zone_t* zone, const void* ptr) { 125 return asan_mz_size(ptr); 126} 127 128void *mz_malloc(malloc_zone_t *zone, size_t size) { 129 if (!asan_inited) { 130 CHECK(system_malloc_zone); 131 return malloc_zone_malloc(system_malloc_zone, size); 132 } 133 GET_STACK_TRACE_HERE_FOR_MALLOC; 134 return asan_malloc(size, &stack); 135} 136 137void *cf_malloc(CFIndex size, CFOptionFlags hint, void *info) { 138 if (!asan_inited) { 139 CHECK(system_malloc_zone); 140 return malloc_zone_malloc(system_malloc_zone, size); 141 } 142 GET_STACK_TRACE_HERE_FOR_MALLOC; 143 return asan_malloc(size, &stack); 144} 145 146void *mz_calloc(malloc_zone_t *zone, size_t nmemb, size_t size) { 147 if (!asan_inited) { 148 // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym. 149 const size_t kCallocPoolSize = 1024; 150 static uptr calloc_memory_for_dlsym[kCallocPoolSize]; 151 static size_t allocated; 152 size_t size_in_words = ((nmemb * size) + kWordSize - 1) / kWordSize; 153 void *mem = (void*)&calloc_memory_for_dlsym[allocated]; 154 allocated += size_in_words; 155 CHECK(allocated < kCallocPoolSize); 156 return mem; 157 } 158 GET_STACK_TRACE_HERE_FOR_MALLOC; 159 return asan_calloc(nmemb, size, &stack); 160} 161 162void *mz_valloc(malloc_zone_t *zone, size_t size) { 163 if (!asan_inited) { 164 CHECK(system_malloc_zone); 165 return malloc_zone_valloc(system_malloc_zone, size); 166 } 167 GET_STACK_TRACE_HERE_FOR_MALLOC; 168 return asan_memalign(GetPageSizeCached(), size, &stack); 169} 170 171#define GET_ZONE_FOR_PTR(ptr) \ 172 malloc_zone_t *zone_ptr = malloc_zone_from_ptr(ptr); \ 173 const char *zone_name = (zone_ptr == 0) ? 0 : zone_ptr->zone_name 174 175void ALWAYS_INLINE free_common(void *context, void *ptr) { 176 if (!ptr) return; 177 if (asan_mz_size(ptr)) { 178 GET_STACK_TRACE_HERE_FOR_FREE(ptr); 179 asan_free(ptr, &stack); 180 } else { 181 // If the pointer does not belong to any of the zones, use one of the 182 // fallback methods to free memory. 183 malloc_zone_t *zone_ptr = malloc_zone_from_ptr(ptr); 184 if (zone_ptr == system_purgeable_zone) { 185 // allocations from malloc_default_purgeable_zone() done before 186 // __asan_init() may be occasionally freed via free_common(). 187 // see http://code.google.com/p/address-sanitizer/issues/detail?id=99. 188 malloc_zone_free(zone_ptr, ptr); 189 } else { 190 // If the memory chunk pointer was moved to store additional 191 // CFAllocatorRef, fix it back. 192 ptr = get_saved_cfallocator_ref(ptr); 193 GET_STACK_TRACE_HERE_FOR_FREE(ptr); 194 if (!flags()->mac_ignore_invalid_free) { 195 asan_free(ptr, &stack); 196 } else { 197 GET_ZONE_FOR_PTR(ptr); 198 WarnMacFreeUnallocated((uptr)ptr, (uptr)zone_ptr, zone_name, &stack); 199 return; 200 } 201 } 202 } 203} 204 205// TODO(glider): the allocation callbacks need to be refactored. 206void mz_free(malloc_zone_t *zone, void *ptr) { 207 free_common(zone, ptr); 208} 209 210void cf_free(void *ptr, void *info) { 211 free_common(info, ptr); 212} 213 214void *mz_realloc(malloc_zone_t *zone, void *ptr, size_t size) { 215 if (!ptr) { 216 GET_STACK_TRACE_HERE_FOR_MALLOC; 217 return asan_malloc(size, &stack); 218 } else { 219 if (asan_mz_size(ptr)) { 220 GET_STACK_TRACE_HERE_FOR_MALLOC; 221 return asan_realloc(ptr, size, &stack); 222 } else { 223 // We can't recover from reallocating an unknown address, because 224 // this would require reading at most |size| bytes from 225 // potentially unaccessible memory. 226 GET_STACK_TRACE_HERE_FOR_FREE(ptr); 227 GET_ZONE_FOR_PTR(ptr); 228 ReportMacMzReallocUnknown((uptr)ptr, (uptr)zone_ptr, zone_name, &stack); 229 } 230 } 231} 232 233void *cf_realloc(void *ptr, CFIndex size, CFOptionFlags hint, void *info) { 234 if (!ptr) { 235 GET_STACK_TRACE_HERE_FOR_MALLOC; 236 return asan_malloc(size, &stack); 237 } else { 238 if (asan_mz_size(ptr)) { 239 GET_STACK_TRACE_HERE_FOR_MALLOC; 240 return asan_realloc(ptr, size, &stack); 241 } else { 242 // We can't recover from reallocating an unknown address, because 243 // this would require reading at most |size| bytes from 244 // potentially unaccessible memory. 245 GET_STACK_TRACE_HERE_FOR_FREE(ptr); 246 GET_ZONE_FOR_PTR(ptr); 247 ReportMacCfReallocUnknown((uptr)ptr, (uptr)zone_ptr, zone_name, &stack); 248 } 249 } 250} 251 252void mz_destroy(malloc_zone_t* zone) { 253 // A no-op -- we will not be destroyed! 254 Printf("mz_destroy() called -- ignoring\n"); 255} 256 // from AvailabilityMacros.h 257#if defined(MAC_OS_X_VERSION_10_6) && \ 258 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 259void *mz_memalign(malloc_zone_t *zone, size_t align, size_t size) { 260 if (!asan_inited) { 261 CHECK(system_malloc_zone); 262 return malloc_zone_memalign(system_malloc_zone, align, size); 263 } 264 GET_STACK_TRACE_HERE_FOR_MALLOC; 265 return asan_memalign(align, size, &stack); 266} 267 268// This function is currently unused, and we build with -Werror. 269#if 0 270void mz_free_definite_size(malloc_zone_t* zone, void *ptr, size_t size) { 271 // TODO(glider): check that |size| is valid. 272 UNIMPLEMENTED(); 273} 274#endif 275#endif 276 277kern_return_t mi_enumerator(task_t task, void *, 278 unsigned type_mask, vm_address_t zone_address, 279 memory_reader_t reader, 280 vm_range_recorder_t recorder) { 281 // Should enumerate all the pointers we have. Seems like a lot of work. 282 return KERN_FAILURE; 283} 284 285size_t mi_good_size(malloc_zone_t *zone, size_t size) { 286 // I think it's always safe to return size, but we maybe could do better. 287 return size; 288} 289 290boolean_t mi_check(malloc_zone_t *zone) { 291 UNIMPLEMENTED(); 292} 293 294void mi_print(malloc_zone_t *zone, boolean_t verbose) { 295 UNIMPLEMENTED(); 296} 297 298void mi_log(malloc_zone_t *zone, void *address) { 299 // I don't think we support anything like this 300} 301 302void mi_force_lock(malloc_zone_t *zone) { 303 asan_mz_force_lock(); 304} 305 306void mi_force_unlock(malloc_zone_t *zone) { 307 asan_mz_force_unlock(); 308} 309 310void mi_statistics(malloc_zone_t *zone, malloc_statistics_t *stats) { 311 AsanMallocStats malloc_stats; 312 asanThreadRegistry().FillMallocStatistics(&malloc_stats); 313 CHECK(sizeof(malloc_statistics_t) == sizeof(AsanMallocStats)); 314 internal_memcpy(stats, &malloc_stats, sizeof(malloc_statistics_t)); 315} 316 317#if defined(MAC_OS_X_VERSION_10_6) && \ 318 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 319boolean_t mi_zone_locked(malloc_zone_t *zone) { 320 // UNIMPLEMENTED(); 321 return false; 322} 323#endif 324 325} // unnamed namespace 326 327extern int __CFRuntimeClassTableSize; 328 329namespace __asan { 330void MaybeReplaceCFAllocator() { 331 static CFAllocatorContext asan_context = { 332 /*version*/ 0, /*info*/ &asan_zone, 333 /*retain*/ 0, /*release*/ 0, 334 /*copyDescription*/0, 335 /*allocate*/ &cf_malloc, 336 /*reallocate*/ &cf_realloc, 337 /*deallocate*/ &cf_free, 338 /*preferredSize*/ 0 }; 339 if (!cf_asan) 340 cf_asan = CFAllocatorCreate(kCFAllocatorUseContext, &asan_context); 341 if (flags()->replace_cfallocator && CFAllocatorGetDefault() != cf_asan) 342 CFAllocatorSetDefault(cf_asan); 343} 344 345void ReplaceSystemMalloc() { 346 static malloc_introspection_t asan_introspection; 347 // Ok to use internal_memset, these places are not performance-critical. 348 internal_memset(&asan_introspection, 0, sizeof(asan_introspection)); 349 350 asan_introspection.enumerator = &mi_enumerator; 351 asan_introspection.good_size = &mi_good_size; 352 asan_introspection.check = &mi_check; 353 asan_introspection.print = &mi_print; 354 asan_introspection.log = &mi_log; 355 asan_introspection.force_lock = &mi_force_lock; 356 asan_introspection.force_unlock = &mi_force_unlock; 357 asan_introspection.statistics = &mi_statistics; 358 359 internal_memset(&asan_zone, 0, sizeof(malloc_zone_t)); 360 361 // Start with a version 4 zone which is used for OS X 10.4 and 10.5. 362 asan_zone.version = 4; 363 asan_zone.zone_name = "asan"; 364 asan_zone.size = &mz_size; 365 asan_zone.malloc = &mz_malloc; 366 asan_zone.calloc = &mz_calloc; 367 asan_zone.valloc = &mz_valloc; 368 asan_zone.free = &mz_free; 369 asan_zone.realloc = &mz_realloc; 370 asan_zone.destroy = &mz_destroy; 371 asan_zone.batch_malloc = 0; 372 asan_zone.batch_free = 0; 373 asan_zone.introspect = &asan_introspection; 374 375 // from AvailabilityMacros.h 376#if defined(MAC_OS_X_VERSION_10_6) && \ 377 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 378 // Switch to version 6 on OSX 10.6 to support memalign. 379 asan_zone.version = 6; 380 asan_zone.free_definite_size = 0; 381 asan_zone.memalign = &mz_memalign; 382 asan_introspection.zone_locked = &mi_zone_locked; 383 384 // Request the default purgable zone to force its creation. The 385 // current default zone is registered with the purgable zone for 386 // doing tiny and small allocs. Sadly, it assumes that the default 387 // zone is the szone implementation from OS X and will crash if it 388 // isn't. By creating the zone now, this will be true and changing 389 // the default zone won't cause a problem. (OS X 10.6 and higher.) 390 system_purgeable_zone = malloc_default_purgeable_zone(); 391#endif 392 393 // Register the ASan zone. At this point, it will not be the 394 // default zone. 395 malloc_zone_register(&asan_zone); 396 397 // Unregister and reregister the default zone. Unregistering swaps 398 // the specified zone with the last one registered which for the 399 // default zone makes the more recently registered zone the default 400 // zone. The default zone is then re-registered to ensure that 401 // allocations made from it earlier will be handled correctly. 402 // Things are not guaranteed to work that way, but it's how they work now. 403 system_malloc_zone = malloc_default_zone(); 404 malloc_zone_unregister(system_malloc_zone); 405 malloc_zone_register(system_malloc_zone); 406 // Make sure the default allocator was replaced. 407 CHECK(malloc_default_zone() == &asan_zone); 408 409 // If __CFInitialize() hasn't been called yet, cf_asan will be created and 410 // installed as the default allocator after __CFInitialize() finishes (see 411 // the interceptor for __CFInitialize() above). Otherwise install cf_asan 412 // right now. On both Snow Leopard and Lion __CFInitialize() calls 413 // __CFAllocatorInitialize(), which initializes the _base._cfisa field of 414 // the default allocators we check here. 415 if (((CFRuntimeBase*)kCFAllocatorSystemDefault)->_cfisa) { 416 MaybeReplaceCFAllocator(); 417 } 418} 419} // namespace __asan 420 421#endif // __APPLE__ 422