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 if(fd != -1 && ::close(fd) == -1)
77 throw MemoryMapping_Failed(
"Could not close file");
83 TemporaryFile file(
"/tmp/botan_");
85 if(file.get_fd() == -1)
86 throw MemoryMapping_Failed(
"Could not create file");
88 std::vector<byte> zeros(4096);
94 const size_t write_try = std::min(zeros.size(), remaining);
96 ssize_t wrote_got = ::write(file.get_fd(),
100 if(wrote_got == -1 && errno != EINTR)
101 throw MemoryMapping_Failed(
"Could not write to file");
103 remaining -= wrote_got;
110 void* ptr = ::mmap(0, n,
111 PROT_READ | PROT_WRITE,
116 throw MemoryMapping_Failed(
"Could not map file");
124 void MemoryMapping_Allocator::dealloc_block(
void* ptr,
size_t n)
129 const byte PATTERNS[] = { 0x00, 0xF5, 0x5A, 0xAF, 0x00 };
133 for(
size_t i = 0; i !=
sizeof(PATTERNS); ++i)
135 std::memset(ptr, PATTERNS[i], n);
137 if(::msync(static_cast<char*>(ptr), n, MS_SYNC))
138 throw MemoryMapping_Failed(
"Sync operation failed");
141 if(::munmap(static_cast<char*>(ptr), n))
142 throw MemoryMapping_Failed(
"Could not unmap file");
std::runtime_error Exception