memory_mac.mm 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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.
  4. #include "base/process/memory.h"
  5. #include <new>
  6. #include "base/allocator/allocator_interception_mac.h"
  7. #include "base/allocator/allocator_shim.h"
  8. #include "base/allocator/buildflags.h"
  9. #include "build/build_config.h"
  10. namespace base {
  11. namespace {
  12. void oom_killer_new() {
  13. TerminateBecauseOutOfMemory(0);
  14. }
  15. } // namespace
  16. void EnableTerminationOnHeapCorruption() {
  17. #if !ARCH_CPU_64_BITS
  18. DLOG(WARNING) << "EnableTerminationOnHeapCorruption only works on 64-bit";
  19. #endif
  20. }
  21. bool UncheckedMalloc(size_t size, void** result) {
  22. #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
  23. // Unlike use_allocator="none", the default malloc zone is replaced with
  24. // PartitionAlloc, so the allocator shim functions work best.
  25. *result = allocator::UncheckedAlloc(size);
  26. return *result != nullptr;
  27. #else // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
  28. return allocator::UncheckedMallocMac(size, result);
  29. #endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
  30. }
  31. // The standard version is defined in memory.cc in case of
  32. // USE_PARTITION_ALLOC_AS_MALLOC.
  33. #if !BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
  34. bool UncheckedCalloc(size_t num_items, size_t size, void** result) {
  35. return allocator::UncheckedCallocMac(num_items, size, result);
  36. }
  37. #endif // !BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
  38. void EnableTerminationOnOutOfMemory() {
  39. // Step 1: Enable OOM killer on C++ failures.
  40. std::set_new_handler(oom_killer_new);
  41. // Step 2: Enable OOM killer on C-malloc failures for the default zone (if we
  42. // have a shim).
  43. #if BUILDFLAG(USE_ALLOCATOR_SHIM)
  44. allocator::SetCallNewHandlerOnMallocFailure(true);
  45. #endif
  46. // Step 3: Enable OOM killer on all other malloc zones (or just "all" without
  47. // "other" if shim is disabled).
  48. allocator::InterceptAllocationsMac();
  49. }
  50. void UncheckedFree(void* ptr) {
  51. #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
  52. // Important: might be different from free(), because in some cases, free()
  53. // does not necessarily know about allocator::* functions.
  54. allocator::UncheckedFree(ptr);
  55. #else // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
  56. free(ptr);
  57. #endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
  58. }
  59. } // namespace base