2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2022-12-12 09:14:20 -05:00
|
|
|
|
|
|
|
use crate::symbol::NativeType;
|
|
|
|
use crate::FfiPermissions;
|
|
|
|
use crate::ForeignFunction;
|
2023-09-27 09:54:43 -04:00
|
|
|
use deno_core::op2;
|
2022-12-12 09:14:20 -05:00
|
|
|
use deno_core::v8;
|
2023-12-11 22:10:33 -05:00
|
|
|
use deno_core::v8::TryCatch;
|
2022-12-12 09:14:20 -05:00
|
|
|
use deno_core::CancelFuture;
|
|
|
|
use deno_core::CancelHandle;
|
|
|
|
use deno_core::OpState;
|
|
|
|
use deno_core::Resource;
|
|
|
|
use deno_core::ResourceId;
|
2023-12-11 22:10:33 -05:00
|
|
|
use deno_core::V8CrossThreadTaskSpawner;
|
2022-12-12 09:14:20 -05:00
|
|
|
use libffi::middle::Cif;
|
|
|
|
use serde::Deserialize;
|
|
|
|
use std::borrow::Cow;
|
|
|
|
use std::cell::RefCell;
|
|
|
|
use std::ffi::c_void;
|
|
|
|
use std::future::Future;
|
|
|
|
use std::future::IntoFuture;
|
|
|
|
use std::pin::Pin;
|
|
|
|
use std::ptr;
|
|
|
|
use std::ptr::NonNull;
|
|
|
|
use std::rc::Rc;
|
2023-05-07 06:31:01 -04:00
|
|
|
use std::sync::atomic;
|
|
|
|
use std::sync::atomic::AtomicU32;
|
2022-12-12 09:14:20 -05:00
|
|
|
use std::task::Poll;
|
2023-05-07 06:31:01 -04:00
|
|
|
|
|
|
|
static THREAD_ID_COUNTER: AtomicU32 = AtomicU32::new(1);
|
|
|
|
|
|
|
|
thread_local! {
|
2024-04-10 18:08:23 -04:00
|
|
|
static LOCAL_THREAD_ID: RefCell<u32> = const { RefCell::new(0) };
|
2023-05-07 06:31:01 -04:00
|
|
|
}
|
|
|
|
|
2024-10-14 18:05:49 -04:00
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
|
|
pub enum CallbackError {
|
|
|
|
#[error(transparent)]
|
|
|
|
Resource(deno_core::error::AnyError),
|
|
|
|
#[error(transparent)]
|
2024-11-04 12:17:21 -05:00
|
|
|
Permission(#[from] deno_permissions::PermissionCheckError),
|
2024-10-14 18:05:49 -04:00
|
|
|
#[error(transparent)]
|
|
|
|
Other(deno_core::error::AnyError),
|
|
|
|
}
|
|
|
|
|
2022-12-12 09:14:20 -05:00
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct PtrSymbol {
|
|
|
|
pub cif: libffi::middle::Cif,
|
|
|
|
pub ptr: libffi::middle::CodePtr,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PtrSymbol {
|
2023-02-22 12:32:38 -05:00
|
|
|
pub fn new(
|
|
|
|
fn_ptr: *mut c_void,
|
|
|
|
def: &ForeignFunction,
|
2024-10-14 18:05:49 -04:00
|
|
|
) -> Result<Self, CallbackError> {
|
2022-12-12 09:14:20 -05:00
|
|
|
let ptr = libffi::middle::CodePtr::from_ptr(fn_ptr as _);
|
|
|
|
let cif = libffi::middle::Cif::new(
|
|
|
|
def
|
|
|
|
.parameters
|
|
|
|
.clone()
|
|
|
|
.into_iter()
|
2023-01-21 10:51:14 -05:00
|
|
|
.map(libffi::middle::Type::try_from)
|
2024-10-14 18:05:49 -04:00
|
|
|
.collect::<Result<Vec<_>, _>>()
|
|
|
|
.map_err(CallbackError::Other)?,
|
|
|
|
def
|
|
|
|
.result
|
|
|
|
.clone()
|
|
|
|
.try_into()
|
|
|
|
.map_err(CallbackError::Other)?,
|
2022-12-12 09:14:20 -05:00
|
|
|
);
|
|
|
|
|
2023-01-21 10:51:14 -05:00
|
|
|
Ok(Self { cif, ptr })
|
2022-12-12 09:14:20 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[allow(clippy::non_send_fields_in_send_ty)]
|
|
|
|
// SAFETY: unsafe trait must have unsafe implementation
|
|
|
|
unsafe impl Send for PtrSymbol {}
|
|
|
|
// SAFETY: unsafe trait must have unsafe implementation
|
|
|
|
unsafe impl Sync for PtrSymbol {}
|
|
|
|
|
|
|
|
struct UnsafeCallbackResource {
|
|
|
|
cancel: Rc<CancelHandle>,
|
|
|
|
// Closure is never directly touched, but it keeps the C callback alive
|
|
|
|
// until `close()` method is called.
|
|
|
|
#[allow(dead_code)]
|
|
|
|
closure: libffi::middle::Closure<'static>,
|
|
|
|
info: *mut CallbackInfo,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Resource for UnsafeCallbackResource {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"unsafecallback".into()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
self.cancel.cancel();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct CallbackInfo {
|
2023-12-11 22:10:33 -05:00
|
|
|
pub async_work_sender: V8CrossThreadTaskSpawner,
|
2022-12-12 09:14:20 -05:00
|
|
|
pub callback: NonNull<v8::Function>,
|
|
|
|
pub context: NonNull<v8::Context>,
|
2023-05-08 03:57:38 -04:00
|
|
|
pub parameters: Box<[NativeType]>,
|
2023-05-07 06:31:01 -04:00
|
|
|
pub result: NativeType,
|
|
|
|
pub thread_id: u32,
|
2022-12-12 09:14:20 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Future for CallbackInfo {
|
|
|
|
type Output = ();
|
|
|
|
fn poll(
|
2023-06-07 17:50:14 -04:00
|
|
|
self: Pin<&mut Self>,
|
|
|
|
_cx: &mut std::task::Context<'_>,
|
2022-12-12 09:14:20 -05:00
|
|
|
) -> std::task::Poll<Self::Output> {
|
|
|
|
// The future for the CallbackInfo never resolves: It can only be canceled.
|
|
|
|
Poll::Pending
|
|
|
|
}
|
|
|
|
}
|
2023-06-07 17:50:14 -04:00
|
|
|
|
2023-12-11 22:10:33 -05:00
|
|
|
struct TaskArgs {
|
|
|
|
cif: NonNull<libffi::low::ffi_cif>,
|
|
|
|
result: NonNull<c_void>,
|
|
|
|
args: *const *const c_void,
|
|
|
|
info: NonNull<CallbackInfo>,
|
|
|
|
}
|
|
|
|
|
|
|
|
// SAFETY: we know these are valid Send-safe pointers as they are for FFI
|
|
|
|
unsafe impl Send for TaskArgs {}
|
|
|
|
|
|
|
|
impl TaskArgs {
|
|
|
|
fn run(&mut self, scope: &mut v8::HandleScope) {
|
|
|
|
// SAFETY: making a call using Send-safe pointers turned back into references. We know the
|
|
|
|
// lifetime of these will last because we block on the result of the spawn call.
|
|
|
|
unsafe {
|
|
|
|
do_ffi_callback(
|
|
|
|
scope,
|
|
|
|
self.cif.as_ref(),
|
|
|
|
self.info.as_ref(),
|
|
|
|
self.result.as_mut(),
|
|
|
|
self.args,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-12 09:14:20 -05:00
|
|
|
unsafe extern "C" fn deno_ffi_callback(
|
2023-01-07 22:58:10 -05:00
|
|
|
cif: &libffi::low::ffi_cif,
|
2022-12-12 09:14:20 -05:00
|
|
|
result: &mut c_void,
|
|
|
|
args: *const *const c_void,
|
|
|
|
info: &CallbackInfo,
|
|
|
|
) {
|
2023-05-07 06:31:01 -04:00
|
|
|
LOCAL_THREAD_ID.with(|s| {
|
|
|
|
if *s.borrow() == info.thread_id {
|
2023-12-11 22:10:33 -05:00
|
|
|
// Call from main thread. If this callback is being triggered due to a
|
|
|
|
// function call coming from Deno itself, then this callback will build
|
|
|
|
// ontop of that stack.
|
|
|
|
// If this callback is being triggered outside of Deno (for example from a
|
|
|
|
// signal handler) then this will either create an empty new stack if
|
|
|
|
// Deno currently has nothing running and is waiting for promises to resolve,
|
|
|
|
// or will (very incorrectly) build ontop of whatever stack exists.
|
|
|
|
// The callback will even be called through from a `while (true)` liveloop, but
|
|
|
|
// it somehow cannot change the values that the loop sees, even if they both
|
|
|
|
// refer the same `let bool_value`.
|
|
|
|
let context: NonNull<v8::Context> = info.context;
|
|
|
|
let context = std::mem::transmute::<
|
|
|
|
NonNull<v8::Context>,
|
|
|
|
v8::Local<v8::Context>,
|
|
|
|
>(context);
|
|
|
|
let mut cb_scope = v8::CallbackScope::new(context);
|
|
|
|
let scope = &mut v8::HandleScope::new(&mut cb_scope);
|
|
|
|
|
|
|
|
do_ffi_callback(scope, cif, info, result, args);
|
2022-12-12 09:14:20 -05:00
|
|
|
} else {
|
|
|
|
let async_work_sender = &info.async_work_sender;
|
2023-12-11 22:10:33 -05:00
|
|
|
|
|
|
|
let mut args = TaskArgs {
|
|
|
|
cif: NonNull::from(cif),
|
|
|
|
result: NonNull::from(result),
|
|
|
|
args,
|
|
|
|
info: NonNull::from(info),
|
|
|
|
};
|
|
|
|
|
|
|
|
async_work_sender.spawn_blocking(move |scope| {
|
|
|
|
// We don't have a lot of choice here, so just print an unhandled exception message
|
|
|
|
let tc_scope = &mut TryCatch::new(scope);
|
|
|
|
args.run(tc_scope);
|
|
|
|
if tc_scope.exception().is_some() {
|
2024-09-04 03:23:19 -04:00
|
|
|
log::error!("Illegal unhandled exception in nonblocking callback");
|
2023-12-11 22:10:33 -05:00
|
|
|
}
|
2022-12-12 09:14:20 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn do_ffi_callback(
|
2023-12-11 22:10:33 -05:00
|
|
|
scope: &mut v8::HandleScope,
|
2023-01-07 22:58:10 -05:00
|
|
|
cif: &libffi::low::ffi_cif,
|
2022-12-12 09:14:20 -05:00
|
|
|
info: &CallbackInfo,
|
|
|
|
result: &mut c_void,
|
|
|
|
args: *const *const c_void,
|
|
|
|
) {
|
|
|
|
let callback: NonNull<v8::Function> = info.callback;
|
2023-05-07 06:31:01 -04:00
|
|
|
let func = std::mem::transmute::<
|
|
|
|
NonNull<v8::Function>,
|
|
|
|
v8::Local<v8::Function>,
|
|
|
|
>(callback);
|
2022-12-12 09:14:20 -05:00
|
|
|
let result = result as *mut c_void;
|
|
|
|
let vals: &[*const c_void] =
|
2022-12-17 17:20:15 -05:00
|
|
|
std::slice::from_raw_parts(args, info.parameters.len());
|
2023-01-07 22:58:10 -05:00
|
|
|
let arg_types = std::slice::from_raw_parts(cif.arg_types, cif.nargs as usize);
|
2022-12-12 09:14:20 -05:00
|
|
|
|
|
|
|
let mut params: Vec<v8::Local<v8::Value>> = vec![];
|
2023-01-07 22:58:10 -05:00
|
|
|
for ((index, native_type), val) in
|
|
|
|
info.parameters.iter().enumerate().zip(vals)
|
|
|
|
{
|
2022-12-12 09:14:20 -05:00
|
|
|
let value: v8::Local<v8::Value> = match native_type {
|
|
|
|
NativeType::Bool => {
|
|
|
|
let value = *((*val) as *const bool);
|
|
|
|
v8::Boolean::new(scope, value).into()
|
|
|
|
}
|
|
|
|
NativeType::F32 => {
|
|
|
|
let value = *((*val) as *const f32);
|
|
|
|
v8::Number::new(scope, value as f64).into()
|
|
|
|
}
|
|
|
|
NativeType::F64 => {
|
|
|
|
let value = *((*val) as *const f64);
|
|
|
|
v8::Number::new(scope, value).into()
|
|
|
|
}
|
|
|
|
NativeType::I8 => {
|
|
|
|
let value = *((*val) as *const i8);
|
|
|
|
v8::Integer::new(scope, value as i32).into()
|
|
|
|
}
|
|
|
|
NativeType::U8 => {
|
|
|
|
let value = *((*val) as *const u8);
|
|
|
|
v8::Integer::new_from_unsigned(scope, value as u32).into()
|
|
|
|
}
|
|
|
|
NativeType::I16 => {
|
|
|
|
let value = *((*val) as *const i16);
|
|
|
|
v8::Integer::new(scope, value as i32).into()
|
|
|
|
}
|
|
|
|
NativeType::U16 => {
|
|
|
|
let value = *((*val) as *const u16);
|
|
|
|
v8::Integer::new_from_unsigned(scope, value as u32).into()
|
|
|
|
}
|
|
|
|
NativeType::I32 => {
|
|
|
|
let value = *((*val) as *const i32);
|
|
|
|
v8::Integer::new(scope, value).into()
|
|
|
|
}
|
|
|
|
NativeType::U32 => {
|
|
|
|
let value = *((*val) as *const u32);
|
|
|
|
v8::Integer::new_from_unsigned(scope, value).into()
|
|
|
|
}
|
|
|
|
NativeType::I64 | NativeType::ISize => {
|
|
|
|
let result = *((*val) as *const i64);
|
BREAKING(ffi/unstable): always return u64 as bigint (#23981)
The mixed `number | bigint` representation was useful optimization for
pointers. Now, pointers are represented as V8 externals. As part of the
FFI stabilization effort we want to make `bigint` the only
representation for `u64` and `i64`.
BigInt representation performance is almost on par with mixed
representation with the added benefit that its less confusing and users
don't need manual checks and conversions for doing operations on the
value.
```
cpu: AMD Ryzen 5 7530U with Radeon Graphics
runtime: deno 1.43.6+92a8d09 (x86_64-unknown-linux-gnu)
file:///home/divy/gh/ffi/main.ts
benchmark time (avg) iter/s (min … max) p75 p99 p995
-------------------------------------------------------------------------- -----------------------------
nop 4.01 ns/iter 249,533,690.5 (3.97 ns … 10.8 ns) 3.97 ns 4.36 ns 9.03 ns
ret bigint 7.74 ns/iter 129,127,186.8 (7.72 ns … 10.46 ns) 7.72 ns 8.11 ns 8.82 ns
ret i32 7.81 ns/iter 128,087,100.5 (7.77 ns … 12.72 ns) 7.78 ns 8.57 ns 9.75 ns
ret bigint (add op) 15.02 ns/iter 66,588,253.2 (14.64 ns … 24.99 ns) 14.76 ns 19.13 ns 19.44 ns
ret i32 (add op) 12.02 ns/iter 83,209,131.8 (11.95 ns … 18.18 ns) 11.98 ns 13.11 ns 14.5 ns
```
2024-05-28 00:01:09 -04:00
|
|
|
v8::BigInt::new_from_i64(scope, result).into()
|
2022-12-12 09:14:20 -05:00
|
|
|
}
|
|
|
|
NativeType::U64 | NativeType::USize => {
|
|
|
|
let result = *((*val) as *const u64);
|
BREAKING(ffi/unstable): always return u64 as bigint (#23981)
The mixed `number | bigint` representation was useful optimization for
pointers. Now, pointers are represented as V8 externals. As part of the
FFI stabilization effort we want to make `bigint` the only
representation for `u64` and `i64`.
BigInt representation performance is almost on par with mixed
representation with the added benefit that its less confusing and users
don't need manual checks and conversions for doing operations on the
value.
```
cpu: AMD Ryzen 5 7530U with Radeon Graphics
runtime: deno 1.43.6+92a8d09 (x86_64-unknown-linux-gnu)
file:///home/divy/gh/ffi/main.ts
benchmark time (avg) iter/s (min … max) p75 p99 p995
-------------------------------------------------------------------------- -----------------------------
nop 4.01 ns/iter 249,533,690.5 (3.97 ns … 10.8 ns) 3.97 ns 4.36 ns 9.03 ns
ret bigint 7.74 ns/iter 129,127,186.8 (7.72 ns … 10.46 ns) 7.72 ns 8.11 ns 8.82 ns
ret i32 7.81 ns/iter 128,087,100.5 (7.77 ns … 12.72 ns) 7.78 ns 8.57 ns 9.75 ns
ret bigint (add op) 15.02 ns/iter 66,588,253.2 (14.64 ns … 24.99 ns) 14.76 ns 19.13 ns 19.44 ns
ret i32 (add op) 12.02 ns/iter 83,209,131.8 (11.95 ns … 18.18 ns) 11.98 ns 13.11 ns 14.5 ns
```
2024-05-28 00:01:09 -04:00
|
|
|
v8::BigInt::new_from_u64(scope, result).into()
|
2022-12-12 09:14:20 -05:00
|
|
|
}
|
|
|
|
NativeType::Pointer | NativeType::Buffer | NativeType::Function => {
|
2023-02-22 12:32:38 -05:00
|
|
|
let result = *((*val) as *const *mut c_void);
|
|
|
|
if result.is_null() {
|
|
|
|
v8::null(scope).into()
|
2022-12-12 09:14:20 -05:00
|
|
|
} else {
|
2023-02-22 12:32:38 -05:00
|
|
|
v8::External::new(scope, result).into()
|
2022-12-12 09:14:20 -05:00
|
|
|
}
|
|
|
|
}
|
2023-01-07 22:58:10 -05:00
|
|
|
NativeType::Struct(_) => {
|
|
|
|
let size = arg_types[index].as_ref().unwrap().size;
|
|
|
|
let ptr = (*val) as *const u8;
|
|
|
|
let slice = std::slice::from_raw_parts(ptr, size);
|
|
|
|
let boxed = Box::from(slice);
|
|
|
|
let store = v8::ArrayBuffer::new_backing_store_from_boxed_slice(boxed);
|
|
|
|
let ab =
|
|
|
|
v8::ArrayBuffer::with_backing_store(scope, &store.make_shared());
|
|
|
|
let local_value: v8::Local<v8::Value> =
|
|
|
|
v8::Uint8Array::new(scope, ab, 0, ab.byte_length())
|
|
|
|
.unwrap()
|
|
|
|
.into();
|
|
|
|
local_value
|
|
|
|
}
|
2022-12-12 09:14:20 -05:00
|
|
|
NativeType::Void => unreachable!(),
|
|
|
|
};
|
|
|
|
params.push(value);
|
|
|
|
}
|
|
|
|
|
|
|
|
let recv = v8::undefined(scope);
|
|
|
|
let call_result = func.call(scope, recv.into(), ¶ms);
|
|
|
|
|
|
|
|
if call_result.is_none() {
|
|
|
|
// JS function threw an exception. Set the return value to zero and return.
|
|
|
|
// The exception continue propagating up the call chain when the event loop
|
|
|
|
// resumes.
|
|
|
|
match info.result {
|
|
|
|
NativeType::Bool => {
|
|
|
|
*(result as *mut bool) = false;
|
|
|
|
}
|
|
|
|
NativeType::U32 | NativeType::I32 => {
|
|
|
|
// zero is equal for signed and unsigned alike
|
|
|
|
*(result as *mut u32) = 0;
|
|
|
|
}
|
|
|
|
NativeType::F32 => {
|
|
|
|
*(result as *mut f32) = 0.0;
|
|
|
|
}
|
|
|
|
NativeType::F64 => {
|
|
|
|
*(result as *mut f64) = 0.0;
|
|
|
|
}
|
|
|
|
NativeType::U8 | NativeType::I8 => {
|
|
|
|
// zero is equal for signed and unsigned alike
|
|
|
|
*(result as *mut u8) = 0;
|
|
|
|
}
|
|
|
|
NativeType::U16 | NativeType::I16 => {
|
|
|
|
// zero is equal for signed and unsigned alike
|
|
|
|
*(result as *mut u16) = 0;
|
|
|
|
}
|
|
|
|
NativeType::Pointer
|
|
|
|
| NativeType::Buffer
|
|
|
|
| NativeType::Function
|
|
|
|
| NativeType::U64
|
|
|
|
| NativeType::I64 => {
|
|
|
|
*(result as *mut usize) = 0;
|
|
|
|
}
|
|
|
|
NativeType::Void => {
|
|
|
|
// nop
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
unreachable!();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let value = call_result.unwrap();
|
|
|
|
|
|
|
|
match info.result {
|
|
|
|
NativeType::Bool => {
|
|
|
|
let value = if let Ok(value) = v8::Local::<v8::Boolean>::try_from(value) {
|
|
|
|
value.is_true()
|
|
|
|
} else {
|
|
|
|
value.boolean_value(scope)
|
|
|
|
};
|
|
|
|
*(result as *mut bool) = value;
|
|
|
|
}
|
|
|
|
NativeType::F32 => {
|
|
|
|
let value = if let Ok(value) = v8::Local::<v8::Number>::try_from(value) {
|
|
|
|
value.value() as f32
|
|
|
|
} else {
|
|
|
|
// Fallthrough, probably UB.
|
|
|
|
value
|
|
|
|
.number_value(scope)
|
|
|
|
.expect("Unable to deserialize result parameter.") as f32
|
|
|
|
};
|
|
|
|
*(result as *mut f32) = value;
|
|
|
|
}
|
|
|
|
NativeType::F64 => {
|
|
|
|
let value = if let Ok(value) = v8::Local::<v8::Number>::try_from(value) {
|
|
|
|
value.value()
|
|
|
|
} else {
|
|
|
|
// Fallthrough, probably UB.
|
|
|
|
value
|
|
|
|
.number_value(scope)
|
|
|
|
.expect("Unable to deserialize result parameter.")
|
|
|
|
};
|
|
|
|
*(result as *mut f64) = value;
|
|
|
|
}
|
2023-02-22 12:32:38 -05:00
|
|
|
NativeType::Buffer => {
|
|
|
|
let pointer: *mut u8 = if let Ok(value) =
|
2022-12-12 09:14:20 -05:00
|
|
|
v8::Local::<v8::ArrayBufferView>::try_from(value)
|
|
|
|
{
|
|
|
|
let byte_offset = value.byte_offset();
|
2023-02-22 12:32:38 -05:00
|
|
|
let pointer = value
|
2022-12-12 09:14:20 -05:00
|
|
|
.buffer(scope)
|
|
|
|
.expect("Unable to deserialize result parameter.")
|
2023-02-22 12:32:38 -05:00
|
|
|
.data();
|
|
|
|
if let Some(non_null) = pointer {
|
|
|
|
// SAFETY: Pointer is non-null, and V8 guarantees that the byte_offset
|
|
|
|
// is within the buffer backing store.
|
|
|
|
unsafe { non_null.as_ptr().add(byte_offset) as *mut u8 }
|
|
|
|
} else {
|
|
|
|
ptr::null_mut()
|
|
|
|
}
|
2022-12-12 09:14:20 -05:00
|
|
|
} else if let Ok(value) = v8::Local::<v8::ArrayBuffer>::try_from(value) {
|
2023-02-22 12:32:38 -05:00
|
|
|
let pointer = value.data();
|
|
|
|
if let Some(non_null) = pointer {
|
|
|
|
non_null.as_ptr() as *mut u8
|
|
|
|
} else {
|
|
|
|
ptr::null_mut()
|
|
|
|
}
|
2022-12-12 09:14:20 -05:00
|
|
|
} else {
|
2023-02-22 12:32:38 -05:00
|
|
|
ptr::null_mut()
|
2022-12-12 09:14:20 -05:00
|
|
|
};
|
2023-02-22 12:32:38 -05:00
|
|
|
*(result as *mut *mut u8) = pointer;
|
|
|
|
}
|
|
|
|
NativeType::Pointer | NativeType::Function => {
|
|
|
|
let pointer: *mut c_void =
|
|
|
|
if let Ok(external) = v8::Local::<v8::External>::try_from(value) {
|
|
|
|
external.value()
|
|
|
|
} else {
|
|
|
|
// TODO(@aapoalas): Start throwing errors into JS about invalid callback return values.
|
|
|
|
ptr::null_mut()
|
|
|
|
};
|
|
|
|
*(result as *mut *mut c_void) = pointer;
|
2022-12-12 09:14:20 -05:00
|
|
|
}
|
|
|
|
NativeType::I8 => {
|
2023-05-07 10:27:16 -04:00
|
|
|
let value = if let Ok(value) = v8::Local::<v8::Int32>::try_from(value) {
|
2022-12-12 09:14:20 -05:00
|
|
|
value.value() as i8
|
|
|
|
} else {
|
|
|
|
// Fallthrough, essentially UB.
|
|
|
|
value
|
|
|
|
.int32_value(scope)
|
|
|
|
.expect("Unable to deserialize result parameter.") as i8
|
|
|
|
};
|
|
|
|
*(result as *mut i8) = value;
|
|
|
|
}
|
|
|
|
NativeType::U8 => {
|
2023-05-07 10:27:16 -04:00
|
|
|
let value = if let Ok(value) = v8::Local::<v8::Uint32>::try_from(value) {
|
2022-12-12 09:14:20 -05:00
|
|
|
value.value() as u8
|
|
|
|
} else {
|
|
|
|
// Fallthrough, essentially UB.
|
|
|
|
value
|
|
|
|
.uint32_value(scope)
|
|
|
|
.expect("Unable to deserialize result parameter.") as u8
|
|
|
|
};
|
|
|
|
*(result as *mut u8) = value;
|
|
|
|
}
|
|
|
|
NativeType::I16 => {
|
2023-05-07 10:27:16 -04:00
|
|
|
let value = if let Ok(value) = v8::Local::<v8::Int32>::try_from(value) {
|
2022-12-12 09:14:20 -05:00
|
|
|
value.value() as i16
|
|
|
|
} else {
|
|
|
|
// Fallthrough, essentially UB.
|
|
|
|
value
|
|
|
|
.int32_value(scope)
|
|
|
|
.expect("Unable to deserialize result parameter.") as i16
|
|
|
|
};
|
|
|
|
*(result as *mut i16) = value;
|
|
|
|
}
|
|
|
|
NativeType::U16 => {
|
2023-05-07 10:27:16 -04:00
|
|
|
let value = if let Ok(value) = v8::Local::<v8::Uint32>::try_from(value) {
|
2022-12-12 09:14:20 -05:00
|
|
|
value.value() as u16
|
|
|
|
} else {
|
|
|
|
// Fallthrough, essentially UB.
|
|
|
|
value
|
|
|
|
.uint32_value(scope)
|
|
|
|
.expect("Unable to deserialize result parameter.") as u16
|
|
|
|
};
|
|
|
|
*(result as *mut u16) = value;
|
|
|
|
}
|
2023-05-07 10:27:16 -04:00
|
|
|
NativeType::I32 => {
|
|
|
|
let value = if let Ok(value) = v8::Local::<v8::Int32>::try_from(value) {
|
|
|
|
value.value()
|
|
|
|
} else {
|
|
|
|
// Fallthrough, essentially UB.
|
|
|
|
value
|
|
|
|
.int32_value(scope)
|
|
|
|
.expect("Unable to deserialize result parameter.")
|
|
|
|
};
|
|
|
|
*(result as *mut i32) = value;
|
|
|
|
}
|
2022-12-12 09:14:20 -05:00
|
|
|
NativeType::U32 => {
|
2023-05-07 10:27:16 -04:00
|
|
|
let value = if let Ok(value) = v8::Local::<v8::Uint32>::try_from(value) {
|
|
|
|
value.value()
|
2022-12-12 09:14:20 -05:00
|
|
|
} else {
|
|
|
|
// Fallthrough, essentially UB.
|
|
|
|
value
|
|
|
|
.uint32_value(scope)
|
|
|
|
.expect("Unable to deserialize result parameter.")
|
|
|
|
};
|
|
|
|
*(result as *mut u32) = value;
|
|
|
|
}
|
2023-05-07 10:27:16 -04:00
|
|
|
NativeType::I64 | NativeType::ISize => {
|
2022-12-12 09:14:20 -05:00
|
|
|
if let Ok(value) = v8::Local::<v8::BigInt>::try_from(value) {
|
|
|
|
*(result as *mut i64) = value.i64_value().0;
|
2023-05-07 10:27:16 -04:00
|
|
|
} else if let Ok(value) = v8::Local::<v8::Int32>::try_from(value) {
|
|
|
|
*(result as *mut i64) = value.value() as i64;
|
|
|
|
} else if let Ok(value) = v8::Local::<v8::Number>::try_from(value) {
|
|
|
|
*(result as *mut i64) = value.value() as i64;
|
2022-12-12 09:14:20 -05:00
|
|
|
} else {
|
|
|
|
*(result as *mut i64) = value
|
|
|
|
.integer_value(scope)
|
2022-12-17 17:20:15 -05:00
|
|
|
.expect("Unable to deserialize result parameter.");
|
2022-12-12 09:14:20 -05:00
|
|
|
}
|
|
|
|
}
|
2023-05-07 10:27:16 -04:00
|
|
|
NativeType::U64 | NativeType::USize => {
|
2022-12-12 09:14:20 -05:00
|
|
|
if let Ok(value) = v8::Local::<v8::BigInt>::try_from(value) {
|
|
|
|
*(result as *mut u64) = value.u64_value().0;
|
2023-05-07 10:27:16 -04:00
|
|
|
} else if let Ok(value) = v8::Local::<v8::Uint32>::try_from(value) {
|
|
|
|
*(result as *mut u64) = value.value() as u64;
|
|
|
|
} else if let Ok(value) = v8::Local::<v8::Number>::try_from(value) {
|
2022-12-12 09:14:20 -05:00
|
|
|
*(result as *mut u64) = value.value() as u64;
|
|
|
|
} else {
|
|
|
|
*(result as *mut u64) = value
|
|
|
|
.integer_value(scope)
|
|
|
|
.expect("Unable to deserialize result parameter.")
|
|
|
|
as u64;
|
|
|
|
}
|
|
|
|
}
|
2023-01-07 22:58:10 -05:00
|
|
|
NativeType::Struct(_) => {
|
|
|
|
let size;
|
|
|
|
let pointer = if let Ok(value) =
|
|
|
|
v8::Local::<v8::ArrayBufferView>::try_from(value)
|
|
|
|
{
|
|
|
|
let byte_offset = value.byte_offset();
|
|
|
|
let ab = value
|
|
|
|
.buffer(scope)
|
|
|
|
.expect("Unable to deserialize result parameter.");
|
|
|
|
size = value.byte_length();
|
|
|
|
ab.data()
|
|
|
|
.expect("Unable to deserialize result parameter.")
|
|
|
|
.as_ptr()
|
|
|
|
.add(byte_offset)
|
|
|
|
} else if let Ok(value) = v8::Local::<v8::ArrayBuffer>::try_from(value) {
|
|
|
|
size = value.byte_length();
|
|
|
|
value
|
|
|
|
.data()
|
|
|
|
.expect("Unable to deserialize result parameter.")
|
|
|
|
.as_ptr()
|
|
|
|
} else {
|
|
|
|
panic!("Unable to deserialize result parameter.");
|
|
|
|
};
|
|
|
|
std::ptr::copy_nonoverlapping(
|
|
|
|
pointer as *mut u8,
|
|
|
|
result as *mut u8,
|
|
|
|
std::cmp::min(size, (*cif.rtype).size),
|
|
|
|
);
|
|
|
|
}
|
2022-12-12 09:14:20 -05:00
|
|
|
NativeType::Void => {
|
|
|
|
// nop
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2023-09-27 09:54:43 -04:00
|
|
|
#[op2(async)]
|
2022-12-12 09:14:20 -05:00
|
|
|
pub fn op_ffi_unsafe_callback_ref(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-09-27 09:54:43 -04:00
|
|
|
#[smi] rid: ResourceId,
|
2024-10-14 18:05:49 -04:00
|
|
|
) -> Result<impl Future<Output = ()>, CallbackError> {
|
2022-12-12 09:14:20 -05:00
|
|
|
let state = state.borrow();
|
2024-10-14 18:05:49 -04:00
|
|
|
let callback_resource = state
|
|
|
|
.resource_table
|
|
|
|
.get::<UnsafeCallbackResource>(rid)
|
|
|
|
.map_err(CallbackError::Resource)?;
|
2022-12-12 09:14:20 -05:00
|
|
|
|
|
|
|
Ok(async move {
|
|
|
|
let info: &mut CallbackInfo =
|
|
|
|
// SAFETY: CallbackInfo pointer stays valid as long as the resource is still alive.
|
|
|
|
unsafe { callback_resource.info.as_mut().unwrap() };
|
|
|
|
// Ignore cancellation rejection
|
|
|
|
let _ = info
|
|
|
|
.into_future()
|
|
|
|
.or_cancel(callback_resource.cancel.clone())
|
|
|
|
.await;
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
pub struct RegisterCallbackArgs {
|
|
|
|
parameters: Vec<NativeType>,
|
|
|
|
result: NativeType,
|
|
|
|
}
|
|
|
|
|
2023-09-27 09:54:43 -04:00
|
|
|
#[op2]
|
2022-12-12 09:14:20 -05:00
|
|
|
pub fn op_ffi_unsafe_callback_create<FP, 'scope>(
|
2023-02-28 01:26:48 -05:00
|
|
|
state: &mut OpState,
|
2022-12-12 09:14:20 -05:00
|
|
|
scope: &mut v8::HandleScope<'scope>,
|
2023-09-27 09:54:43 -04:00
|
|
|
#[serde] args: RegisterCallbackArgs,
|
|
|
|
cb: v8::Local<v8::Function>,
|
2024-10-14 18:05:49 -04:00
|
|
|
) -> Result<v8::Local<'scope, v8::Value>, CallbackError>
|
2022-12-12 09:14:20 -05:00
|
|
|
where
|
|
|
|
FP: FfiPermissions + 'static,
|
|
|
|
{
|
|
|
|
let permissions = state.borrow_mut::<FP>();
|
2024-11-04 12:17:21 -05:00
|
|
|
permissions.check_partial_no_path()?;
|
2022-12-12 09:14:20 -05:00
|
|
|
|
2023-05-07 06:31:01 -04:00
|
|
|
let thread_id: u32 = LOCAL_THREAD_ID.with(|s| {
|
|
|
|
let value = *s.borrow();
|
|
|
|
if value == 0 {
|
|
|
|
let res = THREAD_ID_COUNTER.fetch_add(1, atomic::Ordering::SeqCst);
|
|
|
|
s.replace(res);
|
|
|
|
res
|
|
|
|
} else {
|
|
|
|
value
|
2022-12-12 09:14:20 -05:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-05-07 06:31:01 -04:00
|
|
|
if thread_id == 0 {
|
|
|
|
panic!("Isolate ID counter overflowed u32");
|
|
|
|
}
|
|
|
|
|
2023-12-11 22:10:33 -05:00
|
|
|
let async_work_sender = state.borrow::<V8CrossThreadTaskSpawner>().clone();
|
2023-07-30 09:43:22 -04:00
|
|
|
|
2022-12-12 09:14:20 -05:00
|
|
|
let callback = v8::Global::new(scope, cb).into_raw();
|
|
|
|
let current_context = scope.get_current_context();
|
|
|
|
let context = v8::Global::new(scope, current_context).into_raw();
|
|
|
|
|
|
|
|
let info: *mut CallbackInfo = Box::leak(Box::new(CallbackInfo {
|
|
|
|
async_work_sender,
|
|
|
|
callback,
|
|
|
|
context,
|
2023-05-08 03:57:38 -04:00
|
|
|
parameters: args.parameters.clone().into(),
|
2023-05-07 06:31:01 -04:00
|
|
|
result: args.result.clone(),
|
|
|
|
thread_id,
|
2022-12-12 09:14:20 -05:00
|
|
|
}));
|
|
|
|
let cif = Cif::new(
|
2023-01-21 10:51:14 -05:00
|
|
|
args
|
|
|
|
.parameters
|
|
|
|
.into_iter()
|
|
|
|
.map(libffi::middle::Type::try_from)
|
2024-10-14 18:05:49 -04:00
|
|
|
.collect::<Result<Vec<_>, _>>()
|
|
|
|
.map_err(CallbackError::Other)?,
|
|
|
|
libffi::middle::Type::try_from(args.result)
|
|
|
|
.map_err(CallbackError::Other)?,
|
2022-12-12 09:14:20 -05:00
|
|
|
);
|
|
|
|
|
|
|
|
// SAFETY: CallbackInfo is leaked, is not null and stays valid as long as the callback exists.
|
|
|
|
let closure = libffi::middle::Closure::new(cif, deno_ffi_callback, unsafe {
|
|
|
|
info.as_ref().unwrap()
|
|
|
|
});
|
2023-02-22 12:32:38 -05:00
|
|
|
let ptr = *closure.code_ptr() as *mut c_void;
|
2022-12-12 09:14:20 -05:00
|
|
|
let resource = UnsafeCallbackResource {
|
|
|
|
cancel: CancelHandle::new_rc(),
|
|
|
|
closure,
|
|
|
|
info,
|
|
|
|
};
|
|
|
|
let rid = state.resource_table.add(resource);
|
|
|
|
|
|
|
|
let rid_local = v8::Integer::new_from_unsigned(scope, rid);
|
2023-02-22 12:32:38 -05:00
|
|
|
let ptr_local: v8::Local<v8::Value> = v8::External::new(scope, ptr).into();
|
2022-12-12 09:14:20 -05:00
|
|
|
let array = v8::Array::new(scope, 2);
|
|
|
|
array.set_index(scope, 0, rid_local.into());
|
|
|
|
array.set_index(scope, 1, ptr_local);
|
|
|
|
let array_value: v8::Local<v8::Value> = array.into();
|
|
|
|
|
2023-09-27 09:54:43 -04:00
|
|
|
Ok(array_value)
|
2022-12-12 09:14:20 -05:00
|
|
|
}
|
2023-05-07 06:31:01 -04:00
|
|
|
|
2024-08-21 18:33:21 -04:00
|
|
|
#[op2(fast)]
|
2023-05-07 06:31:01 -04:00
|
|
|
pub fn op_ffi_unsafe_callback_close(
|
|
|
|
state: &mut OpState,
|
|
|
|
scope: &mut v8::HandleScope,
|
2023-09-27 09:54:43 -04:00
|
|
|
#[smi] rid: ResourceId,
|
2024-10-14 18:05:49 -04:00
|
|
|
) -> Result<(), CallbackError> {
|
2023-05-07 06:31:01 -04:00
|
|
|
// SAFETY: This drops the closure and the callback info associated with it.
|
|
|
|
// Any retained function pointers to the closure become dangling pointers.
|
|
|
|
// It is up to the user to know that it is safe to call the `close()` on the
|
|
|
|
// UnsafeCallback instance.
|
|
|
|
unsafe {
|
2024-10-14 18:05:49 -04:00
|
|
|
let callback_resource = state
|
|
|
|
.resource_table
|
|
|
|
.take::<UnsafeCallbackResource>(rid)
|
|
|
|
.map_err(CallbackError::Resource)?;
|
2023-05-07 06:31:01 -04:00
|
|
|
let info = Box::from_raw(callback_resource.info);
|
|
|
|
let _ = v8::Global::from_raw(scope, info.callback);
|
|
|
|
let _ = v8::Global::from_raw(scope, info.context);
|
|
|
|
callback_resource.close();
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|