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
13 changes: 10 additions & 3 deletions nova_vm/src/ecmascript/builtins/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,11 +313,12 @@ impl<'a> InternalSlots<'a> for Array<'a> {
}

fn internal_set_extensible(self, agent: &mut Agent, value: bool) {
// Note: preventing extensions does not make "length" read-only; the
// backing object's shape holds the [[Extensible]] flag.
let ArrayHeapDataMut {
elements: elems,
elements: _,
object_index: backing_object,
} = self.get_mut(agent);
elems.len_writable = value;
if let Some(object_index) = backing_object {
object_index.internal_set_extensible(agent, value)
} else if !value {
Expand Down Expand Up @@ -440,6 +441,12 @@ impl<'a> InternalMethods<'a> for Array<'a> {
if !length_writable {
return TryResult::Continue(false);
}
// Note: index ≥ length means that P is not an own property,
// so OrdinaryDefineOwnProperty below fails if A is not
// extensible.
if !self.internal_extensible(agent) {
return TryResult::Continue(false);
}
let Heap {
elements,
arrays,
Expand Down Expand Up @@ -910,7 +917,7 @@ fn ordinary_define_own_property_for_array(
// Hole

// a. If extensible is false, return false.
if !elements.writable() {
if !array.internal_extensible(agent) {
return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use crate::{
ecmascript::{
Agent, ArgumentsList, ArrayIterator, BUILTIN_STRING_MEMORY, Behaviour, Builtin,
BuiltinIntrinsic, CollectionIteratorKind, ExceptionType, Function, InternalMethods,
JsError, JsResult, Number, Object, PropertyKey, Realm, SmallInteger, String, Value,
array_create, array_species_create, builders::OrdinaryObjectBuilder, call_function,
InternalSlots, JsError, JsResult, Number, Object, PropertyKey, Realm, SmallInteger, String,
Value, array_create, array_species_create, builders::OrdinaryObjectBuilder, call_function,
create_data_property_or_throw, delete_property_or_throw, get, has_property, invoke,
is_array, is_callable, is_strictly_equal, length_of_array_like, same_value_zero, set,
to_boolean, to_integer_or_infinity, to_number, to_object, to_string,
Expand Down Expand Up @@ -3871,6 +3871,7 @@ impl ArrayPrototype {
&& array.is_trivial(agent)
&& array.is_dense(agent)
&& array.length_writable(agent)
&& array.internal_extensible(agent)
{
// Fast path: Reserve enough room in the array and set array length.
if let Err(err) = array.reserve(agent, arg_count as u32) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ pub(super) fn get_template_object<'a>(
}
// 13. Perform ! SetIntegrityLevel(rawObj, frozen).
unwrap_try(raw_obj.try_prevent_extensions(agent, gc));
// Note: the elements are already non-writable and non-configurable.
raw_obj.set_length_readonly(agent);
let prototype = template.internal_prototype(agent).unwrap();
// 14. Perform ! DefinePropertyOrThrow(template,
let template_backing_object = OrdinaryObject::create_object(
Expand All @@ -162,6 +164,7 @@ pub(super) fn get_template_object<'a>(
template.set_backing_object(agent, template_backing_object.unbind());
// 15. Perform ! SetIntegrityLevel(template, frozen).
unwrap_try(template.try_prevent_extensions(agent, gc));
template.set_length_readonly(agent);
// 16. Append the Record { [[Site]]: templateLiteral, [[Array]]: template }
// to realm.[[TemplateMap]].
// 17. Return template.
Expand Down
4 changes: 0 additions & 4 deletions nova_vm/src/heap/element_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,6 @@ impl<'gc> ElementsVector<'gc> {
self.len == self.cap()
}

pub(crate) fn writable(&self) -> bool {
self.len_writable
}

/// Get shared access to the elements storage of an array.
///
/// Value slots with None are either array holes, or accessor properties.
Expand Down
40 changes: 40 additions & 0 deletions nova_vm/tests/array_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use std::{fs, path::PathBuf};

use nova_vm::{
ecmascript::{
AgentOptions, DefaultHostHooks, GcAgent, String, parse_script, script_evaluation,
},
engine::Bindable,
};

#[test]
fn array_prevent_extensions_tests() {
let d: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"tests",
"sources",
"arrayPreventExtensions.test.js",
]
.iter()
.collect();
let contents = fs::read_to_string(d.clone()).expect("Should have been able to read the file");

let mut agent = GcAgent::new(AgentOptions::default(), &DefaultHostHooks);
let realm = agent.create_default_realm();
agent.run_in_realm(&realm, |agent, mut gc| {
let realm = agent.current_realm(gc.nogc());
let source_text = String::from_string(agent, contents, gc.nogc());
let script = parse_script(agent, source_text, realm, false, None, gc.nogc()).unwrap();
if let Err(err) = script_evaluation(agent, script.unbind(), gc.reborrow()) {
panic!(
"Test '{}' failed: {:?}",
d.display(),
err.unbind().to_string(agent, gc).to_string_lossy(agent)
)
}
});
}
98 changes: 98 additions & 0 deletions nova_vm/tests/sources/arrayPreventExtensions.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

function assertEquals(actual, expected, message) {
if (actual !== expected) {
throw new Error(`${message}: expected ${expected}, got ${actual}`);
}
}

function assertThrowsTypeError(fn, message) {
try {
fn();
} catch (err) {
if (err instanceof TypeError) {
return;
}
throw new Error(`${message}: expected TypeError, got ${err}`);
}
throw new Error(`${message}: expected TypeError, got no error`);
}

// Object.preventExtensions leaves "length" writable.
{
const a = Object.preventExtensions([1, 2]);
const desc = Object.getOwnPropertyDescriptor(a, "length");
assertEquals(desc.writable, true, "length stays writable");
assertEquals(Object.isExtensible(a), false, "array is not extensible");
}

// Removing elements works.
{
const a = Object.preventExtensions([1, 2]);
assertEquals(a.pop(), 2, "pop result");
assertEquals(a.length, 1, "length after pop");
}
{
const a = Object.preventExtensions([1, 2, 3]);
assertEquals(a.shift(), 1, "shift result");
assertEquals(a.join(), "2,3", "array after shift");
}
{
const a = Object.preventExtensions([1, 2, 3]);
assertEquals(a.splice(0, 1).join(), "1", "splice result");
assertEquals(a.join(), "2,3", "array after splice");
}
{
const a = Object.preventExtensions([]);
assertEquals(a.pop(), undefined, "pop on empty array");
assertEquals(a.push(), 0, "push with no items");
assertEquals(a.unshift(), 0, "unshift with no items");
}
{
const a = Object.preventExtensions([1, 2, 3]);
a.length = 1;
assertEquals(a.join(), "1", "shrink length");
a.length = 3;
assertEquals(a.length, 3, "grow length");
assertEquals(1 in a, false, "growing length adds holes");
}

// Adding elements still fails.
assertThrowsTypeError(() => {
Object.preventExtensions([1]).push(2);
}, "push");
assertThrowsTypeError(() => {
Object.preventExtensions([1]).unshift(0);
}, "unshift");
assertThrowsTypeError(() => {
"use strict";
const a = Object.preventExtensions([1]);
a[1] = 2;
}, "assign past the end");
assertThrowsTypeError(() => {
"use strict";
const a = Object.preventExtensions([1, , 3]);
a[1] = 2;
}, "assign to a hole");
assertEquals(
Reflect.defineProperty(Object.preventExtensions([1]), 5, { value: 1 }),
false,
"define past the end",
);
{
"use strict";
const a = Object.preventExtensions([1, 2]);
a[0] = 9;
assertEquals(a[0], 9, "overwrite an element");
}

// A non-writable length does not stop filling a hole.
{
"use strict";
const a = [1, , 3];
Object.defineProperty(a, "length", { writable: false });
a[1] = 2;
assertEquals(a.join(), "1,2,3", "fill a hole with read-only length");
}
1 change: 0 additions & 1 deletion tests/expectations.json
Original file line number Diff line number Diff line change
Expand Up @@ -7431,7 +7431,6 @@
"staging/sm/Array/change-array-by-copy-cross-compartment-create.js": "FAIL",
"staging/sm/Array/change-array-by-copy-errors-from-correct-realm.js": "FAIL",
"staging/sm/Array/isArray.js": "FAIL",
"staging/sm/Array/length-01.js": "FAIL",
"staging/sm/Array/set-with-indexed-property-on-prototype-chain.js": "FAIL",
"staging/sm/Array/sort-non-function.js": "FAIL",
"staging/sm/Array/species.js": "FAIL",
Expand Down
4 changes: 2 additions & 2 deletions tests/metrics.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"results": {
"crash": 162,
"fail": 7572,
"pass": 40692,
"fail": 7571,
"pass": 40693,
"skip": 5127,
"timeout": 22,
"unresolved": 41
Expand Down