• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/buildflags.h"
8 
9 #if PA_BUILDFLAG(USE_ALLOCATOR_SHIM)
10 #include "partition_alloc/shim/allocator_shim.h"
11 #endif  // PA_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 }
31 
32 }  // namespace
33 
EnableTerminationOnHeapCorruption()34 void EnableTerminationOnHeapCorruption() {
35   // Ignore the result code. Supported on XP SP3 and Vista.
36   HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
37 }
38 
EnableTerminationOnOutOfMemory()39 void EnableTerminationOnOutOfMemory() {
40   constexpr int kCallNewHandlerOnAllocationFailure = 1;
41   _set_new_handler(&ReleaseReservationOrTerminate);
42   _set_new_mode(kCallNewHandlerOnAllocationFailure);
43 }
44 
UncheckedMalloc(size_t size,void ** result)45 bool UncheckedMalloc(size_t size, void** result) {
46 #if PA_BUILDFLAG(USE_ALLOCATOR_SHIM)
47   *result = allocator_shim::UncheckedAlloc(size);
48 #else
49   // malloc_unchecked is required to implement UncheckedMalloc properly.
50   // It's provided by allocator_shim_win.cc but since that's not always present,
51   // In the case, use regular malloc instead.
52   *result = malloc(size);
53 #endif  // PA_BUILDFLAG(USE_ALLOCATOR_SHIM)
54   return *result != NULL;
55 }
56 
UncheckedFree(void * ptr)57 void UncheckedFree(void* ptr) {
58 #if PA_BUILDFLAG(USE_ALLOCATOR_SHIM)
59   allocator_shim::UncheckedFree(ptr);
60 #else
61   free(ptr);
62 #endif  // PA_BUILDFLAG(USE_ALLOCATOR_SHIM)
63 }
64 
65 }  // namespace base
66