Debian Codegraph @

js/src/vm/Compartment.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 vm_Compartment_h
8 #define vm_Compartment_h
9
10 #include "mozilla/Maybe.h"
11 #include "mozilla/MemoryReporting.h"
12
13 #include <stddef.h>
14 #include <utility>
15
16 #include "gc/NurseryAwareHashMap.h"
17 #include "gc/ZoneAllocator.h"
18 #include "vm/Iteration.h"
19 #include "vm/JSObject.h"
20 #include "vm/JSScript.h"
21
22 namespace js {
23
24 JSString* CopyStringPure(JSContext* cx, JSString* str);
25
26 // The data structure use to storing JSObject CCWs for a given source
27 // compartment. These are partitioned by target compartment so that we can
28 // easily select wrappers by source and target compartment. String CCWs are
29 // stored in a per-zone separate map.
30 class ObjectWrapperMap {
31 static const size_t InitialInnerMapSize = 4;
32
33 using InnerMap = NurseryAwareHashMap<JSObject*, JSObject*, ZoneAllocPolicy>;
34 using OuterMap = GCHashMap<JS::Compartment*, InnerMap,
35 DefaultHasher<JS::Compartment*>, ZoneAllocPolicy>;
36
37 OuterMap map;
38 Zone* zone;
39
40 public:
41 class Enum {
42 Enum(const Enum&) = delete;
43 void operator=(const Enum&) = delete;
44
45 void goToNext() {
46 if (outer.isNothing()) {
47 return;
48 }
49 for (; !outer->empty(); outer->popFront()) {
50 JS::Compartment* c = outer->front().key();
51 MOZ_ASSERT(c);
52 if (filter && !filter->match(c)) {
53 continue;
54 }
55 InnerMap& m = outer->front().value();
56 if (!m.empty()) {
57 if (inner.isSome()) {
58 inner.reset();
59 }
60 inner.emplace(m);
61 outer->popFront();
62 return;
63 }
64 }
65 }
66
67 mozilla::Maybe<OuterMap::Enum> outer;
68 mozilla::Maybe<InnerMap::Enum> inner;
69 const CompartmentFilter* filter;
70
71 public:
72 explicit Enum(ObjectWrapperMap& m) : filter(nullptr) {
73 outer.emplace(m.map);
74 goToNext();
75 }
76
77 Enum(ObjectWrapperMap& m, const CompartmentFilter& f) : filter(&f) {
78 outer.emplace(m.map);
79 goToNext();
80 }
81
82 Enum(ObjectWrapperMap& m, JS::Compartment* target) {
83 // Leave the outer map as nothing and only iterate the inner map we
84 // find here.
85 auto p = m.map.lookup(target);
86 if (p) {
87 inner.emplace(p->value());
88 }
89 }
90
91 bool empty() const {
92 return (outer.isNothing() || outer->empty()) &&
93 (inner.isNothing() || inner->empty());
94 }
95
96 InnerMap::Entry& front() const {
97 MOZ_ASSERT(inner.isSome() && !inner->empty());
98 return inner->front();
99 }
100
101 void popFront() {
102 MOZ_ASSERT(!empty());
103 if (!inner->empty()) {
104 inner->popFront();
105 if (!inner->empty()) {
106 return;
107 }
108 }
109 goToNext();
110 }
111
112 void removeFront() {
113 MOZ_ASSERT(inner.isSome());
114 inner->removeFront();
115 }
116 };
117
118 class Ptr : public InnerMap::Ptr {
119 friend class ObjectWrapperMap;
120
121 InnerMap* map;
122
123 Ptr() : map(nullptr) {}
124 Ptr(const InnerMap::Ptr& p, InnerMap& m) : InnerMap::Ptr(p), map(&m) {}
125 };
126
127 // Iterator over compartments that the ObjectWrapperMap has wrappers for.
128 class WrappedCompartmentEnum {
129 OuterMap::Enum iter;
130
131 void settle() {
132 // It's possible for InnerMap to be empty after wrappers have been
133 // removed, e.g. by being nuked.
134 while (!iter.empty() && iter.front().value().empty()) {
135 iter.popFront();
136 }
137 }
138
139 public:
140 explicit WrappedCompartmentEnum(ObjectWrapperMap& map) : iter(map.map) {
141 settle();
142 }
143 bool empty() const { return iter.empty(); }
144 JS::Compartment* front() const { return iter.front().key(); }
145 operator JS::Compartment*() const { return front(); }
146 void popFront() {
147 iter.popFront();
148 settle();
149 }
150 };
151
152 explicit ObjectWrapperMap(Zone* zone) : map(zone), zone(zone) {}
153 ObjectWrapperMap(Zone* zone, size_t aLen) : map(zone, aLen), zone(zone) {}
154
155 bool empty() {
156 if (map.empty()) {
157 return true;
158 }
159 for (OuterMap::Enum e(map); !e.empty(); e.popFront()) {
160 if (!e.front().value().empty()) {
161 return false;
162 }
163 }
164 return true;
165 }
166
167 Ptr lookup(JSObject* obj) const {
168 auto op = map.lookup(obj->compartment());
169 if (op) {
170 auto ip = op->value().lookup(obj);
171 if (ip) {
172 return Ptr(ip, op->value());
173 }
174 }
175 return Ptr();
176 }
177
178 void remove(Ptr p) {
179 if (p) {
180 p.map->remove(p);
181 }
182 }
183
184 [[nodiscard]] bool put(JSObject* key, JSObject* value) {
185 JS::Compartment* comp = key->compartment();
186 auto ptr = map.lookupForAdd(comp);
187 if (!ptr) {
188 InnerMap m(zone, InitialInnerMapSize);
189 if (!map.add(ptr, comp, std::move(m))) {
190 return false;
191 }
192 }
193 return ptr->value().put(key, value);
194 }
195
196 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) {
197 size_t size = map.shallowSizeOfExcludingThis(mallocSizeOf);
198 for (OuterMap::Enum e(map); !e.empty(); e.popFront()) {
199 size += e.front().value().sizeOfExcludingThis(mallocSizeOf);
200 }
201 return size;
202 }
203 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) {
204 return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf);
205 }
206
207 bool hasNurseryAllocatedWrapperEntries(const CompartmentFilter& f) {
208 for (OuterMap::Enum e(map); !e.empty(); e.popFront()) {
209 JS::Compartment* c = e.front().key();
210 if (c && !f.match(c)) {
211 continue;
212 }
213 InnerMap& m = e.front().value();
214 if (m.hasNurseryEntries()) {
215 return true;
216 }
217 }
218 return false;
219 }
220
221 void sweepAfterMinorGC(JSTracer* trc) {
222 for (OuterMap::Enum e(map); !e.empty(); e.popFront()) {
223 InnerMap& m = e.front().value();
224 m.sweepAfterMinorGC(trc);
225 if (m.empty()) {
226 e.removeFront();
227 }
228 }
229 }
230
231 void traceWeak(JSTracer* trc) {
232 for (OuterMap::Enum e(map); !e.empty(); e.popFront()) {
233 InnerMap& m = e.front().value();
234 m.traceWeak(trc);
235 if (m.empty()) {
236 e.removeFront();
237 }
238 }
239 }
240 };
241
242 using StringWrapperMap =
243 NurseryAwareHashMap<JSString*, JSString*, ZoneAllocPolicy,
244 DuplicatesPossible>;
245
246 } // namespace js
247
248 class JS::Compartment {
249 JS::Zone* zone_;
250 JSRuntime* runtime_;
251 bool invisibleToDebugger_;
252
253 js::ObjectWrapperMap crossCompartmentObjectWrappers;
254
255 using RealmVector = js::Vector<JS::Realm*, 1, js::ZoneAllocPolicy>;
256 RealmVector realms_;
257
258 public:
259 /*
260 * During GC, stores the head of a list of incoming pointers from gray cells.
261 *
262 * The objects in the list are either cross-compartment wrappers, or
263 * debugger wrapper objects. The list link is either in the second extra
264 * slot for the former, or a special slot for the latter.
265 */
266 JSObject* gcIncomingGrayPointers = nullptr;
267
268 void* data = nullptr;
269
270 // Fields set and used by the GC. Be careful, may be stale after we return
271 // to the mutator.
272 struct {
273 // These flags help us to discover if a compartment that shouldn't be
274 // alive manages to outlive a GC. Note that these flags have to be on
275 // the compartment, not the realm, because same-compartment realms can
276 // have cross-realm pointers without wrappers.
277 bool scheduledForDestruction = false;
278 bool hasMarkedCells = false;
279 bool maybeAlive = true;
280
281 // During GC, we may set this to |true| if we entered a realm in this
282 // compartment. Note that (without a stack walk) we don't know exactly
283 // *which* realms, because Realm::enterRealmDepthIgnoringJit_ does not
284 // account for cross-Realm calls in JIT code updating cx->realm_. See
285 // also the enterRealmDepthIgnoringJit_ comment.
286 bool hasEnteredRealm = false;
287 } gcState;
288
289 // True if all outgoing wrappers have been nuked. This happens when all realms
290 // have been nuked and NukeCrossCompartmentWrappers is called with the
291 // NukeAllReferences option. This prevents us from creating new wrappers for
292 // the compartment.
293 bool nukedOutgoingWrappers = false;
294
295 JS::Zone* zone() { return zone_; }
296 const JS::Zone* zone() const { return zone_; }
297
298 JSRuntime* runtimeFromMainThread() const {
299 MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_));
300 return runtime_;
301 }
302
303 // Note: Unrestricted access to the zone's runtime from an arbitrary
304 // thread can easily lead to races. Use this method very carefully.
305 JSRuntime* runtimeFromAnyThread() const { return runtime_; }
306
307 // Certain compartments are implementation details of the embedding, and
308 // references to them should never leak out to script. For realms belonging to
309 // this compartment, onNewGlobalObject does not fire, and addDebuggee is a
310 // no-op.
311 bool invisibleToDebugger() const { return invisibleToDebugger_; }
312
313 RealmVector& realms() { return realms_; }
314
315 // Cross-compartment wrappers are shared by all realms in the compartment, but
316 // they still have a per-realm ObjectGroup etc. To prevent us from having
317 // multiple realms, each with some cross-compartment wrappers potentially
318 // keeping the realm alive longer than necessary, we always allocate CCWs in
319 // the first realm.
320 js::GlobalObject& firstGlobal() const;
321 js::GlobalObject& globalForNewCCW() const { return firstGlobal(); }
322
323 void assertNoCrossCompartmentWrappers() {
324 MOZ_ASSERT(crossCompartmentObjectWrappers.empty());
325 }
326
327 void addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf,
328 size_t* compartmentObjects,
329 size_t* crossCompartmentWrappersTables,
330 size_t* compartmentsPrivateData);
331
332 #ifdef JSGC_HASH_TABLE_CHECKS
333 void checkObjectWrappersAfterMovingGC();
334 #endif
335
336 private:
337 bool getNonWrapperObjectForCurrentCompartment(JSContext* cx,
338 js::HandleObject origObj,
339 js::MutableHandleObject obj);
340 bool getOrCreateWrapper(JSContext* cx, js::HandleObject existing,
341 js::MutableHandleObject obj);
342
343 public:
344 explicit Compartment(JS::Zone* zone, bool invisibleToDebugger);
345
346 void destroy(JS::GCContext* gcx);
347
348 [[nodiscard]] inline bool wrap(JSContext* cx, JS::MutableHandleValue vp);
349
350 [[nodiscard]] inline bool wrap(JSContext* cx,
351 MutableHandle<mozilla::Maybe<Value>> vp);
352
353 [[nodiscard]] bool wrap(JSContext* cx, js::MutableHandleString strp);
354 [[nodiscard]] bool wrap(JSContext* cx, js::MutableHandle<JS::BigInt*> bi);
355 [[nodiscard]] bool wrap(JSContext* cx, JS::MutableHandleObject obj);
356 [[nodiscard]] bool wrap(JSContext* cx,
357 JS::MutableHandle<JS::PropertyDescriptor> desc);
358 [[nodiscard]] bool wrap(
359 JSContext* cx,
360 JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> desc);
361 [[nodiscard]] bool wrap(JSContext* cx,
362 JS::MutableHandle<JS::GCVector<JS::Value>> vec);
363 [[nodiscard]] bool rewrap(JSContext* cx, JS::MutableHandleObject obj,
364 JS::HandleObject existing);
365
366 [[nodiscard]] bool putWrapper(JSContext* cx, JSObject* wrapped,
367 JSObject* wrapper);
368
369 [[nodiscard]] bool putWrapper(JSContext* cx, JSString* wrapped,
370 JSString* wrapper);
371
372 js::ObjectWrapperMap::Ptr lookupWrapper(JSObject* obj) const {
373 return crossCompartmentObjectWrappers.lookup(obj);
374 }
375
376 inline js::StringWrapperMap::Ptr lookupWrapper(JSString* str) const;
377
378 void removeWrapper(js::ObjectWrapperMap::Ptr p);
379
380 bool hasNurseryAllocatedObjectWrapperEntries(const js::CompartmentFilter& f) {
381 return crossCompartmentObjectWrappers.hasNurseryAllocatedWrapperEntries(f);
382 }
383
384 // Iterator over |wrapped -> wrapper| entries for object CCWs in a given
385 // compartment. Can be optionally restricted by target compartment.
386 struct ObjectWrapperEnum : public js::ObjectWrapperMap::Enum {
387 explicit ObjectWrapperEnum(Compartment* c)
388 : js::ObjectWrapperMap::Enum(c->crossCompartmentObjectWrappers) {}
389 explicit ObjectWrapperEnum(Compartment* c, const js::CompartmentFilter& f)
390 : js::ObjectWrapperMap::Enum(c->crossCompartmentObjectWrappers, f) {}
391 explicit ObjectWrapperEnum(Compartment* c, Compartment* target)
392 : js::ObjectWrapperMap::Enum(c->crossCompartmentObjectWrappers,
393 target) {
394 MOZ_ASSERT(target);
395 }
396 };
397
398 // Iterator over compartments that this compartment has CCWs for.
399 struct WrappedObjectCompartmentEnum
400 : public js::ObjectWrapperMap::WrappedCompartmentEnum {
401 explicit WrappedObjectCompartmentEnum(Compartment* c)
402 : js::ObjectWrapperMap::WrappedCompartmentEnum(
403 c->crossCompartmentObjectWrappers) {}
404 };
405
406 /*
407 * These methods mark pointers that cross compartment boundaries. They are
408 * called in per-zone GCs to prevent the wrappers' outgoing edges from
409 * dangling (full GCs naturally follow pointers across compartments) and
410 * when compacting to update cross-compartment pointers.
411 */
412 enum EdgeSelector { AllEdges, NonGrayEdges, GrayEdges, BlackEdges };
413 void traceWrapperTargetsInCollectedZones(JSTracer* trc,
414 EdgeSelector whichEdges);
415 static void traceIncomingCrossCompartmentEdgesForZoneGC(
416 JSTracer* trc, EdgeSelector whichEdges);
417
418 void sweepRealms(JS::GCContext* gcx, bool keepAtleastOne,
419 bool destroyingRuntime);
420 void sweepAfterMinorGC(JSTracer* trc);
421 void traceCrossCompartmentObjectWrapperEdges(JSTracer* trc);
422
423 void fixupCrossCompartmentObjectWrappersAfterMovingGC(JSTracer* trc);
424 void fixupAfterMovingGC(JSTracer* trc);
425
426 [[nodiscard]] bool findSweepGroupEdges();
427
428 private:
429 // Head node of list of active iterators that may need deleted property
430 // suppression.
431 js::NativeIteratorListHead enumerators_;
432
433 public:
434 js::NativeIteratorListHead* enumeratorsAddr() { return &enumerators_; }
435 MOZ_ALWAYS_INLINE bool objectMaybeInIteration(JSObject* obj);
436
437 void traceWeakNativeIterators(JSTracer* trc);
438 };
439
440 namespace js {
441
442 // We only set the hasMarkedCells flag for objects and scripts. It's assumed
443 // that, if a compartment is alive, then it will have at least some live object
444 // or script it in. Even if we get this wrong, the worst that will happen is
445 // that scheduledForDestruction will be set on the compartment, which will cause
446 // some extra GC activity to try to free the compartment.
447 template <typename T>
448 inline void SetCompartmentHasMarkedCells(T* thing) {}
449
450 template <>
451 inline void SetCompartmentHasMarkedCells(JSObject* thing) {
452 thing->compartment()->gcState.hasMarkedCells = true;
453 }
454
455 template <>
456 inline void SetCompartmentHasMarkedCells(JSScript* thing) {
457 thing->compartment()->gcState.hasMarkedCells = true;
458 }
459
460 /*
461 * AutoWrapperVector and AutoWrapperRooter can be used to store wrappers that
462 * are obtained from the cross-compartment map. However, these classes should
463 * not be used if the wrapper will escape. For example, it should not be stored
464 * in the heap.
465 *
466 * The AutoWrapper rooters are different from other autorooters because their
467 * wrappers are marked on every GC slice rather than just the first one. If
468 * there's some wrapper that we want to use temporarily without causing it to be
469 * marked, we can use these AutoWrapper classes. If we get unlucky and a GC
470 * slice runs during the code using the wrapper, the GC will mark the wrapper so
471 * that it doesn't get swept out from under us. Otherwise, the wrapper needn't
472 * be marked. This is useful in functions like JS_TransplantObject that
473 * manipulate wrappers in compartments that may no longer be alive.
474 */
475
476 /*
477 * This class stores the data for AutoWrapperVector and AutoWrapperRooter. It
478 * should not be used in any other situations.
479 */
480 struct WrapperValue {
481 /*
482 * We use unsafeGet() in the constructors to avoid invoking a read barrier
483 * on the wrapper, which may be dead (see the comment about bug 803376 in
484 * gc/GC.cpp regarding this). If there is an incremental GC while the
485 * wrapper is in use, the AutoWrapper rooter will ensure the wrapper gets
486 * marked.
487 */
488 explicit WrapperValue(const ObjectWrapperMap::Ptr& ptr)
489 : value(*ptr->value().unsafeGet()) {}
490
491 explicit WrapperValue(const ObjectWrapperMap::Enum& e)
492 : value(*e.front().value().unsafeGet()) {}
493
494 JSObject*& get() { return value; }
495 JSObject* get() const { return value; }
496 operator JSObject*() const { return value; }
497
498 private:
499 JSObject* value;
500 };
501
502 class MOZ_RAII AutoWrapperVector : public JS::GCVector<WrapperValue, 8>,
503 public JS::AutoGCRooter {
504 public:
505 explicit AutoWrapperVector(JSContext* cx)
506 : JS::GCVector<WrapperValue, 8>(cx),
507 JS::AutoGCRooter(cx, JS::AutoGCRooter::Kind::WrapperVector) {}
508
509 void trace(JSTracer* trc);
510
511 private:
512 };
513
514 class MOZ_RAII AutoWrapperRooter : public JS::AutoGCRooter {
515 public:
516 AutoWrapperRooter(JSContext* cx, const WrapperValue& v)
517 : JS::AutoGCRooter(cx, JS::AutoGCRooter::Kind::Wrapper), value(v) {}
518
519 operator JSObject*() const { return value; }
520
521 void trace(JSTracer* trc);
522
523 private:
524 WrapperValue value;
525 };
526
527 } /* namespace js */
528
529 #endif /* vm_Compartment_h */