Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 50 additions & 6 deletions core/engine/src/object/shape/shared_shape/forward_transition.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,48 @@
use std::fmt::Debug;

use boa_gc::{Finalize, Gc, GcRefCell, Trace, WeakGc};
use boa_gc::{Finalize, Gc, GcRefCell, Trace, WeakGc, empty_trace};
use rustc_hash::FxHashMap;

use crate::object::JsPrototype;

use super::{Inner as SharedShapeInner, TransitionKey};

/// Identity of a prototype transition.
///
/// This deliberately stores the address of the prototype instead of a strong
/// reference to it. A prototype can (indirectly) reference an object that uses
/// the transitioned shape, and therefore reach the shape that owns this map.
/// Keeping the prototype alive here would close that cycle and retain the
/// prototype, the shape and everything reachable from them for as long as the
/// shape holding this map is alive (for example the root shape of the realm).
///
/// The address is enough to identify the prototype because every shape stored
/// under this key strongly references the prototype it was created for, so an
/// entry whose shape is still alive can only match that same live prototype.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Finalize)]
struct PrototypeTransitionKey(usize);

// SAFETY: The key only stores an address, no garbage collected value is held.
unsafe impl Trace for PrototypeTransitionKey {
empty_trace!();
}

impl PrototypeTransitionKey {
/// Creates the transition key of a prototype.
///
/// The `null` prototype is represented by the address `0`, which can never
/// be the address of an allocation.
fn new(prototype: &JsPrototype) -> Self {
match prototype {
Some(prototype) => {
let ptr: *const _ = prototype.inner().as_ref();
Self(ptr as usize)
}
None => Self(0),
}
}
}

/// Maps transition key type to a [`SharedShapeInner`] transition.
#[derive(Debug, Trace, Finalize)]
struct TransitionMap<T: Debug + Trace + Finalize> {
Expand Down Expand Up @@ -41,7 +77,7 @@ impl<T: Debug + Trace + Finalize> TransitionMap<T> {
#[derive(Default, Debug, Trace, Finalize)]
struct Inner {
properties: Option<Box<TransitionMap<TransitionKey>>>,
prototypes: Option<Box<TransitionMap<JsPrototype>>>,
prototypes: Option<Box<TransitionMap<PrototypeTransitionKey>>>,
}

/// Holds a forward reference to a previously created transition.
Expand All @@ -66,15 +102,17 @@ impl ForwardTransition {
}

/// Insert a prototype transition.
pub(super) fn insert_prototype(&self, key: JsPrototype, value: &Gc<SharedShapeInner>) {
pub(super) fn insert_prototype(&self, key: &JsPrototype, value: &Gc<SharedShapeInner>) {
let mut this = self.inner.borrow_mut();
let prototypes = this.prototypes.get_or_insert_with(Box::default);

if prototypes.get_and_increment_count() == u8::MAX {
prototypes.map.retain(|_, v| v.is_upgradable());
}

prototypes.map.insert(key, WeakGc::new(value));
prototypes
.map
.insert(PrototypeTransitionKey::new(key), WeakGc::new(value));
}

/// Get a property transition, return [`None`] otherwise.
Expand All @@ -88,7 +126,10 @@ impl ForwardTransition {
pub(super) fn get_prototype(&self, key: &JsPrototype) -> Option<WeakGc<SharedShapeInner>> {
let this = self.inner.borrow();
let transitions = this.prototypes.as_ref()?;
transitions.map.get(key).cloned()
transitions
.map
.get(&PrototypeTransitionKey::new(key))
.cloned()
}

/// Prunes the [`WeakGc`]s that have been garbage collected.
Expand All @@ -103,13 +144,16 @@ impl ForwardTransition {
}

/// Prunes the [`WeakGc`]s that have been garbage collected.
///
/// The insertion counter is intentionally left untouched, so that this
/// opportunistic cleanup doesn't delay the periodic prune that would have
/// happened anyway.
pub(super) fn prune_prototype_transitions(&self) {
let mut this = self.inner.borrow_mut();
let Some(transitions) = this.prototypes.as_deref_mut() else {
return;
};

transitions.insertion_count_since_prune = 0;
transitions.map.retain(|_, v| v.is_upgradable());
}

Expand Down
4 changes: 2 additions & 2 deletions core/engine/src/object/shape/shared_shape/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ impl SharedShape {
}
let new_inner_shape = Inner {
forward_transitions: ForwardTransition::default(),
prototype: prototype.clone(),
prototype,
property_table: self.property_table().clone(),
property_count: self.property_count(),
previous: Some(self.clone()),
Expand All @@ -206,7 +206,7 @@ impl SharedShape {
let new_shape = Self::new(new_inner_shape);

self.forward_transitions()
.insert_prototype(prototype, &new_shape.inner);
.insert_prototype(&new_shape.prototype(), &new_shape.inner);

new_shape
}
Expand Down
66 changes: 58 additions & 8 deletions core/engine/src/object/shape/shared_shape/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
use crate::{JsObject, JsSymbol, object::shape::slot::SlotAttributes, property::PropertyKey};
use crate::{
JsObject, JsSymbol,
object::{WeakJsObject, shape::slot::SlotAttributes},
property::PropertyKey,
};

use super::{SharedShape, TransitionKey};

Expand Down Expand Up @@ -66,13 +70,19 @@ fn test_prune_prototype_on_counter_limit() {
(0, 0)
);

// Keep the prototypes alive, otherwise their addresses can be reused by the
// next allocation and the entries would be replaced instead of added.
let mut kept_alive = Vec::with_capacity(256);

for i in 0..255 {
assert_eq!(
shape.forward_transitions().prototype_transitions_count(),
(i, i as u8)
);

shape.change_prototype_transition(Some(JsObject::with_null_proto()));
let prototype = JsObject::with_null_proto();
kept_alive.push(prototype.clone());
shape.change_prototype_transition(Some(prototype));
}

boa_gc::force_collect();
Expand All @@ -82,18 +92,28 @@ fn test_prune_prototype_on_counter_limit() {
(255, 255)
);

{
shape.change_prototype_transition(Some(JsObject::with_null_proto()));
}
// The prototypes are unreachable now, but they are pruned on the next
// insertion, when the counter limit is reached.
kept_alive.clear();
boa_gc::force_collect();

assert_eq!(
shape.forward_transitions().prototype_transitions_count(),
(255, 255)
);

let prototype = JsObject::with_null_proto();
kept_alive.push(prototype.clone());
shape.change_prototype_transition(Some(prototype));

assert_eq!(
shape.forward_transitions().prototype_transitions_count(),
(1, 0)
);

{
shape.change_prototype_transition(Some(JsObject::with_null_proto()));
}
let prototype = JsObject::with_null_proto();
kept_alive.push(prototype.clone());
shape.change_prototype_transition(Some(prototype));

assert_eq!(
shape.forward_transitions().prototype_transitions_count(),
Expand All @@ -107,3 +127,33 @@ fn test_prune_prototype_on_counter_limit() {
(2, 1)
);
}

#[test]
fn test_prototype_transition_is_reused() {
let shape = SharedShape::root();
let prototype = JsObject::with_null_proto();

let first = shape.change_prototype_transition(Some(prototype.clone()));
let second = shape.change_prototype_transition(Some(prototype));

assert_eq!(first.to_addr_usize(), second.to_addr_usize());
}

#[test]
fn test_prototype_transition_does_not_keep_prototype_alive() {
let shape = SharedShape::root();

let weak_prototype = {
let prototype = JsObject::with_null_proto();
let weak_prototype = WeakJsObject::new(&prototype);
shape.change_prototype_transition(Some(prototype));
weak_prototype
};

boa_gc::force_collect();

assert!(
weak_prototype.upgrade().is_none(),
"the prototype transition should not keep the prototype alive"
);
}