Truly independent web browser
LibCompositing+Compositor: Replay large WebGL uploads in place
Aliaksandr Kalenik2fcbfa5a8f82
diff --git a/Libraries/LibCompositing/Rust/src/webgl/wire.rs b/Libraries/LibCompositing/Rust/src/webgl/wire.rsindex 16d8ec3ed24..db61d9122a1 100644--- a/Libraries/LibCompositing/Rust/src/webgl/wire.rs+++ b/Libraries/LibCompositing/Rust/src/webgl/wire.rs@@ -291,7 +291,7 @@ pub fn encode_sync_request<R: SyncRequest>(true}-fn read_header(bytes: &[u8]) -> Option<(u16, usize)> {+pub fn read_header(bytes: &[u8]) -> Option<(u16, usize)> {let header: &[u8; HEADER_SIZE] = bytes.first_chunk()?;let type_number = u16::from_ne_bytes([header[0], header[1]]);let size_after_header = u32::from_ne_bytes(*header[HEADER_PAYLOAD_SIZE_OFFSET..].first_chunk()?);diff --git a/Services/Compositor/Rust/generate/webgl_replayer.rs b/Services/Compositor/Rust/generate/webgl_replayer.rsindex 03f633cd18f..409a7b99187 100644--- a/Services/Compositor/Rust/generate/webgl_replayer.rs+++ b/Services/Compositor/Rust/generate/webgl_replayer.rs@@ -280,6 +280,13 @@ fn data_pointer(argument: &Argument, bytes: &str) -> String {}}+fn opaque_data_pointer(argument: &Argument, data: &str) -> String {+ match element_type(argument) {+ Some(element) => format!("typed_opaque_data::<{element}>({data})?"),+ None => format!("{data}.pointer.cast()"),+ }+}+/// Resolves the data of an argument that points at some, and answers what the GL function is passed for it.fn write_data_resolution(out: &mut String, function: &Function, argument: &Argument) -> Result<String, String> {let field = field_name(argument);@@ -293,8 +300,8 @@ fn write_data_resolution(out: &mut String, function: &Function, argument: &Argumwriteln!(out," let {field}_data = if command.has_{field} {{- let bytes = if command.{field}.size != 0 {{ data_span(payload, command.{field})? }} else {{ &[] }};- if !size_matches(bytes.len(), {factors}) {{+ let data = if command.{field}.size != 0 {{ self.opaque_data(payload, command.{field})? }} else {{ OpaqueData::EMPTY }};+ if !size_matches(data.size, {factors}) {{return Err({mismatch});}}if command.{field}.size != 0 {{ {} }} else {{ core::ptr::null() }}@@ -304,19 +311,19 @@ fn write_data_resolution(out: &mut String, function: &Function, argument: &Argum}}core::ptr::null()}};",- data_pointer(argument, "bytes"),+ opaque_data_pointer(argument, "data"),argument.name).unwrap();} else {writeln!(out,- " let {field}_bytes = data_span(payload, command.{field})?;- if !size_matches({field}_bytes.len(), {factors}) {{+ " let {field}_opaque_data = self.opaque_data(payload, command.{field})?;+ if !size_matches({field}_opaque_data.size, {factors}) {{return Err({mismatch});}}let {field}_data = {};",- data_pointer(argument, &format!("{field}_bytes"))+ opaque_data_pointer(argument, &format!("{field}_opaque_data"))).unwrap();}@@ -643,6 +650,35 @@ pub fn write_replayer(functions: &[Function]) -> Result<String, String> {Category::Custom | Category::BuiltinCommand => {}}}+ out.push_str("}\n\n");++ let commands_with_only_opaque_data: Vec<String> = functions+ .iter()+ .filter(|function| function.category == Category::Command && has_only_opaque_data(function))+ .map(|function| format!("CommandType::{}", function.command_name()))+ .collect();+ out.push_str("pub fn only_gl_reads_the_data_of(command_type: CommandType) -> bool {\n");+ if commands_with_only_opaque_data.is_empty() {+ out.push_str(" let _ = command_type;\n false\n");+ } else {+ writeln!(+ out,+ " matches!(command_type, {})",+ commands_with_only_opaque_data.join(" | ")+ )+ .unwrap();+ }out.push_str("}\n");Ok(out)}++fn has_only_opaque_data(function: &Function) -> bool {+ let reads_its_data = function+ .arguments+ .iter()+ .any(|argument| argument.is_string || (argument.is_object && argument.is_const_pointer()));+ let has_data_that_write_data_resolution_resolves = function.arguments.iter().any(|argument| {+ !argument.is_string && !argument.is_offset && !argument.is_object && argument.payload.is_some()+ });+ has_data_that_write_data_resolution_resolves && !reads_its_data+}diff --git a/Services/Compositor/Rust/src/webgl/mod.rs b/Services/Compositor/Rust/src/webgl/mod.rsindex b3bdd1ed47a..85eeb13c79d 100644--- a/Services/Compositor/Rust/src/webgl/mod.rs+++ b/Services/Compositor/Rust/src/webgl/mod.rs@@ -19,9 +19,12 @@ mod testing;mod tests;use std::collections::HashMap;+use std::ops::Range;use std::sync::atomic::{AtomicU64, Ordering};use libcompositing_rust::display_list::commands::CanvasId;+use libcompositing_rust::webgl::vocabulary::{CommandType, MAX_COMMAND_STRUCT_SIZE};+use libcompositing_rust::webgl::wire::{HEADER_SIZE, read_header};use libcompositing_rust::webgl::{ImageSource, SHARED_DATA_REGION_OFFSET};use libgfx_rust::{IntRect, IntSize};@@ -30,7 +33,7 @@ use self::gl::GlFunctions;use self::gl_constants::GL_MAP_READ_BIT;use self::host::{ContextOptions, DefaultBuffers, MappedMemory, PresentOutcome, WebGLHost};use self::object_map::ObjectMap;-use self::replay::{ReplayError, Replayer};+use self::replay::{PayloadInSharedMemory, ReplayError, Replayer, only_gl_reads_the_data_of};use crate::host::WebContentClientId;const MAX_DRAWING_BUFFER_DIMENSION: i32 = 16384;@@ -38,6 +41,10 @@ const MAX_DRAWING_BUFFER_DIMENSION: i32 = 16384;/// A copy of what is replayed that holds more than this is not kept for the next message.const MAX_KEPT_SCRATCH_SIZE: usize = 1024 * 1024;+/// A record with a payload this big, which holds data that only GL reads, is replayed where WebContent wrote it rather+/// than copied.+const SMALLEST_PAYLOAD_REPLAYED_IN_PLACE: usize = 16 * 1024;+pub struct CreatedContext {pub canvas_id: CanvasId,pub supported_extensions: Vec<String>,@@ -97,6 +104,73 @@ unsafe fn copy_to_scratch(scratch: &mut Vec<u64>, bytes: *const u8, size: usize)}}+/// # Safety+///+/// `commands` is valid for reads of the bytes of `records`.+unsafe fn replay_copied_records<H: WebGLHost>(+ replayer: &mut Replayer<'_, H>,+ scratch: &mut Vec<u64>,+ commands: *const u8,+ records: Range<usize>,+) -> Result<(), ReplayError> {+ if records.is_empty() {+ return Ok(());+ }+ // SAFETY: Guaranteed by the caller.+ let copy = unsafe { copy_to_scratch(scratch, commands.add(records.start), records.len()) };+ replayer.replay_commands(copy)+}++/// Replays records that WebContent can write while they are replayed. Runs of records are copied before they are+/// replayed, and a record with a large payload that only GL reads is replayed where it is, with only its struct copied.+///+/// # Safety+///+/// `commands` is valid for reads of `size` bytes, which stay mapped while they are replayed.+unsafe fn replay_records_in_shared_memory<H: WebGLHost>(+ replayer: &mut Replayer<'_, H>,+ scratch: &mut Vec<u64>,+ commands: *const u8,+ size: usize,+) -> Result<(), ReplayError> {+ let mut copied_records_start = 0;+ let mut offset = 0;+ while size - offset >= HEADER_SIZE {+ let mut header = [0_u8; HEADER_SIZE];+ // SAFETY: The header lies inside the records.+ unsafe { core::ptr::copy_nonoverlapping(commands.add(offset), header.as_mut_ptr(), HEADER_SIZE) };+ let Some((type_number, payload_size)) = read_header(&header) else {+ break;+ };+ let payload_start = offset + HEADER_SIZE;+ if payload_size > size - payload_start {+ break;+ }+ let command_type = CommandType::from_number(type_number).filter(|&command_type| {+ payload_size >= SMALLEST_PAYLOAD_REPLAYED_IN_PLACE && only_gl_reads_the_data_of(command_type)+ });+ if let Some(command_type) = command_type {+ // SAFETY: Guaranteed by the caller.+ unsafe { replay_copied_records(replayer, scratch, commands, copied_records_start..offset)? };+ // SAFETY: The payload lies inside the records.+ let payload = unsafe { commands.add(payload_start) };+ // SAFETY: As above.+ let struct_bytes = unsafe { copy_to_scratch(scratch, payload, payload_size.min(MAX_COMMAND_STRUCT_SIZE)) };+ replayer.payload_in_shared_memory = Some(PayloadInSharedMemory {+ start: payload,+ size: payload_size,+ });+ let result = replayer.replay_record(command_type, struct_bytes);+ replayer.payload_in_shared_memory = None;+ result?;+ copied_records_start = payload_start + payload_size;+ }+ offset = payload_start + payload_size;+ }+ // SAFETY: Guaranteed by the caller.+ unsafe { replay_copied_records(replayer, scratch, commands, copied_records_start..size) }+}+#[derive(Default)]pub struct WebGLContexts {gl: Option<Box<GlFunctions>>,@@ -220,6 +294,7 @@ impl WebGLContexts {stashed_errors: &mut context.stashed_errors,defaults,image_sources,+ payload_in_shared_memory: None,};commands(&mut replayer)}@@ -258,14 +333,15 @@ impl WebGLContexts {};let mut scratch = core::mem::take(&mut context.scratch);// SAFETY: The range lies inside the region of records of the mapping, which is readable.- let commands = unsafe { copy_to_scratch(&mut scratch, base.add(SHARED_DATA_REGION_OFFSET + offset), size) };- // NB: The records were copied, so WebContent may write over them once it learns that they were taken.+ let commands = unsafe { base.add(SHARED_DATA_REGION_OFFSET + offset) };+ let result = Self::replay(context, gl, host, client, canvas_id, image_sources, |replayer| {+ // SAFETY: The context holds the mapping while the records are replayed.+ unsafe { replay_records_in_shared_memory(replayer, &mut scratch, commands, size) }+ });+ // NB: The records were replayed, so WebContent may write over them once it learns that they were taken.// SAFETY: The mapping starts at a page, where the u64 that the sequence number is stored in is, and WebContent// only reads it.unsafe { AtomicU64::from_ptr(base.cast::<u64>()) }.store(flush_sequence_number, Ordering::Release);- let result = Self::replay(context, gl, host, client, canvas_id, image_sources, |replayer| {- replayer.replay_commands(commands)- });context.give_back_scratch(scratch);result}@@ -281,10 +357,9 @@ impl WebGLContexts {let (context, gl) = self.context_and_gl(client, canvas_id)?;let commands = commands.ok_or(ReplayError("WebContent sent an invalid WebGL command buffer"))?;let mut scratch = core::mem::take(&mut context.scratch);- // SAFETY: The mapping holds as many readable bytes.- let commands = unsafe { copy_to_scratch(&mut scratch, commands.as_mut_ptr(), commands.len()) };let result = Self::replay(context, gl, host, client, canvas_id, image_sources, |replayer| {- replayer.replay_commands(commands)+ // SAFETY: The mapping holds as many readable bytes, and the caller holds it while the records are replayed.+ unsafe { replay_records_in_shared_memory(replayer, &mut scratch, commands.as_mut_ptr(), commands.len()) }});context.give_back_scratch(scratch);resultdiff --git a/Services/Compositor/Rust/src/webgl/replay.rs b/Services/Compositor/Rust/src/webgl/replay.rsindex 4b9055b8bff..b9fee233457 100644--- a/Services/Compositor/Rust/src/webgl/replay.rs+++ b/Services/Compositor/Rust/src/webgl/replay.rs@@ -29,6 +29,27 @@ pub struct ReplayError(pub &'static str);/// A buffer that a synchronous call fills is never bigger than this.const MAX_OUT_DATA_SIZE: usize = 64 * 1024 * 1024;+/// The payload of a record that is replayed where WebContent wrote it, of which only the struct was copied.+#[derive(Clone, Copy)]+pub struct PayloadInSharedMemory {+ pub start: *const u8,+ pub size: usize,+}++/// Data that only GL reads, which can be in memory that WebContent writes.+#[derive(Clone, Copy)]+pub(super) struct OpaqueData {+ pub pointer: *const u8,+ pub size: usize,+}++impl OpaqueData {+ pub const EMPTY: Self = Self {+ pointer: core::ptr::null(),+ size: 0,+ };+}+pub struct Replayer<'a, H: WebGLHost> {pub gl: &'a GlFunctions,pub host: &'a H,@@ -39,6 +60,7 @@ pub struct Replayer<'a, H: WebGLHost> {pub stashed_errors: &'a mut Vec<u32>,pub defaults: DefaultBuffers,pub image_sources: &'a [ImageSource],+ pub payload_in_shared_memory: Option<PayloadInSharedMemory>,}impl<H: WebGLHost> Replayer<'_, H> {@@ -80,6 +102,26 @@ impl<H: WebGLHost> Replayer<'_, H> {}}+ pub(super) fn opaque_data(&self, payload: &[u8], span: DataSpan) -> Result<OpaqueData, ReplayError> {+ let Some(payload_in_shared_memory) = self.payload_in_shared_memory else {+ let bytes = data_span(payload, span)?;+ return Ok(OpaqueData {+ pointer: bytes.as_ptr(),+ size: bytes.len(),+ });+ };+ let start = span.offset as usize;+ start+ .checked_add(span.size as usize)+ .filter(|&end| end <= payload_in_shared_memory.size)+ .ok_or(ReplayError("WebGL data span lies outside its payload"))?;+ Ok(OpaqueData {+ // SAFETY: The span lies inside the payload, which stays mapped while the record is replayed.+ pointer: unsafe { payload_in_shared_memory.start.add(start) },+ size: span.size as usize,+ })+ }+pub fn discard_errors(&mut self) {loop {// SAFETY: The context of the replayer is current.@@ -105,10 +147,17 @@ pub(super) fn data_span(payload: &[u8], span: DataSpan) -> Result<&[u8], ReplayE}pub(super) fn typed_data<T>(bytes: &[u8]) -> Result<*const T, ReplayError> {- if !bytes.as_ptr().cast::<T>().is_aligned() || !bytes.len().is_multiple_of(size_of::<T>()) {+ typed_opaque_data(OpaqueData {+ pointer: bytes.as_ptr(),+ size: bytes.len(),+ })+}++pub(super) fn typed_opaque_data<T>(data: OpaqueData) -> Result<*const T, ReplayError> {+ if !data.pointer.cast::<T>().is_aligned() || !data.size.is_multiple_of(size_of::<T>()) {return Err(ReplayError("WebGL data does not hold whole values"));}- Ok(bytes.as_ptr().cast())+ Ok(data.pointer.cast())}/// A string that ends at the last byte of its span.diff --git a/Services/Compositor/Rust/src/webgl/tests.rs b/Services/Compositor/Rust/src/webgl/tests.rsindex ce951e7341b..d9b678fac44 100644--- a/Services/Compositor/Rust/src/webgl/tests.rs+++ b/Services/Compositor/Rust/src/webgl/tests.rs@@ -272,6 +272,140 @@ fn data_that_may_be_null_is_either_there_or_empty() {);}+struct BufferDataCall {+ data_address: usize,+ first_byte: u8,+ executed_flush_sequence_number: u64,+}++thread_local! {+ static BUFFER_DATA_CALLS: core::cell::RefCell<Vec<BufferDataCall>> = const { core::cell::RefCell::new(Vec::new()) };+ static SHARED_COMMAND_BUFFER_START: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };+}++unsafe extern "system" fn buffer_data_that_notes_where_its_data_is(+ _: u32,+ _: isize,+ data: *const core::ffi::c_void,+ _: u32,+) {+ let shared_command_buffer_start = SHARED_COMMAND_BUFFER_START.get();+ // SAFETY: The replayer passes data that holds the bytes of the call, and a test that sets the start of a shared+ // command buffer holds the buffer.+ let call = unsafe {+ BufferDataCall {+ data_address: data as usize,+ first_byte: data.cast::<u8>().read(),+ executed_flush_sequence_number: if shared_command_buffer_start == 0 {+ 0+ } else {+ (shared_command_buffer_start as *const u64).read()+ },+ }+ };+ BUFFER_DATA_CALLS.with_borrow_mut(|calls| calls.push(call));+}++fn contexts_that_note_where_buffer_data_is(host: &FakeHost) -> (WebGLContexts, CanvasId) {+ reset();+ BUFFER_DATA_CALLS.take();+ SHARED_COMMAND_BUFFER_START.set(0);+ let mut gl = recording::functions();+ gl.buffer_data = buffer_data_that_notes_where_its_data_is;+ let mut contexts = WebGLContexts::with_gl_functions(gl);+ let canvas_id = contexts.create(host, CLIENT, options(false)).unwrap().canvas_id;+ (contexts, canvas_id)+}++fn buffer_data_of(bytes: &[u8]) -> Vec<u8> {+ let data = InlineData::Bytes(bytes);+ record_of(+ &commands::BufferData {+ target: GL_ARRAY_BUFFER,+ size: bytes.len() as i64,+ has_data: true,+ data: DataSpan::following::<commands::BufferData>(data),+ usage: GL_STATIC_DRAW,+ ..commands::BufferData::ZEROED+ },+ data,+ )+}++#[test]+fn a_large_upload_is_passed_to_gl_where_webcontent_wrote_it() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_that_note_where_buffer_data_is(&host);+ let records = [+ buffer_data_of(&[9; 64]),+ buffer_data_of(&vec![7; 64 * 1024]),+ buffer_data_of(&[5; 64]),+ ];+ let commands = TestMemory::new(&records.concat());+ let written = commands.bytes().as_ptr_range();+ let written = written.start as usize..written.end as usize;+ contexts+ .execute_commands(&host, CLIENT, canvas_id, Some(&commands), &[])+ .unwrap();+ let calls = BUFFER_DATA_CALLS.take();+ let placements: Vec<(u8, bool)> = calls+ .iter()+ .map(|call| (call.first_byte, written.contains(&call.data_address)))+ .collect();+ assert_eq!(placements, [(9, false), (7, true), (5, false)]);+}++#[test]+fn the_data_of_a_large_upload_lies_inside_its_record() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_that_note_where_buffer_data_is(&host);+ let bytes = vec![7; 64 * 1024];+ let data = InlineData::Bytes(&bytes);+ let span = DataSpan::following::<commands::BufferData>(data);+ let record = record_of(+ &commands::BufferData {+ target: GL_ARRAY_BUFFER,+ size: bytes.len() as i64 + 4096,+ has_data: true,+ data: DataSpan {+ size: span.size + 4096,+ ..span+ },+ usage: GL_STATIC_DRAW,+ ..commands::BufferData::ZEROED+ },+ data,+ );+ let commands = TestMemory::new(&record);+ assert_eq!(+ contexts.execute_commands(&host, CLIENT, canvas_id, Some(&commands), &[]),+ Err(ReplayError("WebGL data span lies outside its payload"))+ );+ assert!(BUFFER_DATA_CALLS.take().is_empty());+}++#[test]+fn a_shared_command_buffer_is_given_back_once_its_records_are_replayed() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_that_note_where_buffer_data_is(&host);+ let record = buffer_data_of(&vec![7; 64 * 1024]);+ let mut shared = vec![0_u8; SHARED_DATA_REGION_OFFSET + record.len()];+ shared[SHARED_DATA_REGION_OFFSET..].copy_from_slice(&record);+ let shared = Box::new(TestMemory::new(&shared));+ let shared_start = shared.bytes().as_ptr();+ SHARED_COMMAND_BUFFER_START.set(shared_start as usize);+ contexts.set_command_buffer(CLIENT, canvas_id, Some(shared)).unwrap();+ contexts+ .execute_commands_from_shared_buffer(&host, CLIENT, canvas_id, 0, record.len() as u64, 42, &[])+ .unwrap();+ let calls = BUFFER_DATA_CALLS.take();+ assert_eq!(calls.len(), 1);+ assert_eq!(calls[0].executed_flush_sequence_number, 0);+ // SAFETY: The test owns the memory, which the context holds.+ assert_eq!(unsafe { shared_start.cast::<u64>().read() }, 42);+ SHARED_COMMAND_BUFFER_START.set(0);+}+#[test]fn a_record_whose_booleans_or_spans_are_out_of_range_is_rejected() {let host = FakeHost::default();@@ -458,6 +592,7 @@ fn the_errors_of_the_compositor_are_collected_before_those_of_gl() {stashed_errors: &mut context.stashed_errors,defaults: host.defaults.get(),image_sources: &[],+ payload_in_shared_memory: None,};assert!(replayer.stash_errors());let errors: Vec<u32> = (0..4).map(|_| replayer.get_error()).collect();diff --git a/Tests/LibWeb/Text/expected/WebGL/large-uploads-reach-gl-intact.txt b/Tests/LibWeb/Text/expected/WebGL/large-uploads-reach-gl-intact.txtnew file mode 100644index 00000000000..71347bd6f1b--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebGL/large-uploads-reach-gl-intact.txt@@ -0,0 +1,4 @@+bufferData: true+bufferSubData: true+texImage2D: true+error: 0diff --git a/Tests/LibWeb/Text/input/WebGL/large-uploads-reach-gl-intact.html b/Tests/LibWeb/Text/input/WebGL/large-uploads-reach-gl-intact.htmlnew file mode 100644index 00000000000..279491f4967--- /dev/null+++ b/Tests/LibWeb/Text/input/WebGL/large-uploads-reach-gl-intact.html@@ -0,0 +1,38 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ function pattern(size, step) {+ return new Uint8Array(size).map((_, index) => (index * step) & 0xff);+ }++ test(() => {+ const gl = document.createElement("canvas").getContext("webgl2");++ const bufferBytes = pattern(64 * 1024, 7);+ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());+ gl.bufferData(gl.ARRAY_BUFFER, bufferBytes, gl.STATIC_DRAW);+ const bufferReadBack = new Uint8Array(bufferBytes.length);+ gl.getBufferSubData(gl.ARRAY_BUFFER, 0, bufferReadBack);+ println(`bufferData: ${bufferReadBack.every((value, index) => value === bufferBytes[index])}`);++ const updateOffset = 1024;+ const update = pattern(32 * 1024, 11);+ gl.bufferSubData(gl.ARRAY_BUFFER, updateOffset, update);+ gl.getBufferSubData(gl.ARRAY_BUFFER, 0, bufferReadBack);+ const expectedAfterUpdate = bufferBytes.slice();+ expectedAfterUpdate.set(update, updateOffset);+ println(`bufferSubData: ${bufferReadBack.every((value, index) => value === expectedAfterUpdate[index])}`);++ const size = 128;+ const texels = pattern(size * size * 4, 13);+ gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, texels);+ gl.bindFramebuffer(gl.FRAMEBUFFER, gl.createFramebuffer());+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, gl.getParameter(gl.TEXTURE_BINDING_2D), 0);+ const texelsReadBack = new Uint8Array(texels.length);+ gl.readPixels(0, 0, size, size, gl.RGBA, gl.UNSIGNED_BYTE, texelsReadBack);+ println(`texImage2D: ${texelsReadBack.every((value, index) => value === texels[index])}`);++ println(`error: ${gl.getError()}`);+ });+</script>