From 1fcbb7b45d4f6e4d7ad130823ea19049ef15b65d Mon Sep 17 00:00:00 2001 From: Osei Fortune Date: Tue, 1 Dec 2026 20:29:14 -0400 Subject: [PATCH] perf(classic): V8 fast API overloads for WinRT methods with simple signatures Static and instance methods whose in-params are Int32, UInt32, Single, Double, Boolean, String or a runtime class or interface, and whose result is void, a boolean or a number, get a fast API overload built from metadata. Optimized callers skip the generic argument marshalling: strings pass as fast-pass references, objects are queried through the wrapper's interface cache, and the call goes through the register trampolines Win32 binds already use. Other methods, and calls with a different argument count, take the existing callback. --- runtime/src/lib.rs | 39 ++++- runtime/src/method_call.rs | 24 ++++ runtime/src/win32_call.rs | 4 +- runtime/src/winrt_fast.rs | 282 +++++++++++++++++++++++++++++++++++++ 4 files changed, 340 insertions(+), 9 deletions(-) create mode 100644 runtime/src/winrt_fast.rs diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 02a5fdf..8cd5f5f 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -67,6 +67,8 @@ pub(crate) mod win32_callback; #[cfg(feature = "classic")] pub(crate) mod win32_fast; #[cfg(feature = "classic")] +pub(crate) mod winrt_fast; +#[cfg(feature = "classic")] pub(crate) mod win32_known_fns; mod websocket; mod winhttp; @@ -1426,6 +1428,9 @@ pub(crate) struct DeclarationFFI { pub(crate) prepared_method: std::cell::OnceCell, #[cfg(feature = "classic")] pub(crate) prepared_property: std::cell::OnceCell, + /// Method callbacks with a simple signature: the V8 fast API overload's plan. + #[cfg(feature = "classic")] + pub(crate) fast: Option>, } unsafe impl Sync for DeclarationFFI {} @@ -1444,6 +1449,7 @@ impl DeclarationFFI { qi: crate::method_call::QiCache::new(), prepared_method: std::cell::OnceCell::new(), prepared_property: std::cell::OnceCell::new(), + fast: None, } } @@ -1461,6 +1467,7 @@ impl DeclarationFFI { qi: crate::method_call::QiCache::new(), prepared_method: std::cell::OnceCell::new(), prepared_property: std::cell::OnceCell::new(), + fast: None, } } @@ -4317,7 +4324,7 @@ fn create_ns_ctor_instance_object<'a>( let name = v8::String::new(scope, method_name.as_str()); - let declaration = DeclarationFFI::new_with_instance( + let mut declaration = DeclarationFFI::new_with_instance( Arc::new(RwLock::new(method.clone())), if is_static { factory.clone() @@ -4325,6 +4332,10 @@ fn create_ns_ctor_instance_object<'a>( instance.clone() }, ); + // Optimized callers of a simple signature skip the generic marshalling. + let fast = crate::winrt_fast::plan(method, !is_static); + let cfn = fast.as_ref().map(|f| crate::winrt_fast::cfunction(f)); + declaration.fast = fast.map(std::rc::Rc::new); let declaration = Box::into_raw(Box::new(declaration)); @@ -4409,9 +4420,11 @@ fn create_ns_ctor_instance_object<'a>( retval.set(v); } - let func = FunctionTemplate::builder_raw(callback) - .data(ext.into()) - .build(scope); + let builder = FunctionTemplate::builder_raw(callback).data(ext.into()); + let func = match cfn { + Some(cfn) => builder.build_fast(scope, &[cfn]), + None => builder.build(scope), + }; if is_static { tmpl.set_with_attr( @@ -7049,8 +7062,17 @@ fn create_ns_ctor_object<'a>( .collect(); let func = if let [dec] = decs.as_slice() { + // Optimized callers of a simple signature skip the generic marshalling. + let fast = { + let lock = unsafe { &**dec }.read(); + lock.as_any() + .downcast_ref::() + .and_then(|method| crate::winrt_fast::plan(method, false)) + }; + let cfn = fast.as_ref().map(|f| crate::winrt_fast::cfunction(f)); + unsafe { (**dec).fast = fast.map(std::rc::Rc::new) }; let ext = v8::External::new(scope, *dec as _); - v8::FunctionTemplate::builder( + let builder = v8::FunctionTemplate::builder( |scope: &mut v8::PinScope<'_, '_>, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue| { @@ -7059,8 +7081,11 @@ fn create_ns_ctor_object<'a>( call_static_method(scope, &args, &mut retval, dec); }, ) - .data(ext.into()) - .build(scope) + .data(ext.into()); + match cfn { + Some(cfn) => builder.build_fast(scope, &[cfn]), + None => builder.build(scope), + } } else { let ext = v8::External::new(scope, Box::into_raw(Box::new(decs)) as _); v8::FunctionTemplate::builder( diff --git a/runtime/src/method_call.rs b/runtime/src/method_call.rs index 249e6ab..859f3eb 100644 --- a/runtime/src/method_call.rs +++ b/runtime/src/method_call.rs @@ -370,6 +370,30 @@ pub(crate) struct PreparedCall { is_initializer: bool, } +impl MethodCall { + pub(crate) fn raw_interface(&self) -> *mut c_void { + self.interface.as_raw() + } + + pub(crate) fn vtable_func(&self) -> *mut c_void { + self.func + } + + pub(crate) fn init_failed(&self) -> bool { + self.init_error.is_some() + } +} + +impl PreparedCall { + pub(crate) fn raw_interface(&self) -> *mut c_void { + self.interface.as_raw() + } + + pub(crate) fn func(&self) -> *mut c_void { + self.func + } +} + impl MethodCall { /// Static info for a method already seen on this thread, if any. fn cached_static_info( diff --git a/runtime/src/win32_call.rs b/runtime/src/win32_call.rs index 3169a8f..e946c9c 100644 --- a/runtime/src/win32_call.rs +++ b/runtime/src/win32_call.rs @@ -345,7 +345,7 @@ impl Prepared { // x64: a variadic call puts floats at positions 1 to 3 in both the integer and XMM register, // so one type fits any callee; position 0 is fixed and needs two variants. #[cfg(target_arch = "x86_64")] -unsafe fn call_registers(address: usize, args: &[Kind], words: &[u64], float_ret: bool) -> u64 { +pub(crate) unsafe fn call_registers(address: usize, args: &[Kind], words: &[u64], float_ret: bool) -> u64 { type IntInt = unsafe extern "C" fn(i64, ...) -> i64; type IntFloat = unsafe extern "C" fn(i64, ...) -> f64; type FloatInt = unsafe extern "C" fn(f64, ...) -> i64; @@ -381,7 +381,7 @@ unsafe fn call_registers(address: usize, args: &[Kind], words: &[u64], float_ret // arm64: X0-X7 and D0-D7 are separate, so one type taking both covers every signature. #[cfg(target_arch = "aarch64")] -unsafe fn call_registers(address: usize, args: &[Kind], words: &[u64], float_ret: bool) -> u64 { +pub(crate) unsafe fn call_registers(address: usize, args: &[Kind], words: &[u64], float_ret: bool) -> u64 { type IntFn = unsafe extern "C" fn( i64, i64, diff --git a/runtime/src/winrt_fast.rs b/runtime/src/winrt_fast.rs new file mode 100644 index 0000000..7cda9df --- /dev/null +++ b/runtime/src/winrt_fast.rs @@ -0,0 +1,282 @@ +//! V8 fast API overloads for WinRT methods (static and instance) with simple signatures: +//! numbers, booleans, strings and runtime objects in, a number, boolean or nothing out. +//! +//! The overload has no fallback, so a method qualifies only when every parameter is one of +//! those, decided from metadata when the function template is built. + +use crate::method_call::{MethodCall, PointerPlan}; +use crate::value::{ffi_parse_query_interface_arg, StringRef}; +use crate::win32_call::{call_registers, Kind, MAX_ARGS}; +use crate::DeclarationFFI; +use metadata::declarations::method_declaration::MethodDeclaration; +use metadata::declarations::parameter_declaration::ParameterDeclaration; +use metadata::signature::Signature; +use smallvec::SmallVec; +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::{Mutex, OnceLock}; +use v8::fast_api::{CFunction, CFunctionInfo, CTypeInfo, FastApiCallbackOptions, Int64Representation, Type as CType}; +use windows::core::GUID; + +#[derive(Clone, Copy)] +enum Param { + Number(Kind), + Bool, + Str, + Object(GUID), +} + +#[derive(Clone, Copy, PartialEq)] +enum Ret { + Void, + Bool, + I32, + U32, + F32, + F64, +} + +impl Ret { + fn ctype(self) -> CType { + match self { + Ret::Void => CType::Void, + Ret::Bool => CType::Bool, + Ret::I32 => CType::Int32, + Ret::U32 => CType::Uint32, + Ret::F32 | Ret::F64 => CType::Float64, + } + } +} + +/// One method's fast path, kept in its `DeclarationFFI`. +pub(crate) struct FastMethod { + /// Called on the receiver (`this`) rather than the class factory. + instance: bool, + params: SmallVec<[Param; 6]>, + kinds: SmallVec<[Kind; MAX_ARGS]>, + ret: Ret, +} + +fn param_of(signature: &str, parameter: &ParameterDeclaration) -> Option { + Some(match signature { + "Int32" => Param::Number(Kind::I32), + "UInt32" => Param::Number(Kind::U32), + "Single" => Param::Number(Kind::F32), + "Double" => Param::Number(Kind::F64), + "Boolean" => Param::Bool, + "String" => Param::Str, + _ => match PointerPlan::for_parameter(signature, parameter, &[], true) { + PointerPlan::Interface(iid) => Param::Object(iid), + _ => return None, + }, + }) +} + +fn ret_of(signature: &str) -> Option { + Some(match signature { + "Void" | "" => Ret::Void, + "Boolean" => Ret::Bool, + "Int32" => Ret::I32, + "UInt32" => Ret::U32, + "Single" => Ret::F32, + "Double" => Ret::F64, + _ => return None, + }) +} + +/// The fast path for `method`, when its signature qualifies. +pub(crate) fn plan(method: &MethodDeclaration, instance: bool) -> Option { + let parameters = method.parameters(); + // The words are `this`, the parameters and the return slot. + if parameters.len() + 2 > MAX_ARGS { + return None; + } + let mut params = SmallVec::new(); + for parameter in parameters.iter() { + if parameter.is_out() { + return None; + } + let metadata = parameter.metadata()?; + let signature = Signature::to_string(metadata, ¶meter.type_()); + params.push(param_of(signature.trim(), parameter)?); + } + let return_type = Signature::to_string(method.metadata()?, &method.return_type()); + let ret = ret_of(return_type.trim())?; + let mut kinds: SmallVec<[Kind; MAX_ARGS]> = SmallVec::new(); + kinds.push(Kind::Pointer); + for p in ¶ms { + kinds.push(match p { + Param::Number(kind) => *kind, + Param::Bool => Kind::U8, + Param::Str | Param::Object(_) => Kind::Pointer, + }); + } + if ret != Ret::Void { + kinds.push(Kind::Pointer); + } + Some(FastMethod { instance, params, kinds, ret }) +} + +struct Info(&'static CFunctionInfo); +unsafe impl Send for Info {} +unsafe impl Sync for Info {} + +fn info(arity: usize, ret: CType) -> &'static CFunctionInfo { + static INFOS: OnceLock>> = OnceLock::new(); + let mut infos = INFOS.get_or_init(Default::default).lock().unwrap(); + infos + .entry((arity, ret as u8)) + .or_insert_with(|| { + let mut types = vec![CType::V8Value.as_info()]; + types.extend((0..arity).map(|_| CType::V8Value.as_info())); + types.push(CType::CallbackOptions.as_info()); + let types: &'static [CTypeInfo] = Box::leak(types.into_boxed_slice()); + Info(Box::leak(Box::new(CFunctionInfo::new(ret.as_info(), types, Int64Representation::Number)))) + }) + .0 +} + +#[inline(always)] +unsafe fn local_from_raw(raw: u64) -> v8::Local<'static, v8::Value> { + unsafe { std::mem::transmute::>(raw) } +} + +fn throw(scope: &mut v8::PinScope<'_, '_>, message: &str) { + if let Some(msg) = v8::String::new(scope, message) { + let err = v8::Exception::error(scope, msg); + scope.throw_exception(err); + } +} + +#[inline(never)] +unsafe fn invoke(recv: u64, opts: *mut FastApiCallbackOptions, raw: &[u64]) -> u64 { + let opts = unsafe { &*opts }; + v8::callback_scope!(unsafe scope, opts); + let ext = unsafe { v8::Local::::cast_unchecked(opts.data) }; + let dec = unsafe { &*(ext.value() as *const DeclarationFFI) }; + let Some(fs) = dec.fast.as_deref() else { return 0 }; + // The interface and vtable slot: the receiver's for an instance method (as the slow + // callback resolves them), else the static call prepared on the class factory. + let _call: Option; + let (interface, func) = if fs.instance { + let lock = dec.read(); + let Some(method) = lock.as_any().downcast_ref::() else { return 0 }; + let recv = unsafe { local_from_raw(recv) }; + let Ok(this) = v8::Local::::try_from(recv) else { + throw(scope, "Illegal invocation"); + return 0; + }; + let Some(call) = crate::ns_proxy::receiver_method_call(scope, this, dec, method, method.is_sealed()) else { + return 0; + }; + drop(lock); + if call.init_failed() { + throw(scope, "The object does not implement this method's interface"); + return 0; + } + let target = (call.raw_interface(), call.vtable_func()); + _call = Some(call); + target + } else { + _call = None; + let prepared = match dec.prepared_method.get() { + Some(p) => p, + None => { + let lock = dec.read(); + let Some(method) = lock.as_any().downcast_ref::() else { return 0 }; + let factory = match crate::resolve_class_factory_from_parent(dec) { + Ok(f) => f, + Err(e) => { + throw(scope, &format!("Failed to resolve WinRT static method factory: {}", e.message())); + return 0; + } + }; + let Some(prepared) = MethodCall::prepare(method, method.is_sealed(), factory, false) else { + throw(scope, "Failed to prepare WinRT static method"); + return 0; + }; + drop(lock); + let _ = dec.prepared_method.set(prepared); + dec.prepared_method.get().unwrap() + } + }; + (prepared.raw_interface(), prepared.func()) + }; + let mut words = [0u64; MAX_ARGS]; + words[0] = interface as u64; + let mut refs: SmallVec<[StringRef; 2]> = SmallVec::with_capacity(fs.params.len()); + let mut guards: SmallVec<[windows::core::IUnknown; 2]> = SmallVec::new(); + for (i, p) in fs.params.iter().enumerate() { + let v = unsafe { local_from_raw(raw[i]) }; + words[i + 1] = match p { + Param::Number(kind) => kind.word_from_f64(v.number_value(scope).unwrap_or(0.0)), + Param::Bool => v.boolean_value(scope) as u64, + Param::Str => { + let Some(s) = v.to_string(scope) else { return 0 }; + refs.push(StringRef::default()); + refs.last_mut().unwrap().reference(scope, s) as u64 + } + Param::Object(iid) => match ffi_parse_query_interface_arg(scope, v, iid) { + Ok((nv, guard)) => { + guards.extend(guard); + unsafe { nv.pointer as u64 } + } + Err(e) => { + throw(scope, &format!("argument {}: {e}", i + 1)); + return 0; + } + }, + }; + } + let mut out = 0u64; + let arity = fs.kinds.len(); + if fs.ret != Ret::Void { + words[arity - 1] = &mut out as *mut u64 as u64; + } + let hr = unsafe { call_registers(func as usize, &fs.kinds, &words[..arity], false) } as i32; + drop(guards); + if hr < 0 { + throw(scope, &crate::error::format_hresult_message(windows::core::HRESULT(hr))); + return 0; + } + match fs.ret { + Ret::Void => 0, + Ret::Bool => (out as u8 != 0) as u64, + Ret::I32 | Ret::U32 => out as u32 as u64, + Ret::F32 => (f32::from_bits(out as u32) as f64).to_bits(), + Ret::F64 => out, + } +} + +macro_rules! trampolines { + ($($int:ident, $float:ident ($($a:ident),*);)*) => { + $( + unsafe extern "C" fn $int(recv: u64, $($a: u64,)* opts: *mut FastApiCallbackOptions) -> u64 { + unsafe { invoke(recv, opts, &[$($a),*]) } + } + unsafe extern "C" fn $float(recv: u64, $($a: u64,)* opts: *mut FastApiCallbackOptions) -> f64 { + f64::from_bits(unsafe { invoke(recv, opts, &[$($a),*]) }) + } + )* + const INT: [*const c_void; 7] = [$($int as *const c_void),*]; + const FLOAT: [*const c_void; 7] = [$($float as *const c_void),*]; + }; +} + +trampolines! { + int0, float0 (); + int1, float1 (a); + int2, float2 (a, b); + int3, float3 (a, b, c); + int4, float4 (a, b, c, d); + int5, float5 (a, b, c, d, e); + int6, float6 (a, b, c, d, e, f); +} + +/// The fast overload for a planned method; the template's data stays its `DeclarationFFI`. +pub(crate) fn cfunction(fs: &FastMethod) -> CFunction { + let arity = fs.params.len(); + let ret = fs.ret.ctype(); + let address = if matches!(ret, CType::Float64) { FLOAT[arity] } else { INT[arity] }; + CFunction::new(address, info(arity, ret)) +}