Skip to content

Truly independent web browser

LibWeb: Do not panic in stream steps that script can get ahead of

Andreas Klingdaead28014e5
diff --git a/Libraries/LibWeb/Bindings/Rust/src/compression/compression_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/compression/compression_stream.rs
index dd2a7ae5866..15a5ba33179 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/compression/compression_stream.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/compression/compression_stream.rs
@@ -129,7 +129,7 @@ impl TransformSteps for CompressionContext {
let array = create_uint8_array(cx, &buffer)?;
// 5. For each Uint8Array array of arrays, enqueue array in cs's transform.
- TransformStream::enqueue(transform, cx.vm(), Value::from_object(array));
+ TransformStream::enqueue(transform, cx.vm(), Value::from_object(array))?;
Ok(())
}
@@ -152,7 +152,7 @@ impl TransformSteps for CompressionContext {
let array = create_uint8_array(cx, &buffer)?;
// 4. For each Uint8Array array of arrays, enqueue array in cs's transform.
- TransformStream::enqueue(transform, cx.vm(), Value::from_object(array));
+ TransformStream::enqueue(transform, cx.vm(), Value::from_object(array))?;
Ok(())
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/compression/decompression_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/compression/decompression_stream.rs
index d6a02fdb066..5e4ce683d2f 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/compression/decompression_stream.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/compression/decompression_stream.rs
@@ -121,7 +121,7 @@ impl TransformSteps for DecompressionContext {
let array = create_uint8_array(cx, &buffer)?;
// 5. For each Uint8Array array of arrays, enqueue array in ds's transform.
- TransformStream::enqueue(transform, cx.vm(), Value::from_object(array));
+ TransformStream::enqueue(transform, cx.vm(), Value::from_object(array))?;
}
// 6. If the end of the compressed input has been reached, and ds's context has not fully consumed chunk, then
@@ -152,7 +152,7 @@ impl TransformSteps for DecompressionContext {
let array = create_uint8_array(cx, &buffer)?;
// 2. For each Uint8Array array of arrays, enqueue array in ds's transform.
- TransformStream::enqueue(transform, cx.vm(), Value::from_object(array));
+ TransformStream::enqueue(transform, cx.vm(), Value::from_object(array))?;
}
// 3. If the end of the compressed input has not been reached, then throw a TypeError.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder_stream.rs
index 10fefbcd911..59e96c88da7 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder_stream.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder_stream.rs
@@ -146,15 +146,16 @@ impl EmbedderValue for Decoder {
}
/// Enqueues the output of the decoder in the transform as a string, unless it is the empty string.
-fn enqueue_output_chunk(cx: &CallContext, transform: Ref<TransformStream>, output: &[u16]) {
+fn enqueue_output_chunk(cx: &CallContext, transform: Ref<TransformStream>, output: &[u16]) -> WebIdlResult<()> {
let output_chunk = UsvString::from_utf16_replacing_lone_surrogates(output).into_utf16_string();
if !output_chunk.is_empty() {
TransformStream::enqueue(
transform,
cx.vm(),
Value::from_string(PrimitiveString::create(cx.vm(), output_chunk)),
- );
+ )?;
}
+ Ok(())
}
fn decoding_failed(_: DecodingFailed) -> Exception {
@@ -188,8 +189,7 @@ impl TransformSteps for Decoder {
// the chunk while its bytes are read.
let output =
unsafe { buffer_source.with_bytes(|bytes| decoder.decode(bytes, true)) }.map_err(decoding_failed)?;
- enqueue_output_chunk(cx, transform, &output);
- Ok(())
+ enqueue_output_chunk(cx, transform, &output)
}
// https://encoding.spec.whatwg.org/#flush-and-enqueue
@@ -206,7 +206,6 @@ impl TransformSteps for Decoder {
// 4. Otherwise, if result is error, throw a TypeError.
// NB: The decoder's I/O queue holds no more bytes, so the decoder decodes the end of the input.
let output = self.decoder.borrow_mut().decode(&[], false).map_err(decoding_failed)?;
- enqueue_output_chunk(cx, transform, &output);
- Ok(())
+ enqueue_output_chunk(cx, transform, &output)
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder_stream.rs
index 203972a5dc9..4b72cff7170 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder_stream.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder_stream.rs
@@ -170,7 +170,7 @@ impl TransformSteps for Encoder {
let chunk = create_uint8_array(cx, &output)?;
// 2. Enqueue chunk into encoder's transform.
- TransformStream::enqueue(transform, cx.vm(), Value::from_object(chunk));
+ TransformStream::enqueue(transform, cx.vm(), Value::from_object(chunk))?;
}
// 3. Return.
@@ -199,7 +199,7 @@ impl TransformSteps for Encoder {
let chunk = create_uint8_array(cx, &REPLACEMENT_CHARACTER_UTF8_BYTES)?;
// 2. Enqueue chunk into encoder's transform.
- TransformStream::enqueue(transform, cx.vm(), Value::from_object(chunk));
+ TransformStream::enqueue(transform, cx.vm(), Value::from_object(chunk))?;
}
Ok(())
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_byte_stream_controller.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_byte_stream_controller.rs
index 9a2eb2eb4a3..fbcf22fc00d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_byte_stream_controller.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_byte_stream_controller.rs
@@ -1271,7 +1271,9 @@ pub(crate) fn readable_byte_stream_controller_process_read_requests_using_queue(
// 2. Let readRequest be reader.[[readRequests]][0].
// 3. Remove readRequest from reader.[[readRequests]].
- let read_request = reader.take_first_read_request(cx.vm());
+ let read_request = reader
+ .take_first_read_request(cx.vm())
+ .expect("the list of read requests is not empty");
// 4. Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest).
readable_byte_stream_controller_fill_read_request_from_queue(cx, controller, read_request);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs
index 45c180a2759..91baa65e6bf 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs
@@ -1340,14 +1340,18 @@ pub(crate) fn readable_stream_fulfill_read_into_request(
) {
// 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.
// 2. Let reader be stream.[[reader]].
+ // AD-HOC: Fulfilling a request looks up "then" on the result, so script can run in between two requests of one chunk.
+ // A lock that it released took the rest of the requests along, and nobody is waiting for this one anymore.
let Some(ReadableStreamReader::ReadableStreamBYOBReader(reader)) = stream.reader() else {
- panic!("the stream has a ReadableStreamBYOBReader");
+ return;
};
// 3. Assert: reader.[[readIntoRequests]] is not empty.
// 4. Let readIntoRequest be reader.[[readIntoRequests]][0].
// 5. Remove readIntoRequest from reader.[[readIntoRequests]].
- let read_into_request = reader.take_first_read_into_request(vm);
+ let Some(read_into_request) = reader.take_first_read_into_request(vm) else {
+ return;
+ };
// 6. If done is true, perform readIntoRequest’s close steps, given chunk.
if done {
@@ -1363,14 +1367,17 @@ pub(crate) fn readable_stream_fulfill_read_into_request(
pub(crate) fn readable_stream_fulfill_read_request(vm: &Vm, stream: Ref<ReadableStream>, chunk: Value, done: bool) {
// 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.
// 2. Let reader be stream.[[reader]].
+ // AD-HOC: See readable_stream_fulfill_read_into_request().
let Some(ReadableStreamReader::ReadableStreamDefaultReader(reader)) = stream.reader() else {
- panic!("the stream has a ReadableStreamDefaultReader");
+ return;
};
// 3. Assert: reader.[[readRequests]] is not empty.
// 4. Let readRequest be reader.[[readRequests]][0].
// 5. Remove readRequest from reader.[[readRequests]].
- let read_request = reader.take_first_read_request(vm);
+ let Some(read_request) = reader.take_first_read_request(vm) else {
+ return;
+ };
// 6. If done is true, perform readRequest’s close steps.
if done {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_byob_reader.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_byob_reader.rs
index a6de1c6f12f..6674d0e56d5 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_byob_reader.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_byob_reader.rs
@@ -70,11 +70,8 @@ impl ReadableStreamBYOBReader {
}
/// Removes the first of the reader's [[readIntoRequests]], which are not empty.
- pub(crate) fn take_first_read_into_request(&self, vm: &Vm) -> ReadIntoRequest {
- self.read_into_requests
- .borrow_mut(vm)
- .pop_front()
- .expect("the reader has a read-into request")
+ pub(crate) fn take_first_read_into_request(&self, vm: &Vm) -> Option<ReadIntoRequest> {
+ self.read_into_requests.borrow_mut(vm).pop_front()
}
pub(crate) fn read_into_requests_len(&self) -> usize {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_default_reader.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_default_reader.rs
index 3df74334963..637e9c5c972 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_default_reader.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_default_reader.rs
@@ -87,11 +87,8 @@ impl ReadableStreamDefaultReader {
}
/// Removes the first of the reader's [[readRequests]], which are not empty.
- pub(crate) fn take_first_read_request(&self, vm: &Vm) -> ReadRequest {
- self.read_requests
- .borrow_mut(vm)
- .pop_front()
- .expect("the reader has a read request")
+ pub(crate) fn take_first_read_request(&self, vm: &Vm) -> Option<ReadRequest> {
+ self.read_requests.borrow_mut(vm).pop_front()
}
pub(crate) fn read_requests_len(&self) -> usize {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream.rs
index c2193160e0a..b2dbb4af828 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream.rs
@@ -285,9 +285,11 @@ impl TransformStream {
}
// https://streams.spec.whatwg.org/#transformstream-enqueue
- pub(crate) fn enqueue(this: Ref<Self>, vm: &Vm, chunk: Value) {
+ pub(crate) fn enqueue(this: Ref<Self>, vm: &Vm, chunk: Value) -> WebIdlResult<()> {
// To enqueue the JavaScript value chunk into a TransformStream stream, perform
// ! TransformStreamDefaultControllerEnqueue(stream.[[controller]], chunk).
+ // AD-HOC: This can throw: a chunk looks up "then" on the read result, and script there can cancel the readable
+ // side before the next chunk of the same transform.
let controller = this
.controller()
.expect("a transform stream that is set up has a controller");
@@ -296,7 +298,6 @@ impl TransformStream {
controller,
chunk,
)
- .must();
}
}
@@ -597,10 +598,13 @@ pub(crate) fn transform_stream_default_sink_abort_algorithm(
controller.set_finish_promise(Some(create_promise(vm, realm)));
// 5. Let cancelPromise be the result of performing controller.[[cancelAlgorithm]], passing reason.
- let cancel_algorithm = controller
- .cancel_algorithm()
- .expect("the controller's algorithms are not cleared");
- let cancel_promise = cancel_algorithm.run(&stream.context(vm), reason);
+ // AD-HOC: terminate() and an error clear the algorithms without setting controller.[[finishPromise]], and script can
+ // get here after that, by aborting the writable side or canceling the readable side. There is nothing left
+ // to run then.
+ let cancel_promise = match controller.cancel_algorithm() {
+ Some(cancel_algorithm) => cancel_algorithm.run(&stream.context(vm), reason),
+ None => create_resolved_promise(vm, realm, Value::UNDEFINED),
+ };
// 6. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).
transform_stream_default_controller_clear_algorithms(controller);
@@ -688,10 +692,11 @@ pub(crate) fn transform_stream_default_sink_close_algorithm(
controller.set_finish_promise(Some(create_promise(vm, realm)));
// 5. Let flushPromise be the result of performing controller.[[flushAlgorithm]].
- let flush_algorithm = controller
- .flush_algorithm()
- .expect("the controller's algorithms are not cleared");
- let flush_promise = flush_algorithm.run(&stream.context(vm));
+ // AD-HOC: As with the abort algorithm, there is nothing left to run once the algorithms are cleared.
+ let flush_promise = match controller.flush_algorithm() {
+ Some(flush_algorithm) => flush_algorithm.run(&stream.context(vm)),
+ None => create_resolved_promise(vm, realm, Value::UNDEFINED),
+ };
// 6. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).
transform_stream_default_controller_clear_algorithms(controller);
@@ -776,10 +781,13 @@ pub(crate) fn transform_stream_default_source_cancel_algorithm(
controller.set_finish_promise(Some(create_promise(vm, realm)));
// 5. Let cancelPromise be the result of performing controller.[[cancelAlgorithm]], passing reason.
- let cancel_algorithm = controller
- .cancel_algorithm()
- .expect("the controller's algorithms are not cleared");
- let cancel_promise = cancel_algorithm.run(&stream.context(vm), reason);
+ // AD-HOC: terminate() and an error clear the algorithms without setting controller.[[finishPromise]], and script can
+ // get here after that, by aborting the writable side or canceling the readable side. There is nothing left
+ // to run then.
+ let cancel_promise = match controller.cancel_algorithm() {
+ Some(cancel_algorithm) => cancel_algorithm.run(&stream.context(vm), reason),
+ None => create_resolved_promise(vm, realm, Value::UNDEFINED),
+ };
// 6. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).
transform_stream_default_controller_clear_algorithms(controller);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream_default_controller.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream_default_controller.rs
index d258eabdcd1..6519e000af0 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream_default_controller.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream_default_controller.rs
@@ -12,7 +12,7 @@ use core::cell::Cell;
use libjs_rust::api::{GcRefCell, Throw, Trace, Value};
use crate::bindings::interface::{Ref, Wrappable, allocate};
-use crate::bindings::promise::{WebIdlPromise, exception_value, upon_rejection};
+use crate::bindings::promise::{WebIdlPromise, create_resolved_promise, exception_value, upon_rejection};
use crate::bindings::{CallContext, Exception, WebIdlResult};
use crate::streams::algorithms::{CancelAlgorithm, FlushAlgorithm, TransformAlgorithm};
use crate::streams::readable_stream_default_controller::{
@@ -306,10 +306,12 @@ pub(crate) fn transform_stream_default_controller_perform_transform(
let vm = cx.vm();
// 1. Let transformPromise be the result of performing controller.[[transformAlgorithm]], passing chunk.
- let transform_algorithm = controller
- .transform_algorithm()
- .expect("the controller's algorithms are not cleared");
- let transform_promise = transform_algorithm.run(&controller.stream().context(vm), chunk);
+ // AD-HOC: A write that waited for backpressure to go away can get here after terminate() or an error cleared the
+ // algorithms. There is nothing left to run then.
+ let transform_promise = match controller.transform_algorithm() {
+ Some(transform_algorithm) => transform_algorithm.run(&controller.stream().context(vm), chunk),
+ None => create_resolved_promise(vm, cx.realm(), Value::UNDEFINED),
+ };
// 2. Return the result of reacting to transformPromise with the following rejection steps given the argument r:
upon_rejection(vm, transform_promise, controller, |cx, controller, reason| {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream_default_controller.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream_default_controller.rs
index adf1ee5c54e..f39a56de5f7 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream_default_controller.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream_default_controller.rs
@@ -477,7 +477,8 @@ pub(crate) fn writable_stream_default_controller_get_chunk_size(
// 1. If controller.[[strategySizeAlgorithm]] is undefined, then:
let Some(strategy_size_algorithm) = controller.strategy_size_algorithm() else {
// 1. Assert: controller.[[stream]].[[state]] is not "writable".
- assert!(controller.stream().state() != WritableStreamState::Writable);
+ // AD-HOC: This does not hold: closing clears the algorithms, and the stream is "writable" until the sink closed.
+ // A write in that time gets here on its way to being rejected.
// 2. Return 1.
return Value::from_f64(1.0);
diff --git a/Tests/LibWeb/Text/expected/Streams/stream-steps-after-script-changed-the-stream.txt b/Tests/LibWeb/Text/expected/Streams/stream-steps-after-script-changed-the-stream.txt
new file mode 100644
index 00000000000..6c978c932b9
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Streams/stream-steps-after-script-changed-the-stream.txt
@@ -0,0 +1,5 @@
+abort after terminate: survived
+write while closing: TypeError
+write after cancel: undefined
+cancel during transform: TypeError
+release between requests: fulfilled rejected
diff --git a/Tests/LibWeb/Text/input/Streams/stream-steps-after-script-changed-the-stream.html b/Tests/LibWeb/Text/input/Streams/stream-steps-after-script-changed-the-stream.html
new file mode 100644
index 00000000000..57074d7e337
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Streams/stream-steps-after-script-changed-the-stream.html
@@ -0,0 +1,89 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ const nextTask = () => new Promise(resolve => setTimeout(resolve, 0));
+
+ async function abortAfterTerminate() {
+ let controller;
+ let finishTransform;
+ const stream = new TransformStream(
+ {
+ start: c => (controller = c),
+ transform: () => new Promise(resolve => (finishTransform = resolve)),
+ },
+ {},
+ { highWaterMark: 1 }
+ );
+ const writer = stream.writable.getWriter();
+ await nextTask();
+ const write = writer.write(1).catch(() => {});
+ await nextTask();
+ const abort = writer.abort("reason");
+ controller.terminate();
+ finishTransform();
+ await write;
+ await abort;
+ println("abort after terminate: survived");
+ }
+
+ async function writeWhileClosing() {
+ const writer = new WritableStream({ close: () => new Promise(() => {}) }).getWriter();
+ writer.close();
+ await nextTask();
+ const result = await writer.write(1).catch(error => error.name);
+ println(`write while closing: ${result}`);
+ }
+
+ async function writeAfterCancel() {
+ const stream = new TextDecoderStream();
+ const reader = stream.readable.getReader();
+ const writer = stream.writable.getWriter();
+ await nextTask();
+ const write = writer.write(new Uint8Array([97])).catch(error => error.name);
+ await nextTask();
+ reader.read();
+ reader.cancel();
+ println(`write after cancel: ${await write}`);
+ }
+
+ async function cancelDuringTransform() {
+ const stream = new TextEncoderStream();
+ const reader = stream.readable.getReader();
+ const writer = stream.writable.getWriter();
+ await nextTask();
+ reader.read();
+ const chunk = {
+ toString() {
+ reader.cancel();
+ return "a";
+ },
+ };
+ println(`cancel during transform: ${await writer.write(chunk).catch(error => error.name)}`);
+ }
+
+ async function releaseBetweenRequests() {
+ let controller;
+ const stream = new ReadableStream({ type: "bytes", start: c => (controller = c) });
+ const reader = stream.getReader({ mode: "byob" });
+ const reads = [reader.read(new Uint8Array(1)), reader.read(new Uint8Array(1))];
+ Object.defineProperty(Object.prototype, "then", {
+ configurable: true,
+ get() {
+ delete Object.prototype.then;
+ reader.releaseLock();
+ },
+ });
+ controller.enqueue(new Uint8Array([1, 2]));
+ delete Object.prototype.then;
+ const results = await Promise.allSettled(reads);
+ println(`release between requests: ${results.map(result => result.status).join(" ")}`);
+ }
+
+ promiseTest(async () => {
+ await abortAfterTerminate();
+ await writeWhileClosing();
+ await writeAfterCancel();
+ await cancelDuringTransform();
+ await releaseBetweenRequests();
+ });
+</script>