Debian Codegraph @

js/src/gc/WeakMap.h

raw
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 gc_WeakMap_h
8 #define gc_WeakMap_h
9
10 #include "mozilla/Atomics.h"
11 #include "mozilla/LinkedList.h"
12
13 #include "gc/Barrier.h"
14 #include "gc/Marking.h"
15 #include "gc/Tracer.h"
16 #include "gc/ZoneAllocator.h"
17 #include "js/HashTable.h"
18 #include "js/HeapAPI.h"
19 #include "vm/JSObject.h"
20
21 namespace JS {
22 class Zone;
23 }
24
25 namespace js {
26
27 class GCMarker;
28 class WeakMapBase;
29 struct WeakMapTracer;
30
31 extern void DumpWeakMapLog(JSRuntime* rt);
32
33 namespace gc {
34
35 struct WeakMarkable;
36
37 #if defined(JS_GC_ZEAL) || defined(DEBUG)
38 // Check whether a weak map entry is marked correctly.
39 bool CheckWeakMapEntryMarking(const WeakMapBase* map, Cell* key, Cell* value);
40 #endif
41
42 } // namespace gc
43
44 // A subclass template of js::HashMap whose keys and values may be
45 // garbage-collected. When a key is collected, the table entry disappears,
46 // dropping its reference to the value.
47 //
48 // More precisely:
49 //
50 // A WeakMap entry is live if and only if both the WeakMap and the entry's
51 // key are live. An entry holds a strong reference to its value.
52 //
53 // You must call this table's 'trace' method when its owning object is reached
54 // by the garbage collection tracer. Once a table is known to be live, the
55 // implementation takes care of the special weak marking (ie, marking through
56 // the implicit edges stored in the map) and of removing (sweeping) table
57 // entries when collection is complete.
58
59 // WeakMaps are marked with an incremental linear-time algorithm that handles
60 // all orderings of map and key marking. The basic algorithm is:
61 //
62 // At first while marking, do nothing special when marking WeakMap keys (there
63 // is no straightforward way to know whether a particular object is being used
64 // as a key in some weakmap.) When a WeakMap is marked, scan through it to mark
65 // all entries with live keys, and collect all unmarked keys into a "weak keys"
66 // table.
67 //
68 // At some point, everything reachable has been marked. At this point, enter
69 // "weak marking mode". In this mode, whenever any object is marked, look it up
70 // in the weak keys table to see if it is the key for any WeakMap entry and if
71 // so, mark the value. When entering weak marking mode, scan the weak key table
72 // to find all keys that have been marked since we added them to the table, and
73 // mark those entries.
74 //
75 // In addition, we want weakmap marking to work incrementally. So WeakMap
76 // mutations are barriered to keep the weak keys table up to date: entries are
77 // removed if their key is removed from the table, etc.
78 //
79 // You can break down various ways that WeakMap values get marked based on the
80 // order that the map and key are marked. All of these assume the map and key
81 // get marked at some point:
82 //
83 // key marked, then map marked:
84 // - value was marked with map in `markEntries()`
85 // map marked, key already in map, key marked before weak marking mode:
86 // - key added to gcEphemeronEdges when map marked in `markEntries()`
87 // - value marked during `enterWeakMarkingMode`
88 // map marked, key already in map, key marked after weak marking mode:
89 // - when key is marked, gcEphemeronEdges[key] triggers marking of value in
90 // `markImplicitEdges()`
91 // map marked, key inserted into map, key marked:
92 // - value was live when inserted and must get marked at some point
93 //
94
95 using WeakMapColors = HashMap<WeakMapBase*, js::gc::CellColor,
96 DefaultHasher<WeakMapBase*>, SystemAllocPolicy>;
97
98 // Common base class for all WeakMap specializations, used for calling
99 // subclasses' GC-related methods.
100 class WeakMapBase : public mozilla::LinkedListElement<WeakMapBase> {
101 friend class js::GCMarker;
102
103 public:
104 using CellColor = js::gc::CellColor;
105
106 WeakMapBase(JSObject* memOf, JS::Zone* zone);
107 virtual ~WeakMapBase() {}
108
109 JS::Zone* zone() const { return zone_; }
110
111 // Garbage collector entry points.
112
113 // Unmark all weak maps in a zone.
114 static void unmarkZone(JS::Zone* zone);
115
116 // Check all weak maps in a zone that have been marked as live in this garbage
117 // collection, and mark the values of all entries that have become strong
118 // references to them. Return true if we marked any new values, indicating
119 // that we need to make another pass. In other words, mark my marked maps'
120 // marked members' mid-collection.
121 static bool markZoneIteratively(JS::Zone* zone, GCMarker* marker);
122
123 // Add zone edges for weakmaps in zone |mapZone| with key delegates in a
124 // different zone.
125 [[nodiscard]] static bool findSweepGroupEdgesForZone(JS::Zone* atomsZone,
126 JS::Zone* mapZone);
127
128 // Sweep the marked weak maps in a zone, updating moved keys.
129 static void sweepZoneAfterMinorGC(JS::Zone* zone);
130
131 // Trace all weak map bindings. Used by the cycle collector.
132 static void traceAllMappings(WeakMapTracer* tracer);
133
134 // Save information about which weak maps are marked for a zone.
135 static bool saveZoneMarkedWeakMaps(JS::Zone* zone,
136 WeakMapColors& markedWeakMaps);
137
138 // Restore information about which weak maps are marked for many zones.
139 static void restoreMarkedWeakMaps(WeakMapColors& markedWeakMaps);
140
141 #if defined(JS_GC_ZEAL) || defined(DEBUG)
142 static bool checkMarkingForZone(JS::Zone* zone);
143 #endif
144
145 #ifdef JSGC_HASH_TABLE_CHECKS
146 static void checkWeakMapsAfterMovingGC(JS::Zone* zone);
147 #endif
148
149 protected:
150 // Instance member functions called by the above. Instantiations of WeakMap
151 // override these with definitions appropriate for their Key and Value types.
152 virtual void trace(JSTracer* tracer) = 0;
153 virtual bool findSweepGroupEdges(Zone* atomsZone) = 0;
154 virtual void traceWeakEdges(JSTracer* trc) = 0;
155 virtual void traceMappings(WeakMapTracer* tracer) = 0;
156 virtual void clearAndCompact() = 0;
157
158 // We have a key that, if it or its delegate is marked, may lead to a WeakMap
159 // value getting marked. Insert the necessary edges into the appropriate
160 // zone's gcEphemeronEdges or gcNurseryEphemeronEdges tables.
161 [[nodiscard]] bool addEphemeronEdgesForEntry(gc::MarkColor mapColor,
162 gc::Cell* key,
163 gc::Cell* delegate,
164 gc::TenuredCell* value);
165 [[nodiscard]] bool addEphemeronEdge(gc::MarkColor color, gc::Cell* src,
166 gc::Cell* dst);
167
168 virtual bool markEntries(GCMarker* marker) = 0;
169
170 gc::CellColor mapColor() const { return gc::CellColor(uint32_t(mapColor_)); }
171 void setMapColor(gc::CellColor newColor) { mapColor_ = uint32_t(newColor); }
172 bool markMap(gc::MarkColor markColor);
173
174 #ifdef JS_GC_ZEAL
175 virtual bool checkMarking() const = 0;
176 virtual bool allowKeysInOtherZones() const { return false; }
177 friend bool gc::CheckWeakMapEntryMarking(const WeakMapBase*, gc::Cell*,
178 gc::Cell*);
179 #endif
180
181 #ifdef JSGC_HASH_TABLE_CHECKS
182 virtual void checkAfterMovingGC() const = 0;
183 #endif
184
185 // Object that this weak map is part of, if any.
186 HeapPtr<JSObject*> memberOf;
187
188 // Zone containing this weak map.
189 JS::Zone* zone_;
190
191 // Whether this object has been marked during garbage collection and which
192 // color it was marked.
193 mozilla::Atomic<uint32_t, mozilla::Relaxed> mapColor_;
194
195 // Cached information about keys to speed up findSweepGroupEdges.
196 bool mayHaveKeyDelegates = false;
197 bool mayHaveSymbolKeys = false;
198
199 friend class JS::Zone;
200 };
201
202 template <class Key, class Value>
203 class WeakMap : public WeakMapBase {
204 using BarrieredKey = HeapPtr<Key>;
205 using BarrieredValue = HeapPtr<Value>;
206
207 using Map = HashMap<HeapPtr<Key>, HeapPtr<Value>,
208 StableCellHasher<HeapPtr<Key>>, ZoneAllocPolicy>;
209 using UnbarrieredMap =
210 HashMap<Key, Value, StableCellHasher<Key>, ZoneAllocPolicy>;
211
212 UnbarrieredMap map_; // Barriers are added by |map()| accessor.
213
214 public:
215 using Lookup = typename Map::Lookup;
216 using Entry = typename Map::Entry;
217 using Range = typename Map::Range;
218 using Ptr = typename Map::Ptr;
219 using AddPtr = typename Map::AddPtr;
220
221 struct Enum : public Map::Enum {
222 explicit Enum(WeakMap& map) : Map::Enum(map.map()) {}
223 };
224
225 explicit WeakMap(JSContext* cx, JSObject* memOf = nullptr);
226 explicit WeakMap(JS::Zone* zone, JSObject* memOf = nullptr);
227 ~WeakMap() override;
228
229 Range all() const { return map().all(); }
230 uint32_t count() const { return map().count(); }
231 bool empty() const { return map().empty(); }
232 bool has(const Lookup& lookup) const { return map().has(lookup); }
233 void remove(const Lookup& lookup) { return map().remove(lookup); }
234 void remove(Ptr ptr) { return map().remove(ptr); }
235
236 size_t shallowSizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const {
237 return map().shallowSizeOfExcludingThis(aMallocSizeOf);
238 }
239 size_t shallowSizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const {
240 return aMallocSizeOf(this) + shallowSizeOfExcludingThis(aMallocSizeOf);
241 }
242
243 // Get the value associated with a key, or a default constructed Value if the
244 // key is not present in the map.
245 Value get(const Lookup& l) {
246 Ptr ptr = lookup(l);
247 if (!ptr) {
248 return Value();
249 }
250 return ptr->value();
251 }
252
253 // Add a read barrier to prevent a gray value from escaping the weak map. This
254 // is necessary because we don't unmark gray through weak maps.
255 Ptr lookup(const Lookup& l) const {
256 Ptr p = map().lookup(l);
257 if (p) {
258 valueReadBarrier(p->value());
259 }
260 return p;
261 }
262
263 Ptr lookupUnbarriered(const Lookup& l) const { return map().lookup(l); }
264
265 AddPtr lookupForAdd(const Lookup& l) {
266 AddPtr p = map().lookupForAdd(l);
267 if (p) {
268 valueReadBarrier(p->value());
269 }
270 return p;
271 }
272
273 template <typename KeyInput, typename ValueInput>
274 [[nodiscard]] bool add(AddPtr& p, KeyInput&& k, ValueInput&& v) {
275 MOZ_ASSERT(gc::ToMarkable(k));
276 keyWriteBarrier(std::forward<KeyInput>(k));
277 return map().add(p, std::forward<KeyInput>(k), std::forward<ValueInput>(v));
278 }
279
280 template <typename KeyInput, typename ValueInput>
281 [[nodiscard]] bool relookupOrAdd(AddPtr& p, KeyInput&& k, ValueInput&& v) {
282 MOZ_ASSERT(gc::ToMarkable(k));
283 keyWriteBarrier(std::forward<KeyInput>(k));
284 return map().relookupOrAdd(p, std::forward<KeyInput>(k),
285 std::forward<ValueInput>(v));
286 }
287
288 template <typename KeyInput, typename ValueInput>
289 [[nodiscard]] bool put(KeyInput&& k, ValueInput&& v) {
290 MOZ_ASSERT(gc::ToMarkable(k));
291 keyWriteBarrier(std::forward<KeyInput>(k));
292 return map().put(std::forward<KeyInput>(k), std::forward<ValueInput>(v));
293 }
294
295 template <typename KeyInput, typename ValueInput>
296 [[nodiscard]] bool putNew(KeyInput&& k, ValueInput&& v) {
297 MOZ_ASSERT(gc::ToMarkable(k));
298 keyWriteBarrier(std::forward<KeyInput>(k));
299 return map().putNew(std::forward<KeyInput>(k), std::forward<ValueInput>(v));
300 }
301
302 template <typename KeyInput, typename ValueInput>
303 void putNewInfallible(KeyInput&& k, ValueInput&& v) {
304 MOZ_ASSERT(gc::ToMarkable(k));
305 keyWriteBarrier(std::forward<KeyInput>(k));
306 map().putNewInfallible(std::forward(k), std::forward<KeyInput>(k));
307 }
308
309 void clear() {
310 map().clear();
311 mayHaveSymbolKeys = false;
312 mayHaveKeyDelegates = false;
313 }
314
315 #ifdef DEBUG
316 template <typename KeyInput, typename ValueInput>
317 bool hasEntry(KeyInput&& key, ValueInput&& value) {
318 Ptr p = map().lookup(std::forward<KeyInput>(key));
319 return p && p->value() == value;
320 }
321 #endif
322
323 bool markEntry(GCMarker* marker, gc::CellColor mapColor, BarrieredKey& key,
324 BarrieredValue& value, bool populateWeakKeysTable);
325
326 void trace(JSTracer* trc) override;
327
328 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf);
329
330 protected:
331 inline void assertMapIsSameZoneWithValue(const BarrieredValue& v);
332
333 bool markEntries(GCMarker* marker) override;
334
335 // Find sweep group edges for delegates, if the key type has delegates. (If
336 // not, the optimizer should make this a nop.)
337 bool findSweepGroupEdges(Zone* atomsZone) override;
338
339 #if DEBUG
340 void assertEntriesNotAboutToBeFinalized();
341 #endif
342
343 #ifdef JS_GC_ZEAL
344 bool checkMarking() const override;
345 #endif
346
347 #ifdef JSGC_HASH_TABLE_CHECKS
348 void checkAfterMovingGC() const override;
349 #endif
350
351 private:
352 // Map accessor uses a cast to add barriers.
353 Map& map() { return reinterpret_cast<Map&>(map_); }
354 const Map& map() const { return reinterpret_cast<const Map&>(map_); }
355
356 static void valueReadBarrier(const JS::Value& v) {
357 JS::ExposeValueToActiveJS(v);
358 }
359 static void valueReadBarrier(JSObject* obj) {
360 JS::ExposeObjectToActiveJS(obj);
361 }
362
363 void keyWriteBarrier(const JS::Value& v) {
364 if (v.isSymbol()) {
365 mayHaveSymbolKeys = true;
366 }
367 if (v.isObject()) {
368 keyWriteBarrier(&v.toObject());
369 }
370 }
371 void keyWriteBarrier(JSObject* key) {
372 JSObject* delegate = UncheckedUnwrapWithoutExpose(key);
373 if (delegate != key || ObjectMayBeSwapped(key)) {
374 mayHaveKeyDelegates = true;
375 }
376 }
377 void keyWriteBarrier(BaseScript* key) {}
378
379 void traceWeakEdges(JSTracer* trc) override;
380
381 void clearAndCompact() override {
382 map().clear();
383 map().compact();
384 }
385
386 // memberOf can be nullptr, which means that the map is not part of a
387 // JSObject.
388 void traceMappings(WeakMapTracer* tracer) override;
389 };
390
391 using ObjectValueWeakMap = WeakMap<JSObject*, Value>;
392 using ValueValueWeakMap = WeakMap<Value, Value>;
393
394 // Generic weak map for mapping objects to other objects.
395 using ObjectWeakMap = WeakMap<JSObject*, JSObject*>;
396
397 // Get the hash from the Symbol.
398 HashNumber GetSymbolHash(JS::Symbol* sym);
399
400 // NB: The specialization works based on pointer equality and not on JS Value
401 // semantics, and it will assert if the Value's isGCThing() is false.
402 //
403 // When the JS Value is of type JS::Symbol, we cannot access uniqueIds when it
404 // runs on the worker thread, so we get the hashes from the Symbols directly
405 // instead.
406 template <>
407 struct StableCellHasher<HeapPtr<Value>> {
408 using Key = HeapPtr<Value>;
409 using Lookup = Value;
410
411 static bool maybeGetHash(const Lookup& l, HashNumber* hashOut) {
412 if (l.isSymbol()) {
413 *hashOut = GetSymbolHash(l.toSymbol());
414 return true;
415 }
416 return StableCellHasher<gc::Cell*>::maybeGetHash(l.toGCThing(), hashOut);
417 }
418 static bool ensureHash(const Lookup& l, HashNumber* hashOut) {
419 if (l.isSymbol()) {
420 *hashOut = GetSymbolHash(l.toSymbol());
421 return true;
422 }
423 return StableCellHasher<gc::Cell*>::ensureHash(l.toGCThing(), hashOut);
424 }
425 static HashNumber hash(const Lookup& l) {
426 if (l.isSymbol()) {
427 return GetSymbolHash(l.toSymbol());
428 }
429 return StableCellHasher<gc::Cell*>::hash(l.toGCThing());
430 }
431 static bool match(const Key& k, const Lookup& l) {
432 if (l.isSymbol()) {
433 return k.toSymbol() == l.toSymbol();
434 }
435 return StableCellHasher<gc::Cell*>::match(k.toGCThing(), l.toGCThing());
436 }
437 };
438
439 } /* namespace js */
440
441 #endif /* gc_WeakMap_h */