blob: 728d43faabd835903be6fbfa0127a9f592554488 [file] [edit]
// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:cfg/ir/constant_value.dart';
import 'package:cfg/ir/functions.dart';
import 'package:cfg/ir/global_context.dart';
import 'package:cfg/ir/instructions.dart' show FfiType;
import 'package:kernel/ast.dart' as ast;
import 'package:kernel/core_types.dart' show CoreTypes;
import 'package:kernel/library_index.dart' show LibraryIndex;
import 'package:vm/modular/transformations/pragma.dart';
import 'package:vm/modular/transformations/ffi/abi.dart' as ffi_abi;
/// Native signature of an FFI call.
typedef FfiSignature = ({
List<FfiType> argumentTypes,
FfiType returnType,
bool isLeaf,
});
/// Collection of utilities to recognize dart:ffi classes, types and annotations.
class FfiUtils {
final CoreTypes coreTypes;
final LibraryIndex index;
FfiUtils()
: coreTypes = GlobalContext.instance.coreTypes,
index = GlobalContext.instance.coreLibraries;
late final ast.Library _ffiLibrary = index.getLibrary('dart:ffi');
late final ast.Class _ffiNativeClass = index.getClass('dart:ffi', 'Native');
late final ast.Class _ffiStructClass = index.getClass('dart:ffi', 'Struct');
late final ast.Class _ffiUnionClass = index.getClass('dart:ffi', 'Union');
late final ast.Class _ffiAbiSpecificIntegerClass = index.getClass(
'dart:ffi',
'AbiSpecificInteger',
);
late final ast.Class _ffiAbiSpecificIntegerMappingClass = index.getClass(
'dart:ffi',
'AbiSpecificIntegerMapping',
);
late final ast.Field _ffiNativeSymbolField = index.getField(
'dart:ffi',
'Native',
'symbol',
);
late final ast.Field _ffiNativeAssetIdField = index.getField(
'dart:ffi',
'Native',
'assetId',
);
late final ast.Field _ffiNativeIsLeafField = index.getField(
'dart:ffi',
'Native',
'isLeaf',
);
late final ast.Class _ffiCallClass = index.getClass('dart:ffi', '_FfiCall');
late final ast.Field _ffiCallIsLeafField = index.getField(
'dart:ffi',
'_FfiCall',
'isLeaf',
);
/// Constant corresponding to the target [ffi_abi.Abi]
/// (value of the `Abi.<target>` static field from dart:ffi).
ast.Constant getAbiConstant(ffi_abi.Abi abi) =>
(index.getField('dart:ffi', 'Abi', ffi_abi.abiNames[abi]!).initializer
as ast.ConstantExpression)
.constant;
/// Returns options of the pragma [pragmaName] if options is an instance of [optionsClass].
ast.InstanceConstant? _getPragmaOptionsOfClass(
ast.Annotatable node,
String pragmaName,
ast.Class optionsClass,
) {
final options = node.getPragmaOptions(pragmaName, coreTypes);
if (options is ast.InstanceConstant && options.classNode == optionsClass) {
return options;
}
return null;
}
/// Returns `Native` constant from the 'vm:ffi:native' pragma
/// of [member], added by the FFI kernel transformation.
ast.InstanceConstant? getFfiNativePragma(ast.Member member) =>
_getPragmaOptionsOfClass(member, vmFfiNative, _ffiNativeClass);
/// Returns `_FfiCall` constant from the 'vm:ffi:call-closure' pragma
/// of [localFunction], added by the FFI kernel transformation
/// to the closures created for `Pointer.asFunction` and
/// `DynamicLibrary.lookupFunction`.
ast.InstanceConstant? getFfiCallClosurePragma(
ast.LocalFunction localFunction,
) => localFunction is ast.FunctionDeclaration
? _getPragmaOptionsOfClass(
localFunction.variable,
vmFfiCallClosure,
_ffiCallClass,
)
: null;
/// Returns true if [function] is a closure performing FFI call
/// (annotated with 'vm:ffi:call-closure' pragma).
bool isFfiCallClosure(CFunction function) =>
function is LocalFunction &&
getFfiCallClosurePragma(function.localFunction) != null;
/// Returns native integer type of the AbiSpecificInteger subclass [cls]
/// for the target ABI.
ast.Class? getAbiSpecificIntegerMapping(
ast.Class cls,
ffi_abi.Abi targetAbi,
) {
// TODO: consider using '@pragma('vm:ffi:abi-specific-mapping', ...) instead of
// '@AbiSpecificIntegerMapping(...)' as TFA removes AbiSpecificIntegerMapping annotations.
final targetAbiConstant = getAbiConstant(targetAbi);
for (final annotation in cls.annotations) {
if (annotation
case ast.ConstantExpression(constant: ast.InstanceConstant constant)
when constant.classNode == _ffiAbiSpecificIntegerMappingClass) {
final mapping = constant.fieldValues.values.single;
if (mapping is! ast.MapConstant) {
return null;
}
for (final entry in mapping.entries) {
if (entry.key == targetAbiConstant) {
final value = entry.value;
return (value is ast.InstanceConstant) ? value.classNode : null;
}
}
}
}
return null;
}
/// Returns [FfiType] corresponding to the given native type [cls],
/// or `null` if native type is not supported.
FfiType? getFfiType(
ast.Class cls,
ffi_abi.Abi targetAbi, {
bool allowAbiSpecific = true,
}) {
if (cls.enclosingLibrary == _ffiLibrary) {
final type = switch (cls.name) {
'Int8' => FfiType.int8,
'Int16' => FfiType.int16,
'Int32' => FfiType.int32,
'Int64' => FfiType.int64,
'Uint8' => FfiType.uint8,
'Uint16' => FfiType.uint16,
'Uint32' => FfiType.uint32,
'Uint64' => FfiType.uint64,
'Float' => FfiType.float32,
'Double' => FfiType.float64,
'Bool' => FfiType.boolean,
'Pointer' => FfiType.pointer,
'Handle' => FfiType.handle,
'Array' || '_Compound' => FfiType.compound,
'Void' => FfiType.voidType,
_ => null,
};
if (type != null) {
return type;
}
}
final superclass = cls.superclass;
if (superclass == _ffiStructClass || superclass == _ffiUnionClass) {
return FfiType.compound;
}
if (allowAbiSpecific && superclass == _ffiAbiSpecificIntegerClass) {
final mappedClass = getAbiSpecificIntegerMapping(cls, targetAbi);
if (mappedClass != null) {
final type = getFfiType(
mappedClass,
targetAbi,
allowAbiSpecific: false,
);
switch (type) {
case .int8 ||
.int16 ||
.int32 ||
.int64 ||
.uint8 ||
.uint16 ||
.uint32 ||
.uint64:
return type;
default:
return null;
}
}
}
return null;
}
/// Collect native signature for FFI call performed by FFI native function [function].
FfiSignature getFfiNativeSignature(
CFunction function,
ffi_abi.Abi targetAbi,
) {
final native = getFfiNativePragma(function.member)!;
final isLeaf =
(native.fieldValues[_ffiNativeIsLeafField.fieldReference]
as ast.BoolConstant)
.value;
return _getFfiSignature(
function,
native.typeArguments.single,
isLeaf,
targetAbi,
);
}
/// Collect native signature for FFI call performed by FFI call
/// closure [function] (annotated with 'vm:ffi:call-closure' pragma).
FfiSignature getFfiCallClosureSignature(
LocalFunction function,
ffi_abi.Abi targetAbi,
) {
final ffiCall = getFfiCallClosurePragma(function.localFunction)!;
final isLeaf =
(ffiCall.fieldValues[_ffiCallIsLeafField.fieldReference]
as ast.BoolConstant)
.value;
return _getFfiSignature(
function,
ffiCall.typeArguments.single,
isLeaf,
targetAbi,
);
}
/// Translate native function type [nativeType] of the FFI call
/// performed by [function] to [FfiSignature].
FfiSignature _getFfiSignature(
CFunction function,
ast.DartType nativeType,
bool isLeaf,
ffi_abi.Abi targetAbi,
) {
if (nativeType is! ast.FunctionType) {
throw 'Unexpected ffi native type ${nativeType.runtimeType} $nativeType in $function';
}
// TODO: varargs
final numArguments = function.functionNode!.positionalParameters.length;
if (nativeType.positionalParameters.length != numArguments ||
nativeType.namedParameters.isNotEmpty) {
throw 'Mismatch between ffi native type $nativeType and $function';
}
final argumentTypes = <FfiType>[];
for (var i = 0; i < numArguments; ++i) {
final nativeArgType = nativeType.positionalParameters[i];
if (nativeArgType is! ast.InterfaceType) {
throw 'Unexpected ffi argument type ${nativeArgType.runtimeType} $nativeArgType';
}
final type = getFfiType(nativeArgType.classNode, targetAbi);
if (type == null || type == .voidType) {
throw 'Unexpected ffi argument type ${nativeArgType.runtimeType} $nativeArgType';
}
argumentTypes.add(type);
}
final nativeReturnType = nativeType.returnType;
if (nativeReturnType is! ast.InterfaceType) {
throw 'Unexpected ffi return type ${nativeReturnType.runtimeType} $nativeReturnType';
}
final returnType = getFfiType(nativeReturnType.classNode, targetAbi);
if (returnType == null) {
throw 'Unexpected ffi return type ${nativeReturnType.runtimeType} $nativeReturnType';
}
return (
argumentTypes: argumentTypes,
returnType: returnType,
isLeaf: isLeaf,
);
}
/// Collect information used to resolve FFI native function or variable
/// described by [nativeAnnotation] (constant instance of `Native` class from dart:ffi).
({String symbol, String assetId, int numArguments}) getFfiNativeResolverArgs(
ConstantValue nativeAnnotation,
) {
final native = nativeAnnotation.constant as ast.InstanceConstant;
assert(native.classNode == _ffiNativeClass);
final symbol =
(native.fieldValues[_ffiNativeSymbolField.fieldReference]
as ast.StringConstant)
.value;
final assetId =
(native.fieldValues[_ffiNativeAssetIdField.fieldReference]
as ast.StringConstant)
.value;
final nativeType = native.typeArguments.single;
final numArguments = (nativeType is ast.FunctionType)
? nativeType.positionalParameters.length
: 0;
return (symbol: symbol, assetId: assetId, numArguments: numArguments);
}
}