Debian Codegraph @

js/src/gc/FinalizationObservers.cpp

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 /*
8 * GC support for FinalizationRegistry and WeakRef objects.
9 */
10
11 #include "gc/FinalizationObservers.h"
12
13 #include "mozilla/ScopeExit.h"
14
15 #include "builtin/FinalizationRegistryObject.h"
16 #include "builtin/WeakRefObject.h"
17 #include "gc/GCRuntime.h"
18 #include "gc/PublicIterators.h"
19 #include "gc/Zone.h"
20 #include "vm/JSContext.h"
21
22 #include "gc/WeakMap-inl.h"
23 #include "vm/JSObject-inl.h"
24 #include "vm/NativeObject-inl.h"
25
26 using namespace js;
27 using namespace js::gc;
28
29 FinalizationObservers::FinalizationObservers(Zone* zone)
30 : zone(zone),
31 registries(zone),
32 recordMap(zone),
33 crossZoneRecords(zone),
34 weakRefMap(zone),
35 crossZoneWeakRefs(zone) {}
36
37 FinalizationObservers::~FinalizationObservers() {
38 MOZ_ASSERT(registries.empty());
39 MOZ_ASSERT(recordMap.empty());
40 MOZ_ASSERT(crossZoneRecords.empty());
41 MOZ_ASSERT(crossZoneWeakRefs.empty());
42 }
43
44 bool GCRuntime::addFinalizationRegistry(
45 JSContext* cx, Handle<FinalizationRegistryObject*> registry) {
46 if (!cx->zone()->ensureFinalizationObservers() ||
47 !cx->zone()->finalizationObservers()->addRegistry(registry)) {
48 ReportOutOfMemory(cx);
49 return false;
50 }
51
52 return true;
53 }
54
55 bool FinalizationObservers::addRegistry(
56 Handle<FinalizationRegistryObject*> registry) {
57 return registries.put(registry);
58 }
59
60 bool GCRuntime::registerWithFinalizationRegistry(JSContext* cx,
61 HandleObject target,
62 HandleObject record) {
63 MOZ_ASSERT(!IsCrossCompartmentWrapper(target));
64 MOZ_ASSERT(
65 UncheckedUnwrapWithoutExpose(record)->is<FinalizationRecordObject>());
66 MOZ_ASSERT(target->compartment() == record->compartment());
67
68 Zone* zone = cx->zone();
69 if (!zone->ensureFinalizationObservers() ||
70 !zone->finalizationObservers()->addRecord(target, record)) {
71 ReportOutOfMemory(cx);
72 return false;
73 }
74
75 return true;
76 }
77
78 bool FinalizationObservers::addRecord(HandleObject target,
79 HandleObject record) {
80 // Add a record to the record map and clean up on failure.
81 //
82 // The following must be updated and kept in sync:
83 // - the zone's recordMap (to observe the target)
84 // - the registry's global objects's recordSet (to trace the record)
85 // - the count of cross zone records (to calculate sweep groups)
86
87 MOZ_ASSERT(target->zone() == zone);
88
89 FinalizationRecordObject* unwrappedRecord =
90 &UncheckedUnwrapWithoutExpose(record)->as<FinalizationRecordObject>();
91
92 Zone* registryZone = unwrappedRecord->zone();
93 bool crossZone = registryZone != zone;
94 if (crossZone && !addCrossZoneWrapper(crossZoneRecords, record)) {
95 return false;
96 }
97 auto wrapperGuard = mozilla::MakeScopeExit([&] {
98 if (crossZone) {
99 removeCrossZoneWrapper(crossZoneRecords, record);
100 }
101 });
102
103 GlobalObject* registryGlobal = &unwrappedRecord->global();
104 auto* globalData = registryGlobal->getOrCreateFinalizationRegistryData();
105 if (!globalData || !globalData->addRecord(unwrappedRecord)) {
106 return false;
107 }
108 auto globalDataGuard = mozilla::MakeScopeExit(
109 [&] { globalData->removeRecord(unwrappedRecord); });
110
111 auto ptr = recordMap.lookupForAdd(target);
112 if (!ptr && !recordMap.add(ptr, target, RecordVector(zone))) {
113 return false;
114 }
115
116 if (!ptr->value().append(record)) {
117 return false;
118 }
119
120 unwrappedRecord->setInRecordMap(true);
121
122 globalDataGuard.release();
123 wrapperGuard.release();
124 return true;
125 }
126
127 bool FinalizationObservers::addCrossZoneWrapper(WrapperWeakSet& weakSet,
128 JSObject* wrapper) {
129 MOZ_ASSERT(IsCrossCompartmentWrapper(wrapper));
130 MOZ_ASSERT(UncheckedUnwrapWithoutExpose(wrapper)->zone() != zone);
131
132 auto ptr = weakSet.lookupForAdd(wrapper);
133 MOZ_ASSERT(!ptr);
134 return weakSet.add(ptr, wrapper, UndefinedValue());
135 }
136
137 void FinalizationObservers::removeCrossZoneWrapper(WrapperWeakSet& weakSet,
138 JSObject* wrapper) {
139 MOZ_ASSERT(IsCrossCompartmentWrapper(wrapper));
140 MOZ_ASSERT(UncheckedUnwrapWithoutExpose(wrapper)->zone() != zone);
141
142 auto ptr = weakSet.lookupForAdd(wrapper);
143 MOZ_ASSERT(ptr);
144 weakSet.remove(ptr);
145 }
146
147 static FinalizationRecordObject* UnwrapFinalizationRecord(JSObject* obj) {
148 obj = UncheckedUnwrapWithoutExpose(obj);
149 if (!obj->is<FinalizationRecordObject>()) {
150 MOZ_ASSERT(JS_IsDeadWrapper(obj));
151 // CCWs between the compartments have been nuked. The
152 // FinalizationRegistry's callback doesn't run in this case.
153 return nullptr;
154 }
155 return &obj->as<FinalizationRecordObject>();
156 }
157
158 void FinalizationObservers::clearRecords() {
159 // Clear table entries related to FinalizationRecordObjects, which are not
160 // processed after the start of shutdown.
161 //
162 // WeakRefs are still updated during shutdown to avoid the possibility of
163 // stale or dangling pointers.
164
165 #ifdef DEBUG
166 checkTables();
167 #endif
168
169 recordMap.clear();
170 crossZoneRecords.clear();
171 }
172
173 void GCRuntime::traceWeakFinalizationObserverEdges(JSTracer* trc, Zone* zone) {
174 MOZ_ASSERT(CurrentThreadCanAccessRuntime(trc->runtime()));
175 FinalizationObservers* observers = zone->finalizationObservers();
176 if (observers) {
177 observers->traceWeakEdges(trc);
178 }
179 }
180
181 void FinalizationObservers::traceRoots(JSTracer* trc) {
182 // The cross-zone wrapper weak maps are traced as roots; this does not keep
183 // any of their entries alive by itself.
184 crossZoneRecords.trace(trc);
185 crossZoneWeakRefs.trace(trc);
186 }
187
188 void FinalizationObservers::traceWeakEdges(JSTracer* trc) {
189 // Removing dead pointers from vectors may reorder live pointers to gray
190 // things in the vector. This is OK.
191 AutoTouchingGrayThings atgt;
192
193 traceWeakWeakRefEdges(trc);
194 traceWeakFinalizationRegistryEdges(trc);
195 }
196
197 void FinalizationObservers::traceWeakFinalizationRegistryEdges(JSTracer* trc) {
198 // Sweep finalization registry data and queue finalization records for cleanup
199 // for any entries whose target is dying and remove them from the map.
200
201 GCRuntime* gc = &trc->runtime()->gc;
202
203 for (RegistrySet::Enum e(registries); !e.empty(); e.popFront()) {
204 auto result = TraceWeakEdge(trc, &e.mutableFront(), "FinalizationRegistry");
205 if (result.isDead()) {
206 auto* registry =
207 &result.initialTarget()->as<FinalizationRegistryObject>();
208 registry->queue()->setHasRegistry(false);
209 e.removeFront();
210 } else {
211 result.finalTarget()->as<FinalizationRegistryObject>().traceWeak(trc);
212 }
213 }
214
215 for (RecordMap::Enum e(recordMap); !e.empty(); e.popFront()) {
216 RecordVector& records = e.front().value();
217
218 // Sweep finalization records, updating any pointers moved by the GC and
219 // remove if necessary.
220 records.mutableEraseIf([&](HeapPtr<JSObject*>& heapPtr) {
221 auto result = TraceWeakEdge(trc, &heapPtr, "FinalizationRecord");
222 JSObject* obj =
223 result.isLive() ? result.finalTarget() : result.initialTarget();
224 FinalizationRecordObject* record = UnwrapFinalizationRecord(obj);
225 MOZ_ASSERT_IF(record, record->isInRecordMap());
226
227 bool shouldRemove = !result.isLive() || shouldRemoveRecord(record);
228 if (shouldRemove && record && record->isInRecordMap()) {
229 updateForRemovedRecord(obj, record);
230 }
231
232 return shouldRemove;
233 });
234
235 #ifdef DEBUG
236 for (JSObject* obj : records) {
237 MOZ_ASSERT(UnwrapFinalizationRecord(obj)->isInRecordMap());
238 }
239 #endif
240
241 // Queue finalization records for targets that are dying.
242 if (!TraceWeakEdge(trc, &e.front().mutableKey(),
243 "FinalizationRecord target")) {
244 for (JSObject* obj : records) {
245 FinalizationRecordObject* record = UnwrapFinalizationRecord(obj);
246 FinalizationQueueObject* queue = record->queue();
247 updateForRemovedRecord(obj, record);
248 queue->queueRecordToBeCleanedUp(record);
249 gc->queueFinalizationRegistryForCleanup(queue);
250 }
251 e.removeFront();
252 }
253 }
254 }
255
256 // static
257 bool FinalizationObservers::shouldRemoveRecord(
258 FinalizationRecordObject* record) {
259 // Records are removed from the target's vector for the following reasons:
260 return !record || // Nuked CCW to record.
261 !record->isRegistered() || // Unregistered record.
262 !record->queue()->hasRegistry(); // Dead finalization registry.
263 }
264
265 void FinalizationObservers::updateForRemovedRecord(
266 JSObject* wrapper, FinalizationRecordObject* record) {
267 // Remove other references to a record when it has been removed from the
268 // zone's record map. See addRecord().
269 MOZ_ASSERT(record->isInRecordMap());
270
271 Zone* registryZone = record->zone();
272 if (registryZone != zone) {
273 removeCrossZoneWrapper(crossZoneRecords, wrapper);
274 }
275
276 GlobalObject* registryGlobal = &record->global();
277 auto* globalData = registryGlobal->maybeFinalizationRegistryData();
278 globalData->removeRecord(record);
279
280 // The removed record may be gray, and that's OK.
281 AutoTouchingGrayThings atgt;
282
283 record->setInRecordMap(false);
284 }
285
286 void GCRuntime::nukeFinalizationRecordWrapper(
287 JSObject* wrapper, FinalizationRecordObject* record) {
288 // The target of the nuked wrapper may be gray, and that's OK.
289 AutoTouchingGrayThings atgt;
290
291 if (record->isInRecordMap()) {
292 FinalizationRegistryObject::unregisterRecord(record);
293 FinalizationObservers* observers = wrapper->zone()->finalizationObservers();
294 observers->updateForRemovedRecord(wrapper, record);
295 }
296 }
297
298 void GCRuntime::queueFinalizationRegistryForCleanup(
299 FinalizationQueueObject* queue) {
300 // Prod the embedding to call us back later to run the finalization callbacks,
301 // if necessary.
302
303 if (queue->isQueuedForCleanup()) {
304 return;
305 }
306
307 JSObject* unwrappedHostDefineData = nullptr;
308
309 if (JSObject* wrapped = queue->getHostDefinedData()) {
310 unwrappedHostDefineData = UncheckedUnwrapWithoutExpose(wrapped);
311 MOZ_ASSERT(unwrappedHostDefineData);
312 // If the hostDefined object becomes a dead wrapper here, the target global
313 // has already gone, and the finalization callback won't do anything to it
314 // anyway.
315 if (JS_IsDeadWrapper(unwrappedHostDefineData)) {
316 return;
317 }
318 }
319
320 callHostCleanupFinalizationRegistryCallback(queue->doCleanupFunction(),
321 unwrappedHostDefineData);
322
323 // The queue object may be gray, and that's OK.
324 AutoTouchingGrayThings atgt;
325
326 queue->setQueuedForCleanup(true);
327 }
328
329 // Insert a target -> weakRef mapping in the target's Zone so that a dying
330 // target will clear out the weakRef's target. If the weakRef is in a different
331 // Zone, then the crossZoneWeakRefs table will keep the weakRef alive. If the
332 // weakRef is in the same Zone, then it must be the actual WeakRefObject and
333 // not a cross-compartment wrapper, since nothing would keep that alive.
334 bool GCRuntime::registerWeakRef(HandleObject target, HandleObject weakRef) {
335 MOZ_ASSERT(!IsCrossCompartmentWrapper(target));
336 MOZ_ASSERT(UncheckedUnwrap(weakRef)->is<WeakRefObject>());
337 MOZ_ASSERT_IF(target->zone() != weakRef->zone(),
338 target->compartment() == weakRef->compartment());
339
340 Zone* zone = target->zone();
341 return zone->ensureFinalizationObservers() &&
342 zone->finalizationObservers()->addWeakRefTarget(target, weakRef);
343 }
344
345 bool FinalizationObservers::addWeakRefTarget(HandleObject target,
346 HandleObject weakRef) {
347 WeakRefObject* unwrappedWeakRef =
348 &UncheckedUnwrapWithoutExpose(weakRef)->as<WeakRefObject>();
349
350 Zone* weakRefZone = unwrappedWeakRef->zone();
351 bool crossZone = weakRefZone != zone;
352 if (crossZone && !addCrossZoneWrapper(crossZoneWeakRefs, weakRef)) {
353 return false;
354 }
355 auto wrapperGuard = mozilla::MakeScopeExit([&] {
356 if (crossZone) {
357 removeCrossZoneWrapper(crossZoneWeakRefs, weakRef);
358 }
359 });
360
361 auto ptr = weakRefMap.lookupForAdd(target);
362 if (!ptr && !weakRefMap.add(ptr, target, WeakRefHeapPtrVector(zone))) {
363 return false;
364 }
365
366 if (!ptr->value().emplaceBack(weakRef)) {
367 return false;
368 }
369
370 wrapperGuard.release();
371 return true;
372 }
373
374 static WeakRefObject* UnwrapWeakRef(JSObject* obj) {
375 MOZ_ASSERT(!JS_IsDeadWrapper(obj));
376 obj = UncheckedUnwrapWithoutExpose(obj);
377 return &obj->as<WeakRefObject>();
378 }
379
380 void FinalizationObservers::removeWeakRefTarget(
381 Handle<JSObject*> target, Handle<WeakRefObject*> weakRef) {
382 MOZ_ASSERT(target);
383
384 WeakRefHeapPtrVector& weakRefs = weakRefMap.lookup(target)->value();
385 JSObject* wrapper = nullptr;
386 weakRefs.eraseIf([weakRef, &wrapper](JSObject* obj) {
387 if (UnwrapWeakRef(obj) == weakRef) {
388 wrapper = obj;
389 return true;
390 }
391 return false;
392 });
393
394 MOZ_ASSERT(wrapper);
395 updateForRemovedWeakRef(wrapper, weakRef);
396 }
397
398 void GCRuntime::nukeWeakRefWrapper(JSObject* wrapper, WeakRefObject* weakRef) {
399 // WeakRef wrappers can exist independently of the ones we create for the
400 // weakRefMap so don't assume |wrapper| is in the same zone as the WeakRef
401 // target.
402 JSObject* target = weakRef->target();
403 if (!target) {
404 return;
405 }
406
407 FinalizationObservers* observers = target->zone()->finalizationObservers();
408 if (observers) {
409 observers->unregisterWeakRefWrapper(wrapper, weakRef);
410 }
411 }
412
413 void FinalizationObservers::unregisterWeakRefWrapper(JSObject* wrapper,
414 WeakRefObject* weakRef) {
415 JSObject* target = weakRef->target();
416 MOZ_ASSERT(target);
417
418 bool removed = false;
419 WeakRefHeapPtrVector& weakRefs = weakRefMap.lookup(target)->value();
420 weakRefs.eraseIf([wrapper, &removed](JSObject* obj) {
421 bool remove = obj == wrapper;
422 if (remove) {
423 removed = true;
424 }
425 return remove;
426 });
427
428 if (removed) {
429 updateForRemovedWeakRef(wrapper, weakRef);
430 }
431 }
432
433 void FinalizationObservers::updateForRemovedWeakRef(JSObject* wrapper,
434 WeakRefObject* weakRef) {
435 weakRef->clearTarget();
436
437 Zone* weakRefZone = weakRef->zone();
438 if (weakRefZone != zone) {
439 removeCrossZoneWrapper(crossZoneWeakRefs, wrapper);
440 }
441 }
442
443 void FinalizationObservers::traceWeakWeakRefEdges(JSTracer* trc) {
444 for (WeakRefMap::Enum e(weakRefMap); !e.empty(); e.popFront()) {
445 // If target is dying, clear the target field of all weakRefs, and remove
446 // the entry from the map.
447 auto result = TraceWeakEdge(trc, &e.front().mutableKey(), "WeakRef target");
448 if (result.isDead()) {
449 for (JSObject* obj : e.front().value()) {
450 updateForRemovedWeakRef(obj, UnwrapWeakRef(obj));
451 }
452 e.removeFront();
453 } else {
454 // Update the target field after compacting.
455 traceWeakWeakRefVector(trc, e.front().value(), result.finalTarget());
456 }
457 }
458 }
459
460 void FinalizationObservers::traceWeakWeakRefVector(
461 JSTracer* trc, WeakRefHeapPtrVector& weakRefs, JSObject* target) {
462 weakRefs.mutableEraseIf([&](HeapPtr<JSObject*>& obj) -> bool {
463 auto result = TraceWeakEdge(trc, &obj, "WeakRef");
464 if (result.isDead()) {
465 JSObject* wrapper = result.initialTarget();
466 updateForRemovedWeakRef(wrapper, UnwrapWeakRef(wrapper));
467 } else {
468 UnwrapWeakRef(result.finalTarget())->setTargetUnbarriered(target);
469 }
470 return result.isDead();
471 });
472 }
473
474 #ifdef DEBUG
475 void FinalizationObservers::checkTables() const {
476 // Check all cross-zone wrappers are present in the appropriate table.
477 size_t recordCount = 0;
478 for (auto r = recordMap.all(); !r.empty(); r.popFront()) {
479 for (JSObject* object : r.front().value()) {
480 FinalizationRecordObject* record = UnwrapFinalizationRecord(object);
481 if (record && record->isInRecordMap() && record->zone() != zone) {
482 MOZ_ASSERT(crossZoneRecords.has(object));
483 recordCount++;
484 }
485 }
486 }
487 MOZ_ASSERT(crossZoneRecords.count() == recordCount);
488
489 size_t weakRefCount = 0;
490 for (auto r = weakRefMap.all(); !r.empty(); r.popFront()) {
491 for (JSObject* object : r.front().value()) {
492 WeakRefObject* weakRef = UnwrapWeakRef(object);
493 if (weakRef && weakRef->zone() != zone) {
494 MOZ_ASSERT(crossZoneWeakRefs.has(object));
495 weakRefCount++;
496 }
497 }
498 }
499 MOZ_ASSERT(crossZoneWeakRefs.count() == weakRefCount);
500 }
501 #endif
502
503 FinalizationRegistryGlobalData::FinalizationRegistryGlobalData(Zone* zone)
504 : recordSet(zone) {}
505
506 bool FinalizationRegistryGlobalData::addRecord(
507 FinalizationRecordObject* record) {
508 return recordSet.putNew(record);
509 }
510
511 void FinalizationRegistryGlobalData::removeRecord(
512 FinalizationRecordObject* record) {
513 MOZ_ASSERT_IF(!record->runtimeFromMainThread()->gc.isShuttingDown(),
514 recordSet.has(record));
515 recordSet.remove(record);
516 }
517
518 void FinalizationRegistryGlobalData::trace(JSTracer* trc) {
519 recordSet.trace(trc);
520 }
521
522 JS_PUBLIC_API void JS::MaybeClearWeakRefTargets(
523 JSRuntime* runtime, JS::ShouldClearWeakRefTargetCallback callback,
524 void* data) {
525 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime));
526 AssertHeapIsIdle();
527 runtime->gc.maybeClearWeakRefTargets(callback, data);
528 }
529
530 void GCRuntime::maybeClearWeakRefTargets(
531 JS::ShouldClearWeakRefTargetCallback callback, void* data) {
532 for (AllZonesIter zone(this); !zone.done(); zone.next()) {
533 FinalizationObservers* observers = zone->finalizationObservers();
534 if (observers) {
535 observers->maybeClearWeakRefTargets(callback, data);
536 }
537 }
538 }
539
540 void FinalizationObservers::maybeClearWeakRefTargets(
541 JS::ShouldClearWeakRefTargetCallback callback, void* data) {
542 for (auto iter = weakRefMap.modIter(); !iter.done(); iter.next()) {
543 JSObject* target = iter.get().key();
544 if (callback(JS::GCCellPtr(target), data)) {
545 for (JSObject* obj : iter.get().value()) {
546 updateForRemovedWeakRef(obj, UnwrapWeakRef(obj));
547 }
548 iter.remove();
549 }
550 }
551 }