UbiNode.h 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  2. * vim: set ts=8 sts=4 et sw=4 tw=99:
  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. #ifndef js_UbiNode_h
  7. #define js_UbiNode_h
  8. #include "mozilla/Alignment.h"
  9. #include "mozilla/Assertions.h"
  10. #include "mozilla/Attributes.h"
  11. #include "mozilla/Maybe.h"
  12. #include "mozilla/MemoryReporting.h"
  13. #include "mozilla/Move.h"
  14. #include "mozilla/RangedPtr.h"
  15. #include "mozilla/TypeTraits.h"
  16. #include "mozilla/Variant.h"
  17. #include "jspubtd.h"
  18. #include "js/GCAPI.h"
  19. #include "js/HashTable.h"
  20. #include "js/RootingAPI.h"
  21. #include "js/TracingAPI.h"
  22. #include "js/TypeDecls.h"
  23. #include "js/UniquePtr.h"
  24. #include "js/Value.h"
  25. #include "js/Vector.h"
  26. // JS::ubi::Node
  27. //
  28. // JS::ubi::Node is a pointer-like type designed for internal use by heap
  29. // analysis tools. A ubi::Node can refer to:
  30. //
  31. // - a JS value, like a string, object, or symbol;
  32. // - an internal SpiderMonkey structure, like a shape or a scope chain object
  33. // - an instance of some embedding-provided type: in Firefox, an XPCOM
  34. // object, or an internal DOM node class instance
  35. //
  36. // A ubi::Node instance provides metadata about its referent, and can
  37. // enumerate its referent's outgoing edges, so you can implement heap analysis
  38. // algorithms that walk the graph - finding paths between objects, or
  39. // computing heap dominator trees, say - using ubi::Node, while remaining
  40. // ignorant of the details of the types you're operating on.
  41. //
  42. // Of course, when it comes to presenting the results in a developer-facing
  43. // tool, you'll need to stop being ignorant of those details, because you have
  44. // to discuss the ubi::Nodes' referents with the developer. Here, ubi::Node
  45. // can hand you dynamically checked, properly typed pointers to the original
  46. // objects via the as<T> method, or generate descriptions of the referent
  47. // itself.
  48. //
  49. // ubi::Node instances are lightweight (two-word) value types. Instances:
  50. // - compare equal if and only if they refer to the same object;
  51. // - have hash values that respect their equality relation; and
  52. // - have serializations that are only equal if the ubi::Nodes are equal.
  53. //
  54. // A ubi::Node is only valid for as long as its referent is alive; if its
  55. // referent goes away, the ubi::Node becomes a dangling pointer. A ubi::Node
  56. // that refers to a GC-managed object is not automatically a GC root; if the
  57. // GC frees or relocates its referent, the ubi::Node becomes invalid. A
  58. // ubi::Node that refers to a reference-counted object does not bump the
  59. // reference count.
  60. //
  61. // ubi::Node values require no supporting data structures, making them
  62. // feasible for use in memory-constrained devices --- ideally, the memory
  63. // requirements of the algorithm which uses them will be the limiting factor,
  64. // not the demands of ubi::Node itself.
  65. //
  66. // One can construct a ubi::Node value given a pointer to a type that ubi::Node
  67. // supports. In the other direction, one can convert a ubi::Node back to a
  68. // pointer; these downcasts are checked dynamically. In particular, one can
  69. // convert a 'JSContext*' to a ubi::Node, yielding a node with an outgoing edge
  70. // for every root registered with the runtime; starting from this, one can walk
  71. // the entire heap. (Of course, one could also start traversal at any other kind
  72. // of type to which one has a pointer.)
  73. //
  74. //
  75. // Extending ubi::Node To Handle Your Embedding's Types
  76. //
  77. // To add support for a new ubi::Node referent type R, you must define a
  78. // specialization of the ubi::Concrete template, ubi::Concrete<R>, which
  79. // inherits from ubi::Base. ubi::Node itself uses the specialization for
  80. // compile-time information (i.e. the checked conversions between R * and
  81. // ubi::Node), and the inheritance for run-time dispatching.
  82. //
  83. //
  84. // ubi::Node Exposes Implementation Details
  85. //
  86. // In many cases, a JavaScript developer's view of their data differs
  87. // substantially from its actual implementation. For example, while the
  88. // ECMAScript specification describes objects as maps from property names to
  89. // sets of attributes (like ECMAScript's [[Value]]), in practice many objects
  90. // have only a pointer to a shape, shared with other similar objects, and
  91. // indexed slots that contain the [[Value]] attributes. As another example, a
  92. // string produced by concatenating two other strings may sometimes be
  93. // represented by a "rope", a structure that points to the two original
  94. // strings.
  95. //
  96. // We intend to use ubi::Node to write tools that report memory usage, so it's
  97. // important that ubi::Node accurately portray how much memory nodes consume.
  98. // Thus, for example, when data that apparently belongs to multiple nodes is
  99. // in fact shared in a common structure, ubi::Node's graph uses a separate
  100. // node for that shared structure, and presents edges to it from the data's
  101. // apparent owners. For example, ubi::Node exposes SpiderMonkey objects'
  102. // shapes and base shapes, and exposes rope string and substring structure,
  103. // because these optimizations become visible when a tool reports how much
  104. // memory a structure consumes.
  105. //
  106. // However, fine granularity is not a goal. When a particular object is the
  107. // exclusive owner of a separate block of memory, ubi::Node may present the
  108. // object and its block as a single node, and add their sizes together when
  109. // reporting the node's size, as there is no meaningful loss of data in this
  110. // case. Thus, for example, a ubi::Node referring to a JavaScript object, when
  111. // asked for the object's size in bytes, includes the object's slot and
  112. // element arrays' sizes in the total. There is no separate ubi::Node value
  113. // representing the slot and element arrays, since they are owned exclusively
  114. // by the object.
  115. //
  116. //
  117. // Presenting Analysis Results To JavaScript Developers
  118. //
  119. // If an analysis provides its results in terms of ubi::Node values, a user
  120. // interface presenting those results will generally need to clean them up
  121. // before they can be understood by JavaScript developers. For example,
  122. // JavaScript developers should not need to understand shapes, only JavaScript
  123. // objects. Similarly, they should not need to understand the distinction
  124. // between DOM nodes and the JavaScript shadow objects that represent them.
  125. //
  126. //
  127. // Rooting Restrictions
  128. //
  129. // At present there is no way to root ubi::Node instances, so instances can't be
  130. // live across any operation that might GC. Analyses using ubi::Node must either
  131. // run to completion and convert their results to some other rootable type, or
  132. // save their intermediate state in some rooted structure if they must GC before
  133. // they complete. (For algorithms like path-finding and dominator tree
  134. // computation, we implement the algorithm avoiding any operation that could
  135. // cause a GC --- and use AutoCheckCannotGC to verify this.)
  136. //
  137. // If this restriction prevents us from implementing interesting tools, we may
  138. // teach the GC how to root ubi::Nodes, fix up hash tables that use them as
  139. // keys, etc.
  140. //
  141. //
  142. // Hostile Graph Structure
  143. //
  144. // Analyses consuming ubi::Node graphs must be robust when presented with graphs
  145. // that are deliberately constructed to exploit their weaknesses. When operating
  146. // on live graphs, web content has control over the object graph, and less
  147. // direct control over shape and string structure, and analyses should be
  148. // prepared to handle extreme cases gracefully. For example, if an analysis were
  149. // to use the C++ stack in a depth-first traversal, carefully constructed
  150. // content could cause the analysis to overflow the stack.
  151. //
  152. // When ubi::Nodes refer to nodes deserialized from a heap snapshot, analyses
  153. // must be even more careful: since snapshots often come from potentially
  154. // compromised e10s content processes, even properties normally guaranteed by
  155. // the platform (the proper linking of DOM nodes, for example) might be
  156. // corrupted. While it is the deserializer's responsibility to check the basic
  157. // structure of the snapshot file, the analyses should be prepared for ubi::Node
  158. // graphs constructed from snapshots to be even more bizarre.
  159. class JSAtom;
  160. namespace JS {
  161. namespace ubi {
  162. class Edge;
  163. class EdgeRange;
  164. class StackFrame;
  165. } // namespace ubi
  166. } // namespace JS
  167. namespace JS {
  168. namespace ubi {
  169. using mozilla::Forward;
  170. using mozilla::Maybe;
  171. using mozilla::Move;
  172. using mozilla::RangedPtr;
  173. using mozilla::Variant;
  174. template <typename T>
  175. using Vector = mozilla::Vector<T, 0, js::SystemAllocPolicy>;
  176. /*** ubi::StackFrame ******************************************************************************/
  177. // Concrete JS::ubi::StackFrame instances backed by a live SavedFrame object
  178. // store their strings as JSAtom*, while deserialized stack frames from offline
  179. // heap snapshots store their strings as const char16_t*. In order to provide
  180. // zero-cost accessors to these strings in a single interface that works with
  181. // both cases, we use this variant type.
  182. class AtomOrTwoByteChars : public Variant<JSAtom*, const char16_t*> {
  183. using Base = Variant<JSAtom*, const char16_t*>;
  184. public:
  185. template<typename T>
  186. MOZ_IMPLICIT AtomOrTwoByteChars(T&& rhs) : Base(Forward<T>(rhs)) { }
  187. template<typename T>
  188. AtomOrTwoByteChars& operator=(T&& rhs) {
  189. MOZ_ASSERT(this != &rhs, "self-move disallowed");
  190. this->~AtomOrTwoByteChars();
  191. new (this) AtomOrTwoByteChars(Forward<T>(rhs));
  192. return *this;
  193. }
  194. // Return the length of the given AtomOrTwoByteChars string.
  195. size_t length();
  196. // Copy the given AtomOrTwoByteChars string into the destination buffer,
  197. // inflating if necessary. Does NOT null terminate. Returns the number of
  198. // characters written to destination.
  199. size_t copyToBuffer(RangedPtr<char16_t> destination, size_t length);
  200. };
  201. // The base class implemented by each ConcreteStackFrame<T> type. Subclasses
  202. // must not add data members to this class.
  203. class BaseStackFrame {
  204. friend class StackFrame;
  205. BaseStackFrame(const StackFrame&) = delete;
  206. BaseStackFrame& operator=(const StackFrame&) = delete;
  207. protected:
  208. void* ptr;
  209. explicit BaseStackFrame(void* ptr) : ptr(ptr) { }
  210. public:
  211. // This is a value type that should not have a virtual destructor. Don't add
  212. // destructors in subclasses!
  213. // Get a unique identifier for this StackFrame. The identifier is not valid
  214. // across garbage collections.
  215. virtual uint64_t identifier() const { return uint64_t(uintptr_t(ptr)); }
  216. // Get this frame's parent frame.
  217. virtual StackFrame parent() const = 0;
  218. // Get this frame's line number.
  219. virtual uint32_t line() const = 0;
  220. // Get this frame's column number.
  221. virtual uint32_t column() const = 0;
  222. // Get this frame's source name. Never null.
  223. virtual AtomOrTwoByteChars source() const = 0;
  224. // Return this frame's function name if named, otherwise the inferred
  225. // display name. Can be null.
  226. virtual AtomOrTwoByteChars functionDisplayName() const = 0;
  227. // Returns true if this frame's function is system JavaScript running with
  228. // trusted principals, false otherwise.
  229. virtual bool isSystem() const = 0;
  230. // Return true if this frame's function is a self-hosted JavaScript builtin,
  231. // false otherwise.
  232. virtual bool isSelfHosted(JSContext* cx) const = 0;
  233. // Construct a SavedFrame stack for the stack starting with this frame and
  234. // containing all of its parents. The SavedFrame objects will be placed into
  235. // cx's current compartment.
  236. //
  237. // Note that the process of
  238. //
  239. // SavedFrame
  240. // |
  241. // V
  242. // JS::ubi::StackFrame
  243. // |
  244. // V
  245. // offline heap snapshot
  246. // |
  247. // V
  248. // JS::ubi::StackFrame
  249. // |
  250. // V
  251. // SavedFrame
  252. //
  253. // is lossy because we cannot serialize and deserialize the SavedFrame's
  254. // principals in the offline heap snapshot, so JS::ubi::StackFrame
  255. // simplifies the principals check into the boolean isSystem() state. This
  256. // is fine because we only expose JS::ubi::Stack to devtools and chrome
  257. // code, and not to the web platform.
  258. virtual MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx,
  259. MutableHandleObject outSavedFrameStack)
  260. const = 0;
  261. // Trace the concrete implementation of JS::ubi::StackFrame.
  262. virtual void trace(JSTracer* trc) = 0;
  263. };
  264. // A traits template with a specialization for each backing type that implements
  265. // the ubi::BaseStackFrame interface. Each specialization must be the a subclass
  266. // of ubi::BaseStackFrame.
  267. template<typename T> class ConcreteStackFrame;
  268. // A JS::ubi::StackFrame represents a frame in a recorded stack. It can be
  269. // backed either by a live SavedFrame object or by a structure deserialized from
  270. // an offline heap snapshot.
  271. //
  272. // It is a value type that may be memcpy'd hither and thither without worrying
  273. // about constructors or destructors, similar to POD types.
  274. //
  275. // Its lifetime is the same as the lifetime of the graph that is being analyzed
  276. // by the JS::ubi::Node that the JS::ubi::StackFrame came from. That is, if the
  277. // graph being analyzed is the live heap graph, the JS::ubi::StackFrame is only
  278. // valid within the scope of an AutoCheckCannotGC; if the graph being analyzed
  279. // is an offline heap snapshot, the JS::ubi::StackFrame is valid as long as the
  280. // offline heap snapshot is alive.
  281. class StackFrame {
  282. // Storage in which we allocate BaseStackFrame subclasses.
  283. mozilla::AlignedStorage2<BaseStackFrame> storage;
  284. BaseStackFrame* base() { return storage.addr(); }
  285. const BaseStackFrame* base() const { return storage.addr(); }
  286. template<typename T>
  287. void construct(T* ptr) {
  288. static_assert(mozilla::IsBaseOf<BaseStackFrame, ConcreteStackFrame<T>>::value,
  289. "ConcreteStackFrame<T> must inherit from BaseStackFrame");
  290. static_assert(sizeof(ConcreteStackFrame<T>) == sizeof(*base()),
  291. "ubi::ConcreteStackFrame<T> specializations must be the same size as "
  292. "ubi::BaseStackFrame");
  293. ConcreteStackFrame<T>::construct(base(), ptr);
  294. }
  295. struct ConstructFunctor;
  296. public:
  297. StackFrame() { construct<void>(nullptr); }
  298. template<typename T>
  299. MOZ_IMPLICIT StackFrame(T* ptr) {
  300. construct(ptr);
  301. }
  302. template<typename T>
  303. StackFrame& operator=(T* ptr) {
  304. construct(ptr);
  305. return *this;
  306. }
  307. // Constructors accepting SpiderMonkey's generic-pointer-ish types.
  308. template<typename T>
  309. explicit StackFrame(const JS::Handle<T*>& handle) {
  310. construct(handle.get());
  311. }
  312. template<typename T>
  313. StackFrame& operator=(const JS::Handle<T*>& handle) {
  314. construct(handle.get());
  315. return *this;
  316. }
  317. template<typename T>
  318. explicit StackFrame(const JS::Rooted<T*>& root) {
  319. construct(root.get());
  320. }
  321. template<typename T>
  322. StackFrame& operator=(const JS::Rooted<T*>& root) {
  323. construct(root.get());
  324. return *this;
  325. }
  326. // Because StackFrame is just a vtable pointer and an instance pointer, we
  327. // can memcpy everything around instead of making concrete classes define
  328. // virtual constructors. See the comment above Node's copy constructor for
  329. // more details; that comment applies here as well.
  330. StackFrame(const StackFrame& rhs) {
  331. memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u));
  332. }
  333. StackFrame& operator=(const StackFrame& rhs) {
  334. memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u));
  335. return *this;
  336. }
  337. bool operator==(const StackFrame& rhs) const { return base()->ptr == rhs.base()->ptr; }
  338. bool operator!=(const StackFrame& rhs) const { return !(*this == rhs); }
  339. explicit operator bool() const {
  340. return base()->ptr != nullptr;
  341. }
  342. // Copy this StackFrame's source name into the given |destination|
  343. // buffer. Copy no more than |length| characters. The result is *not* null
  344. // terminated. Returns how many characters were written into the buffer.
  345. size_t source(RangedPtr<char16_t> destination, size_t length) const;
  346. // Copy this StackFrame's function display name into the given |destination|
  347. // buffer. Copy no more than |length| characters. The result is *not* null
  348. // terminated. Returns how many characters were written into the buffer.
  349. size_t functionDisplayName(RangedPtr<char16_t> destination, size_t length) const;
  350. // Get the size of the respective strings. 0 is returned for null strings.
  351. size_t sourceLength();
  352. size_t functionDisplayNameLength();
  353. // Methods that forward to virtual calls through BaseStackFrame.
  354. void trace(JSTracer* trc) { base()->trace(trc); }
  355. uint64_t identifier() const {
  356. auto id = base()->identifier();
  357. MOZ_ASSERT(JS::Value::isNumberRepresentable(id));
  358. return id;
  359. }
  360. uint32_t line() const { return base()->line(); }
  361. uint32_t column() const { return base()->column(); }
  362. AtomOrTwoByteChars source() const { return base()->source(); }
  363. AtomOrTwoByteChars functionDisplayName() const { return base()->functionDisplayName(); }
  364. StackFrame parent() const { return base()->parent(); }
  365. bool isSystem() const { return base()->isSystem(); }
  366. bool isSelfHosted(JSContext* cx) const { return base()->isSelfHosted(cx); }
  367. MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx,
  368. MutableHandleObject outSavedFrameStack) const {
  369. return base()->constructSavedFrameStack(cx, outSavedFrameStack);
  370. }
  371. struct HashPolicy {
  372. using Lookup = JS::ubi::StackFrame;
  373. static js::HashNumber hash(const Lookup& lookup) {
  374. return lookup.identifier();
  375. }
  376. static bool match(const StackFrame& key, const Lookup& lookup) {
  377. return key == lookup;
  378. }
  379. static void rekey(StackFrame& k, const StackFrame& newKey) {
  380. k = newKey;
  381. }
  382. };
  383. };
  384. // The ubi::StackFrame null pointer. Any attempt to operate on a null
  385. // ubi::StackFrame crashes.
  386. template<>
  387. class ConcreteStackFrame<void> : public BaseStackFrame {
  388. explicit ConcreteStackFrame(void* ptr) : BaseStackFrame(ptr) { }
  389. public:
  390. static void construct(void* storage, void*) { new (storage) ConcreteStackFrame(nullptr); }
  391. uint64_t identifier() const override { return 0; }
  392. void trace(JSTracer* trc) override { }
  393. MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx, MutableHandleObject out)
  394. const override
  395. {
  396. out.set(nullptr);
  397. return true;
  398. }
  399. uint32_t line() const override { MOZ_CRASH("null JS::ubi::StackFrame"); }
  400. uint32_t column() const override { MOZ_CRASH("null JS::ubi::StackFrame"); }
  401. AtomOrTwoByteChars source() const override { MOZ_CRASH("null JS::ubi::StackFrame"); }
  402. AtomOrTwoByteChars functionDisplayName() const override { MOZ_CRASH("null JS::ubi::StackFrame"); }
  403. StackFrame parent() const override { MOZ_CRASH("null JS::ubi::StackFrame"); }
  404. bool isSystem() const override { MOZ_CRASH("null JS::ubi::StackFrame"); }
  405. bool isSelfHosted(JSContext* cx) const override { MOZ_CRASH("null JS::ubi::StackFrame"); }
  406. };
  407. MOZ_MUST_USE bool ConstructSavedFrameStackSlow(JSContext* cx, JS::ubi::StackFrame& frame,
  408. MutableHandleObject outSavedFrameStack);
  409. /*** ubi::Node ************************************************************************************/
  410. // A concrete node specialization can claim its referent is a member of a
  411. // particular "coarse type" which is less specific than the actual
  412. // implementation type but generally more palatable for web developers. For
  413. // example, JitCode can be considered to have a coarse type of "Script". This is
  414. // used by some analyses for putting nodes into different buckets. The default,
  415. // if a concrete specialization does not provide its own mapping to a CoarseType
  416. // variant, is "Other".
  417. //
  418. // NB: the values associated with a particular enum variant must not change or
  419. // be reused for new variants. Doing so will cause inspecting ubi::Nodes backed
  420. // by an offline heap snapshot from an older SpiderMonkey/Firefox version to
  421. // break. Consider this enum append only.
  422. enum class CoarseType: uint32_t {
  423. Other = 0,
  424. Object = 1,
  425. Script = 2,
  426. String = 3,
  427. FIRST = Other,
  428. LAST = String
  429. };
  430. inline uint32_t
  431. CoarseTypeToUint32(CoarseType type)
  432. {
  433. return static_cast<uint32_t>(type);
  434. }
  435. inline bool
  436. Uint32IsValidCoarseType(uint32_t n)
  437. {
  438. auto first = static_cast<uint32_t>(CoarseType::FIRST);
  439. auto last = static_cast<uint32_t>(CoarseType::LAST);
  440. MOZ_ASSERT(first < last);
  441. return first <= n && n <= last;
  442. }
  443. inline CoarseType
  444. Uint32ToCoarseType(uint32_t n)
  445. {
  446. MOZ_ASSERT(Uint32IsValidCoarseType(n));
  447. return static_cast<CoarseType>(n);
  448. }
  449. // The base class implemented by each ubi::Node referent type. Subclasses must
  450. // not add data members to this class.
  451. class Base {
  452. friend class Node;
  453. // For performance's sake, we'd prefer to avoid a virtual destructor; and
  454. // an empty constructor seems consistent with the 'lightweight value type'
  455. // visible behavior we're trying to achieve. But if the destructor isn't
  456. // virtual, and a subclass overrides it, the subclass's destructor will be
  457. // ignored. Is there a way to make the compiler catch that error?
  458. protected:
  459. // Space for the actual pointer. Concrete subclasses should define a
  460. // properly typed 'get' member function to access this.
  461. void* ptr;
  462. explicit Base(void* ptr) : ptr(ptr) { }
  463. public:
  464. bool operator==(const Base& rhs) const {
  465. // Some compilers will indeed place objects of different types at
  466. // the same address, so technically, we should include the vtable
  467. // in this comparison. But it seems unlikely to cause problems in
  468. // practice.
  469. return ptr == rhs.ptr;
  470. }
  471. bool operator!=(const Base& rhs) const { return !(*this == rhs); }
  472. // An identifier for this node, guaranteed to be stable and unique for as
  473. // long as this ubi::Node's referent is alive and at the same address.
  474. //
  475. // This is probably suitable for use in serializations, as it is an integral
  476. // type. It may also help save memory when constructing HashSets of
  477. // ubi::Nodes: since a uint64_t will always be smaller-or-equal-to the size
  478. // of a ubi::Node, a HashSet<ubi::Node::Id> may use less space per element
  479. // than a HashSet<ubi::Node>.
  480. //
  481. // (Note that 'unique' only means 'up to equality on ubi::Node'; see the
  482. // caveats about multiple objects allocated at the same address for
  483. // 'ubi::Node::operator=='.)
  484. using Id = uint64_t;
  485. virtual Id identifier() const { return Id(uintptr_t(ptr)); }
  486. // Returns true if this node is pointing to something on the live heap, as
  487. // opposed to something from a deserialized core dump. Returns false,
  488. // otherwise.
  489. virtual bool isLive() const { return true; };
  490. // Return the coarse-grained type-of-thing that this node represents.
  491. virtual CoarseType coarseType() const { return CoarseType::Other; }
  492. // Return a human-readable name for the referent's type. The result should
  493. // be statically allocated. (You can use u"strings" for this.)
  494. //
  495. // This must always return Concrete<T>::concreteTypeName; we use that
  496. // pointer as a tag for this particular referent type.
  497. virtual const char16_t* typeName() const = 0;
  498. // Return the size of this node, in bytes. Include any structures that this
  499. // node owns exclusively that are not exposed as their own ubi::Nodes.
  500. // |mallocSizeOf| should be a malloc block sizing function; see
  501. // |mfbt/MemoryReporting.h|.
  502. //
  503. // Because we can use |JS::ubi::Node|s backed by a snapshot that was taken
  504. // on a 64-bit platform when we are currently on a 32-bit platform, we
  505. // cannot rely on |size_t| for node sizes. Instead, |Size| is uint64_t on
  506. // all platforms.
  507. using Size = uint64_t;
  508. virtual Size size(mozilla::MallocSizeOf mallocSizeof) const { return 1; }
  509. // Return an EdgeRange that initially contains all the referent's outgoing
  510. // edges. The caller takes ownership of the EdgeRange.
  511. //
  512. // If wantNames is true, compute names for edges. Doing so can be expensive
  513. // in time and memory.
  514. virtual js::UniquePtr<EdgeRange> edges(JSContext* cx, bool wantNames) const = 0;
  515. // Return the Zone to which this node's referent belongs, or nullptr if the
  516. // referent is not of a type allocated in SpiderMonkey Zones.
  517. virtual JS::Zone* zone() const { return nullptr; }
  518. // Return the compartment for this node. Some ubi::Node referents are not
  519. // associated with JSCompartments, such as JSStrings (which are associated
  520. // with Zones). When the referent is not associated with a compartment,
  521. // nullptr is returned.
  522. virtual JSCompartment* compartment() const { return nullptr; }
  523. // Return whether this node's referent's allocation stack was captured.
  524. virtual bool hasAllocationStack() const { return false; }
  525. // Get the stack recorded at the time this node's referent was
  526. // allocated. This must only be called when hasAllocationStack() is true.
  527. virtual StackFrame allocationStack() const {
  528. MOZ_CRASH("Concrete classes that have an allocation stack must override both "
  529. "hasAllocationStack and allocationStack.");
  530. }
  531. // Methods for JSObject Referents
  532. //
  533. // These methods are only semantically valid if the referent is either a
  534. // JSObject in the live heap, or represents a previously existing JSObject
  535. // from some deserialized heap snapshot.
  536. // Return the object's [[Class]]'s name.
  537. virtual const char* jsObjectClassName() const { return nullptr; }
  538. // If this object was constructed with `new` and we have the data available,
  539. // place the contructor function's display name in the out parameter.
  540. // Otherwise, place nullptr in the out parameter. Caller maintains ownership
  541. // of the out parameter. True is returned on success, false is returned on
  542. // OOM.
  543. virtual MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName)
  544. const
  545. {
  546. outName.reset(nullptr);
  547. return true;
  548. }
  549. // Methods for CoarseType::Script referents
  550. // Return the script's source's filename if available. If unavailable,
  551. // return nullptr.
  552. virtual const char* scriptFilename() const { return nullptr; }
  553. private:
  554. Base(const Base& rhs) = delete;
  555. Base& operator=(const Base& rhs) = delete;
  556. };
  557. // A traits template with a specialization for each referent type that
  558. // ubi::Node supports. The specialization must be the concrete subclass of Base
  559. // that represents a pointer to the referent type. It must include these
  560. // members:
  561. //
  562. // // The specific char16_t array returned by Concrete<T>::typeName().
  563. // static const char16_t concreteTypeName[];
  564. //
  565. // // Construct an instance of this concrete class in |storage| referring
  566. // // to |referent|. Implementations typically use a placement 'new'.
  567. // //
  568. // // In some cases, |referent| will contain dynamic type information that
  569. // // identifies it a some more specific subclass of |Referent|. For
  570. // // example, when |Referent| is |JSObject|, then |referent->getClass()|
  571. // // could tell us that it's actually a JSFunction. Similarly, if
  572. // // |Referent| is |nsISupports|, we would like a ubi::Node that knows its
  573. // // final implementation type.
  574. // //
  575. // // So we delegate the actual construction to this specialization, which
  576. // // knows Referent's details.
  577. // static void construct(void* storage, Referent* referent);
  578. template<typename Referent>
  579. class Concrete;
  580. // A container for a Base instance; all members simply forward to the contained
  581. // instance. This container allows us to pass ubi::Node instances by value.
  582. class Node {
  583. // Storage in which we allocate Base subclasses.
  584. mozilla::AlignedStorage2<Base> storage;
  585. Base* base() { return storage.addr(); }
  586. const Base* base() const { return storage.addr(); }
  587. template<typename T>
  588. void construct(T* ptr) {
  589. static_assert(sizeof(Concrete<T>) == sizeof(*base()),
  590. "ubi::Base specializations must be the same size as ubi::Base");
  591. static_assert(mozilla::IsBaseOf<Base, Concrete<T>>::value,
  592. "ubi::Concrete<T> must inherit from ubi::Base");
  593. Concrete<T>::construct(base(), ptr);
  594. }
  595. struct ConstructFunctor;
  596. public:
  597. Node() { construct<void>(nullptr); }
  598. template<typename T>
  599. MOZ_IMPLICIT Node(T* ptr) {
  600. construct(ptr);
  601. }
  602. template<typename T>
  603. Node& operator=(T* ptr) {
  604. construct(ptr);
  605. return *this;
  606. }
  607. // We can construct and assign from rooted forms of pointers.
  608. template<typename T>
  609. MOZ_IMPLICIT Node(const Rooted<T*>& root) {
  610. construct(root.get());
  611. }
  612. template<typename T>
  613. Node& operator=(const Rooted<T*>& root) {
  614. construct(root.get());
  615. return *this;
  616. }
  617. // Constructors accepting SpiderMonkey's other generic-pointer-ish types.
  618. // Note that we *do* want an implicit constructor here: JS::Value and
  619. // JS::ubi::Node are both essentially tagged references to other sorts of
  620. // objects, so letting conversions happen automatically is appropriate.
  621. MOZ_IMPLICIT Node(JS::HandleValue value);
  622. explicit Node(const JS::GCCellPtr& thing);
  623. // copy construction and copy assignment just use memcpy, since we know
  624. // instances contain nothing but a vtable pointer and a data pointer.
  625. //
  626. // To be completely correct, concrete classes could provide a virtual
  627. // 'construct' member function, which we could invoke on rhs to construct an
  628. // instance in our storage. But this is good enough; there's no need to jump
  629. // through vtables for copying and assignment that are just going to move
  630. // two words around. The compiler knows how to optimize memcpy.
  631. Node(const Node& rhs) {
  632. memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u));
  633. }
  634. Node& operator=(const Node& rhs) {
  635. memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u));
  636. return *this;
  637. }
  638. bool operator==(const Node& rhs) const { return *base() == *rhs.base(); }
  639. bool operator!=(const Node& rhs) const { return *base() != *rhs.base(); }
  640. explicit operator bool() const {
  641. return base()->ptr != nullptr;
  642. }
  643. bool isLive() const { return base()->isLive(); }
  644. // Get the canonical type name for the given type T.
  645. template<typename T>
  646. static const char16_t* canonicalTypeName() { return Concrete<T>::concreteTypeName; }
  647. template<typename T>
  648. bool is() const {
  649. return base()->typeName() == canonicalTypeName<T>();
  650. }
  651. template<typename T>
  652. T* as() const {
  653. MOZ_ASSERT(isLive());
  654. MOZ_ASSERT(is<T>());
  655. return static_cast<T*>(base()->ptr);
  656. }
  657. template<typename T>
  658. T* asOrNull() const {
  659. MOZ_ASSERT(isLive());
  660. return is<T>() ? static_cast<T*>(base()->ptr) : nullptr;
  661. }
  662. // If this node refers to something that can be represented as a JavaScript
  663. // value that is safe to expose to JavaScript code, return that value.
  664. // Otherwise return UndefinedValue(). JSStrings, JS::Symbols, and some (but
  665. // not all!) JSObjects can be exposed.
  666. JS::Value exposeToJS() const;
  667. CoarseType coarseType() const { return base()->coarseType(); }
  668. const char16_t* typeName() const { return base()->typeName(); }
  669. JS::Zone* zone() const { return base()->zone(); }
  670. JSCompartment* compartment() const { return base()->compartment(); }
  671. const char* jsObjectClassName() const { return base()->jsObjectClassName(); }
  672. MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName) const {
  673. return base()->jsObjectConstructorName(cx, outName);
  674. }
  675. const char* scriptFilename() const { return base()->scriptFilename(); }
  676. using Size = Base::Size;
  677. Size size(mozilla::MallocSizeOf mallocSizeof) const {
  678. auto size = base()->size(mallocSizeof);
  679. MOZ_ASSERT(size > 0,
  680. "C++ does not have zero-sized types! Choose 1 if you just need a "
  681. "conservative default.");
  682. return size;
  683. }
  684. js::UniquePtr<EdgeRange> edges(JSContext* cx, bool wantNames = true) const {
  685. return base()->edges(cx, wantNames);
  686. }
  687. bool hasAllocationStack() const { return base()->hasAllocationStack(); }
  688. StackFrame allocationStack() const {
  689. return base()->allocationStack();
  690. }
  691. using Id = Base::Id;
  692. Id identifier() const {
  693. auto id = base()->identifier();
  694. MOZ_ASSERT(JS::Value::isNumberRepresentable(id));
  695. return id;
  696. }
  697. // A hash policy for ubi::Nodes.
  698. // This simply uses the stock PointerHasher on the ubi::Node's pointer.
  699. // We specialize DefaultHasher below to make this the default.
  700. class HashPolicy {
  701. typedef js::PointerHasher<void*, mozilla::tl::FloorLog2<sizeof(void*)>::value> PtrHash;
  702. public:
  703. typedef Node Lookup;
  704. static js::HashNumber hash(const Lookup& l) { return PtrHash::hash(l.base()->ptr); }
  705. static bool match(const Node& k, const Lookup& l) { return k == l; }
  706. static void rekey(Node& k, const Node& newKey) { k = newKey; }
  707. };
  708. };
  709. using NodeSet = js::HashSet<Node, js::DefaultHasher<Node>, js::SystemAllocPolicy>;
  710. using NodeSetPtr = mozilla::UniquePtr<NodeSet, JS::DeletePolicy<NodeSet>>;
  711. /*** Edge and EdgeRange ***************************************************************************/
  712. using EdgeName = UniqueTwoByteChars;
  713. // An outgoing edge to a referent node.
  714. class Edge {
  715. public:
  716. Edge() : name(nullptr), referent() { }
  717. // Construct an initialized Edge, taking ownership of |name|.
  718. Edge(char16_t* name, const Node& referent)
  719. : name(name)
  720. , referent(referent)
  721. { }
  722. // Move construction and assignment.
  723. Edge(Edge&& rhs)
  724. : name(mozilla::Move(rhs.name))
  725. , referent(rhs.referent)
  726. { }
  727. Edge& operator=(Edge&& rhs) {
  728. MOZ_ASSERT(&rhs != this);
  729. this->~Edge();
  730. new (this) Edge(mozilla::Move(rhs));
  731. return *this;
  732. }
  733. Edge(const Edge&) = delete;
  734. Edge& operator=(const Edge&) = delete;
  735. // This edge's name. This may be nullptr, if Node::edges was called with
  736. // false as the wantNames parameter.
  737. //
  738. // The storage is owned by this Edge, and will be freed when this Edge is
  739. // destructed. You may take ownership of the name by `mozilla::Move`ing it
  740. // out of the edge; it is just a UniquePtr.
  741. //
  742. // (In real life we'll want a better representation for names, to avoid
  743. // creating tons of strings when the names follow a pattern; and we'll need
  744. // to think about lifetimes carefully to ensure traversal stays cheap.)
  745. EdgeName name;
  746. // This edge's referent.
  747. Node referent;
  748. };
  749. // EdgeRange is an abstract base class for iterating over a node's outgoing
  750. // edges. (This is modeled after js::HashTable<K,V>::Range.)
  751. //
  752. // Concrete instances of this class need not be as lightweight as Node itself,
  753. // since they're usually only instantiated while iterating over a particular
  754. // object's edges. For example, a dumb implementation for JS Cells might use
  755. // JS::TraceChildren to to get the outgoing edges, and then store them in an
  756. // array internal to the EdgeRange.
  757. class EdgeRange {
  758. protected:
  759. // The current front edge of this range, or nullptr if this range is empty.
  760. Edge* front_;
  761. EdgeRange() : front_(nullptr) { }
  762. public:
  763. virtual ~EdgeRange() { }
  764. // True if there are no more edges in this range.
  765. bool empty() const { return !front_; }
  766. // The front edge of this range. This is owned by the EdgeRange, and is
  767. // only guaranteed to live until the next call to popFront, or until
  768. // the EdgeRange is destructed.
  769. const Edge& front() const { return *front_; }
  770. Edge& front() { return *front_; }
  771. // Remove the front edge from this range. This should only be called if
  772. // !empty().
  773. virtual void popFront() = 0;
  774. private:
  775. EdgeRange(const EdgeRange&) = delete;
  776. EdgeRange& operator=(const EdgeRange&) = delete;
  777. };
  778. typedef mozilla::Vector<Edge, 8, js::SystemAllocPolicy> EdgeVector;
  779. // An EdgeRange concrete class that holds a pre-existing vector of
  780. // Edges. A PreComputedEdgeRange does not take ownership of its
  781. // EdgeVector; it is up to the PreComputedEdgeRange's consumer to manage
  782. // that lifetime.
  783. class PreComputedEdgeRange : public EdgeRange {
  784. EdgeVector& edges;
  785. size_t i;
  786. void settle() {
  787. front_ = i < edges.length() ? &edges[i] : nullptr;
  788. }
  789. public:
  790. explicit PreComputedEdgeRange(EdgeVector& edges)
  791. : edges(edges),
  792. i(0)
  793. {
  794. settle();
  795. }
  796. void popFront() override {
  797. MOZ_ASSERT(!empty());
  798. i++;
  799. settle();
  800. }
  801. };
  802. /*** RootList *************************************************************************************/
  803. // RootList is a class that can be pointed to by a |ubi::Node|, creating a
  804. // fictional root-of-roots which has edges to every GC root in the JS
  805. // runtime. Having a single root |ubi::Node| is useful for algorithms written
  806. // with the assumption that there aren't multiple roots (such as computing
  807. // dominator trees) and you want a single point of entry. It also ensures that
  808. // the roots themselves get visited by |ubi::BreadthFirst| (they would otherwise
  809. // only be used as starting points).
  810. //
  811. // RootList::init itself causes a minor collection, but once the list of roots
  812. // has been created, GC must not occur, as the referent ubi::Nodes are not
  813. // stable across GC. The init calls emplace on |noGC|'s AutoCheckCannotGC, whose
  814. // lifetime must extend at least as long as the RootList itself.
  815. //
  816. // Example usage:
  817. //
  818. // {
  819. // mozilla::Maybe<JS::AutoCheckCannotGC> maybeNoGC;
  820. // JS::ubi::RootList rootList(cx, maybeNoGC);
  821. // if (!rootList.init())
  822. // return false;
  823. //
  824. // // The AutoCheckCannotGC is guaranteed to exist if init returned true.
  825. // MOZ_ASSERT(maybeNoGC.isSome());
  826. //
  827. // JS::ubi::Node root(&rootList);
  828. //
  829. // ...
  830. // }
  831. class MOZ_STACK_CLASS RootList {
  832. Maybe<AutoCheckCannotGC>& noGC;
  833. public:
  834. JSContext* cx;
  835. EdgeVector edges;
  836. bool wantNames;
  837. RootList(JSContext* cx, Maybe<AutoCheckCannotGC>& noGC, bool wantNames = false);
  838. // Find all GC roots.
  839. MOZ_MUST_USE bool init();
  840. // Find only GC roots in the provided set of |JSCompartment|s.
  841. MOZ_MUST_USE bool init(CompartmentSet& debuggees);
  842. // Find only GC roots in the given Debugger object's set of debuggee
  843. // compartments.
  844. MOZ_MUST_USE bool init(HandleObject debuggees);
  845. // Returns true if the RootList has been initialized successfully, false
  846. // otherwise.
  847. bool initialized() { return noGC.isSome(); }
  848. // Explicitly add the given Node as a root in this RootList. If wantNames is
  849. // true, you must pass an edgeName. The RootList does not take ownership of
  850. // edgeName.
  851. MOZ_MUST_USE bool addRoot(Node node, const char16_t* edgeName = nullptr);
  852. };
  853. /*** Concrete classes for ubi::Node referent types ************************************************/
  854. template<>
  855. class Concrete<RootList> : public Base {
  856. protected:
  857. explicit Concrete(RootList* ptr) : Base(ptr) { }
  858. RootList& get() const { return *static_cast<RootList*>(ptr); }
  859. public:
  860. static void construct(void* storage, RootList* ptr) { new (storage) Concrete(ptr); }
  861. js::UniquePtr<EdgeRange> edges(JSContext* cx, bool wantNames) const override;
  862. const char16_t* typeName() const override { return concreteTypeName; }
  863. static const char16_t concreteTypeName[];
  864. };
  865. // A reusable ubi::Concrete specialization base class for types supported by
  866. // JS::TraceChildren.
  867. template<typename Referent>
  868. class TracerConcrete : public Base {
  869. js::UniquePtr<EdgeRange> edges(JSContext* cx, bool wantNames) const override;
  870. JS::Zone* zone() const override;
  871. protected:
  872. explicit TracerConcrete(Referent* ptr) : Base(ptr) { }
  873. Referent& get() const { return *static_cast<Referent*>(ptr); }
  874. };
  875. // For JS::TraceChildren-based types that have a 'compartment' method.
  876. template<typename Referent>
  877. class TracerConcreteWithCompartment : public TracerConcrete<Referent> {
  878. typedef TracerConcrete<Referent> TracerBase;
  879. JSCompartment* compartment() const override;
  880. protected:
  881. explicit TracerConcreteWithCompartment(Referent* ptr) : TracerBase(ptr) { }
  882. };
  883. // Define specializations for some commonly-used public JSAPI types.
  884. // These can use the generic templates above.
  885. template<>
  886. class Concrete<JS::Symbol> : TracerConcrete<JS::Symbol> {
  887. protected:
  888. explicit Concrete(JS::Symbol* ptr) : TracerConcrete(ptr) { }
  889. public:
  890. static void construct(void* storage, JS::Symbol* ptr) {
  891. new (storage) Concrete(ptr);
  892. }
  893. Size size(mozilla::MallocSizeOf mallocSizeOf) const override;
  894. const char16_t* typeName() const override { return concreteTypeName; }
  895. static const char16_t concreteTypeName[];
  896. };
  897. template<>
  898. class Concrete<JSScript> : TracerConcreteWithCompartment<JSScript> {
  899. protected:
  900. explicit Concrete(JSScript *ptr) : TracerConcreteWithCompartment<JSScript>(ptr) { }
  901. public:
  902. static void construct(void *storage, JSScript *ptr) { new (storage) Concrete(ptr); }
  903. CoarseType coarseType() const final { return CoarseType::Script; }
  904. Size size(mozilla::MallocSizeOf mallocSizeOf) const override;
  905. const char* scriptFilename() const final;
  906. const char16_t* typeName() const override { return concreteTypeName; }
  907. static const char16_t concreteTypeName[];
  908. };
  909. // The JSObject specialization.
  910. template<>
  911. class Concrete<JSObject> : public TracerConcreteWithCompartment<JSObject> {
  912. protected:
  913. explicit Concrete(JSObject* ptr) : TracerConcreteWithCompartment(ptr) { }
  914. public:
  915. static void construct(void* storage, JSObject* ptr) {
  916. new (storage) Concrete(ptr);
  917. }
  918. const char* jsObjectClassName() const override;
  919. MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName)
  920. const override;
  921. Size size(mozilla::MallocSizeOf mallocSizeOf) const override;
  922. bool hasAllocationStack() const override;
  923. StackFrame allocationStack() const override;
  924. CoarseType coarseType() const final { return CoarseType::Object; }
  925. const char16_t* typeName() const override { return concreteTypeName; }
  926. static const char16_t concreteTypeName[];
  927. };
  928. // For JSString, we extend the generic template with a 'size' implementation.
  929. template<>
  930. class Concrete<JSString> : TracerConcrete<JSString> {
  931. protected:
  932. explicit Concrete(JSString *ptr) : TracerConcrete<JSString>(ptr) { }
  933. public:
  934. static void construct(void *storage, JSString *ptr) { new (storage) Concrete(ptr); }
  935. Size size(mozilla::MallocSizeOf mallocSizeOf) const override;
  936. CoarseType coarseType() const final { return CoarseType::String; }
  937. const char16_t* typeName() const override { return concreteTypeName; }
  938. static const char16_t concreteTypeName[];
  939. };
  940. // The ubi::Node null pointer. Any attempt to operate on a null ubi::Node asserts.
  941. template<>
  942. class Concrete<void> : public Base {
  943. const char16_t* typeName() const override;
  944. Size size(mozilla::MallocSizeOf mallocSizeOf) const override;
  945. js::UniquePtr<EdgeRange> edges(JSContext* cx, bool wantNames) const override;
  946. JS::Zone* zone() const override;
  947. JSCompartment* compartment() const override;
  948. CoarseType coarseType() const final;
  949. explicit Concrete(void* ptr) : Base(ptr) { }
  950. public:
  951. static void construct(void* storage, void* ptr) { new (storage) Concrete(ptr); }
  952. };
  953. } // namespace ubi
  954. } // namespace JS
  955. namespace js {
  956. // Make ubi::Node::HashPolicy the default hash policy for ubi::Node.
  957. template<> struct DefaultHasher<JS::ubi::Node> : JS::ubi::Node::HashPolicy { };
  958. template<> struct DefaultHasher<JS::ubi::StackFrame> : JS::ubi::StackFrame::HashPolicy { };
  959. } // namespace js
  960. #endif // js_UbiNode_h