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::binder::{AsNative, FromIBinder, Strong};
18 use crate::error::{status_result, Result, StatusCode};
19 use crate::proxy::SpIBinder;
20 use crate::sys;
21
22 use std::ffi::{c_void, CStr, CString};
23 use std::os::raw::c_char;
24 use std::sync::Mutex;
25
26 /// Register a new service with the default service manager.
27 ///
28 /// Registers the given binder object with the given identifier. If successful,
29 /// this service can then be retrieved using that identifier.
30 ///
31 /// This function will panic if the identifier contains a 0 byte (NUL).
add_service(identifier: &str, mut binder: SpIBinder) -> Result<()>32 pub fn add_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
33 let instance = CString::new(identifier).unwrap();
34 let status =
35 // Safety: `AServiceManager_addService` expects valid `AIBinder` and C
36 // string pointers. Caller retains ownership of both pointers.
37 // `AServiceManager_addService` creates a new strong reference and copies
38 // the string, so both pointers need only be valid until the call returns.
39 unsafe { sys::AServiceManager_addService(binder.as_native_mut(), instance.as_ptr()) };
40 status_result(status)
41 }
42
43 /// Register a dynamic service via the LazyServiceRegistrar.
44 ///
45 /// Registers the given binder object with the given identifier. If successful,
46 /// this service can then be retrieved using that identifier. The service process
47 /// will be shut down once all registered services are no longer in use.
48 ///
49 /// If any service in the process is registered as lazy, all should be, otherwise
50 /// the process may be shut down while a service is in use.
51 ///
52 /// This function will panic if the identifier contains a 0 byte (NUL).
register_lazy_service(identifier: &str, mut binder: SpIBinder) -> Result<()>53 pub fn register_lazy_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
54 let instance = CString::new(identifier).unwrap();
55 // Safety: `AServiceManager_registerLazyService` expects valid `AIBinder` and C
56 // string pointers. Caller retains ownership of both
57 // pointers. `AServiceManager_registerLazyService` creates a new strong reference
58 // and copies the string, so both pointers need only be valid until the
59 // call returns.
60 let status = unsafe {
61 sys::AServiceManager_registerLazyService(binder.as_native_mut(), instance.as_ptr())
62 };
63 status_result(status)
64 }
65
66 /// Prevent a process which registers lazy services from being shut down even when none
67 /// of the services is in use.
68 ///
69 /// If persist is true then shut down will be blocked until this function is called again with
70 /// persist false. If this is to be the initial state, call this function before calling
71 /// register_lazy_service.
72 ///
73 /// Consider using [`LazyServiceGuard`] rather than calling this directly.
force_lazy_services_persist(persist: bool)74 pub fn force_lazy_services_persist(persist: bool) {
75 // Safety: No borrowing or transfer of ownership occurs here.
76 unsafe { sys::AServiceManager_forceLazyServicesPersist(persist) }
77 }
78
79 /// An RAII object to ensure a process which registers lazy services is not killed. During the
80 /// lifetime of any of these objects the service manager will not kill the process even if none
81 /// of its lazy services are in use.
82 #[must_use]
83 #[derive(Debug)]
84 pub struct LazyServiceGuard {
85 // Prevent construction outside this module.
86 _private: (),
87 }
88
89 // Count of how many LazyServiceGuard objects are in existence.
90 static GUARD_COUNT: Mutex<u64> = Mutex::new(0);
91
92 impl LazyServiceGuard {
93 /// Create a new LazyServiceGuard to prevent the service manager prematurely killing this
94 /// process.
new() -> Self95 pub fn new() -> Self {
96 let mut count = GUARD_COUNT.lock().unwrap();
97 *count += 1;
98 if *count == 1 {
99 // It's important that we make this call with the mutex held, to make sure
100 // that multiple calls (e.g. if the count goes 1 -> 0 -> 1) are correctly
101 // sequenced. (That also means we can't just use an AtomicU64.)
102 force_lazy_services_persist(true);
103 }
104 Self { _private: () }
105 }
106 }
107
108 impl Drop for LazyServiceGuard {
drop(&mut self)109 fn drop(&mut self) {
110 let mut count = GUARD_COUNT.lock().unwrap();
111 *count -= 1;
112 if *count == 0 {
113 force_lazy_services_persist(false);
114 }
115 }
116 }
117
118 impl Clone for LazyServiceGuard {
clone(&self) -> Self119 fn clone(&self) -> Self {
120 Self::new()
121 }
122 }
123
124 impl Default for LazyServiceGuard {
default() -> Self125 fn default() -> Self {
126 Self::new()
127 }
128 }
129
130 /// Determine whether the current thread is currently executing an incoming
131 /// transaction.
is_handling_transaction() -> bool132 pub fn is_handling_transaction() -> bool {
133 // Safety: This method is always safe to call.
134 unsafe { sys::AIBinder_isHandlingTransaction() }
135 }
136
interface_cast<T: FromIBinder + ?Sized>(service: Option<SpIBinder>) -> Result<Strong<T>>137 fn interface_cast<T: FromIBinder + ?Sized>(service: Option<SpIBinder>) -> Result<Strong<T>> {
138 if let Some(service) = service {
139 FromIBinder::try_from(service)
140 } else {
141 Err(StatusCode::NAME_NOT_FOUND)
142 }
143 }
144
145 /// Retrieve an existing service, blocking for a few seconds if it doesn't yet
146 /// exist.
147 #[deprecated = "this polls 5s, use wait_for_service or check_service"]
get_service(name: &str) -> Option<SpIBinder>148 pub fn get_service(name: &str) -> Option<SpIBinder> {
149 let name = CString::new(name).ok()?;
150 // Safety: `AServiceManager_getService` returns either a null pointer or a
151 // valid pointer to an owned `AIBinder`. Either of these values is safe to
152 // pass to `SpIBinder::from_raw`.
153 unsafe { SpIBinder::from_raw(sys::AServiceManager_getService(name.as_ptr())) }
154 }
155
156 /// Retrieve an existing service. Returns `None` immediately if the service is not available.
check_service(name: &str) -> Option<SpIBinder>157 pub fn check_service(name: &str) -> Option<SpIBinder> {
158 let name = CString::new(name).ok()?;
159 // Safety: `AServiceManager_checkService` returns either a null pointer or
160 // a valid pointer to an owned `AIBinder`. Either of these values is safe to
161 // pass to `SpIBinder::from_raw`.
162 unsafe { SpIBinder::from_raw(sys::AServiceManager_checkService(name.as_ptr())) }
163 }
164
165 /// Retrieve an existing service, or start it if it is configured as a dynamic
166 /// service and isn't yet started.
wait_for_service(name: &str) -> Option<SpIBinder>167 pub fn wait_for_service(name: &str) -> Option<SpIBinder> {
168 let name = CString::new(name).ok()?;
169 // Safety: `AServiceManager_waitforService` returns either a null pointer or
170 // a valid pointer to an owned `AIBinder`. Either of these values is safe to
171 // pass to `SpIBinder::from_raw`.
172 unsafe { SpIBinder::from_raw(sys::AServiceManager_waitForService(name.as_ptr())) }
173 }
174
175 /// Retrieve an existing service for a particular interface, blocking for a few
176 /// seconds if it doesn't yet exist.
177 #[deprecated = "this polls 5s, use wait_for_interface or check_interface"]
get_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>>178 pub fn get_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> {
179 #[allow(deprecated)]
180 interface_cast(get_service(name))
181 }
182
183 /// Retrieve an existing service for a particular interface. Returns
184 /// `Err(StatusCode::NAME_NOT_FOUND)` immediately if the service is not available.
check_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>>185 pub fn check_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> {
186 interface_cast(check_service(name))
187 }
188
189 /// Retrieve an existing service for a particular interface, or start it if it
190 /// is configured as a dynamic service and isn't yet started.
wait_for_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>>191 pub fn wait_for_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> {
192 interface_cast(wait_for_service(name))
193 }
194
195 /// Check if a service is declared (e.g. in a VINTF manifest)
is_declared(interface: &str) -> Result<bool>196 pub fn is_declared(interface: &str) -> Result<bool> {
197 let interface = CString::new(interface).or(Err(StatusCode::UNEXPECTED_NULL))?;
198
199 // Safety: `interface` is a valid null-terminated C-style string and is only
200 // borrowed for the lifetime of the call. The `interface` local outlives
201 // this call as it lives for the function scope.
202 unsafe { Ok(sys::AServiceManager_isDeclared(interface.as_ptr())) }
203 }
204
205 /// Retrieve all declared instances for a particular interface
206 ///
207 /// For instance, if 'android.foo.IFoo/foo' is declared, and 'android.foo.IFoo'
208 /// is passed here, then ["foo"] would be returned.
get_declared_instances(interface: &str) -> Result<Vec<String>>209 pub fn get_declared_instances(interface: &str) -> Result<Vec<String>> {
210 unsafe extern "C" fn callback(instance: *const c_char, opaque: *mut c_void) {
211 // Safety: opaque was a mutable pointer created below from a Vec of
212 // CString, and outlives this callback. The null handling here is just
213 // to avoid the possibility of unwinding across C code if this crate is
214 // ever compiled with panic=unwind.
215 if let Some(instances) = unsafe { opaque.cast::<Vec<CString>>().as_mut() } {
216 // Safety: instance is a valid null-terminated C string with a
217 // lifetime at least as long as this function, and we immediately
218 // copy it into an owned CString.
219 unsafe {
220 instances.push(CStr::from_ptr(instance).to_owned());
221 }
222 } else {
223 eprintln!("Opaque pointer was null in get_declared_instances callback!");
224 }
225 }
226
227 let interface = CString::new(interface).or(Err(StatusCode::UNEXPECTED_NULL))?;
228 let mut instances: Vec<CString> = vec![];
229 // Safety: `interface` and `instances` are borrowed for the length of this
230 // call and both outlive the call. `interface` is guaranteed to be a valid
231 // null-terminated C-style string.
232 unsafe {
233 sys::AServiceManager_forEachDeclaredInstance(
234 interface.as_ptr(),
235 &mut instances as *mut _ as *mut c_void,
236 Some(callback),
237 );
238 }
239
240 instances
241 .into_iter()
242 .map(CString::into_string)
243 .collect::<std::result::Result<Vec<String>, _>>()
244 .map_err(|e| {
245 eprintln!("An interface instance name was not a valid UTF-8 string: {}", e);
246 StatusCode::BAD_VALUE
247 })
248 }
249