lock_mem.cpp

来自「含有多种公开密钥算法、多种块加密、多种数据流加密、多种HASH函数、多种Chec」· C++ 代码 · 共 110 行

CPP
110
字号
/************************************************** Memory Locking Allocator Source File           ** (C) 1999-2002 The Botan Project                **************************************************/#include <botan/lock_mem.h>#include <botan/util.h>#include <cstdlib>#include <sys/types.h>#include <sys/mman.h>namespace Botan {/************************************************** Constructor                                    **************************************************/MemoryLocking_Allocator::MemoryLocking_Allocator(u32bit blocks, u32bit size) :   ManagedAllocator(true, check_size(size))   {   size = check_size(size);   allocated.resize(blocks);   for(u32bit j = 0; j != allocated.size(); j++)      {      allocated[j].buf = std::malloc(size);      if(!allocated[j].buf)         throw Memory_Exhaustion();      std::memset(allocated[j].buf, 0, size);      allocated[j].length = size;      allocated[j].in_use = false;      mlock(allocated[j].buf, allocated[j].length);      }   }/************************************************** Destructor                                     **************************************************/MemoryLocking_Allocator::~MemoryLocking_Allocator()   {   for(u32bit j = 0; j != allocated.size(); j++)      {      munlock(allocated[j].buf, allocated[j].length);      std::free(allocated[j].buf);      }   }/************************************************** Check the buffer size                          **************************************************/u32bit MemoryLocking_Allocator::check_size(u32bit size) const   {   if(size >= 2048 && power_of_2(size))      return size;   else      return 8192;   }/************************************************** Allocation                                     **************************************************/void* MemoryLocking_Allocator::alloc_block(u32bit n) const   {   void* out = 0;   for(u32bit j = 0; j != allocated.size(); j++)      if(!allocated[j].in_use && allocated[j].length == n)         {         allocated[j].in_use = true;         out = allocated[j].buf;         break;         }   if(out)      return out;   out = std::malloc(n);   if(out)      {      mlock(out, n);      std::memset(out, 0, n);      }   return out;   }/************************************************** Deallocation                                   **************************************************/void MemoryLocking_Allocator::dealloc_block(void* ptr, u32bit n) const   {   if(ptr == 0) return;   for(u32bit j = 0; j != allocated.size(); j++)      if(allocated[j].buf == ptr)         {         if(!allocated[j].in_use || allocated[j].length != n)            throw Exception("MemoryLocking_Allocator: Internal failure");         allocated[j].in_use = false;         return;         }   munlock(ptr, n);   std::free(ptr);   }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?