xref: /aosp_15_r20/external/cronet/base/process/memory_win.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 The Chromium Authors
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 "partition_alloc/partition_alloc_buildflags.h"
8 
9 #if BUILDFLAG(USE_ALLOCATOR_SHIM)
10 #include "partition_alloc/shim/allocator_shim.h"
11 #endif  // BUILDFLAG(USE_ALLOCATOR_SHIM)
12 
13 #include <windows.h>  // Must be in front of other Windows header files.
14 
15 #include <new.h>
16 #include <psapi.h>
17 #include <stddef.h>
18 #include <stdlib.h>
19 
20 namespace base {
21 
22 namespace {
23 
24 // Return a non-0 value to retry the allocation.
ReleaseReservationOrTerminate(size_t size)25 int ReleaseReservationOrTerminate(size_t size) {
26   constexpr int kRetryAllocation = 1;
27   if (internal::ReleaseAddressSpaceReservation())
28     return kRetryAllocation;
29   TerminateBecauseOutOfMemory(size);
30   return 0;
31 }
32 
33 }  // namespace
34 
EnableTerminationOnHeapCorruption()35 void EnableTerminationOnHeapCorruption() {
36   // Ignore the result code. Supported on XP SP3 and Vista.
37   HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
38 }
39 
EnableTerminationOnOutOfMemory()40 void EnableTerminationOnOutOfMemory() {
41   constexpr int kCallNewHandlerOnAllocationFailure = 1;
42   _set_new_handler(&ReleaseReservationOrTerminate);
43   _set_new_mode(kCallNewHandlerOnAllocationFailure);
44 }
45 
UncheckedMalloc(size_t size,void ** result)46 bool UncheckedMalloc(size_t size, void** result) {
47 #if BUILDFLAG(USE_ALLOCATOR_SHIM)
48   *result = allocator_shim::UncheckedAlloc(size);
49 #else
50   // malloc_unchecked is required to implement UncheckedMalloc properly.
51   // It's provided by allocator_shim_win.cc but since that's not always present,
52   // In the case, use regular malloc instead.
53   *result = malloc(size);
54 #endif  // BUILDFLAG(USE_ALLOCATOR_SHIM)
55   return *result != NULL;
56 }
57 
UncheckedFree(void * ptr)58 void UncheckedFree(void* ptr) {
59 #if BUILDFLAG(USE_ALLOCATOR_SHIM)
60   allocator_shim::UncheckedFree(ptr);
61 #else
62   free(ptr);
63 #endif  // BUILDFLAG(USE_ALLOCATOR_SHIM)
64 }
65 
66 }  // namespace base
67