From 493ab46832b2e19d197b379aa478f58ceafb8a58 Mon Sep 17 00:00:00 2001 From: Benjamin Bouvier Date: Tue, 4 Jun 2024 16:43:45 +0200 Subject: [PATCH] ffi: duplicate the tokio runtime hack for `Encryption` :melting: --- bindings/matrix-sdk-ffi/src/encryption.rs | 26 ++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/bindings/matrix-sdk-ffi/src/encryption.rs b/bindings/matrix-sdk-ffi/src/encryption.rs index b39c5ec1492..32ea4a14814 100644 --- a/bindings/matrix-sdk-ffi/src/encryption.rs +++ b/bindings/matrix-sdk-ffi/src/encryption.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use std::{mem::ManuallyDrop, sync::Arc}; use futures_util::StreamExt; use matrix_sdk::{ @@ -6,6 +6,7 @@ use matrix_sdk::{ encryption::{backups, recovery}, }; use thiserror::Error; +use tracing::info; use zeroize::Zeroize; use super::RUNTIME; @@ -13,12 +14,31 @@ use crate::{error::ClientError, task_handle::TaskHandle}; #[derive(uniffi::Object)] pub struct Encryption { - inner: matrix_sdk::encryption::Encryption, + inner: ManuallyDrop, +} + +impl Drop for Encryption { + fn drop(&mut self) { + // This holds a reference to the `Client`, so it must duplicate the hack on the + // FFI's `Client` data structure, since it may be the last reference to + // a `Client`. + // + // Dropping the inner OlmMachine must happen within a tokio context + // because deadpool drops sqlite connections in the DB pool on tokio's + // blocking threadpool to avoid blocking async worker threads. + let _guard = RUNTIME.enter(); + // SAFETY: self.inner is never used again, which is the only requirement + // for ManuallyDrop::drop to be used safely. + unsafe { + info!("Dropping an Encryption"); + ManuallyDrop::drop(&mut self.inner); + } + } } impl From for Encryption { fn from(value: matrix_sdk::encryption::Encryption) -> Self { - Self { inner: value } + Self { inner: ManuallyDrop::new(value) } } }