This source file includes following definitions.
- OnNoMemory
- EnableLowFragmentationHeap
- EnableTerminationOnHeapCorruption
- EnableTerminationOnOutOfMemory
- GetModuleFromAddress
- UncheckedMalloc
#include "base/process/memory.h"
#include <psapi.h>
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
namespace base {
namespace {
void OnNoMemory() {
__debugbreak();
_exit(1);
}
typedef BOOL (WINAPI* HeapSetFn)(HANDLE, HEAP_INFORMATION_CLASS, PVOID, SIZE_T);
}
bool EnableLowFragmentationHeap() {
HMODULE kernel32 = GetModuleHandle(L"kernel32.dll");
HeapSetFn heap_set = reinterpret_cast<HeapSetFn>(GetProcAddress(
kernel32,
"HeapSetInformation"));
if (!heap_set)
return true;
unsigned number_heaps = GetProcessHeaps(0, NULL);
if (!number_heaps)
return false;
static const int MARGIN = 8;
scoped_ptr<HANDLE[]> heaps(new HANDLE[number_heaps + MARGIN]);
number_heaps = GetProcessHeaps(number_heaps + MARGIN, heaps.get());
if (!number_heaps)
return false;
for (unsigned i = 0; i < number_heaps; ++i) {
ULONG lfh_flag = 2;
heap_set(heaps[i],
HeapCompatibilityInformation,
&lfh_flag,
sizeof(lfh_flag));
}
return true;
}
void EnableTerminationOnHeapCorruption() {
HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
}
void EnableTerminationOnOutOfMemory() {
std::set_new_handler(&OnNoMemory);
}
HMODULE GetModuleFromAddress(void* address) {
HMODULE instance = NULL;
if (!::GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
static_cast<char*>(address),
&instance)) {
NOTREACHED();
}
return instance;
}
bool UncheckedMalloc(size_t size, void** result) {
*result = malloc(size);
return *result != NULL;
}
}