Skip to content

Truly independent web browser

LibCompositing: Assert and report the layout of WebGL command structs

Aliaksandr Kalenikbc7110d5789f
diff --git a/Meta/Generators/generate_libweb_webgl_commands.py b/Meta/Generators/generate_libweb_webgl_commands.py
index 2b4a751fca6..f22fa7c96f5 100644
--- a/Meta/Generators/generate_libweb_webgl_commands.py
+++ b/Meta/Generators/generate_libweb_webgl_commands.py
@@ -13,13 +13,13 @@ sys.path.append(str(Path(__file__).resolve().parent))
from libweb_webgl import command_name
from libweb_webgl import command_stream_entries
-from libweb_webgl import command_struct_fields
-from libweb_webgl import is_wire_command
-from libweb_webgl import is_wire_sync
+from libweb_webgl import command_wire_fields
from libweb_webgl import run_generator
from libweb_webgl import sync_call_entries
-from libweb_webgl import sync_reply_fields
-from libweb_webgl import sync_request_fields
+from libweb_webgl import sync_reply_wire_fields
+from libweb_webgl import sync_request_wire_fields
+from libweb_webgl import wire_layout_name_hash
+from libweb_webgl import wire_structs
# Generates the WebGL command stream vocabulary from GLFunctions.json: one opcode and one
# trivially-copyable struct per "command"/"gen" entry. The recorder (WebContent) and the
@@ -95,6 +95,7 @@ def write_header_file(out: TextIO, functions: list) -> None:
out.write("""#pragma once
#include <AK/Assertions.h>
+#include <AK/Span.h>
#include <AK/StdLibExtras.h>
#include <AK/StringView.h>
#include <AK/Types.h>
@@ -116,12 +117,8 @@ namespace Compositing::WebGL {
name = command_name(f)
out.write(f"\nstruct {name} {{\n")
out.write(f" static constexpr auto command_type = WebGLCommandType::{name};\n")
- if is_wire_command(f):
- for field in f["wire_command"]:
- out.write(f" {field['type']} {field['name']} {{}};\n")
- else:
- for cpp_type, field_name, _ in command_struct_fields(f):
- out.write(f" {cpp_type} {field_name} {{}};\n")
+ for cpp_type, field_name in command_wire_fields(f):
+ out.write(f" {cpp_type} {field_name} {{}};\n")
out.write("};\n")
out.write("\n}\n")
write_visit_function(out, "ENUMERATE_WEBGL_COMMANDS", "WebGLCommandType", "visit_webgl_command_type", "Commands")
@@ -138,20 +135,14 @@ namespace Compositing::WebGL {
out.write("\nnamespace SyncCalls {\n")
for f in sync_calls:
name = command_name(f)
- if is_wire_sync(f):
- request_fields = [(field["type"], field["name"]) for field in f["wire_request"]]
- reply_fields = [(field["type"], field["name"]) for field in f["wire_reply"]]
- else:
- request_fields = [(cpp_type, field_name) for cpp_type, field_name, _ in sync_request_fields(f)]
- reply_fields = [(cpp_type, field_name) for cpp_type, field_name, _ in sync_reply_fields(f)]
out.write(f"\nstruct {name} {{\n")
out.write(f" static constexpr auto call_type = WebGLSyncCallType::{name};\n")
out.write(" struct Request {\n")
- for cpp_type, field_name in request_fields:
+ for cpp_type, field_name in sync_request_wire_fields(f):
out.write(f" {cpp_type} {field_name} {{}};\n")
out.write(" };\n")
out.write(" struct Reply {\n")
- for cpp_type, field_name in reply_fields:
+ for cpp_type, field_name in sync_reply_wire_fields(f):
out.write(f" {cpp_type} {field_name} {{}};\n")
out.write(" };\n")
out.write("};\n")
@@ -164,17 +155,78 @@ namespace Compositing::WebGL {
"ENUMERATE_WEBGL_SYNC_CALLS",
"static_assert(IsTriviallyCopyable<SyncCalls::name::Request>); static_assert(IsTriviallyCopyable<SyncCalls::name::Reply>);",
)
- out.write("\n}\n")
+ out.write("""
+// The layout of every struct that crosses the command stream, as the compiler of this side laid it out, for a recorder
+// that is not compiled from this header to compare its own against. A struct is the words (hash of its name, size,
+// alignment, number of fields) followed by the words (hash of its name, hash of the name of its type, offset, size)
+// of each of its fields.
+COMPOSITING_API ReadonlySpan<u32> webgl_wire_struct_layouts();
+
+}
+
+extern "C" COMPOSITING_API u32 const* compositing_webgl_wire_struct_layouts(size_t* out_word_count);
+""")
+
+
+def write_wire_struct_layout_assertions(out: TextIO, functions: list) -> None:
+ out.write("""
+// The recorder and the replayer exchange these structs as bytes, and they can be compiled by different compilers, or
+// from definitions in different languages. So the layout of each is not left to what a compiler happens to do: it is
+// computed from the size and the alignment of the types of the fields, and has to be what the compiler does.
+""")
+ for struct in wire_structs(functions):
+ out.write(f"static_assert(sizeof({struct.name}) == {struct.size});\n")
+ out.write(f"static_assert(alignof({struct.name}) == {struct.alignment});\n")
+ for field in struct.fields:
+ out.write(f"static_assert(offsetof({struct.name}, {field.name}) == {field.offset});\n")
+ out.write(f"static_assert(sizeof({struct.name}::{field.name}) == {field.size});\n")
+
+
+def write_wire_struct_layouts(out: TextIO, functions: list) -> None:
+ out.write("\nstatic constexpr u32 s_wire_struct_layouts[] = {\n")
+ for struct in wire_structs(functions):
+ struct_name_hash = wire_layout_name_hash(struct.name)
+ out.write(f" // {struct.name}\n")
+ out.write(
+ f" {struct_name_hash:#010x}u, sizeof({struct.name}), alignof({struct.name}), {len(struct.fields)},\n"
+ )
+ for field in struct.fields:
+ field_name_hash = wire_layout_name_hash(field.name)
+ type_name_hash = wire_layout_name_hash(field.cpp_type)
+ out.write(
+ f" {field_name_hash:#010x}u, {type_name_hash:#010x}u, "
+ f"offsetof({struct.name}, {field.name}), sizeof({struct.name}::{field.name}),\n"
+ )
+ out.write("""};
+
+ReadonlySpan<u32> webgl_wire_struct_layouts()
+{
+ return s_wire_struct_layouts;
+}
+""")
def write_implementation_file(out: TextIO, functions: list) -> None:
- out.write("""#include <LibCompositing/WebGL/WebGLCommands.h>
+ out.write("""#include <AK/Span.h>
+#include <LibCompositing/WebGL/WebGLCommands.h>
+#include <stddef.h>
namespace Compositing::WebGL {
""")
write_to_string_implementation(out, "ENUMERATE_WEBGL_COMMANDS", "WebGLCommandType")
write_to_string_implementation(out, "ENUMERATE_WEBGL_SYNC_CALLS", "WebGLSyncCallType")
- out.write("\n}\n")
+ write_wire_struct_layout_assertions(out, functions)
+ write_wire_struct_layouts(out, functions)
+ out.write("""
+}
+
+u32 const* compositing_webgl_wire_struct_layouts(size_t* out_word_count)
+{
+ auto layouts = Compositing::WebGL::webgl_wire_struct_layouts();
+ *out_word_count = layouts.size();
+ return layouts.data();
+}
+""")
if __name__ == "__main__":
diff --git a/Meta/Generators/libweb_webgl.py b/Meta/Generators/libweb_webgl.py
index ab37020d88d..12009e88d39 100644
--- a/Meta/Generators/libweb_webgl.py
+++ b/Meta/Generators/libweb_webgl.py
@@ -9,7 +9,10 @@ import argparse
import json
import sys
+from dataclasses import dataclass
from pathlib import Path
+from typing import List
+from typing import Tuple
sys.path.append(str(Path(__file__).resolve().parent.parent))
@@ -152,3 +155,99 @@ def command_struct_fields(function: dict) -> list:
assert not is_pointer(arg), f"unhandled pointer arg {function['name']}.{arg['name']}"
fields.append((arg["type"], field_name, arg))
return fields
+
+
+# Returns the ordered (cpp_type, field_name) pairs of the struct that a command stream entry serializes to.
+def command_wire_fields(function: dict) -> list:
+ if is_wire_command(function):
+ return [(field["type"], field["name"]) for field in function["wire_command"]]
+ return [(cpp_type, field_name) for cpp_type, field_name, _ in command_struct_fields(function)]
+
+
+# Returns the ordered (cpp_type, field_name) pairs of the request struct of a synchronous call.
+def sync_request_wire_fields(function: dict) -> list:
+ if is_wire_sync(function):
+ return [(field["type"], field["name"]) for field in function["wire_request"]]
+ return [(cpp_type, field_name) for cpp_type, field_name, _ in sync_request_fields(function)]
+
+
+# Returns the ordered (cpp_type, field_name) pairs of the reply struct of a synchronous call.
+def sync_reply_wire_fields(function: dict) -> list:
+ if is_wire_sync(function):
+ return [(field["type"], field["name"]) for field in function["wire_reply"]]
+ return [(cpp_type, field_name) for cpp_type, field_name, _ in sync_reply_fields(function)]
+
+
+# The (size, alignment) in bytes of every type that a field of a wire struct can have. Both sides of the command
+# stream are 64-bit, and the generated structs assert that the compiler lays them out as computed from this table.
+WIRE_TYPE_LAYOUTS = {
+ "GLenum": (4, 4),
+ "GLuint": (4, 4),
+ "GLbitfield": (4, 4),
+ "GLint": (4, 4),
+ "GLsizei": (4, 4),
+ "GLfloat": (4, 4),
+ "GLboolean": (1, 1),
+ "GLintptr": (8, 8),
+ "GLsizeiptr": (8, 8),
+ "GLuint64": (8, 8),
+ "WebGLObjectId": (4, 4),
+ "WebGLDataSpan": (8, 4),
+ "bool": (1, 1),
+ "int": (4, 4),
+ "u32": (4, 4),
+}
+
+
+@dataclass
+class WireField:
+ cpp_type: str
+ name: str
+ offset: int
+ size: int
+
+
+@dataclass
+class WireStruct:
+ # The name of the struct inside the namespace Compositing::WebGL.
+ name: str
+ fields: List[WireField]
+ size: int
+ alignment: int
+
+
+def wire_struct(name: str, fields: List[Tuple[str, str]]) -> WireStruct:
+ placed_fields = []
+ end_of_fields = 0
+ alignment = 1
+ for cpp_type, field_name in fields:
+ if cpp_type not in WIRE_TYPE_LAYOUTS:
+ raise ValueError(f"{name}.{field_name} has the type {cpp_type}, which has no entry in WIRE_TYPE_LAYOUTS")
+ field_size, field_alignment = WIRE_TYPE_LAYOUTS[cpp_type]
+ offset = -(-end_of_fields // field_alignment) * field_alignment
+ placed_fields.append(WireField(cpp_type, field_name, offset, field_size))
+ end_of_fields = offset + field_size
+ alignment = max(alignment, field_alignment)
+ # NB: A struct without fields has the size 1 in C++.
+ size = max(1, -(-end_of_fields // alignment) * alignment)
+ return WireStruct(name, placed_fields, size, alignment)
+
+
+# Every struct that crosses the command stream, in the order of their definition in WebGLCommands.h.
+def wire_structs(functions: list) -> List[WireStruct]:
+ structs = []
+ for function in command_stream_entries(functions):
+ structs.append(wire_struct(f"Commands::{command_name(function)}", command_wire_fields(function)))
+ for function in sync_call_entries(functions):
+ name = command_name(function)
+ structs.append(wire_struct(f"SyncCalls::{name}::Request", sync_request_wire_fields(function)))
+ structs.append(wire_struct(f"SyncCalls::{name}::Reply", sync_reply_wire_fields(function)))
+ return structs
+
+
+# The 32-bit FNV-1a hash that stands for the name of a struct, a field or a type in the table of layout words.
+def wire_layout_name_hash(name: str) -> int:
+ hash_value = 0x811C9DC5
+ for byte in name.encode("utf-8"):
+ hash_value = ((hash_value ^ byte) * 0x01000193) & 0xFFFFFFFF
+ return hash_value