1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/process/memory.h"
7 #include <CoreFoundation/CoreFoundation.h>
10 #include <mach/mach_vm.h>
11 #include <malloc/malloc.h>
12 #import <objc/runtime.h>
16 #include "base/lazy_instance.h"
17 #include "base/logging.h"
18 #include "base/mac/mac_util.h"
19 #include "base/mac/mach_logging.h"
20 #include "base/scoped_clear_errno.h"
21 #include "third_party/apple_apsl/CFBase.h"
22 #include "third_party/apple_apsl/malloc.h"
26 void EnableTerminationOnHeapCorruption() {
28 DLOG(WARNING) << "EnableTerminationOnHeapCorruption only works on 64-bit";
32 // ------------------------------------------------------------------------
36 bool g_oom_killer_enabled;
38 #if !defined(ADDRESS_SANITIZER)
40 // Starting with Mac OS X 10.7, the zone allocators set up by the system are
41 // read-only, to prevent them from being overwritten in an attack. However,
42 // blindly unprotecting and reprotecting the zone allocators fails with
43 // GuardMalloc because GuardMalloc sets up its zone allocator using a block of
44 // memory in its bss. Explicit saving/restoring of the protection is required.
46 // This function takes a pointer to a malloc zone, de-protects it if necessary,
47 // and returns (in the out parameters) a region of memory (if any) to be
48 // re-protected when modifications are complete. This approach assumes that
49 // there is no contention for the protection of this memory.
50 void DeprotectMallocZone(ChromeMallocZone* default_zone,
51 mach_vm_address_t* reprotection_start,
52 mach_vm_size_t* reprotection_length,
53 vm_prot_t* reprotection_value) {
55 *reprotection_start = reinterpret_cast<mach_vm_address_t>(default_zone);
56 struct vm_region_basic_info_64 info;
57 mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64;
58 kern_return_t result =
59 mach_vm_region(mach_task_self(),
62 VM_REGION_BASIC_INFO_64,
63 reinterpret_cast<vm_region_info_t>(&info),
66 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_region";
68 // The kernel always returns a null object for VM_REGION_BASIC_INFO_64, but
69 // balance it with a deallocate in case this ever changes. See 10.9.2
70 // xnu-2422.90.20/osfmk/vm/vm_map.c vm_map_region.
71 mach_port_deallocate(mach_task_self(), unused);
73 // Does the region fully enclose the zone pointers? Possibly unwarranted
74 // simplification used: using the size of a full version 8 malloc zone rather
75 // than the actual smaller size if the passed-in zone is not version 8.
76 CHECK(*reprotection_start <=
77 reinterpret_cast<mach_vm_address_t>(default_zone));
78 mach_vm_size_t zone_offset = reinterpret_cast<mach_vm_size_t>(default_zone) -
79 reinterpret_cast<mach_vm_size_t>(*reprotection_start);
80 CHECK(zone_offset + sizeof(ChromeMallocZone) <= *reprotection_length);
82 if (info.protection & VM_PROT_WRITE) {
83 // No change needed; the zone is already writable.
84 *reprotection_start = 0;
85 *reprotection_length = 0;
86 *reprotection_value = VM_PROT_NONE;
88 *reprotection_value = info.protection;
89 result = mach_vm_protect(mach_task_self(),
93 info.protection | VM_PROT_WRITE);
94 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
98 // === C malloc/calloc/valloc/realloc/posix_memalign ===
100 typedef void* (*malloc_type)(struct _malloc_zone_t* zone,
102 typedef void* (*calloc_type)(struct _malloc_zone_t* zone,
105 typedef void* (*valloc_type)(struct _malloc_zone_t* zone,
107 typedef void (*free_type)(struct _malloc_zone_t* zone,
109 typedef void* (*realloc_type)(struct _malloc_zone_t* zone,
112 typedef void* (*memalign_type)(struct _malloc_zone_t* zone,
116 malloc_type g_old_malloc;
117 calloc_type g_old_calloc;
118 valloc_type g_old_valloc;
119 free_type g_old_free;
120 realloc_type g_old_realloc;
121 memalign_type g_old_memalign;
123 malloc_type g_old_malloc_purgeable;
124 calloc_type g_old_calloc_purgeable;
125 valloc_type g_old_valloc_purgeable;
126 free_type g_old_free_purgeable;
127 realloc_type g_old_realloc_purgeable;
128 memalign_type g_old_memalign_purgeable;
130 void* oom_killer_malloc(struct _malloc_zone_t* zone,
132 void* result = g_old_malloc(zone, size);
134 TerminateBecauseOutOfMemory(size);
138 void* oom_killer_calloc(struct _malloc_zone_t* zone,
141 void* result = g_old_calloc(zone, num_items, size);
142 if (!result && num_items && size)
143 TerminateBecauseOutOfMemory(num_items * size);
147 void* oom_killer_valloc(struct _malloc_zone_t* zone,
149 void* result = g_old_valloc(zone, size);
151 TerminateBecauseOutOfMemory(size);
155 void oom_killer_free(struct _malloc_zone_t* zone,
157 g_old_free(zone, ptr);
160 void* oom_killer_realloc(struct _malloc_zone_t* zone,
163 void* result = g_old_realloc(zone, ptr, size);
165 TerminateBecauseOutOfMemory(size);
169 void* oom_killer_memalign(struct _malloc_zone_t* zone,
172 void* result = g_old_memalign(zone, alignment, size);
173 // Only die if posix_memalign would have returned ENOMEM, since there are
174 // other reasons why NULL might be returned (see
175 // http://opensource.apple.com/source/Libc/Libc-583/gen/malloc.c ).
176 if (!result && size && alignment >= sizeof(void*) &&
177 (alignment & (alignment - 1)) == 0) {
178 TerminateBecauseOutOfMemory(size);
183 void* oom_killer_malloc_purgeable(struct _malloc_zone_t* zone,
185 void* result = g_old_malloc_purgeable(zone, size);
187 TerminateBecauseOutOfMemory(size);
191 void* oom_killer_calloc_purgeable(struct _malloc_zone_t* zone,
194 void* result = g_old_calloc_purgeable(zone, num_items, size);
195 if (!result && num_items && size)
196 TerminateBecauseOutOfMemory(num_items * size);
200 void* oom_killer_valloc_purgeable(struct _malloc_zone_t* zone,
202 void* result = g_old_valloc_purgeable(zone, size);
204 TerminateBecauseOutOfMemory(size);
208 void oom_killer_free_purgeable(struct _malloc_zone_t* zone,
210 g_old_free_purgeable(zone, ptr);
213 void* oom_killer_realloc_purgeable(struct _malloc_zone_t* zone,
216 void* result = g_old_realloc_purgeable(zone, ptr, size);
218 TerminateBecauseOutOfMemory(size);
222 void* oom_killer_memalign_purgeable(struct _malloc_zone_t* zone,
225 void* result = g_old_memalign_purgeable(zone, alignment, size);
226 // Only die if posix_memalign would have returned ENOMEM, since there are
227 // other reasons why NULL might be returned (see
228 // http://opensource.apple.com/source/Libc/Libc-583/gen/malloc.c ).
229 if (!result && size && alignment >= sizeof(void*)
230 && (alignment & (alignment - 1)) == 0) {
231 TerminateBecauseOutOfMemory(size);
236 #endif // !defined(ADDRESS_SANITIZER)
238 // === C++ operator new ===
240 void oom_killer_new() {
241 TerminateBecauseOutOfMemory(0);
244 #if !defined(ADDRESS_SANITIZER)
246 // === Core Foundation CFAllocators ===
248 bool CanGetContextForCFAllocator() {
249 return !base::mac::IsOSLaterThanElCapitan_DontCallThis();
252 CFAllocatorContext* ContextForCFAllocator(CFAllocatorRef allocator) {
253 if (base::mac::IsOSSnowLeopard()) {
254 ChromeCFAllocatorLeopards* our_allocator =
255 const_cast<ChromeCFAllocatorLeopards*>(
256 reinterpret_cast<const ChromeCFAllocatorLeopards*>(allocator));
257 return &our_allocator->_context;
258 } else if (base::mac::IsOSLion() ||
259 base::mac::IsOSMountainLion() ||
260 base::mac::IsOSMavericks() ||
261 base::mac::IsOSYosemite() ||
262 base::mac::IsOSElCapitan()) {
263 ChromeCFAllocatorLions* our_allocator =
264 const_cast<ChromeCFAllocatorLions*>(
265 reinterpret_cast<const ChromeCFAllocatorLions*>(allocator));
266 return &our_allocator->_context;
272 CFAllocatorAllocateCallBack g_old_cfallocator_system_default;
273 CFAllocatorAllocateCallBack g_old_cfallocator_malloc;
274 CFAllocatorAllocateCallBack g_old_cfallocator_malloc_zone;
276 void* oom_killer_cfallocator_system_default(CFIndex alloc_size,
279 void* result = g_old_cfallocator_system_default(alloc_size, hint, info);
281 TerminateBecauseOutOfMemory(alloc_size);
285 void* oom_killer_cfallocator_malloc(CFIndex alloc_size,
288 void* result = g_old_cfallocator_malloc(alloc_size, hint, info);
290 TerminateBecauseOutOfMemory(alloc_size);
294 void* oom_killer_cfallocator_malloc_zone(CFIndex alloc_size,
297 void* result = g_old_cfallocator_malloc_zone(alloc_size, hint, info);
299 TerminateBecauseOutOfMemory(alloc_size);
303 #endif // !defined(ADDRESS_SANITIZER)
305 // === Cocoa NSObject allocation ===
307 typedef id (*allocWithZone_t)(id, SEL, NSZone*);
308 allocWithZone_t g_old_allocWithZone;
310 id oom_killer_allocWithZone(id self, SEL _cmd, NSZone* zone)
312 id result = g_old_allocWithZone(self, _cmd, zone);
314 TerminateBecauseOutOfMemory(0);
320 bool UncheckedMalloc(size_t size, void** result) {
321 #if defined(ADDRESS_SANITIZER)
322 *result = malloc(size);
325 *result = g_old_malloc(malloc_default_zone(), size);
327 *result = malloc(size);
329 #endif // defined(ADDRESS_SANITIZER)
331 return *result != NULL;
334 bool UncheckedCalloc(size_t num_items, size_t size, void** result) {
335 #if defined(ADDRESS_SANITIZER)
336 *result = calloc(num_items, size);
339 *result = g_old_calloc(malloc_default_zone(), num_items, size);
341 *result = calloc(num_items, size);
343 #endif // defined(ADDRESS_SANITIZER)
345 return *result != NULL;
348 void* UncheckedMalloc(size_t size) {
350 return UncheckedMalloc(size, &address) ? address : NULL;
353 void* UncheckedCalloc(size_t num_items, size_t size) {
355 return UncheckedCalloc(num_items, size, &address) ? address : NULL;
358 void EnableTerminationOnOutOfMemory() {
359 if (g_oom_killer_enabled)
362 g_oom_killer_enabled = true;
364 // === C malloc/calloc/valloc/realloc/posix_memalign ===
366 // This approach is not perfect, as requests for amounts of memory larger than
367 // MALLOC_ABSOLUTE_MAX_SIZE (currently SIZE_T_MAX - (2 * PAGE_SIZE)) will
368 // still fail with a NULL rather than dying (see
369 // http://opensource.apple.com/source/Libc/Libc-583/gen/malloc.c for details).
370 // Unfortunately, it's the best we can do. Also note that this does not affect
371 // allocations from non-default zones.
373 #if !defined(ADDRESS_SANITIZER)
374 // Don't do anything special on OOM for the malloc zones replaced by
375 // AddressSanitizer, as modifying or protecting them may not work correctly.
377 CHECK(!g_old_malloc && !g_old_calloc && !g_old_valloc && !g_old_realloc &&
378 !g_old_memalign) << "Old allocators unexpectedly non-null";
380 CHECK(!g_old_malloc_purgeable && !g_old_calloc_purgeable &&
381 !g_old_valloc_purgeable && !g_old_realloc_purgeable &&
382 !g_old_memalign_purgeable) << "Old allocators unexpectedly non-null";
384 ChromeMallocZone* default_zone =
385 reinterpret_cast<ChromeMallocZone*>(malloc_default_zone());
386 ChromeMallocZone* purgeable_zone =
387 reinterpret_cast<ChromeMallocZone*>(malloc_default_purgeable_zone());
389 mach_vm_address_t default_reprotection_start = 0;
390 mach_vm_size_t default_reprotection_length = 0;
391 vm_prot_t default_reprotection_value = VM_PROT_NONE;
392 DeprotectMallocZone(default_zone,
393 &default_reprotection_start,
394 &default_reprotection_length,
395 &default_reprotection_value);
397 mach_vm_address_t purgeable_reprotection_start = 0;
398 mach_vm_size_t purgeable_reprotection_length = 0;
399 vm_prot_t purgeable_reprotection_value = VM_PROT_NONE;
400 if (purgeable_zone) {
401 DeprotectMallocZone(purgeable_zone,
402 &purgeable_reprotection_start,
403 &purgeable_reprotection_length,
404 &purgeable_reprotection_value);
409 g_old_malloc = default_zone->malloc;
410 g_old_calloc = default_zone->calloc;
411 g_old_valloc = default_zone->valloc;
412 g_old_free = default_zone->free;
413 g_old_realloc = default_zone->realloc;
414 CHECK(g_old_malloc && g_old_calloc && g_old_valloc && g_old_free &&
416 << "Failed to get system allocation functions.";
418 default_zone->malloc = oom_killer_malloc;
419 default_zone->calloc = oom_killer_calloc;
420 default_zone->valloc = oom_killer_valloc;
421 default_zone->free = oom_killer_free;
422 default_zone->realloc = oom_killer_realloc;
424 if (default_zone->version >= 5) {
425 g_old_memalign = default_zone->memalign;
427 default_zone->memalign = oom_killer_memalign;
430 // Purgeable zone (if it exists)
432 if (purgeable_zone) {
433 g_old_malloc_purgeable = purgeable_zone->malloc;
434 g_old_calloc_purgeable = purgeable_zone->calloc;
435 g_old_valloc_purgeable = purgeable_zone->valloc;
436 g_old_free_purgeable = purgeable_zone->free;
437 g_old_realloc_purgeable = purgeable_zone->realloc;
438 CHECK(g_old_malloc_purgeable && g_old_calloc_purgeable &&
439 g_old_valloc_purgeable && g_old_free_purgeable &&
440 g_old_realloc_purgeable)
441 << "Failed to get system allocation functions.";
443 purgeable_zone->malloc = oom_killer_malloc_purgeable;
444 purgeable_zone->calloc = oom_killer_calloc_purgeable;
445 purgeable_zone->valloc = oom_killer_valloc_purgeable;
446 purgeable_zone->free = oom_killer_free_purgeable;
447 purgeable_zone->realloc = oom_killer_realloc_purgeable;
449 if (purgeable_zone->version >= 5) {
450 g_old_memalign_purgeable = purgeable_zone->memalign;
451 if (g_old_memalign_purgeable)
452 purgeable_zone->memalign = oom_killer_memalign_purgeable;
456 // Restore protection if it was active.
458 if (default_reprotection_start) {
459 kern_return_t result = mach_vm_protect(mach_task_self(),
460 default_reprotection_start,
461 default_reprotection_length,
463 default_reprotection_value);
464 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
467 if (purgeable_reprotection_start) {
468 kern_return_t result = mach_vm_protect(mach_task_self(),
469 purgeable_reprotection_start,
470 purgeable_reprotection_length,
472 purgeable_reprotection_value);
473 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
477 // === C malloc_zone_batch_malloc ===
479 // batch_malloc is omitted because the default malloc zone's implementation
480 // only supports batch_malloc for "tiny" allocations from the free list. It
481 // will fail for allocations larger than "tiny", and will only allocate as
482 // many blocks as it's able to from the free list. These factors mean that it
483 // can return less than the requested memory even in a non-out-of-memory
484 // situation. There's no good way to detect whether a batch_malloc failure is
485 // due to these other factors, or due to genuine memory or address space
486 // exhaustion. The fact that it only allocates space from the "tiny" free list
487 // means that it's likely that a failure will not be due to memory exhaustion.
488 // Similarly, these constraints on batch_malloc mean that callers must always
489 // be expecting to receive less memory than was requested, even in situations
490 // where memory pressure is not a concern. Finally, the only public interface
491 // to batch_malloc is malloc_zone_batch_malloc, which is specific to the
492 // system's malloc implementation. It's unlikely that anyone's even heard of
495 // === C++ operator new ===
497 // Yes, operator new does call through to malloc, but this will catch failures
498 // that our imperfect handling of malloc cannot.
500 std::set_new_handler(oom_killer_new);
502 #ifndef ADDRESS_SANITIZER
503 // === Core Foundation CFAllocators ===
505 // This will not catch allocation done by custom allocators, but will catch
506 // all allocation done by system-provided ones.
508 CHECK(!g_old_cfallocator_system_default && !g_old_cfallocator_malloc &&
509 !g_old_cfallocator_malloc_zone)
510 << "Old allocators unexpectedly non-null";
512 bool cf_allocator_internals_known = CanGetContextForCFAllocator();
514 if (cf_allocator_internals_known) {
515 CFAllocatorContext* context =
516 ContextForCFAllocator(kCFAllocatorSystemDefault);
517 CHECK(context) << "Failed to get context for kCFAllocatorSystemDefault.";
518 g_old_cfallocator_system_default = context->allocate;
519 CHECK(g_old_cfallocator_system_default)
520 << "Failed to get kCFAllocatorSystemDefault allocation function.";
521 context->allocate = oom_killer_cfallocator_system_default;
523 context = ContextForCFAllocator(kCFAllocatorMalloc);
524 CHECK(context) << "Failed to get context for kCFAllocatorMalloc.";
525 g_old_cfallocator_malloc = context->allocate;
526 CHECK(g_old_cfallocator_malloc)
527 << "Failed to get kCFAllocatorMalloc allocation function.";
528 context->allocate = oom_killer_cfallocator_malloc;
530 context = ContextForCFAllocator(kCFAllocatorMallocZone);
531 CHECK(context) << "Failed to get context for kCFAllocatorMallocZone.";
532 g_old_cfallocator_malloc_zone = context->allocate;
533 CHECK(g_old_cfallocator_malloc_zone)
534 << "Failed to get kCFAllocatorMallocZone allocation function.";
535 context->allocate = oom_killer_cfallocator_malloc_zone;
537 DLOG(WARNING) << "Internals of CFAllocator not known; out-of-memory "
538 "failures via CFAllocator will not result in termination. "
539 "http://crbug.com/45650";
543 // === Cocoa NSObject allocation ===
545 // Note that both +[NSObject new] and +[NSObject alloc] call through to
546 // +[NSObject allocWithZone:].
548 CHECK(!g_old_allocWithZone)
549 << "Old allocator unexpectedly non-null";
551 Class nsobject_class = [NSObject class];
552 Method orig_method = class_getClassMethod(nsobject_class,
553 @selector(allocWithZone:));
554 g_old_allocWithZone = reinterpret_cast<allocWithZone_t>(
555 method_getImplementation(orig_method));
556 CHECK(g_old_allocWithZone)
557 << "Failed to get allocWithZone allocation function.";
558 method_setImplementation(orig_method,
559 reinterpret_cast<IMP>(oom_killer_allocWithZone));