MemoryMappedFile.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "il2cpp-config.h"
  2. #if !RUNTIME_TINY
  3. #include "MemoryMappedFile.h"
  4. #include "Baselib.h"
  5. #include "Cpp/ReentrantLock.h"
  6. namespace il2cpp
  7. {
  8. namespace utils
  9. {
  10. static baselib::ReentrantLock s_Mutex;
  11. static std::map<void*, os::FileHandle*> s_MappedAddressToMappedFileObject;
  12. static std::map<void*, int64_t> s_MappedAddressToMappedLength;
  13. void* MemoryMappedFile::Map(os::FileHandle* file)
  14. {
  15. return Map(file, 0, 0);
  16. }
  17. bool MemoryMappedFile::Unmap(void* address)
  18. {
  19. return Unmap(address, 0);
  20. }
  21. void* MemoryMappedFile::Map(os::FileHandle* file, int64_t length, int64_t offset)
  22. {
  23. return Map(file, length, offset, os::MMAP_FILE_ACCESS_READ);
  24. }
  25. void* MemoryMappedFile::Map(os::FileHandle* file, int64_t length, int64_t offset, int32_t access)
  26. {
  27. os::FastAutoLock lock(&s_Mutex);
  28. int64_t unused = 0;
  29. os::MemoryMappedFileError error = os::NO_MEMORY_MAPPED_FILE_ERROR;
  30. os::FileHandle* mappedFileHandle = os::MemoryMappedFile::Create(file, NULL, 0, &unused, (os::MemoryMappedFileAccess)access, 0, &error);
  31. if (error != 0)
  32. return NULL;
  33. int64_t actualOffset = offset;
  34. void* address = os::MemoryMappedFile::View(mappedFileHandle, &length, offset, (os::MemoryMappedFileAccess)access, &actualOffset, &error);
  35. if (address != NULL)
  36. {
  37. address = (uint8_t*)address + (offset - actualOffset);
  38. if (os::MemoryMappedFile::OwnsDuplicatedFileHandle(mappedFileHandle))
  39. s_MappedAddressToMappedFileObject[address] = mappedFileHandle;
  40. s_MappedAddressToMappedLength[address] = length;
  41. }
  42. return address;
  43. }
  44. bool MemoryMappedFile::Unmap(void* address, int64_t length)
  45. {
  46. os::FastAutoLock lock(&s_Mutex);
  47. if (length == 0)
  48. {
  49. std::map<void*, int64_t>::iterator entry = s_MappedAddressToMappedLength.find(address);
  50. if (entry != s_MappedAddressToMappedLength.end())
  51. {
  52. length = entry->second;
  53. s_MappedAddressToMappedLength.erase(entry);
  54. }
  55. }
  56. bool success = os::MemoryMappedFile::UnmapView(address, length);
  57. if (!success)
  58. return false;
  59. std::map<void*, os::FileHandle*>::iterator entry = s_MappedAddressToMappedFileObject.find(address);
  60. if (entry != s_MappedAddressToMappedFileObject.end())
  61. {
  62. bool result = os::MemoryMappedFile::Close(entry->second);
  63. s_MappedAddressToMappedFileObject.erase(entry);
  64. return result;
  65. }
  66. return true;
  67. }
  68. }
  69. }
  70. #endif