memory_win.cc 2.1 KB

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