jsweakmap.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  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 jsweakmap_h
  6. #define jsweakmap_h
  7. #include "mozilla/LinkedList.h"
  8. #include "mozilla/Move.h"
  9. #include "jscompartment.h"
  10. #include "jsfriendapi.h"
  11. #include "jsobj.h"
  12. #include "gc/Marking.h"
  13. #include "gc/StoreBuffer.h"
  14. #include "js/HashTable.h"
  15. namespace js {
  16. class WeakMapBase;
  17. // A subclass template of js::HashMap whose keys and values may be garbage-collected. When
  18. // a key is collected, the table entry disappears, dropping its reference to the value.
  19. //
  20. // More precisely:
  21. //
  22. // A WeakMap entry is live if and only if both the WeakMap and the entry's key
  23. // are live. An entry holds a strong reference to its value.
  24. //
  25. // You must call this table's 'trace' method when its owning object is reached
  26. // by the garbage collection tracer. Once a table is known to be live, the
  27. // implementation takes care of the special weak marking (ie, marking through
  28. // the implicit edges stored in the map) and of removing (sweeping) table
  29. // entries when collection is complete.
  30. typedef HashSet<WeakMapBase*, DefaultHasher<WeakMapBase*>, SystemAllocPolicy> WeakMapSet;
  31. // Common base class for all WeakMap specializations, used for calling
  32. // subclasses' GC-related methods.
  33. class WeakMapBase : public mozilla::LinkedListElement<WeakMapBase>
  34. {
  35. friend class js::GCMarker;
  36. public:
  37. WeakMapBase(JSObject* memOf, JS::Zone* zone);
  38. virtual ~WeakMapBase();
  39. // Garbage collector entry points.
  40. // Unmark all weak maps in a zone.
  41. static void unmarkZone(JS::Zone* zone);
  42. // Mark all the weakmaps in a zone.
  43. static void markAll(JS::Zone* zone, JSTracer* tracer);
  44. // Check all weak maps in a zone that have been marked as live in this garbage
  45. // collection, and mark the values of all entries that have become strong references
  46. // to them. Return true if we marked any new values, indicating that we need to make
  47. // another pass. In other words, mark my marked maps' marked members' mid-collection.
  48. static bool markZoneIteratively(JS::Zone* zone, JSTracer* tracer);
  49. // Add zone edges for weakmaps with key delegates in a different zone.
  50. static bool findInterZoneEdges(JS::Zone* zone);
  51. // Sweep the weak maps in a zone, removing dead weak maps and removing
  52. // entries of live weak maps whose keys are dead.
  53. static void sweepZone(JS::Zone* zone);
  54. // Trace all delayed weak map bindings. Used by the cycle collector.
  55. static void traceAllMappings(WeakMapTracer* tracer);
  56. // Save information about which weak maps are marked for a zone.
  57. static bool saveZoneMarkedWeakMaps(JS::Zone* zone, WeakMapSet& markedWeakMaps);
  58. // Restore information about which weak maps are marked for many zones.
  59. static void restoreMarkedWeakMaps(WeakMapSet& markedWeakMaps);
  60. protected:
  61. // Instance member functions called by the above. Instantiations of WeakMap override
  62. // these with definitions appropriate for their Key and Value types.
  63. virtual void trace(JSTracer* tracer) = 0;
  64. virtual bool findZoneEdges() = 0;
  65. virtual void sweep() = 0;
  66. virtual void traceMappings(WeakMapTracer* tracer) = 0;
  67. virtual void finish() = 0;
  68. // Any weakmap key types that want to participate in the non-iterative
  69. // ephemeron marking must override this method.
  70. virtual void traceEntry(JSTracer* trc, gc::Cell* markedCell, JS::GCCellPtr l) = 0;
  71. virtual bool traceEntries(JSTracer* trc) = 0;
  72. protected:
  73. // Object that this weak map is part of, if any.
  74. GCPtrObject memberOf;
  75. // Zone containing this weak map.
  76. JS::Zone* zone;
  77. // Whether this object has been traced during garbage collection.
  78. bool marked;
  79. };
  80. template <typename T>
  81. static T extractUnbarriered(WriteBarrieredBase<T> v)
  82. {
  83. return v.get();
  84. }
  85. template <typename T>
  86. static T* extractUnbarriered(T* v)
  87. {
  88. return v;
  89. }
  90. template <class Key, class Value,
  91. class HashPolicy = DefaultHasher<Key> >
  92. class WeakMap : public HashMap<Key, Value, HashPolicy, RuntimeAllocPolicy>,
  93. public WeakMapBase
  94. {
  95. public:
  96. typedef HashMap<Key, Value, HashPolicy, RuntimeAllocPolicy> Base;
  97. typedef typename Base::Enum Enum;
  98. typedef typename Base::Lookup Lookup;
  99. typedef typename Base::Entry Entry;
  100. typedef typename Base::Range Range;
  101. typedef typename Base::Ptr Ptr;
  102. typedef typename Base::AddPtr AddPtr;
  103. explicit WeakMap(JSContext* cx, JSObject* memOf = nullptr)
  104. : Base(cx->runtime()), WeakMapBase(memOf, cx->compartment()->zone()) { }
  105. bool init(uint32_t len = 16) {
  106. if (!Base::init(len))
  107. return false;
  108. zone->gcWeakMapList.insertFront(this);
  109. JSRuntime* rt = zone->runtimeFromMainThread();
  110. marked = JS::IsIncrementalGCInProgress(rt->contextFromMainThread());
  111. return true;
  112. }
  113. // Overwritten to add a read barrier to prevent an incorrectly gray value
  114. // from escaping the weak map. See the UnmarkGrayTracer::onChild comment in
  115. // gc/Marking.cpp.
  116. Ptr lookup(const Lookup& l) const {
  117. Ptr p = Base::lookup(l);
  118. if (p)
  119. exposeGCThingToActiveJS(p->value());
  120. return p;
  121. }
  122. AddPtr lookupForAdd(const Lookup& l) const {
  123. AddPtr p = Base::lookupForAdd(l);
  124. if (p)
  125. exposeGCThingToActiveJS(p->value());
  126. return p;
  127. }
  128. Ptr lookupWithDefault(const Key& k, const Value& defaultValue) {
  129. Ptr p = Base::lookupWithDefault(k, defaultValue);
  130. if (p)
  131. exposeGCThingToActiveJS(p->value());
  132. return p;
  133. }
  134. // Resolve ambiguity with LinkedListElement<>::remove.
  135. using Base::remove;
  136. // Trace a WeakMap entry based on 'markedCell' getting marked, where
  137. // 'origKey' is the key in the weakmap. These will probably be the same,
  138. // but can be different eg when markedCell is a delegate for origKey.
  139. //
  140. // This implementation does not use 'markedCell'; it looks up origKey and
  141. // checks the mark bits on everything it cares about, one of which will be
  142. // markedCell. But a subclass might use it to optimize the liveness check.
  143. void traceEntry(JSTracer* trc, gc::Cell* markedCell, JS::GCCellPtr origKey) override
  144. {
  145. MOZ_ASSERT(marked);
  146. // If this cast fails, then you're instantiating the WeakMap with a
  147. // Lookup that can't be constructed from a Cell*. The WeakKeyTable
  148. // mechanism is indexed with a GCCellPtr, so that won't work.
  149. Ptr p = Base::lookup(static_cast<Lookup>(origKey.asCell()));
  150. MOZ_ASSERT(p.found());
  151. Key key(p->key());
  152. MOZ_ASSERT((markedCell == extractUnbarriered(key)) || (markedCell == getDelegate(key)));
  153. if (gc::IsMarked(trc->runtime(), &key)) {
  154. TraceEdge(trc, &p->value(), "ephemeron value");
  155. } else if (keyNeedsMark(key)) {
  156. TraceEdge(trc, &p->value(), "WeakMap ephemeron value");
  157. TraceEdge(trc, &key, "proxy-preserved WeakMap ephemeron key");
  158. MOZ_ASSERT(key == p->key()); // No moving
  159. }
  160. key.unsafeSet(nullptr); // Prevent destructor from running barriers.
  161. }
  162. void trace(JSTracer* trc) override {
  163. MOZ_ASSERT(isInList());
  164. if (trc->isMarkingTracer())
  165. marked = true;
  166. if (trc->weakMapAction() == DoNotTraceWeakMaps)
  167. return;
  168. if (!trc->isMarkingTracer()) {
  169. // Trace keys only if weakMapAction() says to.
  170. if (trc->weakMapAction() == TraceWeakMapKeysValues) {
  171. for (Enum e(*this); !e.empty(); e.popFront())
  172. TraceEdge(trc, &e.front().mutableKey(), "WeakMap entry key");
  173. }
  174. // Always trace all values (unless weakMapAction() is
  175. // DoNotTraceWeakMaps).
  176. for (Range r = Base::all(); !r.empty(); r.popFront())
  177. TraceEdge(trc, &r.front().value(), "WeakMap entry value");
  178. return;
  179. }
  180. // Marking tracer
  181. MOZ_ASSERT(trc->weakMapAction() == ExpandWeakMaps);
  182. (void) traceEntries(trc);
  183. }
  184. protected:
  185. static void addWeakEntry(JSTracer* trc, JS::GCCellPtr key, gc::WeakMarkable markable)
  186. {
  187. GCMarker& marker = *static_cast<GCMarker*>(trc);
  188. Zone* zone = key.asCell()->asTenured().zone();
  189. auto p = zone->gcWeakKeys.get(key);
  190. if (p) {
  191. gc::WeakEntryVector& weakEntries = p->value;
  192. if (!weakEntries.append(Move(markable)))
  193. marker.abortLinearWeakMarking();
  194. } else {
  195. gc::WeakEntryVector weakEntries;
  196. MOZ_ALWAYS_TRUE(weakEntries.append(Move(markable)));
  197. if (!zone->gcWeakKeys.put(JS::GCCellPtr(key), Move(weakEntries)))
  198. marker.abortLinearWeakMarking();
  199. }
  200. }
  201. bool traceEntries(JSTracer* trc) override {
  202. MOZ_ASSERT(marked);
  203. bool markedAny = false;
  204. for (Enum e(*this); !e.empty(); e.popFront()) {
  205. // If the entry is live, ensure its key and value are marked.
  206. bool keyIsMarked = gc::IsMarked(trc->runtime(), &e.front().mutableKey());
  207. if (!keyIsMarked && keyNeedsMark(e.front().key())) {
  208. TraceEdge(trc, &e.front().mutableKey(), "proxy-preserved WeakMap entry key");
  209. keyIsMarked = true;
  210. markedAny = true;
  211. }
  212. if (keyIsMarked) {
  213. if (!gc::IsMarked(trc->runtime(), &e.front().value())) {
  214. TraceEdge(trc, &e.front().value(), "WeakMap entry value");
  215. markedAny = true;
  216. }
  217. } else if (trc->isWeakMarkingTracer()) {
  218. // Entry is not yet known to be live. Record this weakmap and
  219. // the lookup key in the list of weak keys. Also record the
  220. // delegate, if any, because marking the delegate also marks
  221. // the entry.
  222. JS::GCCellPtr weakKey(extractUnbarriered(e.front().key()));
  223. gc::WeakMarkable markable(this, weakKey);
  224. addWeakEntry(trc, weakKey, markable);
  225. if (JSObject* delegate = getDelegate(e.front().key()))
  226. addWeakEntry(trc, JS::GCCellPtr(delegate), markable);
  227. }
  228. }
  229. return markedAny;
  230. }
  231. JSObject* getDelegate(JSObject* key) const {
  232. JSWeakmapKeyDelegateOp op = key->getClass()->extWeakmapKeyDelegateOp();
  233. if (!op)
  234. return nullptr;
  235. JSObject* obj = op(key);
  236. if (!obj)
  237. return nullptr;
  238. MOZ_ASSERT(obj->runtimeFromMainThread() == zone->runtimeFromMainThread());
  239. return obj;
  240. }
  241. JSObject* getDelegate(JSScript* script) const {
  242. return nullptr;
  243. }
  244. private:
  245. void exposeGCThingToActiveJS(const JS::Value& v) const { JS::ExposeValueToActiveJS(v); }
  246. void exposeGCThingToActiveJS(JSObject* obj) const { JS::ExposeObjectToActiveJS(obj); }
  247. bool keyNeedsMark(JSObject* key) const {
  248. JSObject* delegate = getDelegate(key);
  249. /*
  250. * Check if the delegate is marked with any color to properly handle
  251. * gray marking when the key's delegate is black and the map is gray.
  252. */
  253. return delegate && gc::IsMarkedUnbarriered(zone->runtimeFromMainThread(), &delegate);
  254. }
  255. bool keyNeedsMark(JSScript* script) const {
  256. return false;
  257. }
  258. bool findZoneEdges() override {
  259. // This is overridden by ObjectValueMap.
  260. return true;
  261. }
  262. void sweep() override {
  263. /* Remove all entries whose keys remain unmarked. */
  264. for (Enum e(*this); !e.empty(); e.popFront()) {
  265. if (gc::IsAboutToBeFinalized(&e.front().mutableKey()))
  266. e.removeFront();
  267. }
  268. /*
  269. * Once we've swept, all remaining edges should stay within the
  270. * known-live part of the graph.
  271. */
  272. assertEntriesNotAboutToBeFinalized();
  273. }
  274. void finish() override {
  275. Base::finish();
  276. }
  277. /* memberOf can be nullptr, which means that the map is not part of a JSObject. */
  278. void traceMappings(WeakMapTracer* tracer) override {
  279. for (Range r = Base::all(); !r.empty(); r.popFront()) {
  280. gc::Cell* key = gc::ToMarkable(r.front().key());
  281. gc::Cell* value = gc::ToMarkable(r.front().value());
  282. if (key && value) {
  283. tracer->trace(memberOf,
  284. JS::GCCellPtr(r.front().key().get()),
  285. JS::GCCellPtr(r.front().value().get()));
  286. }
  287. }
  288. }
  289. protected:
  290. void assertEntriesNotAboutToBeFinalized() {
  291. #if DEBUG
  292. for (Range r = Base::all(); !r.empty(); r.popFront()) {
  293. Key k(r.front().key());
  294. MOZ_ASSERT(!gc::IsAboutToBeFinalized(&k));
  295. MOZ_ASSERT(!gc::IsAboutToBeFinalized(&r.front().value()));
  296. MOZ_ASSERT(k == r.front().key());
  297. }
  298. #endif
  299. }
  300. };
  301. /* WeakMap methods exposed so they can be installed in the self-hosting global. */
  302. extern JSObject*
  303. InitBareWeakMapCtor(JSContext* cx, js::HandleObject obj);
  304. extern bool
  305. WeakMap_has(JSContext* cx, unsigned argc, Value* vp);
  306. extern bool
  307. WeakMap_get(JSContext* cx, unsigned argc, Value* vp);
  308. extern bool
  309. WeakMap_set(JSContext* cx, unsigned argc, Value* vp);
  310. extern bool
  311. WeakMap_delete(JSContext* cx, unsigned argc, Value* vp);
  312. extern JSObject*
  313. InitWeakMapClass(JSContext* cx, HandleObject obj);
  314. class ObjectValueMap : public WeakMap<HeapPtr<JSObject*>, HeapPtr<Value>,
  315. MovableCellHasher<HeapPtr<JSObject*>>>
  316. {
  317. public:
  318. ObjectValueMap(JSContext* cx, JSObject* obj)
  319. : WeakMap<HeapPtr<JSObject*>, HeapPtr<Value>,
  320. MovableCellHasher<HeapPtr<JSObject*>>>(cx, obj)
  321. {}
  322. virtual bool findZoneEdges();
  323. };
  324. // Generic weak map for mapping objects to other objects.
  325. class ObjectWeakMap
  326. {
  327. ObjectValueMap map;
  328. public:
  329. explicit ObjectWeakMap(JSContext* cx);
  330. bool init();
  331. JSObject* lookup(const JSObject* obj);
  332. bool add(JSContext* cx, JSObject* obj, JSObject* target);
  333. void clear();
  334. void trace(JSTracer* trc);
  335. size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf);
  336. size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) {
  337. return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf);
  338. }
  339. #ifdef JSGC_HASH_TABLE_CHECKS
  340. void checkAfterMovingGC();
  341. #endif
  342. };
  343. } /* namespace js */
  344. namespace JS {
  345. template <>
  346. struct DeletePolicy<js::ObjectValueMap> : public js::GCManagedDeletePolicy<js::ObjectValueMap>
  347. {};
  348. } /* namespace JS */
  349. #endif /* jsweakmap_h */