fix(napi): ensure that napi_call_threadsafe_function cannot be called after abort (#1533)

* refactor(napi): reduce boilerplate code for accessing `aborted` lock

* refactor: ensure that `napi_call_threadsafe_function` cannot be called after abort

---------

Co-authored-by: LongYinan <lynweklm@gmail.com>
This commit is contained in:
Bo 2023-03-28 20:54:55 +08:00 committed by GitHub
parent e47c13f177
commit d8cfcfdfda
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -6,7 +6,7 @@ use std::marker::PhantomData;
use std::os::raw::c_void;
use std::ptr::{self, null_mut};
use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering};
use std::sync::{Arc, RwLock, Weak};
use std::sync::{Arc, RwLock, RwLockWriteGuard, Weak};
use crate::bindgen_runtime::{FromNapiValue, ToNapiValue, TypeName, ValidateNapiValue};
use crate::{check_status, sys, Env, JsError, JsUnknown, Result, Status};
@ -112,6 +112,30 @@ impl ThreadsafeFunctionHandle {
})
}
/// Lock `aborted` with read access, call `f` with the value of `aborted`, then unlock it
fn with_read_aborted<RT, F>(&self, f: F) -> RT
where
F: FnOnce(bool) -> RT,
{
let aborted_guard = self
.aborted
.read()
.expect("Threadsafe Function aborted lock failed");
f(*aborted_guard)
}
/// Lock `aborted` with write access, call `f` with the `RwLockWriteGuard`, then unlock it
fn with_write_aborted<RT, F>(&self, f: F) -> RT
where
F: FnOnce(RwLockWriteGuard<bool>) -> RT,
{
let aborted_guard = self
.aborted
.write()
.expect("Threadsafe Function aborted lock failed");
f(aborted_guard)
}
fn null() -> Arc<Self> {
Self::new(null_mut())
}
@ -127,11 +151,8 @@ impl ThreadsafeFunctionHandle {
impl Drop for ThreadsafeFunctionHandle {
fn drop(&mut self) {
let aborted_guard = self
.aborted
.read()
.expect("Threadsafe Function aborted lock failed");
if !*aborted_guard {
self.with_read_aborted(|aborted| {
if !aborted {
let release_status = unsafe {
sys::napi_release_threadsafe_function(
self.get_raw(),
@ -144,6 +165,7 @@ impl Drop for ThreadsafeFunctionHandle {
Status::from(release_status)
);
}
})
}
}
@ -215,19 +237,16 @@ pub struct ThreadsafeFunction<T: 'static, ES: ErrorStrategy::T = ErrorStrategy::
impl<T: 'static, ES: ErrorStrategy::T> Clone for ThreadsafeFunction<T, ES> {
fn clone(&self) -> Self {
let aborted_guard = self
.handle
.aborted
.read()
.expect("Threadsafe Function aborted lock failed");
if *aborted_guard {
self.handle.with_read_aborted(|aborted| {
if aborted {
panic!("ThreadsafeFunction was aborted, can not clone it");
}
};
Self {
handle: self.handle.clone(),
_phantom: PhantomData,
}
})
}
}
@ -351,48 +370,35 @@ impl<T: 'static, ES: ErrorStrategy::T> ThreadsafeFunction<T, ES> {
///
/// "ref" is a keyword so that we use "refer" here.
pub fn refer(&mut self, env: &Env) -> Result<()> {
let aborted_guard = self
.handle
.aborted
.read()
.expect("Threadsafe Function aborted lock failed");
if !*aborted_guard && !self.handle.referred.load(Ordering::Relaxed) {
self.handle.with_read_aborted(|aborted| {
if !aborted && !self.handle.referred.load(Ordering::Relaxed) {
check_status!(unsafe { sys::napi_ref_threadsafe_function(env.0, self.handle.get_raw()) })?;
self.handle.referred.store(true, Ordering::Relaxed);
}
Ok(())
})
}
/// See [napi_unref_threadsafe_function](https://nodejs.org/api/n-api.html#n_api_napi_unref_threadsafe_function)
/// for more information.
pub fn unref(&mut self, env: &Env) -> Result<()> {
let aborted_guard = self
.handle
.aborted
.read()
.expect("Threadsafe Function aborted lock failed");
if !*aborted_guard && self.handle.referred.load(Ordering::Relaxed) {
check_status!(unsafe { sys::napi_unref_threadsafe_function(env.0, self.handle.get_raw()) })?;
self.handle.with_read_aborted(|aborted| {
if !aborted && self.handle.referred.load(Ordering::Relaxed) {
check_status!(unsafe {
sys::napi_unref_threadsafe_function(env.0, self.handle.get_raw())
})?;
self.handle.referred.store(false, Ordering::Relaxed);
}
Ok(())
})
}
pub fn aborted(&self) -> bool {
let aborted_guard = self
.handle
.aborted
.read()
.expect("Threadsafe Function aborted lock failed");
*aborted_guard
self.handle.with_read_aborted(|aborted| aborted)
}
pub fn abort(self) -> Result<()> {
let mut aborted_guard = self
.handle
.aborted
.write()
.expect("Threadsafe Function aborted lock failed");
self.handle.with_write_aborted(|mut aborted_guard| {
if !*aborted_guard {
check_status!(unsafe {
sys::napi_release_threadsafe_function(
@ -403,6 +409,7 @@ impl<T: 'static, ES: ErrorStrategy::T> ThreadsafeFunction<T, ES> {
*aborted_guard = true;
}
Ok(())
})
}
/// Get the raw `ThreadSafeFunction` pointer
@ -415,6 +422,11 @@ impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::CalleeHandled> {
/// See [napi_call_threadsafe_function](https://nodejs.org/api/n-api.html#n_api_napi_call_threadsafe_function)
/// for more information.
pub fn call(&self, value: Result<T>, mode: ThreadsafeFunctionCallMode) -> Status {
self.handle.with_read_aborted(|aborted| {
if aborted {
return Status::Closing;
}
unsafe {
sys::napi_call_threadsafe_function(
self.handle.get_raw(),
@ -430,6 +442,7 @@ impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::CalleeHandled> {
)
}
.into()
})
}
pub fn call_with_return_value<D: FromNapiValue, F: 'static + FnOnce(D) -> Result<()>>(
@ -438,6 +451,11 @@ impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::CalleeHandled> {
mode: ThreadsafeFunctionCallMode,
cb: F,
) -> Status {
self.handle.with_read_aborted(|aborted| {
if aborted {
return Status::Closing;
}
unsafe {
sys::napi_call_threadsafe_function(
self.handle.get_raw(),
@ -455,11 +473,18 @@ impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::CalleeHandled> {
)
}
.into()
})
}
#[cfg(feature = "tokio_rt")]
pub async fn call_async<D: 'static + FromNapiValue>(&self, value: Result<T>) -> Result<D> {
let (sender, receiver) = tokio::sync::oneshot::channel::<D>();
self.handle.with_read_aborted(|aborted| {
if aborted {
return Err(crate::Error::from_status(Status::Closing));
}
check_status!(unsafe {
sys::napi_call_threadsafe_function(
self.handle.get_raw(),
@ -479,6 +504,7 @@ impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::CalleeHandled> {
.cast(),
ThreadsafeFunctionCallMode::NonBlocking.into(),
)
})
})?;
receiver
.await
@ -490,6 +516,11 @@ impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::Fatal> {
/// See [napi_call_threadsafe_function](https://nodejs.org/api/n-api.html#n_api_napi_call_threadsafe_function)
/// for more information.
pub fn call(&self, value: T, mode: ThreadsafeFunctionCallMode) -> Status {
self.handle.with_read_aborted(|aborted| {
if aborted {
return Status::Closing;
}
unsafe {
sys::napi_call_threadsafe_function(
self.handle.get_raw(),
@ -503,6 +534,7 @@ impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::Fatal> {
)
}
.into()
})
}
pub fn call_with_return_value<D: FromNapiValue, F: 'static + FnOnce(D) -> Result<()>>(
@ -511,6 +543,11 @@ impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::Fatal> {
mode: ThreadsafeFunctionCallMode,
cb: F,
) -> Status {
self.handle.with_read_aborted(|aborted| {
if aborted {
return Status::Closing;
}
unsafe {
sys::napi_call_threadsafe_function(
self.handle.get_raw(),
@ -526,11 +563,18 @@ impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::Fatal> {
)
}
.into()
})
}
#[cfg(feature = "tokio_rt")]
pub async fn call_async<D: 'static + FromNapiValue>(&self, value: T) -> Result<D> {
let (sender, receiver) = tokio::sync::oneshot::channel::<D>();
self.handle.with_read_aborted(|aborted| {
if aborted {
return Err(crate::Error::from_status(Status::Closing));
}
check_status!(unsafe {
sys::napi_call_threadsafe_function(
self.handle.get_raw(),
@ -548,7 +592,9 @@ impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::Fatal> {
.cast(),
ThreadsafeFunctionCallMode::NonBlocking.into(),
)
})
})?;
receiver
.await
.map_err(|err| crate::Error::new(Status::GenericFailure, format!("{}", err)))
@ -567,14 +613,11 @@ unsafe extern "C" fn thread_finalize_cb<T: 'static, V: ToNapiValue, R>(
unsafe { Weak::from_raw(finalize_data.cast::<ThreadsafeFunctionHandle>()).upgrade() };
if let Some(handle) = handle_option {
let mut aborted_guard = handle
.aborted
.write()
.expect("Threadsafe Function Handle aborted lock failed");
handle.with_write_aborted(|mut aborted_guard| {
if !*aborted_guard {
*aborted_guard = true;
}
});
}
// cleanup