diff options
Diffstat (limited to 'modules/alloc_mmap/mmap_mem.cpp')
-rw-r--r-- | modules/alloc_mmap/mmap_mem.cpp | 59 |
1 files changed, 40 insertions, 19 deletions
diff --git a/modules/alloc_mmap/mmap_mem.cpp b/modules/alloc_mmap/mmap_mem.cpp index a55a54869..5d5b140f2 100644 --- a/modules/alloc_mmap/mmap_mem.cpp +++ b/modules/alloc_mmap/mmap_mem.cpp @@ -46,31 +46,52 @@ class MemoryMapping_Failed : public Exception *************************************************/ void* MemoryMapping_Allocator::alloc_block(u32bit n) { - const std::string path = "/tmp/botan_XXXXXX"; - - char* filepath = new char[path.length() + 1]; - std::strcpy(filepath, path.c_str()); - - mode_t old_umask = umask(077); - int fd = mkstemp(filepath); - umask(old_umask); - - if(fd == -1) + class TemporaryFile + { + public: + int get_fd() const { return fd; } + const std::string path() const { return filepath; } + + TemporaryFile(const std::string& base) + { + const std::string path = base + "XXXXXX"; + + filepath = new char[path.length() + 1]; + std::strcpy(filepath, path.c_str()); + + mode_t old_umask = umask(077); + fd = mkstemp(filepath); + umask(old_umask); + } + + ~TemporaryFile() + { + delete[] filepath; + if(fd != -1 && close(fd) == -1) + throw MemoryMapping_Failed("Could not close file"); + } + private: + int fd; + char* filepath; + }; + + TemporaryFile file("/tmp/botan_"); + + if(file.get_fd() == -1) throw MemoryMapping_Failed("Could not create file"); - if(unlink(filepath)) - throw MemoryMapping_Failed("Could not unlink file " + - std::string(filepath)); - delete[] filepath; + if(unlink(file.path().c_str())) + throw MemoryMapping_Failed("Could not unlink file " + file.path()); - lseek(fd, n-1, SEEK_SET); - if(write(fd, "\0", 1) != 1) + lseek(file.get_fd(), n-1, SEEK_SET); + if(write(file.get_fd(), "\0", 1) != 1) throw MemoryMapping_Failed("Could not write to file"); - void* ptr = mmap(0, n, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + + void* ptr = mmap(0, n, PROT_READ | PROT_WRITE, MAP_SHARED, + file.get_fd(), 0); + if(ptr == (void*)MAP_FAILED) throw MemoryMapping_Failed("Could not map file"); - if(close(fd)) - throw MemoryMapping_Failed("Could not close file"); return ptr; } |