Skip to content

Truly independent web browser

LibJS: Store private elements as properties of their objects

Shannon Bootha9585198cc31
diff --git a/Libraries/LibJS/HostObjectABI.h b/Libraries/LibJS/HostObjectABI.h
index a1a6843d98e..dac181dd5a7 100644
--- a/Libraries/LibJS/HostObjectABI.h
+++ b/Libraries/LibJS/HostObjectABI.h
@@ -32,9 +32,9 @@ enum {
// Layout of every host object of kind JS_HOST_CLASS_OBJECT. Direct getter functions read the wrappable slot without
// checking what it holds, so it only ever holds the embedder's wrapped implementation object. Any other per-object state
-// belongs in the host data slot. The host object's own fields follow the engine's object, which is 56 bytes.
+// belongs in the host data slot. The host object's own fields follow the engine's object, which is 48 bytes.
enum {
- JS_HOST_OBJECT_HOST_CLASS_OFFSET = 56,
+ JS_HOST_OBJECT_HOST_CLASS_OFFSET = 48,
JS_HOST_OBJECT_WRAPPABLE_OFFSET = JS_HOST_OBJECT_HOST_CLASS_OFFSET + 8,
JS_HOST_OBJECT_HOST_DATA_OFFSET = JS_HOST_OBJECT_WRAPPABLE_OFFSET + 8,
JS_HOST_OBJECT_SIZE = JS_HOST_OBJECT_HOST_DATA_OFFSET + 8,
diff --git a/Libraries/LibJS/Rust/generate/layout_forward.rs b/Libraries/LibJS/Rust/generate/layout_forward.rs
index fd16c1675d3..972c52afa56 100644
--- a/Libraries/LibJS/Rust/generate/layout_forward.rs
+++ b/Libraries/LibJS/Rust/generate/layout_forward.rs
@@ -17,9 +17,6 @@ pub struct Module;
pub struct ObjectEnvironment;
pub struct Intrinsics;
-#[repr(transparent)]
-pub struct PrivateElements(usize);
-
#[repr(transparent)]
pub struct FlyStringSlot(usize);
diff --git a/Libraries/LibJS/Rust/src/layout/function_object.rs b/Libraries/LibJS/Rust/src/layout/function_object.rs
index 37a03224d56..6cb4ee973e6 100644
--- a/Libraries/LibJS/Rust/src/layout/function_object.rs
+++ b/Libraries/LibJS/Rust/src/layout/function_object.rs
@@ -31,7 +31,7 @@ pub struct FunctionObject {
pub ecmascript_shared_data: NullableMember<SharedFunctionInstanceData>,
}
-const _: () = assert!(size_of::<FunctionObject>() == 64);
+const _: () = assert!(size_of::<FunctionObject>() == 56);
#[repr(C)]
pub struct NativeFunction {
@@ -45,14 +45,14 @@ pub struct NativeFunction {
pub raw_native_function_index: Cell<u32>,
}
-const _: () = assert!(size_of::<NativeFunction>() == 88);
+const _: () = assert!(size_of::<NativeFunction>() == 80);
#[repr(C)]
pub struct RawNativeFunction {
pub base: NativeFunction,
}
-const _: () = assert!(size_of::<RawNativeFunction>() == 88);
+const _: () = assert!(size_of::<RawNativeFunction>() == 80);
/// A raw native getter that reads a wrapped value straight out of a platform object, at offsets the embedder provides:
/// word offsets of pointer-sized fields, and the byte offset of the implementation value, which is a compressed cell
diff --git a/Libraries/LibJS/Rust/src/layout/object.rs b/Libraries/LibJS/Rust/src/layout/object.rs
index 7e5c88aebd6..393730baaf5 100644
--- a/Libraries/LibJS/Rust/src/layout/object.rs
+++ b/Libraries/LibJS/Rust/src/layout/object.rs
@@ -10,7 +10,7 @@ use super::cell::{CellHeader, CellKind, CellState};
use super::member::Member;
use super::shape::Shape;
use super::value::Value;
-use crate::layout_forward::{PrivateElements, TypedArrayBaseStorage};
+use crate::layout_forward::TypedArrayBaseStorage;
pub mod object_flag {
pub const IS_EXTENSIBLE: u16 = 1 << 0;
@@ -65,7 +65,6 @@ pub struct Object {
/// Points at `inline_named_storage` until the object needs more room.
pub named_properties: Cell<*mut Value>,
pub indexed_elements: Cell<*mut Value>,
- pub private_elements: PrivateElements,
pub inline_named_storage: [Cell<Value>; INLINE_NAMED_STORAGE_CAPACITY],
}
@@ -76,7 +75,7 @@ const _: () = {
assert!(offset_of!(Object, kind) == offset_of!(CellHeader, kind));
};
-const _: () = assert!(size_of::<Object>() == 56);
+const _: () = assert!(size_of::<Object>() == 48);
const _: () = assert!(
core::mem::offset_of!(Object, inline_named_storage) + INLINE_NAMED_STORAGE_CAPACITY * size_of::<Value>()
== size_of::<Object>()
diff --git a/Libraries/LibJS/Rust/src/layout_forward.rs b/Libraries/LibJS/Rust/src/layout_forward.rs
index edd7b073047..3dd08133a17 100644
--- a/Libraries/LibJS/Rust/src/layout_forward.rs
+++ b/Libraries/LibJS/Rust/src/layout_forward.rs
@@ -11,7 +11,6 @@ use core::ffi::c_void;
pub use crate::gc::class::Class;
pub use crate::gc::foreign::ForeignCellSlot;
-pub use crate::runtime::object::PrivateElements;
pub use crate::runtime::private_environment::PrivateEnvironmentStorage;
pub use crate::runtime::realm::RealmStorage;
pub use crate::runtime::shape::ShapeStorage;
diff --git a/Libraries/LibJS/Rust/src/runtime/array.rs b/Libraries/LibJS/Rust/src/runtime/array.rs
index d00a4195cf0..ad53a01203c 100644
--- a/Libraries/LibJS/Rust/src/runtime/array.rs
+++ b/Libraries/LibJS/Rust/src/runtime/array.rs
@@ -43,7 +43,7 @@ pub struct Array {
is_proxy_target: Cell<bool>,
}
-const _: () = assert!(size_of::<Array>() == 64);
+const _: () = assert!(size_of::<Array>() == 56);
/// The offsets of the flags JIT code checks before writing elements of an array.
pub const ARRAY_LENGTH_WRITABLE_OFFSET: usize = core::mem::offset_of!(Array, length_writable);
diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
index 82d61db2ca9..2d5339ebb02 100644
--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
@@ -76,7 +76,7 @@ pub struct EcmascriptFunctionObjectStorage {
}
// NB: Every ECMAScript function has these bytes, so keep what only some functions need in the rare data.
-const _: () = assert!(size_of::<EcmascriptFunctionObject>() == 104);
+const _: () = assert!(size_of::<EcmascriptFunctionObject>() == 96);
// SAFETY: Visits the cells of the rare data, if there is any.
unsafe impl Trace for EcmascriptFunctionObjectStorage {
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index 90bd05eeae2..b850b770cb9 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -6,7 +6,6 @@
use core::cell::Cell;
use core::ops::ControlFlow;
-use core::ptr::NonNull;
use std::collections::HashSet;
use ak::{Utf16FlyString, Utf16String};
@@ -51,7 +50,7 @@ use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFun
use crate::runtime::object_prototype::ObjectPrototype;
use crate::runtime::primitive_string::PrimitiveString;
use crate::runtime::private_environment::PrivateName;
-use crate::runtime::property_attributes::{DEFAULT_ATTRIBUTES, PropertyAttributes};
+use crate::runtime::property_attributes::{Attribute, DEFAULT_ATTRIBUTES, PropertyAttributes};
use crate::runtime::property_descriptor::{PropertyDescriptor, to_property_descriptor};
use crate::runtime::property_key::{NonSymbolPropertyKey, PropertyKey};
use crate::runtime::realm::Realm;
@@ -69,6 +68,8 @@ pub enum PrivateElementKind {
Accessor,
}
+/// A PrivateElement record, as class definitions collect them. Objects keep theirs as properties (see
+/// `private_element_find`).
#[derive(Clone, Debug, Trace)]
pub struct PrivateElement {
pub key: PrivateName,
@@ -77,33 +78,6 @@ pub struct PrivateElement {
pub value: Value,
}
-/// [[PrivateElements]], allocated when the first one is added and freed when the object is finalized.
-#[repr(transparent)]
-#[derive(Default)]
-pub struct PrivateElements(Cell<Option<NonNull<GcRefCell<Vec<PrivateElement>>>>>);
-
-impl PrivateElements {
- fn get(&self) -> Option<&GcRefCell<Vec<PrivateElement>>> {
- // SAFETY: The elements are owned by the object and live until it is destroyed.
- self.0.get().map(|elements| unsafe { elements.as_ref() })
- }
-
- fn ensure(&self) -> &GcRefCell<Vec<PrivateElement>> {
- if self.0.get().is_none() {
- self.0
- .set(Some(NonNull::from(Box::leak(Box::new(GcRefCell::new(Vec::new()))))));
- }
- self.get().expect("the private elements were just allocated")
- }
-
- fn free(&self) {
- if let Some(elements) = self.0.take() {
- // SAFETY: The elements were leaked from a Box by ensure() and nothing refers to them any more.
- drop(unsafe { Box::from_raw(elements.as_ptr()) });
- }
- }
-}
-
// Non-standard: This is information optionally returned by object property access functions.
// It can be used to implement inline caches for property lookup.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -327,20 +301,15 @@ define_cell!(
external_memory_size: external_memory_size
);
-// Object::external_memory_size(): the heap-allocated named and indexed property storage and the private elements.
+// Object::external_memory_size(): the heap-allocated named and indexed property storage.
impl ExternalMemorySize for Object {
fn external_memory_size(&self) -> usize {
- let mut size = self.named_storage_external_memory_size();
- size += self.indexed_storage_external_memory_size();
- if let Some(private_elements) = self.private_elements.get() {
- size += private_elements.borrow().capacity() * size_of::<PrivateElement>();
- }
- size
+ self.named_storage_external_memory_size() + self.indexed_storage_external_memory_size()
}
}
-// SAFETY: Visits the shape, the named properties the shape describes, the indexed properties and the private
-// elements, which are all the cells an object reaches.
+// SAFETY: Visits the shape, the named properties the shape describes and the indexed properties, which are all the
+// cells an object reaches.
unsafe impl Trace for Object {
fn trace(&self, visitor: &mut Visitor) {
self.shape.trace(visitor);
@@ -379,10 +348,6 @@ unsafe impl Trace for Object {
{
visitor.visit(storage);
}
-
- if let Some(private_elements) = self.private_elements.get() {
- private_elements.trace(visitor);
- }
}
}
@@ -400,11 +365,10 @@ impl Drop for Object {
}
impl Object {
- /// Whether the object has no malloc storage, dictionary elements or private elements, which the object frees.
+ /// Whether the object has no malloc storage or dictionary elements, which the object frees.
pub(crate) fn owns_nothing_outside_the_heap(&self) -> bool {
self.flags.get() & (object_flag::HAS_MALLOC_NAMED_STORAGE | object_flag::HAS_MALLOC_INDEXED_STORAGE) == 0
&& self.indexed_storage_kind() != IndexedStorageKind::Dictionary
- && self.private_elements.get().is_none()
}
#[cold]
@@ -424,7 +388,6 @@ impl Object {
}
_ => {}
}
- self.private_elements.free();
}
}
@@ -618,7 +581,6 @@ impl Object {
inline_named_capacity: Cell::new(INLINE_NAMED_STORAGE_CAPACITY as u8),
named_properties: Cell::new(core::ptr::null_mut()),
indexed_elements: Cell::new(core::ptr::null_mut()),
- private_elements: PrivateElements::default(),
inline_named_storage: [const { Cell::new(Value::UNDEFINED) }; INLINE_NAMED_STORAGE_CAPACITY],
};
if may_interfere_with_indexed_property_access == MayInterfereWithIndexedPropertyAccess::Yes {
@@ -1226,6 +1188,10 @@ impl Object {
let mut properties = Vec::with_capacity(shape.property_count() as usize);
let mut has_accessors = false;
shape.for_each_property_in_insertion_order(|property_key, metadata| {
+ // NB: Private elements are not properties, and integrity levels leave them as they are.
+ if property_key.is_private() {
+ return ControlFlow::Continue(());
+ }
if self.get_direct(metadata.offset).is_accessor() {
has_accessors = true;
return ControlFlow::Break(());
@@ -1692,28 +1658,14 @@ impl Object {
}
// 7.3.27 PrivateElementFind ( O, P ), https://tc39.es/ecma262/#sec-privateelementfind
- /// The index of the element in [[PrivateElements]], which stays valid until another element is added.
- pub fn private_element_find(&self, name: &PrivateName) -> Option<usize> {
- let private_elements = self.private_elements.get()?;
-
+ /// The private element as the property the object stores under the symbol of P, which no other code sees: a field
+ /// is a writable data property, a method a read-only data property and an accessor an accessor property, none of
+ /// them enumerable.
+ pub fn private_element_find(&self, name: &PrivateName) -> Option<ValueAndAttributes> {
// 1. If O.[[PrivateElements]] contains a PrivateElement pe such that pe.[[Key]] is P, then
// a. Return pe.
// 2. Return empty.
- private_elements
- .borrow()
- .iter()
- .position(|element| element.key == *name)
- }
-
- /// The [[Kind]] and [[Value]] of the private element at `index`, without copying its key.
- fn private_element_kind_and_value_at(&self, index: usize) -> (PrivateElementKind, Value) {
- let private_elements = self
- .private_elements
- .get()
- .expect("the object has private elements")
- .borrow();
- let element = &private_elements[index];
- (element.kind, element.value)
+ self.storage_get_symbol(&name.property_key())
}
// 7.3.28 PrivateFieldAdd ( O, P, value ), https://tc39.es/ecma262/#sec-privatefieldadd
@@ -1734,11 +1686,11 @@ impl Object {
}
// 4. Append PrivateElement { [[Key]]: P, [[Kind]]: field, [[Value]]: value } to O.[[PrivateElements]].
- self.private_elements.ensure().borrow_mut(vm).push(PrivateElement {
- key: name.clone(),
- kind: PrivateElementKind::Field,
- value,
- });
+ self.storage_add(
+ vm,
+ &name.property_key(),
+ ValueAndAttributes::new(value, PropertyAttributes::new(Attribute::WRITABLE)),
+ );
// 5. Return unused.
Ok(())
@@ -1748,6 +1700,7 @@ impl Object {
pub fn private_method_or_accessor_add(&self, vm: &Vm, element: PrivateElement) -> ThrowCompletionOr<()> {
// 1. Assert: method.[[Kind]] is either method or accessor.
assert!(element.kind == PrivateElementKind::Method || element.kind == PrivateElementKind::Accessor);
+ assert!((element.kind == PrivateElementKind::Accessor) == element.value.is_accessor());
// 2. If the host is a web browser, then
// a. Perform ? HostEnsureCanAddPrivateElement(O).
@@ -1765,7 +1718,11 @@ impl Object {
}
// 5. Append method to O.[[PrivateElements]].
- self.private_elements.ensure().borrow_mut(vm).push(element);
+ self.storage_add(
+ vm,
+ &element.key.property_key(),
+ ValueAndAttributes::new(element.value, PropertyAttributes::default()),
+ );
// 6. Return unused.
Ok(())
@@ -1784,19 +1741,17 @@ impl Object {
&[&name.description],
);
};
- let (kind, value) = self.private_element_kind_and_value_at(entry);
// 3. If entry.[[Kind]] is either field or method, then
- if kind != PrivateElementKind::Accessor {
+ if !entry.value.is_accessor() {
// a. Return entry.[[Value]].
- return Ok(value);
+ return Ok(entry.value);
}
// Assert: entry.[[Kind]] is accessor.
- assert!(value.is_accessor());
// 6. Let getter be entry.[[Get]].
- let getter = value.as_accessor().getter();
+ let getter = entry.value.as_accessor().getter();
// 5. If entry.[[Get]] is undefined, throw a TypeError exception.
let Some(getter) = getter else {
@@ -1814,30 +1769,26 @@ impl Object {
// 7.3.32 PrivateSet ( O, P, value ), https://tc39.es/ecma262/#sec-privateset
pub fn private_set(&self, vm: &Vm, name: &PrivateName, value: Value) -> ThrowCompletionOr<()> {
// 1. Let entry be PrivateElementFind(O, P).
- let entry_index = self.private_element_find(name);
+ let entry = self.private_element_find(name);
// 2. If entry is empty, throw a TypeError exception.
- let Some(entry_index) = entry_index else {
+ let Some(entry) = entry else {
return vm.throw_completion(
ErrorKind::TypeError,
ErrorType::PrivateFieldDoesNotExistOnObject,
&[&name.description],
);
};
- let (kind, accessor) = self.private_element_kind_and_value_at(entry_index);
// 3. If entry.[[Kind]] is field, then
- if kind == PrivateElementKind::Field {
+ if entry.attributes.is_writable() {
// a. Set entry.[[Value]] to value.
- self.private_elements
- .get()
- .expect("the object has private elements")
- .borrow_mut(vm)[entry_index]
- .value = value;
+ let offset = entry.property_offset.expect("a private element is a named property");
+ self.replace_direct(vm, offset, value);
return Ok(());
}
// 4. Else if entry.[[Kind]] is method, then
- else if kind == PrivateElementKind::Method {
+ else if !entry.value.is_accessor() {
// a. Throw a TypeError exception.
return vm.throw_completion(
ErrorKind::TypeError,
@@ -1849,12 +1800,9 @@ impl Object {
// 5. Else,
// a. Assert: entry.[[Kind]] is accessor.
- assert!(kind == PrivateElementKind::Accessor);
-
- assert!(accessor.is_accessor());
// c. Let setter be entry.[[Set]].
- let setter = accessor.as_accessor().setter();
+ let setter = entry.value.as_accessor().setter();
// b. If entry.[[Set]] is undefined, throw a TypeError exception.
let Some(setter) = setter else {
diff --git a/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rs b/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rs
index 2c635b34308..1d2ef68d426 100644
--- a/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rs
+++ b/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rs
@@ -41,7 +41,7 @@ pub struct PromiseResolvingFunction {
kind: PromiseResolvingFunctionKind,
}
-const _: () = assert!(size_of::<PromiseResolvingFunction>() == 104);
+const _: () = assert!(size_of::<PromiseResolvingFunction>() == 96);
static PROMISE_RESOLVING_FUNCTION_VIRTUAL_METHODS: NativeFunctionMethods = NativeFunctionMethods {
call: PromiseResolvingFunction::call,
diff --git a/Libraries/LibJS/Rust/src/runtime/proxy_object.rs b/Libraries/LibJS/Rust/src/runtime/proxy_object.rs
index efea06bc7a9..a5ef09b611e 100644
--- a/Libraries/LibJS/Rust/src/runtime/proxy_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/proxy_object.rs
@@ -85,7 +85,7 @@ pub struct ProxyObject {
is_revoked: Cell<bool>,
}
-const _: () = assert!(size_of::<ProxyObject>() == 80);
+const _: () = assert!(size_of::<ProxyObject>() == 72);
/// The internal methods of a Proxy exotic object. Every proxy has [[Call]] and [[Construct]]: IsCallable and
/// IsConstructor only reach them for a proxy whose target has them, since the proxy keeps the IsFunction flag only if
diff --git a/Libraries/LibJS/Rust/src/runtime/regexp_object.rs b/Libraries/LibJS/Rust/src/runtime/regexp_object.rs
index 09e2bf93c23..02f05131b49 100644
--- a/Libraries/LibJS/Rust/src/runtime/regexp_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/regexp_object.rs
@@ -148,7 +148,7 @@ pub struct RegExpObject {
cached_regex: RefCell<Option<Rc<EcmaScriptRegex>>>,
}
-const _: () = assert!(size_of::<RegExpObject>() == 112);
+const _: () = assert!(size_of::<RegExpObject>() == 104);
static REGEXP_OBJECT_METHODS: ObjectMethods = ObjectMethods {
initialize: RegExpObject::initialize,
diff --git a/Tests/LibJS/Runtime/classes/class-private-elements-on-objects.js b/Tests/LibJS/Runtime/classes/class-private-elements-on-objects.js
new file mode 100644
index 00000000000..5ce0020a3e0
--- /dev/null
+++ b/Tests/LibJS/Runtime/classes/class-private-elements-on-objects.js
@@ -0,0 +1,109 @@
+// Private elements live in the storage of the objects they are added to, as properties nothing outside the engine sees.
+
+class Stamper extends class {
+ constructor(object) {
+ return object;
+ }
+} {
+ #field = 1;
+ #method() {
+ return "method";
+ }
+ get #accessor() {
+ return this.#field;
+ }
+ set #accessor(value) {
+ this.#field = value;
+ }
+
+ static has(object) {
+ return #field in object;
+ }
+
+ static field(object) {
+ return object.#field;
+ }
+
+ static setField(object, value) {
+ object.#field = value;
+ }
+
+ static callMethod(object) {
+ return object.#method();
+ }
+
+ static setMethod(object) {
+ object.#method = null;
+ }
+
+ static setAccessor(object, value) {
+ object.#accessor = value;
+ return object.#accessor;
+ }
+}
+
+test("private elements are not properties", () => {
+ const object = new Stamper({ visible: 1 });
+ expect(Stamper.has(object)).toBeTrue();
+ expect(Reflect.ownKeys(object)).toEqual(["visible"]);
+ expect({ ...object }).toEqual({ visible: 1 });
+ expect(Object.assign({}, object)).toEqual({ visible: 1 });
+ expect(JSON.stringify(object)).toBe('{"visible":1}');
+});
+
+test("fields stay writable on frozen objects", () => {
+ const object = new Stamper({});
+ Object.freeze(object);
+ expect(Object.isFrozen(object)).toBeTrue();
+ Stamper.setField(object, 2);
+ expect(Stamper.field(object)).toBe(2);
+ expect(Stamper.setAccessor(object, 3)).toBe(3);
+});
+
+test("methods are read-only", () => {
+ const object = new Stamper({});
+ expect(Stamper.callMethod(object)).toBe("method");
+ expect(() => Stamper.setMethod(object)).toThrowWithMessage(TypeError, "Cannot set private method");
+});
+
+test("proxies keep private elements without calling traps", () => {
+ const proxy = new Proxy(
+ {},
+ new Proxy(
+ {},
+ {
+ get() {
+ throw new Error("trap called");
+ },
+ }
+ )
+ );
+ new Stamper(proxy);
+ Stamper.setField(proxy, 2);
+ expect(Stamper.field(proxy)).toBe(2);
+});
+
+test("private elements survive dictionary objects losing properties", () => {
+ const object = {};
+ for (let i = 0; i < 100; ++i) object[`property${i}`] = i;
+ new Stamper(object);
+ for (let i = 0; i < 100; ++i) delete object[`property${i}`];
+ expect(Stamper.field(object)).toBe(1);
+ expect(Stamper.setAccessor(object, 4)).toBe(4);
+ expect(Reflect.ownKeys(object)).toEqual([]);
+});
+
+test("each evaluation of a class has private names of its own", () => {
+ const makeClass = () =>
+ class {
+ #field;
+ static has(object) {
+ return #field in object;
+ }
+ };
+ const A = makeClass();
+ const B = makeClass();
+ const a = new A();
+ expect(A.has(a)).toBeTrue();
+ expect(B.has(a)).toBeFalse();
+});