Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
//! Writes LibJS/Embedding/Layout.h: the offsets, sizes and constants of the runtime's structures that an embedder
//! reads or writes directly, computed from the crate's layout module the same way as the interpreter's layout. Every
//! offset and size is also written out as a static assertion that the crate compiles. The header's C++ section checks
//! the size, alignment, field count and the offset and type of every field of the layout module's mirror of
//! LibJS/HostObjectABI.h, and the value of every constant the mirror defines, against that header. A constant that
//! only the header defines goes unnoticed.
use core::mem::offset_of;
use std::collections::HashSet;
use std::fmt::{Display, Write};
use crate::c_type_spelling::{CTypeSpelling, c_type_spelling_of_field};
use crate::class_id::{ALL_CLASS_IDS, CLASS_COUNT};
use crate::layout::cell::*;
use crate::layout::class::*;
use crate::layout::execution_context::*;
use crate::layout::function_object::*;
use crate::layout::host_class::*;
use crate::layout::host_object::*;
use crate::layout::object::*;
use crate::layout::primitive_string::*;
use crate::layout::realm::*;
use crate::layout::shape::*;
use crate::layout::vm::*;
/// The imports the static assertions need to name the same types as the header.
const STATIC_ASSERTIONS_PREAMBLE: &str = "\
use crate::layout::cell::*;
use crate::layout::class::*;
use crate::layout::execution_context::*;
use crate::layout::function_object::*;
use crate::layout::host_object::*;
use crate::layout::object::*;
use crate::layout::primitive_string::*;
use crate::layout::realm::*;
use crate::layout::shape::*;
use crate::layout::vm::*;
const fn size_of_field<Struct, Field>(_: fn(&Struct) -> *const Field) -> usize {
size_of::<Field>()
}
";
const PREAMBLE: &str = "\
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
// Generated by the build script of libjs_embedding_headers from the runtime's layout module -- DO NOT EDIT
//
// The offsets, sizes and constants of the runtime's structures that an embedder reads or writes directly.
#ifndef LIBJS_EMBEDDING_LAYOUT_H
#define LIBJS_EMBEDDING_LAYOUT_H
#include <LibJS/HostObjectABI.h>
";
/// The start of the header's C++ section, which checks the layout module's mirror of LibJS/HostObjectABI.h against
/// that header.
const HOST_OBJECT_ABI_CHECKS_PREAMBLE: &str = "\
#ifdef __cplusplus
# include <type_traits>
# include <utility>
// The runtime mirrors LibJS/HostObjectABI.h in src/layout/host_class.rs and src/layout/host_object.rs. These check the
// size, alignment, field count and the offset and type of every field of that mirror, and the value of every constant
// it defines, against the header.
namespace JSEmbeddingLayoutChecks {
struct InitializerOfAnyField {
template<typename Field>
operator Field() const;
};
template<size_t>
using InitializerOfAnyFieldAt = InitializerOfAnyField;
template<typename Aggregate, size_t... field_indices>
consteval bool initializes_from_initializers(std::index_sequence<field_indices...>)
{
return requires { Aggregate { InitializerOfAnyFieldAt<field_indices> {}... }; };
}
// Aggregate initialization takes one initializer per field and no more, which also counts fields that fit in padding.
template<typename Aggregate, size_t field_count>
constexpr bool has_exactly_fields = initializes_from_initializers<Aggregate>(std::make_index_sequence<field_count> {})
&& !initializes_from_initializers<Aggregate>(std::make_index_sequence<field_count + 1> {});
}
";
pub struct LayoutHeader {
pub text: String,
pub static_assertions: String,
}
struct HeaderWriter {
definitions: String,
defined_names: HashSet<String>,
host_object_abi_checks: String,
static_assertions: String,
}
impl HeaderWriter {
fn new() -> Self {
Self {
definitions: String::new(),
defined_names: HashSet::new(),
host_object_abi_checks: String::new(),
static_assertions: STATIC_ASSERTIONS_PREAMBLE.to_string(),
}
}
fn section(&mut self, title: &str) {
let _ = write!(self.definitions, "\n// {title}\n");
}
fn define(&mut self, name: &str, value: impl Display) {
assert!(
self.defined_names.insert(name.to_string()),
"JS_LAYOUT_{name} is defined twice"
);
let _ = writeln!(self.definitions, "#define JS_LAYOUT_{name} {value}");
}
fn define_hex(&mut self, name: &str, value: u64) {
self.define(name, format!("0x{value:X}"));
}
fn assert_offset(&mut self, type_path: &str, field_path: &str, offset: usize) {
let _ = writeln!(
self.static_assertions,
"const _: () = assert!(core::mem::offset_of!({type_path}, {field_path}) == {offset});"
);
}
fn assert_size(&mut self, type_path: &str, size: usize) {
let _ = writeln!(
self.static_assertions,
"const _: () = assert!(size_of::<{type_path}>() == {size});"
);
}
fn assert_field_size(&mut self, type_path: &str, field_path: &str, size: usize) {
let _ = writeln!(
self.static_assertions,
"const _: () = assert!(size_of_field(|value: &{type_path}| &raw const value.{field_path}) == {size});"
);
}
fn check_host_object_abi(&mut self, condition: &str) {
let _ = writeln!(self.host_object_abi_checks, "static_assert({condition});");
}
fn finish(self) -> LayoutHeader {
let mut text = String::from(PREAMBLE);
text.push_str(&self.definitions);
text.push('\n');
text.push_str(HOST_OBJECT_ABI_CHECKS_PREAMBLE);
text.push_str(&self.host_object_abi_checks);
text.push_str("#endif\n\n#endif // LIBJS_EMBEDDING_LAYOUT_H\n");
LayoutHeader {
text,
static_assertions: self.static_assertions,
}
}
}
/// Takes a raw pointer to the field, since a field of a packed struct such as CellHeader cannot have a reference.
fn size_of_field<Struct, Field>(_: fn(&Struct) -> *const Field) -> usize {
size_of::<Field>()
}
/// Defines the offset of a field and its size, which tells an embedder the width to read it at.
macro_rules! offset {
($writer:expr, $name:expr, $type:ident, $($field:tt)+) => {{
let name = $name;
let offset = offset_of!($type, $($field)+);
$writer.define(&format!("{name}_OFFSET"), offset);
$writer.assert_offset(stringify!($type), stringify!($($field)+), offset);
let size = size_of_field(|value: &$type| &raw const value.$($field)+);
$writer.define(&format!("{name}_SIZE"), size);
$writer.assert_field_size(stringify!($type), stringify!($($field)+), size);
}};
}
macro_rules! size {
($writer:expr, $name:expr, $type:ident) => {{
let size = size_of::<$type>();
$writer.define(&format!("{}_SIZE", $name), size);
$writer.assert_size(stringify!($type), size);
}};
}
/// Defines the offset of each listed field. The list has to name every field of the struct, so that one added to it
/// fails to compile here until the header has it too.
macro_rules! every_field_offset {
($writer:expr, $prefix:literal, $type:ident { $($field:ident),* $(,)? }) => {{
const _: fn(&$type) = |value| {
let $type { $($field: _),* } = value;
};
$(offset!($writer, format!("{}_{}", $prefix, stringify!($field).to_uppercase()), $type, $field);)*
}};
}
/// Checks the size, alignment, field count and the offset and type of every field of a struct that mirrors one of
/// LibJS/HostObjectABI.h.
macro_rules! check_host_object_abi_struct {
($writer:expr, $type:ident { $($field:ident),* $(,)? }) => {{
const _: fn(&$type) = |value| {
let $type { $($field: _),* } = value;
};
let type_name = stringify!($type);
$writer.check_host_object_abi(&format!("sizeof({type_name}) == {}", size_of::<$type>()));
$writer.check_host_object_abi(&format!("alignof({type_name}) == {}", align_of::<$type>()));
let field_count = [$(stringify!($field)),*].len();
$writer.check_host_object_abi(&format!(
"JSEmbeddingLayoutChecks::has_exactly_fields<{type_name}, {field_count}>"
));
$(
let field_name = stringify!($field).trim_start_matches("r#");
$writer.check_host_object_abi(&format!(
"offsetof({type_name}, {field_name}) == {}",
offset_of!($type, $field)
));
$writer.check_host_object_abi(&format!(
"std::is_same_v<decltype({type_name}::{field_name}), {}>",
c_type_spelling_of_field(|value: &$type| &value.$field)
));
)*
}};
}
macro_rules! check_host_object_abi_constants {
($writer:expr, $($name:ident),* $(,)?) => {
$($writer.check_host_object_abi(&format!("{} == {}", stringify!($name), $name));)*
};
}
/// Spells a class name such as RawJSONObject the way C spells constants, RAW_JSON_OBJECT.
fn screaming_snake_case(name: &str) -> String {
let characters: Vec<char> = name.chars().collect();
let mut result = String::new();
for (index, &character) in characters.iter().enumerate() {
if index > 0 && character.is_ascii_uppercase() {
let previous = characters[index - 1];
let next_is_lowercase = characters.get(index + 1).is_some_and(char::is_ascii_lowercase);
if previous.is_ascii_lowercase()
|| previous.is_ascii_digit()
|| (previous.is_ascii_uppercase() && next_is_lowercase)
{
result.push('_');
}
}
result.push(character.to_ascii_uppercase());
}
result
}
fn cell_kind_name(kind: CellKind) -> &'static str {
match kind {
CellKind::Other => "OTHER",
CellKind::Object => "OBJECT",
CellKind::PrimitiveString => "PRIMITIVE_STRING",
CellKind::Symbol => "SYMBOL",
CellKind::BigInt => "BIG_INT",
CellKind::Accessor => "ACCESSOR",
}
}
#[rustfmt::skip]
pub fn generate() -> LayoutHeader {
let mut w = HeaderWriter::new();
w.section("Cell header, at the start of every cell");
offset!(w, "CELL_STATE", CellHeader, state);
offset!(w, "CELL_KIND", CellHeader, kind);
for kind in [CellKind::Other, CellKind::Object, CellKind::PrimitiveString, CellKind::Symbol, CellKind::BigInt, CellKind::Accessor] {
w.define(&format!("CELL_KIND_{}", cell_kind_name(kind)), kind as u8);
}
w.section("Class, which the block of a cell holds: its id and the class it extends");
w.define("BLOCK_CLASS_TAIL_TAG", BLOCK_CLASS_TAIL_TAG);
offset!(w, "CLASS_ID", ClassLayout, id);
offset!(w, "CLASS_PARENT", ClassLayout, parent);
w.section("Object");
offset!(w, "OBJECT_FLAGS", Object, flags);
offset!(w, "OBJECT_SHAPE", Object, shape);
size!(w, "OBJECT", Object);
w.section("Object flags");
w.define_hex("OBJECT_FLAG_IS_EXTENSIBLE", object_flag::IS_EXTENSIBLE.into());
w.define_hex("OBJECT_FLAG_IS_RAW_NATIVE_FUNCTION", object_flag::IS_RAW_NATIVE_FUNCTION.into());
w.define_hex("OBJECT_FLAG_HAS_MAGICAL_LENGTH_PROPERTY", object_flag::HAS_MAGICAL_LENGTH_PROPERTY.into());
w.define_hex("OBJECT_FLAG_IS_TYPED_ARRAY", object_flag::IS_TYPED_ARRAY.into());
w.define_hex("OBJECT_FLAG_MAY_INTERFERE_WITH_INDEXED_PROPERTY_ACCESS", object_flag::MAY_INTERFERE_WITH_INDEXED_PROPERTY_ACCESS.into());
w.define_hex("OBJECT_FLAG_HAS_INTRINSIC_ACCESSORS", object_flag::HAS_INTRINSIC_ACCESSORS.into());
w.define_hex("OBJECT_FLAG_IS_ECMASCRIPT_FUNCTION_OBJECT", object_flag::IS_ECMASCRIPT_FUNCTION_OBJECT.into());
w.define_hex("OBJECT_FLAG_IS_FUNCTION", object_flag::IS_FUNCTION.into());
w.define_hex("OBJECT_FLAG_REQUIRES_SLOW_ADD_OWN_PROPERTY", object_flag::REQUIRES_SLOW_ADD_OWN_PROPERTY.into());
w.define_hex("OBJECT_FLAG_IS_PLATFORM_OBJECT", object_flag::IS_PLATFORM_OBJECT.into());
w.define_hex("OBJECT_FLAG_IS_DIRECT_GETTER_FUNCTION", object_flag::IS_DIRECT_GETTER_FUNCTION.into());
w.define_hex("OBJECT_FLAG_IS_GLOBAL_OBJECT", object_flag::IS_GLOBAL_OBJECT.into());
w.define_hex("OBJECT_FLAG_HAS_UNIMPLEMENTED_PROPERTIES", object_flag::HAS_UNIMPLEMENTED_PROPERTIES.into());
w.define_hex("OBJECT_FLAG_IS_HTMLDDA", object_flag::IS_HTMLDDA.into());
w.section("Shape");
offset!(w, "SHAPE_REALM", Shape, realm);
offset!(w, "SHAPE_PROTOTYPE", Shape, prototype);
w.section("ECMAScript functions, whose [[ScriptOrModule]] is in their shared data");
w.define(
"ECMASCRIPT_FUNCTION_OBJECT_SHARED_DATA_OFFSET",
ECMASCRIPT_FUNCTION_OBJECT_SHARED_DATA_OFFSET,
);
w.define(
"ECMASCRIPT_FUNCTION_OBJECT_SHARED_DATA_SIZE",
size_of_field(|fields: &EcmascriptFunctionFields| &raw const fields.shared_data),
);
offset!(w, "SHARED_FUNCTION_INSTANCE_DATA_SCRIPT_OR_MODULE", SharedFunctionInstanceData, script_or_module);
w.section("Realm");
offset!(w, "REALM_GLOBAL_OBJECT", Realm, global_object);
offset!(w, "REALM_GLOBAL_ENVIRONMENT", Realm, global_environment);
offset!(w, "REALM_INTRINSICS", Realm, intrinsics);
offset!(w, "REALM_HOST_DEFINED", Realm, host_defined);
w.section("ExecutionContext, whose value slots follow it directly");
every_field_offset!(w, "EXECUTION_CONTEXT", ExecutionContext {
function,
realm_without_function,
script_or_module_without_function,
lexical_environment,
variable_environment_in_frame,
private_environment_in_frame,
frame_id,
program_counter,
yield_continuation,
yield_is_await,
yield_value_is_iterator_result,
caller_is_construct,
frame_initialized,
this_value,
executable,
caller_frame,
passed_argument_count,
caller_return_pc,
caller_dst_raw,
registers_and_constants_and_locals_and_arguments_count,
argument_count,
returns_to_native_caller,
runs_jit_code,
caller_is_derived_construct,
new_target,
});
size!(w, "EXECUTION_CONTEXT", ExecutionContext);
w.define("EXECUTION_CONTEXT_ALIGN", align_of::<ExecutionContext>());
w.section("ScriptOrModule, the script or module cell it names in one word");
size!(w, "SCRIPT_OR_MODULE", ScriptOrModuleSlot);
w.define("SCRIPT_OR_MODULE_MODULE_BIT", SCRIPT_OR_MODULE_SLOT_MODULE_BIT);
w.section("VM, whose head is at its start");
offset!(w, "VM_RUNNING_EXECUTION_CONTEXT", VmHead, running_execution_context);
offset!(w, "VM_INTERPRETER_STACK_TOP", VmHead, interpreter_stack.top);
offset!(w, "VM_INTERPRETER_STACK_LIMIT", VmHead, interpreter_stack.limit);
offset!(w, "VM_EXECUTION_GENERATION", VmHead, execution_generation);
offset!(w, "VM_PRIMITIVE_STORAGE_CAGE_BASE", VmHead, primitive_storage_cage_base);
offset!(w, "VM_EXECUTION_CONTEXT_STACK_ENTRIES", VmHead, execution_context_stack_entries);
offset!(w, "VM_EXECUTION_CONTEXT_STACK_LENGTH", VmHead, execution_context_stack_length);
offset!(w, "VM_EXECUTION_CONTEXT_STACK_CAPACITY", VmHead, execution_context_stack_capacity);
offset!(w, "VM_TYPE_ERROR_REALM_OVERRIDE", VmHead, type_error_realm_override);
offset!(w, "VM_TYPE_ERROR_REALM_OVERRIDE_DEPTH", VmHead, type_error_realm_override_depth);
offset!(w, "VM_CURRENT_REALM", VmHead, current_realm);
w.section("ExecutionContextStackEntry, the entries of the VM's execution context stack");
every_field_offset!(w, "EXECUTION_CONTEXT_STACK_ENTRY", ExecutionContextStackEntry {
execution_context,
previous_running_execution_context,
previous_realm,
});
size!(w, "EXECUTION_CONTEXT_STACK_ENTRY", ExecutionContextStackEntry);
w.section("Storage to reserve for constructing the VM in place, at least its size and alignment");
w.define("VM_SIZE", VM_SIZE);
w.define("VM_ALIGN", VM_ALIGN);
w.section("PrimitiveString");
offset!(w, "PRIMITIVE_STRING_DEFERRED_KIND_AND_FLAGS", PrimitiveString, deferred_kind_and_flags);
w.define_hex("PRIMITIVE_STRING_DEFERRED_KIND_MASK", DEFERRED_KIND_MASK.into());
w.define("PRIMITIVE_STRING_DEFERRED_KIND_NONE", DeferredKind::None as u8);
offset!(w, "PRIMITIVE_STRING_UTF16_STRING", PrimitiveString, utf16_string);
w.section("TypedArrayBase");
offset!(w, "TYPED_ARRAY_KIND", TypedArrayBase, kind);
offset!(w, "TYPED_ARRAY_ELEMENT_SIZE", TypedArrayBase, element_size);
offset!(w, "TYPED_ARRAY_ARRAY_LENGTH", TypedArrayBase, array_length.length);
offset!(w, "TYPED_ARRAY_ARRAY_LENGTH_ALTERNATIVE_INDEX", TypedArrayBase, array_length.alternative_index);
w.define("TYPED_ARRAY_ARRAY_LENGTH_LENGTH_ALTERNATIVE_INDEX", BYTE_LENGTH_LENGTH_INDEX);
offset!(w, "TYPED_ARRAY_BYTE_OFFSET", TypedArrayBase, byte_offset);
w.section("TypedArrayBase kinds");
w.define("TYPED_ARRAY_KIND_UINT8", typed_array_kind::UINT8);
w.define("TYPED_ARRAY_KIND_UINT8_CLAMPED", typed_array_kind::UINT8_CLAMPED);
w.define("TYPED_ARRAY_KIND_UINT16", typed_array_kind::UINT16);
w.define("TYPED_ARRAY_KIND_UINT32", typed_array_kind::UINT32);
w.define("TYPED_ARRAY_KIND_BIG_UINT64", typed_array_kind::BIG_UINT64);
w.define("TYPED_ARRAY_KIND_INT8", typed_array_kind::INT8);
w.define("TYPED_ARRAY_KIND_INT16", typed_array_kind::INT16);
w.define("TYPED_ARRAY_KIND_INT32", typed_array_kind::INT32);
w.define("TYPED_ARRAY_KIND_BIG_INT64", typed_array_kind::BIG_INT64);
w.define("TYPED_ARRAY_KIND_FLOAT16", typed_array_kind::FLOAT16);
w.define("TYPED_ARRAY_KIND_FLOAT32", typed_array_kind::FLOAT32);
w.define("TYPED_ARRAY_KIND_FLOAT64", typed_array_kind::FLOAT64);
w.section("HostObject, laid out as LibJS/HostObjectABI.h requires");
offset!(w, "HOST_OBJECT_HOST_CLASS", HostObject, host_class);
offset!(w, "HOST_OBJECT_WRAPPABLE", HostObject, wrappable);
offset!(w, "HOST_OBJECT_HOST_DATA", HostObject, host_data);
size!(w, "HOST_OBJECT", HostObject);
w.section("ClassId values");
let mut class_id_names = HashSet::new();
for (value, class_id) in ALL_CLASS_IDS.iter().enumerate() {
assert_eq!(*class_id as usize, value);
let name = screaming_snake_case(&format!("{class_id:?}"));
w.define(&format!("CLASS_ID_{name}"), value);
assert!(class_id_names.insert(name), "two class ids are spelled {class_id:?} in C");
}
w.define("CLASS_COUNT", CLASS_COUNT);
w.check_host_object_abi("JS_LAYOUT_HOST_OBJECT_HOST_CLASS_OFFSET == JS_HOST_OBJECT_HOST_CLASS_OFFSET");
w.check_host_object_abi("JS_LAYOUT_HOST_OBJECT_WRAPPABLE_OFFSET == JS_HOST_OBJECT_WRAPPABLE_OFFSET");
w.check_host_object_abi("JS_LAYOUT_HOST_OBJECT_HOST_DATA_OFFSET == JS_HOST_OBJECT_HOST_DATA_OFFSET");
w.check_host_object_abi("JS_LAYOUT_HOST_OBJECT_SIZE == JS_HOST_OBJECT_SIZE");
w.check_host_object_abi(&format!("std::is_same_v<JSValue, {}>", JSValue::c_type_spelling()));
check_host_object_abi_struct!(w, JSPropertyKey { bits });
check_host_object_abi_struct!(w, JSCompletion { payload, variant });
check_host_object_abi_struct!(w, JSPropertyDescriptor { value, get, set, property_offset, flags });
check_host_object_abi_struct!(w, JSValueSink { context, append });
check_host_object_abi_struct!(w, JSStringSink { context, append });
check_host_object_abi_struct!(w, JSHostObjectHooks {
get_prototype_of,
set_prototype_of,
is_extensible,
prevent_extensions,
get_own_property,
define_own_property,
has_property,
get,
set,
delete_property,
own_property_keys,
is_cacheable_for_inherited_property,
error_data,
finalize,
get_indexed_value,
preserve_identity,
});
check_host_object_abi_struct!(w, JSHostFunctionHooks { call, construct, finalize });
check_host_object_abi_struct!(w, JSHostArrayHooks { define_own_property, set, delete_property });
check_host_object_abi_struct!(w, JSResolvedBinding { module, binding_name, r#type });
check_host_object_abi_struct!(w, JSHostModuleHooks { get_exported_names, resolve_export, initialize_environment, execute_module });
check_host_object_abi_struct!(w, JSHostClass { kind, flags, name, name_length, parent, hooks, user_data });
check_host_object_abi_constants!(
w,
JS_COMPLETION_NORMAL,
JS_COMPLETION_THROW,
JS_PROPERTY_LOOKUP_PHASE_OWN_PROPERTY,
JS_PROPERTY_LOOKUP_PHASE_PROTOTYPE_CHAIN,
JS_PD_HAS_VALUE,
JS_PD_HAS_GET,
JS_PD_HAS_SET,
JS_PD_HAS_WRITABLE,
JS_PD_WRITABLE,
JS_PD_HAS_ENUMERABLE,
JS_PD_ENUMERABLE,
JS_PD_HAS_CONFIGURABLE,
JS_PD_CONFIGURABLE,
JS_PD_HAS_PROPERTY_OFFSET,
JS_PD_PRESENT,
JS_HOST_CLASS_OBJECT,
JS_HOST_CLASS_FUNCTION,
JS_HOST_CLASS_ARRAY,
JS_HOST_CLASS_MODULE,
JS_HOST_CLASS_IS_PLATFORM_OBJECT,
JS_HOST_CLASS_REQUIRES_SLOW_ADD_OWN_PROPERTY,
JS_HOST_CLASS_MAY_INTERFERE_WITH_INDEXED_PROPERTY_ACCESS,
JS_HOST_CLASS_IS_HTMLDDA,
JS_HOST_CLASS_IS_GLOBAL_OBJECT,
JS_HOST_CLASS_IMMUTABLE_PROTOTYPE,
JS_HOST_CLASS_NOT_CACHEABLE_FOR_PROPERTY_ABSENCE,
JS_HOST_CLASS_NOT_ELIGIBLE_FOR_OWN_PROPERTY_ENUMERATION_FAST_PATH,
JS_HOST_CLASS_HAS_CONSTRUCTOR,
JS_HOST_CLASS_SHARES_ALLOCATOR_WITH_PARENT,
JS_HOST_CLASS_NOT_CACHEABLE_FOR_INDEXED_PROPERTY_ABSENCE,
JS_HOST_CLASS_NOT_CACHEABLE_ACROSS_REALMS,
JS_RESOLVED_BINDING_BINDING_NAME,
JS_RESOLVED_BINDING_NAMESPACE,
JS_RESOLVED_BINDING_AMBIGUOUS,
JS_RESOLVED_BINDING_NULL,
);
w.finish()
}