| 6 | #include "base/stl_util.h" |
| 7 |
| 8 | #include <windows.h> // Must be in front of other Windows header files. |
| 9 |
| 10 | #include <new.h> |
| 11 | #include <psapi.h> |
| 12 | #include <stddef.h> |
| 13 |
| 14 | #if defined(__clang__) |
| 15 | // This global constructor is trivial and non-racy (per being const). |
| 16 | #pragma clang diagnostic push |
| 17 | #pragma clang diagnostic ignored "-Wglobal-constructors" |
| 18 | #endif |
| 19 |
| 20 | // malloc_unchecked is required to implement UncheckedMalloc properly. |
| 21 | // It's provided by allocator_shim_win.cc but since that's not always present, |
| 22 | // we provide a default that falls back to regular malloc. |
| 23 | typedef void* (*MallocFn)(size_t); |
| 24 | extern "C" void* (*const malloc_unchecked)(size_t); |
| 25 | extern "C" void* (*const malloc_default)(size_t) = &malloc; |
| 26 |
| 27 | #if defined(__clang__) |
| 28 | #pragma clang diagnostic pop // -Wglobal-constructors |
| 29 | #endif |
| 30 |
| 31 | #if defined(_M_IX86) |
| 32 | #pragma comment(linker, "/alternatename:_malloc_unchecked=_malloc_default") |
| 33 | #elif defined(_M_X64) || defined(_M_ARM) || defined(_M_ARM64) |
| 34 | #pragma comment(linker, "/alternatename:malloc_unchecked=malloc_default") |
| 35 | #else |
| 36 | #error Unsupported platform |
| 37 | #endif |
| 38 |
| 39 | namespace base { |
| 40 |
| 41 | namespace { |
| 42 |
| 43 | // Return a non-0 value to retry the allocation. |
| 44 | int ReleaseReservationOrTerminate(size_t size) { |
| 45 | constexpr int kRetryAllocation = 1; |
| 46 | if (internal::ReleaseAddressSpaceReservation()) |
| 47 | return kRetryAllocation; |
| 48 | internal::OnNoMemoryInternal(size); |
| 49 | return 0; |
| 50 | } |
| 51 |
| 52 | // TODO(crbug.com/1062949): Remove the NOINLINE once the crash servers handle |
| 53 | // the |OnNoMemoryInternal()| signature.. |
| 54 | NOINLINE int OnNoMemory(size_t size) { |
| 55 | internal::OnNoMemoryInternal(size); |
| 56 | return 0; |
| 57 | } |
| 58 |
| 59 | } // namespace |
| 60 |
| 61 | void TerminateBecauseOutOfMemory(size_t size) { |
| 62 | OnNoMemory(size); |
| 63 | } |
| 64 |
| 65 | void EnableTerminationOnHeapCorruption() { |
| 66 | // Ignore the result code. Supported on XP SP3 and Vista. |
| 67 | HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0); |
| 68 | } |
| 69 |
| 70 | void EnableTerminationOnOutOfMemory() { |
| 71 | constexpr int kCallNewHandlerOnAllocationFailure = 1; |
| 72 | _set_new_handler(&ReleaseReservationOrTerminate); |
| 73 | _set_new_mode(kCallNewHandlerOnAllocationFailure); |
| 74 | } |
| 75 |
| 76 | // Implemented using a weak symbol. |
| 77 | bool UncheckedMalloc(size_t size, void** result) { |
| 78 | *result = malloc_unchecked(size); |
| 79 | return *result != NULL; |
| 80 | } |
| 81 |
| 82 | } // namespace base |
| 83 |