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::IsOSLaterThanYosemite_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 ChromeCFAllocatorLions* our_allocator =
263 const_cast<ChromeCFAllocatorLions*>(
264 reinterpret_cast<const ChromeCFAllocatorLions*>(allocator));
265 return &our_allocator->_context;
271 CFAllocatorAllocateCallBack g_old_cfallocator_system_default;
272 CFAllocatorAllocateCallBack g_old_cfallocator_malloc;
273 CFAllocatorAllocateCallBack g_old_cfallocator_malloc_zone;
275 void* oom_killer_cfallocator_system_default(CFIndex alloc_size,
278 void* result = g_old_cfallocator_system_default(alloc_size, hint, info);
280 TerminateBecauseOutOfMemory(alloc_size);
284 void* oom_killer_cfallocator_malloc(CFIndex alloc_size,
287 void* result = g_old_cfallocator_malloc(alloc_size, hint, info);
289 TerminateBecauseOutOfMemory(alloc_size);
293 void* oom_killer_cfallocator_malloc_zone(CFIndex alloc_size,
296 void* result = g_old_cfallocator_malloc_zone(alloc_size, hint, info);
298 TerminateBecauseOutOfMemory(alloc_size);
302 #endif // !defined(ADDRESS_SANITIZER)
304 // === Cocoa NSObject allocation ===
306 typedef id (*allocWithZone_t)(id, SEL, NSZone*);
307 allocWithZone_t g_old_allocWithZone;
309 id oom_killer_allocWithZone(id self, SEL _cmd, NSZone* zone)
311 id result = g_old_allocWithZone(self, _cmd, zone);
313 TerminateBecauseOutOfMemory(0);
319 bool UncheckedMalloc(size_t size, void** result) {
320 #if defined(ADDRESS_SANITIZER)
321 *result = malloc(size);
324 *result = g_old_malloc(malloc_default_zone(), size);
326 *result = malloc(size);
328 #endif // defined(ADDRESS_SANITIZER)
330 return *result != NULL;
333 bool UncheckedCalloc(size_t num_items, size_t size, void** result) {
334 #if defined(ADDRESS_SANITIZER)
335 *result = calloc(num_items, size);
338 *result = g_old_calloc(malloc_default_zone(), num_items, size);
340 *result = calloc(num_items, size);
342 #endif // defined(ADDRESS_SANITIZER)
344 return *result != NULL;
347 void* UncheckedMalloc(size_t size) {
349 return UncheckedMalloc(size, &address) ? address : NULL;
352 void* UncheckedCalloc(size_t num_items, size_t size) {
354 return UncheckedCalloc(num_items, size, &address) ? address : NULL;
357 void EnableTerminationOnOutOfMemory() {
358 if (g_oom_killer_enabled)
361 g_oom_killer_enabled = true;
363 // === C malloc/calloc/valloc/realloc/posix_memalign ===
365 // This approach is not perfect, as requests for amounts of memory larger than
366 // MALLOC_ABSOLUTE_MAX_SIZE (currently SIZE_T_MAX - (2 * PAGE_SIZE)) will
367 // still fail with a NULL rather than dying (see
368 // http://opensource.apple.com/source/Libc/Libc-583/gen/malloc.c for details).
369 // Unfortunately, it's the best we can do. Also note that this does not affect
370 // allocations from non-default zones.
372 #if !defined(ADDRESS_SANITIZER)
373 // Don't do anything special on OOM for the malloc zones replaced by
374 // AddressSanitizer, as modifying or protecting them may not work correctly.
376 CHECK(!g_old_malloc && !g_old_calloc && !g_old_valloc && !g_old_realloc &&
377 !g_old_memalign) << "Old allocators unexpectedly non-null";
379 CHECK(!g_old_malloc_purgeable && !g_old_calloc_purgeable &&
380 !g_old_valloc_purgeable && !g_old_realloc_purgeable &&
381 !g_old_memalign_purgeable) << "Old allocators unexpectedly non-null";
383 ChromeMallocZone* default_zone =
384 reinterpret_cast<ChromeMallocZone*>(malloc_default_zone());
385 ChromeMallocZone* purgeable_zone =
386 reinterpret_cast<ChromeMallocZone*>(malloc_default_purgeable_zone());
388 mach_vm_address_t default_reprotection_start = 0;
389 mach_vm_size_t default_reprotection_length = 0;
390 vm_prot_t default_reprotection_value = VM_PROT_NONE;
391 DeprotectMallocZone(default_zone,
392 &default_reprotection_start,
393 &default_reprotection_length,
394 &default_reprotection_value);
396 mach_vm_address_t purgeable_reprotection_start = 0;
397 mach_vm_size_t purgeable_reprotection_length = 0;
398 vm_prot_t purgeable_reprotection_value = VM_PROT_NONE;
399 if (purgeable_zone) {
400 DeprotectMallocZone(purgeable_zone,
401 &purgeable_reprotection_start,
402 &purgeable_reprotection_length,
403 &purgeable_reprotection_value);
408 g_old_malloc = default_zone->malloc;
409 g_old_calloc = default_zone->calloc;
410 g_old_valloc = default_zone->valloc;
411 g_old_free = default_zone->free;
412 g_old_realloc = default_zone->realloc;
413 CHECK(g_old_malloc && g_old_calloc && g_old_valloc && g_old_free &&
415 << "Failed to get system allocation functions.";
417 default_zone->malloc = oom_killer_malloc;
418 default_zone->calloc = oom_killer_calloc;
419 default_zone->valloc = oom_killer_valloc;
420 default_zone->free = oom_killer_free;
421 default_zone->realloc = oom_killer_realloc;
423 if (default_zone->version >= 5) {
424 g_old_memalign = default_zone->memalign;
426 default_zone->memalign = oom_killer_memalign;
429 // Purgeable zone (if it exists)
431 if (purgeable_zone) {
432 g_old_malloc_purgeable = purgeable_zone->malloc;
433 g_old_calloc_purgeable = purgeable_zone->calloc;
434 g_old_valloc_purgeable = purgeable_zone->valloc;
435 g_old_free_purgeable = purgeable_zone->free;
436 g_old_realloc_purgeable = purgeable_zone->realloc;
437 CHECK(g_old_malloc_purgeable && g_old_calloc_purgeable &&
438 g_old_valloc_purgeable && g_old_free_purgeable &&
439 g_old_realloc_purgeable)
440 << "Failed to get system allocation functions.";
442 purgeable_zone->malloc = oom_killer_malloc_purgeable;
443 purgeable_zone->calloc = oom_killer_calloc_purgeable;
444 purgeable_zone->valloc = oom_killer_valloc_purgeable;
445 purgeable_zone->free = oom_killer_free_purgeable;
446 purgeable_zone->realloc = oom_killer_realloc_purgeable;
448 if (purgeable_zone->version >= 5) {
449 g_old_memalign_purgeable = purgeable_zone->memalign;
450 if (g_old_memalign_purgeable)
451 purgeable_zone->memalign = oom_killer_memalign_purgeable;
455 // Restore protection if it was active.
457 if (default_reprotection_start) {
458 kern_return_t result = mach_vm_protect(mach_task_self(),
459 default_reprotection_start,
460 default_reprotection_length,
462 default_reprotection_value);
463 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
466 if (purgeable_reprotection_start) {
467 kern_return_t result = mach_vm_protect(mach_task_self(),
468 purgeable_reprotection_start,
469 purgeable_reprotection_length,
471 purgeable_reprotection_value);
472 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
476 // === C malloc_zone_batch_malloc ===
478 // batch_malloc is omitted because the default malloc zone's implementation
479 // only supports batch_malloc for "tiny" allocations from the free list. It
480 // will fail for allocations larger than "tiny", and will only allocate as
481 // many blocks as it's able to from the free list. These factors mean that it
482 // can return less than the requested memory even in a non-out-of-memory
483 // situation. There's no good way to detect whether a batch_malloc failure is
484 // due to these other factors, or due to genuine memory or address space
485 // exhaustion. The fact that it only allocates space from the "tiny" free list
486 // means that it's likely that a failure will not be due to memory exhaustion.
487 // Similarly, these constraints on batch_malloc mean that callers must always
488 // be expecting to receive less memory than was requested, even in situations
489 // where memory pressure is not a concern. Finally, the only public interface
490 // to batch_malloc is malloc_zone_batch_malloc, which is specific to the
491 // system's malloc implementation. It's unlikely that anyone's even heard of
494 // === C++ operator new ===
496 // Yes, operator new does call through to malloc, but this will catch failures
497 // that our imperfect handling of malloc cannot.
499 std::set_new_handler(oom_killer_new);
501 #ifndef ADDRESS_SANITIZER
502 // === Core Foundation CFAllocators ===
504 // This will not catch allocation done by custom allocators, but will catch
505 // all allocation done by system-provided ones.
507 CHECK(!g_old_cfallocator_system_default && !g_old_cfallocator_malloc &&
508 !g_old_cfallocator_malloc_zone)
509 << "Old allocators unexpectedly non-null";
511 bool cf_allocator_internals_known = CanGetContextForCFAllocator();
513 if (cf_allocator_internals_known) {
514 CFAllocatorContext* context =
515 ContextForCFAllocator(kCFAllocatorSystemDefault);
516 CHECK(context) << "Failed to get context for kCFAllocatorSystemDefault.";
517 g_old_cfallocator_system_default = context->allocate;
518 CHECK(g_old_cfallocator_system_default)
519 << "Failed to get kCFAllocatorSystemDefault allocation function.";
520 context->allocate = oom_killer_cfallocator_system_default;
522 context = ContextForCFAllocator(kCFAllocatorMalloc);
523 CHECK(context) << "Failed to get context for kCFAllocatorMalloc.";
524 g_old_cfallocator_malloc = context->allocate;
525 CHECK(g_old_cfallocator_malloc)
526 << "Failed to get kCFAllocatorMalloc allocation function.";
527 context->allocate = oom_killer_cfallocator_malloc;
529 context = ContextForCFAllocator(kCFAllocatorMallocZone);
530 CHECK(context) << "Failed to get context for kCFAllocatorMallocZone.";
531 g_old_cfallocator_malloc_zone = context->allocate;
532 CHECK(g_old_cfallocator_malloc_zone)
533 << "Failed to get kCFAllocatorMallocZone allocation function.";
534 context->allocate = oom_killer_cfallocator_malloc_zone;
536 DLOG(WARNING) << "Internals of CFAllocator not known; out-of-memory "
537 "failures via CFAllocator will not result in termination. "
538 "http://crbug.com/45650";
542 // === Cocoa NSObject allocation ===
544 // Note that both +[NSObject new] and +[NSObject alloc] call through to
545 // +[NSObject allocWithZone:].
547 CHECK(!g_old_allocWithZone)
548 << "Old allocator unexpectedly non-null";
550 Class nsobject_class = [NSObject class];
551 Method orig_method = class_getClassMethod(nsobject_class,
552 @selector(allocWithZone:));
553 g_old_allocWithZone = reinterpret_cast<allocWithZone_t>(
554 method_getImplementation(orig_method));
555 CHECK(g_old_allocWithZone)
556 << "Failed to get allocWithZone allocation function.";
557 method_setImplementation(orig_method,
558 reinterpret_cast<IMP>(oom_killer_allocWithZone));