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