Debian Codegraph @

js/src/gc/WeakMap-inl.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_inl_h
8 #define gc_WeakMap_inl_h
9
10 #include "gc/WeakMap.h"
11
12 #include "mozilla/DebugOnly.h"
13 #include "mozilla/Maybe.h"
14
15 #include <algorithm>
16 #include <type_traits>
17
18 #include "gc/GCLock.h"
19 #include "gc/Marking.h"
20 #include "gc/Zone.h"
21 #include "js/Prefs.h"
22 #include "js/TraceKind.h"
23 #include "vm/JSContext.h"
24
25 #include "gc/Marking-inl.h"
26 #include "gc/StableCellHasher-inl.h"
27
28 namespace js {
29
30 namespace gc::detail {
31
32 // Return the effective cell color given the current marking state.
33 // This must be kept in sync with ShouldMark in Marking.cpp.
34 template <typename T>
35 static CellColor GetEffectiveColor(GCMarker* marker, const T& item) {
36 Cell* cell = ToMarkable(item);
37 if (!cell->isTenured()) {
38 return CellColor::Black;
39 }
40 const TenuredCell& t = cell->asTenured();
41 if (!t.zoneFromAnyThread()->shouldMarkInZone(marker->markColor())) {
42 return CellColor::Black;
43 }
44 MOZ_ASSERT(t.runtimeFromAnyThread() == marker->runtime());
45 return t.color();
46 }
47
48 // If a wrapper is used as a key in a weakmap, the garbage collector should
49 // keep that object around longer than it otherwise would. We want to avoid
50 // collecting the wrapper (and removing the weakmap entry) as long as the
51 // wrapped object is alive (because the object can be rewrapped and looked up
52 // again). As long as the wrapper is used as a weakmap key, it will not be
53 // collected (and remain in the weakmap) until the wrapped object is
54 // collected.
55
56 // Only objects have delegates, so default to returning nullptr. Note that some
57 // compilation units will only ever use the object version.
58 static MOZ_MAYBE_UNUSED JSObject* GetDelegateInternal(gc::Cell* key) {
59 return nullptr;
60 }
61
62 static MOZ_MAYBE_UNUSED JSObject* GetDelegateInternal(JSObject* key) {
63 JSObject* delegate = UncheckedUnwrapWithoutExpose(key);
64 return (key == delegate) ? nullptr : delegate;
65 }
66 static MOZ_MAYBE_UNUSED JSObject* GetDelegateInternal(const Value& key) {
67 if (key.isObject()) {
68 return GetDelegateInternal(&key.toObject());
69 }
70 return nullptr;
71 }
72
73 // Use a helper function to do overload resolution to handle cases like
74 // Heap<ObjectSubclass*>: find everything that is convertible to JSObject* (and
75 // avoid calling barriers).
76 template <typename T>
77 static inline JSObject* GetDelegate(const T& key) {
78 return GetDelegateInternal(key);
79 }
80
81 template <>
82 inline JSObject* GetDelegate(gc::Cell* const&) = delete;
83
84 template <typename T>
85 static inline bool IsSymbol(const T& key) {
86 return false;
87 }
88
89 template <>
90 inline bool IsSymbol(const HeapPtr<JS::Value>& key) {
91 return key.isSymbol();
92 }
93
94 } // namespace gc::detail
95
96 // Weakmap entry -> value edges are only visible if the map is traced, which
97 // only happens if the map zone is being collected. If the map and the value
98 // were in different zones, then we could have a case where the map zone is not
99 // collecting but the value zone is, and incorrectly free a value that is
100 // reachable solely through weakmaps.
101 template <class K, class V>
102 void WeakMap<K, V>::assertMapIsSameZoneWithValue(const BarrieredValue& v) {
103 #ifdef DEBUG
104 gc::Cell* cell = gc::ToMarkable(v);
105 if (cell) {
106 Zone* cellZone = cell->zoneFromAnyThread();
107 MOZ_ASSERT(zone() == cellZone || cellZone->isAtomsZone());
108 }
109 #endif
110 }
111
112 template <class K, class V>
113 WeakMap<K, V>::WeakMap(JSContext* cx, JSObject* memOf)
114 : WeakMap(cx->zone(), memOf) {}
115
116 template <class K, class V>
117 WeakMap<K, V>::WeakMap(JS::Zone* zone, JSObject* memOf)
118 : WeakMapBase(memOf, zone), map_(zone) {
119 static_assert(std::is_same_v<typename RemoveBarrier<K>::Type, K>);
120 static_assert(std::is_same_v<typename RemoveBarrier<V>::Type, V>);
121
122 // The object's TraceKind needs to be added to CC graph if this object is
123 // used as a WeakMap key, otherwise the key is considered to be pointed from
124 // somewhere unknown, and results in leaking the subgraph which contains the
125 // key. See the comments in NoteWeakMapsTracer::trace for more details.
126 if constexpr (std::is_pointer_v<K>) {
127 using NonPtrType = std::remove_pointer_t<K>;
128 static_assert(JS::IsCCTraceKind(NonPtrType::TraceKind),
129 "Object's TraceKind should be added to CC graph.");
130 }
131
132 zone->gcWeakMapList().insertFront(this);
133 if (zone->gcState() > Zone::Prepare) {
134 setMapColor(CellColor::Black);
135 }
136 }
137
138 template <class K, class V>
139 WeakMap<K, V>::~WeakMap() {
140 #ifdef DEBUG
141 // Weak maps store their data in an unbarriered map (|map_|) meaning that no
142 // barriers are run on destruction. This is safe because:
143
144 // 1. Weak maps have GC lifetime except on construction failure, therefore no
145 // prebarrier is required.
146 MOZ_ASSERT_IF(!empty(),
147 CurrentThreadIsGCSweeping() || CurrentThreadIsGCFinalizing());
148
149 // 2. If we're finalizing a weak map due to GC then it cannot contain nursery
150 // things, because we evicted the nursery at the start of collection and
151 // writing a nursery thing into the table would require the map to be
152 // live. Therefore no postbarrier is required.
153 size_t i = 0;
154 for (auto r = all(); !r.empty() && i < 1000; r.popFront(), i++) {
155 K key = r.front().key();
156 MOZ_ASSERT_IF(gc::ToMarkable(key), !IsInsideNursery(gc::ToMarkable(key)));
157 V value = r.front().value();
158 MOZ_ASSERT_IF(gc::ToMarkable(value),
159 !IsInsideNursery(gc::ToMarkable(value)));
160 }
161 #endif
162 }
163
164 // If the entry is live, ensure its key and value are marked. Also make sure the
165 // key is at least as marked as min(map, delegate), so it cannot get discarded
166 // and then recreated by rewrapping the delegate.
167 //
168 // Optionally adds edges to the ephemeron edges table for any keys (or
169 // delegates) where future changes to their mark color would require marking the
170 // value (or the key).
171 template <class K, class V>
172 bool WeakMap<K, V>::markEntry(GCMarker* marker, gc::CellColor mapColor,
173 BarrieredKey& key, BarrieredValue& value,
174 bool populateWeakKeysTable) {
175 #ifdef DEBUG
176 MOZ_ASSERT(IsMarked(mapColor));
177 if (marker->isParallelMarking()) {
178 marker->runtime()->gc.assertCurrentThreadHasLockedGC();
179 }
180 #endif
181
182 bool marked = false;
183 CellColor markColor = AsCellColor(marker->markColor());
184 CellColor keyColor = gc::detail::GetEffectiveColor(marker, key);
185 JSObject* delegate = gc::detail::GetDelegate(key);
186 JSTracer* trc = marker->tracer();
187
188 gc::Cell* keyCell = gc::ToMarkable(key);
189 MOZ_ASSERT(keyCell);
190
191 if (delegate) {
192 CellColor delegateColor = gc::detail::GetEffectiveColor(marker, delegate);
193 // The key needs to stay alive while both the delegate and map are live.
194 CellColor proxyPreserveColor = std::min(delegateColor, mapColor);
195 if (keyColor < proxyPreserveColor) {
196 MOZ_ASSERT(markColor >= proxyPreserveColor);
197 if (markColor == proxyPreserveColor) {
198 TraceWeakMapKeyEdge(trc, zone(), &key,
199 "proxy-preserved WeakMap entry key");
200 MOZ_ASSERT(keyCell->color() >= proxyPreserveColor);
201 marked = true;
202 keyColor = proxyPreserveColor;
203 }
204 }
205 }
206
207 gc::Cell* cellValue = gc::ToMarkable(value);
208 if (IsMarked(keyColor)) {
209 if (cellValue) {
210 CellColor targetColor = std::min(mapColor, keyColor);
211 CellColor valueColor = gc::detail::GetEffectiveColor(marker, cellValue);
212 if (valueColor < targetColor) {
213 MOZ_ASSERT(markColor >= targetColor);
214 if (markColor == targetColor) {
215 TraceEdge(trc, &value, "WeakMap entry value");
216 MOZ_ASSERT(cellValue->color() >= targetColor);
217 marked = true;
218 }
219 }
220 }
221 }
222
223 if (populateWeakKeysTable) {
224 MOZ_ASSERT(trc->weakMapAction() == JS::WeakMapTraceAction::Expand);
225
226 // Note that delegateColor >= keyColor because marking a key marks its
227 // delegate, so we only need to check whether keyColor < mapColor to tell
228 // this.
229 if (keyColor < mapColor) {
230 // The final color of the key is not yet known. Add an edge to the
231 // relevant ephemerons table to ensure that the value will be marked if
232 // the key is marked. If the key has a delegate, also add an edge to
233 // ensure the key is marked if the delegate is marked.
234
235 gc::TenuredCell* tenuredValue = nullptr;
236 if (cellValue && cellValue->isTenured()) {
237 tenuredValue = &cellValue->asTenured();
238 }
239
240 if (!this->addEphemeronEdgesForEntry(AsMarkColor(mapColor), keyCell,
241 delegate, tenuredValue)) {
242 marker->abortLinearWeakMarking();
243 }
244 }
245 }
246
247 return marked;
248 }
249
250 template <class K, class V>
251 void WeakMap<K, V>::trace(JSTracer* trc) {
252 MOZ_ASSERT(isInList());
253
254 TraceNullableEdge(trc, &memberOf, "WeakMap owner");
255
256 if (trc->isMarkingTracer()) {
257 MOZ_ASSERT(trc->weakMapAction() == JS::WeakMapTraceAction::Expand);
258 GCMarker* marker = GCMarker::fromTracer(trc);
259 if (markMap(marker->markColor())) {
260 (void)markEntries(marker);
261 }
262 return;
263 }
264
265 if (trc->weakMapAction() == JS::WeakMapTraceAction::Skip) {
266 return;
267 }
268
269 // Trace keys only if weakMapAction() says to.
270 if (trc->weakMapAction() == JS::WeakMapTraceAction::TraceKeysAndValues) {
271 for (Enum e(*this); !e.empty(); e.popFront()) {
272 TraceWeakMapKeyEdge(trc, zone(), &e.front().mutableKey(),
273 "WeakMap entry key");
274 }
275 }
276
277 // Always trace all values (unless weakMapAction() is Skip).
278 for (Range r = all(); !r.empty(); r.popFront()) {
279 TraceEdge(trc, &r.front().value(), "WeakMap entry value");
280 }
281 }
282
283 template <class K, class V>
284 bool WeakMap<K, V>::markEntries(GCMarker* marker) {
285 // This method is called whenever the map's mark color changes. Mark values
286 // (and keys with delegates) as required for the new color and populate the
287 // ephemeron edges if we're in incremental marking mode.
288
289 // Lock during parallel marking to synchronize updates to the ephemeron edges
290 // table.
291 mozilla::Maybe<AutoLockGC> lock;
292 if (marker->isParallelMarking()) {
293 lock.emplace(marker->runtime());
294 }
295
296 MOZ_ASSERT(IsMarked(mapColor()));
297 bool markedAny = false;
298
299 // If we don't populate the weak keys table now then we do it when we enter
300 // weak marking mode.
301 bool populateWeakKeysTable =
302 marker->incrementalWeakMapMarkingEnabled || marker->isWeakMarking();
303
304 // Read the atomic color into a local variable so the compiler doesn't load it
305 // every time.
306 gc::CellColor mapColor = this->mapColor();
307
308 for (Enum e(*this); !e.empty(); e.popFront()) {
309 if (markEntry(marker, mapColor, e.front().mutableKey(), e.front().value(),
310 populateWeakKeysTable)) {
311 markedAny = true;
312 }
313 }
314
315 return markedAny;
316 }
317
318 template <class K, class V>
319 void WeakMap<K, V>::traceWeakEdges(JSTracer* trc) {
320 // Scan the map, removing all entries whose keys remain unmarked. Rebuild
321 // cached key state at the same time.
322 mayHaveSymbolKeys = false;
323 mayHaveKeyDelegates = false;
324 for (Enum e(*this); !e.empty(); e.popFront()) {
325 if (TraceWeakEdge(trc, &e.front().mutableKey(), "WeakMap key")) {
326 keyWriteBarrier(e.front().key());
327 } else {
328 e.removeFront();
329 }
330 }
331
332 #if DEBUG
333 // Once we've swept, all remaining edges should stay within the known-live
334 // part of the graph.
335 assertEntriesNotAboutToBeFinalized();
336 #endif
337 }
338
339 // memberOf can be nullptr, which means that the map is not part of a JSObject.
340 template <class K, class V>
341 void WeakMap<K, V>::traceMappings(WeakMapTracer* tracer) {
342 for (Range r = all(); !r.empty(); r.popFront()) {
343 gc::Cell* key = gc::ToMarkable(r.front().key());
344 gc::Cell* value = gc::ToMarkable(r.front().value());
345 if (key && value) {
346 tracer->trace(memberOf, JS::GCCellPtr(r.front().key().get()),
347 JS::GCCellPtr(r.front().value().get()));
348 }
349 }
350 }
351
352 template <class K, class V>
353 bool WeakMap<K, V>::findSweepGroupEdges(Zone* atomsZone) {
354 // For weakmap keys with delegates in a different zone, add a zone edge to
355 // ensure that the delegate zone finishes marking before the key zone.
356
357 #ifdef DEBUG
358 if (!mayHaveSymbolKeys || !mayHaveKeyDelegates) {
359 for (Range r = all(); !r.empty(); r.popFront()) {
360 const K& key = r.front().key();
361 MOZ_ASSERT_IF(!mayHaveKeyDelegates, !gc::detail::GetDelegate(key));
362 MOZ_ASSERT_IF(!mayHaveSymbolKeys, !gc::detail::IsSymbol(key));
363 }
364 }
365 #endif
366
367 #ifdef NIGHTLY_BUILD
368 if (mayHaveSymbolKeys) {
369 MOZ_ASSERT(JS::Prefs::experimental_symbols_as_weakmap_keys());
370 if (atomsZone->isGCMarking()) {
371 if (!atomsZone->addSweepGroupEdgeTo(zone())) {
372 return false;
373 }
374 }
375 }
376 #endif
377
378 if (mayHaveKeyDelegates) {
379 for (Range r = all(); !r.empty(); r.popFront()) {
380 const K& key = r.front().key();
381
382 JSObject* delegate = gc::detail::GetDelegate(key);
383 if (delegate) {
384 // Marking a WeakMap key's delegate will mark the key, so process the
385 // delegate zone no later than the key zone.
386 Zone* delegateZone = delegate->zone();
387 gc::Cell* keyCell = gc::ToMarkable(key);
388 MOZ_ASSERT(keyCell);
389 Zone* keyZone = keyCell->zone();
390 if (delegateZone != keyZone && delegateZone->isGCMarking() &&
391 keyZone->isGCMarking()) {
392 if (!delegateZone->addSweepGroupEdgeTo(keyZone)) {
393 return false;
394 }
395 }
396 }
397 }
398 }
399
400 return true;
401 }
402
403 template <class K, class V>
404 size_t WeakMap<K, V>::sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) {
405 return mallocSizeOf(this) + shallowSizeOfExcludingThis(mallocSizeOf);
406 }
407
408 #if DEBUG
409 template <class K, class V>
410 void WeakMap<K, V>::assertEntriesNotAboutToBeFinalized() {
411 for (Range r = all(); !r.empty(); r.popFront()) {
412 K k = r.front().key();
413 MOZ_ASSERT(!gc::IsAboutToBeFinalizedUnbarriered(k));
414 JSObject* delegate = gc::detail::GetDelegate(k);
415 if (delegate) {
416 MOZ_ASSERT(!gc::IsAboutToBeFinalizedUnbarriered(delegate),
417 "weakmap marking depends on a key tracing its delegate");
418 }
419 MOZ_ASSERT(!gc::IsAboutToBeFinalized(r.front().value()));
420 }
421 }
422 #endif
423
424 #ifdef JS_GC_ZEAL
425 template <class K, class V>
426 bool WeakMap<K, V>::checkMarking() const {
427 bool ok = true;
428 for (Range r = all(); !r.empty(); r.popFront()) {
429 gc::Cell* key = gc::ToMarkable(r.front().key());
430 gc::Cell* value = gc::ToMarkable(r.front().value());
431 if (key && value) {
432 if (!gc::CheckWeakMapEntryMarking(this, key, value)) {
433 ok = false;
434 }
435 }
436 }
437 return ok;
438 }
439 #endif
440
441 #ifdef JSGC_HASH_TABLE_CHECKS
442 template <class K, class V>
443 void WeakMap<K, V>::checkAfterMovingGC() const {
444 for (Range r = all(); !r.empty(); r.popFront()) {
445 gc::Cell* key = gc::ToMarkable(r.front().key());
446 gc::Cell* value = gc::ToMarkable(r.front().value());
447 CheckGCThingAfterMovingGC(key);
448 if (!allowKeysInOtherZones()) {
449 Zone* keyZone = key->zoneFromAnyThread();
450 MOZ_RELEASE_ASSERT(keyZone == zone() || keyZone->isAtomsZone());
451 }
452 CheckGCThingAfterMovingGC(value, zone());
453 auto ptr = lookupUnbarriered(r.front().key());
454 MOZ_RELEASE_ASSERT(ptr.found() && &*ptr == &r.front());
455 }
456 }
457 #endif // JSGC_HASH_TABLE_CHECKS
458
459 inline HashNumber GetSymbolHash(JS::Symbol* sym) { return sym->hash(); }
460
461 } // namespace js
462
463 #endif /* gc_WeakMap_inl_h */