#include "orconfig.h"
#include <stdlib.h>
#include <string.h>
#include "lib/testsupport/testsupport.h"
#define UTIL_MALLOC_PRIVATE
#include "lib/malloc/malloc.h"
#include "lib/cc/torint.h"
#include "lib/err/torerr.h"
#ifdef __clang_analyzer__
#undef MALLOC_ZERO_WORKS
#endif
void *
tor_malloc_(size_t size)
{
void *result;
raw_assert(size < SIZE_T_CEILING);
#ifndef MALLOC_ZERO_WORKS
if (size==0) {
size=1;
}
#endif
result = raw_malloc(size);
if (PREDICT_UNLIKELY(result == NULL)) {
raw_assert_unreached_msg("Out of memory on malloc(). Dying.");
}
return result;
}
void *
tor_malloc_zero_(size_t size)
{
void *result = tor_malloc_(size);
memset(result, 0, size);
return result;
}
#define SQRT_SIZE_MAX_P1 (((size_t)1) << (sizeof(size_t)*4))
STATIC int
size_mul_check(const size_t x, const size_t y)
{
return ((x|y) < SQRT_SIZE_MAX_P1 ||
y == 0 ||
x <= SIZE_MAX / y);
}
void *
tor_calloc_(size_t nmemb, size_t size)
{
raw_assert(size_mul_check(nmemb, size));
return tor_malloc_zero_((nmemb * size));
}
void *
tor_realloc_(void *ptr, size_t size)
{
void *result;
raw_assert(size < SIZE_T_CEILING);
#ifndef MALLOC_ZERO_WORKS
if (size==0) {
size=1;
}
#endif
result = raw_realloc(ptr, size);
if (PREDICT_UNLIKELY(result == NULL)) {
raw_assert_unreached_msg("Out of memory on realloc(). Dying.");
}
return result;
}
void *
tor_reallocarray_(void *ptr, size_t sz1, size_t sz2)
{
raw_assert(size_mul_check(sz1, sz2));
return tor_realloc(ptr, (sz1 * sz2));
}
char *
tor_strdup_(const char *s)
{
char *duplicate;
raw_assert(s);
duplicate = raw_strdup(s);
if (PREDICT_UNLIKELY(duplicate == NULL)) {
raw_assert_unreached_msg("Out of memory on strdup(). Dying.");
}
return duplicate;
}
char *
tor_strndup_(const char *s, size_t n)
{
char *duplicate;
raw_assert(s);
raw_assert(n < SIZE_T_CEILING);
duplicate = tor_malloc_((n+1));
strncpy(duplicate, s, n);
duplicate[n]='\0';
return duplicate;
}
void *
tor_memdup_(const void *mem, size_t len)
{
char *duplicate;
raw_assert(len < SIZE_T_CEILING);
raw_assert(mem);
duplicate = tor_malloc_(len);
memcpy(duplicate, mem, len);
return duplicate;
}
void *
tor_memdup_nulterm_(const void *mem, size_t len)
{
char *duplicate;
raw_assert(len < SIZE_T_CEILING+1);
raw_assert(mem);
duplicate = tor_malloc_(len+1);
memcpy(duplicate, mem, len);
duplicate[len] = '\0';
return duplicate;
}
void
tor_free_(void *mem)
{
tor_free(mem);
}