blob: 3ca3b540c46824032125c741cf65fffca959cff4 [file] [log] [blame]
Andrei Homescuc5bf3f82024-03-29 04:45:59 +00001/*
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
17use crate::binder::{AsNative, FromIBinder, Strong};
18use crate::error::{status_result, Result, StatusCode};
19use crate::proxy::SpIBinder;
20use crate::sys;
21
22use std::ffi::{c_void, CStr, CString};
23use std::os::raw::c_char;
24use 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).
32pub 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).
53pub 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.
74pub 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)]
84pub struct LazyServiceGuard {
85 // Prevent construction outside this module.
86 _private: (),
87}
88
89// Count of how many LazyServiceGuard objects are in existence.
90static GUARD_COUNT: Mutex<u64> = Mutex::new(0);
91
92impl LazyServiceGuard {
93 /// Create a new LazyServiceGuard to prevent the service manager prematurely killing this
94 /// process.
95 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
108impl Drop for LazyServiceGuard {
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
118impl Clone for LazyServiceGuard {
119 fn clone(&self) -> Self {
120 Self::new()
121 }
122}
123
124impl Default for LazyServiceGuard {
125 fn default() -> Self {
126 Self::new()
127 }
128}
129
130/// Determine whether the current thread is currently executing an incoming
131/// transaction.
132pub fn is_handling_transaction() -> bool {
133 // Safety: This method is always safe to call.
134 unsafe { sys::AIBinder_isHandlingTransaction() }
135}
136
137fn 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.
147pub fn get_service(name: &str) -> Option<SpIBinder> {
148 let name = CString::new(name).ok()?;
149 // Safety: `AServiceManager_getService` returns either a null pointer or a
150 // valid pointer to an owned `AIBinder`. Either of these values is safe to
151 // pass to `SpIBinder::from_raw`.
152 unsafe { SpIBinder::from_raw(sys::AServiceManager_getService(name.as_ptr())) }
153}
154
155/// Retrieve an existing service, or start it if it is configured as a dynamic
156/// service and isn't yet started.
157pub fn wait_for_service(name: &str) -> Option<SpIBinder> {
158 let name = CString::new(name).ok()?;
159 // Safety: `AServiceManager_waitforService` 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_waitForService(name.as_ptr())) }
163}
164
165/// Retrieve an existing service for a particular interface, blocking for a few
166/// seconds if it doesn't yet exist.
167pub fn get_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> {
168 interface_cast(get_service(name))
169}
170
171/// Retrieve an existing service for a particular interface, or start it if it
172/// is configured as a dynamic service and isn't yet started.
173pub fn wait_for_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> {
174 interface_cast(wait_for_service(name))
175}
176
177/// Check if a service is declared (e.g. in a VINTF manifest)
178pub fn is_declared(interface: &str) -> Result<bool> {
179 let interface = CString::new(interface).or(Err(StatusCode::UNEXPECTED_NULL))?;
180
181 // Safety: `interface` is a valid null-terminated C-style string and is only
182 // borrowed for the lifetime of the call. The `interface` local outlives
183 // this call as it lives for the function scope.
184 unsafe { Ok(sys::AServiceManager_isDeclared(interface.as_ptr())) }
185}
186
187/// Retrieve all declared instances for a particular interface
188///
189/// For instance, if 'android.foo.IFoo/foo' is declared, and 'android.foo.IFoo'
190/// is passed here, then ["foo"] would be returned.
191pub fn get_declared_instances(interface: &str) -> Result<Vec<String>> {
192 unsafe extern "C" fn callback(instance: *const c_char, opaque: *mut c_void) {
193 // Safety: opaque was a mutable pointer created below from a Vec of
194 // CString, and outlives this callback. The null handling here is just
195 // to avoid the possibility of unwinding across C code if this crate is
196 // ever compiled with panic=unwind.
197 if let Some(instances) = unsafe { opaque.cast::<Vec<CString>>().as_mut() } {
198 // Safety: instance is a valid null-terminated C string with a
199 // lifetime at least as long as this function, and we immediately
200 // copy it into an owned CString.
201 unsafe {
202 instances.push(CStr::from_ptr(instance).to_owned());
203 }
204 } else {
205 eprintln!("Opaque pointer was null in get_declared_instances callback!");
206 }
207 }
208
209 let interface = CString::new(interface).or(Err(StatusCode::UNEXPECTED_NULL))?;
210 let mut instances: Vec<CString> = vec![];
211 // Safety: `interface` and `instances` are borrowed for the length of this
212 // call and both outlive the call. `interface` is guaranteed to be a valid
213 // null-terminated C-style string.
214 unsafe {
215 sys::AServiceManager_forEachDeclaredInstance(
216 interface.as_ptr(),
217 &mut instances as *mut _ as *mut c_void,
218 Some(callback),
219 );
220 }
221
222 instances
223 .into_iter()
224 .map(CString::into_string)
225 .collect::<std::result::Result<Vec<String>, _>>()
226 .map_err(|e| {
227 eprintln!("An interface instance name was not a valid UTF-8 string: {}", e);
228 StatusCode::BAD_VALUE
229 })
230}