diff options
Diffstat (limited to 'ext/ffi')
-rw-r--r-- | ext/ffi/00_ffi.js | 9 | ||||
-rw-r--r-- | ext/ffi/lib.rs | 45 |
2 files changed, 50 insertions, 4 deletions
diff --git a/ext/ffi/00_ffi.js b/ext/ffi/00_ffi.js index cdaf69e0d..ac8dda317 100644 --- a/ext/ffi/00_ffi.js +++ b/ext/ffi/00_ffi.js @@ -10,7 +10,6 @@ ObjectPrototypeIsPrototypeOf, PromisePrototypeThen, TypeError, - Uint8Array, } = window.__bootstrap.primordials; function unpackU64([hi, lo]) { @@ -107,9 +106,11 @@ } getArrayBuffer(byteLength, offset = 0) { - const uint8array = new Uint8Array(byteLength); - this.copyInto(uint8array, offset); - return uint8array.buffer; + return core.opSync( + "op_ffi_get_buf", + offset ? this.pointer + BigInt(offset) : this.pointer, + byteLength, + ); } copyInto(destination, offset = 0) { diff --git a/ext/ffi/lib.rs b/ext/ffi/lib.rs index 05dcba362..396affdb3 100644 --- a/ext/ffi/lib.rs +++ b/ext/ffi/lib.rs @@ -165,6 +165,7 @@ pub fn init<P: FfiPermissions + 'static>(unstable: bool) -> Extension { op_ffi_call_ptr::decl::<P>(), op_ffi_call_ptr_nonblocking::decl::<P>(), op_ffi_ptr_of::decl::<P>(), + op_ffi_get_buf::decl::<P>(), op_ffi_buf_copy_into::decl::<P>(), op_ffi_cstr_read::decl::<P>(), op_ffi_read_u8::decl::<P>(), @@ -1912,6 +1913,50 @@ where Ok(big_int.into()) } +unsafe extern "C" fn noop_deleter_callback( + _data: *mut c_void, + _byte_length: usize, + _deleter_data: *mut c_void, +) { +} + +#[op(v8)] +fn op_ffi_get_buf<FP, 'scope>( + scope: &mut v8::HandleScope<'scope>, + state: &mut deno_core::OpState, + src: serde_v8::Value<'scope>, + len: usize, +) -> Result<serde_v8::Value<'scope>, AnyError> +where + FP: FfiPermissions + 'static, +{ + check_unstable(state, "Deno.UnsafePointerView#arrayBuffer"); + + let permissions = state.borrow_mut::<FP>(); + permissions.check(None)?; + + let value = v8::Local::<v8::BigInt>::try_from(src.v8_value) + .map_err(|_| type_error("Invalid FFI pointer value, expected BigInt"))?; + let ptr = value.u64_value().0 as usize as *mut c_void; + if std::ptr::eq(ptr, std::ptr::null()) { + return Err(type_error("Invalid FFI pointer value, got nullptr")); + } + + // SAFETY: Trust the user to have provided a real pointer, and a valid matching size to it. Since this is a foreign pointer, we should not do any deletion. + let backing_store = unsafe { + v8::ArrayBuffer::new_backing_store_from_ptr( + ptr, + len, + noop_deleter_callback, + std::ptr::null_mut(), + ) + } + .make_shared(); + let array_buffer: v8::Local<v8::Value> = + v8::ArrayBuffer::with_backing_store(scope, &backing_store).into(); + Ok(array_buffer.into()) +} + #[op] fn op_ffi_buf_copy_into<FP>( state: &mut deno_core::OpState, |