Skip to content

Truly independent web browser

LibJS: Limit array buffers to 2^32 bytes

Shannon Booth47b0b2b12e1a
diff --git a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs b/Libraries/LibJS/Rust/src/runtime/array_buffer.rs
index 2d6cde19f02..f97f9c31073 100644
--- a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs
+++ b/Libraries/LibJS/Rust/src/runtime/array_buffer.rs
@@ -914,6 +914,9 @@ impl ArrayBuffer {
byte_length: usize,
is_shared: Shared,
) -> ThrowCompletionOr<Gc<ArrayBuffer>> {
+ if exceeds_max_array_buffer_byte_length(byte_length, None) {
+ return vm.throw_completion(ErrorKind::RangeError, ErrorType::InvalidLength, &[&"array buffer"]);
+ }
let Ok(buffer) = allocate_or_retry_after_gc(vm.heap(), || OwnedBackingStore::create_zeroed(byte_length)) else {
return vm.throw_completion(
ErrorKind::RangeError,
@@ -951,6 +954,9 @@ impl ArrayBuffer {
is_shared: Shared,
write: impl FnOnce(&mut [MaybeUninit<u8>]) -> usize,
) -> ThrowCompletionOr<Gc<ArrayBuffer>> {
+ if exceeds_max_array_buffer_byte_length(byte_length, None) {
+ return vm.throw_completion(ErrorKind::RangeError, ErrorType::InvalidLength, &[&"array buffer"]);
+ }
let Ok(buffer) = allocate_or_retry_after_gc(vm.heap(), || OwnedBackingStore::create_uninitialized(byte_length))
else {
return vm.throw_completion(
@@ -1550,6 +1556,14 @@ impl ArrayBuffer {
}
}
+/// The largest byte length of a buffer. Every byte of a buffer this long can be indexed by a Uint8Array, whose element
+/// indices are u32s.
+pub const MAX_ARRAY_BUFFER_BYTE_LENGTH: usize = 1 << 32;
+
+fn exceeds_max_array_buffer_byte_length(size: usize, capacity: Option<usize>) -> bool {
+ capacity.unwrap_or(size).max(size) > MAX_ARRAY_BUFFER_BYTE_LENGTH
+}
+
// 6.2.9.1 CreateByteDataBlock ( size ), https://tc39.es/ecma262/#sec-createbytedatablock
pub fn create_byte_data_block(vm: &Vm, size: usize, capacity: Option<usize>) -> ThrowCompletionOr<DataBlock> {
// 1. If size > 2^53 - 1, throw a RangeError exception.
@@ -1562,6 +1576,11 @@ pub fn create_byte_data_block(vm: &Vm, size: usize, capacity: Option<usize>) ->
return vm.throw_completion(ErrorKind::RangeError, ErrorType::InvalidLength, &[&"array buffer"]);
}
+ // AD-HOC: See MAX_ARRAY_BUFFER_BYTE_LENGTH.
+ if exceeds_max_array_buffer_byte_length(size, capacity) {
+ return vm.throw_completion(ErrorKind::RangeError, ErrorType::InvalidLength, &[&"array buffer"]);
+ }
+
// 2. Let db be a new Data Block value consisting of size bytes. If it is impossible to create such a Data Block, throw a RangeError exception.
// 3. Set all of the bytes of db to 0.
let data_block = allocate_or_retry_after_gc(vm.heap(), || match capacity {
@@ -1583,6 +1602,15 @@ pub fn create_byte_data_block(vm: &Vm, size: usize, capacity: Option<usize>) ->
// FIXME: The returned DataBlock is not shared in the sense that the standard specifies it.
// 6.2.9.2 CreateSharedByteDataBlock ( size ), https://tc39.es/ecma262/#sec-createsharedbytedatablock
fn create_shared_byte_data_block(vm: &Vm, size: usize, capacity: Option<usize>) -> ThrowCompletionOr<DataBlock> {
+ // AD-HOC: See MAX_ARRAY_BUFFER_BYTE_LENGTH.
+ if exceeds_max_array_buffer_byte_length(size, capacity) {
+ return vm.throw_completion(
+ ErrorKind::RangeError,
+ ErrorType::InvalidLength,
+ &[&"shared array buffer"],
+ );
+ }
+
let capacity = capacity.unwrap_or(size);
// AD-HOC: A fixed-length shared Data Block is backed by cross-process shared memory (Core::AnonymousBuffer) — so
diff --git a/Libraries/LibJS/Rust/src/runtime/typed_array.rs b/Libraries/LibJS/Rust/src/runtime/typed_array.rs
index 396aecb889e..e26330c8fec 100644
--- a/Libraries/LibJS/Rust/src/runtime/typed_array.rs
+++ b/Libraries/LibJS/Rust/src/runtime/typed_array.rs
@@ -23,8 +23,8 @@ use crate::runtime::abstract_operations::{
};
use crate::runtime::array::Array;
use crate::runtime::array_buffer::{
- ArrayBuffer, ElementType, INVALID_DATA_OFFSET, Order, ReadWriteModifyOperation, allocate_array_buffer,
- array_buffer_byte_length, clone_array_buffer, f64_to_binary16_bits,
+ ArrayBuffer, ElementType, INVALID_DATA_OFFSET, MAX_ARRAY_BUFFER_BYTE_LENGTH, Order, ReadWriteModifyOperation,
+ allocate_array_buffer, array_buffer_byte_length, clone_array_buffer, f64_to_binary16_bits,
};
use crate::runtime::array_iterator::packed_array_iteration_is_unobservable;
use crate::runtime::byte_length::{ByteLength, ByteLengthSlot};
@@ -1041,11 +1041,12 @@ pub fn typed_array_from(vm: &Vm, typed_array_value: Value) -> ThrowCompletionOr<
.expect("an object with the typed array flag is a typed array"))
}
+/// Whether a typed array of `array_length` elements of `element_size` fits in the largest buffer.
pub fn validate_typed_array_length(vm: &Vm, array_length: usize, element_size: usize) -> ThrowCompletionOr<()> {
- if array_length > i32::MAX as usize / element_size {
- return vm.throw_completion(ErrorKind::RangeError, ErrorType::InvalidLength, &[&"typed array"]);
- }
- if array_length.checked_mul(element_size).is_none() {
+ if array_length
+ .checked_mul(element_size)
+ .is_none_or(|byte_length| byte_length > MAX_ARRAY_BUFFER_BYTE_LENGTH)
+ {
return vm.throw_completion(ErrorKind::RangeError, ErrorType::InvalidLength, &[&"typed array"]);
}
Ok(())
@@ -1158,7 +1159,6 @@ pub fn initialize_typed_array_from_array_buffer(
}
let new_array_length = new_byte_length / element_size;
- validate_typed_array_length(vm, new_array_length, element_size)?;
// c. Set O.[[ByteLength]] to newByteLength.
typed_array.set_byte_length(ByteLength::Length(new_byte_length));
@@ -1305,18 +1305,11 @@ fn initialize_typed_array_from_typed_array(
fn allocate_typed_array_buffer(vm: &Vm, typed_array: &TypedArrayBase, length: usize) -> ThrowCompletionOr<()> {
let realm = vm.current_realm().expect("a typed array is initialized in a realm");
- // Enforce 2GB "Excessive Length" limit
- if length > i32::MAX as usize / typed_array.kind().element_type().size() {
- return vm.throw_completion(ErrorKind::RangeError, ErrorType::InvalidLength, &[&"typed array"]);
- }
-
// 1. Assert: O.[[ViewedArrayBuffer]] is undefined.
// 2. Let elementSize be TypedArrayElementSize(O).
let element_size = typed_array.element_size();
- if element_size.checked_mul(length).is_none() {
- return vm.throw_completion(ErrorKind::RangeError, ErrorType::InvalidLength, &[&"typed array"]);
- }
+ validate_typed_array_length(vm, length, element_size)?;
// 3. Let byteLength be elementSize × length.
let byte_length = element_size * length;
diff --git a/Tests/LibJS/Runtime/builtins/ArrayBuffer/ArrayBuffer-max-byte-length.js b/Tests/LibJS/Runtime/builtins/ArrayBuffer/ArrayBuffer-max-byte-length.js
new file mode 100644
index 00000000000..ec4f0cdda32
--- /dev/null
+++ b/Tests/LibJS/Runtime/builtins/ArrayBuffer/ArrayBuffer-max-byte-length.js
@@ -0,0 +1,68 @@
+// Buffers are capped at 2^32 bytes.
+const maxLength = 2 ** 32;
+
+test("buffers of the largest byte length", () => {
+ expect(new ArrayBuffer(maxLength).byteLength).toBe(maxLength);
+ expect(() => new ArrayBuffer(maxLength + 1)).toThrowWithMessage(RangeError, "Invalid array buffer length");
+
+ const resizable = new ArrayBuffer(0, { maxByteLength: maxLength });
+ resizable.resize(maxLength);
+ expect(resizable.byteLength).toBe(maxLength);
+ expect(() => new ArrayBuffer(0, { maxByteLength: maxLength + 1 })).toThrowWithMessage(
+ RangeError,
+ "Invalid array buffer length"
+ );
+
+ expect(new ArrayBuffer(8).transfer(maxLength).byteLength).toBe(maxLength);
+ expect(() => new ArrayBuffer(8).transfer(maxLength + 1)).toThrowWithMessage(
+ RangeError,
+ "Invalid array buffer length"
+ );
+
+ expect(new SharedArrayBuffer(0, { maxByteLength: maxLength }).maxByteLength).toBe(maxLength);
+ expect(() => new SharedArrayBuffer(0, { maxByteLength: maxLength + 1 })).toThrowWithMessage(
+ RangeError,
+ "Invalid shared array buffer length"
+ );
+});
+
+test("views of a buffer of the largest byte length", () => {
+ const buffer = new ArrayBuffer(maxLength);
+
+ const view = new Uint8Array(buffer);
+ view[maxLength - 1] = 42;
+ expect(view).toHaveLength(maxLength);
+ expect(view.byteLength).toBe(maxLength);
+ expect(view[maxLength - 1]).toBe(42);
+ expect(view.at(-1)).toBe(42);
+ expect(view[-1]).toBeUndefined();
+ view[-1] = 1;
+ expect(view[maxLength - 1]).toBe(42);
+ expect(view.lastIndexOf(42)).toBe(maxLength - 1);
+ expect(view.subarray(-1).byteOffset).toBe(maxLength - 1);
+ expect(Array.from(view.slice(-1))).toEqual([42]);
+
+ const empty = new Uint8Array(buffer, maxLength);
+ expect(empty).toHaveLength(0);
+ expect(empty.byteOffset).toBe(maxLength);
+ expect(() => new Uint8Array(buffer, 0, maxLength + 1)).toThrow(RangeError);
+
+ expect(new Float64Array(buffer)).toHaveLength(maxLength / 8);
+
+ const dataView = new DataView(buffer);
+ expect(dataView.byteLength).toBe(maxLength);
+ expect(dataView.getUint8(maxLength - 1)).toBe(42);
+ expect(new DataView(buffer, maxLength).byteOffset).toBe(maxLength);
+ expect(() => new DataView(buffer, 0, maxLength + 1)).toThrow(RangeError);
+});
+
+test("length-tracking views of a resizable buffer of the largest byte length", () => {
+ const buffer = new ArrayBuffer(maxLength, { maxByteLength: maxLength });
+
+ const view = new Uint8Array(buffer);
+ view[maxLength - 1] = 7;
+ expect(view).toHaveLength(maxLength);
+ expect(view[maxLength - 1]).toBe(7);
+
+ expect(new DataView(buffer).byteLength).toBe(maxLength);
+});
diff --git a/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-length-above-int32-max.js b/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-length-above-int32-max.js
index 40f2956ef13..f5e26904514 100644
--- a/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-length-above-int32-max.js
+++ b/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-length-above-int32-max.js
@@ -1,13 +1,10 @@
-// Only a length-tracking view can be this long, since fixed-length views are capped at INT32_MAX bytes.
const length = 0x80000001;
const typedArray = new Uint8Array(new ArrayBuffer(length, { maxByteLength: length }));
typedArray[length - 2] = 11;
typedArray[length - 1] = 22;
-test("copying into a fixed-length view", () => {
- [Uint8Array, Float64Array].forEach(T => {
- expect(() => new T(typedArray)).toThrowWithMessage(RangeError, "Invalid typed array length");
- });
+test("copying into a view longer than the largest buffer", () => {
+ expect(() => new Float64Array(typedArray)).toThrowWithMessage(RangeError, "Invalid typed array length");
});
test("find, findIndex, findLast and findLastIndex", () => {
diff --git a/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-limits.js b/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-limits.js
index 38abb09c794..eb13a52dfd8 100644
--- a/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-limits.js
+++ b/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-limits.js
@@ -1,8 +1,9 @@
test("some oversized typed arrays", () => {
- expect(() => new Uint8Array(2 * 1024 * 1024 * 1024)).toThrowWithMessage(RangeError, "Invalid typed array length");
- expect(() => new Uint16Array(2 * 1024 * 1024 * 1024)).toThrowWithMessage(RangeError, "Invalid typed array length");
- expect(() => new Uint32Array(1024 * 1024 * 1024)).toThrowWithMessage(RangeError, "Invalid typed array length");
- expect(() => new Uint32Array(4 * 1024 * 1024 * 1024)).toThrowWithMessage(RangeError, "Invalid typed array length");
+ expect(() => new Uint8Array(2 ** 32 + 1)).toThrowWithMessage(RangeError, "Invalid typed array length");
+ expect(() => new Uint16Array(2 ** 31 + 1)).toThrowWithMessage(RangeError, "Invalid typed array length");
+ expect(() => new Uint32Array(2 ** 30 + 1)).toThrowWithMessage(RangeError, "Invalid typed array length");
+ expect(() => new Float64Array(2 ** 29 + 1)).toThrowWithMessage(RangeError, "Invalid typed array length");
+ expect(() => new Uint32Array(2 ** 32)).toThrowWithMessage(RangeError, "Invalid typed array length");
});
test("default species creation preserves constructor length limits", () => {
@@ -20,7 +21,7 @@ test("default species creation preserves constructor length limits", () => {
BigUint64Array,
BigInt64Array,
].forEach(T => {
- const oversizedLength = Math.floor(0x7fffffff / T.BYTES_PER_ELEMENT) + 1;
+ const oversizedLength = 2 ** 32 / T.BYTES_PER_ELEMENT + 1;
expect(() => createDefaultTypedArray(new T(), oversizedLength)).toThrowWithMessage(
RangeError,
"Invalid typed array length"