Truly independent web browser
LibJS: Read holes and indices past the end as undefined in JIT code
Andreas Kling87c5e9039cd9
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/keyed.rs b/Libraries/LibJS/JIT/Rust/src/builder/keyed.rsindex de1eeebef59..54aa4ee17b5 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/keyed.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/keyed.rs@@ -10,7 +10,9 @@//! A `GetByValue` with an int32 key branches on the elements kind of its//! object, one kind its feedback saw after the other, and loads the element://! bounds checks against the element counts, the load, and for holey-//! elements a check for a hole, each a node of its own. Strings give the+//! elements a check for a hole, each a node of its own. Sites that saw+//! holes or indices past the end read undefined there, where the prototype+//! chain has no indexed properties. Strings give the//! strings of their ASCII characters. Other keys probe the property lookup//! caches. Everything else takes the instruction's slow path, and all paths//! join after the instruction. `PutByValue` is built the same way.@@ -32,11 +34,13 @@ use crate::ir::ElementsKind;use crate::ir::NodeId;use crate::ir::Op;use crate::ir::TypedArrayElement;+use crate::ir::value;use crate::snapshot::Forwarding;use crate::snapshot::Intrinsic;use crate::snapshot::keyed_feedback_bits::HOLEY;use crate::snapshot::keyed_feedback_bits::INT32_INDEX;use crate::snapshot::keyed_feedback_bits::OTHER_KEY;+use crate::snapshot::keyed_feedback_bits::OUT_OF_BOUNDS;use crate::snapshot::keyed_feedback_bits::PACKED;use crate::snapshot::keyed_feedback_bits::STRING_KEY;use crate::snapshot::keyed_feedback_bits::SYMBOL_KEY;@@ -175,6 +179,21 @@ impl GraphBuilder<'_> {self.branch_to_slow_path(slow_paths, BranchCondition::IndexInBounds, vec![index, capacity], true)}+ /// Ends the current block, where the object at `address` has no element+ /// at a non-negative index, as a path that read undefined, if its+ /// prototype chain has no indexed properties. Takes the slow path+ /// otherwise.+ fn read_missing_element(&mut self, slow_paths: &mut SlowPaths, address: NodeId) {+ self.branch_to_slow_path(+ slow_paths,+ BranchCondition::PlainArrayPrototypeChain,+ vec![address],+ true,+ );+ let undefined = self.constant(value::UNDEFINED);+ self.end_hot_path(slow_paths, vec![undefined]);+ }+/// Builds `GetByValue` (`Handling::Expanded`) for the keys and elements/// its feedback saw.pub(super) fn build_get_by_value(@@ -197,6 +216,14 @@ impl GraphBuilder<'_> {let strings = bits & OTHER_KEY != 0 && self.runtime.layout.single_ascii_character_strings != 0;let indexed = !kinds.is_empty() || strings;let named = bits & (STRING_KEY | SYMBOL_KEY) != 0;+ // NB: Holes and indices past the end read undefined where the+ // prototype chain is the realm's default one, without indexed+ // properties. Sites that saw any are built to read them.+ let reads_missing_elements = bits & OUT_OF_BOUNDS != 0;+ if reads_missing_elements {+ self.embed(self.runtime.array_prototype);+ self.embed(self.runtime.object_prototype);+ }let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;let object = self.read(base)?;let key = self.read(property)?;@@ -219,13 +246,48 @@ impl GraphBuilder<'_> {|builder, slow_paths, case, object| {let kind = kinds[case];let address = builder.cell_address(object);- let (storage, index) = builder.element_index_in_bounds(slow_paths, kind, address, index);+ if !reads_missing_elements || matches!(kind, ElementsKind::TypedArray(_)) {+ let (storage, index) = builder.element_index_in_bounds(slow_paths, kind, address, index);+ let element = builder.load_element(kind, storage, index);+ let mut element = builder.tagged(element);+ if kind == ElementsKind::Holey {+ element = builder.branch_if_empty(slow_paths, element);+ }+ builder.end_hot_path(slow_paths, vec![element]);+ return;+ }+ let (storage, bound) = builder.element_storage_and_bound(kind, address);+ let (inside, outside) =+ builder.branch_both_ways(BranchCondition::IndexInBounds, vec![index, bound]);+ builder.block = outside;+ let zero = builder.int32_constant(0);+ builder.branch_to_slow_path(+ slow_paths,+ BranchCondition::Int32(Comparison::GreaterThanEquals),+ vec![index, zero],+ true,+ );+ builder.read_missing_element(slow_paths, address);+ builder.block = inside;+ let index = builder.refine(BranchCondition::IndexInBounds, true, vec![index, bound]);let element = builder.load_element(kind, storage, index);- let mut element = builder.tagged(element);+ let element = builder.tagged(element);if kind == ElementsKind::Holey {- element = builder.branch_if_empty(slow_paths, element);+ let empty = builder.constant(value::EMPTY);+ let (hole, present) = builder+ .branch_both_ways(BranchCondition::TaggedEquals { equal: true }, vec![element, empty]);+ builder.block = hole;+ builder.read_missing_element(slow_paths, address);+ builder.block = present;+ let element = builder.refine(+ BranchCondition::TaggedEquals { equal: true },+ false,+ vec![element, empty],+ );+ builder.end_hot_path(slow_paths, vec![element]);+ } else {+ builder.end_hot_path(slow_paths, vec![element]);}- builder.end_hot_path(slow_paths, vec![element]);},);// NB: The feedback counts the characters of strings as other keys.diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rsindex 3eaa82cd64b..523efd5f4f1 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs@@ -67,6 +67,39 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.branch_unless_plain_prototype(prototype, self.runtime.object_prototype.0, array, exit);}+ /// A branch on `BranchCondition::PlainArrayPrototypeChain`: to `target`+ /// where the object at `object` is an array whose prototype chain is the+ /// realm's default one, without indexed properties, or where it is not,+ /// with `invert`.+ pub(in crate::codegen) fn emit_branch_on_plain_array_prototype_chain(+ &mut self,+ node: NodeId,+ object: Gpr,+ target: Label,+ invert: bool,+ ) {+ let prototype = self.temp(node, 0);+ let scratch = self.pinned.scratch;+ let other = self.masm.new_label();+ let fail = if invert { target } else { other };+ self.masm+ .load16(scratch, &Address::new(object, self.runtime.offsets.object_flags as i32));+ self.masm.branch_test32(+ Condition::Zero,+ scratch,+ u32::from(self.runtime.layout.object_flag_has_magical_length),+ fail,+ );+ // NB: %Object.prototype% is an immutable prototype exotic object,+ // so the chain ends there.+ self.branch_unless_plain_prototype(object, self.runtime.array_prototype.0, prototype, fail);+ self.branch_unless_plain_prototype(prototype, self.runtime.object_prototype.0, prototype, fail);+ if !invert {+ self.masm.jump(target);+ }+ self.masm.bind(other);+ }+/// `LoadElementsCapacity`: the capacity of packed or holey indexed/// storage, and 0 without storage.pub(in crate::codegen) fn emit_load_elements_capacity(&mut self, node: NodeId) {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 2d05674590d..456250f83d7 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -2160,6 +2160,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {BranchCondition::Shape(_) => unreachable!("only refinements of shape switch cases test one shape"),BranchCondition::Float64(_) => unreachable!("float64 comparisons branch above"),BranchCondition::ArrayIterator => self.emit_branch_on_array_iterator(input, target, invert),+ BranchCondition::PlainArrayPrototypeChain => {+ self.emit_branch_on_plain_array_prototype_chain(node, input, target, invert);+ }BranchCondition::MagicalLength | BranchCondition::Extensible => {let flag = match condition {BranchCondition::MagicalLength => self.runtime.layout.object_flag_has_magical_length,diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rsindex 383b257f6b0..f51aa7404a7 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs@@ -75,6 +75,7 @@ fn condition_text(condition: BranchCondition) -> String {BranchCondition::MagicalLength => "MagicalLength".to_string(),BranchCondition::Extensible => "Extensible".to_string(),BranchCondition::ArrayIterator => "ArrayIterator".to_string(),+ BranchCondition::PlainArrayPrototypeChain => "PlainArrayPrototypeChain".to_string(),BranchCondition::Shape(shape) => format!("Shape {}", shapes_text(std::iter::once(&shape))),BranchCondition::NonNegativeInt32 => "NonNegativeInt32".to_string(),BranchCondition::Int32(comparison) => format!("Int32{comparison:?}"),diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex ee21aedfd06..6268111d3b1 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -132,6 +132,12 @@ pub enum BranchCondition {/// The input is the `Repr::Pointer` of an object: is it an array/// iterator over values, like `%Array.prototype.values%` makes?ArrayIterator,+ /// The input is the `Repr::Pointer` of an object: is it an array whose+ /// prototype is the realm's `%Array.prototype%`, and do that and+ /// `%Object.prototype%` have no indexed properties and nothing that may+ /// interfere with indexed property access, so that indices it has no+ /// element at read undefined?+ PlainArrayPrototypeChain,/// Input 0 is an object and input 1 its address: does it have the/// shape, like `Op::ShapeSwitch` cases test it? Only the refinements of/// those cases have this condition; no branch does.diff --git a/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs b/Libraries/LibJS/JIT/Rust/src/passes/simplify.rsindex 3d9813e80be..d2ed86c22c6 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs@@ -277,6 +277,7 @@ fn constant_condition(graph: &Graph, condition: BranchCondition, input: NodeId,| BranchCondition::MagicalLength| BranchCondition::Extensible| BranchCondition::ArrayIterator+ | BranchCondition::PlainArrayPrototypeChain| BranchCondition::Shape(_) => None,}}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rsindex d9b506a482e..11a5f113b16 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs@@ -481,7 +481,8 @@ fn branch_input_reprs(condition: crate::ir::BranchCondition) -> Vec<Repr> {crate::ir::BranchCondition::ResolvedString| crate::ir::BranchCondition::MagicalLength| crate::ir::BranchCondition::Extensible- | crate::ir::BranchCondition::ArrayIterator => vec![Repr::Pointer],+ | crate::ir::BranchCondition::ArrayIterator+ | crate::ir::BranchCondition::PlainArrayPrototypeChain => vec![Repr::Pointer],crate::ir::BranchCondition::Shape(_) => vec![Repr::Tagged, Repr::Pointer],crate::ir::BranchCondition::PropertyIteratorCacheValid => tagged(2),crate::ir::BranchCondition::BindingMutable { .. } | crate::ir::BranchCondition::NextBindingOfShape { .. } => {diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rsindex 3f80e87c511..f4fe9d3b927 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs@@ -426,6 +426,11 @@ fn constraints(node: &Node, registers: &RegisterSet) -> Constraints {Op::StoreEnvironmentBinding { .. } | Op::AppendEnvironmentBinding => constraints.temps = 1,// The array, then its prototypes.Op::CheckAppendableArray => constraints.temps = 2,+ // The object's prototypes.+ Op::Branch {+ condition: BranchCondition::PlainArrayPrototypeChain,+ ..+ } => constraints.temps = 1,// The object's elements.Op::LoadElementsCapacity | Op::AppendElement => constraints.temps = 1,// The object, then its elements or element address.diff --git a/Tests/LibJS/Runtime/jit/missing-elements.js b/Tests/LibJS/Runtime/jit/missing-elements.jsnew file mode 100644index 00000000000..fb19c92a431--- /dev/null+++ b/Tests/LibJS/Runtime/jit/missing-elements.js@@ -0,0 +1,98 @@+function compileWith(f, ...args) {+ jit.prepare(f);+ for (let i = 0; i < 10; ++i) f(...args);+ expect(jit.compile(f)).toBe(jit.enabled);+ return f;+}++function at(array, index) {+ return array[index];+}++function warmUp() {+ // NB: The feedback sees elements, holes and indices past the end of packed and holey arrays.+ compileWith(array => [at(array, 0), at(array, 1), at(array, 5), at([1, , 3], 1)], [1, 2]);+ jit.prepare(at);+ for (let i = 0; i < 10; ++i) {+ at([1, 2], 0);+ at([1, 2], 5);+ at([1, , 3], 1);+ }+ expect(jit.compile(at)).toBe(jit.enabled);+}++test("holes and indices past the end read undefined", () => {+ warmUp();+ expect(at([1, 2], 0)).toBe(1);+ expect(at([1, 2], 2)).toBeUndefined();+ expect(at([1, 2], 1000)).toBeUndefined();+ expect(at([1, , 3], 1)).toBeUndefined();+ expect(at([], 0)).toBeUndefined();+ const sparse = [1, 2, 3];+ sparse.length = 100;+ expect(at(sparse, 50)).toBeUndefined();+ expect(at(sparse, 2)).toBe(3);+});++test("negative indices read named properties", () => {+ warmUp();+ const array = [1, 2];+ array["-1"] = "named";+ expect(at(array, -1)).toBe("named");+ expect(at([1, 2], -1)).toBeUndefined();+});++test("holes and indices past the end read indexed properties of Array.prototype", () => {+ warmUp();+ Array.prototype[5] = "array prototype";+ Array.prototype[1] = "array prototype hole";+ try {+ expect(at([1, 2], 5)).toBe("array prototype");+ expect(at([1, , 3], 1)).toBe("array prototype hole");+ } finally {+ delete Array.prototype[5];+ delete Array.prototype[1];+ }+ expect(at([1, 2], 5)).toBeUndefined();+});++test("holes and indices past the end read indexed properties of Object.prototype", () => {+ warmUp();+ Object.prototype[5] = "object prototype";+ try {+ expect(at([1, 2], 5)).toBe("object prototype");+ } finally {+ delete Object.prototype[5];+ }+ expect(at([1, 2], 5)).toBeUndefined();+});++test("holes and indices past the end call getters of prototypes", () => {+ warmUp();+ let calls = 0;+ Object.defineProperty(Array.prototype, 7, {+ get() {+ ++calls;+ return "getter";+ },+ configurable: true,+ });+ try {+ expect(at([1, 2], 7)).toBe("getter");+ expect(calls).toBe(1);+ } finally {+ delete Array.prototype[7];+ }+});++test("holes and indices past the end read other prototypes", () => {+ warmUp();+ const array = [1, 2];+ Object.setPrototypeOf(array, { 5: "own prototype" });+ expect(at(array, 5)).toBe("own prototype");++ const proxied = [1, , 3];+ Object.setPrototypeOf(proxied, new Proxy([], { get: () => "proxy" }));+ expect(at(proxied, 1)).toBe("proxy");+ expect(at(proxied, 10)).toBe("proxy");+});