ble: Apple BLE no longer leaks each write, notification, and scan; move to objc2 0.6

This commit is contained in:
DeFiDude committed 2026-11-19 19:55:16 -07:00
1 parent 5dadbd44bd
commit 7631c75afd
9 files changed
+313 -366

No files matched your search

Generated
+11 -59
View File
@@ -182,22 +182,13 @@ dependencies = [
"generic-array", "generic-array",
] ]
[[package]]
name = "block2"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
dependencies = [
"objc2 0.5.2",
]
[[package]] [[package]]
name = "block2" name = "block2"
version = "0.6.2" version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
dependencies = [ dependencies = [
"objc2 0.6.5", "objc2",
] ]
[[package]] [[package]]
@@ -272,9 +263,9 @@ dependencies = [
"futures", "futures",
"jni 0.22.4", "jni 0.22.4",
"log", "log",
"objc2 0.6.5", "objc2",
"objc2-core-bluetooth 0.3.2", "objc2-core-bluetooth",
"objc2-foundation 0.3.2", "objc2-foundation",
"once_cell", "once_cell",
"static_assertions", "static_assertions",
"thiserror 2.0.21", "thiserror 2.0.21",
@@ -1445,22 +1436,6 @@ dependencies = [
"libm", "libm",
] ]
[[package]]
name = "objc-sys"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
[[package]]
name = "objc2"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
dependencies = [
"objc-sys",
"objc2-encode",
]
[[package]] [[package]]
name = "objc2" name = "objc2"
version = "0.6.5" version = "0.6.5"
@@ -1470,17 +1445,6 @@ dependencies = [
"objc2-encode", "objc2-encode",
] ]
[[package]]
name = "objc2-core-bluetooth"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
dependencies = [
"bitflags 2.13.2",
"objc2 0.5.2",
"objc2-foundation 0.2.2",
]
[[package]] [[package]]
name = "objc2-core-bluetooth" name = "objc2-core-bluetooth"
version = "0.3.2" version = "0.3.2"
@@ -1488,8 +1452,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394" checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"objc2 0.6.5", "objc2",
"objc2-foundation 0.3.2", "objc2-foundation",
] ]
[[package]] [[package]]
@@ -1498,18 +1462,6 @@ version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "objc2-foundation"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
dependencies = [
"bitflags 2.13.2",
"block2 0.5.1",
"libc",
"objc2 0.5.2",
]
[[package]] [[package]]
name = "objc2-foundation" name = "objc2-foundation"
version = "0.3.2" version = "0.3.2"
@@ -1517,8 +1469,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"block2 0.6.2", "block2",
"objc2 0.6.5", "objc2",
] ]
[[package]] [[package]]
@@ -1930,9 +1882,9 @@ dependencies = [
"libc", "libc",
"md-5", "md-5",
"mio", "mio",
"objc2 0.5.2", "objc2",
"objc2-core-bluetooth 0.2.2", "objc2-core-bluetooth",
"objc2-foundation 0.2.2", "objc2-foundation",
"rand 0.8.5", "rand 0.8.5",
"rns-crypto", "rns-crypto",
"rns-identity", "rns-identity",
+11 -59
View File
@@ -79,22 +79,13 @@ dependencies = [
"generic-array", "generic-array",
] ]
[[package]]
name = "block2"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
dependencies = [
"objc2 0.5.2",
]
[[package]] [[package]]
name = "block2" name = "block2"
version = "0.6.2" version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
dependencies = [ dependencies = [
"objc2 0.6.5", "objc2",
] ]
[[package]] [[package]]
@@ -169,9 +160,9 @@ dependencies = [
"futures", "futures",
"jni 0.22.4", "jni 0.22.4",
"log", "log",
"objc2 0.6.5", "objc2",
"objc2-core-bluetooth 0.3.2", "objc2-core-bluetooth",
"objc2-foundation 0.3.2", "objc2-foundation",
"once_cell", "once_cell",
"static_assertions", "static_assertions",
"thiserror 2.0.20", "thiserror 2.0.20",
@@ -994,22 +985,6 @@ dependencies = [
"autocfg", "autocfg",
] ]
[[package]]
name = "objc-sys"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
[[package]]
name = "objc2"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
dependencies = [
"objc-sys",
"objc2-encode",
]
[[package]] [[package]]
name = "objc2" name = "objc2"
version = "0.6.5" version = "0.6.5"
@@ -1019,17 +994,6 @@ dependencies = [
"objc2-encode", "objc2-encode",
] ]
[[package]]
name = "objc2-core-bluetooth"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
dependencies = [
"bitflags 2.13.2",
"objc2 0.5.2",
"objc2-foundation 0.2.2",
]
[[package]] [[package]]
name = "objc2-core-bluetooth" name = "objc2-core-bluetooth"
version = "0.3.2" version = "0.3.2"
@@ -1037,8 +1001,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394" checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"objc2 0.6.5", "objc2",
"objc2-foundation 0.3.2", "objc2-foundation",
] ]
[[package]] [[package]]
@@ -1047,18 +1011,6 @@ version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "objc2-foundation"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
dependencies = [
"bitflags 2.13.2",
"block2 0.5.1",
"libc",
"objc2 0.5.2",
]
[[package]] [[package]]
name = "objc2-foundation" name = "objc2-foundation"
version = "0.3.2" version = "0.3.2"
@@ -1066,8 +1018,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"block2 0.6.2", "block2",
"objc2 0.6.5", "objc2",
] ]
[[package]] [[package]]
@@ -1305,9 +1257,9 @@ dependencies = [
"libc", "libc",
"md-5", "md-5",
"mio", "mio",
"objc2 0.5.2", "objc2",
"objc2-core-bluetooth 0.2.2", "objc2-core-bluetooth",
"objc2-foundation 0.2.2", "objc2-foundation",
"rand", "rand",
"rns-crypto", "rns-crypto",
"rns-identity", "rns-identity",
+10 -7
View File
@@ -803,7 +803,7 @@
"rename": null, "rename": null,
"kind": null, "kind": null,
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))", "target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
"requirement": "^0.5", "requirement": "^0.6",
"optional": false, "optional": false,
"defaultFeatures": true, "defaultFeatures": true,
"features": [], "features": [],
@@ -814,12 +814,14 @@
"rename": null, "rename": null,
"kind": null, "kind": null,
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))", "target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
"requirement": "^0.2", "requirement": "^0.3",
"optional": false, "optional": false,
"defaultFeatures": true, "defaultFeatures": false,
"features": [ "features": [
"CBAdvertisementData", "CBAdvertisementData",
"CBCentralManagerConstants" "CBCentralManagerConstants",
"CBPeripheralManagerConstants",
"std"
], ],
"sourceKind": "registry" "sourceKind": "registry"
}, },
@@ -828,11 +830,12 @@
"rename": null, "rename": null,
"kind": null, "kind": null,
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))", "target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
"requirement": "^0.2", "requirement": "^0.3",
"optional": false, "optional": false,
"defaultFeatures": true, "defaultFeatures": false,
"features": [ "features": [
"NSString" "NSString",
"std"
], ],
"sourceKind": "registry" "sourceKind": "registry"
}, },
+3 -3
View File
@@ -45,9 +45,9 @@ md-5 = { workspace = true }
# CB*RestoreIdentifierKey, etc.) instead of re-declaring their literal # CB*RestoreIdentifierKey, etc.) instead of re-declaring their literal
# values, which Apple is free to change. # values, which Apple is free to change.
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies] [target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
objc2 = "0.5" objc2 = "0.6"
objc2-foundation = { version = "0.2", features = ["NSString"] } objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString"] }
objc2-core-bluetooth = { version = "0.2", features = ["CBAdvertisementData", "CBCentralManagerConstants"] } objc2-core-bluetooth = { version = "0.3", default-features = false, features = ["std", "CBAdvertisementData", "CBCentralManagerConstants", "CBPeripheralManagerConstants"] }
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
libc = "0.2" libc = "0.2"
+94
View File
@@ -0,0 +1,94 @@
//! Owned Objective-C values for the Apple BLE modules. Their calls run on Tokio
//! workers and other threads with no autorelease pool, where an autoreleased
//! object lives until the thread exits.
use objc2::msg_send;
use objc2::rc::{Allocated, Retained};
use objc2::runtime::{AnyClass, AnyObject};
use objc2_foundation::NSString;
use uuid::Uuid;
/// `UUIDWithString:` autoreleases, so call this inside `autoreleasepool`.
pub(crate) fn cbuuid(uuid: &Uuid) -> Retained<AnyObject> {
let s = NSString::from_str(&uuid.to_string());
let cls = AnyClass::get(c"CBUUID").expect("CBUUID must exist at runtime");
unsafe { msg_send![cls, UUIDWithString: &*s] }
}
/// A copy of `bytes`, never autoreleased.
pub(crate) fn nsdata(bytes: &[u8]) -> Retained<AnyObject> {
let cls = AnyClass::get(c"NSData").expect("NSData must exist at runtime");
unsafe {
let obj: Allocated<AnyObject> = msg_send![cls, alloc];
msg_send![obj,
initWithBytes: bytes.as_ptr().cast::<std::ffi::c_void>(),
length: bytes.len()]
}
}
/// Never autoreleased; the array retains each element.
pub(crate) fn nsarray(objects: &[&AnyObject]) -> Retained<AnyObject> {
let cls = AnyClass::get(c"NSArray").expect("NSArray must exist at runtime");
let ptrs: Vec<*const AnyObject> = objects.iter().map(|o| *o as *const AnyObject).collect();
unsafe {
let obj: Allocated<AnyObject> = msg_send![cls, alloc];
msg_send![obj, initWithObjects: ptrs.as_ptr(), count: ptrs.len()]
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use objc2::rc::{Weak, autoreleasepool};
/// Runs `make` on a thread with no autorelease pool, drops what it returns,
/// and reports whether every returned object was freed. A stray retain or
/// an autorelease outside `make`'s own pool keeps the object alive.
pub(crate) fn freed_on_drop<F>(make: F) -> bool
where
F: FnOnce() -> Vec<Retained<AnyObject>> + Send + 'static,
{
std::thread::spawn(move || {
let weak: Vec<Weak<AnyObject>> = {
let objs = make();
let weak: Vec<_> = objs.iter().map(Weak::from_retained).collect();
// A class without weak-reference support would pass vacuously.
assert!(weak.iter().all(|w| w.load().is_some()));
weak
};
weak.iter().all(|w| w.load().is_none())
})
.join()
.expect("probe thread")
}
#[test]
fn probe_sees_an_autoreleased_object() {
assert!(!freed_on_drop(|| {
let cls = AnyClass::get(c"NSData").unwrap();
let bytes = [0xCDu8; 300];
unsafe {
let raw: *mut AnyObject = msg_send![cls,
dataWithBytes: bytes.as_ptr().cast::<std::ffi::c_void>(),
length: bytes.len()];
vec![Retained::retain(raw).unwrap()]
}
}));
}
#[test]
fn nsdata_and_nsarray_are_never_autoreleased() {
assert!(freed_on_drop(|| {
let data = nsdata(&[0xAB; 300]);
let arr = nsarray(&[&data]);
vec![data, arr]
}));
}
#[test]
fn cbuuid_holds_no_extra_retain() {
assert!(freed_on_drop(|| {
autoreleasepool(|_| vec![cbuuid(&crate::ble_peer::RATSPEAK_SERVICE_UUID)])
}));
}
}
+19 -39
View File
@@ -8,6 +8,7 @@ use crate::ble_central_lifecycle::{
CentralEvent, CentralLifecycle, CentralState, DiscoveryEvent, classify_protocol, CentralEvent, CentralLifecycle, CentralState, DiscoveryEvent, classify_protocol,
}; };
use crate::ble_peer::{COLUMBA_SERVICE_UUID, RATSPEAK_SERVICE_UUID}; use crate::ble_peer::{COLUMBA_SERVICE_UUID, RATSPEAK_SERVICE_UUID};
use objc2::rc::autoreleasepool;
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel}; use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
use objc2::{msg_send, sel}; use objc2::{msg_send, sel};
use objc2_core_bluetooth::{ use objc2_core_bluetooth::{
@@ -144,7 +145,7 @@ pub async fn start_scan(
let delegate_raw: *mut AnyObject = msg_send![delegate_cls, alloc]; let delegate_raw: *mut AnyObject = msg_send![delegate_cls, alloc];
let delegate_raw: *mut AnyObject = msg_send![delegate_raw, init]; let delegate_raw: *mut AnyObject = msg_send![delegate_raw, init];
let Some(mgr_cls) = AnyClass::get("CBCentralManager") else { let Some(mgr_cls) = AnyClass::get(c"CBCentralManager") else {
tracing::error!("Apple BLE Central: CBCentralManager class not found"); tracing::error!("Apple BLE Central: CBCentralManager class not found");
return; return;
}; };
@@ -216,12 +217,12 @@ pub async fn stop_scan() -> Result<(), String> {
} }
}; };
unsafe { // We do NOT release the manager — the next start_scan reuses it.
// We do NOT release the manager — the next start_scan reuses it. // Per-cycle release on macOS triggers CBManagerStateUnsupported.
// Per-cycle release on macOS triggers CBManagerStateUnsupported. // `teardown_central` does the full release on interface shutdown.
// `teardown_central` does the full release on interface shutdown. autoreleasepool(|_| unsafe {
let _: () = msg_send![&*mgr_ptr, stopScan]; let _: () = msg_send![&*mgr_ptr, stopScan];
} });
finalize_stop(); finalize_stop();
Ok(()) Ok(())
@@ -286,8 +287,8 @@ pub fn central_manager_ptr() -> Option<*mut AnyObject> {
fn get_delegate_class() -> &'static AnyClass { fn get_delegate_class() -> &'static AnyClass {
DELEGATE_CLASS.get_or_init(|| { DELEGATE_CLASS.get_or_init(|| {
let superclass = AnyClass::get("NSObject").expect("NSObject must exist"); let superclass = AnyClass::get(c"NSObject").expect("NSObject must exist");
let mut builder = ClassBuilder::new("RatspeakBleCentralDelegate", superclass) let mut builder = ClassBuilder::new(c"RatspeakBleCentralDelegate", superclass)
.expect("ClassBuilder for central delegate must succeed"); .expect("ClassBuilder for central delegate must succeed");
extern "C" fn did_update_state( extern "C" fn did_update_state(
@@ -720,23 +721,14 @@ unsafe fn scan_with_manager(mgr_raw: *mut AnyObject) -> Result<(), String> {
.map_err(|e| format!("scan_services lock poisoned: {e}"))? .map_err(|e| format!("scan_services lock poisoned: {e}"))?
.clone(); .clone();
unsafe { autoreleasepool(|_| unsafe {
let uuids: Vec<_> = services.iter().map(crate::apple_objc::cbuuid).collect();
let refs: Vec<&AnyObject> = uuids.iter().map(|u| &**u).collect();
// nil filter = scan all. // nil filter = scan all.
let svc_arr: *mut AnyObject = if services.is_empty() { let svc_arr = (!refs.is_empty()).then(|| crate::apple_objc::nsarray(&refs));
std::ptr::null_mut()
} else {
let arr_cls = AnyClass::get("NSArray").ok_or("NSArray not found")?;
let mut raw_ptrs: Vec<*const AnyObject> = Vec::with_capacity(services.len());
for u in &services {
raw_ptrs.push(cbuuid(u) as *const AnyObject);
}
msg_send![arr_cls,
arrayWithObjects: raw_ptrs.as_ptr(),
count: raw_ptrs.len()]
};
let number_cls = AnyClass::get("NSNumber").ok_or("NSNumber not found")?; let number_cls = AnyClass::get(c"NSNumber").ok_or("NSNumber not found")?;
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?; let dict_cls = AnyClass::get(c"NSDictionary").ok_or("NSDictionary not found")?;
let yes: *mut AnyObject = msg_send![number_cls, numberWithBool: true]; let yes: *mut AnyObject = msg_send![number_cls, numberWithBool: true];
let opts: *mut AnyObject = msg_send![dict_cls, let opts: *mut AnyObject = msg_send![dict_cls,
dictionaryWithObject: yes, dictionaryWithObject: yes,
@@ -750,16 +742,16 @@ unsafe fn scan_with_manager(mgr_raw: *mut AnyObject) -> Result<(), String> {
"Apple BLE Central: scanForPeripheralsWithServices" "Apple BLE Central: scanForPeripheralsWithServices"
); );
let _: () = msg_send![&*mgr_raw, let _: () = msg_send![&*mgr_raw,
scanForPeripheralsWithServices: svc_arr, scanForPeripheralsWithServices: svc_arr.as_deref(),
options: opts]; options: opts];
} Ok(())
Ok(()) })
} }
/// `{ RestoreIdentifierKey: CENTRAL_RESTORE_ID }`. Ignored on macOS. /// `{ RestoreIdentifierKey: CENTRAL_RESTORE_ID }`. Ignored on macOS.
unsafe fn build_init_options() -> Result<*mut AnyObject, String> { unsafe fn build_init_options() -> Result<*mut AnyObject, String> {
unsafe { unsafe {
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?; let dict_cls = AnyClass::get(c"NSDictionary").ok_or("NSDictionary not found")?;
let restore_id = NSString::from_str(CENTRAL_RESTORE_ID); let restore_id = NSString::from_str(CENTRAL_RESTORE_ID);
let opts: *mut AnyObject = msg_send![dict_cls, let opts: *mut AnyObject = msg_send![dict_cls,
dictionaryWithObject: &*restore_id, dictionaryWithObject: &*restore_id,
@@ -852,18 +844,6 @@ unsafe fn nsstring_to_string(s: *mut AnyObject) -> String {
} }
} }
fn cbuuid(uuid: &Uuid) -> *mut AnyObject {
let s = NSString::from_str(&uuid.to_string());
unsafe {
let cls = AnyClass::get("CBUUID").expect("CBUUID must exist at runtime");
let obj: *mut AnyObject = msg_send![cls, UUIDWithString: &*s];
// UUIDWithString: returns autoreleased; retain so the pointer
// survives the autorelease pool drain.
let _: *mut AnyObject = msg_send![obj, retain];
obj
}
}
/// Expand a SIG short UUID ("180D" / "0000180D") to its 128-bit form using /// Expand a SIG short UUID ("180D" / "0000180D") to its 128-bit form using
/// the Bluetooth base UUID. /// the Bluetooth base UUID.
fn parse_short_uuid(s: &str) -> Result<Uuid, ()> { fn parse_short_uuid(s: &str) -> Result<Uuid, ()> {
@@ -5,10 +5,11 @@
#![cfg(any(target_os = "ios", target_os = "macos"))] #![cfg(any(target_os = "ios", target_os = "macos"))]
use crate::apple_objc::{cbuuid, nsarray, nsdata};
use crate::ble_tx_queue::PacketQueue; use crate::ble_tx_queue::PacketQueue;
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel}; use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
use objc2::{msg_send, sel}; use objc2::{msg_send, sel};
use objc2_foundation::NSString;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock}; use std::sync::{Arc, Mutex, OnceLock};
@@ -135,7 +136,7 @@ pub struct ConnectedPeer {
impl Drop for ConnectedPeer { impl Drop for ConnectedPeer {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { autoreleasepool(|_| unsafe {
// Clear the (weakly-retained) delegate first so a late callback // Clear the (weakly-retained) delegate first so a late callback
// can't fire into freed memory after the release below. // can't fire into freed memory after the release below.
if !self.peripheral.0.is_null() { if !self.peripheral.0.is_null() {
@@ -157,7 +158,7 @@ impl Drop for ConnectedPeer {
let _: () = msg_send![p.0, release]; let _: () = msg_send![p.0, release];
} }
} }
} });
} }
} }
@@ -212,12 +213,12 @@ pub async fn connect_peer(
reason = %reason, reason = %reason,
"Apple BLE central connect: tearing down partial connection" "Apple BLE central connect: tearing down partial connection"
); );
unsafe { autoreleasepool(|_| unsafe {
let _: () = msg_send![&*manager, cancelPeripheralConnection: peripheral]; let _: () = msg_send![&*manager, cancelPeripheralConnection: peripheral];
let _: () = msg_send![peripheral, setDelegate: std::ptr::null::<AnyObject>()]; let _: () = msg_send![peripheral, setDelegate: std::ptr::null::<AnyObject>()];
let _: () = msg_send![delegate, release]; let _: () = msg_send![delegate, release];
let _: () = msg_send![peripheral, release]; let _: () = msg_send![peripheral, release];
} });
if let Ok(mut g) = pending().lock() { if let Ok(mut g) = pending().lock() {
for kind in [ for kind in [
CallbackKind::Connect, CallbackKind::Connect,
@@ -239,11 +240,11 @@ pub async fn connect_peer(
"Apple BLE central: connectPeripheral" "Apple BLE central: connectPeripheral"
); );
let rx = install_pending(&address, CallbackKind::Connect); let rx = install_pending(&address, CallbackKind::Connect);
unsafe { autoreleasepool(|_| unsafe {
let _: () = msg_send![&*manager.0, let _: () = msg_send![&*manager.0,
connectPeripheral: peripheral.0, connectPeripheral: peripheral.0,
options: std::ptr::null::<AnyObject>()]; options: std::ptr::null::<AnyObject>()];
} });
if let Err(e) = await_step(rx, "connect", CONNECT_TIMEOUT).await { if let Err(e) = await_step(rx, "connect", CONNECT_TIMEOUT).await {
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e); teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
return Err(e); return Err(e);
@@ -263,17 +264,19 @@ pub async fn connect_peer(
// install_pending must run BEFORE the CB call so a fast-path callback // install_pending must run BEFORE the CB call so a fast-path callback
// (cached service data) can't race ahead of its own entry. // (cached service data) can't race ahead of its own entry.
let rx = install_pending(&address, CallbackKind::Services); let rx = install_pending(&address, CallbackKind::Services);
unsafe { autoreleasepool(|_| unsafe {
let _: () = msg_send![peripheral.0, setDelegate: delegate.0]; let _: () = msg_send![peripheral.0, setDelegate: delegate.0];
let svc_filter = build_cbuuid_array(&[target_service_uuid]); let svc_filter = build_cbuuid_array(&[target_service_uuid]);
let _: () = msg_send![peripheral.0, discoverServices: svc_filter]; let _: () = msg_send![peripheral.0, discoverServices: &*svc_filter];
} });
if let Err(e) = await_step(rx, "discoverServices", DISCOVERY_TIMEOUT).await { if let Err(e) = await_step(rx, "discoverServices", DISCOVERY_TIMEOUT).await {
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e); teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
return Err(e); return Err(e);
} }
let service = match unsafe { find_service(peripheral.0, target_service_uuid) } { let service = match autoreleasepool(|_| unsafe {
find_service(peripheral.0, target_service_uuid)
}) {
Some(p) => SendPtr(p), Some(p) => SendPtr(p),
None => { None => {
let msg = format!("target service {target_service_uuid} not present after discovery"); let msg = format!("target service {target_service_uuid} not present after discovery");
@@ -295,39 +298,41 @@ pub async fn connect_peer(
PeerProtocol::Columba => (COLUMBA_RX_UUID, COLUMBA_TX_UUID), PeerProtocol::Columba => (COLUMBA_RX_UUID, COLUMBA_TX_UUID),
}; };
let rx = install_pending(&address, CallbackKind::Chars); let rx = install_pending(&address, CallbackKind::Chars);
unsafe { autoreleasepool(|_| unsafe {
let chars_filter = build_cbuuid_array(&[rx_uuid, tx_uuid]); let chars_filter = build_cbuuid_array(&[rx_uuid, tx_uuid]);
let _: () = msg_send![peripheral.0, let _: () = msg_send![peripheral.0,
discoverCharacteristics: chars_filter, discoverCharacteristics: &*chars_filter,
forService: service.0]; forService: service.0];
} });
if let Err(e) = await_step(rx, "discoverCharacteristics", DISCOVERY_TIMEOUT).await { if let Err(e) = await_step(rx, "discoverCharacteristics", DISCOVERY_TIMEOUT).await {
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e); teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
return Err(e); return Err(e);
} }
let rx_char = match unsafe { find_char(service.0, rx_uuid) } { // The peripheral owns these; retain so they outlive any single
Some(p) => SendPtr(p), // delegate callback frame.
None => { let found = autoreleasepool(|_| unsafe {
let rx_char = find_char(service.0, rx_uuid);
let tx_char = find_char(service.0, tx_uuid);
if let (Some(rx), Some(tx)) = (rx_char, tx_char) {
let _: *mut AnyObject = msg_send![rx, retain];
let _: *mut AnyObject = msg_send![tx, retain];
}
(rx_char, tx_char)
});
let (rx_char, tx_char) = match found {
(Some(rx), Some(tx)) => (SendPtr(rx), SendPtr(tx)),
(None, _) => {
let msg = format!("rx characteristic {rx_uuid} missing after discovery"); let msg = format!("rx characteristic {rx_uuid} missing after discovery");
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg); teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg);
return Err(msg); return Err(msg);
} }
}; (_, None) => {
let tx_char = match unsafe { find_char(service.0, tx_uuid) } {
Some(p) => SendPtr(p),
None => {
let msg = format!("tx characteristic {tx_uuid} missing after discovery"); let msg = format!("tx characteristic {tx_uuid} missing after discovery");
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg); teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg);
return Err(msg); return Err(msg);
} }
}; };
// The peripheral owns these; retain so they outlive any single
// delegate callback frame.
unsafe {
let _: *mut AnyObject = msg_send![rx_char.0, retain];
let _: *mut AnyObject = msg_send![tx_char.0, retain];
}
tracing::info!( tracing::info!(
target: "ble_trace", target: "ble_trace",
step = "apple_connect.chars_discovered", step = "apple_connect.chars_discovered",
@@ -339,11 +344,11 @@ pub async fn connect_peer(
// Step 4: setNotifyValue:YES on tx_char (CB handles CCCD internally). // Step 4: setNotifyValue:YES on tx_char (CB handles CCCD internally).
let rx = install_pending(&address, CallbackKind::Notify); let rx = install_pending(&address, CallbackKind::Notify);
unsafe { autoreleasepool(|_| unsafe {
let _: () = msg_send![peripheral.0, let _: () = msg_send![peripheral.0,
setNotifyValue: true, setNotifyValue: true,
forCharacteristic: tx_char.0]; forCharacteristic: tx_char.0];
} });
if let Err(e) = await_step(rx, "setNotifyValue", DISCOVERY_TIMEOUT).await { if let Err(e) = await_step(rx, "setNotifyValue", DISCOVERY_TIMEOUT).await {
// Balance the rx/tx retains on failure. // Balance the rx/tx retains on failure.
unsafe { unsafe {
@@ -437,17 +442,19 @@ fn enqueue_packet(peer: &ConnectedPeer, frames: Vec<Vec<u8>>) -> Result<bool, St
} }
fn drain_peer_queue(peer: &ConnectedPeer, q: &mut PacketQueue) { fn drain_peer_queue(peer: &ConnectedPeer, q: &mut PacketQueue) {
while q.drain_one(|data| { autoreleasepool(|_| {
if !peer.online.load(Ordering::SeqCst) { while q.drain_one(|data| {
return false; if !peer.online.load(Ordering::SeqCst) {
} return false;
let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] }; }
if !ready { let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] };
return false; if !ready {
} return false;
unsafe { issue_write(peer, data) }; }
true unsafe { issue_write(peer, data) };
}) {} true
}) {}
});
} }
/// Caller must have either confirmed `canSendWriteWithoutResponse` or be /// Caller must have either confirmed `canSendWriteWithoutResponse` or be
@@ -457,11 +464,11 @@ fn drain_peer_queue(peer: &ConnectedPeer, q: &mut PacketQueue) {
/// `peer.peripheral.0` and `peer.rx_char.0` must be retained, valid CB /// `peer.peripheral.0` and `peer.rx_char.0` must be retained, valid CB
/// pointers. /// pointers.
unsafe fn issue_write(peer: &ConnectedPeer, data: &[u8]) { unsafe fn issue_write(peer: &ConnectedPeer, data: &[u8]) {
let value = nsdata(data);
const WRITE_WITHOUT_RESPONSE: i64 = 1;
unsafe { unsafe {
let nsdata = nsdata_from_slice(data);
const WRITE_WITHOUT_RESPONSE: i64 = 1;
let _: () = msg_send![peer.peripheral.0, let _: () = msg_send![peer.peripheral.0,
writeValue: nsdata, writeValue: &*value,
forCharacteristic: peer.rx_char.0, forCharacteristic: peer.rx_char.0,
type: WRITE_WITHOUT_RESPONSE]; type: WRITE_WITHOUT_RESPONSE];
} }
@@ -481,10 +488,10 @@ pub fn disconnect_peer(address: &str) {
*q = PacketQueue::default(); *q = PacketQueue::default();
} }
if let Some(manager_ptr) = crate::ble_central_apple::central_manager_ptr() { if let Some(manager_ptr) = crate::ble_central_apple::central_manager_ptr() {
unsafe { autoreleasepool(|_| unsafe {
let _: () = msg_send![&*manager_ptr, let _: () = msg_send![&*manager_ptr,
cancelPeripheralConnection: peer.peripheral.0]; cancelPeripheralConnection: peer.peripheral.0];
} });
} }
// online_flags entry stays — the disconnect callback flips it. // online_flags entry stays — the disconnect callback flips it.
tracing::info!( tracing::info!(
@@ -575,8 +582,6 @@ pub unsafe fn adopt_restored_peer(
Some(p) => SendPtr(p), Some(p) => SendPtr(p),
None => { None => {
unsafe { unsafe {
let _: () = msg_send![rx_char.0, retain];
let _: () = msg_send![rx_char.0, release];
let _: () = msg_send![peripheral, release]; let _: () = msg_send![peripheral, release];
} }
return Err(format!( return Err(format!(
@@ -824,8 +829,8 @@ async fn await_step(
fn peripheral_delegate_class() -> &'static AnyClass { fn peripheral_delegate_class() -> &'static AnyClass {
DELEGATE_CLASS.get_or_init(|| { DELEGATE_CLASS.get_or_init(|| {
let superclass = AnyClass::get("NSObject").expect("NSObject must exist"); let superclass = AnyClass::get(c"NSObject").expect("NSObject must exist");
let mut builder = ClassBuilder::new("RatspeakBlePeripheralDelegate", superclass) let mut builder = ClassBuilder::new(c"RatspeakBlePeripheralDelegate", superclass)
.expect("ClassBuilder for peripheral delegate must succeed"); .expect("ClassBuilder for peripheral delegate must succeed");
extern "C" fn did_discover_services( extern "C" fn did_discover_services(
@@ -1015,41 +1020,11 @@ fn peripheral_delegate_class() -> &'static AnyClass {
}) })
} }
/// Autoreleased `NSArray<CBUUID>`; CB retains internally. /// Call inside `autoreleasepool`: the CBUUIDs autorelease.
fn build_cbuuid_array(uuids: &[Uuid]) -> *mut AnyObject { fn build_cbuuid_array(uuids: &[Uuid]) -> Retained<AnyObject> {
if uuids.is_empty() { let owned: Vec<_> = uuids.iter().map(cbuuid).collect();
return std::ptr::null_mut(); let refs: Vec<&AnyObject> = owned.iter().map(|u| &**u).collect();
} nsarray(&refs)
let cbuuid_cls = match AnyClass::get("CBUUID") {
Some(c) => c,
None => return std::ptr::null_mut(),
};
let nsarr_cls = match AnyClass::get("NSArray") {
Some(c) => c,
None => return std::ptr::null_mut(),
};
let mut raw_ptrs: Vec<*const AnyObject> = Vec::with_capacity(uuids.len());
for u in uuids {
let s = NSString::from_str(&u.to_string());
unsafe {
let cb: *mut AnyObject = msg_send![cbuuid_cls, UUIDWithString: &*s];
raw_ptrs.push(cb as *const AnyObject);
}
}
unsafe {
msg_send![nsarr_cls,
arrayWithObjects: raw_ptrs.as_ptr(),
count: raw_ptrs.len()]
}
}
/// Autoreleased `NSData` over a copy of `bytes`; valid for the synchronous
/// CB call only.
unsafe fn nsdata_from_slice(bytes: &[u8]) -> *mut AnyObject {
let cls = AnyClass::get("NSData").expect("NSData class must exist");
let ptr = bytes.as_ptr() as *const std::ffi::c_void;
let len = bytes.len();
unsafe { msg_send![cls, dataWithBytes: ptr, length: len] }
} }
unsafe fn find_service(peripheral: *mut AnyObject, uuid: Uuid) -> Option<*mut AnyObject> { unsafe fn find_service(peripheral: *mut AnyObject, uuid: Uuid) -> Option<*mut AnyObject> {
@@ -1204,6 +1179,13 @@ unsafe fn nsstring_to_string(s: *mut AnyObject) -> String {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn cbuuid_filter_holds_no_extra_retains() {
assert!(crate::apple_objc::tests::freed_on_drop(|| {
autoreleasepool(|_| vec![build_cbuuid_array(&[RATSPEAK_RX_UUID, RATSPEAK_TX_UUID])])
}));
}
#[test] #[test]
fn expand_short_uuid_round_trip_16bit() { fn expand_short_uuid_round_trip_16bit() {
let u = expand_short_uuid("180D").expect("must parse"); let u = expand_short_uuid("180D").expect("must parse");
+97 -115
View File
@@ -1510,8 +1510,15 @@ pub(crate) fn try_push_apple_inbound(peer: String, data: Vec<u8>) -> bool {
#[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg(any(target_os = "ios", target_os = "macos"))]
mod apple_peripheral { mod apple_peripheral {
use super::*; use super::*;
use crate::apple_objc::{cbuuid, nsarray, nsdata};
use objc2::rc::{Allocated, Retained, autoreleasepool};
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel}; use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
use objc2::{msg_send, sel}; use objc2::{msg_send, sel};
use objc2_core_bluetooth::{
CBPeripheralManagerOptionRestoreIdentifierKey,
CBPeripheralManagerRestoredStateAdvertisementDataKey,
CBPeripheralManagerRestoredStateServicesKey,
};
use objc2_foundation::NSString; use objc2_foundation::NSString;
use std::sync::OnceLock; use std::sync::OnceLock;
@@ -1631,15 +1638,6 @@ mod apple_peripheral {
/// previously-backgrounded GATT subscriptions. /// previously-backgrounded GATT subscriptions.
const PERIPHERAL_RESTORE_ID: &str = "org.ratspeak.ios.peripheral"; const PERIPHERAL_RESTORE_ID: &str = "org.ratspeak.ios.peripheral";
// objc2-core-bluetooth 0.2.2 only exports the central-role keys; link
// the peripheral-role NSString constants directly.
#[link(name = "CoreBluetooth", kind = "framework")]
unsafe extern "C" {
static CBPeripheralManagerOptionRestoreIdentifierKey: &'static NSString;
static CBPeripheralManagerRestoredStateServicesKey: &'static NSString;
static CBPeripheralManagerRestoredStateAdvertisementDataKey: &'static NSString;
}
/// Ratspeak primary + Columba compat. /// Ratspeak primary + Columba compat.
const EXPECTED_SERVICE_COUNT: usize = 2; const EXPECTED_SERVICE_COUNT: usize = 2;
@@ -1856,8 +1854,8 @@ mod apple_peripheral {
fn get_delegate_class() -> &'static AnyClass { fn get_delegate_class() -> &'static AnyClass {
DELEGATE_CLASS.get_or_init(|| { DELEGATE_CLASS.get_or_init(|| {
let superclass = AnyClass::get("NSObject").unwrap(); let superclass = AnyClass::get(c"NSObject").unwrap();
let mut builder = ClassBuilder::new("RatspeakBleDelegate", superclass).unwrap(); let mut builder = ClassBuilder::new(c"RatspeakBleDelegate", superclass).unwrap();
extern "C" fn did_update_state( extern "C" fn did_update_state(
_this: *mut AnyObject, _this: *mut AnyObject,
@@ -2488,40 +2486,27 @@ mod apple_peripheral {
return false; return false;
} }
}; };
unsafe { autoreleasepool(|_| unsafe {
let arr_cls = match AnyClass::get("NSArray") { let payload = nsdata(data);
Some(c) => c, let centrals = match to_peer {
None => return false, Some(peer_id) => {
}; let map = subscribed_centrals_map().lock().unwrap();
let data_cls = match AnyClass::get("NSData") { let Some(central) = map.get(peer_id) else {
Some(c) => c,
None => return false,
};
let payload: *mut AnyObject = msg_send![data_cls,
dataWithBytes: data.as_ptr() as *const std::ffi::c_void,
length: data.len()];
let centrals: *mut AnyObject = if let Some(peer_id) = to_peer {
let map = subscribed_centrals_map().lock().unwrap();
let ptr = match map.get(peer_id) {
Some(p) => p.0,
None => {
tracing::warn!(peer = %peer_id, "Apple BLE notify_tx: peer not in subscribed map"); tracing::warn!(peer = %peer_id, "Apple BLE notify_tx: peer not in subscribed map");
return false; return false;
} };
}; Some(nsarray(&[&*central.0]))
let one = [ptr as *const AnyObject]; }
msg_send![arr_cls, arrayWithObjects: one.as_ptr(), count: 1usize] None => None,
} else {
std::ptr::null_mut()
}; };
let ok: bool = msg_send![ let ok: bool = msg_send![
mgr, mgr,
updateValue: payload, updateValue: &*payload,
forCharacteristic: char_ptr, forCharacteristic: char_ptr,
onSubscribedCentrals: centrals, onSubscribedCentrals: centrals.as_deref(),
]; ];
ok ok
} })
} }
// We only need the TX chars from notify_tx, but the registry is keyed // We only need the TX chars from notify_tx, but the registry is keyed
@@ -2556,17 +2541,6 @@ mod apple_peripheral {
.map(|(uuid, _)| *uuid) .map(|(uuid, _)| *uuid)
} }
/// Returns a raw retained pointer.
fn cbuuid(uuid: &Uuid) -> *mut AnyObject {
let s = NSString::from_str(&uuid.to_string());
unsafe {
let cls = AnyClass::get("CBUUID").unwrap();
let obj: *mut AnyObject = msg_send![cls, UUIDWithString: &*s];
let _: *mut AnyObject = msg_send![obj, retain];
obj
}
}
pub async fn start_advertising(identity_hash: &[u8]) -> Result<(), String> { pub async fn start_advertising(identity_hash: &[u8]) -> Result<(), String> {
// Drive the lifecycle BEFORE any side effects. // Drive the lifecycle BEFORE any side effects.
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::StartRequested); apply_event(crate::ble_peer_lifecycle::LifecycleEvent::StartRequested);
@@ -2608,7 +2582,7 @@ mod apple_peripheral {
let delegate_raw: *mut AnyObject = msg_send![delegate_cls, alloc]; let delegate_raw: *mut AnyObject = msg_send![delegate_cls, alloc];
let delegate_raw: *mut AnyObject = msg_send![delegate_raw, init]; let delegate_raw: *mut AnyObject = msg_send![delegate_raw, init];
let Some(mgr_cls) = AnyClass::get("CBPeripheralManager") else { let Some(mgr_cls) = AnyClass::get(c"CBPeripheralManager") else {
tracing::error!("iOS BLE Peripheral: CBPeripheralManager class not found"); tracing::error!("iOS BLE Peripheral: CBPeripheralManager class not found");
return; return;
}; };
@@ -2617,7 +2591,7 @@ mod apple_peripheral {
// background BLE event after the process is killed. // background BLE event after the process is killed.
let opts: *mut AnyObject = { let opts: *mut AnyObject = {
let dict_cls = let dict_cls =
AnyClass::get("NSDictionary").expect("NSDictionary must exist at runtime"); AnyClass::get(c"NSDictionary").expect("NSDictionary must exist at runtime");
let id = NSString::from_str(PERIPHERAL_RESTORE_ID); let id = NSString::from_str(PERIPHERAL_RESTORE_ID);
msg_send![dict_cls, msg_send![dict_cls,
dictionaryWithObject: &*id, dictionaryWithObject: &*id,
@@ -2682,68 +2656,21 @@ mod apple_peripheral {
mgr_raw: *mut AnyObject, mgr_raw: *mut AnyObject,
id_hash: &[u8], id_hash: &[u8],
) -> Result<(), String> { ) -> Result<(), String> {
unsafe { autoreleasepool(|_| unsafe {
let char_cls = AnyClass::get("CBMutableCharacteristic") let gatt = build_gatt_services()?;
.ok_or("CBMutableCharacteristic not found")?; let dict_cls = AnyClass::get(c"NSDictionary").ok_or("NSDictionary not found")?;
let svc_cls = AnyClass::get("CBMutableService").ok_or("CBMutableService not found")?; // The registry owns these +1s until it is drained.
let arr_cls = AnyClass::get("NSArray").ok_or("NSArray not found")?; register_characteristic(RATSPEAK_TX_UUID, Retained::into_raw(gatt.ratspeak_tx));
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?; register_characteristic(COLUMBA_TX_UUID, Retained::into_raw(gatt.columba_tx));
// The manager retains each service.
// RX (write + writeNoResponse) let _: () = msg_send![mgr_raw, addService: &*gatt.ratspeak];
let rx_raw: *mut AnyObject = msg_send![char_cls, alloc]; let _: () = msg_send![mgr_raw, addService: &*gatt.columba];
let rx_raw: *mut AnyObject = msg_send![rx_raw,
initWithType: cbuuid(&RATSPEAK_RX_UUID), properties: 0x0Cu64,
value: std::ptr::null::<AnyObject>(), permissions: 0x02u64];
// TX (read + notify)
let tx_raw: *mut AnyObject = msg_send![char_cls, alloc];
let tx_raw: *mut AnyObject = msg_send![tx_raw,
initWithType: cbuuid(&RATSPEAK_TX_UUID), properties: 0x12u64,
value: std::ptr::null::<AnyObject>(), permissions: 0x01u64];
// Keep the registry pointer valid for notify_tx.
let _: *mut AnyObject = msg_send![tx_raw, retain];
register_characteristic(RATSPEAK_TX_UUID, tx_raw);
// No static ID characteristic: it exposed a MAC-rotation-stable
// identity read to any connecting scanner (a tracking vector) and
// was never read by this stack — identity is learned from signed
// announces instead.
// Ratspeak service (primary)
let svc_raw: *mut AnyObject = msg_send![svc_cls, alloc];
let svc_raw: *mut AnyObject = msg_send![svc_raw,
initWithType: cbuuid(&RATSPEAK_SERVICE_UUID), primary: true];
let char_ptrs = [rx_raw as *const AnyObject, tx_raw as *const AnyObject];
let chars: *mut AnyObject = msg_send![arr_cls,
arrayWithObjects: char_ptrs.as_ptr(), count: 2usize];
let _: () = msg_send![svc_raw, setCharacteristics: chars];
let _: () = msg_send![mgr_raw, addService: svc_raw];
// Columba compat (secondary, omitted from advertising payload).
let c_rx_raw: *mut AnyObject = msg_send![char_cls, alloc];
let c_rx_raw: *mut AnyObject = msg_send![c_rx_raw,
initWithType: cbuuid(&COLUMBA_RX_UUID), properties: 0x0Cu64,
value: std::ptr::null::<AnyObject>(), permissions: 0x02u64];
let c_tx_raw: *mut AnyObject = msg_send![char_cls, alloc];
let c_tx_raw: *mut AnyObject = msg_send![c_tx_raw,
initWithType: cbuuid(&COLUMBA_TX_UUID), properties: 0x12u64,
value: std::ptr::null::<AnyObject>(), permissions: 0x01u64];
let _: *mut AnyObject = msg_send![c_tx_raw, retain];
register_characteristic(COLUMBA_TX_UUID, c_tx_raw);
let c_svc_raw: *mut AnyObject = msg_send![svc_cls, alloc];
let c_svc_raw: *mut AnyObject = msg_send![c_svc_raw,
initWithType: cbuuid(&COLUMBA_SERVICE_UUID), primary: false];
let c_char_ptrs = [c_rx_raw as *const AnyObject, c_tx_raw as *const AnyObject];
let c_chars: *mut AnyObject = msg_send![arr_cls,
arrayWithObjects: c_char_ptrs.as_ptr(), count: 2usize];
let _: () = msg_send![c_svc_raw, setCharacteristics: c_chars];
let _: () = msg_send![mgr_raw, addService: c_svc_raw];
// One 128-bit UUID fits in the 31-byte BLE 4.x adv PDU; two do not. // One 128-bit UUID fits in the 31-byte BLE 4.x adv PDU; two do not.
let ad_key = NSString::from_str("kCBAdvDataServiceUUIDs"); let ad_key = NSString::from_str("kCBAdvDataServiceUUIDs");
let uuid_ptrs = [cbuuid(&RATSPEAK_SERVICE_UUID) as *const AnyObject]; let uuid_arr = nsarray(&[&*cbuuid(&RATSPEAK_SERVICE_UUID)]);
let uuid_arr: *mut AnyObject = msg_send![arr_cls,
arrayWithObjects: uuid_ptrs.as_ptr(), count: 1usize];
let ad_dict: *mut AnyObject = msg_send![dict_cls, let ad_dict: *mut AnyObject = msg_send![dict_cls,
dictionaryWithObject: uuid_arr, forKey: &*ad_key]; dictionaryWithObject: &*uuid_arr, forKey: &*ad_key];
let _: () = msg_send![mgr_raw, startAdvertising: ad_dict]; let _: () = msg_send![mgr_raw, startAdvertising: ad_dict];
tracing::info!( tracing::info!(
@@ -2755,7 +2682,53 @@ mod apple_peripheral {
"Apple BLE Peripheral: advertising started" "Apple BLE Peripheral: advertising started"
); );
Ok(()) Ok(())
} })
}
struct GattServices {
ratspeak: Retained<AnyObject>,
columba: Retained<AnyObject>,
ratspeak_tx: Retained<AnyObject>,
columba_tx: Retained<AnyObject>,
}
/// Call inside `autoreleasepool`: the CBUUIDs autorelease. No static ID
/// characteristic: it exposed a MAC-rotation-stable identity read to any
/// connecting scanner (a tracking vector) and was never read by this
/// stack — identity is learned from signed announces instead.
unsafe fn build_gatt_services() -> Result<GattServices, String> {
let char_cls =
AnyClass::get(c"CBMutableCharacteristic").ok_or("CBMutableCharacteristic not found")?;
let svc_cls = AnyClass::get(c"CBMutableService").ok_or("CBMutableService not found")?;
// RX: write + writeNoResponse, writeable. TX: read + notify, readable.
let characteristic = |uuid: &Uuid, properties: u64, permissions: u64| unsafe {
let obj: Allocated<AnyObject> = msg_send![char_cls, alloc];
let obj: Retained<AnyObject> = msg_send![obj,
initWithType: &*cbuuid(uuid), properties: properties,
value: std::ptr::null::<AnyObject>(), permissions: permissions];
obj
};
let service = |uuid: &Uuid, primary: bool, rx: &AnyObject, tx: &AnyObject| unsafe {
let obj: Allocated<AnyObject> = msg_send![svc_cls, alloc];
let obj: Retained<AnyObject> =
msg_send![obj, initWithType: &*cbuuid(uuid), primary: primary];
let chars = nsarray(&[rx, tx]);
let _: () = msg_send![&*obj, setCharacteristics: &*chars];
obj
};
let rx = characteristic(&RATSPEAK_RX_UUID, 0x0C, 0x02);
let ratspeak_tx = characteristic(&RATSPEAK_TX_UUID, 0x12, 0x01);
let ratspeak = service(&RATSPEAK_SERVICE_UUID, true, &rx, &ratspeak_tx);
// Columba compat: secondary, omitted from the advertising payload.
let c_rx = characteristic(&COLUMBA_RX_UUID, 0x0C, 0x02);
let columba_tx = characteristic(&COLUMBA_TX_UUID, 0x12, 0x01);
let columba = service(&COLUMBA_SERVICE_UUID, false, &c_rx, &columba_tx);
Ok(GattServices {
ratspeak,
columba,
ratspeak_tx,
columba_tx,
})
} }
/// Walks the lifecycle state machine in lockstep with the platform /// Walks the lifecycle state machine in lockstep with the platform
@@ -2829,9 +2802,9 @@ mod apple_peripheral {
let mgr_send = SendPtr(mgr_ptr); let mgr_send = SendPtr(mgr_ptr);
if needs_stop_ad { if needs_stop_ad {
unsafe { autoreleasepool(|_| unsafe {
let _: () = msg_send![mgr_send.0, stopAdvertising]; let _: () = msg_send![mgr_send.0, stopAdvertising];
} });
// CB has no peripheralManagerDidStopAdvertising delegate — poll // CB has no peripheralManagerDidStopAdvertising delegate — poll
// `isAdvertising`. Radio flips within ~20ms; 1s budget covers // `isAdvertising`. Radio flips within ~20ms; 1s budget covers
// contended radios and bounce loops. // contended radios and bounce loops.
@@ -2855,13 +2828,13 @@ mod apple_peripheral {
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::AdvertiseStopped); apply_event(crate::ble_peer_lifecycle::LifecycleEvent::AdvertiseStopped);
} }
unsafe { autoreleasepool(|_| unsafe {
let _: () = msg_send![mgr_send.0, removeAllServices]; let _: () = msg_send![mgr_send.0, removeAllServices];
} });
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::ServicesRemoved); apply_event(crate::ble_peer_lifecycle::LifecycleEvent::ServicesRemoved);
// Without this, every toggle cycle leaks two CBMutableCharacteristic // Releases the registry's TX characteristics, so notify_tx can't race
// pointers and notify_tx can race onto dead characteristics post-teardown. // onto dead characteristics post-teardown.
{ {
let mut map = characteristic_registry().lock().unwrap(); let mut map = characteristic_registry().lock().unwrap();
for (_, ptr) in map.drain() { for (_, ptr) in map.drain() {
@@ -2930,6 +2903,15 @@ mod apple_peripheral {
mod notify_tests { mod notify_tests {
use super::*; use super::*;
#[test] #[test]
fn gatt_services_hold_no_extra_retains() {
assert!(crate::apple_objc::tests::freed_on_drop(|| {
autoreleasepool(|_| {
let g = unsafe { build_gatt_services() }.unwrap();
vec![g.ratspeak, g.columba, g.ratspeak_tx, g.columba_tx]
})
}));
}
#[test]
fn readiness_keeps_partial_packet_first_across_characteristics() { fn readiness_keeps_partial_packet_first_across_characteristics() {
let mut state = NotifyState { let mut state = NotifyState {
accepting: true, accepting: true,
+2
View File
@@ -9,6 +9,8 @@ pub mod android_usb;
mod android_usb_lifecycle; mod android_usb_lifecycle;
#[cfg(any(target_os = "android", test))] #[cfg(any(target_os = "android", test))]
mod android_usb_setup; mod android_usb_setup;
#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))]
mod apple_objc;
pub mod auto; pub mod auto;
pub mod ax25kiss; pub mod ax25kiss;
pub mod backbone; pub mod backbone;