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 SizeOfState_h 8 #define SizeOfState_h 9 10 #include "mozilla/fallible.h" 11 #include "mozilla/MemoryReporting.h" 12 #include "mozilla/Unused.h" 13 #include "nsTHashtable.h" 14 #include "nsHashKeys.h" 15 16 // This file includes types that are useful during memory reporting, but which 17 // cannot be put into mfbt/MemoryReporting.h because they depend on things that 18 // are not in MFBT. 19 20 namespace mozilla { 21 22 // A table of seen pointers. Useful when measuring structures that contain 23 // nodes that may be pointed to from multiple places, e.g. via RefPtr (in C++ 24 // code) or Arc (in Rust code). 25 class SeenPtrs : public nsTHashtable<nsPtrHashKey<const void>> { 26 public: 27 // Returns true if we have seen this pointer before, false otherwise. Also 28 // remembers this pointer for later queries. HaveSeenPtr(const void * aPtr)29 bool HaveSeenPtr(const void* aPtr) { 30 uint32_t oldCount = Count(); 31 32 mozilla::Unused << PutEntry(aPtr, fallible); 33 34 // If the counts match, there are two possibilities. 35 // 36 // - Lookup succeeded: we've seen the pointer before, and didn't need to 37 // add a new entry. 38 // 39 // - PutEntry() tried to add the entry and failed due to lack of memory. In 40 // this case we can't tell if this pointer has been seen before (because 41 // the table is in an unreliable state and may have dropped previous 42 // insertions). When doing memory reporting it's better to err on the 43 // side of under-reporting rather than over-reporting, so we assume we've 44 // seen the pointer before. 45 // 46 return oldCount == Count(); 47 } 48 }; 49 50 // Memory reporting state. Some memory measuring functions 51 // (SizeOfIncludingThis(), etc.) just need a MallocSizeOf parameter, but some 52 // also need a record of pointers that have been seen and should not be 53 // re-measured. This class encapsulates both of those things. 54 class SizeOfState { 55 public: SizeOfState(MallocSizeOf aMallocSizeOf)56 explicit SizeOfState(MallocSizeOf aMallocSizeOf) 57 : mMallocSizeOf(aMallocSizeOf) {} 58 HaveSeenPtr(const void * aPtr)59 bool HaveSeenPtr(const void* aPtr) { return mSeenPtrs.HaveSeenPtr(aPtr); } 60 61 MallocSizeOf mMallocSizeOf; 62 SeenPtrs mSeenPtrs; 63 }; 64 65 } // namespace mozilla 66 67 #endif // SizeOfState_h 68