Skip to content

Truly independent web browser

Flap: Take the address of an operand array, and reject its other uses

Andreas Klingcd02eed1a8f8
diff --git a/Libraries/LibJS/Flap/src/hir/mod.rs b/Libraries/LibJS/Flap/src/hir/mod.rs
index 6baaf5179f4..6b7c6df2df1 100644
--- a/Libraries/LibJS/Flap/src/hir/mod.rs
+++ b/Libraries/LibJS/Flap/src/hir/mod.rs
@@ -1954,7 +1954,11 @@ impl<'a> Checker<'a> {
};
let return_type = if symbol.ty == Type::EnvironmentCoordinate {
Type::BytecodeEnvironmentCoordinate
- } else if self.bytecode_fields.contains(&symbol.id) && matches!(symbol.ty, Type::Sequence(_)) {
+ } else if (self.bytecode_fields.contains(&symbol.id) || symbol.parameter_mode.is_some())
+ && matches!(symbol.ty, Type::Sequence(_))
+ {
+ // NB: A sequence parameter of an inline function is a bytecode field of the handler
+ // that calls it; lowering rejects any other argument.
symbol.ty.clone()
} else {
return self.error(operand.span, format!("cannot take the address of {}", symbol.ty));
@@ -3257,6 +3261,152 @@ enum InlineOperationArgument {
Parameter(VariableId),
}
+/// A handler's operand array is a bytecode field: as a value, it is the field's offset in the instruction, and only
+/// its address (`&operands`) finds the operands. Inline functions cannot tell an operand array from a sequence
+/// that holds an address, so a handler may only pass its operand arrays to parameters that are not used as values.
+fn validate_operand_array_uses(
+ filename: &str,
+ inline_functions: &[InlineFunction],
+ handlers: &[Handler],
+) -> Result<(), Diagnostic> {
+ // Visits every use of a variable as a value, with the call and the argument's index for a call argument.
+ fn for_each_use(statements: &[Statement], visit: &mut impl FnMut(VariableId, Option<(&Call, usize)>, SourceSpan)) {
+ for statement in statements {
+ let mut uses = Vec::new();
+ match &statement.kind {
+ StatementKindIr::Call(_, call) => {
+ for (argument_index, argument) in call.arguments.iter().enumerate() {
+ match argument.kind {
+ ValueKind::Variable(variable) => {
+ visit(variable, Some((call, argument_index)), statement.span)
+ }
+ _ => uses.extend(value_variable_ids(argument)),
+ }
+ }
+ }
+ StatementKindIr::MachineAssign { arguments, .. } => {
+ uses.extend(arguments.iter().flat_map(value_variable_ids));
+ }
+ StatementKindIr::ValueRefinement { value, .. } | StatementKindIr::ValueMatch { value, .. } => {
+ uses.extend(value_variable_ids(value));
+ }
+ StatementKindIr::ScalarMatch { value, arms, .. } => {
+ uses.extend(value_variable_ids(value));
+ for arm in arms {
+ add_scalar_pattern_variables(&mut uses, &arm.pattern);
+ }
+ }
+ StatementKindIr::Assert(condition)
+ | StatementKindIr::Guard { condition, .. }
+ | StatementKindIr::If { condition, .. }
+ | StatementKindIr::While { condition, .. } => {
+ uses.extend(condition_uses_and_defs(condition).0);
+ }
+ StatementKindIr::Continuation { .. } => {}
+ }
+ for variable in uses {
+ visit(variable, None, statement.span);
+ }
+ statement.kind.for_each_nested_body(|body| for_each_use(body, visit));
+ }
+ }
+ fn takes_address(call: &Call) -> bool {
+ call.target == CallTarget::Intrinsic(Intrinsic::Address(AddressOperation::BytecodeField))
+ }
+
+ // The sequence parameters that an inline function uses as values, directly or through the inline functions
+ // that it passes them to.
+ let mut used_as_value = HashSet::default();
+ let mut forwards = Vec::new();
+ for (function_index, function) in inline_functions.iter().enumerate() {
+ // NB: The arguments of a call leave out the parameters that the return value becomes.
+ let parameter_indices = function
+ .parameters
+ .iter()
+ .filter(|parameter| !function.body.variables[**parameter].name.starts_with("__return_value"))
+ .enumerate()
+ .filter(|(_, parameter)| matches!(function.body.variables[**parameter].ty, Type::Sequence(_)))
+ .map(|(index, parameter)| (*parameter, index))
+ .collect::<HashMap<_, _>>();
+ for_each_use(&function.body.statements, &mut |variable, argument, _| {
+ let Some(&parameter_index) = parameter_indices.get(&variable) else {
+ return;
+ };
+ match argument {
+ Some((call, argument_index)) => match call.target {
+ CallTarget::InlineFunction(callee) => {
+ forwards.push(((function_index, parameter_index), (callee.index(), argument_index)));
+ }
+ _ if takes_address(call) => {}
+ _ => {
+ used_as_value.insert((function_index, parameter_index));
+ }
+ },
+ None => {
+ used_as_value.insert((function_index, parameter_index));
+ }
+ }
+ });
+ }
+ loop {
+ let before = used_as_value.len();
+ for (parameter, forwarded_to) in &forwards {
+ if used_as_value.contains(forwarded_to) {
+ used_as_value.insert(*parameter);
+ }
+ }
+ if used_as_value.len() == before {
+ break;
+ }
+ }
+
+ for handler in handlers {
+ let body = &handler.body;
+ let mut error = None;
+ for_each_use(&body.statements, &mut |variable, argument, span| {
+ if error.is_some()
+ || !body.bytecode_fields.contains(&variable)
+ || !matches!(body.variables[variable].ty, Type::Sequence(_))
+ {
+ return;
+ }
+ let name = &body.variables[variable].name;
+ let value_use_error = || {
+ Diagnostic::new(
+ filename,
+ span,
+ format!(
+ "the operand array '{name}' as a value is the field's offset; use '&{name}' for its address"
+ ),
+ )
+ };
+ let Some((call, argument_index)) = argument else {
+ error = Some(value_use_error());
+ return;
+ };
+ match call.target {
+ CallTarget::InlineFunction(callee) if used_as_value.contains(&(callee.index(), argument_index)) => {
+ let callee = &inline_functions[callee.index()].name;
+ error = Some(Diagnostic::new(
+ filename,
+ span,
+ format!(
+ "'{callee}' uses its parameter for the operand array '{name}' as a value, which is the field's offset; it has to take the address with '&'"
+ ),
+ ));
+ }
+ CallTarget::InlineFunction(_) => {}
+ _ if takes_address(call) => {}
+ _ => error = Some(value_use_error()),
+ }
+ });
+ if let Some(error) = error {
+ return Err(error);
+ }
+ }
+ Ok(())
+}
+
struct InlineCallSite {
callee: usize,
operation_arguments: Vec<Option<InlineOperationArgument>>,
@@ -3652,6 +3802,7 @@ pub(crate) fn check_with_layouts(
}
}
validate_inline_call_graph(filename, &inline_functions)?;
+ validate_operand_array_uses(filename, &inline_functions, &handlers)?;
Ok(Program {
inline_functions,
handlers,
diff --git a/Libraries/LibJS/Flap/tests/operand_arrays.rs b/Libraries/LibJS/Flap/tests/operand_arrays.rs
new file mode 100644
index 00000000000..bca8953bf5a
--- /dev/null
+++ b/Libraries/LibJS/Flap/tests/operand_arrays.rs
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use flapc::{Architecture, CompilationUnit, CompileOptions, Compiler, ObjectFormat, SourceInput, Target};
+
+fn compile(program: &str) -> Result<String, String> {
+ Compiler::new(CompileOptions {
+ target: Target {
+ architecture: Architecture::X86_64,
+ object_format: ObjectFormat::Elf,
+ },
+ has_jscvt: false,
+ has_lzcnt: false,
+ has_bmi1: false,
+ enable_assertions: true,
+ profiling: false,
+ profile: flapc::Profile::JavaScript,
+ })
+ .compile(CompilationUnit {
+ source: SourceInput {
+ name: "operand_arrays.flap",
+ contents: program,
+ },
+ constants: Some(SourceInput {
+ name: "layout.conf",
+ contents: include_str!("interpreter-layout.conf"),
+ }),
+ })
+ .map(|assembly| assembly.as_str().to_owned())
+ .map_err(|error| format!("{error:?}"))
+}
+
+#[test]
+fn an_inline_function_takes_the_address_of_its_operand_array_parameter() {
+ let assembly = compile(
+ "
+inline fn first_operand(operands: Operand[]) -> u32 {
+ let indices = &operands;
+ u32(indices[0])
+}
+
+handler Check(
+ operands_count: u8,
+ operands: Operand[]
+) {
+ let first = first_operand(operands);
+ values[first] = Value<Undefined>;
+ let mut count: u32;
+ load8(count, [pb, pc, operands_count]);
+ let length: u32 = 3 + count;
+ dispatch_variable(length);
+}
+",
+ )
+ .unwrap();
+ // NB: The parameter is the handler's field, so its address is in the instruction, not its offset.
+ assert!(assembly.contains("[r14 + r13 + 2]"), "{assembly}");
+}
+
+const CHECK_HANDLER: &str = "
+handler Check(
+ operands_count: u8,
+ operands: Operand[]
+) {
+ let first = first_operand(operands);
+ values[first] = Value<Undefined>;
+ let mut count: u32;
+ load8(count, [pb, pc, operands_count]);
+ let length: u32 = 3 + count;
+ dispatch_variable(length);
+}
+";
+
+#[test]
+fn an_inline_function_cannot_use_an_operand_array_parameter_as_a_value() {
+ let error = compile(&format!(
+ "
+inline fn first_operand(operands: Operand[]) -> u32 {{
+ let indices = operands;
+ u32(indices[0])
+}}
+{CHECK_HANDLER}"
+ ))
+ .unwrap_err();
+ assert!(
+ error.contains("'first_operand' uses its parameter for the operand array 'operands' as a value"),
+ "{error}"
+ );
+}
+
+#[test]
+fn an_inline_function_cannot_pass_an_operand_array_parameter_on_to_a_value_use() {
+ let error = compile(&format!(
+ "
+inline fn copy_operands(operands: Operand[]) -> u32 {{
+ let indices = operands;
+ u32(indices[0])
+}}
+
+inline fn first_operand(operands: Operand[]) -> u32 {{
+ copy_operands(operands)
+}}
+{CHECK_HANDLER}"
+ ))
+ .unwrap_err();
+ assert!(
+ error.contains("'first_operand' uses its parameter for the operand array 'operands' as a value"),
+ "{error}"
+ );
+}
+
+#[test]
+fn a_handler_cannot_use_its_operand_array_as_a_value() {
+ let error = compile(
+ "
+handler Check(
+ operands_count: u8,
+ operands: Operand[]
+) {
+ let indices = operands;
+ values[u32(indices[0])] = Value<Undefined>;
+ let mut count: u32;
+ load8(count, [pb, pc, operands_count]);
+ let length: u32 = 3 + count;
+ dispatch_variable(length);
+}
+",
+ )
+ .unwrap_err();
+ assert!(
+ error.contains("the operand array 'operands' as a value is the field's offset"),
+ "{error}"
+ );
+}
+
+#[test]
+fn a_handler_cannot_use_its_operand_array_in_a_condition() {
+ let error = compile(
+ "
+handler Check(
+ operands_count: u8,
+ operands: Operand[]
+) {
+ if operands != 0 {
+ values[0] = Value<Undefined>;
+ }
+ let mut count: u32;
+ load8(count, [pb, pc, operands_count]);
+ let length: u32 = 3 + count;
+ dispatch_variable(length);
+}
+",
+ )
+ .unwrap_err();
+ assert!(
+ error.contains("the operand array 'operands' as a value is the field's offset"),
+ "{error}"
+ );
+}
+
+#[test]
+fn an_inline_function_cannot_use_an_operand_array_parameter_in_a_condition() {
+ let error = compile(&format!(
+ "
+inline fn first_operand(operands: Operand[]) -> u32 {{
+ assert(operands != null);
+ let indices = &operands;
+ u32(indices[0])
+}}
+{CHECK_HANDLER}"
+ ))
+ .unwrap_err();
+ assert!(
+ error.contains("'first_operand' uses its parameter for the operand array 'operands' as a value"),
+ "{error}"
+ );
+}