AutoMemMap.h (2128B)
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; -*- */ 2 /* This Source Code Form is subject to the terms of the Mozilla Public 3 * License, v. 2.0. If a copy of the MPL was not distributed with this 4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 5 6 #ifndef loader_AutoMemMap_h 7 #define loader_AutoMemMap_h 8 9 #include "mozilla/FileUtils.h" 10 #include "mozilla/RangedPtr.h" 11 #include "mozilla/Result.h" 12 13 #include <prio.h> 14 15 class nsIFile; 16 17 namespace mozilla { 18 namespace ipc { 19 class FileDescriptor; 20 } 21 22 namespace loader { 23 24 class AutoMemMap { 25 typedef mozilla::ipc::FileDescriptor FileDescriptor; 26 27 public: 28 AutoMemMap() = default; 29 30 ~AutoMemMap(); 31 32 Result<Ok, nsresult> init(nsIFile* file, int flags = PR_RDONLY, int mode = 0, 33 PRFileMapProtect prot = PR_PROT_READONLY); 34 35 Result<Ok, nsresult> init(const FileDescriptor& file, 36 PRFileMapProtect prot = PR_PROT_READONLY, 37 size_t maybeSize = 0); 38 39 void reset(); 40 41 bool initialized() const { return addr; } 42 43 uint32_t size() const { return size_; } 44 45 template <typename T = void> 46 RangedPtr<T> get() { 47 MOZ_ASSERT(addr); 48 return {static_cast<T*>(addr), size_}; 49 } 50 51 template <typename T = void> 52 const RangedPtr<T> get() const { 53 MOZ_ASSERT(addr); 54 return {static_cast<T*>(addr), size_}; 55 } 56 57 size_t nonHeapSizeOfExcludingThis() { return size_; } 58 59 FileDescriptor cloneFileDescriptor() const; 60 FileDescriptor cloneHandle() const; 61 62 // Makes this mapping persistent. After calling this, the mapped memory 63 // will remained mapped, even after this instance is destroyed. 64 void setPersistent() { persistent_ = true; } 65 66 private: 67 Result<Ok, nsresult> initInternal(PRFileMapProtect prot, 68 size_t maybeSize = 0); 69 70 AutoFDClose fd; 71 PRFileMap* fileMap = nullptr; 72 73 uint32_t size_ = 0; 74 void* addr = nullptr; 75 76 bool persistent_ = 0; 77 78 AutoMemMap(const AutoMemMap&) = delete; 79 void operator=(const AutoMemMap&) = delete; 80 }; 81 82 } // namespace loader 83 } // namespace mozilla 84 85 #endif // loader_AutoMemMap_h