8 #include <botan/internal/mmap_mem.h> 12 #include <sys/types.h> 31 class BOTAN_DLL MemoryMapping_Failed :
public Exception 34 MemoryMapping_Failed(
const std::string& msg) :
35 Exception(
"MemoryMapping_Allocator: " + msg) {}
43 void* MemoryMapping_Allocator::alloc_block(
size_t n)
48 int get_fd()
const {
return fd; }
50 TemporaryFile(
const std::string& base)
52 const std::string mkstemp_template = base +
"XXXXXX";
54 std::vector<char> filepath(mkstemp_template.begin(),
55 mkstemp_template.end());
56 filepath.push_back(0);
58 mode_t old_umask = ::umask(077);
59 fd = ::mkstemp(&filepath[0]);
63 throw MemoryMapping_Failed(
"Temporary file allocation failed");
65 if(::unlink(&filepath[0]) != 0)
66 throw MemoryMapping_Failed(
"Could not unlink temporary file");
76 fd != -1 && ::close(fd);
82 TemporaryFile file(
"/tmp/botan_");
84 if(file.get_fd() == -1)
85 throw MemoryMapping_Failed(
"Could not create file");
87 std::vector<byte> zeros(4096);
93 const size_t write_try =
std::min(zeros.size(), remaining);
95 ssize_t wrote_got = ::write(file.get_fd(),
99 if(wrote_got == -1 && errno != EINTR)
100 throw MemoryMapping_Failed(
"Could not write to file");
102 remaining -= wrote_got;
109 void* ptr = ::mmap(0, n,
110 PROT_READ | PROT_WRITE,
115 throw MemoryMapping_Failed(
"Could not map file");
123 void MemoryMapping_Allocator::dealloc_block(
void* ptr,
size_t n)
128 const byte PATTERNS[] = { 0x00, 0xF5, 0x5A, 0xAF, 0x00 };
132 for(
size_t i = 0; i !=
sizeof(PATTERNS); ++i)
134 std::memset(ptr, PATTERNS[i], n);
136 if(::msync(static_cast<char*>(ptr), n, MS_SYNC))
137 throw MemoryMapping_Failed(
"Sync operation failed");
140 if(::munmap(static_cast<char*>(ptr), n))
141 throw MemoryMapping_Failed(
"Could not unmap file");
std::runtime_error Exception