mmap.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "memlog.h"
  2. #if defined(_unix_)
  3. #include <sys/mman.h>
  4. #elif defined(_win_)
  5. #include <util/system/winint.h>
  6. #else
  7. #error NO IMPLEMENTATION FOR THE PLATFORM
  8. #endif
  9. void TMemoryLog::TMMapArea::MMap(size_t amount) {
  10. Y_VERIFY(amount > 0);
  11. #if defined(_unix_)
  12. constexpr int mmapProt = PROT_READ | PROT_WRITE;
  13. #if defined(_linux_)
  14. constexpr int mmapFlags = MAP_PRIVATE | MAP_ANON | MAP_POPULATE;
  15. #else
  16. constexpr int mmapFlags = MAP_PRIVATE | MAP_ANON;
  17. #endif
  18. BufPtr = ::mmap(nullptr, amount, mmapProt, mmapFlags, -1, 0);
  19. if (BufPtr == MAP_FAILED) {
  20. throw std::bad_alloc();
  21. }
  22. #elif defined(_win_)
  23. Mapping = ::CreateFileMapping(
  24. (HANDLE)-1, nullptr, PAGE_READWRITE, 0, amount, nullptr);
  25. if (Mapping == NULL) {
  26. throw std::bad_alloc();
  27. }
  28. BufPtr = ::MapViewOfFile(Mapping, FILE_MAP_WRITE, 0, 0, amount);
  29. if (BufPtr == NULL) {
  30. throw std::bad_alloc();
  31. }
  32. #endif
  33. Size = amount;
  34. }
  35. void TMemoryLog::TMMapArea::MUnmap() {
  36. if (BufPtr == nullptr) {
  37. return;
  38. }
  39. #if defined(_unix_)
  40. int result = ::munmap(BufPtr, Size);
  41. Y_VERIFY(result == 0);
  42. #elif defined(_win_)
  43. BOOL result = ::UnmapViewOfFile(BufPtr);
  44. Y_VERIFY(result != 0);
  45. result = ::CloseHandle(Mapping);
  46. Y_VERIFY(result != 0);
  47. Mapping = 0;
  48. #endif
  49. BufPtr = nullptr;
  50. Size = 0;
  51. }