HeapSnapshot.h 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. #ifndef mozilla_devtools_HeapSnapshot__
  6. #define mozilla_devtools_HeapSnapshot__
  7. #include "js/HashTable.h"
  8. #include "mozilla/ErrorResult.h"
  9. #include "mozilla/devtools/DeserializedNode.h"
  10. #include "mozilla/dom/BindingDeclarations.h"
  11. #include "mozilla/dom/Nullable.h"
  12. #include "mozilla/HashFunctions.h"
  13. #include "mozilla/Maybe.h"
  14. #include "mozilla/RefCounted.h"
  15. #include "mozilla/RefPtr.h"
  16. #include "mozilla/TimeStamp.h"
  17. #include "mozilla/UniquePtr.h"
  18. #include "CoreDump.pb.h"
  19. #include "nsCOMPtr.h"
  20. #include "nsCRTGlue.h"
  21. #include "nsCycleCollectionParticipant.h"
  22. #include "nsISupports.h"
  23. #include "nsWrapperCache.h"
  24. #include "nsXPCOM.h"
  25. namespace mozilla {
  26. namespace devtools {
  27. class DominatorTree;
  28. struct NSFreePolicy {
  29. void operator()(void* ptr) {
  30. NS_Free(ptr);
  31. }
  32. };
  33. using UniqueTwoByteString = UniquePtr<char16_t[], NSFreePolicy>;
  34. using UniqueOneByteString = UniquePtr<char[], NSFreePolicy>;
  35. class HeapSnapshot final : public nsISupports
  36. , public nsWrapperCache
  37. {
  38. friend struct DeserializedNode;
  39. friend struct DeserializedEdge;
  40. friend struct DeserializedStackFrame;
  41. friend class JS::ubi::Concrete<JS::ubi::DeserializedNode>;
  42. explicit HeapSnapshot(JSContext* cx, nsISupports* aParent)
  43. : timestamp(Nothing())
  44. , rootId(0)
  45. , nodes(cx)
  46. , frames(cx)
  47. , mParent(aParent)
  48. {
  49. MOZ_ASSERT(aParent);
  50. };
  51. // Initialize this HeapSnapshot from the given buffer that contains a
  52. // serialized core dump. Do NOT take ownership of the buffer, only borrow it
  53. // for the duration of the call. Return false on failure.
  54. bool init(JSContext* cx, const uint8_t* buffer, uint32_t size);
  55. using NodeIdSet = js::HashSet<NodeId>;
  56. // Save the given `protobuf::Node` message in this `HeapSnapshot` as a
  57. // `DeserializedNode`.
  58. bool saveNode(const protobuf::Node& node, NodeIdSet& edgeReferents);
  59. // Save the given `protobuf::StackFrame` message in this `HeapSnapshot` as a
  60. // `DeserializedStackFrame`. The saved stack frame's id is returned via the
  61. // out parameter.
  62. bool saveStackFrame(const protobuf::StackFrame& frame,
  63. StackFrameId& outFrameId);
  64. public:
  65. // The maximum number of stack frames that we will serialize into a core
  66. // dump. This helps prevent over-recursion in the protobuf library when
  67. // deserializing stacks.
  68. static const size_t MAX_STACK_DEPTH = 60;
  69. private:
  70. // If present, a timestamp in the same units that `PR_Now` gives.
  71. Maybe<uint64_t> timestamp;
  72. // The id of the root node for this deserialized heap graph.
  73. NodeId rootId;
  74. // The set of nodes in this deserialized heap graph, keyed by id.
  75. using NodeSet = js::HashSet<DeserializedNode, DeserializedNode::HashPolicy>;
  76. NodeSet nodes;
  77. // The set of stack frames in this deserialized heap graph, keyed by id.
  78. using FrameSet = js::HashSet<DeserializedStackFrame,
  79. DeserializedStackFrame::HashPolicy>;
  80. FrameSet frames;
  81. Vector<UniqueTwoByteString> internedTwoByteStrings;
  82. Vector<UniqueOneByteString> internedOneByteStrings;
  83. using StringOrRef = Variant<const std::string*, uint64_t>;
  84. template<typename CharT,
  85. typename InternedStringSet>
  86. const CharT* getOrInternString(InternedStringSet& internedStrings,
  87. Maybe<StringOrRef>& maybeStrOrRef);
  88. protected:
  89. nsCOMPtr<nsISupports> mParent;
  90. virtual ~HeapSnapshot() { }
  91. public:
  92. // Create a `HeapSnapshot` from the given buffer that contains a serialized
  93. // core dump. Do NOT take ownership of the buffer, only borrow it for the
  94. // duration of the call.
  95. static already_AddRefed<HeapSnapshot> Create(JSContext* cx,
  96. dom::GlobalObject& global,
  97. const uint8_t* buffer,
  98. uint32_t size,
  99. ErrorResult& rv);
  100. // Creates the `$TEMP_DIR/XXXXXX-XXX.fxsnapshot` core dump file that heap
  101. // snapshots are serialized into.
  102. static already_AddRefed<nsIFile> CreateUniqueCoreDumpFile(ErrorResult& rv,
  103. const TimeStamp& now,
  104. nsAString& outFilePath);
  105. NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  106. NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(HeapSnapshot)
  107. MOZ_DECLARE_REFCOUNTED_TYPENAME(HeapSnapshot)
  108. nsISupports* GetParentObject() const { return mParent; }
  109. virtual JSObject* WrapObject(JSContext* aCx,
  110. JS::Handle<JSObject*> aGivenProto) override;
  111. const char16_t* borrowUniqueString(const char16_t* duplicateString,
  112. size_t length);
  113. // Get the root node of this heap snapshot's graph.
  114. JS::ubi::Node getRoot() {
  115. MOZ_ASSERT(nodes.initialized());
  116. auto p = nodes.lookup(rootId);
  117. MOZ_ASSERT(p);
  118. const DeserializedNode& node = *p;
  119. return JS::ubi::Node(const_cast<DeserializedNode*>(&node));
  120. }
  121. Maybe<JS::ubi::Node> getNodeById(JS::ubi::Node::Id nodeId) {
  122. auto p = nodes.lookup(nodeId);
  123. if (!p)
  124. return Nothing();
  125. return Some(JS::ubi::Node(const_cast<DeserializedNode*>(&*p)));
  126. }
  127. void TakeCensus(JSContext* cx, JS::HandleObject options,
  128. JS::MutableHandleValue rval, ErrorResult& rv);
  129. void DescribeNode(JSContext* cx, JS::HandleObject breakdown, uint64_t nodeId,
  130. JS::MutableHandleValue rval, ErrorResult& rv);
  131. already_AddRefed<DominatorTree> ComputeDominatorTree(ErrorResult& rv);
  132. void ComputeShortestPaths(JSContext*cx, uint64_t start,
  133. const dom::Sequence<uint64_t>& targets,
  134. uint64_t maxNumPaths,
  135. JS::MutableHandleObject results,
  136. ErrorResult& rv);
  137. dom::Nullable<uint64_t> GetCreationTime() {
  138. static const uint64_t maxTime = uint64_t(1) << 53;
  139. if (timestamp.isSome() && timestamp.ref() <= maxTime) {
  140. return dom::Nullable<uint64_t>(timestamp.ref());
  141. }
  142. return dom::Nullable<uint64_t>();
  143. }
  144. };
  145. // A `CoreDumpWriter` is given the data we wish to save in a core dump and
  146. // serializes it to disk, or memory, or a socket, etc.
  147. class CoreDumpWriter
  148. {
  149. public:
  150. virtual ~CoreDumpWriter() { };
  151. // Write the given bits of metadata we would like to associate with this core
  152. // dump.
  153. virtual bool writeMetadata(uint64_t timestamp) = 0;
  154. enum EdgePolicy : bool {
  155. INCLUDE_EDGES = true,
  156. EXCLUDE_EDGES = false
  157. };
  158. // Write the given `JS::ubi::Node` to the core dump. The given `EdgePolicy`
  159. // dictates whether its outgoing edges should also be written to the core
  160. // dump, or excluded.
  161. virtual bool writeNode(const JS::ubi::Node& node,
  162. EdgePolicy includeEdges) = 0;
  163. };
  164. // Serialize the heap graph as seen from `node` with the given `CoreDumpWriter`.
  165. // If `wantNames` is true, capture edge names. If `zones` is non-null, only
  166. // capture the sub-graph within the zone set, otherwise capture the whole heap
  167. // graph. Returns false on failure.
  168. bool
  169. WriteHeapGraph(JSContext* cx,
  170. const JS::ubi::Node& node,
  171. CoreDumpWriter& writer,
  172. bool wantNames,
  173. JS::CompartmentSet* compartments,
  174. JS::AutoCheckCannotGC& noGC);
  175. // Get the mozilla::MallocSizeOf for the current thread's JSRuntime.
  176. MallocSizeOf GetCurrentThreadDebuggerMallocSizeOf();
  177. } // namespace devtools
  178. } // namespace mozilla
  179. #endif // mozilla_devtools_HeapSnapshot__