• 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 <windows.h>  // Must be in front of other Windows header files.
8 
9 #include <new.h>
10 #include <psapi.h>
11 #include <stddef.h>
12 #include <stdlib.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.
ReleaseReservationOrTerminate(size_t size)44 int ReleaseReservationOrTerminate(size_t size) {
45   constexpr int kRetryAllocation = 1;
46   if (internal::ReleaseAddressSpaceReservation())
47     return kRetryAllocation;
48   TerminateBecauseOutOfMemory(size);
49   return 0;
50 }
51 
52 }  // namespace
53 
EnableTerminationOnHeapCorruption()54 void EnableTerminationOnHeapCorruption() {
55   // Ignore the result code. Supported on XP SP3 and Vista.
56   HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
57 }
58 
EnableTerminationOnOutOfMemory()59 void EnableTerminationOnOutOfMemory() {
60   constexpr int kCallNewHandlerOnAllocationFailure = 1;
61   _set_new_handler(&ReleaseReservationOrTerminate);
62   _set_new_mode(kCallNewHandlerOnAllocationFailure);
63 }
64 
65 // Implemented using a weak symbol.
UncheckedMalloc(size_t size,void ** result)66 bool UncheckedMalloc(size_t size, void** result) {
67   *result = malloc_unchecked(size);
68   return *result != NULL;
69 }
70 
UncheckedFree(void * ptr)71 void UncheckedFree(void* ptr) {
72   free(ptr);
73 }
74 
75 }  // namespace base
76