AutoMemMap.h (2145B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef mozilla_devtools_AutoMemMap_h 8 #define mozilla_devtools_AutoMemMap_h 9 10 #include <prio.h> 11 #include "nsIFile.h" 12 #include "mozilla/Assertions.h" 13 #include "ErrorList.h" 14 15 namespace mozilla { 16 namespace devtools { 17 18 // # AutoMemMap 19 // 20 // AutoMemMap is an RAII class to manage mapping a file to memory. It is a 21 // wrapper around managing opening and closing a file and calling PR_MemMap and 22 // PR_MemUnmap. 23 // 24 // Example usage: 25 // 26 // { 27 // AutoMemMap mm; 28 // if (NS_FAILED(mm.init("/path/to/desired/file"))) { 29 // // Handle the error however you see fit. 30 // return false; 31 // } 32 // 33 // doStuffWithMappedMemory(mm.address()); 34 // } 35 // // The memory is automatically unmapped when the AutoMemMap leaves scope. 36 class MOZ_RAII AutoMemMap { 37 // At the time of this writing, this class supports file imports up to 38 // UINT32_MAX bytes due to limitations in the underlying function PR_MemMap. 39 uint32_t fileSize; 40 PRFileDesc* fd; 41 PRFileMap* fileMap; 42 void* addr; 43 44 AutoMemMap(const AutoMemMap& aOther) = delete; 45 void operator=(const AutoMemMap& aOther) = delete; 46 47 public: 48 explicit AutoMemMap() 49 : fileSize(0), fd(nullptr), fileMap(nullptr), addr(nullptr) {}; 50 ~AutoMemMap(); 51 52 // Initialize this AutoMemMap. 53 nsresult init(nsIFile* file, int flags = PR_RDONLY, int mode = 0, 54 PRFileMapProtect prot = PR_PROT_READONLY); 55 56 // Get the size of the memory mapped file. 57 uint32_t size() const { 58 MOZ_ASSERT(fd, "Should only call size() if init() succeeded."); 59 return fileSize; 60 } 61 62 // Get the mapped memory. 63 void* address() { 64 MOZ_ASSERT(addr); 65 return addr; 66 } 67 const void* address() const { 68 MOZ_ASSERT(addr); 69 return addr; 70 } 71 }; 72 73 } // namespace devtools 74 } // namespace mozilla 75 76 #endif // mozilla_devtools_AutoMemMap_h