memguard.cc 885 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include "memguard.h"
  2. #include <sys/mman.h>
  3. MemGuard::MemGuard()
  4. {
  5. protect();
  6. }
  7. MemGuard::MemGuard(const MemGuard& m)
  8. {
  9. protect();
  10. // Explicit copy constructor: don't access m->guard
  11. }
  12. MemGuard& MemGuard::operator= (const MemGuard& m)
  13. {
  14. // Explicit operator=: don't access m->guard
  15. return *this;
  16. }
  17. MemGuard::~MemGuard() {
  18. // Memory may be reused by actual data, so reset the permissions
  19. unprotect();
  20. }
  21. void MemGuard::protect()
  22. {
  23. mprotect(pagePointer(), isAligned() ? 2*PAGE_SIZE : PAGE_SIZE, PROT_NONE);
  24. }
  25. void MemGuard::unprotect()
  26. {
  27. mprotect(pagePointer(), isAligned() ? 2*PAGE_SIZE : PAGE_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC);
  28. }
  29. bool MemGuard::isAligned()
  30. {
  31. return ((unsigned long)this->m_guard & (PAGE_SIZE-1)) == 0;
  32. }
  33. void* MemGuard::pagePointer()
  34. {
  35. return (void*)((unsigned long)(this->m_guard + PAGE_SIZE - 1) & ~(PAGE_SIZE-1));
  36. }