#include <openssl/base.h>
#if defined(__GLIBC__) && !defined(__UCLIBC__)
#define OPENSSL_GLIBC
#endif
#if defined(__linux__) && defined(OPENSSL_GLIBC) && !defined(OPENSSL_ARM) && \
!defined(OPENSSL_AARCH64) && !defined(OPENSSL_ASAN) && \
!defined(OPENSSL_MSAN) && !defined(OPENSSL_TSAN)
#include <errno.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <new>
static uint64_t current_malloc_count = 0;
static uint64_t malloc_number_to_fail = 0;
static bool failure_enabled = false, break_on_fail = false, in_call = false;
extern "C" {
extern void *__libc_malloc(size_t size);
extern void *__libc_calloc(size_t num_elems, size_t size);
extern void *__libc_realloc(void *ptr, size_t size);
}
static void exit_handler(void) {
if (failure_enabled && current_malloc_count > malloc_number_to_fail) {
_exit(88);
}
}
static void cpp_new_handler() {
return;
}
static bool should_fail_allocation() {
static bool init = false;
if (in_call) {
return false;
}
in_call = true;
if (!init) {
const char *env = getenv("MALLOC_NUMBER_TO_FAIL");
if (env != NULL && env[0] != 0) {
char *endptr;
malloc_number_to_fail = strtoull(env, &endptr, 10);
if (*endptr == 0) {
failure_enabled = true;
atexit(exit_handler);
std::set_new_handler(cpp_new_handler);
}
}
break_on_fail = (NULL != getenv("MALLOC_BREAK_ON_FAIL"));
init = true;
}
in_call = false;
if (!failure_enabled) {
return false;
}
bool should_fail = (current_malloc_count == malloc_number_to_fail);
current_malloc_count++;
if (should_fail && break_on_fail) {
raise(SIGTRAP);
}
return should_fail;
}
extern "C" {
void *malloc(size_t size) {
if (should_fail_allocation()) {
errno = ENOMEM;
return NULL;
}
return __libc_malloc(size);
}
void *calloc(size_t num_elems, size_t size) {
if (should_fail_allocation()) {
errno = ENOMEM;
return NULL;
}
return __libc_calloc(num_elems, size);
}
void *realloc(void *ptr, size_t size) {
if (should_fail_allocation()) {
errno = ENOMEM;
return NULL;
}
return __libc_realloc(ptr, size);
}
}
#endif