Line data Source code
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 "mozilla/GuardObjects.h"
12 :
13 : namespace mozilla {
14 : namespace devtools {
15 :
16 : // # AutoMemMap
17 : //
18 : // AutoMemMap is an RAII class to manage mapping a file to memory. It is a
19 : // wrapper aorund managing opening and closing a file and calling PR_MemMap and
20 : // PR_MemUnmap.
21 : //
22 : // Example usage:
23 : //
24 : // {
25 : // AutoMemMap mm;
26 : // if (NS_FAILED(mm.init("/path/to/desired/file"))) {
27 : // // Handle the error however you see fit.
28 : // return false;
29 : // }
30 : //
31 : // doStuffWithMappedMemory(mm.address());
32 : // }
33 : // // The memory is automatically unmapped when the AutoMemMap leaves scope.
34 : class MOZ_RAII AutoMemMap
35 : {
36 : MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER;
37 :
38 : PRFileInfo64 fileInfo;
39 : PRFileDesc* fd;
40 : PRFileMap* fileMap;
41 : void* addr;
42 :
43 : AutoMemMap(const AutoMemMap& aOther) = delete;
44 : void operator=(const AutoMemMap& aOther) = delete;
45 :
46 : public:
47 0 : explicit AutoMemMap(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM)
48 0 : : fd(nullptr)
49 : , fileMap(nullptr)
50 0 : , addr(nullptr)
51 : {
52 0 : MOZ_GUARD_OBJECT_NOTIFIER_INIT;
53 0 : };
54 : ~AutoMemMap();
55 :
56 : // Initialize this AutoMemMap.
57 : nsresult init(const char* filePath, int flags = PR_RDONLY, int mode = 0,
58 : PRFileMapProtect prot = PR_PROT_READONLY);
59 :
60 : // Get the size of the memory mapped file.
61 0 : uint32_t size() const {
62 0 : MOZ_ASSERT(fileInfo.size <= UINT32_MAX,
63 : "Should only call size() if init() succeeded.");
64 0 : return uint32_t(fileInfo.size);
65 : }
66 :
67 : // Get the mapped memory.
68 0 : void* address() { MOZ_ASSERT(addr); return addr; }
69 : const void* address() const { MOZ_ASSERT(addr); return addr; }
70 : };
71 :
72 : } // namespace devtools
73 : } // namespace mozilla
74 :
75 : #endif // mozilla_devtools_AutoMemMap_h
|