blob: 4d719f8054e69398f1f40da51f26f4d7b9ca11b3 [file] [log] [blame]
Daniel Eratb8cf9492015-07-06 13:18:13 -06001// 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.
4
5#include "base/process/memory.h"
6
7#include <CoreFoundation/CoreFoundation.h>
8#include <errno.h>
9#include <mach/mach.h>
10#include <mach/mach_vm.h>
11#include <malloc/malloc.h>
12#import <objc/runtime.h>
13
14#include <new>
15
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"
23
24namespace base {
25
26void EnableTerminationOnHeapCorruption() {
27#if !ARCH_CPU_64_BITS
28 DLOG(WARNING) << "EnableTerminationOnHeapCorruption only works on 64-bit";
29#endif
30}
31
32// ------------------------------------------------------------------------
33
34namespace {
35
36bool g_oom_killer_enabled;
37
38#if !defined(ADDRESS_SANITIZER)
39
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.
45//
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.
50void DeprotectMallocZone(ChromeMallocZone* default_zone,
51 mach_vm_address_t* reprotection_start,
52 mach_vm_size_t* reprotection_length,
53 vm_prot_t* reprotection_value) {
54 mach_port_t unused;
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(),
60 reprotection_start,
61 reprotection_length,
62 VM_REGION_BASIC_INFO_64,
63 reinterpret_cast<vm_region_info_t>(&info),
64 &count,
65 &unused);
66 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_region";
67
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);
72
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);
81
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;
87 } else {
88 *reprotection_value = info.protection;
89 result = mach_vm_protect(mach_task_self(),
90 *reprotection_start,
91 *reprotection_length,
92 false,
93 info.protection | VM_PROT_WRITE);
94 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
95 }
96}
97
98// === C malloc/calloc/valloc/realloc/posix_memalign ===
99
100typedef void* (*malloc_type)(struct _malloc_zone_t* zone,
101 size_t size);
102typedef void* (*calloc_type)(struct _malloc_zone_t* zone,
103 size_t num_items,
104 size_t size);
105typedef void* (*valloc_type)(struct _malloc_zone_t* zone,
106 size_t size);
107typedef void (*free_type)(struct _malloc_zone_t* zone,
108 void* ptr);
109typedef void* (*realloc_type)(struct _malloc_zone_t* zone,
110 void* ptr,
111 size_t size);
112typedef void* (*memalign_type)(struct _malloc_zone_t* zone,
113 size_t alignment,
114 size_t size);
115
116malloc_type g_old_malloc;
117calloc_type g_old_calloc;
118valloc_type g_old_valloc;
119free_type g_old_free;
120realloc_type g_old_realloc;
121memalign_type g_old_memalign;
122
123malloc_type g_old_malloc_purgeable;
124calloc_type g_old_calloc_purgeable;
125valloc_type g_old_valloc_purgeable;
126free_type g_old_free_purgeable;
127realloc_type g_old_realloc_purgeable;
128memalign_type g_old_memalign_purgeable;
129
130void* oom_killer_malloc(struct _malloc_zone_t* zone,
131 size_t size) {
132 void* result = g_old_malloc(zone, size);
133 if (!result && size)
134 TerminateBecauseOutOfMemory(size);
135 return result;
136}
137
138void* oom_killer_calloc(struct _malloc_zone_t* zone,
139 size_t num_items,
140 size_t size) {
141 void* result = g_old_calloc(zone, num_items, size);
142 if (!result && num_items && size)
143 TerminateBecauseOutOfMemory(num_items * size);
144 return result;
145}
146
147void* oom_killer_valloc(struct _malloc_zone_t* zone,
148 size_t size) {
149 void* result = g_old_valloc(zone, size);
150 if (!result && size)
151 TerminateBecauseOutOfMemory(size);
152 return result;
153}
154
155void oom_killer_free(struct _malloc_zone_t* zone,
156 void* ptr) {
157 g_old_free(zone, ptr);
158}
159
160void* oom_killer_realloc(struct _malloc_zone_t* zone,
161 void* ptr,
162 size_t size) {
163 void* result = g_old_realloc(zone, ptr, size);
164 if (!result && size)
165 TerminateBecauseOutOfMemory(size);
166 return result;
167}
168
169void* oom_killer_memalign(struct _malloc_zone_t* zone,
170 size_t alignment,
171 size_t size) {
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);
179 }
180 return result;
181}
182
183void* oom_killer_malloc_purgeable(struct _malloc_zone_t* zone,
184 size_t size) {
185 void* result = g_old_malloc_purgeable(zone, size);
186 if (!result && size)
187 TerminateBecauseOutOfMemory(size);
188 return result;
189}
190
191void* oom_killer_calloc_purgeable(struct _malloc_zone_t* zone,
192 size_t num_items,
193 size_t size) {
194 void* result = g_old_calloc_purgeable(zone, num_items, size);
195 if (!result && num_items && size)
196 TerminateBecauseOutOfMemory(num_items * size);
197 return result;
198}
199
200void* oom_killer_valloc_purgeable(struct _malloc_zone_t* zone,
201 size_t size) {
202 void* result = g_old_valloc_purgeable(zone, size);
203 if (!result && size)
204 TerminateBecauseOutOfMemory(size);
205 return result;
206}
207
208void oom_killer_free_purgeable(struct _malloc_zone_t* zone,
209 void* ptr) {
210 g_old_free_purgeable(zone, ptr);
211}
212
213void* oom_killer_realloc_purgeable(struct _malloc_zone_t* zone,
214 void* ptr,
215 size_t size) {
216 void* result = g_old_realloc_purgeable(zone, ptr, size);
217 if (!result && size)
218 TerminateBecauseOutOfMemory(size);
219 return result;
220}
221
222void* oom_killer_memalign_purgeable(struct _malloc_zone_t* zone,
223 size_t alignment,
224 size_t size) {
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);
232 }
233 return result;
234}
235
236#endif // !defined(ADDRESS_SANITIZER)
237
238// === C++ operator new ===
239
240void oom_killer_new() {
241 TerminateBecauseOutOfMemory(0);
242}
243
244#if !defined(ADDRESS_SANITIZER)
245
246// === Core Foundation CFAllocators ===
247
248bool CanGetContextForCFAllocator() {
249 return !base::mac::IsOSLaterThanYosemite_DontCallThis();
250}
251
252CFAllocatorContext* 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;
266 } else {
267 return NULL;
268 }
269}
270
271CFAllocatorAllocateCallBack g_old_cfallocator_system_default;
272CFAllocatorAllocateCallBack g_old_cfallocator_malloc;
273CFAllocatorAllocateCallBack g_old_cfallocator_malloc_zone;
274
275void* oom_killer_cfallocator_system_default(CFIndex alloc_size,
276 CFOptionFlags hint,
277 void* info) {
278 void* result = g_old_cfallocator_system_default(alloc_size, hint, info);
279 if (!result)
280 TerminateBecauseOutOfMemory(alloc_size);
281 return result;
282}
283
284void* oom_killer_cfallocator_malloc(CFIndex alloc_size,
285 CFOptionFlags hint,
286 void* info) {
287 void* result = g_old_cfallocator_malloc(alloc_size, hint, info);
288 if (!result)
289 TerminateBecauseOutOfMemory(alloc_size);
290 return result;
291}
292
293void* oom_killer_cfallocator_malloc_zone(CFIndex alloc_size,
294 CFOptionFlags hint,
295 void* info) {
296 void* result = g_old_cfallocator_malloc_zone(alloc_size, hint, info);
297 if (!result)
298 TerminateBecauseOutOfMemory(alloc_size);
299 return result;
300}
301
302#endif // !defined(ADDRESS_SANITIZER)
303
304// === Cocoa NSObject allocation ===
305
306typedef id (*allocWithZone_t)(id, SEL, NSZone*);
307allocWithZone_t g_old_allocWithZone;
308
309id oom_killer_allocWithZone(id self, SEL _cmd, NSZone* zone)
310{
311 id result = g_old_allocWithZone(self, _cmd, zone);
312 if (!result)
313 TerminateBecauseOutOfMemory(0);
314 return result;
315}
316
317} // namespace
318
319bool UncheckedMalloc(size_t size, void** result) {
320#if defined(ADDRESS_SANITIZER)
321 *result = malloc(size);
322#else
323 if (g_old_malloc) {
324 *result = g_old_malloc(malloc_default_zone(), size);
325 } else {
326 *result = malloc(size);
327 }
328#endif // defined(ADDRESS_SANITIZER)
329
330 return *result != NULL;
331}
332
333bool UncheckedCalloc(size_t num_items, size_t size, void** result) {
334#if defined(ADDRESS_SANITIZER)
335 *result = calloc(num_items, size);
336#else
337 if (g_old_calloc) {
338 *result = g_old_calloc(malloc_default_zone(), num_items, size);
339 } else {
340 *result = calloc(num_items, size);
341 }
342#endif // defined(ADDRESS_SANITIZER)
343
344 return *result != NULL;
345}
346
347void* UncheckedMalloc(size_t size) {
348 void* address;
349 return UncheckedMalloc(size, &address) ? address : NULL;
350}
351
352void* UncheckedCalloc(size_t num_items, size_t size) {
353 void* address;
354 return UncheckedCalloc(num_items, size, &address) ? address : NULL;
355}
356
357void EnableTerminationOnOutOfMemory() {
358 if (g_oom_killer_enabled)
359 return;
360
361 g_oom_killer_enabled = true;
362
363 // === C malloc/calloc/valloc/realloc/posix_memalign ===
364
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.
371
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.
375
376 CHECK(!g_old_malloc && !g_old_calloc && !g_old_valloc && !g_old_realloc &&
377 !g_old_memalign) << "Old allocators unexpectedly non-null";
378
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";
382
383 ChromeMallocZone* default_zone =
384 reinterpret_cast<ChromeMallocZone*>(malloc_default_zone());
385 ChromeMallocZone* purgeable_zone =
386 reinterpret_cast<ChromeMallocZone*>(malloc_default_purgeable_zone());
387
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);
395
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);
404 }
405
406 // Default zone
407
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 &&
414 g_old_realloc)
415 << "Failed to get system allocation functions.";
416
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;
422
423 if (default_zone->version >= 5) {
424 g_old_memalign = default_zone->memalign;
425 if (g_old_memalign)
426 default_zone->memalign = oom_killer_memalign;
427 }
428
429 // Purgeable zone (if it exists)
430
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.";
441
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;
447
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;
452 }
453 }
454
455 // Restore protection if it was active.
456
457 if (default_reprotection_start) {
458 kern_return_t result = mach_vm_protect(mach_task_self(),
459 default_reprotection_start,
460 default_reprotection_length,
461 false,
462 default_reprotection_value);
463 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
464 }
465
466 if (purgeable_reprotection_start) {
467 kern_return_t result = mach_vm_protect(mach_task_self(),
468 purgeable_reprotection_start,
469 purgeable_reprotection_length,
470 false,
471 purgeable_reprotection_value);
472 MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
473 }
474#endif
475
476 // === C malloc_zone_batch_malloc ===
477
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
492 // it.
493
494 // === C++ operator new ===
495
496 // Yes, operator new does call through to malloc, but this will catch failures
497 // that our imperfect handling of malloc cannot.
498
499 std::set_new_handler(oom_killer_new);
500
501#ifndef ADDRESS_SANITIZER
502 // === Core Foundation CFAllocators ===
503
504 // This will not catch allocation done by custom allocators, but will catch
505 // all allocation done by system-provided ones.
506
507 CHECK(!g_old_cfallocator_system_default && !g_old_cfallocator_malloc &&
508 !g_old_cfallocator_malloc_zone)
509 << "Old allocators unexpectedly non-null";
510
511 bool cf_allocator_internals_known = CanGetContextForCFAllocator();
512
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;
521
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;
528
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;
535 } else {
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";
539 }
540#endif
541
542 // === Cocoa NSObject allocation ===
543
544 // Note that both +[NSObject new] and +[NSObject alloc] call through to
545 // +[NSObject allocWithZone:].
546
547 CHECK(!g_old_allocWithZone)
548 << "Old allocator unexpectedly non-null";
549
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));
559}
560
561} // namespace base