Truly independent web browser
LibWeb: Record WebGL commands in Rust
Aliaksandr Kalenik5bb1c7d9b423
diff --git a/Libraries/LibWeb/Bindings/Rust/build.rs b/Libraries/LibWeb/Bindings/Rust/build.rsindex a36a286c6b5..81d36180bc1 100644--- a/Libraries/LibWeb/Bindings/Rust/build.rs+++ b/Libraries/LibWeb/Bindings/Rust/build.rs@@ -11,7 +11,8 @@//! the crate includes it.//!//! Also generates what the WebGL implementation shares with the rest of the tree: the vocabulary of the command-//! stream and the GL constants. Those do not need the bindings, so every build of the crate has them.+//! stream, the methods of its recorder and the GL constants. Those do not need the bindings, so every build of the+//! crate has them.use std::env;use std::fs;@@ -20,6 +21,9 @@ use std::path::{Path, PathBuf};#[path = "generate/webgl_constants.rs"]mod webgl_constants;+#[path = "generate/webgl_proxy.rs"]+mod webgl_proxy;+#[path = "generate/webgl_wire.rs"]mod webgl_wire;@@ -31,16 +35,20 @@ fn read_tracked(path: &Path) -> String {fs::read_to_string(path).unwrap_or_else(|error| panic!("read {}: {error}", path.display()))}-fn generate_webgl_wire_vocabulary(libraries: &Path, out_dir: &Path) {+fn generate_webgl_command_recording(libraries: &Path, out_dir: &Path) {let functions_path = libraries.join("LibCompositing/WebGL/GLFunctions.json");- let generated = webgl_wire_model::parse_functions(&read_tracked(&functions_path))- .and_then(|functions| {- Ok(webgl_wire::write_wire_vocabulary(&webgl_wire_model::vocabulary(- &functions,- )?))- })+ let generate = |json: &str| -> Result<(String, String), String> {+ let functions = webgl_wire_model::parse_functions(json)?;+ let vocabulary = webgl_wire_model::vocabulary(&functions)?;+ Ok((+ webgl_wire::write_wire_vocabulary(&vocabulary),+ webgl_proxy::write_proxy(&functions)?,+ ))+ };+ let (wire_vocabulary, proxy) = generate(&read_tracked(&functions_path)).unwrap_or_else(|error| panic!("{}: {error}", functions_path.display()));- fs::write(out_dir.join("webgl_wire.rs"), generated).expect("write webgl_wire.rs");+ fs::write(out_dir.join("webgl_wire.rs"), wire_vocabulary).expect("write webgl_wire.rs");+ fs::write(out_dir.join("webgl_proxy.rs"), proxy).expect("write webgl_proxy.rs");}fn idl_files_in(directory: &Path, idl_files: &mut Vec<PathBuf>) {@@ -83,7 +91,7 @@ fn main() {.ancestors().nth(3).expect("the crate is in Libraries/LibWeb/Bindings/Rust");- generate_webgl_wire_vocabulary(libraries, &out_dir);+ generate_webgl_command_recording(libraries, &out_dir);generate_webgl_constants(libraries, &out_dir);println!("cargo:rustc-check-cfg=cfg(web_idl_bindings)");diff --git a/Libraries/LibWeb/Bindings/Rust/generate/webgl_proxy.rs b/Libraries/LibWeb/Bindings/Rust/generate/webgl_proxy.rsnew file mode 100644index 00000000000..6fdd6269872--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/generate/webgl_proxy.rs@@ -0,0 +1,535 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Writes the methods of the WebGL command recorder that follow from the signature of a GL function, which+//! src/web_gl/proxy/generated.rs includes: one per command, per object creation and per synchronous call of+//! GLFunctions.json. A method has the name and the arguments of the GL function, records the struct of the command+//! or makes the round trip of the call, and returns what the function returns.++use std::fmt::Write;++use crate::webgl_wire_model::{+ Argument, Category, FieldSpec, Function, WireStruct, WireType, rust_identifier, title_case_to_snake_case,+ wire_struct,+};++fn parameter_name(argument: &Argument) -> String {+ rust_identifier(&title_case_to_snake_case(&argument.name))+}++fn inline_data_name(argument: &Argument) -> String {+ format!("{}_inline_data", title_case_to_snake_case(&argument.name))+}++fn unsupported(function: &Function, argument: &Argument, what: &str) -> String {+ format!(+ "the recorder has no method for {}, whose argument {} {what}",+ function.name, argument.name+ )+}++fn scalar_parameter_type(function: &Function, argument: &Argument) -> Result<&'static str, String> {+ match WireType::of(&argument.cpp_type) {+ // A GLboolean.+ Some(WireType::U8) => Ok("bool"),+ Some(WireType::DataSpan) | None => Err(unsupported(function, argument, "is not a plain value")),+ Some(wire_type) => Ok(wire_type.rust_type()),+ }+}++fn size_of_gl_type(gl_type: &str) -> Option<usize> {+ Some(match gl_type {+ "GLchar" | "GLboolean" => 1,+ "GLint" | "GLuint" | "GLfloat" | "GLenum" => 4,+ "GLint64" => 8,+ _ => return None,+ })+}++fn payload_size_expression(function: &Function, argument: &Argument) -> Result<String, String> {+ let payload = argument.payload.as_deref().expect("the argument has a payload");+ let mut factors = Vec::new();+ for factor in payload.split(" * ") {+ if factor.bytes().all(|byte| byte.is_ascii_digit()) {+ factors.push(factor.to_string());+ } else if let Some(gl_type) = factor.strip_prefix("sizeof(").and_then(|rest| rest.strip_suffix(')')) {+ let size = size_of_gl_type(gl_type)+ .ok_or_else(|| unsupported(function, argument, &format!("is counted in {gl_type}")))?;+ factors.push(size.to_string());+ } else if factor == "(buffer == GL_COLOR ? 4 : 1)" {+ factors.push("if buffer == GL_COLOR { 4 } else { 1 }".to_string());+ } else {+ let counted_by = function+ .arguments+ .iter()+ .find(|other| other.name == factor && !other.is_out);+ let name = counted_by.map(parameter_name);+ match (name, counted_by.and_then(|other| WireType::of(&other.cpp_type))) {+ (Some(name), Some(WireType::I32)) => factors.push(format!("i64::from({name})")),+ (Some(name), Some(WireType::I64)) => factors.push(name),+ _ => return Err(unsupported(function, argument, &format!("has the size {payload:?}"))),+ }+ }+ }+ Ok(format!("payload_size(&[{}])", factors.join(", ")))+}++#[derive(Default)]+struct Inputs {+ parameters: Vec<String>,+ statements: Vec<String>,+ inline_data: Option<String>,+ /// `None` for a field that has the name of the parameter it is from.+ field_values: Vec<(String, Option<String>)>,+}++impl Inputs {+ fn add_inline_data(&mut self, function: &Function, argument: &Argument, data: String) -> Result<(), String> {+ if self.inline_data.is_some() {+ return Err(unsupported(function, argument, "is a second one that points at data"));+ }+ let name = inline_data_name(argument);+ self.statements.push(format!("let {name} = {data};"));+ self.inline_data = Some(name);+ Ok(())+ }++ fn inline_data(&self) -> &str {+ self.inline_data.as_deref().unwrap_or("InlineData::NONE")+ }++ fn parameter_list(&self) -> String {+ self.parameters+ .iter()+ .map(|parameter| format!(", {parameter}"))+ .collect()+ }+}++fn inputs(function: &Function, struct_path: &str, fields: &[FieldSpec]) -> Result<Inputs, String> {+ let mut inputs = Inputs::default();+ for (index, argument) in function.arguments.iter().enumerate() {+ if argument.is_out {+ continue;+ }+ let name = parameter_name(argument);+ let span = format!("DataSpan::following::<{struct_path}>({})", inline_data_name(argument));+ let fields_of_argument = fields.iter().filter(|field| field.argument == Some(index));+ if argument.is_string {+ inputs.parameters.push(format!("{name}: &[u8]"));+ inputs.add_inline_data(+ function,+ argument,+ format!("InlineData::NulTerminated(until_nul({name}))"),+ )?;+ inputs.field_values.push((name, Some(span)));+ } else if argument.is_offset {+ inputs.parameters.push(format!("{name}: i64"));+ inputs.field_values.push((name, None));+ } else if argument.is_object && !argument.is_pointer() {+ inputs.parameters.push(format!("{name}: u32"));+ inputs.field_values.push((name, None));+ } else if argument.payload.is_some() {+ if !argument.is_const_pointer() {+ return Err(unsupported(function, argument, "points at data that is not const"));+ }+ let size = payload_size_expression(function, argument)?;+ let data = if argument.is_object {+ inputs.parameters.push(format!("{name}: &[u32]"));+ format!("leading_bytes(bytes_of({name}), {size})")+ } else if argument.is_nullable {+ inputs.parameters.push(format!("{name}: Option<&[u8]>"));+ format!("{name}.map(|{name}| leading_bytes({name}, {size})).unwrap_or_default()")+ } else {+ inputs.parameters.push(format!("{name}: &[u8]"));+ format!("leading_bytes({name}, {size})")+ };+ inputs.add_inline_data(function, argument, format!("InlineData::Bytes({data})"))?;+ for field in fields_of_argument {+ if field.cpp_type == "bool" {+ inputs+ .field_values+ .push((rust_identifier(&field.name), Some(format!("{name}.is_some()"))));+ }+ }+ inputs.field_values.push((name, Some(span)));+ } else if argument.is_pointer() {+ return Err(unsupported(function, argument, "is a pointer without a size"));+ } else {+ let parameter_type = scalar_parameter_type(function, argument)?;+ inputs.parameters.push(format!("{name}: {parameter_type}"));+ let value = (argument.cpp_type == "GLboolean").then(|| format!("u8::from({name})"));+ inputs.field_values.push((name, value));+ }+ }+ Ok(inputs)+}++fn struct_expression(struct_path: &str, layout: &WireStruct, field_values: &[(String, Option<String>)]) -> String {+ if layout.fields.is_empty() {+ return format!("{struct_path}::ZEROED");+ }+ let mut expression = format!("{struct_path} {{ ");+ for (name, value) in field_values {+ match value {+ Some(value) => write!(expression, "{name}: {value}, ").unwrap(),+ None => write!(expression, "{name}, ").unwrap(),+ }+ }+ if layout.has_unused_bytes() {+ write!(expression, "..{struct_path}::ZEROED ").unwrap();+ }+ expression.push('}');+ expression+}++fn check_fields_have_values(+ function: &Function,+ layout: &WireStruct,+ field_values: &[(String, Option<String>)],+) -> Result<(), String> {+ let mut field_names: Vec<String> = layout+ .fields+ .iter()+ .map(|field| rust_identifier(&field.spec.name))+ .collect();+ let mut value_names: Vec<String> = field_values.iter().map(|(name, _)| name.clone()).collect();+ field_names.sort();+ value_names.sort();+ if field_names == value_names {+ Ok(())+ } else {+ Err(format!(+ "the recorder would fill the fields {value_names:?} of {}, which has the fields {field_names:?}",+ function.name+ ))+ }+}++fn write_statements(out: &mut String, statements: &[String]) {+ for statement in statements {+ writeln!(out, " {statement}").unwrap();+ }+}++fn write_command_method(out: &mut String, function: &Function) -> Result<(), String> {+ let name = function.command_name();+ let struct_path = format!("commands::{name}");+ let fields = function.command_fields()?;+ let layout = wire_struct(format!("Commands::{name}"), fields.clone())?;+ let inputs = inputs(function, &struct_path, &fields)?;+ check_fields_have_values(function, &layout, &inputs.field_values)?;++ writeln!(+ out,+ " pub(crate) fn {}(&self{}) {{",+ function.method_name(),+ inputs.parameter_list()+ )+ .unwrap();+ write_statements(out, &inputs.statements);+ let command = struct_expression(&struct_path, &layout, &inputs.field_values);+ match &inputs.inline_data {+ Some(inline_data) => writeln!(out, " self.record_with_data(&{command}, {inline_data});").unwrap(),+ None => writeln!(out, " self.record(&{command});").unwrap(),+ }+ out.push_str(" }\n\n");+ Ok(())+}++/// The recorder allocates the ids of the objects, so that it does not have to wait for the replayer to create them.+fn write_gen_method(out: &mut String, function: &Function) -> Result<(), String> {+ let name = function.command_name();+ let struct_path = format!("commands::{name}");+ let fields = function.command_fields()?;+ let layout = wire_struct(format!("Commands::{name}"), fields.clone())?;+ let method_name = function.method_name();++ if !function.returns_void() {+ let mut inputs = inputs(function, &struct_path, &fields)?;+ if inputs.inline_data.is_some() {+ return Err(format!(+ "the recorder has no method for {}, which creates an object from data",+ function.name+ ));+ }+ inputs.field_values.insert(0, ("id".to_string(), None));+ check_fields_have_values(function, &layout, &inputs.field_values)?;+ writeln!(+ out,+ " pub(crate) fn {method_name}(&self{}) -> u32 {{",+ inputs.parameter_list()+ )+ .unwrap();+ out.push_str(" let id = self.allocate_object_id();\n");+ let command = struct_expression(&struct_path, &layout, &inputs.field_values);+ writeln!(out, " self.record(&{command});").unwrap();+ out.push_str(" id\n }\n\n");+ return Ok(());+ }++ let [count, ids] = function.arguments.as_slice() else {+ return Err(format!(+ "the recorder has no method for {}, which is not a count and ids",+ function.name+ ));+ };+ if WireType::of(&count.cpp_type) != Some(WireType::I32) || ids.cpp_type != "GLuint*" {+ return Err(format!(+ "the recorder has no method for {}, which is not a count and ids",+ function.name+ ));+ }+ let count_name = parameter_name(count);+ let ids_name = parameter_name(ids);+ let inline_data = inline_data_name(ids);+ let field_values = [+ (count_name, Some(format!("gen_count({ids_name})"))),+ (+ ids_name.clone(),+ Some(format!("DataSpan::following::<{struct_path}>({inline_data})")),+ ),+ ];+ check_fields_have_values(function, &layout, &field_values)?;+ writeln!(out, " pub(crate) fn {method_name}(&self, {ids_name}: &mut [u32]) {{").unwrap();+ writeln!(out, " if {ids_name}.is_empty() {{").unwrap();+ out.push_str(" return;\n }\n");+ writeln!(out, " for id in &mut *{ids_name} {{").unwrap();+ out.push_str(" *id = self.allocate_object_id();\n }\n");+ writeln!(+ out,+ " let {inline_data} = InlineData::Bytes(bytes_of({ids_name}));"+ )+ .unwrap();+ let command = struct_expression(&struct_path, &layout, &field_values);+ writeln!(out, " self.record_with_data(&{command}, {inline_data});").unwrap();+ out.push_str(" }\n\n");+ Ok(())+}++fn output_element_type(function: &Function, argument: &Argument) -> Result<&'static str, String> {+ match argument.pointee_cpp_type().as_str() {+ "GLchar" | "GLboolean" => Ok("u8"),+ "GLint" | "GLsizei" => Ok("i32"),+ "GLuint" | "GLenum" => Ok("u32"),+ "GLfloat" => Ok("f32"),+ "GLint64" => Ok("i64"),+ other => Err(unsupported(function, argument, &format!("is a buffer of {other}"))),+ }+}++/// A value that a synchronous call returns: the return value of the GL function, or what it stores through a+/// pointer to one value.+struct ScalarOutput {+ name: String,+ rust_type: &'static str,+ value: String,+}++fn scalar_output(function: &Function, field: &FieldSpec) -> Result<ScalarOutput, String> {+ let name = rust_identifier(&field.name);+ let no_rust_type = || {+ format!(+ "the recorder has no method for {}, which returns a {}",+ function.name, field.cpp_type+ )+ };+ let (rust_type, value) = match WireType::of(&field.cpp_type).ok_or_else(no_rust_type)? {+ WireType::DataSpan | WireType::Bool => return Err(no_rust_type()),+ // A GLboolean.+ WireType::U8 => ("bool", format!("reply.{name} != 0")),+ wire_type => (wire_type.rust_type(), format!("reply.{name}")),+ };+ Ok(ScalarOutput { name, rust_type, value })+}++fn write_sync_method(out: &mut String, output_structs: &mut String, function: &Function) -> Result<(), String> {+ let name = function.command_name();+ let struct_path = format!("sync_calls::{name}Request");+ let request_fields = function.sync_request_fields()?;+ let request_layout = wire_struct(format!("SyncCalls::{name}::Request"), request_fields.clone())?;+ let mut inputs = inputs(function, &struct_path, &request_fields)?;+ check_fields_have_values(function, &request_layout, &inputs.field_values)?;++ let mut scalar_outputs = Vec::new();+ let mut copies = Vec::new();+ for field in function.sync_reply_fields() {+ let argument = field.argument.map(|index| &function.arguments[index]);+ match argument {+ Some(argument) if argument.payload.is_some() => {+ let parameter = parameter_name(argument);+ let element_type = output_element_type(function, argument)?;+ inputs.parameters.push(format!("{parameter}: &mut [{element_type}]"));+ let size = payload_size_expression(function, argument)?;+ copies.push(format!(+ "copy_reply_data(reply_bytes, reply.{}, leading_bytes_mut(bytes_of_mut({parameter}), {size}));",+ rust_identifier(&field.name)+ ));+ }+ _ => scalar_outputs.push(scalar_output(function, &field)?),+ }+ }++ let (return_type, output) = match scalar_outputs.as_slice() {+ [] => (String::new(), None),+ [output] => (format!(" -> {}", output.rust_type), Some(output.value.clone())),+ outputs => {+ let struct_name = format!("{name}Outputs");+ writeln!(output_structs, "/// What `{}` returns.", function.name).unwrap();+ output_structs.push_str("#[derive(Clone, Copy, Debug, Default, PartialEq)]\n");+ writeln!(output_structs, "pub(crate) struct {struct_name} {{").unwrap();+ let mut values = String::new();+ for output in outputs {+ writeln!(output_structs, " pub(crate) {}: {},", output.name, output.rust_type).unwrap();+ write!(values, "{}: {}, ", output.name, output.value).unwrap();+ }+ output_structs.push_str("}\n\n");+ (+ format!(" -> {struct_name}"),+ Some(format!("{struct_name} {{ {values}}}")),+ )+ }+ };++ writeln!(+ out,+ " pub(crate) fn {}(&self{}){return_type} {{",+ function.method_name(),+ inputs.parameter_list()+ )+ .unwrap();+ write_statements(out, &inputs.statements);+ let request = struct_expression(&struct_path, &request_layout, &inputs.field_values);+ writeln!(out, " let request = {request};").unwrap();+ let reply = if output.is_some() || !copies.is_empty() {+ "reply"+ } else {+ "_reply"+ };+ let reply_bytes = if copies.is_empty() {+ "_reply_bytes"+ } else {+ "reply_bytes"+ };+ writeln!(+ out,+ " self.sync_call(&request, {}, |{reply}, {reply_bytes}| {{",+ inputs.inline_data()+ )+ .unwrap();+ for copy in &copies {+ writeln!(out, " {copy}").unwrap();+ }+ if let Some(output) = &output {+ writeln!(out, " {output}").unwrap();+ }+ // NB: Without a reply, which is when the context is lost, a call returns zeros and leaves the buffers alone.+ out.push_str(if output.is_some() {+ " })\n .unwrap_or_default()\n"+ } else {+ " });\n"+ });+ out.push_str(" }\n\n");+ Ok(())+}++pub fn write_proxy(functions: &[Function]) -> Result<String, String> {+ let mut methods = String::new();+ let mut output_structs = String::new();+ for function in functions {+ match function.category {+ Category::Command => write_command_method(&mut methods, function)?,+ Category::Gen => write_gen_method(&mut methods, function)?,+ Category::Sync => write_sync_method(&mut methods, &mut output_structs, function)?,+ // Written by hand in src/web_gl/proxy/custom.rs.+ Category::Custom | Category::BuiltinCommand => {}+ }+ }++ let mut out = String::from("// Generated by build.rs from Libraries/LibCompositing/WebGL/GLFunctions.json.\n\n");+ out.push_str(&output_structs);+ out.push_str(+ "#[allow(clippy::too_many_arguments, reason = \"the methods have the arguments of the GL functions\")]\n",+ );+ out.push_str("impl<T: Transport> Proxy<T> {\n");+ out.push_str(methods.trim_end());+ out.push_str("\n}\n");+ Ok(out)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::webgl_wire_model::parse_functions;++ fn proxy_for(function_json: &str) -> Result<String, String> {+ write_proxy(&parse_functions(&format!("[{function_json}]")).unwrap())+ }++ #[test]+ fn the_size_of_a_payload_is_the_product_that_the_json_gives() {+ let proxy = proxy_for(+ r#"{"name": "glUniformMatrix4fv", "return": "void", "category": "command", "args": [+ {"type": "GLint", "name": "location"},+ {"type": "GLsizei", "name": "count"},+ {"type": "GLboolean", "name": "transpose"},+ {"type": "GLfloat const*", "name": "value", "payload": "count * 16 * sizeof(GLfloat)"}]}"#,+ )+ .unwrap();+ assert!(proxy.contains(+ "pub(crate) fn uniform_matrix4fv(&self, location: i32, count: i32, transpose: bool, value: &[u8]) {"+ ));+ assert!(proxy.contains("leading_bytes(value, payload_size(&[i64::from(count), 16, 4]))"));+ assert!(proxy.contains("transpose: u8::from(transpose), value: DataSpan::following::<"));+ }++ #[test]+ fn a_synchronous_call_returns_its_outputs_and_fills_its_buffers() {+ let proxy = proxy_for(+ r#"{"name": "glGetActiveAttrib", "return": "void", "category": "sync", "args": [+ {"type": "GLuint", "name": "program", "object": true},+ {"type": "GLsizei", "name": "bufSize"},+ {"type": "GLsizei*", "name": "length", "out": true},+ {"type": "GLenum*", "name": "type", "out": true},+ {"type": "GLchar*", "name": "name", "out": true, "payload": "bufSize * sizeof(GLchar)"}]}"#,+ )+ .unwrap();+ assert!(proxy.contains(+ "pub(crate) struct GetActiveAttribOutputs {\n pub(crate) length: i32,\n pub(crate) r#type: u32,\n}"+ ));+ assert!(proxy.contains(+ "pub(crate) fn get_active_attrib(&self, program: u32, buf_size: i32, name: &mut [u8]) -> GetActiveAttribOutputs {"+ ));+ assert!(proxy.contains("copy_reply_data(reply_bytes, reply.name, leading_bytes_mut(bytes_of_mut(name), payload_size(&[i64::from(buf_size), 1])));"));+ assert!(proxy.contains("GetActiveAttribOutputs { length: reply.length, r#type: reply.r#type, }"));+ }++ #[test]+ fn what_the_recorder_cannot_serialize_is_rejected() {+ let two_payloads = proxy_for(+ r#"{"name": "glTwo", "return": "void", "category": "command", "args": [+ {"type": "GLsizei", "name": "n"},+ {"type": "GLint const*", "name": "a", "payload": "n * sizeof(GLint)"},+ {"type": "GLint const*", "name": "b", "payload": "n * sizeof(GLint)"}]}"#,+ );+ assert!(+ two_payloads+ .unwrap_err()+ .contains("is a second one that points at data")+ );+ let unknown_size = proxy_for(+ r#"{"name": "glSized", "return": "void", "category": "command", "args": [+ {"type": "GLint const*", "name": "a", "payload": "strlen(a)"}]}"#,+ );+ assert!(unknown_size.unwrap_err().contains("has the size \"strlen(a)\""));+ let unknown_element = proxy_for(+ r#"{"name": "glGetDoubles", "return": "void", "category": "sync", "args": [+ {"type": "GLsizei", "name": "n"},+ {"type": "GLdouble*", "name": "values", "out": true, "payload": "n * sizeof(GLint64)"}]}"#,+ );+ assert!(unknown_element.unwrap_err().contains("is a buffer of GLdouble"));+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs b/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rsindex 9dbed163c7b..cb03e0365f5 100644--- a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs+++ b/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs@@ -156,6 +156,18 @@ pub fn write_wire_vocabulary(vocabulary: &Vocabulary) -> String {"What a synchronous call is, in the order of the C++ enum `WebGLSyncCallType`.",&sync_call_names,);+ let max_command_struct_size = vocabulary+ .commands+ .iter()+ .map(|entry| entry.layout.size)+ .max()+ .unwrap_or(0);+ out.push_str("/// The size of the largest struct of a record.\n");+ writeln!(+ out,+ "pub(crate) const MAX_COMMAND_STRUCT_SIZE: usize = {max_command_struct_size};\n"+ )+ .unwrap();out.push_str("/// The structs of the records of the command stream, which are those of the C++ namespace `Commands`.\n",diff --git a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire_model.rs b/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire_model.rsindex 98b5e43f801..9822df85939 100644--- a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire_model.rs+++ b/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire_model.rs@@ -53,6 +53,8 @@ impl Argument {pub struct FieldSpec {pub cpp_type: String,pub name: String,+ /// The index of the argument that the field carries, for a field that follows from the signature of the function.+ pub argument: Option<usize>,}#[derive(Debug)]@@ -157,6 +159,7 @@ fn parse_wire_fields(field_specs.push(FieldSpec {cpp_type: required_string_member(field, "type", &what)?,name: required_string_member(field, "name", &what)?,+ argument: None,});}Ok(Some(field_specs))@@ -260,6 +263,10 @@ impl Function {if self.is_builtin() { &self.name } else { &self.name[2..] }}+ pub fn method_name(&self) -> String {+ title_case_to_snake_case(self.command_name())+ }+pub fn is_command_stream_entry(&self) -> bool {matches!(self.category, Category::Command | Category::Gen) || self.wire_command.is_some()}@@ -285,9 +292,10 @@ impl Function {fields.push(FieldSpec {cpp_type: "WebGLObjectId".into(),name: "id".into(),+ argument: None,});}- for argument in &self.arguments {+ for (index, argument) in self.arguments.iter().enumerate() {let name = title_case_to_snake_case(&argument.name);let cpp_type = if is_gen && argument.is_pointer() && !argument.is_const_pointer() {// The ids that the recorder allocated.@@ -303,6 +311,7 @@ impl Function {fields.push(FieldSpec {cpp_type: "bool".into(),name: format!("has_{name}"),+ argument: Some(index),});}"WebGLDataSpan"@@ -314,6 +323,7 @@ impl Function {fields.push(FieldSpec {cpp_type: cpp_type.to_string(),name,+ argument: Some(index),});}Ok(fields)@@ -324,7 +334,7 @@ impl Function {return Ok(fields.clone());}let mut fields = Vec::new();- for argument in &self.arguments {+ for (index, argument) in self.arguments.iter().enumerate() {if argument.is_out {continue;}@@ -340,6 +350,7 @@ impl Function {fields.push(FieldSpec {cpp_type: cpp_type.to_string(),name: title_case_to_snake_case(&argument.name),+ argument: Some(index),});}Ok(fields)@@ -357,9 +368,10 @@ impl Function {fields.push(FieldSpec {cpp_type: return_type.clone(),name: "return_value".into(),+ argument: None,});}- for argument in &self.arguments {+ for (index, argument) in self.arguments.iter().enumerate() {if !argument.is_out {continue;}@@ -371,6 +383,7 @@ impl Function {fields.push(FieldSpec {cpp_type,name: title_case_to_snake_case(&argument.name),+ argument: Some(index),});}fields@@ -481,6 +494,14 @@ pub struct WireStruct {pub alignment: usize,}+impl WireStruct {+ /// The Rust struct has fields of its own for the bytes that are not part of a field of the model.+ pub fn has_unused_bytes(&self) -> bool {+ let size_of_fields: usize = self.fields.iter().map(|field| field.wire_type.size()).sum();+ size_of_fields != self.size+ }+}+pub fn wire_struct(cpp_name: String, field_specs: Vec<FieldSpec>) -> Result<WireStruct, String> {let mut fields = Vec::new();let mut end_of_fields: usize = 0;@@ -578,6 +599,7 @@ mod tests {.map(|(cpp_type, name)| FieldSpec {cpp_type: (*cpp_type).into(),name: (*name).into(),+ argument: None,}).collect()}diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 6abb7aea750..d351a57c596 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -56,7 +56,13 @@ pub(crate) mod web_gl;#[path = "../generate/webgl_constants.rs"]mod webgl_constants;#[cfg(test)]-#[allow(dead_code, reason = "the tests do not run the writers that the model is for")]+#[path = "../generate/webgl_proxy.rs"]+mod webgl_proxy;+#[cfg(test)]+#[allow(+ dead_code,+ reason = "the tests do not run the writer of the vocabulary, which the model is for as well"+)]#[path = "../generate/webgl_wire_model.rs"]mod webgl_wire_model;diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/fingerprint.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/fingerprint.rsnew file mode 100644index 00000000000..34c63d8c1c1--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/fingerprint.rs@@ -0,0 +1,72 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The check that the recorder and the replayer mean the same bytes. Both get their structs from GLFunctions.json,+//! but through two generators, and what is not generated, such as the framing, is a constant on each side. A+//! difference would not fail a build, and would make the replayer read garbage, so the two sides are compared before+//! the first context records.++use std::sync::Once;++use super::proxy::recorder::{DEFAULT_SHARED_DATA_REGION_CAPACITY, SHARED_DATA_REGION_OFFSET};+use super::proxy::vocabulary::WIRE_STRUCT_LAYOUTS;+use super::proxy::wire::{HEADER_PAYLOAD_SIZE_OFFSET, HEADER_SIZE, RECORD_ALIGNMENT};++/// RemoteWebGLTransportFFI.cpp has a struct of the same name, and reports the constants of the C++ side as one.+#[derive(Debug, Default, PartialEq, Eq)]+#[repr(C)]+struct ConstantsRestatedInRust {+ record_alignment: usize,+ header_size: usize,+ header_payload_size_offset: usize,+ shared_data_region_offset: usize,+ shared_data_region_capacity: usize,+}++unsafe extern "C" {+ fn compositing_webgl_wire_struct_layouts(out_word_count: *mut usize) -> *const u32;+ fn web_webgl_constants_restated_in_rust(out_constants: *mut ConstantsRestatedInRust);+}++pub(crate) fn verify_that_the_replayer_reads_what_the_recorder_writes() {+ static VERIFIED: Once = Once::new();+ VERIFIED.call_once(|| {+ let mut constants_of_the_cpp_side = ConstantsRestatedInRust::default();+ // SAFETY: The function fills in the struct, which has the layout of its C++ counterpart.+ unsafe { web_webgl_constants_restated_in_rust(&raw mut constants_of_the_cpp_side) };+ let constants_of_the_rust_side = ConstantsRestatedInRust {+ record_alignment: RECORD_ALIGNMENT,+ header_size: HEADER_SIZE,+ header_payload_size_offset: HEADER_PAYLOAD_SIZE_OFFSET,+ shared_data_region_offset: SHARED_DATA_REGION_OFFSET,+ shared_data_region_capacity: DEFAULT_SHARED_DATA_REGION_CAPACITY,+ };+ assert!(+ constants_of_the_cpp_side == constants_of_the_rust_side,+ "the WebGL implementation restates constants of the C++ side ({constants_of_the_cpp_side:?}) differently \+ in Rust ({constants_of_the_rust_side:?})"+ );++ let mut word_count = 0;+ // SAFETY: The function returns a table that lives as long as the process, and stores its length.+ let replayer_layouts = unsafe {+ let words = compositing_webgl_wire_struct_layouts(&raw mut word_count);+ core::slice::from_raw_parts(words, word_count)+ };+ let first_difference = replayer_layouts+ .iter()+ .zip(WIRE_STRUCT_LAYOUTS)+ .position(|(theirs, ours)| theirs != ours);+ assert!(+ first_difference.is_none() && replayer_layouts.len() == WIRE_STRUCT_LAYOUTS.len(),+ "the structs of the WebGL command stream differ between its recorder and its replayer, from word \+ {first_difference:?} of {} and {} layout words on; Libraries/LibWeb/Bindings/Rust/generate and \+ Meta/Generators/libweb_webgl.py have to derive the same structs from GLFunctions.json",+ WIRE_STRUCT_LAYOUTS.len(),+ replayer_layouts.len()+ );+ });+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rsnew file mode 100644index 00000000000..59a2bc68fa9--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs@@ -0,0 +1,300 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The transport of a context in the product: a RemoteWebGLTransport of LibWeb, through the C ABI that+//! Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp gives it.++use core::ffi::c_void;+use core::ptr::{self, NonNull};++use super::proxy::transport::{ReadPixelsResult, SharedMemory, Transport};++unsafe extern "C" {+ fn web_webgl_transport_unref(transport: *mut c_void);+ fn web_webgl_transport_canvas_id(transport: *const c_void, out_canvas_id: *mut u64) -> bool;+ fn web_webgl_transport_destroy_context(transport: *mut c_void);+ fn web_webgl_transport_set_shared_command_buffer(transport: *mut c_void, anonymous_buffer: *const c_void);+ fn web_webgl_transport_send_commands_from_shared_buffer(+ transport: *mut c_void,+ offset: u64,+ size_in_bytes: u64,+ flush_sequence_number: u64,+ frames: *const Frame,+ frame_count: usize,+ );+ fn web_webgl_transport_wait_until_published_commands_executed(transport: *mut c_void) -> bool;+ fn web_webgl_transport_send_commands(+ transport: *mut c_void,+ commands: *const u8,+ size_in_bytes: usize,+ frames: *const Frame,+ frame_count: usize,+ );+ fn web_webgl_transport_present_canvas(transport: *mut c_void, preserve_drawing_buffer: bool);+ fn web_webgl_transport_clear_drawing_buffer(transport: *mut c_void);+ fn web_webgl_transport_sync_call(+ transport: *mut c_void,+ request: *const u8,+ request_size: usize,+ reply_sink: *mut c_void,+ write_reply: unsafe extern "C" fn(reply_sink: *mut c_void, reply: *const u8, reply_size: usize),+ );+ fn web_webgl_transport_read_pixels_robust_angle(+ transport: *mut c_void,+ x: i32,+ y: i32,+ width: i32,+ height: i32,+ format: u32,+ r#type: u32,+ buf_size: i32,+ pixels_anonymous_buffer_or_null: *const c_void,+ out_result: *mut ReadPixelsResult,+ );+ fn web_webgl_transport_read_buffer_sub_data(+ transport: *mut c_void,+ target: u32,+ offset: i64,+ size: i64,+ data_anonymous_buffer: *const c_void,+ ) -> bool;+ fn web_webgl_transport_read_back_drawing_buffer(+ transport: *mut c_void,+ x: i32,+ y: i32,+ width: i32,+ height: i32,+ ) -> *mut c_void;+ fn web_webgl_max_frames_per_message() -> usize;+ fn web_webgl_anonymous_buffer_create(size: usize, out_data: *mut *mut u8) -> *mut c_void;+ fn web_webgl_anonymous_buffer_destroy(anonymous_buffer: *mut c_void);+ fn web_webgl_frame_destroy(frame: *mut c_void);+ fn web_webgl_bitmap_unref(bitmap: *mut c_void);+}++pub(crate) struct AnonymousBuffer {+ buffer: NonNull<c_void>,+ data: *mut u8,+ size: usize,+}++impl AnonymousBuffer {+ fn create(size: usize) -> Option<Self> {+ let mut data = ptr::null_mut();+ // SAFETY: The function has no preconditions, and stores where the memory is mapped when it returns a buffer.+ let buffer = NonNull::new(unsafe { web_webgl_anonymous_buffer_create(size, &raw mut data) })?;+ Some(Self { buffer, data, size })+ }+}++impl Drop for AnonymousBuffer {+ fn drop(&mut self) {+ // SAFETY: The value owns the buffer, which nothing uses after this.+ unsafe { web_webgl_anonymous_buffer_destroy(self.buffer.as_ptr()) };+ }+}++impl SharedMemory for AnonymousBuffer {+ fn as_ptr(&self) -> *mut u8 {+ self.data+ }++ fn len(&self) -> usize {+ self.size+ }+}++#[repr(transparent)]+pub(crate) struct Frame(NonNull<c_void>);++impl Frame {+ /// # Safety+ ///+ /// `frame` is a Gfx::DecodedImageFrame allocated with `new`, which the value takes over.+ pub(crate) unsafe fn from_raw(frame: NonNull<c_void>) -> Self {+ Self(frame)+ }+}++impl Drop for Frame {+ fn drop(&mut self) {+ // SAFETY: The value owns the frame, which nothing uses after this.+ unsafe { web_webgl_frame_destroy(self.0.as_ptr()) };+ }+}++pub(crate) struct Bitmap(NonNull<c_void>);++impl Bitmap {+ pub(crate) fn into_raw(self) -> *mut c_void {+ let bitmap = self.0.as_ptr();+ core::mem::forget(self);+ bitmap+ }+}++impl Drop for Bitmap {+ fn drop(&mut self) {+ // SAFETY: The value owns one reference to the bitmap.+ unsafe { web_webgl_bitmap_unref(self.0.as_ptr()) };+ }+}++pub(crate) struct CppTransport(NonNull<c_void>);++impl CppTransport {+ /// # Safety+ ///+ /// `transport` is a RemoteWebGLTransport, one reference to which the value takes over.+ pub(crate) unsafe fn from_raw(transport: NonNull<c_void>) -> Self {+ Self(transport)+ }++ fn as_ptr(&self) -> *mut c_void {+ self.0.as_ptr()+ }+}++impl Drop for CppTransport {+ fn drop(&mut self) {+ // SAFETY: The value owns one reference to the transport.+ unsafe { web_webgl_transport_unref(self.as_ptr()) };+ }+}++unsafe extern "C" fn append_reply(reply_sink: *mut c_void, reply: *const u8, reply_size: usize) {+ if reply_size == 0 {+ return;+ }+ // SAFETY: sync_call() passes its vector as the sink, and the transport passes the bytes of its reply.+ unsafe {+ let reply_sink = &mut *reply_sink.cast::<Vec<u8>>();+ reply_sink.extend_from_slice(core::slice::from_raw_parts(reply, reply_size));+ }+}++// SAFETY (of every call below): The value holds a reference to the transport, the buffers and the frames passed are+// alive for the call, and a pointer with a length is the pointer and the length of one slice.+impl Transport for CppTransport {+ type SharedMemory = AnonymousBuffer;+ type Frame = Frame;+ type Bitmap = Bitmap;++ fn max_frames_per_message(&self) -> usize {+ unsafe { web_webgl_max_frames_per_message() }+ }++ fn create_shared_memory(&self, size: usize) -> Option<AnonymousBuffer> {+ AnonymousBuffer::create(size)+ }++ fn canvas_id(&self) -> Option<u64> {+ let mut canvas_id = 0;+ unsafe { web_webgl_transport_canvas_id(self.as_ptr(), &raw mut canvas_id) }.then_some(canvas_id)+ }++ fn destroy_context(&self) {+ unsafe { web_webgl_transport_destroy_context(self.as_ptr()) };+ }++ fn set_shared_command_buffer(&self, buffer: &AnonymousBuffer) {+ unsafe { web_webgl_transport_set_shared_command_buffer(self.as_ptr(), buffer.buffer.as_ptr()) };+ }++ fn send_commands_from_shared_buffer(+ &self,+ offset: u64,+ size_in_bytes: u64,+ flush_sequence_number: u64,+ frames: &[Frame],+ ) {+ unsafe {+ web_webgl_transport_send_commands_from_shared_buffer(+ self.as_ptr(),+ offset,+ size_in_bytes,+ flush_sequence_number,+ frames.as_ptr(),+ frames.len(),+ );+ }+ }++ fn wait_until_published_commands_executed(&self) -> bool {+ unsafe { web_webgl_transport_wait_until_published_commands_executed(self.as_ptr()) }+ }++ fn send_commands(&self, commands: &[u8], frames: &[Frame]) {+ unsafe {+ web_webgl_transport_send_commands(+ self.as_ptr(),+ commands.as_ptr(),+ commands.len(),+ frames.as_ptr(),+ frames.len(),+ );+ }+ }++ fn present_canvas(&self, preserve_drawing_buffer: bool) {+ unsafe { web_webgl_transport_present_canvas(self.as_ptr(), preserve_drawing_buffer) };+ }++ fn clear_drawing_buffer(&self) {+ unsafe { web_webgl_transport_clear_drawing_buffer(self.as_ptr()) };+ }++ fn sync_call(&self, request: &[u8], reply: &mut Vec<u8>) {+ unsafe {+ web_webgl_transport_sync_call(+ self.as_ptr(),+ request.as_ptr(),+ request.len(),+ ptr::from_mut(reply).cast::<c_void>(),+ append_reply,+ );+ }+ }++ fn read_pixels_robust_angle(+ &self,+ x: i32,+ y: i32,+ width: i32,+ height: i32,+ format: u32,+ r#type: u32,+ buf_size: i32,+ pixels: Option<&AnonymousBuffer>,+ ) -> ReadPixelsResult {+ let mut result = ReadPixelsResult::default();+ let pixels = pixels.map_or(ptr::null(), |pixels| pixels.buffer.as_ptr().cast_const());+ unsafe {+ web_webgl_transport_read_pixels_robust_angle(+ self.as_ptr(),+ x,+ y,+ width,+ height,+ format,+ r#type,+ buf_size,+ pixels,+ &raw mut result,+ );+ }+ result+ }++ fn read_buffer_sub_data(&self, target: u32, offset: i64, size: i64, data: &AnonymousBuffer) -> bool {+ unsafe { web_webgl_transport_read_buffer_sub_data(self.as_ptr(), target, offset, size, data.buffer.as_ptr()) }+ }++ fn read_back_drawing_buffer(&self, x: i32, y: i32, width: i32, height: i32) -> Option<Bitmap> {+ let bitmap = unsafe { web_webgl_transport_read_back_drawing_buffer(self.as_ptr(), x, y, width, height) };+ NonNull::new(bitmap).map(Bitmap)+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rsindex 4dff7a36b15..4edaff4c0d6 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs@@ -8,4 +8,8 @@//! back, and records everything else as commands for the Compositor, which runs GL.pub(crate) mod constants;+#[cfg(not(test))]+pub(crate) mod fingerprint;+#[cfg(not(test))]+pub(crate) mod host;pub(crate) mod proxy;diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/custom.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/custom.rsnew file mode 100644index 00000000000..8a4d1dd60ac--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/custom.rs@@ -0,0 +1,395 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The entry points of the recorder that are written by hand: the GL functions that GLFunctions.json marks as+//! custom, because their arguments do not serialize the way their signature suggests, and the commands that are no+//! GL functions.++use std::rc::Rc;++use super::recorder::{Proxy, bytes_of_mut, copy_reply_data, until_nul};+use super::transport::{ReadPixelsResult, SharedMemory, Transport};+use super::vocabulary::{commands, sync_calls};+use super::wire::{DataSpan, InlineData, WireStruct, resolve_data_span};+use crate::web_gl::constants::{GL_INVALID_VALUE, GL_OUT_OF_MEMORY};++fn pack_strings(strings: &[&[u8]]) -> Vec<u8> {+ let mut packed_strings = Vec::new();+ for string in strings {+ packed_strings.extend_from_slice(until_nul(string));+ packed_strings.push(0);+ }+ packed_strings+}++#[derive(Clone, Copy, Debug)]+pub(crate) struct FrameUpload {+ /// `None` uploads the frame at its own size.+ pub(crate) destination_size: Option<(i32, i32)>,+ pub(crate) flip_y: bool,+ pub(crate) premultiply_alpha: bool,+}++impl FrameUpload {+ fn destination_width(self) -> i32 {+ self.destination_size.map_or(0, |(width, _)| width)+ }++ fn destination_height(self) -> i32 {+ self.destination_size.map_or(0, |(_, height)| height)+ }+}++impl<T: Transport> Proxy<T> {+ fn string_count(&self, strings: &[&[u8]]) -> Option<i32> {+ let count = i32::try_from(strings.len()).ok();+ if count.is_none() && !self.is_lost() {+ self.set_pending_local_error(GL_INVALID_VALUE);+ }+ count+ }++ pub(crate) fn set_size(&self, width: i32, height: i32) {+ self.record(&commands::SetDrawingBufferSize { width, height });+ }++ #[expect(clippy::too_many_arguments, reason = "the arguments of the GL function")]+ pub(crate) fn read_pixels_into_pixel_pack_buffer(+ &self,+ x: i32,+ y: i32,+ width: i32,+ height: i32,+ format: u32,+ r#type: u32,+ offset: i64,+ ) {+ self.record(&commands::ReadPixelsIntoPixelPackBuffer {+ x,+ y,+ width,+ height,+ format,+ r#type,+ offset,+ });+ }++ #[expect(+ clippy::too_many_arguments,+ reason = "the arguments of the GL function, and the frame"+ )]+ pub(crate) fn tex_image2d_from_bitmap(+ &self,+ target: u32,+ level: i32,+ internalformat: i32,+ format: u32,+ r#type: u32,+ frame: T::Frame,+ upload: FrameUpload,+ ) {+ if self.is_lost() {+ return;+ }+ let bitmap_index = self.append_pending_frame(frame);+ self.record(&commands::TexImage2DFromBitmap {+ target,+ level,+ internalformat,+ format,+ r#type,+ bitmap_index,+ has_explicit_destination_size: upload.destination_size.is_some(),+ destination_width: upload.destination_width(),+ destination_height: upload.destination_height(),+ flip_y: upload.flip_y,+ premultiply_alpha: upload.premultiply_alpha,+ ..commands::TexImage2DFromBitmap::ZEROED+ });+ }++ #[expect(+ clippy::too_many_arguments,+ reason = "the arguments of the GL function, and the frame"+ )]+ pub(crate) fn tex_sub_image2d_from_bitmap(+ &self,+ target: u32,+ level: i32,+ xoffset: i32,+ yoffset: i32,+ format: u32,+ r#type: u32,+ frame: T::Frame,+ upload: FrameUpload,+ ) {+ if self.is_lost() {+ return;+ }+ let bitmap_index = self.append_pending_frame(frame);+ self.record(&commands::TexSubImage2DFromBitmap {+ target,+ level,+ xoffset,+ yoffset,+ format,+ r#type,+ bitmap_index,+ has_explicit_destination_size: upload.destination_size.is_some(),+ destination_width: upload.destination_width(),+ destination_height: upload.destination_height(),+ flip_y: upload.flip_y,+ premultiply_alpha: upload.premultiply_alpha,+ ..commands::TexSubImage2DFromBitmap::ZEROED+ });+ }++ #[expect(+ clippy::too_many_arguments,+ reason = "the arguments of the GL function, and the frame"+ )]+ pub(crate) fn tex_image3d_from_bitmap(+ &self,+ target: u32,+ level: i32,+ internalformat: i32,+ depth: i32,+ format: u32,+ r#type: u32,+ frame: T::Frame,+ upload: FrameUpload,+ ) {+ if self.is_lost() {+ return;+ }+ let bitmap_index = self.append_pending_frame(frame);+ self.record(&commands::TexImage3DFromBitmap {+ target,+ level,+ internalformat,+ depth,+ format,+ r#type,+ bitmap_index,+ has_explicit_destination_size: upload.destination_size.is_some(),+ destination_width: upload.destination_width(),+ destination_height: upload.destination_height(),+ flip_y: upload.flip_y,+ premultiply_alpha: upload.premultiply_alpha,+ ..commands::TexImage3DFromBitmap::ZEROED+ });+ }++ #[expect(+ clippy::too_many_arguments,+ reason = "the arguments of the GL function, and the frame"+ )]+ pub(crate) fn tex_sub_image3d_from_bitmap(+ &self,+ target: u32,+ level: i32,+ xoffset: i32,+ yoffset: i32,+ zoffset: i32,+ depth: i32,+ format: u32,+ r#type: u32,+ frame: T::Frame,+ upload: FrameUpload,+ ) {+ if self.is_lost() {+ return;+ }+ let bitmap_index = self.append_pending_frame(frame);+ self.record(&commands::TexSubImage3DFromBitmap {+ target,+ level,+ xoffset,+ yoffset,+ zoffset,+ depth,+ format,+ r#type,+ bitmap_index,+ has_explicit_destination_size: upload.destination_size.is_some(),+ destination_width: upload.destination_width(),+ destination_height: upload.destination_height(),+ flip_y: upload.flip_y,+ premultiply_alpha: upload.premultiply_alpha,+ ..commands::TexSubImage3DFromBitmap::ZEROED+ });+ }++ /// The source is all of `source`, whatever it contains.+ pub(crate) fn shader_source(&self, shader: u32, source: &[u8]) {+ let source_data = InlineData::NulTerminated(source);+ self.record_with_data(+ &commands::ShaderSource {+ shader,+ source: DataSpan::following::<commands::ShaderSource>(source_data),+ },+ source_data,+ );+ }++ pub(crate) fn transform_feedback_varyings(&self, program: u32, varyings: &[&[u8]], buffer_mode: u32) {+ let Some(count) = self.string_count(varyings) else {+ return;+ };+ let packed_varyings = pack_strings(varyings);+ let varyings_data = InlineData::Bytes(&packed_varyings);+ self.record_with_data(+ &commands::TransformFeedbackVaryings {+ program,+ count,+ varyings: DataSpan::following::<commands::TransformFeedbackVaryings>(varyings_data),+ buffer_mode,+ },+ varyings_data,+ );+ }++ /// Leaves `uniform_indices` as it is when the context is lost or has an error for the names.+ pub(crate) fn get_uniform_indices(&self, program: u32, uniform_names: &[&[u8]], uniform_indices: &mut [u32]) {+ assert!(uniform_indices.len() >= uniform_names.len());+ let Some(uniform_count) = self.string_count(uniform_names) else {+ return;+ };+ let packed_names = pack_strings(uniform_names);+ let names_data = InlineData::Bytes(&packed_names);+ let request = sync_calls::GetUniformIndicesRequest {+ program,+ uniform_count,+ uniform_names: DataSpan::following::<sync_calls::GetUniformIndicesRequest>(names_data),+ };+ self.sync_call(&request, names_data, |reply, reply_bytes| {+ copy_reply_data(+ reply_bytes,+ reply.uniform_indices,+ bytes_of_mut(&mut uniform_indices[..uniform_names.len()]),+ );+ });+ }++ /// Without the NUL that ends it, and empty when the context is lost.+ pub(crate) fn get_string(&self, name: u32) -> Rc<[u8]> {+ if let Some(string) = self.cached_string(name) {+ return string;+ }+ let request = sync_calls::GetStringRequest { name };+ let string = self.sync_call(&request, InlineData::NONE, |reply, reply_bytes| {+ let string = resolve_data_span(reply_bytes, reply.value);+ assert!(+ string.last() == Some(&0),+ "the replayer ends the string that it returns with a NUL"+ );+ Rc::<[u8]>::from(until_nul(string))+ });+ match string {+ Some(string) => {+ self.cache_string(name, Rc::clone(&string));+ string+ }+ None => Rc::from([]),+ }+ }++ pub(crate) fn get_vertex_attrib_pointerv_robust_angle(&self, index: u32, pname: u32) -> i64 {+ let request = sync_calls::GetVertexAttribPointervRobustANGLERequest { index, pname };+ self.sync_call(&request, InlineData::NONE, |reply, _| reply.pointer)+ .unwrap_or(0)+ }++ /// `use_pixels` does not run when the context is lost or when there is no memory to read into, which is a GL+ /// error of the context.+ #[expect(clippy::too_many_arguments, reason = "the arguments of the GL function")]+ pub(crate) fn read_pixels_robust_angle(+ &self,+ x: i32,+ y: i32,+ width: i32,+ height: i32,+ format: u32,+ r#type: u32,+ buf_size: i32,+ use_pixels: impl FnOnce(ReadPixelsResult, &[u8]),+ ) {+ if self.is_lost() {+ return;+ }+ let transport = self.transport();+ let shared_pixels = match usize::try_from(buf_size) {+ Ok(size) if size > 0 => {+ let Some(shared_pixels) = transport.create_shared_memory(size) else {+ self.set_pending_local_error(GL_OUT_OF_MEMORY);+ return;+ };+ Some(shared_pixels)+ }+ _ => None,+ };++ self.flush_commands();+ let result =+ transport.read_pixels_robust_angle(x, y, width, height, format, r#type, buf_size, shared_pixels.as_ref());+ if self.is_lost() {+ return;+ }+ let pixels = match (&shared_pixels, usize::try_from(result.length)) {+ (Some(shared_pixels), Ok(length)) if length > 0 => {+ assert!(+ length <= shared_pixels.len(),+ "the replayer reads no more pixels than it has room for"+ );+ // SAFETY: The memory is mapped and at least `length` bytes long, and the replayer, which is the only+ // other user of it, has answered the call and does not write to it any more.+ unsafe { core::slice::from_raw_parts(shared_pixels.as_ptr(), length) }+ }+ _ => &[],+ };+ use_pixels(result, pixels);+ }++ /// False when the context is lost, when the replayer refuses, or when there is no memory to read into, which is a+ /// GL error of the context.+ pub(crate) fn read_buffer_sub_data(+ &self,+ target: u32,+ offset: i64,+ size: usize,+ use_data: impl FnOnce(&[u8]),+ ) -> bool {+ if self.is_lost() {+ return false;+ }+ if size == 0 {+ return true;+ }+ let Ok(size_for_replayer) = i64::try_from(size) else {+ self.set_pending_local_error(GL_OUT_OF_MEMORY);+ return false;+ };+ let transport = self.transport();+ let Some(shared_data) = transport.create_shared_memory(size) else {+ self.set_pending_local_error(GL_OUT_OF_MEMORY);+ return false;+ };++ self.flush_commands();+ if !transport.read_buffer_sub_data(target, offset, size_for_replayer, &shared_data) {+ return false;+ }+ if self.is_lost() {+ return false;+ }+ assert!(size <= shared_data.len());+ // SAFETY: The memory is mapped and at least `size` bytes long, and the replayer, which is the only other+ // user of it, has answered the call and does not write to it any more.+ use_data(unsafe { core::slice::from_raw_parts(shared_data.as_ptr(), size) });+ true+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/generated.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/generated.rsnew file mode 100644index 00000000000..2f9a8ff73ba--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/generated.rs@@ -0,0 +1,19 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The methods of the recorder that follow from the signature of a GL function. The build script writes them from+//! GLFunctions.json (generate/webgl_proxy.rs).++use super::recorder::{+ Proxy, bytes_of, bytes_of_mut, copy_reply_data, gen_count, leading_bytes, leading_bytes_mut, payload_size,+ until_nul,+};+use super::transport::Transport;+use super::vocabulary::{commands, sync_calls};+use super::wire::{DataSpan, InlineData, WireStruct};+use crate::web_gl::constants::GL_COLOR;++include!(concat!(env!("OUT_DIR"), "/webgl_proxy.rs"));diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/mod.rsindex 19846881369..a8053cbf57f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/mod.rs@@ -7,5 +7,12 @@//! The recording side of the WebGL command stream. Libraries/LibCompositing/WebGL is the replaying side, and//! GLFunctions.json there defines what crosses the stream for both.+pub(crate) mod custom;+pub(crate) mod generated;+pub(crate) mod recorder;+pub(crate) mod transport;pub(crate) mod vocabulary;pub(crate) mod wire;++#[cfg(test)]+mod tests;diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rsnew file mode 100644index 00000000000..1681acebc60--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rs@@ -0,0 +1,571 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The recorder of one WebGL context: it takes the place of GL for the implementation of the context, writes what+//! is asked of it as records into a buffer that it shares with the replayer, and publishes them in batches. A call+//! that returns something is a synchronous round trip, which everything recorded before it is flushed for.++use core::cell::{Cell, RefCell};+use core::ptr;+use core::sync::atomic::{AtomicU64, Ordering};+use std::rc::Rc;++use super::transport::{SharedMemory, Transport};+use super::vocabulary::{CommandType, MAX_COMMAND_STRUCT_SIZE};+use super::wire::{+ Command, DataSpan, HEADER_SIZE, InlineData, Record, SyncReply, SyncRequest, encode_sync_request,+ padded_record_size, resolve_data_span,+};+use crate::web_gl::constants::GL_OUT_OF_MEMORY;++/// The `u64` that the replayer stores the sequence number of the last executed flush in is at the start of the shared+/// command buffer, before the region of records.+pub(crate) const SHARED_DATA_REGION_OFFSET: usize = 128;+pub(crate) const DEFAULT_SHARED_DATA_REGION_CAPACITY: usize = 32 * 1024 * 1024;++pub(crate) const MAX_PENDING_COMMAND_BYTES: usize = 4 * 1024 * 1024;++/// What is kept free in the region of records for the command that names a frame, before the frame is added to the+/// pending ones. Making room only when the command is recorded could flush in between, and that flush would publish+/// the frame with the wrong batch.+const RESERVED_RECORD_SIZE_FOR_FRAME_COMMAND: usize = 256;+const _: () = assert!(HEADER_SIZE + MAX_COMMAND_STRUCT_SIZE <= RESERVED_RECORD_SIZE_FOR_FRAME_COMMAND);++pub(crate) struct Proxy<T: Transport> {+ transport: RefCell<Rc<T>>,+ lost: Cell<bool>,+ pending_local_error: Cell<u32>,+ next_object_id: Cell<u32>,++ // NB: A call of the transport can mark the context lost, which calls back into the recorder. So nothing below is+ // borrowed across one: a number is in a Cell, and a vector is taken out of its Cell for as long as it is used.+ shared_command_buffer: RefCell<Option<T::SharedMemory>>,+ /// The start of the shared command buffer, which `shared_command_buffer` keeps mapped, or null without one.+ shared_command_buffer_start: Cell<*mut u8>,+ shared_data_capacity: Cell<usize>,+ wanted_shared_data_capacity: usize,+ shared_data_cursor: Cell<usize>,+ /// Where the records that are not published yet start.+ shared_data_flush_base: Cell<usize>,+ last_published_flush_sequence_number: Cell<u64>,++ /// The records of a context that could not get a shared command buffer.+ out_of_line_commands: Cell<Vec<u8>>,+ pending_frames: Cell<Vec<T::Frame>>,+ sync_request_bytes: Cell<Vec<u8>>,+ sync_reply_bytes: Cell<Vec<u8>>,+ /// By GL name. The strings do not change while a context lives.+ string_cache: RefCell<Vec<(u32, Rc<[u8]>)>>,+ max_frames_per_message: Cell<usize>,++ transport_calls_are_deferred: Cell<bool>,+ deferred_record_count: Cell<usize>,+ deferred_flush_is_due: Cell<bool>,+ /// The record that had no room at the cursor while the calls of the transport that make room were deferred.+ deferred_record: Cell<Vec<u8>>,+}++impl<T: Transport> Proxy<T> {+ pub(crate) fn new(transport: T) -> Self {+ Self::with_shared_data_capacity(transport, DEFAULT_SHARED_DATA_REGION_CAPACITY)+ }++ pub(super) fn with_shared_data_capacity(transport: T, shared_data_capacity: usize) -> Self {+ let proxy = Self {+ max_frames_per_message: Cell::new(transport.max_frames_per_message()),+ transport: RefCell::new(Rc::new(transport)),+ lost: Cell::new(false),+ pending_local_error: Cell::new(0),+ next_object_id: Cell::new(1),+ shared_command_buffer: RefCell::new(None),+ shared_command_buffer_start: Cell::new(ptr::null_mut()),+ shared_data_capacity: Cell::new(0),+ wanted_shared_data_capacity: shared_data_capacity,+ shared_data_cursor: Cell::new(0),+ shared_data_flush_base: Cell::new(0),+ last_published_flush_sequence_number: Cell::new(0),+ out_of_line_commands: Cell::new(Vec::new()),+ pending_frames: Cell::new(Vec::new()),+ sync_request_bytes: Cell::new(Vec::new()),+ sync_reply_bytes: Cell::new(Vec::new()),+ string_cache: RefCell::new(Vec::new()),+ transport_calls_are_deferred: Cell::new(false),+ deferred_record_count: Cell::new(0),+ deferred_flush_is_due: Cell::new(false),+ deferred_record: Cell::new(Vec::new()),+ };+ proxy.initialize_shared_command_buffer();+ proxy+ }++ /// Nothing that was recorded for the lost context reaches the new one.+ pub(crate) fn restore(&self, transport: T) {+ self.max_frames_per_message.set(transport.max_frames_per_message());+ self.transport.replace(Rc::new(transport));+ self.lost.set(false);+ self.out_of_line_commands.take();+ self.pending_frames.take();+ self.string_cache.borrow_mut().clear();+ self.initialize_shared_command_buffer();+ }++ pub(super) fn transport(&self) -> Rc<T> {+ assert!(+ !self.transport_calls_are_deferred.get(),+ "the WebGL transport is not called while the data of a command is borrowed"+ );+ Rc::clone(&self.transport.borrow())+ }++ fn initialize_shared_command_buffer(&self) {+ self.shared_data_cursor.set(0);+ self.shared_data_flush_base.set(0);+ self.last_published_flush_sequence_number.set(0);++ let transport = self.transport();+ let buffer = transport.create_shared_memory(SHARED_DATA_REGION_OFFSET + self.wanted_shared_data_capacity);+ match &buffer {+ Some(buffer) => {+ assert!(buffer.len() > SHARED_DATA_REGION_OFFSET);+ assert!(buffer.as_ptr().cast::<AtomicU64>().is_aligned());+ transport.set_shared_command_buffer(buffer);+ self.shared_command_buffer_start.set(buffer.as_ptr());+ self.shared_data_capacity.set(buffer.len() - SHARED_DATA_REGION_OFFSET);+ }+ None => {+ self.shared_command_buffer_start.set(ptr::null_mut());+ self.shared_data_capacity.set(0);+ }+ }+ // NB: The pointer above is into the new buffer already, so the old one is not used once it is unmapped here.+ self.shared_command_buffer.replace(buffer);+ }++ fn has_shared_command_buffer(&self) -> bool {+ !self.shared_command_buffer_start.get().is_null()+ }++ fn executed_flush_sequence_number(&self) -> u64 {+ // SAFETY: Only called with a shared command buffer, which is mapped, larger than a u64 and aligned for one.+ // The replayer writes the number as an atomic as well.+ unsafe { &*self.shared_command_buffer_start.get().cast::<AtomicU64>() }.load(Ordering::Acquire)+ }++ pub(crate) fn set_lost(&self) {+ self.lost.set(true);+ }++ pub(crate) fn is_lost(&self) -> bool {+ self.lost.get()+ }++ pub(crate) fn canvas_id(&self) -> Option<u64> {+ self.transport().canvas_id()+ }++ pub(super) fn allocate_object_id(&self) -> u32 {+ let id = self.next_object_id.get();+ self.next_object_id.set(id + 1);+ id+ }++ pub(super) fn set_pending_local_error(&self, error: u32) {+ if self.pending_local_error.get() == 0 {+ self.pending_local_error.set(error);+ }+ }++ pub(crate) fn take_pending_local_error(&self) -> u32 {+ self.pending_local_error.replace(0)+ }++ #[inline]+ pub(super) fn record<C: Command>(&self, command: &C) {+ self.record_bytes(C::TYPE, command.as_bytes(), InlineData::NONE);+ }++ #[inline]+ pub(super) fn record_with_data<C: Command>(&self, command: &C, inline_data: InlineData<'_>) {+ self.record_bytes(C::TYPE, command.as_bytes(), inline_data);+ }++ fn record_bytes(&self, command_type: CommandType, payload: &[u8], inline_data: InlineData<'_>) {+ if self.lost.get() {+ return;+ }+ let transport_calls_are_deferred = self.transport_calls_are_deferred.get();+ if transport_calls_are_deferred {+ // NB: What is deferred runs once the record is made. After a second record it would run in the wrong+ // order: a record that had no room after a record that was made after it.+ assert!(+ self.deferred_record_count.replace(1) == 0,+ "one command is recorded with borrowed data"+ );+ }+ let Some(record) = Record::new(command_type, payload, inline_data) else {+ self.set_pending_local_error(GL_OUT_OF_MEMORY);+ return;+ };++ if !self.has_shared_command_buffer() {+ let mut commands = self.out_of_line_commands.take();+ record.append_to(&mut commands);+ let flush_is_due = commands.len() >= MAX_PENDING_COMMAND_BYTES;+ self.out_of_line_commands.set(commands);+ if flush_is_due {+ self.flush_commands_or_defer();+ }+ return;+ }++ if transport_calls_are_deferred {+ self.rewind_shared_data_cursor_if_all_published_commands_executed();+ if record.size() > self.shared_data_capacity.get() - self.shared_data_cursor.get() {+ self.deferred_record.set(record.encoded());+ return;+ }+ } else if record.size() > self.shared_data_capacity.get() {+ self.send_oversized_record(&record.encoded());+ return;+ } else {+ self.rewind_shared_data_cursor_if_all_published_commands_executed();+ self.ensure_shared_data_capacity(record.size());+ if self.lost.get() {+ return;+ }+ }++ // SAFETY: The destination has room for the record, which was just made sure of, and neither the payload nor+ // the data is in the region of records.+ self.write_at_shared_data_cursor(record.size(), |destination| unsafe { record.write_to(destination) });+ }++ fn record_encoded(&self, record: &[u8]) {+ if self.lost.get() {+ return;+ }+ if record.len() > self.shared_data_capacity.get() {+ self.send_oversized_record(record);+ return;+ }+ self.rewind_shared_data_cursor_if_all_published_commands_executed();+ self.ensure_shared_data_capacity(record.len());+ if self.lost.get() {+ return;+ }+ // SAFETY: The destination has room for the record, which was just made sure of, and the record is not in+ // the region of records.+ self.write_at_shared_data_cursor(record.len(), |destination| unsafe {+ ptr::copy_nonoverlapping(record.as_ptr(), destination, record.len());+ });+ }++ fn write_at_shared_data_cursor(&self, record_size: usize, write_record_to: impl FnOnce(*mut u8)) {+ let cursor = self.shared_data_cursor.get();+ assert!(record_size <= self.shared_data_capacity.get() - cursor);+ // SAFETY: The region of records is mapped and has the bytes from the cursor on. The replayer does not read+ // the region past what was published.+ let destination = unsafe {+ self.shared_command_buffer_start+ .get()+ .add(SHARED_DATA_REGION_OFFSET + cursor)+ };+ write_record_to(destination);+ let cursor = cursor + record_size;+ self.shared_data_cursor.set(cursor);+ if cursor - self.shared_data_flush_base.get() >= MAX_PENDING_COMMAND_BYTES {+ self.flush_commands_or_defer();+ }+ }++ fn flush_commands_or_defer(&self) {+ if self.transport_calls_are_deferred.get() {+ self.deferred_flush_is_due.set(true);+ } else {+ self.flush_commands();+ }+ }++ fn send_oversized_record(&self, record: &[u8]) {+ self.flush_commands();+ self.transport().send_commands(record, &[]);+ }++ /// Runs `record`, which records one command with data that is borrowed from memory of script, without a call of+ /// the transport while it runs, as nothing else may run while the data is borrowed: the calls that the record+ /// needs are made before and after it.+ ///+ /// `data_size_hint` is how many bytes of data the command is expected to carry. Room for a record with as many is+ /// made before the data is borrowed. A record that there is no room for then, whatever the hint was, is copied,+ /// and the copy is put into the stream once the data is given back.+ pub(crate) fn record_with_borrowed_data<R>(&self, data_size_hint: usize, record: impl FnOnce() -> R) -> R {+ if !self.lost.get() && self.has_shared_command_buffer() {+ // NB: Which command it is going to be is not known here, so room is made for the largest struct. A+ // record that the region is too small for even with the smallest struct is sent on its own, and+ // needs no room.+ let capacity = self.shared_data_capacity.get();+ let smallest_record_size = padded_record_size(1, data_size_hint);+ let largest_record_size = data_size_hint+ .checked_add(1)+ .and_then(|data_size| padded_record_size(MAX_COMMAND_STRUCT_SIZE, data_size));+ if let (Some(smallest_record_size), Some(largest_record_size)) = (smallest_record_size, largest_record_size)+ && smallest_record_size <= capacity+ {+ self.rewind_shared_data_cursor_if_all_published_commands_executed();+ self.ensure_shared_data_capacity(largest_record_size.min(capacity));+ }+ }++ assert!(!self.transport_calls_are_deferred.replace(true));+ self.deferred_record_count.set(0);+ let result = {+ let _deferral = EndOfDeferral(&self.transport_calls_are_deferred);+ record()+ };++ let deferred_record = self.deferred_record.take();+ if !deferred_record.is_empty() {+ self.record_encoded(&deferred_record);+ }+ if self.deferred_flush_is_due.replace(false) {+ self.flush_commands();+ }+ result+ }++ fn rewind_shared_data_cursor_if_all_published_commands_executed(&self) {+ let cursor = self.shared_data_cursor.get();+ if cursor == 0 || cursor != self.shared_data_flush_base.get() {+ return;+ }+ if self.executed_flush_sequence_number() >= self.last_published_flush_sequence_number.get() {+ self.shared_data_cursor.set(0);+ self.shared_data_flush_base.set(0);+ }+ }++ /// When the region is full, everything in it is published and the recorder waits for the replayer to have+ /// executed it, which loses the context if the replayer never will.+ fn ensure_shared_data_capacity(&self, record_size: usize) {+ let capacity = self.shared_data_capacity.get();+ assert!(record_size <= capacity);+ if record_size <= capacity - self.shared_data_cursor.get() {+ return;+ }++ self.flush_commands();+ assert!(self.shared_data_cursor.get() == self.shared_data_flush_base.get());+ if self.executed_flush_sequence_number() < self.last_published_flush_sequence_number.get() {+ if !self.transport().wait_until_published_commands_executed() {+ self.set_lost();+ return;+ }+ assert!(self.executed_flush_sequence_number() >= self.last_published_flush_sequence_number.get());+ }+ self.shared_data_cursor.set(0);+ self.shared_data_flush_base.set(0);+ }++ pub(crate) fn flush_commands(&self) {+ if self.has_shared_command_buffer() {+ let cursor = self.shared_data_cursor.get();+ let flush_base = self.shared_data_flush_base.get();+ if cursor == flush_base {+ return;+ }+ let flush_sequence_number = self.last_published_flush_sequence_number.get() + 1;+ self.last_published_flush_sequence_number.set(flush_sequence_number);+ self.shared_data_flush_base.set(cursor);+ let frames = self.pending_frames.take();+ self.transport().send_commands_from_shared_buffer(+ flush_base as u64,+ (cursor - flush_base) as u64,+ flush_sequence_number,+ &frames,+ );+ self.keep_capacity_of_pending_frames(frames);+ return;+ }++ let mut commands = self.out_of_line_commands.take();+ if commands.is_empty() {+ return;+ }+ let frames = self.pending_frames.take();+ self.transport().send_commands(&commands, &frames);+ commands.clear();+ self.out_of_line_commands.set(commands);+ self.keep_capacity_of_pending_frames(frames);+ }++ fn keep_capacity_of_pending_frames(&self, mut sent_frames: Vec<T::Frame>) {+ sent_frames.clear();+ self.pending_frames.set(sent_frames);+ }++ /// Returns the index that the command which uses the frame names it by.+ pub(super) fn append_pending_frame(&self, frame: T::Frame) -> u32 {+ if self.with_pending_frames(|frames| frames.len()) >= self.max_frames_per_message.get() {+ self.flush_commands();+ }+ if self.has_shared_command_buffer() {+ self.ensure_shared_data_capacity(RESERVED_RECORD_SIZE_FOR_FRAME_COMMAND);+ }+ self.with_pending_frames(|frames| {+ let frame_index = u32::try_from(frames.len()).expect("the frames of a message are fewer than 4 billion");+ frames.push(frame);+ frame_index+ })+ }++ fn with_pending_frames<O>(&self, use_frames: impl FnOnce(&mut Vec<T::Frame>) -> O) -> O {+ let mut frames = self.pending_frames.take();+ let output = use_frames(&mut frames);+ self.pending_frames.set(frames);+ output+ }++ /// `None` when the context is lost before or by the call, and when the stream cannot carry the request, which is+ /// a GL_OUT_OF_MEMORY error of the context.+ pub(super) fn sync_call<R: SyncRequest, O>(+ &self,+ request: &R,+ inline_data: InlineData<'_>,+ read_reply: impl FnOnce(R::Reply, &[u8]) -> O,+ ) -> Option<O> {+ if self.lost.get() {+ return None;+ }+ self.flush_commands();++ let mut request_bytes = self.sync_request_bytes.take();+ let mut reply_bytes = self.sync_reply_bytes.take();+ let output = if encode_sync_request(&mut request_bytes, request, inline_data) {+ reply_bytes.clear();+ self.transport().sync_call(&request_bytes, &mut reply_bytes);+ if reply_bytes.is_empty() {+ self.set_lost();+ }+ (!self.lost.get()).then(|| read_reply(R::Reply::from_reply_bytes(&reply_bytes), reply_bytes.as_slice()))+ } else {+ self.set_pending_local_error(GL_OUT_OF_MEMORY);+ None+ };+ self.sync_request_bytes.set(request_bytes);+ self.sync_reply_bytes.set(reply_bytes);+ output+ }++ pub(super) fn cached_string(&self, name: u32) -> Option<Rc<[u8]>> {+ let string_cache = self.string_cache.borrow();+ let (_, string) = string_cache.iter().find(|(cached_name, _)| *cached_name == name)?;+ Some(Rc::clone(string))+ }++ pub(super) fn cache_string(&self, name: u32, string: Rc<[u8]>) {+ self.string_cache.borrow_mut().push((name, string));+ }++ pub(crate) fn present_canvas_for_compositing(&self, preserve_drawing_buffer: bool) {+ self.flush_commands();+ self.transport().present_canvas(preserve_drawing_buffer);+ }++ pub(crate) fn clear_drawing_buffer(&self) {+ if self.lost.get() {+ return;+ }+ self.flush_commands();+ self.transport().clear_drawing_buffer();+ }++ pub(crate) fn read_back_drawing_buffer(&self, x: i32, y: i32, width: i32, height: i32) -> Option<T::Bitmap> {+ if self.lost.get() {+ return None;+ }+ self.flush_commands();+ self.transport().read_back_drawing_buffer(x, y, width, height)+ }+}++/// Ends the deferral of the calls of the transport however the record ends, unwinding included.+struct EndOfDeferral<'a>(&'a Cell<bool>);++impl Drop for EndOfDeferral<'_> {+ fn drop(&mut self) {+ self.0.set(false);+ }+}++impl<T: Transport> Drop for Proxy<T> {+ fn drop(&mut self) {+ self.transport().destroy_context();+ }+}++/// The product of the factors that GLFunctions.json gives for the size of a pointer argument.+pub(super) fn payload_size(factors: &[i64]) -> usize {+ factors+ .iter()+ .try_fold(1usize, |size, &factor| size.checked_mul(usize::try_from(factor).ok()?))+ .expect("the size of the data of a WebGL command is validated before the command is recorded")+}++pub(super) fn leading_bytes(bytes: &[u8], size: usize) -> &[u8] {+ bytes+ .get(..size)+ .expect("the data of a WebGL command is as large as the command says")+}++pub(super) fn leading_bytes_mut(bytes: &mut [u8], size: usize) -> &mut [u8] {+ bytes+ .get_mut(..size)+ .expect("the buffer for the output of a WebGL call is as large as the call says")+}++pub(super) fn gen_count(ids: &[u32]) -> i32 {+ i32::try_from(ids.len()).expect("the objects that one WebGL command creates are counted by a GLsizei")+}++/// The replayer ends a string at its first NUL.+pub(super) fn until_nul(string: &[u8]) -> &[u8] {+ let length = string.iter().position(|&byte| byte == 0).unwrap_or(string.len());+ &string[..length]+}++/// # Safety+///+/// The type has no padding, and every bit pattern is a value of it.+pub(crate) unsafe trait PlainNumber: Copy + 'static {}+// SAFETY: The types are primitive numbers.+unsafe impl PlainNumber for u8 {}+// SAFETY: As above.+unsafe impl PlainNumber for i32 {}+// SAFETY: As above.+unsafe impl PlainNumber for u32 {}+// SAFETY: As above.+unsafe impl PlainNumber for f32 {}+// SAFETY: As above.+unsafe impl PlainNumber for i64 {}++pub(crate) fn bytes_of<N: PlainNumber>(numbers: &[N]) -> &[u8] {+ // SAFETY: Per the contract of PlainNumber the numbers are their bytes, all of which are initialized.+ unsafe { core::slice::from_raw_parts(numbers.as_ptr().cast::<u8>(), size_of_val(numbers)) }+}++pub(super) fn bytes_of_mut<N: PlainNumber>(numbers: &mut [N]) -> &mut [u8] {+ // SAFETY: Per the contract of PlainNumber the numbers are their bytes, and any bytes written are numbers.+ unsafe { core::slice::from_raw_parts_mut(numbers.as_mut_ptr().cast::<u8>(), size_of_val(numbers)) }+}++pub(super) fn copy_reply_data(reply: &[u8], span: DataSpan, destination: &mut [u8]) {+ let data = resolve_data_span(reply, span);+ assert!(+ data.len() <= destination.len(),+ "the replayer returns no more data than a WebGL call asks for"+ );+ destination[..data.len()].copy_from_slice(data);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rsnew file mode 100644index 00000000000..15edd074b74--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rs@@ -0,0 +1,1546 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The recorder against a transport that plays the replayer: it logs what it is called with, and reads the region of+//! records the way the replayer does when a range of it is published.++use core::cell::{Cell, RefCell, UnsafeCell};+use core::sync::atomic::{AtomicU64, Ordering};+use std::collections::VecDeque;+use std::rc::{Rc, Weak};++use super::custom::FrameUpload;+use super::generated::GetActiveAttribOutputs;+use super::recorder::{MAX_PENDING_COMMAND_BYTES, Proxy, SHARED_DATA_REGION_OFFSET, bytes_of};+use super::transport::{ReadPixelsResult, SharedMemory, Transport};+use super::vocabulary::{CommandType, SyncCallType, commands, sync_calls};+use super::wire::{DataSpan, HEADER_SIZE, WireStruct};+use crate::web_gl::constants::{GL_ARRAY_BUFFER, GL_INVALID_ENUM, GL_OUT_OF_MEMORY, GL_RGBA, GL_UNSIGNED_BYTE};++#[derive(Clone)]+struct MockMemory {+ words: Rc<[UnsafeCell<u64>]>,+ size: usize,+}++impl MockMemory {+ fn new(size: usize) -> Self {+ Self {+ words: (0..size.div_ceil(8)).map(|_| UnsafeCell::new(0)).collect(),+ size,+ }+ }++ fn bytes(&self, offset: usize, size: usize) -> Vec<u8> {+ assert!(offset + size <= self.size);+ // SAFETY: The range is inside the memory, which nothing else reads or writes while the test runs this.+ unsafe { core::slice::from_raw_parts(self.as_ptr().add(offset), size) }.to_vec()+ }++ fn fill(&self, bytes: &[u8]) {+ // SAFETY: As above.+ unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), self.as_ptr(), bytes.len().min(self.size)) };+ }+}++impl SharedMemory for MockMemory {+ fn as_ptr(&self) -> *mut u8 {+ UnsafeCell::raw_get(self.words.as_ptr()).cast::<u8>()+ }++ fn len(&self) -> usize {+ self.size+ }+}++#[derive(Clone, Debug, PartialEq)]+struct Record {+ command_type: u16,+ payload: Vec<u8>,+}++fn records_in(mut bytes: &[u8]) -> Vec<Record> {+ let mut records = Vec::new();+ while !bytes.is_empty() {+ let command_type = u16::from_ne_bytes([bytes[0], bytes[1]]);+ let payload_size = u32::from_ne_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize;+ let (record, rest) = bytes[HEADER_SIZE..].split_at(payload_size);+ records.push(Record {+ command_type,+ payload: record.to_vec(),+ });+ bytes = rest;+ }+ records+}++fn record_of<C: super::wire::Command>(command: &C) -> Record {+ let mut payload = command.as_bytes().to_vec();+ payload.resize((HEADER_SIZE + payload.len()).next_multiple_of(16) - HEADER_SIZE, 0);+ Record {+ command_type: C::TYPE as u16,+ payload,+ }+}++#[derive(Clone, Debug, PartialEq)]+enum Call {+ DestroyContext,+ SetSharedCommandBuffer {+ size: usize,+ },+ SendFromSharedBuffer {+ offset: u64,+ records: Vec<Record>,+ flush_sequence_number: u64,+ frames: Vec<u32>,+ },+ WaitUntilPublishedCommandsExecuted,+ SendCommands {+ records: Vec<Record>,+ frames: Vec<u32>,+ },+ PresentCanvas {+ preserve_drawing_buffer: bool,+ },+ ClearDrawingBuffer,+ Synchronous {+ request: Vec<u8>,+ },+ ReadPixels {+ buf_size: i32,+ has_pixels: bool,+ },+ ReadBufferSubData {+ target: u32,+ offset: i64,+ size: i64,+ },+ ReadBackDrawingBuffer,+}++struct MockReplayer {+ calls: RefCell<Vec<Call>>,+ shared_command_buffer: RefCell<Option<MockMemory>>,+ last_published_flush_sequence_number: Cell<u64>,+ refuses_shared_memory: Cell<bool>,+ executes_at_once: Cell<bool>,+ wait_succeeds: Cell<bool>,+ max_frames_per_message: Cell<usize>,+ sync_replies: RefCell<VecDeque<Vec<u8>>>,+ read_data: RefCell<Vec<u8>>,+ read_pixels_result: Cell<ReadPixelsResult>,+ read_buffer_sub_data_succeeds: Cell<bool>,+ calls_are_forbidden: Cell<bool>,+ recorder_to_lose: RefCell<Weak<Proxy<MockTransport>>>,+}++impl MockReplayer {+ fn new() -> Rc<Self> {+ Rc::new(Self {+ calls: RefCell::new(Vec::new()),+ shared_command_buffer: RefCell::new(None),+ last_published_flush_sequence_number: Cell::new(0),+ refuses_shared_memory: Cell::new(false),+ executes_at_once: Cell::new(true),+ wait_succeeds: Cell::new(true),+ max_frames_per_message: Cell::new(16),+ sync_replies: RefCell::new(VecDeque::new()),+ read_data: RefCell::new(Vec::new()),+ read_pixels_result: Cell::new(ReadPixelsResult::default()),+ read_buffer_sub_data_succeeds: Cell::new(true),+ calls_are_forbidden: Cell::new(false),+ recorder_to_lose: RefCell::new(Weak::new()),+ })+ }++ fn recorder(self: &Rc<Self>, shared_data_capacity: usize) -> Proxy<MockTransport> {+ Proxy::with_shared_data_capacity(+ MockTransport {+ replayer: Rc::clone(self),+ },+ shared_data_capacity,+ )+ }++ fn called(&self, call: Call) {+ assert!(+ !self.calls_are_forbidden.get(),+ "{call:?} while the calls of the transport are deferred"+ );+ self.calls.borrow_mut().push(call);+ // NB: This is the host finding the replayer gone in the middle of a call.+ let recorder_to_lose = self.recorder_to_lose.borrow().upgrade();+ if let Some(recorder) = recorder_to_lose {+ recorder.set_lost();+ }+ }++ fn take_calls(&self) -> Vec<Call> {+ self.calls.take()+ }++ /// The calls are allowed again even when the function panics, as the recorder calls the transport when it is+ /// dropped.+ fn forbidding_calls<R>(&self, function: impl FnOnce() -> R) -> R {+ struct CallsAreAllowedAgain<'a>(&'a Cell<bool>);+ impl Drop for CallsAreAllowedAgain<'_> {+ fn drop(&mut self) {+ self.0.set(false);+ }+ }++ self.calls_are_forbidden.set(true);+ let _calls_are_allowed_again = CallsAreAllowedAgain(&self.calls_are_forbidden);+ function()+ }++ fn bytes_of_region(&self, offset: usize, size: usize) -> Vec<u8> {+ let shared_command_buffer = self.shared_command_buffer.borrow();+ shared_command_buffer+ .as_ref()+ .expect("a shared command buffer")+ .bytes(SHARED_DATA_REGION_OFFSET + offset, size)+ }++ fn store_executed_flush_sequence_number(&self, flush_sequence_number: u64) {+ let shared_command_buffer = self.shared_command_buffer.borrow();+ let start = shared_command_buffer+ .as_ref()+ .expect("a shared command buffer")+ .as_ptr();+ // SAFETY: The memory is larger than a u64 and aligned for one.+ unsafe { &*start.cast::<AtomicU64>() }.store(flush_sequence_number, Ordering::Release);+ }++ fn queue_reply<R: WireStruct>(&self, reply: &R, inline_data: &[u8]) {+ let mut bytes = reply.as_bytes().to_vec();+ if !inline_data.is_empty() {+ bytes.resize(bytes.len().next_multiple_of(16), 0);+ bytes.extend_from_slice(inline_data);+ }+ bytes.resize(bytes.len().next_multiple_of(16), 0);+ self.sync_replies.borrow_mut().push_back(bytes);+ }+}++struct MockTransport {+ replayer: Rc<MockReplayer>,+}++impl Transport for MockTransport {+ type SharedMemory = MockMemory;+ type Frame = u32;+ type Bitmap = (i32, i32, i32, i32);++ fn max_frames_per_message(&self) -> usize {+ self.replayer.max_frames_per_message.get()+ }++ fn create_shared_memory(&self, size: usize) -> Option<MockMemory> {+ (!self.replayer.refuses_shared_memory.get()).then(|| MockMemory::new(size))+ }++ fn canvas_id(&self) -> Option<u64> {+ Some(42)+ }++ fn destroy_context(&self) {+ self.replayer.called(Call::DestroyContext);+ }++ fn set_shared_command_buffer(&self, buffer: &MockMemory) {+ self.replayer.shared_command_buffer.replace(Some(buffer.clone()));+ self.replayer.last_published_flush_sequence_number.set(0);+ self.replayer+ .called(Call::SetSharedCommandBuffer { size: buffer.len() });+ }++ fn send_commands_from_shared_buffer(+ &self,+ offset: u64,+ size_in_bytes: u64,+ flush_sequence_number: u64,+ frames: &[u32],+ ) {+ let published = {+ let shared_command_buffer = self.replayer.shared_command_buffer.borrow();+ let shared_command_buffer = shared_command_buffer.as_ref().expect("a shared command buffer");+ shared_command_buffer.bytes(SHARED_DATA_REGION_OFFSET + offset as usize, size_in_bytes as usize)+ };+ self.replayer+ .last_published_flush_sequence_number+ .set(flush_sequence_number);+ if self.replayer.executes_at_once.get() {+ self.replayer+ .store_executed_flush_sequence_number(flush_sequence_number);+ }+ self.replayer.called(Call::SendFromSharedBuffer {+ offset,+ records: records_in(&published),+ flush_sequence_number,+ frames: frames.to_vec(),+ });+ }++ fn wait_until_published_commands_executed(&self) -> bool {+ let wait_succeeds = self.replayer.wait_succeeds.get();+ if wait_succeeds {+ let last_published = self.replayer.last_published_flush_sequence_number.get();+ self.replayer.store_executed_flush_sequence_number(last_published);+ }+ self.replayer.called(Call::WaitUntilPublishedCommandsExecuted);+ wait_succeeds+ }++ fn send_commands(&self, commands: &[u8], frames: &[u32]) {+ self.replayer.called(Call::SendCommands {+ records: records_in(commands),+ frames: frames.to_vec(),+ });+ }++ fn present_canvas(&self, preserve_drawing_buffer: bool) {+ self.replayer.called(Call::PresentCanvas {+ preserve_drawing_buffer,+ });+ }++ fn clear_drawing_buffer(&self) {+ self.replayer.called(Call::ClearDrawingBuffer);+ }++ fn sync_call(&self, request: &[u8], reply: &mut Vec<u8>) {+ if let Some(queued_reply) = self.replayer.sync_replies.borrow_mut().pop_front() {+ reply.extend_from_slice(&queued_reply);+ }+ self.replayer.called(Call::Synchronous {+ request: request.to_vec(),+ });+ }++ fn read_pixels_robust_angle(+ &self,+ _x: i32,+ _y: i32,+ _width: i32,+ _height: i32,+ _format: u32,+ _type: u32,+ buf_size: i32,+ pixels: Option<&MockMemory>,+ ) -> ReadPixelsResult {+ if let Some(pixels) = pixels {+ pixels.fill(&self.replayer.read_data.borrow());+ }+ self.replayer.called(Call::ReadPixels {+ buf_size,+ has_pixels: pixels.is_some(),+ });+ self.replayer.read_pixels_result.get()+ }++ fn read_buffer_sub_data(&self, target: u32, offset: i64, size: i64, data: &MockMemory) -> bool {+ data.fill(&self.replayer.read_data.borrow());+ self.replayer.called(Call::ReadBufferSubData { target, offset, size });+ self.replayer.read_buffer_sub_data_succeeds.get()+ }++ fn read_back_drawing_buffer(&self, x: i32, y: i32, width: i32, height: i32) -> Option<(i32, i32, i32, i32)> {+ self.replayer.called(Call::ReadBackDrawingBuffer);+ Some((x, y, width, height))+ }+}++const SMALL_CAPACITY: usize = 4096;+const VIEWPORT: commands::Viewport = commands::Viewport {+ x: 1,+ y: 2,+ width: 3,+ height: 4,+};+const VIEWPORT_RECORD_SIZE: usize = 32;++fn record_viewport(recorder: &Proxy<MockTransport>) {+ recorder.viewport(VIEWPORT.x, VIEWPORT.y, VIEWPORT.width, VIEWPORT.height);+}++fn sent_from_shared_buffer(offset: u64, records: Vec<Record>, flush_sequence_number: u64) -> Call {+ Call::SendFromSharedBuffer {+ offset,+ records,+ flush_sequence_number,+ frames: Vec::new(),+ }+}++const BUFFER_SUB_DATA_STRUCT_SIZE: usize = 32;++fn buffer_sub_data_record_size(data: &[u8]) -> usize {+ (HEADER_SIZE + BUFFER_SUB_DATA_STRUCT_SIZE + data.len()).next_multiple_of(16)+}++/// `data` is not empty.+fn buffer_sub_data_record(data: &[u8]) -> Record {+ let command = commands::BufferSubData {+ target: GL_ARRAY_BUFFER,+ size: data.len() as i64,+ data: DataSpan {+ offset: BUFFER_SUB_DATA_STRUCT_SIZE as u32,+ size: data.len() as u32,+ },+ ..commands::BufferSubData::ZEROED+ };+ let mut payload = command.as_bytes().to_vec();+ payload.extend_from_slice(data);+ payload.resize(buffer_sub_data_record_size(data) - HEADER_SIZE, 0);+ Record {+ command_type: CommandType::BufferSubData as u16,+ payload,+ }+}++fn record_borrowed_buffer_sub_data(+ replayer: &MockReplayer,+ recorder: &Proxy<MockTransport>,+ data_size_hint: usize,+ data: &[u8],+ check_while_data_is_borrowed: impl FnOnce(),+) {+ recorder.record_with_borrowed_data(data_size_hint, || {+ replayer.forbidding_calls(|| recorder.buffer_sub_data(GL_ARRAY_BUFFER, 0, data.len() as i64, data));+ check_while_data_is_borrowed();+ });+}++fn frame_upload() -> FrameUpload {+ FrameUpload {+ destination_size: None,+ flip_y: false,+ premultiply_alpha: false,+ }+}++fn upload_frame(recorder: &Proxy<MockTransport>, frame: u32) {+ recorder.tex_image2d_from_bitmap(1, 0, 3, GL_RGBA, GL_UNSIGNED_BYTE, frame, frame_upload());+}++fn frame_record(bitmap_index: u32) -> Record {+ record_of(&commands::TexImage2DFromBitmap {+ target: 1,+ internalformat: 3,+ format: GL_RGBA,+ r#type: GL_UNSIGNED_BYTE,+ bitmap_index,+ ..commands::TexImage2DFromBitmap::ZEROED+ })+}++#[test]+fn a_command_waits_in_the_shared_buffer_for_a_flush() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ assert_eq!(+ replayer.take_calls(),+ [Call::SetSharedCommandBuffer {+ size: SHARED_DATA_REGION_OFFSET + SMALL_CAPACITY+ }]+ );++ record_viewport(&recorder);+ recorder.enable(7);+ assert_eq!(replayer.take_calls(), []);++ recorder.flush_commands();+ let records = vec![record_of(&VIEWPORT), record_of(&commands::Enable { cap: 7 })];+ assert_eq!(replayer.take_calls(), [sent_from_shared_buffer(0, records, 1)]);++ recorder.flush_commands();+ assert_eq!(replayer.take_calls(), []);+}++#[test]+fn the_cursor_rewinds_once_everything_published_is_executed() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();++ replayer.executes_at_once.set(false);+ record_viewport(&recorder);+ recorder.flush_commands();+ record_viewport(&recorder);+ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(0, vec![record_of(&VIEWPORT)], 1),+ sent_from_shared_buffer(VIEWPORT_RECORD_SIZE as u64, vec![record_of(&VIEWPORT)], 2),+ ]+ );++ replayer.store_executed_flush_sequence_number(2);+ record_viewport(&recorder);+ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [sent_from_shared_buffer(0, vec![record_of(&VIEWPORT)], 3)]+ );+}++#[test]+fn a_full_region_is_published_and_waited_for() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(3 * VIEWPORT_RECORD_SIZE);+ replayer.take_calls();+ replayer.executes_at_once.set(false);++ for _ in 0..3 {+ record_viewport(&recorder);+ }+ assert_eq!(replayer.take_calls(), []);++ recorder.enable(7);+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(0, vec![record_of(&VIEWPORT); 3], 1),+ Call::WaitUntilPublishedCommandsExecuted+ ]+ );+ assert!(!recorder.is_lost());++ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [sent_from_shared_buffer(+ 0,+ vec![record_of(&commands::Enable { cap: 7 })],+ 2+ )]+ );+}++#[test]+fn a_replayer_that_never_executes_what_was_published_loses_the_context() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(VIEWPORT_RECORD_SIZE);+ replayer.executes_at_once.set(false);+ replayer.wait_succeeds.set(false);++ record_viewport(&recorder);+ record_viewport(&recorder);+ assert!(recorder.is_lost());+ replayer.take_calls();++ record_viewport(&recorder);+ recorder.flush_commands();+ assert_eq!(replayer.take_calls(), []);+}++#[test]+fn pending_commands_are_published_at_the_threshold() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(4 * MAX_PENDING_COMMAND_BYTES);+ replayer.take_calls();++ let data = vec![5u8; MAX_PENDING_COMMAND_BYTES / 2];+ recorder.buffer_sub_data(GL_ARRAY_BUFFER, 0, data.len() as i64, &data);+ assert_eq!(replayer.take_calls(), []);+ recorder.buffer_sub_data(GL_ARRAY_BUFFER, 0, data.len() as i64, &data);+ let calls = replayer.take_calls();+ let [+ Call::SendFromSharedBuffer {+ offset: 0,+ records,+ flush_sequence_number: 1,+ ..+ },+ ] = calls.as_slice()+ else {+ panic!("{} calls", calls.len());+ };+ assert_eq!(records.len(), 2);+ assert_eq!(records[1].command_type, CommandType::BufferSubData as u16);+ assert_eq!(records[1].payload[32..32 + data.len()], data);+}++#[test]+fn a_record_larger_than_the_region_is_sent_on_its_own() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();++ record_viewport(&recorder);+ let data = vec![5u8; SMALL_CAPACITY];+ recorder.buffer_sub_data(GL_ARRAY_BUFFER, 8, data.len() as i64, &data);+ let calls = replayer.take_calls();+ let [first, Call::SendCommands { records, frames }] = calls.as_slice() else {+ panic!("{} calls", calls.len());+ };+ assert_eq!(*first, sent_from_shared_buffer(0, vec![record_of(&VIEWPORT)], 1));+ assert!(frames.is_empty());+ assert_eq!(records.len(), 1);+ let command = commands::BufferSubData {+ target: GL_ARRAY_BUFFER,+ offset: 8,+ size: SMALL_CAPACITY as i64,+ data: DataSpan {+ offset: 32,+ size: SMALL_CAPACITY as u32,+ },+ ..commands::BufferSubData::ZEROED+ };+ assert_eq!(records[0].payload[..32], *command.as_bytes());+ assert_eq!(records[0].payload[32..32 + data.len()], data);++ record_viewport(&recorder);+ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [sent_from_shared_buffer(0, vec![record_of(&VIEWPORT)], 2)]+ );+}++#[test]+fn without_a_shared_buffer_commands_are_sent_as_bytes() {+ let replayer = MockReplayer::new();+ replayer.refuses_shared_memory.set(true);+ let recorder = replayer.recorder(SMALL_CAPACITY);+ assert_eq!(replayer.take_calls(), []);++ record_viewport(&recorder);+ upload_frame(&recorder, 70);+ assert_eq!(replayer.take_calls(), []);+ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [Call::SendCommands {+ records: vec![record_of(&VIEWPORT), frame_record(0)],+ frames: vec![70]+ }]+ );+ recorder.flush_commands();+ assert_eq!(replayer.take_calls(), []);++ let data = vec![5u8; MAX_PENDING_COMMAND_BYTES];+ recorder.buffer_sub_data(GL_ARRAY_BUFFER, 0, data.len() as i64, &data);+ let calls = replayer.take_calls();+ assert!(matches!(calls.as_slice(), [Call::SendCommands { records, .. }] if records.len() == 1));+}++#[test]+fn a_frame_is_published_with_the_command_that_names_it() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();++ upload_frame(&recorder, 70);+ recorder.tex_sub_image2d_from_bitmap(+ 1,+ 0,+ 5,+ 6,+ GL_RGBA,+ GL_UNSIGNED_BYTE,+ 90,+ FrameUpload {+ destination_size: Some((8, 9)),+ flip_y: true,+ premultiply_alpha: true,+ },+ );+ recorder.flush_commands();+ let sub_image = commands::TexSubImage2DFromBitmap {+ target: 1,+ xoffset: 5,+ yoffset: 6,+ format: GL_RGBA,+ r#type: GL_UNSIGNED_BYTE,+ bitmap_index: 1,+ has_explicit_destination_size: true,+ destination_width: 8,+ destination_height: 9,+ flip_y: true,+ premultiply_alpha: true,+ ..commands::TexSubImage2DFromBitmap::ZEROED+ };+ assert_eq!(+ replayer.take_calls(),+ [Call::SendFromSharedBuffer {+ offset: 0,+ records: vec![frame_record(0), record_of(&sub_image)],+ flush_sequence_number: 1,+ frames: vec![70, 90],+ }]+ );++ upload_frame(&recorder, 80);+ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [Call::SendFromSharedBuffer {+ offset: 0,+ records: vec![frame_record(0)],+ flush_sequence_number: 2,+ frames: vec![80],+ }]+ );+}++#[test]+fn a_message_carries_no_more_frames_than_the_transport_allows() {+ let replayer = MockReplayer::new();+ replayer.max_frames_per_message.set(2);+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();++ for frame in [70, 80, 90] {+ upload_frame(&recorder, frame);+ }+ assert_eq!(+ replayer.take_calls(),+ [Call::SendFromSharedBuffer {+ offset: 0,+ records: vec![frame_record(0), frame_record(1)],+ flush_sequence_number: 1,+ frames: vec![70, 80],+ }]+ );+ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [Call::SendFromSharedBuffer {+ offset: 0,+ records: vec![frame_record(0)],+ flush_sequence_number: 2,+ frames: vec![90],+ }]+ );+}++#[test]+fn room_for_the_command_of_a_frame_is_made_before_the_frame_is_pending() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(512);+ replayer.take_calls();++ // NB: This leaves less room than is kept free for a command that names a frame, though the command would fit.+ for _ in 0..9 {+ record_viewport(&recorder);+ }+ upload_frame(&recorder, 70);+ assert_eq!(+ replayer.take_calls(),+ [sent_from_shared_buffer(0, vec![record_of(&VIEWPORT); 9], 1)]+ );+ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [Call::SendFromSharedBuffer {+ offset: 0,+ records: vec![frame_record(0)],+ flush_sequence_number: 2,+ frames: vec![70],+ }]+ );+}++#[test]+fn a_lost_context_records_nothing_and_answers_with_zeros() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();+ recorder.set_lost();++ record_viewport(&recorder);+ upload_frame(&recorder, 70);+ recorder.flush_commands();+ assert_eq!(recorder.get_error(), 0);+ assert!(!recorder.is_buffer(1));+ let mut name = [0xAAu8; 4];+ assert_eq!(+ recorder.get_active_attrib(1, 0, 4, &mut name),+ GetActiveAttribOutputs::default()+ );+ assert_eq!(name, [0xAA; 4]);+ assert!(recorder.get_string(1).is_empty());+ assert_eq!(recorder.get_vertex_attrib_pointerv_robust_angle(0, 1), 0);+ recorder.clear_drawing_buffer();+ assert_eq!(recorder.read_back_drawing_buffer(0, 0, 1, 1), None);+ assert!(!recorder.read_buffer_sub_data(GL_ARRAY_BUFFER, 0, 4, |_| panic!("nothing was read")));+ recorder.read_pixels_robust_angle(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 4, |_, _| {+ panic!("nothing was read")+ });+ assert_eq!(replayer.take_calls(), []);++ // NB: Objects are still created, so that the implementation of the context does not have to tell the cases apart.+ assert_eq!(recorder.create_program(), 1);+ assert_eq!(recorder.create_shader(2), 2);+}++#[test]+fn a_synchronous_call_publishes_what_was_recorded_before_it() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();++ replayer.queue_reply(+ &sync_calls::GetErrorReply {+ return_value: GL_INVALID_ENUM,+ },+ &[],+ );+ record_viewport(&recorder);+ assert_eq!(recorder.get_error(), GL_INVALID_ENUM);++ let mut request = Vec::new();+ request.extend_from_slice(&(SyncCallType::GetError as u16).to_ne_bytes());+ request.extend_from_slice(&[0, 0]);+ request.extend_from_slice(&16u32.to_ne_bytes());+ request.extend_from_slice(&[0; 16]);+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(0, vec![record_of(&VIEWPORT)], 1),+ Call::Synchronous { request }+ ]+ );+ assert!(!recorder.is_lost());+}++#[test]+fn a_call_without_a_reply_loses_the_context() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ assert_eq!(recorder.get_error(), 0);+ assert!(recorder.is_lost());+}++#[test]+fn a_synchronous_call_returns_its_outputs_and_fills_its_buffers() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);++ let reply = sync_calls::GetActiveAttribReply {+ length: 3,+ size: 1,+ r#type: 0x8B50,+ name: DataSpan { offset: 32, size: 4 },+ };+ replayer.queue_reply(&reply, b"pos\0");+ let mut name = [0xAAu8; 8];+ let outputs = recorder.get_active_attrib(5, 0, 8, &mut name);+ assert_eq!(+ outputs,+ GetActiveAttribOutputs {+ length: 3,+ size: 1,+ r#type: 0x8B50+ }+ );+ assert_eq!(name, *b"pos\0\xAA\xAA\xAA\xAA");++ replayer.queue_reply(&sync_calls::IsBufferReply { return_value: 1 }, &[]);+ assert!(recorder.is_buffer(5));++ let reply = sync_calls::GetIntegervRobustANGLEReply {+ length: 2,+ data: DataSpan { offset: 16, size: 8 },+ };+ replayer.queue_reply(&reply, bytes_of(&[640i32, 480]));+ let mut size = [0i32; 2];+ assert_eq!(recorder.get_integerv_robust_angle(0x0D3A, 2, &mut size), 2);+ assert_eq!(size, [640, 480]);++ replayer.queue_reply(+ &sync_calls::GetUniformIndicesReply {+ uniform_indices: DataSpan { offset: 16, size: 8 },+ },+ bytes_of(&[4u32, 6]),+ );+ let mut indices = [0u32; 2];+ replayer.take_calls();+ recorder.get_uniform_indices(5, &[b"first", b"second\0ignored"], &mut indices);+ assert_eq!(indices, [4, 6]);+ let calls = replayer.take_calls();+ let [Call::Synchronous { request }] = calls.as_slice() else {+ panic!("{} calls", calls.len());+ };+ assert_eq!(request[HEADER_SIZE + 16..HEADER_SIZE + 29], *b"first\0second\0");+}++#[test]+fn a_string_ends_at_its_first_nul() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();++ recorder.bind_attrib_location(1, 2, b"ab\0cd");+ recorder.shader_source(3, b"void\0main");+ recorder.transform_feedback_varyings(4, &[b"a", b"bc\0d"], 5);+ recorder.flush_commands();+ let calls = replayer.take_calls();+ let [Call::SendFromSharedBuffer { records, .. }] = calls.as_slice() else {+ panic!("{} calls", calls.len());+ };+ let bind = commands::BindAttribLocation {+ program: 1,+ index: 2,+ name: DataSpan { offset: 16, size: 3 },+ };+ assert_eq!(records[0].payload[..16], *bind.as_bytes());+ assert_eq!(records[0].payload[16..], *b"ab\0\0\0\0\0\0");+ // NB: The source of a shader is passed with its length, so a NUL does not end it.+ let source = commands::ShaderSource {+ shader: 3,+ source: DataSpan { offset: 16, size: 10 },+ };+ assert_eq!(records[1].payload[..12], *source.as_bytes());+ assert_eq!(records[1].payload[16..26], *b"void\0main\0");+ let varyings = commands::TransformFeedbackVaryings {+ program: 4,+ count: 2,+ varyings: DataSpan { offset: 32, size: 5 },+ buffer_mode: 5,+ };+ assert_eq!(records[2].payload[..20], *varyings.as_bytes());+ assert_eq!(records[2].payload[32..37], *b"a\0bc\0");+}++#[test]+fn the_replayer_is_asked_for_a_string_once() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();++ replayer.queue_reply(+ &sync_calls::GetStringReply {+ value: DataSpan { offset: 16, size: 6 },+ },+ b"ANGLE\0",+ );+ assert_eq!(*recorder.get_string(0x1F01), *b"ANGLE");+ assert_eq!(*recorder.get_string(0x1F01), *b"ANGLE");+ assert_eq!(replayer.take_calls().len(), 1);++ // NB: The string that a lost context answers with is not the string of the name.+ recorder.set_lost();+ assert!(recorder.get_string(0x1F00).is_empty());+ recorder.restore(MockTransport {+ replayer: Rc::clone(&replayer),+ });+ replayer.take_calls();+ replayer.queue_reply(+ &sync_calls::GetStringReply {+ value: DataSpan { offset: 16, size: 2 },+ },+ b"X\0",+ );+ assert_eq!(*recorder.get_string(0x1F01), *b"X");+}++#[test]+fn objects_get_their_ids_from_the_recorder() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();++ let mut buffers = [0u32; 3];+ recorder.gen_buffers(&mut buffers);+ assert_eq!(buffers, [1, 2, 3]);+ assert_eq!(recorder.create_shader(0x8B31), 4);+ recorder.gen_textures(&mut []);+ recorder.delete_buffers(2, &buffers);+ recorder.flush_commands();++ let calls = replayer.take_calls();+ let [Call::SendFromSharedBuffer { records, .. }] = calls.as_slice() else {+ panic!("{} calls", calls.len());+ };+ assert_eq!(records.len(), 3);+ let gen_buffers = commands::GenBuffers {+ n: 3,+ buffers: DataSpan { offset: 16, size: 12 },+ };+ assert_eq!(records[0].payload[..12], *gen_buffers.as_bytes());+ assert_eq!(records[0].payload[16..28], *bytes_of(&[1u32, 2, 3]));+ assert_eq!(records[1], record_of(&commands::CreateShader { id: 4, r#type: 0x8B31 }));+ let delete_buffers = commands::DeleteBuffers {+ n: 2,+ buffers: DataSpan { offset: 16, size: 8 },+ };+ assert_eq!(records[2].payload[..12], *delete_buffers.as_bytes());+ assert_eq!(records[2].payload[16..24], *bytes_of(&[1u32, 2]));+}++#[test]+fn data_without_bytes_takes_no_room() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();++ recorder.buffer_data(GL_ARRAY_BUFFER, 16, None, 9);+ recorder.buffer_data(GL_ARRAY_BUFFER, 4, Some(&[1, 2, 3, 4, 5]), 9);+ recorder.flush_commands();+ let calls = replayer.take_calls();+ let [Call::SendFromSharedBuffer { records, .. }] = calls.as_slice() else {+ panic!("{} calls", calls.len());+ };+ let without_data = commands::BufferData {+ target: GL_ARRAY_BUFFER,+ size: 16,+ data: DataSpan { offset: 32, size: 0 },+ usage: 9,+ ..commands::BufferData::ZEROED+ };+ assert_eq!(records[0], record_of(&without_data));+ let with_data = commands::BufferData {+ target: GL_ARRAY_BUFFER,+ size: 4,+ has_data: true,+ data: DataSpan { offset: 32, size: 4 },+ usage: 9,+ ..commands::BufferData::ZEROED+ };+ assert_eq!(records[1].payload[..32], *with_data.as_bytes());+ assert_eq!(records[1].payload[32..], [1, 2, 3, 4, 0, 0, 0, 0]);+}++#[test]+#[should_panic(expected = "as large as the command says")]+fn data_that_is_smaller_than_its_command_says_is_not_recorded() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ recorder.uniform2fv(1, 2, bytes_of(&[1.0f32, 2.0, 3.0]));+}++#[test]+fn the_transport_is_not_called_while_data_is_borrowed() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(8 * VIEWPORT_RECORD_SIZE);+ replayer.take_calls();+ let record_with_borrowed_data = |data: &[u8]| {+ recorder.record_with_borrowed_data(data.len(), || {+ replayer.forbidding_calls(|| recorder.buffer_sub_data(GL_ARRAY_BUFFER, 0, data.len() as i64, data));+ });+ };++ // Room that the record needs is made before the data is borrowed.+ for _ in 0..7 {+ record_viewport(&recorder);+ }+ record_with_borrowed_data(&[5; 16]);+ assert_eq!(+ replayer.take_calls(),+ [sent_from_shared_buffer(0, vec![record_of(&VIEWPORT); 7], 1)]+ );+ recorder.flush_commands();+ let calls = replayer.take_calls();+ assert!(matches!(calls.as_slice(), [Call::SendFromSharedBuffer { offset: 0, records, .. }] if records.len() == 1));++ // A record that the region is too small for is sent after the data is given back.+ record_viewport(&recorder);+ record_with_borrowed_data(&[5; 1024]);+ let calls = replayer.take_calls();+ let [first, Call::SendCommands { records, .. }] = calls.as_slice() else {+ panic!("{} calls", calls.len());+ };+ assert_eq!(*first, sent_from_shared_buffer(0, vec![record_of(&VIEWPORT)], 3));+ assert_eq!(records[0].payload[32..32 + 1024], [5; 1024]);+}++#[test]+fn a_flush_that_is_due_while_data_is_borrowed_follows_the_record() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(4 * MAX_PENDING_COMMAND_BYTES);+ replayer.take_calls();++ let data = vec![5u8; MAX_PENDING_COMMAND_BYTES];+ recorder.record_with_borrowed_data(data.len(), || {+ replayer.forbidding_calls(|| recorder.buffer_sub_data(GL_ARRAY_BUFFER, 0, data.len() as i64, &data));+ });+ let calls = replayer.take_calls();+ assert!(matches!(calls.as_slice(), [Call::SendFromSharedBuffer { offset: 0, records, .. }] if records.len() == 1));+}++#[test]+#[should_panic(expected = "one command is recorded with borrowed data")]+fn only_one_command_is_recorded_with_borrowed_data() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ recorder.record_with_borrowed_data(0, || {+ record_viewport(&recorder);+ record_viewport(&recorder);+ });+}++#[test]+fn data_of_the_expected_size_is_recorded_while_it_is_borrowed() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(8 * VIEWPORT_RECORD_SIZE);+ replayer.take_calls();+ replayer.executes_at_once.set(false);++ for _ in 0..7 {+ record_viewport(&recorder);+ }+ let data = [5u8; 16];+ record_borrowed_buffer_sub_data(&replayer, &recorder, data.len(), &data, || {+ // The room that the record needs was made before the data was borrowed, and the record is in the region+ // before the data is given back.+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(0, vec![record_of(&VIEWPORT); 7], 1),+ Call::WaitUntilPublishedCommandsExecuted+ ]+ );+ let record_in_region = replayer.bytes_of_region(0, buffer_sub_data_record_size(&data));+ assert_eq!(records_in(&record_in_region), [buffer_sub_data_record(&data)]);+ });+ assert_eq!(replayer.take_calls(), []);++ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [sent_from_shared_buffer(0, vec![buffer_sub_data_record(&data)], 2)]+ );+}++#[test]+fn a_record_with_less_data_than_expected_gets_its_room_once_the_data_is_given_back() {+ let replayer = MockReplayer::new();+ let capacity = 8 * VIEWPORT_RECORD_SIZE;+ let recorder = replayer.recorder(capacity);+ replayer.take_calls();+ replayer.executes_at_once.set(false);++ // NB: This is an upload of the first bytes of a view that is larger than the region of records, with less room+ // left in the region than the record takes.+ for _ in 0..7 {+ record_viewport(&recorder);+ }+ let data = [5u8; 16];+ let size_of_view = 1024 * capacity;+ record_borrowed_buffer_sub_data(&replayer, &recorder, size_of_view, &data, || {+ assert_eq!(replayer.take_calls(), []);+ let room_at_cursor = replayer.bytes_of_region(7 * VIEWPORT_RECORD_SIZE, VIEWPORT_RECORD_SIZE);+ assert_eq!(room_at_cursor, [0; VIEWPORT_RECORD_SIZE]);+ });+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(0, vec![record_of(&VIEWPORT); 7], 1),+ Call::WaitUntilPublishedCommandsExecuted+ ]+ );+ assert!(!recorder.is_lost());++ record_viewport(&recorder);+ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [sent_from_shared_buffer(+ 0,+ vec![buffer_sub_data_record(&data), record_of(&VIEWPORT)],+ 2+ )]+ );+}++#[test]+fn a_record_with_more_data_than_expected_gets_its_room_once_the_data_is_given_back() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(8 * VIEWPORT_RECORD_SIZE);+ replayer.take_calls();+ replayer.executes_at_once.set(false);++ // NB: The room that is left is enough for a record with as much data as expected, so none is made before the+ // data is borrowed.+ for _ in 0..4 {+ record_viewport(&recorder);+ }+ let data = [5u8; 100];+ assert!(buffer_sub_data_record_size(&data) > 4 * VIEWPORT_RECORD_SIZE);+ record_borrowed_buffer_sub_data(&replayer, &recorder, 0, &data, || {+ assert_eq!(replayer.take_calls(), []);+ });+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(0, vec![record_of(&VIEWPORT); 4], 1),+ Call::WaitUntilPublishedCommandsExecuted+ ]+ );++ // A record that the region is too small for is sent on its own, after what was recorded before it.+ record_viewport(&recorder);+ let data_larger_than_region = [6u8; 1024];+ record_borrowed_buffer_sub_data(&replayer, &recorder, 0, &data_larger_than_region, || {+ assert_eq!(replayer.take_calls(), []);+ });+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(0, vec![buffer_sub_data_record(&data), record_of(&VIEWPORT)], 2),+ Call::SendCommands {+ records: vec![buffer_sub_data_record(&data_larger_than_region)],+ frames: Vec::new()+ }+ ]+ );+}++#[test]+fn the_replayer_is_waited_for_only_when_a_record_with_borrowed_data_finds_the_region_full() {+ let replayer = MockReplayer::new();+ let capacity = 8 * VIEWPORT_RECORD_SIZE;+ let recorder = replayer.recorder(capacity);+ replayer.take_calls();+ let data = [5u8; 16];+ let unexpected_data_size = 1024 * capacity;++ // With room where the cursor is, the record is written there while its data is borrowed, whatever was expected.+ replayer.executes_at_once.set(false);+ record_viewport(&recorder);+ record_borrowed_buffer_sub_data(&replayer, &recorder, unexpected_data_size, &data, || {+ let record_in_region = replayer.bytes_of_region(VIEWPORT_RECORD_SIZE, buffer_sub_data_record_size(&data));+ assert_eq!(records_in(&record_in_region), [buffer_sub_data_record(&data)]);+ });+ assert_eq!(replayer.take_calls(), []);++ // Without room, what is in the region is published, and the replayer is waited for unless it has executed it.+ for _ in 0..4 {+ record_viewport(&recorder);+ }+ record_borrowed_buffer_sub_data(&replayer, &recorder, unexpected_data_size, &data, || {});+ let mut published_records = vec![record_of(&VIEWPORT), buffer_sub_data_record(&data)];+ published_records.extend(vec![record_of(&VIEWPORT); 4]);+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(0, published_records, 1),+ Call::WaitUntilPublishedCommandsExecuted+ ]+ );++ replayer.executes_at_once.set(true);+ for _ in 0..5 {+ record_viewport(&recorder);+ }+ record_borrowed_buffer_sub_data(&replayer, &recorder, unexpected_data_size, &data, || {});+ let mut published_records = vec![buffer_sub_data_record(&data)];+ published_records.extend(vec![record_of(&VIEWPORT); 5]);+ assert_eq!(+ replayer.take_calls(),+ [sent_from_shared_buffer(0, published_records, 2)]+ );++ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [sent_from_shared_buffer(0, vec![buffer_sub_data_record(&data)], 3)]+ );+}++#[test]+fn a_context_that_is_lost_while_room_is_made_for_a_record_with_borrowed_data_drops_the_record() {+ let replayer = MockReplayer::new();+ let capacity = 8 * VIEWPORT_RECORD_SIZE;+ let recorder = replayer.recorder(capacity);+ replayer.take_calls();+ replayer.executes_at_once.set(false);+ replayer.wait_succeeds.set(false);++ for _ in 0..7 {+ record_viewport(&recorder);+ }+ record_borrowed_buffer_sub_data(&replayer, &recorder, 1024 * capacity, &[5; 16], || {});+ assert!(recorder.is_lost());+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(0, vec![record_of(&VIEWPORT); 7], 1),+ Call::WaitUntilPublishedCommandsExecuted+ ]+ );+ recorder.flush_commands();+ assert_eq!(replayer.take_calls(), []);+}++#[test]+fn a_flush_that_is_due_for_a_record_that_got_its_room_late_is_made() {+ let replayer = MockReplayer::new();+ let viewport_count = 129;+ let recorder = replayer.recorder(MAX_PENDING_COMMAND_BYTES + (viewport_count - 1) * VIEWPORT_RECORD_SIZE);+ replayer.take_calls();++ for _ in 0..viewport_count {+ record_viewport(&recorder);+ }+ let data = vec![5u8; MAX_PENDING_COMMAND_BYTES];+ record_borrowed_buffer_sub_data(&replayer, &recorder, 0, &data, || {+ assert_eq!(replayer.take_calls(), []);+ });+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(0, vec![record_of(&VIEWPORT); viewport_count], 1),+ sent_from_shared_buffer(0, vec![buffer_sub_data_record(&data)], 2),+ ]+ );+}++#[test]+fn without_a_shared_buffer_borrowed_data_of_any_size_is_recorded_in_order() {+ let replayer = MockReplayer::new();+ replayer.refuses_shared_memory.set(true);+ let recorder = replayer.recorder(SMALL_CAPACITY);++ record_viewport(&recorder);+ let data = [5u8; 16];+ record_borrowed_buffer_sub_data(&replayer, &recorder, 1024 * SMALL_CAPACITY, &data, || {});+ record_borrowed_buffer_sub_data(&replayer, &recorder, 0, &data, || {});+ record_viewport(&recorder);+ assert_eq!(replayer.take_calls(), []);+ recorder.flush_commands();+ assert_eq!(+ replayer.take_calls(),+ [Call::SendCommands {+ records: vec![+ record_of(&VIEWPORT),+ buffer_sub_data_record(&data),+ buffer_sub_data_record(&data),+ record_of(&VIEWPORT)+ ],+ frames: Vec::new()+ }]+ );++ // A flush that is due once the record is made waits for the data to be given back.+ record_viewport(&recorder);+ let data = vec![5u8; MAX_PENDING_COMMAND_BYTES];+ record_borrowed_buffer_sub_data(&replayer, &recorder, 0, &data, || {+ assert_eq!(replayer.take_calls(), []);+ });+ assert_eq!(+ replayer.take_calls(),+ [Call::SendCommands {+ records: vec![record_of(&VIEWPORT), buffer_sub_data_record(&data)],+ frames: Vec::new()+ }]+ );+}++#[test]+fn what_is_read_back_goes_through_memory_shared_for_the_read() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();+ replayer.read_data.replace(vec![1, 2, 3, 4, 5, 6, 7, 8]);++ record_viewport(&recorder);+ let mut read = Vec::new();+ assert!(recorder.read_buffer_sub_data(GL_ARRAY_BUFFER, 12, 6, |data| read.extend_from_slice(data)));+ assert_eq!(read, [1, 2, 3, 4, 5, 6]);+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(0, vec![record_of(&VIEWPORT)], 1),+ Call::ReadBufferSubData {+ target: GL_ARRAY_BUFFER,+ offset: 12,+ size: 6+ },+ ]+ );+ assert!(recorder.read_buffer_sub_data(GL_ARRAY_BUFFER, 12, 0, |_| panic!("nothing to read")));+ assert_eq!(replayer.take_calls(), []);+ replayer.read_buffer_sub_data_succeeds.set(false);+ assert!(!recorder.read_buffer_sub_data(GL_ARRAY_BUFFER, 12, 6, |_| panic!("the replayer refused")));++ replayer.read_pixels_result.set(ReadPixelsResult {+ length: 4,+ columns: 1,+ rows: 1,+ });+ let mut read = Vec::new();+ recorder.read_pixels_robust_angle(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 8, |result, pixels| {+ assert_eq!(+ result,+ ReadPixelsResult {+ length: 4,+ columns: 1,+ rows: 1+ }+ );+ read.extend_from_slice(pixels);+ });+ assert_eq!(read, [1, 2, 3, 4]);+ let mut was_called = false;+ recorder.read_pixels_robust_angle(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 0, |_, pixels| {+ was_called = pixels.is_empty();+ });+ assert!(was_called);+ assert_eq!(+ replayer.take_calls().last(),+ Some(&Call::ReadPixels {+ buf_size: 0,+ has_pixels: false+ })+ );++ replayer.refuses_shared_memory.set(true);+ assert!(!recorder.read_buffer_sub_data(GL_ARRAY_BUFFER, 12, 6, |_| panic!("no memory to read into")));+ recorder.read_pixels_robust_angle(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 8, |_, _| panic!("no memory"));+ assert_eq!(replayer.take_calls(), []);+ assert_eq!(recorder.take_pending_local_error(), GL_OUT_OF_MEMORY);+ assert_eq!(recorder.take_pending_local_error(), 0);+}++#[test]+fn the_drawing_buffer_is_presented_after_what_was_recorded() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY);+ replayer.take_calls();++ recorder.set_size(300, 150);+ recorder.present_canvas_for_compositing(true);+ recorder.clear_drawing_buffer();+ assert_eq!(recorder.read_back_drawing_buffer(1, 2, 3, 4), Some((1, 2, 3, 4)));+ assert_eq!(recorder.canvas_id(), Some(42));+ assert_eq!(+ replayer.take_calls(),+ [+ sent_from_shared_buffer(+ 0,+ vec![record_of(&commands::SetDrawingBufferSize {+ width: 300,+ height: 150+ })],+ 1+ ),+ Call::PresentCanvas {+ preserve_drawing_buffer: true+ },+ Call::ClearDrawingBuffer,+ Call::ReadBackDrawingBuffer,+ ]+ );++ drop(recorder);+ assert_eq!(replayer.take_calls(), [Call::DestroyContext]);+}++#[test]+fn a_call_of_the_transport_can_mark_the_context_lost() {+ let replayer = MockReplayer::new();+ let recorder = Rc::new(replayer.recorder(2 * VIEWPORT_RECORD_SIZE));+ replayer.take_calls();+ let transport_loses_the_context = |loses: bool| {+ replayer+ .recorder_to_lose+ .replace(if loses { Rc::downgrade(&recorder) } else { Weak::new() });+ };+ let restore = || {+ transport_loses_the_context(false);+ recorder.restore(MockTransport {+ replayer: Rc::clone(&replayer),+ });+ assert!(!recorder.is_lost());+ replayer.take_calls();+ transport_loses_the_context(true);+ };++ // While a flush publishes.+ restore();+ record_viewport(&recorder);+ recorder.flush_commands();+ assert!(recorder.is_lost());++ // While the region is drained for a record, which is then not written.+ restore();+ transport_loses_the_context(false);+ replayer.executes_at_once.set(false);+ record_viewport(&recorder);+ record_viewport(&recorder);+ recorder.flush_commands();+ transport_loses_the_context(true);+ record_viewport(&recorder);+ assert!(recorder.is_lost());+ replayer.executes_at_once.set(true);++ // While a call waits for its reply, which is then not read.+ restore();+ replayer.queue_reply(+ &sync_calls::GetErrorReply {+ return_value: GL_INVALID_ENUM,+ },+ &[],+ );+ assert_eq!(recorder.get_error(), 0);+ assert!(recorder.is_lost());++ // While something is read back, which is then not handed out.+ restore();+ assert!(!recorder.read_buffer_sub_data(GL_ARRAY_BUFFER, 0, 4, |_| panic!("the context is lost")));+ restore();+ recorder.read_pixels_robust_angle(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 4, |_, _| {+ panic!("the context is lost")+ });+ assert!(recorder.is_lost());++ // While a record that is too large for the region is sent, and while the canvas is presented.+ restore();+ recorder.buffer_sub_data(GL_ARRAY_BUFFER, 0, 128, &[5; 128]);+ assert!(recorder.is_lost());+ restore();+ recorder.present_canvas_for_compositing(false);+ assert!(recorder.is_lost());++ // While the new shared command buffer of a restored context is announced.+ transport_loses_the_context(true);+ recorder.restore(MockTransport {+ replayer: Rc::clone(&replayer),+ });+ assert!(recorder.is_lost());+ transport_loses_the_context(false);+}++#[test]+fn a_restored_context_starts_over_with_its_new_transport() {+ let old_replayer = MockReplayer::new();+ let recorder = old_replayer.recorder(SMALL_CAPACITY);+ assert_eq!(recorder.create_program(), 1);+ upload_frame(&recorder, 70);+ recorder.flush_commands();+ record_viewport(&recorder);+ upload_frame(&recorder, 80);+ recorder.set_lost();+ old_replayer.take_calls();++ let new_replayer = MockReplayer::new();+ recorder.restore(MockTransport {+ replayer: Rc::clone(&new_replayer),+ });+ assert!(!recorder.is_lost());+ assert_eq!(old_replayer.take_calls(), []);+ assert_eq!(+ new_replayer.take_calls(),+ [Call::SetSharedCommandBuffer {+ size: SHARED_DATA_REGION_OFFSET + SMALL_CAPACITY+ }]+ );++ // NB: What the lost context did not publish is gone, and so is the frame that it named.+ assert_eq!(recorder.create_program(), 2);+ recorder.flush_commands();+ let created_program = record_of(&commands::CreateProgram { id: 2 });+ assert_eq!(+ new_replayer.take_calls(),+ [sent_from_shared_buffer(0, vec![created_program], 1)]+ );+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/transport.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/transport.rsnew file mode 100644index 00000000000..3b51a137b68--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/transport.rs@@ -0,0 +1,71 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++/// Zeroed when it is created.+pub(crate) trait SharedMemory {+ /// Aligned for a `u64`, and stays where it is for as long as the value lives.+ fn as_ptr(&self) -> *mut u8;+ fn len(&self) -> usize;+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[repr(C)]+pub(crate) struct ReadPixelsResult {+ pub(crate) length: i32,+ pub(crate) columns: i32,+ pub(crate) rows: i32,+}++/// A call can find the replayer gone. The host then marks every context lost before the call returns, the one that+/// made the call included. That is all a call does to the recorder that made it: it neither records, nor flushes,+/// nor runs script.+pub(crate) trait Transport {+ type SharedMemory: SharedMemory;+ /// An image that a command names by its position among the frames sent with the commands.+ type Frame;+ type Bitmap;++ fn max_frames_per_message(&self) -> usize;+ fn create_shared_memory(&self, size: usize) -> Option<Self::SharedMemory>;++ fn canvas_id(&self) -> Option<u64>;+ fn destroy_context(&self);++ /// Makes the memory the shared command buffer of the context: a `u64` that the replayer stores the sequence+ /// number of the last flush that it executed in, and a region of records.+ fn set_shared_command_buffer(&self, buffer: &Self::SharedMemory);+ /// `offset` is into the region of records.+ fn send_commands_from_shared_buffer(+ &self,+ offset: u64,+ size_in_bytes: u64,+ flush_sequence_number: u64,+ frames: &[Self::Frame],+ );+ /// Returns once the replayer has executed everything published, or false if it never will.+ fn wait_until_published_commands_executed(&self) -> bool;+ fn send_commands(&self, commands: &[u8], frames: &[Self::Frame]);++ fn present_canvas(&self, preserve_drawing_buffer: bool);+ fn clear_drawing_buffer(&self);++ /// A call that failed appends nothing to `reply`.+ fn sync_call(&self, request: &[u8], reply: &mut Vec<u8>);+ #[expect(clippy::too_many_arguments, reason = "the arguments of the GL function")]+ fn read_pixels_robust_angle(+ &self,+ x: i32,+ y: i32,+ width: i32,+ height: i32,+ format: u32,+ r#type: u32,+ buf_size: i32,+ pixels: Option<&Self::SharedMemory>,+ ) -> ReadPixelsResult;+ fn read_buffer_sub_data(&self, target: u32, offset: i64, size: i64, data: &Self::SharedMemory) -> bool;+ fn read_back_drawing_buffer(&self, x: i32, y: i32, width: i32, height: i32) -> Option<Self::Bitmap>;+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/wire.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/wire.rsindex 264aad52d4a..03a17b4c230 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/wire.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/wire.rs@@ -20,9 +20,9 @@ pub(crate) const RECORD_ALIGNMENT: usize = 16;/// What precedes the struct of a record and of a request: its type as a `u16`, two unused bytes, and the number of/// bytes that follow the header as a `u32`.pub(crate) const HEADER_SIZE: usize = 8;+pub(crate) const HEADER_PAYLOAD_SIZE_OFFSET: usize = 4;-/// The data that a field of a struct stands for: `size` bytes that start `offset` bytes after the start of the-/// struct.+/// `size` bytes that start `offset` bytes after the start of the struct that has the span as a field.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]#[repr(C)]pub(crate) struct DataSpan {@@ -33,29 +33,28 @@ pub(crate) struct DataSpan {impl DataSpan {pub(crate) const EMPTY: Self = Self { offset: 0, size: 0 };- /// The span of the data that follows a struct `S`.pub(crate) fn following<S: WireStruct>(data: InlineData<'_>) -> Self {Self {- offset: wire_u32(size_of::<S>().next_multiple_of(RECORD_ALIGNMENT)),- size: wire_u32(data.len()),+ offset: const { offset_of_data_following_struct(size_of::<S>()) },+ // NB: Data of 4 GiB or more has no span. It has no `FramedSize` either, so the recorder refuses what it+ // would be sent in, and the size that stands in for the real one here is never sent.+ size: u32::try_from(data.len()).unwrap_or(u32::MAX),}}}-/// A size or an offset as the stream carries it. The stream cannot carry a record of 4 GiB, which is far more than a-/// buffer that script can allocate holds.-fn wire_u32(size: usize) -> u32 {- u32::try_from(size).expect("a WebGL command and its data are smaller than 4 GiB")+const fn offset_of_data_following_struct(struct_size: usize) -> u32 {+ let offset = struct_size.next_multiple_of(RECORD_ALIGNMENT);+ assert!(offset <= u32::MAX as usize);+ offset as u32}-/// A struct that crosses the command stream as its bytes.-////// # Safety////// The type is `repr(C)`, made of numbers, booleans and [`DataSpan`]s, and has no byte that is not part of a field.pub(crate) unsafe trait WireStruct: Copy + 'static {- /// The struct with every field zero. A struct is built from it, so that the bytes that the C ABI leaves unused- /// between its fields, which are fields of their own here, do not have to be named.+ /// A struct is built from it, so that the bytes that the C ABI leaves unused between its fields, which are fields+ /// of their own here, do not have to be named.const ZEROED: Self;fn as_bytes(&self) -> &[u8] {@@ -121,41 +120,71 @@ impl InlineData<'_> {}}-/// The number of bytes that a struct and its data take together.-fn payload_layout_size(struct_size: usize, inline_data: InlineData<'_>) -> usize {- match inline_data.len() {- 0 => struct_size,- inline_data_size => struct_size.next_multiple_of(RECORD_ALIGNMENT) + inline_data_size,+fn payload_layout_size(struct_size: usize, inline_data_size: usize) -> Option<usize> {+ match inline_data_size {+ 0 => Some(struct_size),+ inline_data_size => struct_size+ .checked_next_multiple_of(RECORD_ALIGNMENT)?+ .checked_add(inline_data_size),+ }+}++/// There is none for a struct with 4 GiB of data or more, as the header says in a `u32` how many bytes follow it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct FramedSize {+ size_with_header: usize,+ size_after_header: u32,+}++impl FramedSize {+ fn with_size_after_header(size_after_header: usize) -> Option<Self> {+ Some(Self {+ size_with_header: HEADER_SIZE.checked_add(size_after_header)?,+ size_after_header: u32::try_from(size_after_header).ok()?,+ })+ }++ /// A record is padded to the alignment of records as a whole.+ fn of_record(struct_size: usize, inline_data_size: usize) -> Option<Self> {+ let size_with_header = HEADER_SIZE+ .checked_add(payload_layout_size(struct_size, inline_data_size)?)?+ .checked_next_multiple_of(RECORD_ALIGNMENT)?;+ Self::with_size_after_header(size_with_header - HEADER_SIZE)+ }++ /// What follows the header of a request is padded to the alignment of records.+ fn of_sync_request(struct_size: usize, inline_data_size: usize) -> Option<Self> {+ let size_after_header =+ payload_layout_size(struct_size, inline_data_size)?.checked_next_multiple_of(RECORD_ALIGNMENT)?;+ Self::with_size_after_header(size_after_header)}}-/// The number of bytes that a record takes in the command stream.-pub(crate) fn padded_record_size(struct_size: usize, inline_data: InlineData<'_>) -> usize {- (HEADER_SIZE + payload_layout_size(struct_size, inline_data)).next_multiple_of(RECORD_ALIGNMENT)+pub(crate) fn padded_record_size(struct_size: usize, inline_data_size: usize) -> Option<usize> {+ FramedSize::of_record(struct_size, inline_data_size).map(|size| size.size_with_header)}-/// Writes a header, a struct and its data, and zeroes what is left of `size` bytes, so that no byte of the stream is-/// one that happened to be in memory.+/// Writes a header, a struct and its data, and zeroes what is left of the size, so that no byte of the stream is one+/// that happened to be in memory.////// # Safety///-/// `destination` is valid for writes of `size` bytes, which are at least as many as the header, the struct and the-/// data take, and which overlap neither the struct nor the data.+/// `size` is that of the struct with the data, and `destination` is valid for writes of as many bytes, which overlap+/// neither the struct nor the data.unsafe fn write_framed(destination: *mut u8,- size: usize,+ size: FramedSize,type_number: u16,payload: &[u8],inline_data: InlineData<'_>,) {- let payload_size = wire_u32(size - HEADER_SIZE);let mut header = [0; HEADER_SIZE];header[..2].copy_from_slice(&type_number.to_ne_bytes());- header[4..].copy_from_slice(&payload_size.to_ne_bytes());+ header[HEADER_PAYLOAD_SIZE_OFFSET..].copy_from_slice(&size.size_after_header.to_ne_bytes());let mut written = HEADER_SIZE + payload.len();- // SAFETY: The caller provides `size` bytes, and every write below stays inside the layout that- // payload_layout_size() computes, which `size` covers.+ // SAFETY: The caller provides the bytes of the size, and every write below stays inside the layout that+ // payload_layout_size() computes, which the size covers.unsafe {ptr::copy_nonoverlapping(header.as_ptr(), destination, HEADER_SIZE);ptr::copy_nonoverlapping(payload.as_ptr(), destination.add(HEADER_SIZE), payload.len());@@ -165,70 +194,87 @@ unsafe fn write_framed(inline_data.write_to(destination.add(inline_data_offset));written = inline_data_offset + inline_data.len();}- ptr::write_bytes(destination.add(written), 0, size - written);+ ptr::write_bytes(destination.add(written), 0, size.size_with_header - written);}}-/// Writes a record of the command stream.-///-/// # Safety-///-/// `destination` is valid for writes of `padded_record_size(payload.len(), inline_data)` bytes that overlap neither-/// the payload nor the data.-pub(crate) unsafe fn write_record(- destination: *mut u8,+pub(crate) struct Record<'a> {command_type: CommandType,- payload: &[u8],- inline_data: InlineData<'_>,-) {- let record_size = padded_record_size(payload.len(), inline_data);- // SAFETY: The caller provides the bytes of the record.- unsafe { write_framed(destination, record_size, command_type as u16, payload, inline_data) };+ payload: &'a [u8],+ inline_data: InlineData<'a>,+ size: FramedSize,}-/// Appends a record to commands that are kept outside the shared command buffer.-pub(crate) fn append_record(- commands: &mut Vec<u8>,- command_type: CommandType,- payload: &[u8],- inline_data: InlineData<'_>,-) {- let record_offset = commands.len();- assert!(record_offset.is_multiple_of(RECORD_ALIGNMENT));- commands.resize(record_offset + padded_record_size(payload.len(), inline_data), 0);- // SAFETY: The vector was just grown by the size of the record, and it owns its bytes.- unsafe {- write_record(- commands.as_mut_ptr().add(record_offset),+impl<'a> Record<'a> {+ pub(crate) fn new(command_type: CommandType, payload: &'a [u8], inline_data: InlineData<'a>) -> Option<Self> {+ Some(Self {command_type,payload,inline_data,- );+ size: FramedSize::of_record(payload.len(), inline_data.len())?,+ })+ }++ pub(crate) fn size(&self) -> usize {+ self.size.size_with_header+ }++ /// # Safety+ ///+ /// `destination` is valid for writes of `self.size()` bytes that overlap neither the struct nor the data.+ pub(crate) unsafe fn write_to(&self, destination: *mut u8) {+ // SAFETY: The caller provides the bytes of the record, whose size is that of the struct with the data.+ unsafe {+ write_framed(+ destination,+ self.size,+ self.command_type as u16,+ self.payload,+ self.inline_data,+ );+ }+ }++ pub(crate) fn append_to(&self, commands: &mut Vec<u8>) {+ let record_offset = commands.len();+ assert!(record_offset.is_multiple_of(RECORD_ALIGNMENT));+ commands.resize(record_offset + self.size(), 0);+ // SAFETY: The vector was just grown by the size of the record, and it owns its bytes.+ unsafe { self.write_to(commands.as_mut_ptr().add(record_offset)) };+ }++ pub(crate) fn encoded(&self) -> Vec<u8> {+ let mut bytes = Vec::new();+ self.append_to(&mut bytes);+ bytes}}-/// Replaces the contents of `request_bytes` with the request of a synchronous call.+/// False, with no request in `request_bytes`, when the stream cannot carry the request.+#[must_use]pub(crate) fn encode_sync_request<R: SyncRequest>(request_bytes: &mut Vec<u8>,request: &R,inline_data: InlineData<'_>,-) {- let payload_size = payload_layout_size(size_of::<R>(), inline_data).next_multiple_of(RECORD_ALIGNMENT);+) -> bool {request_bytes.clear();- request_bytes.resize(HEADER_SIZE + payload_size, 0);- // SAFETY: The vector has the size of the header and the padded payload, and it owns its bytes.+ let Some(size) = FramedSize::of_sync_request(size_of::<R>(), inline_data.len()) else {+ return false;+ };+ request_bytes.resize(size.size_with_header, 0);+ // SAFETY: The vector has the size of the request, and it owns its bytes.unsafe {write_framed(request_bytes.as_mut_ptr(),- request_bytes.len(),+ size,R::TYPE as u16,request.as_bytes(),inline_data,);}+ true}-/// The data that a span of the struct of a reply stands for.pub(crate) fn resolve_data_span(reply: &[u8], span: DataSpan) -> &[u8] {let start = span.offset as usize;start@@ -243,10 +289,15 @@ mod tests {use super::*;fn record(command_type: CommandType, payload: &[u8], inline_data: InlineData<'_>) -> Vec<u8> {+ let record = Record::new(command_type, payload, inline_data).unwrap();+ assert_eq!(+ Some(record.size()),+ padded_record_size(payload.len(), inline_data.len())+ );// NB: The bytes that a record is written over are not zero, as those of a reused buffer are not.- let mut bytes = vec![0xAA; padded_record_size(payload.len(), inline_data)];+ let mut bytes = vec![0xAA; record.size()];// SAFETY: The vector has the size of the record.- unsafe { write_record(bytes.as_mut_ptr(), command_type, payload, inline_data) };+ unsafe { record.write_to(bytes.as_mut_ptr()) };bytes}@@ -343,13 +394,12 @@ mod tests {width: 3,height: 4,};- append_record(&mut commands, CommandType::Enable, enable.as_bytes(), InlineData::NONE);- append_record(- &mut commands,- CommandType::Viewport,- viewport.as_bytes(),- InlineData::NONE,- );+ Record::new(CommandType::Enable, enable.as_bytes(), InlineData::NONE)+ .unwrap()+ .append_to(&mut commands);+ Record::new(CommandType::Viewport, viewport.as_bytes(), InlineData::NONE)+ .unwrap()+ .append_to(&mut commands);assert_eq!(commands.len(), 16 + 32);assert_eq!(commands[..8], header(CommandType::Enable as u16, 8));assert_eq!(commands[16..24], header(CommandType::Viewport as u16, 24));@@ -360,11 +410,11 @@ mod tests {// NB: The replayer rejects a request whose payload is shorter than its struct, and the struct of a request// without arguments is one byte in C++.let mut request_bytes = vec![0xAA; 64];- encode_sync_request(+ assert!(encode_sync_request(&mut request_bytes,&sync_calls::GetErrorRequest::ZEROED,InlineData::NONE,- );+ ));assert_eq!(request_bytes.len(), 24);assert_eq!(request_bytes[..8], header(SyncCallType::GetError as u16, 16));assert_eq!(request_bytes[8..], [0; 16]);@@ -374,7 +424,7 @@ mod tests {program: 3,name: DataSpan::following::<sync_calls::GetAttribLocationRequest>(name),};- encode_sync_request(&mut request_bytes, &request, name);+ assert!(encode_sync_request(&mut request_bytes, &request, name));assert_eq!(request_bytes.len(), 8 + 32);assert_eq!(request_bytes[..8], header(SyncCallType::GetAttribLocation as u16, 32));assert_eq!(request_bytes[8..20], *request.as_bytes());@@ -382,6 +432,41 @@ mod tests {assert_eq!(request_bytes[30..], [0; 10]);}+ #[test]+ fn the_stream_carries_what_its_header_can_count() {+ const FOUR_GIB: usize = 1 << 32;++ // The largest record: 8 bytes of header, 16 of struct, and data up to the last multiple of the alignment+ // that leaves what follows the header countable.+ let largest_data_size = FOUR_GIB - 8 - 16;+ assert_eq!(padded_record_size(16, largest_data_size), Some(FOUR_GIB));+ assert_eq!(+ FramedSize::of_record(16, largest_data_size),+ Some(FramedSize {+ size_with_header: FOUR_GIB,+ size_after_header: u32::MAX - 7+ })+ );+ assert_eq!(padded_record_size(16, largest_data_size + 1), None);+ assert_eq!(padded_record_size(16, FOUR_GIB), None);+ assert_eq!(padded_record_size(16, usize::MAX), None);+ assert_eq!(padded_record_size(16, usize::MAX - 16), None);+ assert_eq!(padded_record_size(usize::MAX, 0), None);+ assert_eq!(padded_record_size(usize::MAX, 1), None);++ // The largest request: what follows its header is padded on its own.+ assert_eq!(+ FramedSize::of_sync_request(16, FOUR_GIB - 16 - 16),+ Some(FramedSize {+ size_with_header: FOUR_GIB - 8,+ size_after_header: u32::MAX - 15+ })+ );+ assert_eq!(FramedSize::of_sync_request(16, FOUR_GIB - 16 - 15), None);+ assert_eq!(FramedSize::of_sync_request(16, usize::MAX), None);+ assert_eq!(FramedSize::of_sync_request(1, 0).unwrap().size_with_header, 8 + 16);+ }+#[test]fn a_reply_starts_with_its_struct() {let mut reply = Vec::new();diff --git a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cppindex f26e1c2f361..61a808cbddd 100644--- a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp+++ b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp@@ -7,10 +7,13 @@#include <AK/ByteBuffer.h>#include <AK/Vector.h>#include <AK/kmalloc.h>+#include <LibCompositing/WebGL/WebGLCommandList.h>+#include <LibCompositing/WebGL/WebGLSharedCommandBuffer.h>#include <LibCore/AnonymousBuffer.h>#include <LibGfx/Bitmap.h>#include <LibGfx/DecodedImageFrame.h>#include <LibGfx/ShareableBitmap.h>+#include <LibIPC/Limits.h>#include <LibWeb/WebGL/RemoteWebGLTransport.h>// The C ABI of RemoteWebGLTransport, for the WebGL command recorder in Libraries/LibWeb/Bindings/Rust/src/web_gl,@@ -21,9 +24,35 @@namespace Web::WebGL {+// NB: `ReadPixelsResult` of proxy/transport.rs is three `i32`s in this order.static_assert(sizeof(ReadPixelsResult) == 3 * sizeof(i32));+static_assert(offsetof(ReadPixelsResult, length) == 0);+static_assert(offsetof(ReadPixelsResult, columns) == sizeof(i32));+static_assert(offsetof(ReadPixelsResult, rows) == 2 * sizeof(i32));static_assert(sizeof(Compositing::CanvasId) == sizeof(u64));+// What the recorder and the replayer of the command stream have to agree on besides the command structs. The+// recorder has constants of its own for these, and compares them with this before it records (fingerprint.rs).+struct ConstantsRestatedInRust {+ size_t record_alignment { 0 };+ size_t header_size { 0 };+ size_t header_payload_size_offset { 0 };+ size_t shared_data_region_offset { 0 };+ size_t shared_data_region_capacity { 0 };+};++// NB: The recorder writes the header of a command and that of a synchronous call the same way.+static_assert(sizeof(Compositing::WebGL::WebGLSyncCallHeader) == sizeof(Compositing::WebGL::WebGLCommandHeader));+static_assert(offsetof(Compositing::WebGL::WebGLSyncCallHeader, payload_size) == offsetof(Compositing::WebGL::WebGLCommandHeader, payload_size));+static_assert(offsetof(Compositing::WebGL::WebGLSyncCallHeader, type) == 0 && offsetof(Compositing::WebGL::WebGLCommandHeader, type) == 0);+static_assert(sizeof(Compositing::WebGL::WebGLSyncCallType) == sizeof(u16) && sizeof(Compositing::WebGL::WebGLCommandType) == sizeof(u16));+static_assert(sizeof(Compositing::WebGL::WebGLCommandHeader::payload_size) == sizeof(u32));++// NB: `DataSpan` of proxy/wire.rs is two `u32`s in this order.+static_assert(sizeof(Compositing::WebGL::WebGLDataSpan) == 2 * sizeof(u32));+static_assert(offsetof(Compositing::WebGL::WebGLDataSpan, offset) == 0);+static_assert(offsetof(Compositing::WebGL::WebGLDataSpan, size) == sizeof(u32));+extern "C" {void web_webgl_transport_unref(void* transport);@@ -39,6 +68,8 @@ void web_webgl_transport_sync_call(void* transport, u8 const* request, size_t revoid web_webgl_transport_read_pixels_robust_angle(void* transport, i32 x, i32 y, i32 width, i32 height, u32 format, u32 type, i32 buf_size, void const* pixels_anonymous_buffer_or_null, ReadPixelsResult* out_result);bool web_webgl_transport_read_buffer_sub_data(void* transport, u32 target, i64 offset, i64 size, void const* data_anonymous_buffer);void* web_webgl_transport_read_back_drawing_buffer(void* transport, i32 x, i32 y, i32 width, i32 height);+size_t web_webgl_max_frames_per_message();+void web_webgl_constants_restated_in_rust(ConstantsRestatedInRust* out_constants);void* web_webgl_anonymous_buffer_create(size_t size, u8** out_data);void web_webgl_anonymous_buffer_destroy(void* anonymous_buffer);void web_webgl_frame_destroy(void* frame);@@ -148,6 +179,24 @@ void* web_webgl_transport_read_back_drawing_buffer(void* transport, i32 x, i32 yreturn &NonnullRefPtr<Gfx::Bitmap> { *shareable_bitmap.bitmap() }.leak_ref();}+size_t web_webgl_max_frames_per_message()+{+ // NB: The bytes of the commands take one of the attachments of a message.+ static_assert(IPC::MAX_MESSAGE_FD_COUNT > 1);+ return IPC::MAX_MESSAGE_FD_COUNT - 1;+}++void web_webgl_constants_restated_in_rust(ConstantsRestatedInRust* out_constants)+{+ *out_constants = {+ .record_alignment = Compositing::WebGL::WebGLCommandList::command_alignment,+ .header_size = sizeof(Compositing::WebGL::WebGLCommandHeader),+ .header_payload_size_offset = offsetof(Compositing::WebGL::WebGLCommandHeader, payload_size),+ .shared_data_region_offset = Compositing::WebGL::WebGLSharedCommandBuffer::data_region_offset,+ .shared_data_region_capacity = Compositing::WebGL::WebGLSharedCommandBuffer::default_data_region_capacity,+ };+}+void* web_webgl_anonymous_buffer_create(size_t size, u8** out_data){auto buffer_or_error = Core::AnonymousBuffer::create_with_size(size);