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     interface_cast(get_service(name))
180 }
181 
182 /// Retrieve an existing service for a particular interface. Returns
183 /// `Err(StatusCode::NAME_NOT_FOUND)` immediately if the service is not available.
check_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>>184 pub fn check_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> {
185     interface_cast(check_service(name))
186 }
187 
188 /// Retrieve an existing service for a particular interface, or start it if it
189 /// is configured as a dynamic service and isn't yet started.
wait_for_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>>190 pub fn wait_for_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> {
191     interface_cast(wait_for_service(name))
192 }
193 
194 /// Check if a service is declared (e.g. in a VINTF manifest)
is_declared(interface: &str) -> Result<bool>195 pub fn is_declared(interface: &str) -> Result<bool> {
196     let interface = CString::new(interface).or(Err(StatusCode::UNEXPECTED_NULL))?;
197 
198     // Safety: `interface` is a valid null-terminated C-style string and is only
199     // borrowed for the lifetime of the call. The `interface` local outlives
200     // this call as it lives for the function scope.
201     unsafe { Ok(sys::AServiceManager_isDeclared(interface.as_ptr())) }
202 }
203 
204 /// Retrieve all declared instances for a particular interface
205 ///
206 /// For instance, if 'android.foo.IFoo/foo' is declared, and 'android.foo.IFoo'
207 /// is passed here, then ["foo"] would be returned.
get_declared_instances(interface: &str) -> Result<Vec<String>>208 pub fn get_declared_instances(interface: &str) -> Result<Vec<String>> {
209     unsafe extern "C" fn callback(instance: *const c_char, opaque: *mut c_void) {
210         // Safety: opaque was a mutable pointer created below from a Vec of
211         // CString, and outlives this callback. The null handling here is just
212         // to avoid the possibility of unwinding across C code if this crate is
213         // ever compiled with panic=unwind.
214         if let Some(instances) = unsafe { opaque.cast::<Vec<CString>>().as_mut() } {
215             // Safety: instance is a valid null-terminated C string with a
216             // lifetime at least as long as this function, and we immediately
217             // copy it into an owned CString.
218             unsafe {
219                 instances.push(CStr::from_ptr(instance).to_owned());
220             }
221         } else {
222             eprintln!("Opaque pointer was null in get_declared_instances callback!");
223         }
224     }
225 
226     let interface = CString::new(interface).or(Err(StatusCode::UNEXPECTED_NULL))?;
227     let mut instances: Vec<CString> = vec![];
228     // Safety: `interface` and `instances` are borrowed for the length of this
229     // call and both outlive the call. `interface` is guaranteed to be a valid
230     // null-terminated C-style string.
231     unsafe {
232         sys::AServiceManager_forEachDeclaredInstance(
233             interface.as_ptr(),
234             &mut instances as *mut _ as *mut c_void,
235             Some(callback),
236         );
237     }
238 
239     instances
240         .into_iter()
241         .map(CString::into_string)
242         .collect::<std::result::Result<Vec<String>, _>>()
243         .map_err(|e| {
244             eprintln!("An interface instance name was not a valid UTF-8 string: {}", e);
245             StatusCode::BAD_VALUE
246         })
247 }
248