Skip to main content

webbluetooth_apple/
objc.rs

1//! Objective-C runtime: message sends, collection readers, and class synthesis.
2//!
3//! CoreBluetooth exports no Swift-native symbols — its `.tbd` lists Objective-C
4//! classes and nothing mangled — so the Swift metadata synthesis that
5//! `swiftui-native`'s `state`/`conformance` modules perform has no target here.
6//! The equivalent for an Objective-C framework is [`ClassBuilder`], modelled on
7//! `swiftui-native::objc`: allocate a class pair, give it methods whose
8//! implementations are `extern "C"` Rust functions, declare the protocol, and
9//! register it. That is how [`crate::delegate`] produces a
10//! `CBCentralManagerDelegate` without a line of Objective-C or Swift.
11//!
12//! Message sends go through `apple-objc-sys`, whose `msg_send!` family
13//! transmutes `objc_msgSend` to a correctly-typed, *non-variadic* signature per
14//! call site. That matters on arm64: variadic arguments are passed on the
15//! stack, so a variadic declaration delivers them where the receiver never
16//! looks.
17
18use core::ffi::{c_char, c_void, CStr};
19
20/// An opaque Objective-C object pointer.
21pub type Id = *mut c_void;
22/// An opaque Objective-C selector.
23pub type Sel = *const c_void;
24/// `nil`.
25pub const NIL: Id = core::ptr::null_mut();
26
27unsafe extern "C" {
28    /// Declared variadic to match the symbol; never called through this
29    /// declaration. See [`crate::macros`].
30    pub fn objc_msgSend(receiver: Id, sel: Sel, ...) -> Id;
31    pub fn sel_registerName(name: *const c_char) -> Sel;
32    fn objc_getClass(name: *const c_char) -> Id;
33    fn objc_getProtocol(name: *const c_char) -> *mut c_void;
34    fn objc_allocateClassPair(sup: Id, name: *const c_char, extra: usize) -> Id;
35    fn objc_registerClassPair(cls: Id);
36    fn class_addMethod(cls: Id, sel: Sel, imp: *const c_void, types: *const c_char) -> bool;
37    fn class_addProtocol(cls: Id, protocol: *mut c_void) -> bool;
38    fn objc_retain(obj: Id) -> Id;
39    fn objc_release(obj: Id);
40    fn objc_autoreleasePoolPush() -> *mut c_void;
41    fn objc_autoreleasePoolPop(ctx: *mut c_void);
42    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
43}
44
45const RTLD_DEFAULT: *mut c_void = -2isize as *mut c_void;
46
47/// Register (or look up) a selector.
48#[inline]
49pub fn sel(name: &CStr) -> Sel {
50    unsafe { sel_registerName(name.as_ptr()) }
51}
52
53/// Look up a registered class by name. Null if the framework is not loaded.
54#[inline]
55pub fn class(name: &CStr) -> Id {
56    unsafe { objc_getClass(name.as_ptr()) }
57}
58
59/// Look up a class, panicking with the name if it is missing.
60#[inline]
61pub fn require_class(name: &CStr) -> Id {
62    let c = class(name);
63    assert!(!c.is_null(), "Objective-C class not found: {name:?}");
64    c
65}
66
67/// Look up a protocol. Null unless some loaded image references it.
68#[inline]
69pub fn protocol(name: &CStr) -> *mut c_void {
70    unsafe { objc_getProtocol(name.as_ptr()) }
71}
72
73/// Read a global `NSString * const` (e.g. `CBAdvertisementDataLocalNameKey`).
74///
75/// The symbol is a pointer *to* the string pointer, so this dereferences once.
76pub fn global_nsstring(symbol: &CStr) -> Id {
77    unsafe {
78        let p = dlsym(RTLD_DEFAULT, symbol.as_ptr());
79        if p.is_null() {
80            NIL
81        } else {
82            *(p as *const Id)
83        }
84    }
85}
86
87// ── Ownership ───────────────────────────────────────────────────────────────
88
89/// A `+1` Objective-C reference, released on drop.
90///
91/// Delegate callbacks hand over objects they own; anything kept past the end of
92/// the callback — a peripheral we are about to connect to, the characteristic a
93/// pending read belongs to — has to be retained, and the retain has to be
94/// balanced from Rust's side rather than by an autorelease pool that drained
95/// when the callback returned.
96#[derive(Debug)]
97pub struct Retained(Id);
98
99impl Retained {
100    /// Retain a borrowed pointer. `None` if null.
101    ///
102    /// # Safety
103    /// `ptr` must be null or a live Objective-C object.
104    pub unsafe fn retain(ptr: Id) -> Option<Self> {
105        if ptr.is_null() {
106            return None;
107        }
108        Some(Self(unsafe { objc_retain(ptr) }))
109    }
110
111    /// Adopt a pointer already owned at `+1` (from `alloc`/`new`/`copy`).
112    ///
113    /// # Safety
114    /// `ptr` must be null or an object the caller owns a reference to.
115    pub unsafe fn adopt(ptr: Id) -> Option<Self> {
116        if ptr.is_null() {
117            return None;
118        }
119        Some(Self(ptr))
120    }
121
122    #[inline]
123    pub fn as_ptr(&self) -> Id {
124        self.0
125    }
126
127    /// The pointer value, used as a stable identity key.
128    ///
129    /// CoreBluetooth hands back the *same* `CBService` / `CBCharacteristic`
130    /// instances for the life of a connection, so the address correlates a
131    /// delegate callback with the request that provoked it.
132    #[inline]
133    pub fn key(&self) -> usize {
134        self.0 as usize
135    }
136}
137
138impl Clone for Retained {
139    fn clone(&self) -> Self {
140        Self(unsafe { objc_retain(self.0) })
141    }
142}
143
144impl Drop for Retained {
145    fn drop(&mut self) {
146        unsafe { objc_release(self.0) }
147    }
148}
149
150impl PartialEq for Retained {
151    fn eq(&self, other: &Self) -> bool {
152        self.0 == other.0
153    }
154}
155impl Eq for Retained {}
156
157// CoreBluetooth objects are delivered on our own serial queue and are safe to
158// message from any thread; the retain count itself is atomic.
159unsafe impl Send for Retained {}
160unsafe impl Sync for Retained {}
161
162/// An autorelease pool, drained on drop.
163///
164/// A Rust program has no Cocoa event loop to provide one, so without this every
165/// autoreleased temporary — every `UUIDString`, every `NSData` — accumulates
166/// for the life of the process.
167pub struct AutoreleasePool(*mut c_void);
168
169impl AutoreleasePool {
170    pub fn new() -> Self {
171        Self(unsafe { objc_autoreleasePoolPush() })
172    }
173}
174impl Default for AutoreleasePool {
175    fn default() -> Self {
176        Self::new()
177    }
178}
179impl Drop for AutoreleasePool {
180    fn drop(&mut self) {
181        unsafe { objc_autoreleasePoolPop(self.0) }
182    }
183}
184
185// ── Foundation readers ──────────────────────────────────────────────────────
186
187/// Create an `NSString` from a Rust `&str`. Returned at `+1`.
188///
189/// # Safety
190/// Caller owns the result.
191pub unsafe fn nsstring(s: &str) -> Id {
192    unsafe {
193        let alloc = msg_send![require_class(c"NSString"), alloc];
194        type InitBytes = unsafe extern "C" fn(Id, Sel, *const u8, usize, usize) -> Id;
195        let f: InitBytes = core::mem::transmute(objc_msgSend as *const ());
196        // 4 = NSUTF8StringEncoding
197        f(
198            alloc,
199            sel(c"initWithBytes:length:encoding:"),
200            s.as_ptr(),
201            s.len(),
202            4,
203        )
204    }
205}
206
207/// Read an `NSString` into a Rust `String`. `None` if null.
208///
209/// # Safety
210/// `s` must be null or an `NSString`.
211pub unsafe fn to_string(s: Id) -> Option<String> {
212    if s.is_null() {
213        return None;
214    }
215    unsafe {
216        let c: *const c_char = msg_send_t![*const c_char; s, UTF8String];
217        if c.is_null() {
218            return None;
219        }
220        Some(CStr::from_ptr(c).to_string_lossy().into_owned())
221    }
222}
223
224/// Number of elements in an `NSArray`. Zero if null.
225///
226/// # Safety
227/// `array` must be null or an `NSArray`.
228pub unsafe fn array_count(array: Id) -> usize {
229    if array.is_null() {
230        return 0;
231    }
232    unsafe { msg_send_t![usize; array, count] }
233}
234
235/// Element `i` of an `NSArray`, borrowed.
236///
237/// # Safety
238/// `array` must be an `NSArray` and `i` within bounds.
239pub unsafe fn array_get(array: Id, i: usize) -> Id {
240    unsafe { msg_send![array, objectAtIndex: i] }
241}
242
243/// Collect an `NSArray` into a `Vec` by applying `f` to each borrowed element.
244///
245/// # Safety
246/// `array` must be null or an `NSArray`.
247pub unsafe fn array_map<T>(array: Id, mut f: impl FnMut(Id) -> T) -> Vec<T> {
248    let n = unsafe { array_count(array) };
249    (0..n).map(|i| f(unsafe { array_get(array, i) })).collect()
250}
251
252/// Build an `NSArray` from borrowed elements. Returned at `+1`.
253///
254/// # Safety
255/// Every element must be a live object. Caller owns the result.
256pub unsafe fn nsarray(items: &[Id]) -> Id {
257    unsafe {
258        type WithObjects = unsafe extern "C" fn(Id, Sel, *const Id, usize) -> Id;
259        let f: WithObjects = core::mem::transmute(objc_msgSend as *const ());
260        let arr = f(
261            require_class(c"NSArray"),
262            sel(c"arrayWithObjects:count:"),
263            items.as_ptr(),
264            items.len(),
265        );
266        objc_retain(arr)
267    }
268}
269
270/// Build an `NSDictionary` from parallel borrowed key/value slices. `+1`.
271///
272/// # Safety
273/// The slices must be the same length and hold live objects. Caller owns the
274/// result.
275pub unsafe fn nsdictionary(keys: &[Id], values: &[Id]) -> Option<Retained> {
276    debug_assert_eq!(keys.len(), values.len());
277    unsafe {
278        let k = Retained::adopt(nsarray(keys))?;
279        let v = Retained::adopt(nsarray(values))?;
280        let d: Id = msg_send![
281            require_class(c"NSDictionary"),
282            dictionaryWithObjects: v.as_ptr(),
283            forKeys: k.as_ptr()
284        ];
285        Retained::retain(d)
286    }
287}
288
289/// `[dict objectForKey: key]`, borrowed. Null if either is null or absent.
290///
291/// # Safety
292/// `dict` must be null or an `NSDictionary`.
293pub unsafe fn dict_get(dict: Id, key: Id) -> Id {
294    if dict.is_null() || key.is_null() {
295        return NIL;
296    }
297    unsafe { msg_send![dict, objectForKey: key] }
298}
299
300/// All keys of an `NSDictionary`, borrowed.
301///
302/// # Safety
303/// `dict` must be null or an `NSDictionary`.
304pub unsafe fn dict_keys(dict: Id) -> Id {
305    if dict.is_null() {
306        return NIL;
307    }
308    unsafe { msg_send![dict, allKeys] }
309}
310
311/// Copy an `NSData` into a `Vec<u8>`. `None` if null.
312///
313/// # Safety
314/// `data` must be null or an `NSData`.
315pub unsafe fn data_bytes(data: Id) -> Option<Vec<u8>> {
316    if data.is_null() {
317        return None;
318    }
319    unsafe {
320        let len = msg_send_t![usize; data, length];
321        let ptr = msg_send_t![*const u8; data, bytes];
322        if ptr.is_null() || len == 0 {
323            return Some(Vec::new());
324        }
325        Some(core::slice::from_raw_parts(ptr, len).to_vec())
326    }
327}
328
329/// Build an `NSData` from bytes. Returned at `+1`.
330///
331/// # Safety
332/// Caller owns the result.
333pub unsafe fn nsdata(bytes: &[u8]) -> Id {
334    unsafe {
335        // On the write path, so the class and both selectors are resolved
336        // once rather than per packet. See `cached_sel`.
337        let alloc = msg_send![crate::cached_class!(c"NSData"), alloc];
338        type InitBytes = unsafe extern "C" fn(Id, Sel, *const u8, usize) -> Id;
339        let f: InitBytes = core::mem::transmute(objc_msgSend as *const ());
340        f(
341            alloc,
342            crate::cached_sel!("initWithBytes:length:\0"),
343            bytes.as_ptr(),
344            bytes.len(),
345        )
346    }
347}
348
349/// `[number integerValue]`. `None` if null.
350///
351/// # Safety
352/// `n` must be null or an `NSNumber`.
353pub unsafe fn number_i64(n: Id) -> Option<i64> {
354    if n.is_null() {
355        return None;
356    }
357    Some(unsafe { msg_send_t![isize; n, integerValue] } as i64)
358}
359
360/// `[number boolValue]`. `None` if null.
361///
362/// # Safety
363/// `n` must be null or an `NSNumber`.
364pub unsafe fn number_bool(n: Id) -> Option<bool> {
365    if n.is_null() {
366        return None;
367    }
368    Some(unsafe { msg_send_t![bool; n, boolValue] })
369}
370
371/// `[error localizedDescription]` plus its code. `None` if the error is null.
372///
373/// # Safety
374/// `err` must be null or an `NSError`.
375pub unsafe fn error_message(err: Id) -> Option<(i64, String)> {
376    if err.is_null() {
377        return None;
378    }
379    unsafe {
380        let code = msg_send_t![isize; err, code] as i64;
381        let desc = to_string(msg_send![err, localizedDescription])
382            .unwrap_or_else(|| "unknown CoreBluetooth error".into());
383        Some((code, desc))
384    }
385}
386
387// ── Class synthesis ─────────────────────────────────────────────────────────
388
389/// A class under construction. Add methods, declare protocols, then
390/// [`register`](ClassBuilder::register).
391///
392/// This is the Objective-C counterpart of building a Swift type at runtime:
393/// CoreBluetooth will not talk to anything but a delegate *object*, and writing
394/// one in Objective-C would mean shipping a source file and a compiler step, so
395/// it is synthesised here instead.
396pub struct ClassBuilder {
397    class: Id,
398}
399
400impl ClassBuilder {
401    /// Begin a new class. `None` if `name` is already registered — which is how
402    /// a second copy of this crate in the same process is detected.
403    ///
404    /// # Safety
405    /// `superclass` must name a registered class.
406    pub unsafe fn new(superclass: &CStr, name: &CStr) -> Option<Self> {
407        unsafe {
408            let sup = objc_getClass(superclass.as_ptr());
409            assert!(!sup.is_null(), "superclass not found: {superclass:?}");
410            let class = objc_allocateClassPair(sup, name.as_ptr(), 0);
411            if class.is_null() {
412                return None;
413            }
414            Some(Self { class })
415        }
416    }
417
418    /// Add a method.
419    ///
420    /// `types` is an Objective-C type encoding: return type, then `@:` for the
421    /// implicit receiver and selector, then one code per argument. Every
422    /// CoreBluetooth delegate method returns void and takes only objects, so
423    /// these are all `v@:` followed by one `@` per argument — no `BOOL`, whose
424    /// encoding differs between arm64 (`B`) and x86_64 (`c`).
425    ///
426    /// # Safety
427    /// `imp`'s signature must match `types`, receiver and selector included.
428    pub unsafe fn method(self, selector: &CStr, imp: *const c_void, types: &CStr) -> Self {
429        unsafe {
430            let ok = class_addMethod(self.class, sel(selector), imp, types.as_ptr());
431            assert!(ok, "could not add method {selector:?}");
432        }
433        self
434    }
435
436    /// Declare conformance to a protocol. Silently skipped if the protocol is
437    /// not registered, which only happens if the framework is not loaded.
438    ///
439    /// # Safety
440    /// The class must implement the protocol's required methods.
441    pub unsafe fn conforms(self, name: &CStr) -> Self {
442        unsafe {
443            let p = objc_getProtocol(name.as_ptr());
444            if !p.is_null() {
445                class_addProtocol(self.class, p);
446            }
447        }
448        self
449    }
450
451    /// Register the class with the runtime and return it.
452    pub fn register(self) -> Id {
453        unsafe { objc_registerClassPair(self.class) };
454        self.class
455    }
456}