Path: blob/a-new-beginning/SharedDependencies/Sources/cryptopp/allocate.cpp
2 views
// allocate.cpp - written and placed in the public domain by Jeffrey Walton12// The functions in allocate.h and allocate.cpp were originally in misc.h3// and misc.cpp. They were extracted in September 2019 to sidestep a circular4// dependency with misc.h and secblock.h.56#include "pch.h"7#include "config.h"89#ifndef CRYPTOPP_IMPORTS1011#include "allocate.h"12#include "stdcpp.h"13#include "misc.h"14#include "trap.h"1516// for memalign17#if defined(CRYPTOPP_MEMALIGN_AVAILABLE) || defined(CRYPTOPP_MM_MALLOC_AVAILABLE) || defined(QNX)18# include <malloc.h>19#endif20// for posix_memalign21#if defined(CRYPTOPP_POSIX_MEMALIGN_AVAILABLE)22# include <stdlib.h>23#endif2425NAMESPACE_BEGIN(CryptoPP)2627void CallNewHandler()28{29std::new_handler newHandler = std::set_new_handler(NULLPTR);30if (newHandler)31std::set_new_handler(newHandler);3233if (newHandler)34newHandler();35else36throw std::bad_alloc();37}3839void * AlignedAllocate(size_t size)40{41byte *p;42#if defined(CRYPTOPP_MM_MALLOC_AVAILABLE)43while ((p = (byte *)_mm_malloc(size, 16)) == NULLPTR)44#elif defined(CRYPTOPP_MEMALIGN_AVAILABLE)45while ((p = (byte *)memalign(16, size)) == NULLPTR)46#elif defined(CRYPTOPP_MALLOC_ALIGNMENT_IS_16)47while ((p = (byte *)malloc(size)) == NULLPTR)48#elif defined(CRYPTOPP_POSIX_MEMALIGN_AVAILABLE)49while (posix_memalign(reinterpret_cast<void**>(&p), 16, size) != 0)50#else51while ((p = (byte *)malloc(size + 16)) == NULLPTR)52#endif53CallNewHandler();5455#ifdef CRYPTOPP_NO_ALIGNED_ALLOC56size_t adjustment = 16-((size_t)p%16);57CRYPTOPP_ASSERT(adjustment > 0);58p += adjustment;59p[-1] = (byte)adjustment;60#endif6162// If this assert fires then there are problems that need63// to be fixed. Please open a bug report.64CRYPTOPP_ASSERT(IsAlignedOn(p, 16));65return p;66}6768void AlignedDeallocate(void *p)69{70// Guard pointer due to crash on AIX when CRYPTOPP_NO_ALIGNED_ALLOC71// is in effect. The guard was previously in place in SecBlock,72// but it was removed at f4d68353ca7c as part of GH #875.73CRYPTOPP_ASSERT(p);7475if (p != NULLPTR)76{77#ifdef CRYPTOPP_MM_MALLOC_AVAILABLE78_mm_free(p);79#elif defined(CRYPTOPP_NO_ALIGNED_ALLOC)80p = (byte *)p - ((byte *)p)[-1];81free(p);82#else83free(p);84#endif85}86}8788void * UnalignedAllocate(size_t size)89{90void *p;91while ((p = malloc(size)) == NULLPTR)92CallNewHandler();93return p;94}9596void UnalignedDeallocate(void *p)97{98free(p);99}100101NAMESPACE_END102103#endif // CRYPTOPP_IMPORTS104105106