Truly independent web browser
LibJS: Copy external storage when a stream transfers an ArrayBuffer
Tim Ledbetterc2f7e8de35dc
diff --git a/Libraries/LibJS/Runtime/ArrayBuffer.h b/Libraries/LibJS/Runtime/ArrayBuffer.hindex 8eedc7ac654..700f0593622 100644--- a/Libraries/LibJS/Runtime/ArrayBuffer.h+++ b/Libraries/LibJS/Runtime/ArrayBuffer.h@@ -338,7 +338,7 @@ public:DataBlock const data_block() const;// Detaches this ArrayBuffer and returns its underlying DataBlock for use in a TransferArrayBuffer-like operation.- // If detach fails, the underlying storage is left untouched.+ // If detach fails, the underlying storage is left untouched. External storage is returned as a copy.ThrowCompletionOr<DataBlock> detach_and_take_data_block(VM&);// [[ArrayBufferMaxByteLength]]diff --git a/Libraries/LibJS/Rust/src/embedding/array_buffer.rs b/Libraries/LibJS/Rust/src/embedding/array_buffer.rsindex 128b4165e5f..3055ed37146 100644--- a/Libraries/LibJS/Rust/src/embedding/array_buffer.rs+++ b/Libraries/LibJS/Rust/src/embedding/array_buffer.rs@@ -502,8 +502,8 @@ pub unsafe extern "C" fn js_array_buffer_detach(vm: *mut JSVM, buffer: *mut JSOb/// ArrayBuffer::detach_and_take_data_block(): detaches `buffer`, as DetachArrayBuffer(buffer) does, and describes the/// storage of the data block it had in `out`, which the caller takes over. The caller owns the storage of a block of/// kind JS_ARRAY_BUFFER_STORAGE_OWNED, and frees it with gc_primitive_storage_free() or gives it to-/// js_array_buffer_create_adopting_storage(), and keeps the owner of JS_ARRAY_BUFFER_STORAGE_EXTERNAL storage alive-/// itself. Throws a TypeError, and leaves the buffer as it was, if the buffer has a detach key. Main thread only.+/// js_array_buffer_create_adopting_storage(). Throws a TypeError, and leaves the buffer as it was, if the buffer has a+/// detach key. Main thread only.////// # Safety///@@ -534,16 +534,7 @@ pub unsafe extern "C" fn js_array_buffer_detach_and_take_storage(storage.kind = JS_ARRAY_BUFFER_STORAGE_OWNED;storage.handle = owned.into_handle();}- DataBlockStorage::External(external) => {- storage.kind = JS_ARRAY_BUFFER_STORAGE_EXTERNAL;- storage.handle = external.handle();- storage.external = JSExternalPrimitiveStorage {- owner: external.owner().as_ptr(),- handle: external.handle(),- fixed_byte_length: external.fixed_byte_length().unwrap_or(0),- has_fixed_byte_length: external.fixed_byte_length().is_some(),- };- }+ DataBlockStorage::External(_) => unreachable!("external storage is copied when it is taken"),DataBlockStorage::Shared(_) => unreachable!("a SharedArrayBuffer is never detached"),}storagediff --git a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs b/Libraries/LibJS/Rust/src/runtime/array_buffer.rsindex 0c2aaba7d21..2d6cde19f02 100644--- a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs+++ b/Libraries/LibJS/Rust/src/runtime/array_buffer.rs@@ -1128,7 +1128,7 @@ impl ArrayBuffer {}// Detaches this ArrayBuffer and returns its underlying DataBlock for use in a TransferArrayBuffer-like operation.- // If detach fails, the underlying storage is left untouched.+ // If detach fails, the underlying storage is left untouched. External storage is returned as a copy.pub fn detach_and_take_data_block(&self, vm: &Vm) -> ThrowCompletionOr<DataBlock> {assert!(!self.is_shared_array_buffer());@@ -1140,12 +1140,30 @@ impl ArrayBuffer {);}+ let copy_of_external_storage = if self.is_external() {+ let byte_length = self.byte_length();+ let Ok(storage) =+ allocate_or_retry_after_gc(vm.heap(), || OwnedBackingStore::create_uninitialized(byte_length))+ else {+ return vm.throw_completion(+ ErrorKind::RangeError,+ ErrorType::NotEnoughMemoryToAllocate,+ &[&byte_length],+ );+ };+ let copy = DataBlock::new(storage, Shared::No);+ self.copy_data_to_block(©, 0, 0, byte_length);+ Some(copy)+ } else {+ None+ };+let old_external_memory_size = self.external_memory_size();let is_shared = self.data_block.borrow().is_shared;let block = self.data_block.replace(DataBlock::empty(is_shared));self.invalidate_cached_typed_array_view_offsets();self.account_external_memory_change(vm, old_external_memory_size, 0);- Ok(block)+ Ok(copy_of_external_storage.unwrap_or(block))}// [[ArrayBufferMaxByteLength]]diff --git a/Tests/LibWeb/Text/expected/WebAudio/AudioBuffer-channel-data-transferred-by-stream.txt b/Tests/LibWeb/Text/expected/WebAudio/AudioBuffer-channel-data-transferred-by-stream.txtnew file mode 100644index 00000000000..f75b6c4e79c--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebAudio/AudioBuffer-channel-data-transferred-by-stream.txt@@ -0,0 +1,2 @@+chunk holds the samples it was given: true+AudioBuffer unchanged by writes through the chunk: truediff --git a/Tests/LibWeb/Text/input/WebAudio/AudioBuffer-channel-data-transferred-by-stream.html b/Tests/LibWeb/Text/input/WebAudio/AudioBuffer-channel-data-transferred-by-stream.htmlnew file mode 100644index 00000000000..a8d5f06c616--- /dev/null+++ b/Tests/LibWeb/Text/input/WebAudio/AudioBuffer-channel-data-transferred-by-stream.html@@ -0,0 +1,35 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const audioBuffer = new AudioBuffer({ numberOfChannels: 1, length: 1024, sampleRate: 8000 });++ const readChunk = async () => {+ const channel = audioBuffer.getChannelData(0);+ channel.fill(0.25);+ let controller;+ const stream = new ReadableStream({+ type: "bytes",+ start(c) {+ controller = c;+ },+ });+ controller.enqueue(channel);+ const { value } = await stream.getReader().read();+ return new Float32Array(value.buffer, value.byteOffset, value.byteLength / Float32Array.BYTES_PER_ELEMENT);+ };++ const chunk = await readChunk();+ internals.gc();+ internals.gc();++ const context = new OfflineAudioContext(1, 128, 8000);+ new AudioBufferSourceNode(context, { buffer: audioBuffer }).start();+ const channel = audioBuffer.getChannelData(0);++ println(`chunk holds the samples it was given: ${chunk.every(sample => sample === 0.25)}`);++ chunk.fill(-1);+ println(`AudioBuffer unchanged by writes through the chunk: ${channel[0] !== -1}`);+ });+</script>