|
| 1 | +/* |
| 2 | + * Copyright (C) 2024 The Android Open Source Project |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +use crate::proxy::SpIBinder; |
| 18 | +use crate::sys; |
| 19 | + |
| 20 | +use std::ffi::{c_void, CStr, CString}; |
| 21 | +use std::os::raw::c_char; |
| 22 | + |
| 23 | +use libc::sockaddr; |
| 24 | +use nix::sys::socket::{SockaddrLike, UnixAddr, VsockAddr}; |
| 25 | +use std::sync::Arc; |
| 26 | +use std::{fmt, ptr}; |
| 27 | + |
| 28 | +/// Rust wrapper around ABinderRpc_Accessor objects for RPC binder service management. |
| 29 | +/// |
| 30 | +/// Dropping the `Accessor` will drop the underlying object and the binder it owns. |
| 31 | +pub struct Accessor { |
| 32 | + accessor: *mut sys::ABinderRpc_Accessor, |
| 33 | +} |
| 34 | + |
| 35 | +impl fmt::Debug for Accessor { |
| 36 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 37 | + write!(f, "ABinderRpc_Accessor({:p})", self.accessor) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +/// Socket connection info required for libbinder to connect to a service. |
| 42 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 43 | +pub enum ConnectionInfo { |
| 44 | + /// For vsock connection |
| 45 | + Vsock(VsockAddr), |
| 46 | + /// For unix domain socket connection |
| 47 | + Unix(UnixAddr), |
| 48 | +} |
| 49 | + |
| 50 | +/// Safety: A `Accessor` is a wrapper around `ABinderRpc_Accessor` which is |
| 51 | +/// `Sync` and `Send`. As |
| 52 | +/// `ABinderRpc_Accessor` is threadsafe, this structure is too. |
| 53 | +/// The Fn owned the Accessor has `Sync` and `Send` properties |
| 54 | +unsafe impl Send for Accessor {} |
| 55 | + |
| 56 | +/// Safety: A `Accessor` is a wrapper around `ABinderRpc_Accessor` which is |
| 57 | +/// `Sync` and `Send`. As `ABinderRpc_Accessor` is threadsafe, this structure is too. |
| 58 | +/// The Fn owned the Accessor has `Sync` and `Send` properties |
| 59 | +unsafe impl Sync for Accessor {} |
| 60 | + |
| 61 | +impl Accessor { |
| 62 | + /// Create a new accessor that will call the given callback when its |
| 63 | + /// connection info is required. |
| 64 | + /// The callback object and all objects it captures are owned by the Accessor |
| 65 | + /// and will be deleted some time after the Accessor is Dropped. If the callback |
| 66 | + /// is being called when the Accessor is Dropped, the callback will not be deleted |
| 67 | + /// immediately. |
| 68 | + pub fn new<F>(instance: &str, callback: F) -> Accessor |
| 69 | + where |
| 70 | + F: Fn(&str) -> Option<ConnectionInfo> + Send + Sync + 'static, |
| 71 | + { |
| 72 | + let callback: *mut c_void = Arc::into_raw(Arc::new(callback)) as *mut c_void; |
| 73 | + let inst = CString::new(instance).unwrap(); |
| 74 | + |
| 75 | + // Safety: The function pointer is a valid connection_info callback. |
| 76 | + // This call returns an owned `ABinderRpc_Accessor` pointer which |
| 77 | + // must be destroyed via `ABinderRpc_Accessor_delete` when no longer |
| 78 | + // needed. |
| 79 | + // When the underlying ABinderRpc_Accessor is deleted, it will call |
| 80 | + // the cookie_decr_refcount callback to release its strong ref. |
| 81 | + let accessor = unsafe { |
| 82 | + sys::ABinderRpc_Accessor_new( |
| 83 | + inst.as_ptr(), |
| 84 | + Some(Self::connection_info::<F>), |
| 85 | + callback, |
| 86 | + Some(Self::cookie_decr_refcount::<F>), |
| 87 | + ) |
| 88 | + }; |
| 89 | + |
| 90 | + Accessor { accessor } |
| 91 | + } |
| 92 | + |
| 93 | + /// Get the underlying binder for this Accessor for when it needs to be either |
| 94 | + /// registered with service manager or sent to another process. |
| 95 | + pub fn as_binder(&self) -> Option<SpIBinder> { |
| 96 | + // Safety: `ABinderRpc_Accessor_asBinder` returns either a null pointer or a |
| 97 | + // valid pointer to an owned `AIBinder`. Either of these values is safe to |
| 98 | + // pass to `SpIBinder::from_raw`. |
| 99 | + unsafe { SpIBinder::from_raw(sys::ABinderRpc_Accessor_asBinder(self.accessor)) } |
| 100 | + } |
| 101 | + |
| 102 | + /// Callback invoked from C++ when the connection info is needed. |
| 103 | + /// |
| 104 | + /// # Safety |
| 105 | + /// |
| 106 | + /// The `instance` parameter must be a non-null pointer to a valid C string for |
| 107 | + /// CStr::from_ptr. The memory must contain a valid null terminator at the end of |
| 108 | + /// the string within isize::MAX from the pointer. The memory must not be mutated for |
| 109 | + /// the duration of this function call and must be valid for reads from the pointer |
| 110 | + /// to the null terminator. |
| 111 | + /// The `cookie` parameter must be the cookie for an `Arc<F>` and |
| 112 | + /// the caller must hold a ref-count to it. |
| 113 | + unsafe extern "C" fn connection_info<F>( |
| 114 | + instance: *const c_char, |
| 115 | + cookie: *mut c_void, |
| 116 | + ) -> *mut binder_ndk_sys::ABinderRpc_ConnectionInfo |
| 117 | + where |
| 118 | + F: Fn(&str) -> Option<ConnectionInfo> + Send + Sync + 'static, |
| 119 | + { |
| 120 | + if cookie.is_null() || instance.is_null() { |
| 121 | + log::error!("Cookie({cookie:p}) or instance({instance:p}) is null!"); |
| 122 | + return ptr::null_mut(); |
| 123 | + } |
| 124 | + // Safety: The caller promises that `cookie` is for an Arc<F>. |
| 125 | + let callback = unsafe { (cookie as *const F).as_ref().unwrap() }; |
| 126 | + |
| 127 | + // Safety: The caller in libbinder_ndk will have already verified this is a valid |
| 128 | + // C string |
| 129 | + let inst = unsafe { |
| 130 | + match CStr::from_ptr(instance).to_str() { |
| 131 | + Ok(s) => s, |
| 132 | + Err(err) => { |
| 133 | + log::error!("Failed to get a valid C string! {err:?}"); |
| 134 | + return ptr::null_mut(); |
| 135 | + } |
| 136 | + } |
| 137 | + }; |
| 138 | + |
| 139 | + let connection = match callback(inst) { |
| 140 | + Some(con) => con, |
| 141 | + None => { |
| 142 | + return ptr::null_mut(); |
| 143 | + } |
| 144 | + }; |
| 145 | + |
| 146 | + match connection { |
| 147 | + ConnectionInfo::Vsock(addr) => { |
| 148 | + // Safety: The sockaddr is being copied in the NDK API |
| 149 | + unsafe { sys::ABinderRpc_ConnectionInfo_new(addr.as_ptr(), addr.len()) } |
| 150 | + } |
| 151 | + ConnectionInfo::Unix(addr) => { |
| 152 | + // Safety: The sockaddr is being copied in the NDK API |
| 153 | + // The cast is from sockaddr_un* to sockaddr*. |
| 154 | + unsafe { |
| 155 | + sys::ABinderRpc_ConnectionInfo_new(addr.as_ptr() as *const sockaddr, addr.len()) |
| 156 | + } |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + /// Callback that decrements the ref-count. |
| 162 | + /// This is invoked from C++ when a binder is unlinked. |
| 163 | + /// |
| 164 | + /// # Safety |
| 165 | + /// |
| 166 | + /// The `cookie` parameter must be the cookie for an `Arc<F>` and |
| 167 | + /// the owner must give up a ref-count to it. |
| 168 | + unsafe extern "C" fn cookie_decr_refcount<F>(cookie: *mut c_void) |
| 169 | + where |
| 170 | + F: Fn(&str) -> Option<ConnectionInfo> + Send + Sync + 'static, |
| 171 | + { |
| 172 | + // Safety: The caller promises that `cookie` is for an Arc<F>. |
| 173 | + unsafe { Arc::decrement_strong_count(cookie as *const F) }; |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +impl Drop for Accessor { |
| 178 | + fn drop(&mut self) { |
| 179 | + // Safety: `self.accessor` is always a valid, owned |
| 180 | + // `ABinderRpc_Accessor` pointer returned by |
| 181 | + // `ABinderRpc_Accessor_new` when `self` was created. This delete |
| 182 | + // method can only be called once when `self` is dropped. |
| 183 | + unsafe { |
| 184 | + sys::ABinderRpc_Accessor_delete(self.accessor); |
| 185 | + } |
| 186 | + } |
| 187 | +} |
0 commit comments