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 // AddressSanitizer handles heap corruption, and on 64 bit Macs, the malloc
8 // system automatically abort()s on heap corruption.
9 #if !defined(ADDRESS_SANITIZER) && ARCH_CPU_32_BITS
10 #define HANDLE_MEMORY_CORRUPTION_MANUALLY
13 #include <CoreFoundation/CoreFoundation.h>
15 #include <mach/mach.h>
16 #include <mach/mach_vm.h>
17 #include <malloc/malloc.h>
18 #import <objc/runtime.h>
22 #include "base/lazy_instance.h"
23 #include "base/logging.h"
24 #include "base/mac/mac_util.h"
25 #include "base/mac/mach_logging.h"
26 #include "base/scoped_clear_errno.h"
27 #include "third_party/apple_apsl/CFBase.h"
28 #include "third_party/apple_apsl/malloc.h"
30 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
32 #include <mach-o/nlist.h>
34 #include "base/threading/thread_local.h"
35 #include "third_party/mach_override/mach_override.h"
36 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
40 // These are helpers for EnableTerminationOnHeapCorruption, which is a no-op
42 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
45 // Finds the library path for malloc() and thus the libC part of libSystem,
46 // which in Lion is in a separate image.
47 const char* LookUpLibCPath() {
48 const void* addr = reinterpret_cast<void*>(&malloc);
51 if (dladdr(addr, &info))
52 return info.dli_fname;
54 DLOG(WARNING) << "Could not find image path for malloc()";
58 typedef void(*malloc_error_break_t)(void);
59 malloc_error_break_t g_original_malloc_error_break = NULL;
61 // Returns the function pointer for malloc_error_break. This symbol is declared
62 // as __private_extern__ and cannot be dlsym()ed. Instead, use nlist() to
64 malloc_error_break_t LookUpMallocErrorBreak() {
65 const char* lib_c_path = LookUpLibCPath();
69 // Only need to look up two symbols, but nlist() requires a NULL-terminated
70 // array and takes no count.
72 bzero(&nl, sizeof(nl));
74 // The symbol to find.
75 nl[0].n_un.n_name = const_cast<char*>("_malloc_error_break");
77 // A reference symbol by which the address of the desired symbol will be
79 nl[1].n_un.n_name = const_cast<char*>("_malloc");
81 int rv = nlist(lib_c_path, nl);
82 if (rv != 0 || nl[0].n_type == N_UNDF || nl[1].n_type == N_UNDF) {
86 // nlist() returns addresses as offsets in the image, not the instruction
87 // pointer in memory. Use the known in-memory address of malloc()
88 // to compute the offset for malloc_error_break().
89 uintptr_t reference_addr = reinterpret_cast<uintptr_t>(&malloc);
90 reference_addr -= nl[1].n_value;
91 reference_addr += nl[0].n_value;
93 return reinterpret_cast<malloc_error_break_t>(reference_addr);
96 // Combines ThreadLocalBoolean with AutoReset. It would be convenient
97 // to compose ThreadLocalPointer<bool> with base::AutoReset<bool>, but that
98 // would require allocating some storage for the bool.
99 class ThreadLocalBooleanAutoReset {
101 ThreadLocalBooleanAutoReset(ThreadLocalBoolean* tlb, bool new_value)
103 original_value_(tlb->Get()) {
104 scoped_tlb_->Set(new_value);
106 ~ThreadLocalBooleanAutoReset() {
107 scoped_tlb_->Set(original_value_);
111 ThreadLocalBoolean* scoped_tlb_;
112 bool original_value_;
114 DISALLOW_COPY_AND_ASSIGN(ThreadLocalBooleanAutoReset);
117 base::LazyInstance<ThreadLocalBoolean>::Leaky
118 g_unchecked_alloc = LAZY_INSTANCE_INITIALIZER;
120 // NOTE(shess): This is called when the malloc library noticed that the heap
121 // is fubar. Avoid calls which will re-enter the malloc library.
122 void CrMallocErrorBreak() {
123 g_original_malloc_error_break();
125 // Out of memory is certainly not heap corruption, and not necessarily
126 // something for which the process should be terminated. Leave that decision
127 // to the OOM killer.
131 // The malloc library attempts to log to ASL (syslog) before calling this
132 // code, which fails accessing a Unix-domain socket when sandboxed. The
133 // failed socket results in writing to a -1 fd, leaving EBADF in errno. If
134 // UncheckedMalloc() is on the stack, for large allocations (15k and up) only
135 // an OOM failure leads here. Smaller allocations could also arrive here due
136 // to freelist corruption, but there is no way to distinguish that from OOM at
139 // NOTE(shess): I hypothesize that EPERM case in 10.9 is the same root cause
140 // as EBADF. Unfortunately, 10.9's opensource releases don't include malloc
141 // source code at this time.
142 // <http://crbug.com/312234>
143 if ((errno == EBADF || errno == EPERM) && g_unchecked_alloc.Get().Get())
146 // A unit test checks this error message, so it needs to be in release builds.
148 "Terminating process due to a potential for future heap corruption: "
151 '0' + ((errno / 100) % 10),
152 '0' + ((errno / 10) % 10),
156 COMPILE_ASSERT(ELAST <= 999, errno_too_large_to_encode);
157 strlcat(buf, errnobuf, sizeof(buf));
160 // Crash by writing to NULL+errno to allow analyzing errno from
161 // crash dump info (setting a breakpad key would re-enter the malloc
162 // library). Max documented errno in intro(2) is actually 102, but
163 // it really just needs to be "small" to stay on the right vm page.
164 const int kMaxErrno = 256;
165 char* volatile death_ptr = NULL;
166 death_ptr += std::min(errno, kMaxErrno);
171 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
173 void EnableTerminationOnHeapCorruption() {
174 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
175 // Only override once, otherwise CrMallocErrorBreak() will recurse
177 if (g_original_malloc_error_break)
180 malloc_error_break_t malloc_error_break = LookUpMallocErrorBreak();
181 if (!malloc_error_break) {
182 DLOG(WARNING) << "Could not find malloc_error_break";
186 mach_error_t err = mach_override_ptr(
187 (void*)malloc_error_break,
188 (void*)&CrMallocErrorBreak,
189 (void**)&g_original_malloc_error_break);
192 DLOG(WARNING) << "Could not override malloc_error_break; error = " << err;
193 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
196 // ------------------------------------------------------------------------
200 bool g_oom_killer_enabled;
202 #if !defined(ADDRESS_SANITIZER)
204 // Starting with Mac OS X 10.7, the zone allocators set up by the system are
205 // read-only, to prevent them from being overwritten in an attack. However,
206 // blindly unprotecting and reprotecting the zone allocators fails with
207 // GuardMalloc because GuardMalloc sets up its zone allocator using a block of
208 // memory in its bss. Explicit saving/restoring of the protection is required.
210 // This function takes a pointer to a malloc zone, de-protects it if necessary,
211 // and returns (in the out parameters) a region of memory (if any) to be
212 // re-protected when modifications are complete. This approach assumes that
213 // there is no contention for the protection of this memory.
214 void DeprotectMallocZone(ChromeMallocZone* default_zone,
215 mach_vm_address_t* reprotection_start,
216 mach_vm_size_t* reprotection_length,
217 vm_prot_t* reprotection_value) {
219 *reprotection_start = reinterpret_cast<mach_vm_address_t>(default_zone);
220 struct vm_region_basic_info_64 info;
221 mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64;
222 kern_return_t result =
223 mach_vm_region(mach_task_self(),
226 VM_REGION_BASIC_INFO_64,
227 reinterpret_cast<vm_region_info_t>(&info),
230 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_region";
232 // The kernel always returns a null object for VM_REGION_BASIC_INFO_64, but
233 // balance it with a deallocate in case this ever changes. See 10.9.2
234 // xnu-2422.90.20/osfmk/vm/vm_map.c vm_map_region.
235 mach_port_deallocate(mach_task_self(), unused);
237 // Does the region fully enclose the zone pointers? Possibly unwarranted
238 // simplification used: using the size of a full version 8 malloc zone rather
239 // than the actual smaller size if the passed-in zone is not version 8.
240 CHECK(*reprotection_start <=
241 reinterpret_cast<mach_vm_address_t>(default_zone));
242 mach_vm_size_t zone_offset = reinterpret_cast<mach_vm_size_t>(default_zone) -
243 reinterpret_cast<mach_vm_size_t>(*reprotection_start);
244 CHECK(zone_offset + sizeof(ChromeMallocZone) <= *reprotection_length);
246 if (info.protection & VM_PROT_WRITE) {
247 // No change needed; the zone is already writable.
248 *reprotection_start = 0;
249 *reprotection_length = 0;
250 *reprotection_value = VM_PROT_NONE;
252 *reprotection_value = info.protection;
253 result = mach_vm_protect(mach_task_self(),
255 *reprotection_length,
257 info.protection | VM_PROT_WRITE);
258 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
262 // === C malloc/calloc/valloc/realloc/posix_memalign ===
264 typedef void* (*malloc_type)(struct _malloc_zone_t* zone,
266 typedef void* (*calloc_type)(struct _malloc_zone_t* zone,
269 typedef void* (*valloc_type)(struct _malloc_zone_t* zone,
271 typedef void (*free_type)(struct _malloc_zone_t* zone,
273 typedef void* (*realloc_type)(struct _malloc_zone_t* zone,
276 typedef void* (*memalign_type)(struct _malloc_zone_t* zone,
280 malloc_type g_old_malloc;
281 calloc_type g_old_calloc;
282 valloc_type g_old_valloc;
283 free_type g_old_free;
284 realloc_type g_old_realloc;
285 memalign_type g_old_memalign;
287 malloc_type g_old_malloc_purgeable;
288 calloc_type g_old_calloc_purgeable;
289 valloc_type g_old_valloc_purgeable;
290 free_type g_old_free_purgeable;
291 realloc_type g_old_realloc_purgeable;
292 memalign_type g_old_memalign_purgeable;
294 void* oom_killer_malloc(struct _malloc_zone_t* zone,
296 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
297 ScopedClearErrno clear_errno;
298 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
299 void* result = g_old_malloc(zone, size);
301 debug::BreakDebugger();
305 void* oom_killer_calloc(struct _malloc_zone_t* zone,
308 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
309 ScopedClearErrno clear_errno;
310 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
311 void* result = g_old_calloc(zone, num_items, size);
312 if (!result && num_items && size)
313 debug::BreakDebugger();
317 void* oom_killer_valloc(struct _malloc_zone_t* zone,
319 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
320 ScopedClearErrno clear_errno;
321 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
322 void* result = g_old_valloc(zone, size);
324 debug::BreakDebugger();
328 void oom_killer_free(struct _malloc_zone_t* zone,
330 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
331 ScopedClearErrno clear_errno;
332 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
333 g_old_free(zone, ptr);
336 void* oom_killer_realloc(struct _malloc_zone_t* zone,
339 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
340 ScopedClearErrno clear_errno;
341 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
342 void* result = g_old_realloc(zone, ptr, size);
344 debug::BreakDebugger();
348 void* oom_killer_memalign(struct _malloc_zone_t* zone,
351 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
352 ScopedClearErrno clear_errno;
353 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
354 void* result = g_old_memalign(zone, alignment, size);
355 // Only die if posix_memalign would have returned ENOMEM, since there are
356 // other reasons why NULL might be returned (see
357 // http://opensource.apple.com/source/Libc/Libc-583/gen/malloc.c ).
358 if (!result && size && alignment >= sizeof(void*)
359 && (alignment & (alignment - 1)) == 0) {
360 debug::BreakDebugger();
365 void* oom_killer_malloc_purgeable(struct _malloc_zone_t* zone,
367 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
368 ScopedClearErrno clear_errno;
369 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
370 void* result = g_old_malloc_purgeable(zone, size);
372 debug::BreakDebugger();
376 void* oom_killer_calloc_purgeable(struct _malloc_zone_t* zone,
379 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
380 ScopedClearErrno clear_errno;
381 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
382 void* result = g_old_calloc_purgeable(zone, num_items, size);
383 if (!result && num_items && size)
384 debug::BreakDebugger();
388 void* oom_killer_valloc_purgeable(struct _malloc_zone_t* zone,
390 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
391 ScopedClearErrno clear_errno;
392 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
393 void* result = g_old_valloc_purgeable(zone, size);
395 debug::BreakDebugger();
399 void oom_killer_free_purgeable(struct _malloc_zone_t* zone,
401 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
402 ScopedClearErrno clear_errno;
403 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
404 g_old_free_purgeable(zone, ptr);
407 void* oom_killer_realloc_purgeable(struct _malloc_zone_t* zone,
410 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
411 ScopedClearErrno clear_errno;
412 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
413 void* result = g_old_realloc_purgeable(zone, ptr, size);
415 debug::BreakDebugger();
419 void* oom_killer_memalign_purgeable(struct _malloc_zone_t* zone,
422 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
423 ScopedClearErrno clear_errno;
424 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
425 void* result = g_old_memalign_purgeable(zone, alignment, size);
426 // Only die if posix_memalign would have returned ENOMEM, since there are
427 // other reasons why NULL might be returned (see
428 // http://opensource.apple.com/source/Libc/Libc-583/gen/malloc.c ).
429 if (!result && size && alignment >= sizeof(void*)
430 && (alignment & (alignment - 1)) == 0) {
431 debug::BreakDebugger();
436 #endif // !defined(ADDRESS_SANITIZER)
438 // === C++ operator new ===
440 void oom_killer_new() {
441 debug::BreakDebugger();
444 #if !defined(ADDRESS_SANITIZER)
446 // === Core Foundation CFAllocators ===
448 bool CanGetContextForCFAllocator() {
449 return !base::mac::IsOSLaterThanYosemite_DontCallThis();
452 CFAllocatorContext* ContextForCFAllocator(CFAllocatorRef allocator) {
453 if (base::mac::IsOSSnowLeopard()) {
454 ChromeCFAllocatorLeopards* our_allocator =
455 const_cast<ChromeCFAllocatorLeopards*>(
456 reinterpret_cast<const ChromeCFAllocatorLeopards*>(allocator));
457 return &our_allocator->_context;
458 } else if (base::mac::IsOSLion() ||
459 base::mac::IsOSMountainLion() ||
460 base::mac::IsOSMavericks() ||
461 base::mac::IsOSYosemite()) {
462 ChromeCFAllocatorLions* our_allocator =
463 const_cast<ChromeCFAllocatorLions*>(
464 reinterpret_cast<const ChromeCFAllocatorLions*>(allocator));
465 return &our_allocator->_context;
471 CFAllocatorAllocateCallBack g_old_cfallocator_system_default;
472 CFAllocatorAllocateCallBack g_old_cfallocator_malloc;
473 CFAllocatorAllocateCallBack g_old_cfallocator_malloc_zone;
475 void* oom_killer_cfallocator_system_default(CFIndex alloc_size,
478 void* result = g_old_cfallocator_system_default(alloc_size, hint, info);
480 debug::BreakDebugger();
484 void* oom_killer_cfallocator_malloc(CFIndex alloc_size,
487 void* result = g_old_cfallocator_malloc(alloc_size, hint, info);
489 debug::BreakDebugger();
493 void* oom_killer_cfallocator_malloc_zone(CFIndex alloc_size,
496 void* result = g_old_cfallocator_malloc_zone(alloc_size, hint, info);
498 debug::BreakDebugger();
502 #endif // !defined(ADDRESS_SANITIZER)
504 // === Cocoa NSObject allocation ===
506 typedef id (*allocWithZone_t)(id, SEL, NSZone*);
507 allocWithZone_t g_old_allocWithZone;
509 id oom_killer_allocWithZone(id self, SEL _cmd, NSZone* zone)
511 id result = g_old_allocWithZone(self, _cmd, zone);
513 debug::BreakDebugger();
519 bool UncheckedMalloc(size_t size, void** result) {
520 #if defined(ADDRESS_SANITIZER)
521 *result = malloc(size);
524 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
525 ScopedClearErrno clear_errno;
526 ThreadLocalBooleanAutoReset flag(g_unchecked_alloc.Pointer(), true);
527 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
528 *result = g_old_malloc(malloc_default_zone(), size);
530 *result = malloc(size);
532 #endif // defined(ADDRESS_SANITIZER)
534 return *result != NULL;
537 bool UncheckedCalloc(size_t num_items, size_t size, void** result) {
538 #if defined(ADDRESS_SANITIZER)
539 *result = calloc(num_items, size);
542 #if defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
543 ScopedClearErrno clear_errno;
544 ThreadLocalBooleanAutoReset flag(g_unchecked_alloc.Pointer(), true);
545 #endif // defined(HANDLE_MEMORY_CORRUPTION_MANUALLY)
546 *result = g_old_calloc(malloc_default_zone(), num_items, size);
548 *result = calloc(num_items, size);
550 #endif // defined(ADDRESS_SANITIZER)
552 return *result != NULL;
555 void* UncheckedMalloc(size_t size) {
557 return UncheckedMalloc(size, &address) ? address : NULL;
560 void* UncheckedCalloc(size_t num_items, size_t size) {
562 return UncheckedCalloc(num_items, size, &address) ? address : NULL;
565 void EnableTerminationOnOutOfMemory() {
566 if (g_oom_killer_enabled)
569 g_oom_killer_enabled = true;
571 // === C malloc/calloc/valloc/realloc/posix_memalign ===
573 // This approach is not perfect, as requests for amounts of memory larger than
574 // MALLOC_ABSOLUTE_MAX_SIZE (currently SIZE_T_MAX - (2 * PAGE_SIZE)) will
575 // still fail with a NULL rather than dying (see
576 // http://opensource.apple.com/source/Libc/Libc-583/gen/malloc.c for details).
577 // Unfortunately, it's the best we can do. Also note that this does not affect
578 // allocations from non-default zones.
580 #if !defined(ADDRESS_SANITIZER)
581 // Don't do anything special on OOM for the malloc zones replaced by
582 // AddressSanitizer, as modifying or protecting them may not work correctly.
584 CHECK(!g_old_malloc && !g_old_calloc && !g_old_valloc && !g_old_realloc &&
585 !g_old_memalign) << "Old allocators unexpectedly non-null";
587 CHECK(!g_old_malloc_purgeable && !g_old_calloc_purgeable &&
588 !g_old_valloc_purgeable && !g_old_realloc_purgeable &&
589 !g_old_memalign_purgeable) << "Old allocators unexpectedly non-null";
591 ChromeMallocZone* default_zone =
592 reinterpret_cast<ChromeMallocZone*>(malloc_default_zone());
593 ChromeMallocZone* purgeable_zone =
594 reinterpret_cast<ChromeMallocZone*>(malloc_default_purgeable_zone());
596 mach_vm_address_t default_reprotection_start = 0;
597 mach_vm_size_t default_reprotection_length = 0;
598 vm_prot_t default_reprotection_value = VM_PROT_NONE;
599 DeprotectMallocZone(default_zone,
600 &default_reprotection_start,
601 &default_reprotection_length,
602 &default_reprotection_value);
604 mach_vm_address_t purgeable_reprotection_start = 0;
605 mach_vm_size_t purgeable_reprotection_length = 0;
606 vm_prot_t purgeable_reprotection_value = VM_PROT_NONE;
607 if (purgeable_zone) {
608 DeprotectMallocZone(purgeable_zone,
609 &purgeable_reprotection_start,
610 &purgeable_reprotection_length,
611 &purgeable_reprotection_value);
616 g_old_malloc = default_zone->malloc;
617 g_old_calloc = default_zone->calloc;
618 g_old_valloc = default_zone->valloc;
619 g_old_free = default_zone->free;
620 g_old_realloc = default_zone->realloc;
621 CHECK(g_old_malloc && g_old_calloc && g_old_valloc && g_old_free &&
623 << "Failed to get system allocation functions.";
625 default_zone->malloc = oom_killer_malloc;
626 default_zone->calloc = oom_killer_calloc;
627 default_zone->valloc = oom_killer_valloc;
628 default_zone->free = oom_killer_free;
629 default_zone->realloc = oom_killer_realloc;
631 if (default_zone->version >= 5) {
632 g_old_memalign = default_zone->memalign;
634 default_zone->memalign = oom_killer_memalign;
637 // Purgeable zone (if it exists)
639 if (purgeable_zone) {
640 g_old_malloc_purgeable = purgeable_zone->malloc;
641 g_old_calloc_purgeable = purgeable_zone->calloc;
642 g_old_valloc_purgeable = purgeable_zone->valloc;
643 g_old_free_purgeable = purgeable_zone->free;
644 g_old_realloc_purgeable = purgeable_zone->realloc;
645 CHECK(g_old_malloc_purgeable && g_old_calloc_purgeable &&
646 g_old_valloc_purgeable && g_old_free_purgeable &&
647 g_old_realloc_purgeable)
648 << "Failed to get system allocation functions.";
650 purgeable_zone->malloc = oom_killer_malloc_purgeable;
651 purgeable_zone->calloc = oom_killer_calloc_purgeable;
652 purgeable_zone->valloc = oom_killer_valloc_purgeable;
653 purgeable_zone->free = oom_killer_free_purgeable;
654 purgeable_zone->realloc = oom_killer_realloc_purgeable;
656 if (purgeable_zone->version >= 5) {
657 g_old_memalign_purgeable = purgeable_zone->memalign;
658 if (g_old_memalign_purgeable)
659 purgeable_zone->memalign = oom_killer_memalign_purgeable;
663 // Restore protection if it was active.
665 if (default_reprotection_start) {
666 kern_return_t result = mach_vm_protect(mach_task_self(),
667 default_reprotection_start,
668 default_reprotection_length,
670 default_reprotection_value);
671 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
674 if (purgeable_reprotection_start) {
675 kern_return_t result = mach_vm_protect(mach_task_self(),
676 purgeable_reprotection_start,
677 purgeable_reprotection_length,
679 purgeable_reprotection_value);
680 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
684 // === C malloc_zone_batch_malloc ===
686 // batch_malloc is omitted because the default malloc zone's implementation
687 // only supports batch_malloc for "tiny" allocations from the free list. It
688 // will fail for allocations larger than "tiny", and will only allocate as
689 // many blocks as it's able to from the free list. These factors mean that it
690 // can return less than the requested memory even in a non-out-of-memory
691 // situation. There's no good way to detect whether a batch_malloc failure is
692 // due to these other factors, or due to genuine memory or address space
693 // exhaustion. The fact that it only allocates space from the "tiny" free list
694 // means that it's likely that a failure will not be due to memory exhaustion.
695 // Similarly, these constraints on batch_malloc mean that callers must always
696 // be expecting to receive less memory than was requested, even in situations
697 // where memory pressure is not a concern. Finally, the only public interface
698 // to batch_malloc is malloc_zone_batch_malloc, which is specific to the
699 // system's malloc implementation. It's unlikely that anyone's even heard of
702 // === C++ operator new ===
704 // Yes, operator new does call through to malloc, but this will catch failures
705 // that our imperfect handling of malloc cannot.
707 std::set_new_handler(oom_killer_new);
709 #ifndef ADDRESS_SANITIZER
710 // === Core Foundation CFAllocators ===
712 // This will not catch allocation done by custom allocators, but will catch
713 // all allocation done by system-provided ones.
715 CHECK(!g_old_cfallocator_system_default && !g_old_cfallocator_malloc &&
716 !g_old_cfallocator_malloc_zone)
717 << "Old allocators unexpectedly non-null";
719 bool cf_allocator_internals_known = CanGetContextForCFAllocator();
721 if (cf_allocator_internals_known) {
722 CFAllocatorContext* context =
723 ContextForCFAllocator(kCFAllocatorSystemDefault);
724 CHECK(context) << "Failed to get context for kCFAllocatorSystemDefault.";
725 g_old_cfallocator_system_default = context->allocate;
726 CHECK(g_old_cfallocator_system_default)
727 << "Failed to get kCFAllocatorSystemDefault allocation function.";
728 context->allocate = oom_killer_cfallocator_system_default;
730 context = ContextForCFAllocator(kCFAllocatorMalloc);
731 CHECK(context) << "Failed to get context for kCFAllocatorMalloc.";
732 g_old_cfallocator_malloc = context->allocate;
733 CHECK(g_old_cfallocator_malloc)
734 << "Failed to get kCFAllocatorMalloc allocation function.";
735 context->allocate = oom_killer_cfallocator_malloc;
737 context = ContextForCFAllocator(kCFAllocatorMallocZone);
738 CHECK(context) << "Failed to get context for kCFAllocatorMallocZone.";
739 g_old_cfallocator_malloc_zone = context->allocate;
740 CHECK(g_old_cfallocator_malloc_zone)
741 << "Failed to get kCFAllocatorMallocZone allocation function.";
742 context->allocate = oom_killer_cfallocator_malloc_zone;
744 DLOG(WARNING) << "Internals of CFAllocator not known; out-of-memory "
745 "failures via CFAllocator will not result in termination. "
746 "http://crbug.com/45650";
750 // === Cocoa NSObject allocation ===
752 // Note that both +[NSObject new] and +[NSObject alloc] call through to
753 // +[NSObject allocWithZone:].
755 CHECK(!g_old_allocWithZone)
756 << "Old allocator unexpectedly non-null";
758 Class nsobject_class = [NSObject class];
759 Method orig_method = class_getClassMethod(nsobject_class,
760 @selector(allocWithZone:));
761 g_old_allocWithZone = reinterpret_cast<allocWithZone_t>(
762 method_getImplementation(orig_method));
763 CHECK(g_old_allocWithZone)
764 << "Failed to get allocWithZone allocation function.";
765 method_setImplementation(orig_method,
766 reinterpret_cast<IMP>(oom_killer_allocWithZone));