#include <algorithm>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include "build/build_config.h"
#include "build/rust/std/immediate_crash.h"
#if BUILDFLAG(IS_ANDROID)
#include <malloc.h>
#endif
extern "C" {
#ifdef COMPONENT_BUILD
#define REMAP_ALLOC_ATTRIBUTES \
__attribute__((visibility("default"))) __attribute__((weak))
#else
#define REMAP_ALLOC_ATTRIBUTES __attribute__((weak))
#endif
void* REMAP_ALLOC_ATTRIBUTES __rust_alloc(size_t size, size_t align) {
constexpr size_t max_align = (1 << 21) / 2;
if (align > max_align) {
return nullptr;
}
if (align <= alignof(std::max_align_t)) {
return malloc(size);
} else {
#if defined(COMPILER_MSVC)
return _aligned_malloc(size, align);
#elif BUILDFLAG(IS_ANDROID)
return memalign(align, size);
#else
void* p;
auto ret = posix_memalign(&p, align, size);
return ret == 0 ? p : nullptr;
#endif
}
}
void REMAP_ALLOC_ATTRIBUTES __rust_dealloc(void* p, size_t size, size_t align) {
free(p);
}
void* REMAP_ALLOC_ATTRIBUTES __rust_realloc(void* p,
size_t old_size,
size_t align,
size_t new_size) {
if (align <= alignof(std::max_align_t)) {
return realloc(p, new_size);
} else {
void* out = __rust_alloc(align, new_size);
memcpy(out, p, std::min(old_size, new_size));
return out;
}
}
void* REMAP_ALLOC_ATTRIBUTES __rust_alloc_zeroed(size_t size, size_t align) {
if (align <= alignof(std::max_align_t)) {
return calloc(size, 1);
} else {
void* p = __rust_alloc(size, align);
memset(p, 0, size);
return p;
}
}
void REMAP_ALLOC_ATTRIBUTES __rust_alloc_error_handler(size_t size,
size_t align) {
IMMEDIATE_CRASH();
}
extern const unsigned char REMAP_ALLOC_ATTRIBUTES
__rust_alloc_error_handler_should_panic = 0;
}