Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
//! Writes the replaying side of the WebGL command stream from GLFunctions.json: the table of the GL functions that
//! the Compositor calls, which src/webgl/gl.rs includes, and a method of the replayer for every command and every
//! synchronous call that follows from the signature of its GL function, which src/webgl/generated.rs includes.
use std::fmt::Write;
use crate::webgl_wire_model::{
Argument, Category, DefaultObject, Function, PayloadFactor, WireType, rust_identifier, title_case_to_snake_case,
wire_struct,
};
fn unsupported(function: &Function, what: &str) -> String {
format!("the replayer cannot replay {}: {what}", function.name)
}
/// The Rust type of a GL type in the signature of a GL function.
fn gl_rust_type(cpp_type: &str) -> Option<&'static str> {
Some(match cpp_type {
"void" => "()",
"GLenum" | "GLuint" | "GLbitfield" => "u32",
"GLint" | "GLsizei" => "i32",
"GLfloat" => "f32",
"GLboolean" => "u8",
"GLintptr" | "GLsizeiptr" => "isize",
"GLuint64" => "u64",
"GLint64" => "i64",
"GLsync" | "void*" => "*mut c_void",
"void const*" => "*const c_void",
"void**" => "*mut *mut c_void",
"GLubyte const*" => "*const u8",
"GLchar const*" => "*const c_char",
"GLchar*" => "*mut c_char",
"GLchar const* const*" => "*const *const c_char",
"GLfloat const*" => "*const f32",
"GLfloat*" => "*mut f32",
"GLint const*" => "*const i32",
"GLint*" | "GLsizei*" => "*mut i32",
"GLuint const*" | "GLenum const*" => "*const u32",
"GLuint*" | "GLenum*" => "*mut u32",
"GLboolean*" => "*mut u8",
"GLint64*" => "*mut i64",
_ => return None,
})
}
fn field_name(argument: &Argument) -> String {
rust_identifier(&title_case_to_snake_case(&argument.name))
}
/// A scalar argument as GL takes it, from the field of the struct that carries it.
fn scalar_argument(argument: &Argument, holder: &str) -> String {
let field = field_name(argument);
if matches!(argument.cpp_type.as_str(), "GLintptr" | "GLsizeiptr") {
format!("{holder}.{field} as isize")
} else {
format!("{holder}.{field}")
}
}
fn has_gl_signature(function: &Function) -> bool {
function.category != Category::BuiltinCommand
}
fn parameter_types(function: &Function) -> Result<Vec<&'static str>, String> {
function
.arguments
.iter()
.map(|argument| {
gl_rust_type(&argument.cpp_type).ok_or_else(|| {
unsupported(
function,
&format!("{} has the type {}", argument.name, argument.cpp_type),
)
})
})
.collect()
}
fn return_type(function: &Function) -> Result<&'static str, String> {
let cpp_type = function.return_type.as_deref().unwrap_or("void");
gl_rust_type(cpp_type).ok_or_else(|| unsupported(function, &format!("it returns {cpp_type}")))
}
fn function_pointer_type(function: &Function) -> Result<String, String> {
let parameters = parameter_types(function)?.join(", ");
let return_type = return_type(function)?;
Ok(if return_type == "()" {
format!("unsafe extern \"system\" fn({parameters})")
} else {
format!("unsafe extern \"system\" fn({parameters}) -> {return_type}")
})
}
fn zero_of(rust_type: &str) -> &'static str {
match rust_type {
"()" => "()",
"f32" => "0.0",
"c_char" | "u8" | "u32" | "i32" | "isize" | "u64" | "i64" => "0",
_ if rust_type.starts_with("*mut") => "core::ptr::null_mut()",
_ => "core::ptr::null()",
}
}
/// The table of GL functions, with a loader, and the functions that the tests of the crate replay against, which
/// record what is called.
pub fn write_gl_functions(functions: &[Function]) -> Result<String, String> {
let functions: Vec<&Function> = functions.iter().filter(|function| has_gl_signature(function)).collect();
let mut out = String::from("// Generated by build.rs from Libraries/LibCompositing/WebGL/GLFunctions.json.\n\n");
out.push_str("use core::ffi::{CStr, c_char, c_void};\n\n");
out.push_str("/// The GL functions that the replayer calls.\npub struct GlFunctions {\n");
for function in &functions {
writeln!(
out,
" pub {}: {},",
function.method_name(),
function_pointer_type(function)?
)
.unwrap();
}
out.push_str("}\n\n");
out.push_str(
"impl GlFunctions {\n /// Answers the name of a function that `get_proc_address` does not know.\n ///\n /// # Safety\n ///\n /// `get_proc_address` answers the address of the GL function of a name, or null.\n pub unsafe fn load(mut get_proc_address: impl FnMut(&CStr) -> *const c_void) -> Result<Self, &'static CStr> {\n // SAFETY: Each field has the type of the function of its name.\n unsafe {\n Ok(Self {\n",
);
for function in &functions {
writeln!(
out,
" {}: load_function(&mut get_proc_address, c\"{}\")?,",
function.method_name(),
function.name
)
.unwrap();
}
out.push_str(" })\n }\n }\n}\n\n");
out.push_str(
"/// # Safety\n///\n/// `F` is the type of a pointer to the GL function of the name.\nunsafe fn load_function<F: Copy>(\n get_proc_address: &mut impl FnMut(&CStr) -> *const c_void,\n name: &'static CStr,\n) -> Result<F, &'static CStr> {\n const { assert!(size_of::<F>() == size_of::<*const c_void>()) };\n let address = get_proc_address(name);\n if address.is_null() {\n return Err(name);\n }\n // SAFETY: The address is that of the function, whose type the caller names.\n Ok(unsafe { core::mem::transmute_copy::<*const c_void, F>(&address) })\n}\n\n",
);
out.push_str("#[cfg(test)]\n#[allow(clippy::too_many_arguments)]\npub mod recording {\n");
out.push_str(" use super::*;\n\n");
out.push_str(" fn pointer_text<T>(pointer: *const T) -> &'static str {\n if pointer.is_null() { \"null\" } else { \"ptr\" }\n }\n\n");
for function in &functions {
let types = parameter_types(function)?;
let return_type = return_type(function)?;
let parameters: Vec<String> = function
.arguments
.iter()
.zip(&types)
.map(|(argument, rust_type)| format!("{}: {rust_type}", field_name(argument)))
.collect();
let arguments: Vec<String> = function
.arguments
.iter()
.zip(&types)
.map(|(argument, rust_type)| {
let name = field_name(argument);
if rust_type.starts_with("*mut") {
format!("pointer_text({name}.cast_const())")
} else if rust_type.starts_with('*') {
format!("pointer_text({name})")
} else {
format!("&{name}")
}
})
.collect();
let format_string = vec!["{:?}"; arguments.len()].join(", ");
let signature_return = if return_type == "()" {
String::new()
} else {
format!(" -> {return_type}")
};
writeln!(
out,
" pub unsafe extern \"system\" fn {}({}){signature_return} {{",
function.method_name(),
parameters.join(", ")
)
.unwrap();
writeln!(
out,
" crate::webgl::testing::record(format!(\"{}({format_string})\"{}));",
function.name,
arguments
.iter()
.map(|argument| format!(", {argument}"))
.collect::<String>()
)
.unwrap();
let is_gen = function.category == Category::Gen;
if is_gen && function.returns_void() {
let count = field_name(&function.arguments[0]);
let names = field_name(&function.arguments[1]);
writeln!(
out,
" for index in 0..usize::try_from({count}).unwrap_or(0) {{\n // SAFETY: The replayer passes room for as many names.\n unsafe {{ {names}.add(index).write(crate::webgl::testing::next_name()) }};\n }}"
)
.unwrap();
} else if is_gen && return_type == "u32" {
out.push_str(" crate::webgl::testing::next_name()\n");
} else if is_gen {
out.push_str(" crate::webgl::testing::next_name() as usize as *mut c_void\n");
} else if return_type != "()" {
writeln!(out, " {}", zero_of(return_type)).unwrap();
}
out.push_str(" }\n\n");
}
out.push_str(" pub fn functions() -> GlFunctions {\n GlFunctions {\n");
for function in &functions {
writeln!(
out,
" {}: {},",
function.method_name(),
function.method_name()
)
.unwrap();
}
out.push_str(" }\n }\n}\n");
Ok(out)
}
fn wire_type_of(function: &Function, argument: &Argument) -> Result<WireType, String> {
WireType::of(&argument.cpp_type)
.ok_or_else(|| unsupported(function, &format!("{} has no wire type", argument.name)))
}
/// The factors of the size that the JSON gives for the data of an argument, as `i64` expressions of the fields of
/// `holder`.
fn size_factors(function: &Function, argument: &Argument, holder: &str) -> Result<String, String> {
let mut factors = Vec::new();
for factor in function.payload_size(argument)? {
factors.push(match factor {
PayloadFactor::Constant(constant) => format!("{constant}_i64"),
PayloadFactor::Argument(index) => {
let counted_by = &function.arguments[index];
let field = format!("{holder}.{}", field_name(counted_by));
match wire_type_of(function, counted_by)? {
WireType::I64 => field,
WireType::I32 | WireType::U32 => format!("i64::from({field})"),
_ => {
return Err(unsupported(
function,
&format!("{} counts with {}", argument.name, counted_by.name),
));
}
}
}
PayloadFactor::ColorBufferComponents(index) => format!(
"if {holder}.{} == GL_COLOR {{ 4 }} else {{ 1 }}",
field_name(&function.arguments[index])
),
});
}
Ok(format!("&[{}]", factors.join(", ")))
}
fn element_type(argument: &Argument) -> Option<&'static str> {
let pointee = argument.pointee_cpp_type().replace("const", "");
match pointee.trim() {
"void" | "GLchar" => None,
"GLfloat" => Some("f32"),
"GLint" | "GLsizei" => Some("i32"),
"GLuint" | "GLenum" => Some("u32"),
"GLboolean" => Some("u8"),
"GLint64" => Some("i64"),
_ => None,
}
}
fn data_pointer(argument: &Argument, bytes: &str) -> String {
match element_type(argument) {
Some(element) => format!("typed_data::<{element}>({bytes})?"),
None => format!("{bytes}.as_ptr().cast()"),
}
}
fn opaque_data_pointer(argument: &Argument, data: &str) -> String {
match element_type(argument) {
Some(element) => format!("typed_opaque_data::<{element}>({data})?"),
None => format!("{data}.pointer.cast()"),
}
}
/// Resolves the data of an argument that points at some, and answers what the GL function is passed for it.
fn write_data_resolution(out: &mut String, function: &Function, argument: &Argument) -> Result<String, String> {
let field = field_name(argument);
let name = function.command_name();
let mismatch = format!(
"ReplayError(\"the data of {name}.{} has another size than its arguments give\")",
argument.name
);
let factors = size_factors(function, argument, "command")?;
if argument.is_nullable {
writeln!(
out,
" let {field}_data = if command.has_{field} {{
let data = if command.{field}.size != 0 {{ self.opaque_data(payload, command.{field})? }} else {{ OpaqueData::EMPTY }};
if !size_matches(data.size, {factors}) {{
return Err({mismatch});
}}
if command.{field}.size != 0 {{ {} }} else {{ core::ptr::null() }}
}} else {{
if command.{field}.size != 0 {{
return Err(ReplayError(\"{name}.{} has data although it has none\"));
}}
core::ptr::null()
}};",
opaque_data_pointer(argument, "data"),
argument.name
)
.unwrap();
} else {
writeln!(
out,
" let {field}_opaque_data = self.opaque_data(payload, command.{field})?;
if !size_matches({field}_opaque_data.size, {factors}) {{
return Err({mismatch});
}}
let {field}_data = {};",
opaque_data_pointer(argument, &format!("{field}_opaque_data"))
)
.unwrap();
}
Ok(format!("{field}_data"))
}
fn write_command(out: &mut String, function: &Function) -> Result<(), String> {
let name = function.command_name();
writeln!(
out,
" fn replay_{}(&mut self, payload: &[u8]) -> Result<(), ReplayError> {{",
function.method_name()
)
.unwrap();
if function.arguments.is_empty() {
writeln!(out, " decode::<commands::{name}>(payload)?;").unwrap();
} else {
writeln!(out, " let command: commands::{name} = decode(payload)?;").unwrap();
}
let mut arguments = Vec::new();
for argument in &function.arguments {
let field = field_name(argument);
let take_or_lookup = if function.deletes_objects { "take" } else { "lookup" };
if argument.is_string {
writeln!(
out,
" let {field}_data = string_data(payload, command.{field})?;"
)
.unwrap();
arguments.push(format!("{field}_data"));
} else if argument.is_offset {
arguments.push(format!("command.{field} as isize as *const c_void"));
} else if argument.is_object && !argument.is_pointer() {
if argument.cpp_type == "GLsync" {
writeln!(
out,
" let {field} = self.objects.{take_or_lookup}_sync(command.{field});"
)
.unwrap();
} else if let Some(default) = argument.zero_means_default {
let default = match default {
DefaultObject::Framebuffer => "framebuffer",
DefaultObject::Renderbuffer => "renderbuffer",
};
writeln!(
out,
" let {field} = if command.{field} == 0 {{ self.defaults.{default} }} else {{ self.objects.lookup(command.{field}) }};"
)
.unwrap();
} else {
writeln!(
out,
" let {field} = self.objects.{take_or_lookup}(command.{field});"
)
.unwrap();
}
arguments.push(field);
} else if argument.is_object && argument.is_const_pointer() {
let factors = size_factors(function, argument, "command")?;
writeln!(
out,
" let {field}_bytes = data_span(payload, command.{field})?;
if !size_matches({field}_bytes.len(), {factors}) {{
return Err(ReplayError(\"the objects of {name}.{} have another size than its arguments give\"));
}}
let {field}: Vec<u32> = object_ids({field}_bytes)?.map(|id| self.objects.{take_or_lookup}(id)).collect();",
argument.name
)
.unwrap();
arguments.push(format!("{field}.as_ptr()"));
} else if argument.payload.is_some() {
arguments.push(write_data_resolution(out, function, argument)?);
} else if argument.is_pointer() {
return Err(unsupported(
function,
&format!("{} points at what has no size", argument.name),
));
} else {
arguments.push(scalar_argument(argument, "command"));
}
}
writeln!(
out,
" // SAFETY: The context of the replayer is current, and every pointer is valid for what GL reads of it.\n unsafe {{ (self.gl.{})({}) }};\n Ok(())\n }}\n",
function.method_name(),
arguments.join(", ")
)
.unwrap();
Ok(())
}
fn write_gen(out: &mut String, function: &Function) {
let name = function.command_name();
let method = function.method_name();
writeln!(
out,
" fn replay_{method}(&mut self, payload: &[u8]) -> Result<(), ReplayError> {{\n let command: commands::{name} = decode(payload)?;"
)
.unwrap();
if function.returns_void() {
let count = field_name(&function.arguments[0]);
let ids = field_name(&function.arguments[1]);
writeln!(
out,
" let ids = object_ids(data_span(payload, command.{ids})?)?;
if i64::try_from(ids.len()) != Ok(i64::from(command.{count})) {{
return Err(ReplayError(\"{name} has another number of objects than it creates\"));
}}
for id in ids {{
let mut name = 0;
// SAFETY: The context of the replayer is current, and the name is room for one.
unsafe {{ (self.gl.{method})(1, &raw mut name) }};
self.objects.add(id, name)?;
}}
Ok(())
}}
"
)
.unwrap();
return;
}
let arguments: Vec<String> = function
.arguments
.iter()
.map(|argument| scalar_argument(argument, "command"))
.collect();
let add = if function.return_type.as_deref() == Some("GLsync") {
"add_sync"
} else {
"add"
};
writeln!(
out,
" // SAFETY: The context of the replayer is current.\n let object = unsafe {{ (self.gl.{method})({}) }};\n self.objects.{add}(command.id, object)?;\n Ok(())\n }}\n",
arguments.join(", ")
)
.unwrap();
}
fn write_sync_call(out: &mut String, function: &Function) -> Result<(), String> {
let name = function.command_name();
let method = function.method_name();
writeln!(
out,
" fn handle_{method}(&mut self, payload: &[u8]) -> Result<Vec<u8>, ReplayError> {{"
)
.unwrap();
if function.arguments.iter().any(|argument| !argument.is_out) {
writeln!(
out,
" let request: sync_calls::{name}Request = decode(payload)?;"
)
.unwrap();
} else {
writeln!(out, " let _: sync_calls::{name}Request = decode(payload)?;").unwrap();
}
let mut arguments = Vec::new();
let mut blobs = Vec::new();
let mut reply_fields = Vec::new();
for argument in &function.arguments {
let field = field_name(argument);
if let Some(value) = &argument.host_override {
arguments.push(value.clone());
} else if argument.is_out {
if argument.payload.is_some() {
let element = gl_rust_type(&argument.cpp_type)
.and_then(|pointer| pointer.strip_prefix("*mut "))
.ok_or_else(|| unsupported(function, &format!("{} is no buffer", argument.name)))?;
let factors = size_factors(function, argument, "request")?;
writeln!(
out,
" let mut {field} = vec![{}; out_data_size({factors})? / size_of::<{element}>()];",
zero_of(element)
)
.unwrap();
arguments.push(format!("{field}.as_mut_ptr()"));
blobs.push((field.clone(), element));
reply_fields.push(format!("{field}: spans[{}]", blobs.len() - 1));
} else {
let element = gl_rust_type(&argument.pointee_cpp_type())
.ok_or_else(|| unsupported(function, &format!("{} has no value type", argument.name)))?;
writeln!(out, " let mut {field}: {element} = {};", zero_of(element)).unwrap();
arguments.push(format!("&raw mut {field}"));
reply_fields.push(field);
}
} else if argument.is_object && !argument.is_pointer() {
let lookup = if argument.cpp_type == "GLsync" {
"lookup_sync"
} else {
"lookup"
};
writeln!(out, " let {field} = self.objects.{lookup}(request.{field});").unwrap();
arguments.push(field);
} else if argument.is_string {
writeln!(
out,
" let {field}_data = string_data(payload, request.{field})?;"
)
.unwrap();
arguments.push(format!("{field}_data"));
} else if argument.payload.is_some() {
let factors = size_factors(function, argument, "request")?;
writeln!(
out,
" let {field}_bytes = data_span(payload, request.{field})?;
if !size_matches({field}_bytes.len(), {factors}) {{
return Err(ReplayError(\"the data of {name}.{} has another size than its arguments give\"));
}}",
argument.name
)
.unwrap();
arguments.push(data_pointer(argument, &format!("{field}_bytes")));
} else if argument.is_pointer() {
return Err(unsupported(
function,
&format!("{} points at what has no size", argument.name),
));
} else {
arguments.push(scalar_argument(argument, "request"));
}
}
let invocation = if function.name == "glGetError" {
"self.get_error()".to_string()
} else {
out.push_str(
" // SAFETY: The context of the replayer is current, and every pointer is valid for what GL reads and\n // writes of it.\n",
);
format!("unsafe {{ (self.gl.{method})({}) }}", arguments.join(", "))
};
if function.returns_void() {
writeln!(out, " {invocation};").unwrap();
} else {
writeln!(out, " let return_value = {invocation};").unwrap();
reply_fields.insert(0, "return_value".into());
}
if !blobs.is_empty() {
let blob_sizes: Vec<String> = blobs
.iter()
.map(|(field, element)| format!("{field}.len() * size_of::<{element}>()"))
.collect();
writeln!(
out,
" let spans = reply_data_spans::<sync_calls::{name}Reply, {}>([{}]);",
blobs.len(),
blob_sizes.join(", ")
)
.unwrap();
}
let reply_layout = wire_struct(format!("SyncCalls::{name}::Reply"), function.sync_reply_fields())?;
let rest_of_reply = if reply_layout.has_unused_bytes() {
format!("..sync_calls::{name}Reply::ZEROED")
} else {
String::new()
};
writeln!(
out,
" let reply = sync_calls::{name}Reply {{ {}{rest_of_reply} }};",
reply_fields.join(", ")
+ if reply_fields.is_empty() || rest_of_reply.is_empty() {
""
} else {
", "
}
)
.unwrap();
let blob_bytes: Vec<String> = blobs
.iter()
.map(|(field, _)| format!("bytes_of_slice(&{field})"))
.collect();
writeln!(
out,
" Ok(encode_reply(&reply, &[{}]))\n }}\n",
blob_bytes.join(", ")
)
.unwrap();
Ok(())
}
/// The methods of the replayer that follow from the signatures of GL functions, and the dispatch of every command
/// and every synchronous call to its method. The others are written by hand, under the name of their function.
pub fn write_replayer(functions: &[Function]) -> Result<String, String> {
let mut out = String::from("// Generated by build.rs from Libraries/LibCompositing/WebGL/GLFunctions.json.\n\n");
out.push_str("impl<H: WebGLHost> Replayer<'_, H> {\n");
out.push_str(
" pub fn replay_record(&mut self, command_type: CommandType, payload: &[u8]) -> Result<(), ReplayError> {\n match command_type {\n",
);
for function in functions.iter().filter(|function| function.is_command_stream_entry()) {
let name = function.command_name();
let method = function.method_name();
if matches!(function.category, Category::Command | Category::Gen) {
writeln!(out, " CommandType::{name} => self.replay_{method}(payload),").unwrap();
} else {
writeln!(out, " CommandType::{name} => self.{method}(payload),").unwrap();
}
}
out.push_str(" }\n }\n\n");
out.push_str(
" pub fn handle_sync_call(&mut self, call_type: SyncCallType, payload: &[u8]) -> Result<Vec<u8>, ReplayError> {\n match call_type {\n",
);
for function in functions.iter().filter(|function| function.is_sync_call()) {
let name = function.command_name();
let method = function.method_name();
if function.category == Category::Sync {
writeln!(
out,
" SyncCallType::{name} => self.handle_{method}(payload),"
)
.unwrap();
} else {
writeln!(out, " SyncCallType::{name} => self.{method}(payload),").unwrap();
}
}
out.push_str(" }\n }\n\n");
for function in functions {
match function.category {
Category::Command => write_command(&mut out, function)?,
Category::Gen => write_gen(&mut out, function),
Category::Sync => write_sync_call(&mut out, function)?,
Category::Custom | Category::BuiltinCommand => {}
}
}
out.push_str("}\n\n");
let commands_with_only_opaque_data: Vec<String> = functions
.iter()
.filter(|function| function.category == Category::Command && has_only_opaque_data(function))
.map(|function| format!("CommandType::{}", function.command_name()))
.collect();
out.push_str("pub fn only_gl_reads_the_data_of(command_type: CommandType) -> bool {\n");
if commands_with_only_opaque_data.is_empty() {
out.push_str(" let _ = command_type;\n false\n");
} else {
writeln!(
out,
" matches!(command_type, {})",
commands_with_only_opaque_data.join(" | ")
)
.unwrap();
}
out.push_str("}\n");
Ok(out)
}
fn has_only_opaque_data(function: &Function) -> bool {
let reads_its_data = function
.arguments
.iter()
.any(|argument| argument.is_string || (argument.is_object && argument.is_const_pointer()));
let has_data_that_write_data_resolution_resolves = function.arguments.iter().any(|argument| {
!argument.is_string && !argument.is_offset && !argument.is_object && argument.payload.is_some()
});
has_data_that_write_data_resolution_resolves && !reads_its_data
}