blob: 15ae56fdd74001320d19ef08a93fd16fa5952159 [file] [log] [blame]
Stephen Crane2a3c2502020-06-16 17:48:35 -07001/*
2 * Copyright (C) 2020 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//! Rust Binder crate integration tests
18
Stephen Crane7bca1052021-10-25 17:52:51 -070019use binder::{declare_binder_enum, declare_binder_interface};
Stephen Cranef2735b42022-01-19 17:49:46 +000020use binder::{BinderFeatures, Interface, StatusCode, ThreadState};
21// Import from internal API for testing only, do not use this module in
22// production.
23use binder::binder_impl::{
24 Binder, BorrowedParcel, IBinderInternal, TransactionCode, FIRST_CALL_TRANSACTION,
Andrew Walbran12400d82021-03-04 17:04:34 +000025};
Stephen Cranef2735b42022-01-19 17:49:46 +000026
Janis Danisevskis798a09a2020-08-18 08:35:38 -070027use std::convert::{TryFrom, TryInto};
Stephen Crane2a3297f2021-06-11 16:48:10 -070028use std::ffi::CStr;
Andrei Homescud23c0492023-11-09 01:51:59 +000029use std::io::Write;
Stephen Crane2a3297f2021-06-11 16:48:10 -070030use std::sync::Mutex;
Stephen Crane2a3c2502020-06-16 17:48:35 -070031
32/// Name of service runner.
33///
34/// Must match the binary name in Android.bp
35const RUST_SERVICE_BINARY: &str = "rustBinderTestService";
36
37/// Binary to run a test service.
38///
39/// This needs to be in a separate process from the tests, so we spawn this
40/// binary as a child, providing the service name as an argument.
41fn main() -> Result<(), &'static str> {
42 // Ensure that we can handle all transactions on the main thread.
43 binder::ProcessState::set_thread_pool_max_thread_count(0);
44 binder::ProcessState::start_thread_pool();
45
46 let mut args = std::env::args().skip(1);
47 if args.len() < 1 || args.len() > 2 {
48 print_usage();
49 return Err("");
50 }
51 let service_name = args.next().ok_or_else(|| {
52 print_usage();
53 "Missing SERVICE_NAME argument"
54 })?;
55 let extension_name = args.next();
56
57 {
Stephen Crane2a3297f2021-06-11 16:48:10 -070058 let mut service = Binder::new(BnTest(Box::new(TestService::new(&service_name))));
Janis Danisevskis798a09a2020-08-18 08:35:38 -070059 service.set_requesting_sid(true);
Stephen Crane2a3c2502020-06-16 17:48:35 -070060 if let Some(extension_name) = extension_name {
Andrew Walbran88eca4f2021-04-13 14:26:01 +000061 let extension =
Stephen Crane2a3297f2021-06-11 16:48:10 -070062 BnTest::new_binder(TestService::new(&extension_name), BinderFeatures::default());
Matthew Maurere268a9f2022-07-26 09:31:30 -070063 service.set_extension(&mut extension.as_binder()).expect("Could not add extension");
Stephen Crane2a3c2502020-06-16 17:48:35 -070064 }
65 binder::add_service(&service_name, service.as_binder())
66 .expect("Could not register service");
67 }
68
69 binder::ProcessState::join_thread_pool();
70 Err("Unexpected exit after join_thread_pool")
71}
72
73fn print_usage() {
Matthew Maurere268a9f2022-07-26 09:31:30 -070074 eprintln!("Usage: {} SERVICE_NAME [EXTENSION_NAME]", RUST_SERVICE_BINARY);
Stephen Crane2a3c2502020-06-16 17:48:35 -070075 eprintln!(concat!(
76 "Spawn a Binder test service identified by SERVICE_NAME,",
77 " optionally with an extesion named EXTENSION_NAME",
78 ));
79}
80
Stephen Crane2a3c2502020-06-16 17:48:35 -070081struct TestService {
82 s: String,
Stephen Crane2a3297f2021-06-11 16:48:10 -070083 dump_args: Mutex<Vec<String>>,
84}
85
86impl TestService {
87 fn new(s: &str) -> Self {
Matthew Maurere268a9f2022-07-26 09:31:30 -070088 Self { s: s.to_string(), dump_args: Mutex::new(Vec::new()) }
Stephen Crane2a3297f2021-06-11 16:48:10 -070089 }
Stephen Crane2a3c2502020-06-16 17:48:35 -070090}
91
Janis Danisevskis798a09a2020-08-18 08:35:38 -070092#[repr(u32)]
93enum TestTransactionCode {
Andrew Walbran12400d82021-03-04 17:04:34 +000094 Test = FIRST_CALL_TRANSACTION,
Stephen Crane2a3297f2021-06-11 16:48:10 -070095 GetDumpArgs,
Janis Danisevskis798a09a2020-08-18 08:35:38 -070096 GetSelinuxContext,
Alice Ryhl29a50262021-12-10 11:14:32 +000097 GetIsHandlingTransaction,
Janis Danisevskis798a09a2020-08-18 08:35:38 -070098}
99
100impl TryFrom<u32> for TestTransactionCode {
101 type Error = StatusCode;
102
103 fn try_from(c: u32) -> Result<Self, Self::Error> {
104 match c {
105 _ if c == TestTransactionCode::Test as u32 => Ok(TestTransactionCode::Test),
Matthew Maurere268a9f2022-07-26 09:31:30 -0700106 _ if c == TestTransactionCode::GetDumpArgs as u32 => {
107 Ok(TestTransactionCode::GetDumpArgs)
108 }
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700109 _ if c == TestTransactionCode::GetSelinuxContext as u32 => {
110 Ok(TestTransactionCode::GetSelinuxContext)
111 }
Matthew Maurere268a9f2022-07-26 09:31:30 -0700112 _ if c == TestTransactionCode::GetIsHandlingTransaction as u32 => {
113 Ok(TestTransactionCode::GetIsHandlingTransaction)
114 }
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700115 _ => Err(StatusCode::UNKNOWN_TRANSACTION),
116 }
117 }
118}
119
Stephen Crane2a3297f2021-06-11 16:48:10 -0700120impl Interface for TestService {
Andrei Homescud23c0492023-11-09 01:51:59 +0000121 fn dump(&self, _writer: &mut dyn Write, args: &[&CStr]) -> Result<(), StatusCode> {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700122 let mut dump_args = self.dump_args.lock().unwrap();
123 dump_args.extend(args.iter().map(|s| s.to_str().unwrap().to_owned()));
124 Ok(())
125 }
126}
Stephen Crane2a3c2502020-06-16 17:48:35 -0700127
128impl ITest for TestService {
Stephen Cranef2735b42022-01-19 17:49:46 +0000129 fn test(&self) -> Result<String, StatusCode> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700130 Ok(self.s.clone())
131 }
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700132
Stephen Cranef2735b42022-01-19 17:49:46 +0000133 fn get_dump_args(&self) -> Result<Vec<String>, StatusCode> {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700134 let args = self.dump_args.lock().unwrap().clone();
135 Ok(args)
136 }
137
Stephen Cranef2735b42022-01-19 17:49:46 +0000138 fn get_selinux_context(&self) -> Result<String, StatusCode> {
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700139 let sid =
140 ThreadState::with_calling_sid(|sid| sid.map(|s| s.to_string_lossy().into_owned()));
141 sid.ok_or(StatusCode::UNEXPECTED_NULL)
142 }
Alice Ryhl29a50262021-12-10 11:14:32 +0000143
Stephen Cranef2735b42022-01-19 17:49:46 +0000144 fn get_is_handling_transaction(&self) -> Result<bool, StatusCode> {
Alice Ryhl29a50262021-12-10 11:14:32 +0000145 Ok(binder::is_handling_transaction())
146 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700147}
148
149/// Trivial testing binder interface
150pub trait ITest: Interface {
151 /// Returns a test string
Stephen Cranef2735b42022-01-19 17:49:46 +0000152 fn test(&self) -> Result<String, StatusCode>;
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700153
Stephen Crane2a3297f2021-06-11 16:48:10 -0700154 /// Return the arguments sent via dump
Stephen Cranef2735b42022-01-19 17:49:46 +0000155 fn get_dump_args(&self) -> Result<Vec<String>, StatusCode>;
Stephen Crane2a3297f2021-06-11 16:48:10 -0700156
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700157 /// Returns the caller's SELinux context
Stephen Cranef2735b42022-01-19 17:49:46 +0000158 fn get_selinux_context(&self) -> Result<String, StatusCode>;
Alice Ryhl29a50262021-12-10 11:14:32 +0000159
160 /// Returns the value of calling `is_handling_transaction`.
Stephen Cranef2735b42022-01-19 17:49:46 +0000161 fn get_is_handling_transaction(&self) -> Result<bool, StatusCode>;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700162}
163
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000164/// Async trivial testing binder interface
165pub trait IATest<P>: Interface {
166 /// Returns a test string
Stephen Cranef2735b42022-01-19 17:49:46 +0000167 fn test(&self) -> binder::BoxFuture<'static, Result<String, StatusCode>>;
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000168
169 /// Return the arguments sent via dump
Stephen Cranef2735b42022-01-19 17:49:46 +0000170 fn get_dump_args(&self) -> binder::BoxFuture<'static, Result<Vec<String>, StatusCode>>;
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000171
172 /// Returns the caller's SELinux context
Stephen Cranef2735b42022-01-19 17:49:46 +0000173 fn get_selinux_context(&self) -> binder::BoxFuture<'static, Result<String, StatusCode>>;
Alice Ryhl29a50262021-12-10 11:14:32 +0000174
175 /// Returns the value of calling `is_handling_transaction`.
Stephen Cranef2735b42022-01-19 17:49:46 +0000176 fn get_is_handling_transaction(&self) -> binder::BoxFuture<'static, Result<bool, StatusCode>>;
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000177}
178
Stephen Crane2a3c2502020-06-16 17:48:35 -0700179declare_binder_interface! {
180 ITest["android.os.ITest"] {
181 native: BnTest(on_transact),
182 proxy: BpTest {
183 x: i32 = 100
184 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000185 async: IATest,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700186 }
187}
188
189fn on_transact(
190 service: &dyn ITest,
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700191 code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000192 _data: &BorrowedParcel<'_>,
193 reply: &mut BorrowedParcel<'_>,
Stephen Cranef2735b42022-01-19 17:49:46 +0000194) -> Result<(), StatusCode> {
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700195 match code.try_into()? {
196 TestTransactionCode::Test => reply.write(&service.test()?),
Stephen Crane2a3297f2021-06-11 16:48:10 -0700197 TestTransactionCode::GetDumpArgs => reply.write(&service.get_dump_args()?),
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700198 TestTransactionCode::GetSelinuxContext => reply.write(&service.get_selinux_context()?),
Matthew Maurere268a9f2022-07-26 09:31:30 -0700199 TestTransactionCode::GetIsHandlingTransaction => {
200 reply.write(&service.get_is_handling_transaction()?)
201 }
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700202 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700203}
204
205impl ITest for BpTest {
Stephen Cranef2735b42022-01-19 17:49:46 +0000206 fn test(&self) -> Result<String, StatusCode> {
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700207 let reply =
Matthew Maurere268a9f2022-07-26 09:31:30 -0700208 self.binder.transact(TestTransactionCode::Test as TransactionCode, 0, |_| Ok(()))?;
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700209 reply.read()
210 }
211
Stephen Cranef2735b42022-01-19 17:49:46 +0000212 fn get_dump_args(&self) -> Result<Vec<String>, StatusCode> {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700213 let reply =
214 self.binder
215 .transact(TestTransactionCode::GetDumpArgs as TransactionCode, 0, |_| Ok(()))?;
216 reply.read()
217 }
218
Stephen Cranef2735b42022-01-19 17:49:46 +0000219 fn get_selinux_context(&self) -> Result<String, StatusCode> {
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700220 let reply = self.binder.transact(
221 TestTransactionCode::GetSelinuxContext as TransactionCode,
222 0,
223 |_| Ok(()),
224 )?;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700225 reply.read()
226 }
Alice Ryhl29a50262021-12-10 11:14:32 +0000227
Stephen Cranef2735b42022-01-19 17:49:46 +0000228 fn get_is_handling_transaction(&self) -> Result<bool, StatusCode> {
Alice Ryhl29a50262021-12-10 11:14:32 +0000229 let reply = self.binder.transact(
230 TestTransactionCode::GetIsHandlingTransaction as TransactionCode,
231 0,
232 |_| Ok(()),
233 )?;
234 reply.read()
235 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700236}
237
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000238impl<P: binder::BinderAsyncPool> IATest<P> for BpTest {
Stephen Cranef2735b42022-01-19 17:49:46 +0000239 fn test(&self) -> binder::BoxFuture<'static, Result<String, StatusCode>> {
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000240 let binder = self.binder.clone();
241 P::spawn(
Alice Ryhl8618c482021-11-09 15:35:35 +0000242 move || binder.transact(TestTransactionCode::Test as TransactionCode, 0, |_| Ok(())),
Matthew Maurere268a9f2022-07-26 09:31:30 -0700243 |reply| async move { reply?.read() },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000244 )
245 }
246
Stephen Cranef2735b42022-01-19 17:49:46 +0000247 fn get_dump_args(&self) -> binder::BoxFuture<'static, Result<Vec<String>, StatusCode>> {
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000248 let binder = self.binder.clone();
249 P::spawn(
Matthew Maurere268a9f2022-07-26 09:31:30 -0700250 move || {
251 binder.transact(TestTransactionCode::GetDumpArgs as TransactionCode, 0, |_| Ok(()))
252 },
253 |reply| async move { reply?.read() },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000254 )
255 }
256
Stephen Cranef2735b42022-01-19 17:49:46 +0000257 fn get_selinux_context(&self) -> binder::BoxFuture<'static, Result<String, StatusCode>> {
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000258 let binder = self.binder.clone();
259 P::spawn(
Matthew Maurere268a9f2022-07-26 09:31:30 -0700260 move || {
261 binder.transact(
262 TestTransactionCode::GetSelinuxContext as TransactionCode,
263 0,
264 |_| Ok(()),
265 )
266 },
267 |reply| async move { reply?.read() },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000268 )
269 }
Alice Ryhl29a50262021-12-10 11:14:32 +0000270
Stephen Cranef2735b42022-01-19 17:49:46 +0000271 fn get_is_handling_transaction(&self) -> binder::BoxFuture<'static, Result<bool, StatusCode>> {
Alice Ryhl29a50262021-12-10 11:14:32 +0000272 let binder = self.binder.clone();
273 P::spawn(
Matthew Maurere268a9f2022-07-26 09:31:30 -0700274 move || {
275 binder.transact(
276 TestTransactionCode::GetIsHandlingTransaction as TransactionCode,
277 0,
278 |_| Ok(()),
279 )
280 },
281 |reply| async move { reply?.read() },
Alice Ryhl29a50262021-12-10 11:14:32 +0000282 )
283 }
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000284}
285
Stephen Crane2a3c2502020-06-16 17:48:35 -0700286impl ITest for Binder<BnTest> {
Stephen Cranef2735b42022-01-19 17:49:46 +0000287 fn test(&self) -> Result<String, StatusCode> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700288 self.0.test()
289 }
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700290
Stephen Cranef2735b42022-01-19 17:49:46 +0000291 fn get_dump_args(&self) -> Result<Vec<String>, StatusCode> {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700292 self.0.get_dump_args()
293 }
294
Stephen Cranef2735b42022-01-19 17:49:46 +0000295 fn get_selinux_context(&self) -> Result<String, StatusCode> {
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700296 self.0.get_selinux_context()
297 }
Alice Ryhl29a50262021-12-10 11:14:32 +0000298
Stephen Cranef2735b42022-01-19 17:49:46 +0000299 fn get_is_handling_transaction(&self) -> Result<bool, StatusCode> {
Alice Ryhl29a50262021-12-10 11:14:32 +0000300 self.0.get_is_handling_transaction()
301 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700302}
303
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000304impl<P: binder::BinderAsyncPool> IATest<P> for Binder<BnTest> {
Stephen Cranef2735b42022-01-19 17:49:46 +0000305 fn test(&self) -> binder::BoxFuture<'static, Result<String, StatusCode>> {
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000306 let res = self.0.test();
307 Box::pin(async move { res })
308 }
309
Stephen Cranef2735b42022-01-19 17:49:46 +0000310 fn get_dump_args(&self) -> binder::BoxFuture<'static, Result<Vec<String>, StatusCode>> {
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000311 let res = self.0.get_dump_args();
312 Box::pin(async move { res })
313 }
314
Stephen Cranef2735b42022-01-19 17:49:46 +0000315 fn get_selinux_context(&self) -> binder::BoxFuture<'static, Result<String, StatusCode>> {
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000316 let res = self.0.get_selinux_context();
317 Box::pin(async move { res })
318 }
Alice Ryhl29a50262021-12-10 11:14:32 +0000319
Stephen Cranef2735b42022-01-19 17:49:46 +0000320 fn get_is_handling_transaction(&self) -> binder::BoxFuture<'static, Result<bool, StatusCode>> {
Alice Ryhl29a50262021-12-10 11:14:32 +0000321 let res = self.0.get_is_handling_transaction();
322 Box::pin(async move { res })
323 }
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000324}
325
Stephen Crane669deb62020-09-10 17:31:39 -0700326/// Trivial testing binder interface
327pub trait ITestSameDescriptor: Interface {}
328
329declare_binder_interface! {
330 ITestSameDescriptor["android.os.ITest"] {
331 native: BnTestSameDescriptor(on_transact_same_descriptor),
332 proxy: BpTestSameDescriptor,
333 }
334}
335
336fn on_transact_same_descriptor(
337 _service: &dyn ITestSameDescriptor,
338 _code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000339 _data: &BorrowedParcel<'_>,
340 _reply: &mut BorrowedParcel<'_>,
Stephen Cranef2735b42022-01-19 17:49:46 +0000341) -> Result<(), StatusCode> {
Stephen Crane669deb62020-09-10 17:31:39 -0700342 Ok(())
343}
344
345impl ITestSameDescriptor for BpTestSameDescriptor {}
346
347impl ITestSameDescriptor for Binder<BnTestSameDescriptor> {}
348
Stephen Crane7bca1052021-10-25 17:52:51 -0700349declare_binder_enum! {
350 TestEnum : [i32; 3] {
351 FOO = 1,
352 BAR = 2,
353 BAZ = 3,
354 }
355}
356
357declare_binder_enum! {
358 #[deprecated(since = "1.0.0")]
359 TestDeprecatedEnum : [i32; 3] {
360 FOO = 1,
361 BAR = 2,
362 BAZ = 3,
363 }
364}
365
Stephen Crane2a3c2502020-06-16 17:48:35 -0700366#[cfg(test)]
367mod tests {
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700368 use selinux_bindgen as selinux_sys;
369 use std::ffi::CStr;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700370 use std::fs::File;
371 use std::process::{Child, Command};
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700372 use std::ptr;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700373 use std::sync::atomic::{AtomicBool, Ordering};
374 use std::sync::Arc;
375 use std::thread;
376 use std::time::Duration;
377
Andrew Walbran12400d82021-03-04 17:04:34 +0000378 use binder::{
Stephen Cranef2735b42022-01-19 17:49:46 +0000379 BinderFeatures, DeathRecipient, FromIBinder, IBinder, Interface, SpIBinder, StatusCode,
380 Strong,
Andrew Walbran12400d82021-03-04 17:04:34 +0000381 };
Stephen Cranef2735b42022-01-19 17:49:46 +0000382 // Import from impl API for testing only, should not be necessary as long as
383 // you are using AIDL.
384 use binder::binder_impl::{Binder, IBinderInternal, TransactionCode};
Stephen Crane2a3c2502020-06-16 17:48:35 -0700385
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000386 use binder_tokio::Tokio;
387
Matthew Maurere268a9f2022-07-26 09:31:30 -0700388 use super::{BnTest, IATest, ITest, ITestSameDescriptor, TestService, RUST_SERVICE_BINARY};
Stephen Crane2a3c2502020-06-16 17:48:35 -0700389
390 pub struct ScopedServiceProcess(Child);
391
392 impl ScopedServiceProcess {
393 pub fn new(identifier: &str) -> Self {
394 Self::new_internal(identifier, None)
395 }
396
397 pub fn new_with_extension(identifier: &str, extension: &str) -> Self {
398 Self::new_internal(identifier, Some(extension))
399 }
400
401 fn new_internal(identifier: &str, extension: Option<&str>) -> Self {
402 let mut binary_path =
403 std::env::current_exe().expect("Could not retrieve current executable path");
404 binary_path.pop();
405 binary_path.push(RUST_SERVICE_BINARY);
406 let mut command = Command::new(&binary_path);
407 command.arg(identifier);
408 if let Some(ext) = extension {
409 command.arg(ext);
410 }
411 let child = command.spawn().expect("Could not start service");
412 Self(child)
413 }
414 }
415
416 impl Drop for ScopedServiceProcess {
417 fn drop(&mut self) {
418 self.0.kill().expect("Could not kill child process");
Matthew Maurere268a9f2022-07-26 09:31:30 -0700419 self.0.wait().expect("Could not wait for child process to die");
Stephen Crane2a3c2502020-06-16 17:48:35 -0700420 }
421 }
422
423 #[test]
Frederick Mayle68f34bf2024-05-08 11:04:10 -0700424 fn check_get_service() {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700425 let mut sm = binder::get_service("manager").expect("Did not get manager binder service");
426 assert!(sm.is_binder_alive());
427 assert!(sm.ping_binder().is_ok());
428
429 assert!(binder::get_service("this_service_does_not_exist").is_none());
430 assert_eq!(
431 binder::get_interface::<dyn ITest>("this_service_does_not_exist").err(),
432 Some(StatusCode::NAME_NOT_FOUND)
433 );
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000434 assert_eq!(
435 binder::get_interface::<dyn IATest<Tokio>>("this_service_does_not_exist").err(),
436 Some(StatusCode::NAME_NOT_FOUND)
437 );
Stephen Crane2a3c2502020-06-16 17:48:35 -0700438
439 // The service manager service isn't an ITest, so this must fail.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700440 assert_eq!(binder::get_interface::<dyn ITest>("manager").err(), Some(StatusCode::BAD_TYPE));
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000441 assert_eq!(
442 binder::get_interface::<dyn IATest<Tokio>>("manager").err(),
443 Some(StatusCode::BAD_TYPE)
444 );
Stephen Crane2a3c2502020-06-16 17:48:35 -0700445 }
446
Alice Ryhl929804f2021-11-02 12:04:39 +0000447 #[tokio::test]
Frederick Mayle68f34bf2024-05-08 11:04:10 -0700448 async fn check_get_service_async() {
Alice Ryhl929804f2021-11-02 12:04:39 +0000449 let mut sm = binder::get_service("manager").expect("Did not get manager binder service");
450 assert!(sm.is_binder_alive());
451 assert!(sm.ping_binder().is_ok());
452
453 assert!(binder::get_service("this_service_does_not_exist").is_none());
454 assert_eq!(
455 binder_tokio::get_interface::<dyn ITest>("this_service_does_not_exist").await.err(),
456 Some(StatusCode::NAME_NOT_FOUND)
457 );
458 assert_eq!(
Matthew Maurere268a9f2022-07-26 09:31:30 -0700459 binder_tokio::get_interface::<dyn IATest<Tokio>>("this_service_does_not_exist")
460 .await
461 .err(),
Alice Ryhl929804f2021-11-02 12:04:39 +0000462 Some(StatusCode::NAME_NOT_FOUND)
463 );
464
465 // The service manager service isn't an ITest, so this must fail.
466 assert_eq!(
467 binder_tokio::get_interface::<dyn ITest>("manager").await.err(),
468 Some(StatusCode::BAD_TYPE)
469 );
470 assert_eq!(
471 binder_tokio::get_interface::<dyn IATest<Tokio>>("manager").await.err(),
472 Some(StatusCode::BAD_TYPE)
473 );
474 }
475
Stephen Crane2a3c2502020-06-16 17:48:35 -0700476 #[test]
Frederick Mayle68f34bf2024-05-08 11:04:10 -0700477 fn check_check_service() {
478 let mut sm = binder::check_service("manager").expect("Did not find manager binder service");
479 assert!(sm.is_binder_alive());
480 assert!(sm.ping_binder().is_ok());
481
482 assert!(binder::check_service("this_service_does_not_exist").is_none());
483 assert_eq!(
484 binder::check_interface::<dyn ITest>("this_service_does_not_exist").err(),
485 Some(StatusCode::NAME_NOT_FOUND)
486 );
487 assert_eq!(
488 binder::check_interface::<dyn IATest<Tokio>>("this_service_does_not_exist").err(),
489 Some(StatusCode::NAME_NOT_FOUND)
490 );
491
492 // The service manager service isn't an ITest, so this must fail.
493 assert_eq!(
494 binder::check_interface::<dyn ITest>("manager").err(),
495 Some(StatusCode::BAD_TYPE)
496 );
497 assert_eq!(
498 binder::check_interface::<dyn IATest<Tokio>>("manager").err(),
499 Some(StatusCode::BAD_TYPE)
500 );
501 }
502
503 #[tokio::test]
504 async fn check_check_service_async() {
505 let mut sm = binder::check_service("manager").expect("Did not find manager binder service");
506 assert!(sm.is_binder_alive());
507 assert!(sm.ping_binder().is_ok());
508
509 assert!(binder::check_service("this_service_does_not_exist").is_none());
510 assert_eq!(
511 binder_tokio::check_interface::<dyn ITest>("this_service_does_not_exist").await.err(),
512 Some(StatusCode::NAME_NOT_FOUND)
513 );
514 assert_eq!(
515 binder_tokio::check_interface::<dyn IATest<Tokio>>("this_service_does_not_exist")
516 .await
517 .err(),
518 Some(StatusCode::NAME_NOT_FOUND)
519 );
520
521 // The service manager service isn't an ITest, so this must fail.
522 assert_eq!(
523 binder_tokio::check_interface::<dyn ITest>("manager").await.err(),
524 Some(StatusCode::BAD_TYPE)
525 );
526 assert_eq!(
527 binder_tokio::check_interface::<dyn IATest<Tokio>>("manager").await.err(),
528 Some(StatusCode::BAD_TYPE)
529 );
530 }
531
532 #[test]
Andrew Walbranc3ce5c32021-06-03 16:15:56 +0000533 fn check_wait_for_service() {
534 let mut sm =
535 binder::wait_for_service("manager").expect("Did not get manager binder service");
536 assert!(sm.is_binder_alive());
537 assert!(sm.ping_binder().is_ok());
538
539 // The service manager service isn't an ITest, so this must fail.
540 assert_eq!(
541 binder::wait_for_interface::<dyn ITest>("manager").err(),
542 Some(StatusCode::BAD_TYPE)
543 );
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000544 assert_eq!(
545 binder::wait_for_interface::<dyn IATest<Tokio>>("manager").err(),
546 Some(StatusCode::BAD_TYPE)
547 );
Andrew Walbranc3ce5c32021-06-03 16:15:56 +0000548 }
549
550 #[test]
Stephen Crane098bbc92022-02-14 13:31:53 -0800551 fn get_declared_instances() {
552 // At the time of writing this test, there is no good VINTF interface
553 // guaranteed to be on all devices. Cuttlefish has light, so this will
554 // generally test things.
555 let has_lights = binder::is_declared("android.hardware.light.ILights/default")
556 .expect("Could not check for declared interface");
557
558 let instances = binder::get_declared_instances("android.hardware.light.ILights")
559 .expect("Could not get declared instances");
560
Chris Wailes42471662022-11-16 15:41:38 -0800561 let expected_defaults = usize::from(has_lights);
Stephen Crane098bbc92022-02-14 13:31:53 -0800562 assert_eq!(expected_defaults, instances.iter().filter(|i| i.as_str() == "default").count());
563 }
564
565 #[test]
Stephen Crane2a3c2502020-06-16 17:48:35 -0700566 fn trivial_client() {
567 let service_name = "trivial_client_test";
568 let _process = ScopedServiceProcess::new(service_name);
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800569 let test_client: Strong<dyn ITest> =
Stephen Crane2a3c2502020-06-16 17:48:35 -0700570 binder::get_interface(service_name).expect("Did not get manager binder service");
571 assert_eq!(test_client.test().unwrap(), "trivial_client_test");
572 }
573
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000574 #[tokio::test]
575 async fn trivial_client_async() {
576 let service_name = "trivial_client_test";
577 let _process = ScopedServiceProcess::new(service_name);
Matthew Maurere268a9f2022-07-26 09:31:30 -0700578 let test_client: Strong<dyn IATest<Tokio>> = binder_tokio::get_interface(service_name)
579 .await
580 .expect("Did not get manager binder service");
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000581 assert_eq!(test_client.test().await.unwrap(), "trivial_client_test");
582 }
583
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700584 #[test]
Andrew Walbranc3ce5c32021-06-03 16:15:56 +0000585 fn wait_for_trivial_client() {
586 let service_name = "wait_for_trivial_client_test";
587 let _process = ScopedServiceProcess::new(service_name);
588 let test_client: Strong<dyn ITest> =
589 binder::wait_for_interface(service_name).expect("Did not get manager binder service");
590 assert_eq!(test_client.test().unwrap(), "wait_for_trivial_client_test");
591 }
592
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000593 #[tokio::test]
594 async fn wait_for_trivial_client_async() {
595 let service_name = "wait_for_trivial_client_test";
596 let _process = ScopedServiceProcess::new(service_name);
Matthew Maurere268a9f2022-07-26 09:31:30 -0700597 let test_client: Strong<dyn IATest<Tokio>> = binder_tokio::wait_for_interface(service_name)
598 .await
599 .expect("Did not get manager binder service");
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000600 assert_eq!(test_client.test().await.unwrap(), "wait_for_trivial_client_test");
601 }
602
603 fn get_expected_selinux_context() -> &'static str {
Andrew Walbran4ed9d772023-07-21 18:21:05 +0100604 // SAFETY: The pointer we pass to `getcon` is valid because it comes from a reference, and
605 // `getcon` doesn't retain it after it returns. If `getcon` succeeds then `out_ptr` will
606 // point to a valid C string, otherwise it will remain null. We check for null, so the
607 // pointer we pass to `CStr::from_ptr` must be a valid pointer to a C string. There is a
608 // memory leak as we don't call `freecon`, but that's fine because this is just a test.
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000609 unsafe {
610 let mut out_ptr = ptr::null_mut();
611 assert_eq!(selinux_sys::getcon(&mut out_ptr), 0);
612 assert!(!out_ptr.is_null());
Matthew Maurere268a9f2022-07-26 09:31:30 -0700613 CStr::from_ptr(out_ptr).to_str().expect("context was invalid UTF-8")
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000614 }
615 }
616
Andrew Walbranc3ce5c32021-06-03 16:15:56 +0000617 #[test]
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700618 fn get_selinux_context() {
619 let service_name = "get_selinux_context";
620 let _process = ScopedServiceProcess::new(service_name);
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800621 let test_client: Strong<dyn ITest> =
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700622 binder::get_interface(service_name).expect("Did not get manager binder service");
Matthew Maurere268a9f2022-07-26 09:31:30 -0700623 assert_eq!(test_client.get_selinux_context().unwrap(), get_expected_selinux_context());
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000624 }
625
626 #[tokio::test]
627 async fn get_selinux_context_async() {
Alice Ryhl29a50262021-12-10 11:14:32 +0000628 let service_name = "get_selinux_context_async";
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000629 let _process = ScopedServiceProcess::new(service_name);
Matthew Maurere268a9f2022-07-26 09:31:30 -0700630 let test_client: Strong<dyn IATest<Tokio>> = binder_tokio::get_interface(service_name)
631 .await
632 .expect("Did not get manager binder service");
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000633 assert_eq!(
634 test_client.get_selinux_context().await.unwrap(),
635 get_expected_selinux_context()
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700636 );
637 }
638
Alice Ryhlc1736842021-11-23 12:38:51 +0000639 #[tokio::test]
640 async fn get_selinux_context_sync_to_async() {
641 let service_name = "get_selinux_context";
642 let _process = ScopedServiceProcess::new(service_name);
643 let test_client: Strong<dyn ITest> =
644 binder::get_interface(service_name).expect("Did not get manager binder service");
645 let test_client = test_client.into_async::<Tokio>();
646 assert_eq!(
647 test_client.get_selinux_context().await.unwrap(),
648 get_expected_selinux_context()
649 );
650 }
651
652 #[tokio::test]
653 async fn get_selinux_context_async_to_sync() {
654 let service_name = "get_selinux_context";
655 let _process = ScopedServiceProcess::new(service_name);
Matthew Maurere268a9f2022-07-26 09:31:30 -0700656 let test_client: Strong<dyn IATest<Tokio>> = binder_tokio::get_interface(service_name)
657 .await
658 .expect("Did not get manager binder service");
Alice Ryhlc1736842021-11-23 12:38:51 +0000659 let test_client = test_client.into_sync();
Matthew Maurere268a9f2022-07-26 09:31:30 -0700660 assert_eq!(test_client.get_selinux_context().unwrap(), get_expected_selinux_context());
Alice Ryhlc1736842021-11-23 12:38:51 +0000661 }
662
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000663 struct Bools {
664 binder_died: Arc<AtomicBool>,
665 binder_dealloc: Arc<AtomicBool>,
666 }
667
668 impl Bools {
669 fn is_dead(&self) -> bool {
670 self.binder_died.load(Ordering::Relaxed)
671 }
672 fn assert_died(&self) {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700673 assert!(self.is_dead(), "Did not receive death notification");
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000674 }
675 fn assert_dropped(&self) {
676 assert!(
677 self.binder_dealloc.load(Ordering::Relaxed),
678 "Did not dealloc death notification"
679 );
680 }
681 fn assert_not_dropped(&self) {
682 assert!(
683 !self.binder_dealloc.load(Ordering::Relaxed),
684 "Dealloc death notification too early"
685 );
686 }
687 }
688
689 fn register_death_notification(binder: &mut SpIBinder) -> (Bools, DeathRecipient) {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700690 let binder_died = Arc::new(AtomicBool::new(false));
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000691 let binder_dealloc = Arc::new(AtomicBool::new(false));
692
693 struct SetOnDrop {
694 binder_dealloc: Arc<AtomicBool>,
695 }
696 impl Drop for SetOnDrop {
697 fn drop(&mut self) {
698 self.binder_dealloc.store(true, Ordering::Relaxed);
699 }
700 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700701
702 let mut death_recipient = {
703 let flag = binder_died.clone();
Matthew Maurere268a9f2022-07-26 09:31:30 -0700704 let set_on_drop = SetOnDrop { binder_dealloc: binder_dealloc.clone() };
Stephen Crane2a3c2502020-06-16 17:48:35 -0700705 DeathRecipient::new(move || {
706 flag.store(true, Ordering::Relaxed);
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000707 // Force the closure to take ownership of set_on_drop. When the closure is
708 // dropped, the destructor of `set_on_drop` will run.
709 let _ = &set_on_drop;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700710 })
711 };
712
Matthew Maurere268a9f2022-07-26 09:31:30 -0700713 binder.link_to_death(&mut death_recipient).expect("link_to_death failed");
Stephen Crane2a3c2502020-06-16 17:48:35 -0700714
Matthew Maurere268a9f2022-07-26 09:31:30 -0700715 let bools = Bools { binder_died, binder_dealloc };
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000716
717 (bools, death_recipient)
Stephen Crane2a3c2502020-06-16 17:48:35 -0700718 }
719
720 /// Killing a remote service should unregister the service and trigger
721 /// death notifications.
722 #[test]
723 fn test_death_notifications() {
724 binder::ProcessState::start_thread_pool();
725
726 let service_name = "test_death_notifications";
727 let service_process = ScopedServiceProcess::new(service_name);
728 let mut remote = binder::get_service(service_name).expect("Could not retrieve service");
729
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000730 let (bools, recipient) = register_death_notification(&mut remote);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700731
732 drop(service_process);
Matthew Maurere268a9f2022-07-26 09:31:30 -0700733 remote.ping_binder().expect_err("Service should have died already");
Stephen Crane2a3c2502020-06-16 17:48:35 -0700734
735 // Pause to ensure any death notifications get delivered
736 thread::sleep(Duration::from_secs(1));
737
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000738 bools.assert_died();
739 bools.assert_not_dropped();
740
741 drop(recipient);
742
743 bools.assert_dropped();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700744 }
745
746 /// Test unregistering death notifications.
747 #[test]
748 fn test_unregister_death_notifications() {
749 binder::ProcessState::start_thread_pool();
750
751 let service_name = "test_unregister_death_notifications";
752 let service_process = ScopedServiceProcess::new(service_name);
753 let mut remote = binder::get_service(service_name).expect("Could not retrieve service");
754
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000755 let (bools, mut recipient) = register_death_notification(&mut remote);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700756
Matthew Maurere268a9f2022-07-26 09:31:30 -0700757 remote.unlink_to_death(&mut recipient).expect("Could not unlink death notifications");
Stephen Crane2a3c2502020-06-16 17:48:35 -0700758
759 drop(service_process);
Matthew Maurere268a9f2022-07-26 09:31:30 -0700760 remote.ping_binder().expect_err("Service should have died already");
Stephen Crane2a3c2502020-06-16 17:48:35 -0700761
762 // Pause to ensure any death notifications get delivered
763 thread::sleep(Duration::from_secs(1));
764
Matthew Maurere268a9f2022-07-26 09:31:30 -0700765 assert!(!bools.is_dead(), "Received unexpected death notification after unlinking",);
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000766
767 bools.assert_not_dropped();
768 drop(recipient);
769 bools.assert_dropped();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700770 }
771
772 /// Dropping a remote handle should unregister any death notifications.
773 #[test]
774 fn test_death_notification_registration_lifetime() {
775 binder::ProcessState::start_thread_pool();
776
777 let service_name = "test_death_notification_registration_lifetime";
778 let service_process = ScopedServiceProcess::new(service_name);
779 let mut remote = binder::get_service(service_name).expect("Could not retrieve service");
780
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000781 let (bools, recipient) = register_death_notification(&mut remote);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700782
783 // This should automatically unregister our death notification.
784 drop(remote);
785
786 drop(service_process);
787
788 // Pause to ensure any death notifications get delivered
789 thread::sleep(Duration::from_secs(1));
790
791 // We dropped the remote handle, so we should not receive the death
792 // notification when the remote process dies here.
793 assert!(
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000794 !bools.is_dead(),
Stephen Crane2a3c2502020-06-16 17:48:35 -0700795 "Received unexpected death notification after dropping remote handle"
796 );
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000797
798 bools.assert_not_dropped();
799 drop(recipient);
800 bools.assert_dropped();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700801 }
802
803 /// Test IBinder interface methods not exercised elsewhere.
804 #[test]
805 fn test_misc_ibinder() {
806 let service_name = "rust_test_ibinder";
807
808 {
809 let _process = ScopedServiceProcess::new(service_name);
810
Stephen Crane2a3297f2021-06-11 16:48:10 -0700811 let test_client: Strong<dyn ITest> =
Stephen Cranef2735b42022-01-19 17:49:46 +0000812 binder::get_interface(service_name).expect("Did not get test binder service");
Stephen Crane2a3297f2021-06-11 16:48:10 -0700813 let mut remote = test_client.as_binder();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700814 assert!(remote.is_binder_alive());
815 remote.ping_binder().expect("Could not ping remote service");
816
Stephen Crane2a3297f2021-06-11 16:48:10 -0700817 let dump_args = ["dump", "args", "for", "testing"];
818
Stephen Crane2a3c2502020-06-16 17:48:35 -0700819 let null_out = File::open("/dev/null").expect("Could not open /dev/null");
Matthew Maurere268a9f2022-07-26 09:31:30 -0700820 remote.dump(&null_out, &dump_args).expect("Could not dump remote service");
Stephen Crane2a3297f2021-06-11 16:48:10 -0700821
822 let remote_args = test_client.get_dump_args().expect("Could not fetched dumped args");
823 assert_eq!(dump_args, remote_args[..], "Remote args don't match call to dump");
Stephen Crane2a3c2502020-06-16 17:48:35 -0700824 }
825
826 // get/set_extensions is tested in test_extensions()
827
828 // transact is tested everywhere else, and we can't make raw
829 // transactions outside the [FIRST_CALL_TRANSACTION,
830 // LAST_CALL_TRANSACTION] range from the NDK anyway.
831
832 // link_to_death is tested in test_*_death_notification* tests.
833 }
834
835 #[test]
836 fn test_extensions() {
837 let service_name = "rust_test_extensions";
838 let extension_name = "rust_test_extensions_ext";
839
840 {
841 let _process = ScopedServiceProcess::new(service_name);
842
843 let mut remote = binder::get_service(service_name);
844 assert!(remote.is_binder_alive());
845
Matthew Maurere268a9f2022-07-26 09:31:30 -0700846 let extension = remote.get_extension().expect("Could not check for an extension");
Stephen Crane2a3c2502020-06-16 17:48:35 -0700847 assert!(extension.is_none());
848 }
849
850 {
851 let _process = ScopedServiceProcess::new_with_extension(service_name, extension_name);
852
853 let mut remote = binder::get_service(service_name);
854 assert!(remote.is_binder_alive());
855
Matthew Maurere268a9f2022-07-26 09:31:30 -0700856 let maybe_extension = remote.get_extension().expect("Could not check for an extension");
Stephen Crane2a3c2502020-06-16 17:48:35 -0700857
858 let extension = maybe_extension.expect("Remote binder did not have an extension");
859
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800860 let extension: Strong<dyn ITest> = FromIBinder::try_from(extension)
Stephen Crane2a3c2502020-06-16 17:48:35 -0700861 .expect("Extension could not be converted to the expected interface");
862
863 assert_eq!(extension.test().unwrap(), extension_name);
864 }
865 }
Stephen Crane669deb62020-09-10 17:31:39 -0700866
867 /// Test re-associating a local binder object with a different class.
868 ///
869 /// This is needed because different binder service (e.g. NDK vs Rust)
870 /// implementations are incompatible and must not be interchanged. A local
871 /// service with the same descriptor string but a different class pointer
872 /// may have been created by an NDK service and is therefore incompatible
873 /// with the Rust service implementation. It must be treated as remote and
874 /// all API calls parceled and sent through transactions.
875 ///
876 /// Further tests of this behavior with the C NDK and Rust API are in
877 /// rust_ndk_interop.rs
878 #[test]
879 fn associate_existing_class() {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700880 let service = Binder::new(BnTest(Box::new(TestService::new("testing_service"))));
Stephen Crane669deb62020-09-10 17:31:39 -0700881
882 // This should succeed although we will have to treat the service as
883 // remote.
Andrew Walbran12400d82021-03-04 17:04:34 +0000884 let _interface: Strong<dyn ITestSameDescriptor> =
885 FromIBinder::try_from(service.as_binder())
886 .expect("Could not re-interpret service as the ITestSameDescriptor interface");
Stephen Crane669deb62020-09-10 17:31:39 -0700887 }
888
889 /// Test that we can round-trip a rust service through a generic IBinder
890 #[test]
891 fn reassociate_rust_binder() {
892 let service_name = "testing_service";
Matthew Maurere268a9f2022-07-26 09:31:30 -0700893 let service_ibinder =
894 BnTest::new_binder(TestService::new(service_name), BinderFeatures::default())
895 .as_binder();
Stephen Crane669deb62020-09-10 17:31:39 -0700896
Matthew Maurere268a9f2022-07-26 09:31:30 -0700897 let service: Strong<dyn ITest> =
898 service_ibinder.into_interface().expect("Could not reassociate the generic ibinder");
Stephen Crane669deb62020-09-10 17:31:39 -0700899
900 assert_eq!(service.test().unwrap(), service_name);
901 }
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800902
903 #[test]
904 fn weak_binder_upgrade() {
905 let service_name = "testing_service";
Matthew Maurere268a9f2022-07-26 09:31:30 -0700906 let service = BnTest::new_binder(TestService::new(service_name), BinderFeatures::default());
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800907
908 let weak = Strong::downgrade(&service);
909
910 let upgraded = weak.upgrade().expect("Could not upgrade weak binder");
911
912 assert_eq!(service, upgraded);
913 }
914
915 #[test]
916 fn weak_binder_upgrade_dead() {
917 let service_name = "testing_service";
918 let weak = {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700919 let service =
920 BnTest::new_binder(TestService::new(service_name), BinderFeatures::default());
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800921
922 Strong::downgrade(&service)
923 };
924
925 assert_eq!(weak.upgrade(), Err(StatusCode::DEAD_OBJECT));
926 }
927
928 #[test]
929 fn weak_binder_clone() {
930 let service_name = "testing_service";
Matthew Maurere268a9f2022-07-26 09:31:30 -0700931 let service = BnTest::new_binder(TestService::new(service_name), BinderFeatures::default());
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800932
933 let weak = Strong::downgrade(&service);
934 let cloned = weak.clone();
935 assert_eq!(weak, cloned);
936
937 let upgraded = weak.upgrade().expect("Could not upgrade weak binder");
938 let clone_upgraded = cloned.upgrade().expect("Could not upgrade weak binder");
939
940 assert_eq!(service, upgraded);
941 assert_eq!(service, clone_upgraded);
942 }
943
944 #[test]
945 #[allow(clippy::eq_op)]
946 fn binder_ord() {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700947 let service1 =
948 BnTest::new_binder(TestService::new("testing_service1"), BinderFeatures::default());
949 let service2 =
950 BnTest::new_binder(TestService::new("testing_service2"), BinderFeatures::default());
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800951
Charisee1ccdc902022-02-26 01:22:27 +0000952 assert!((service1 >= service1));
953 assert!((service1 <= service1));
954 assert_eq!(service1 < service2, (service2 >= service1));
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800955 }
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000956
957 #[test]
958 fn binder_parcel_mixup() {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700959 let service1 =
960 BnTest::new_binder(TestService::new("testing_service1"), BinderFeatures::default());
961 let service2 =
962 BnTest::new_binder(TestService::new("testing_service2"), BinderFeatures::default());
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000963
964 let service1 = service1.as_binder();
965 let service2 = service2.as_binder();
966
967 let parcel = service1.prepare_transact().unwrap();
Matthew Maurere268a9f2022-07-26 09:31:30 -0700968 let res = service2.submit_transact(
969 super::TestTransactionCode::Test as TransactionCode,
970 parcel,
971 0,
972 );
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000973
974 match res {
975 Ok(_) => panic!("submit_transact should fail"),
976 Err(err) => assert_eq!(err, binder::StatusCode::BAD_VALUE),
977 }
978 }
Alice Ryhl29a50262021-12-10 11:14:32 +0000979
980 #[test]
981 fn get_is_handling_transaction() {
982 let service_name = "get_is_handling_transaction";
983 let _process = ScopedServiceProcess::new(service_name);
984 let test_client: Strong<dyn ITest> =
985 binder::get_interface(service_name).expect("Did not get manager binder service");
986 // Should be true externally.
987 assert!(test_client.get_is_handling_transaction().unwrap());
988
989 // Should be false locally.
990 assert!(!binder::is_handling_transaction());
991
992 // Should also be false in spawned thread.
993 std::thread::spawn(|| {
994 assert!(!binder::is_handling_transaction());
Matthew Maurere268a9f2022-07-26 09:31:30 -0700995 })
996 .join()
997 .unwrap();
Alice Ryhl29a50262021-12-10 11:14:32 +0000998 }
999
1000 #[tokio::test]
1001 async fn get_is_handling_transaction_async() {
1002 let service_name = "get_is_handling_transaction_async";
1003 let _process = ScopedServiceProcess::new(service_name);
Matthew Maurere268a9f2022-07-26 09:31:30 -07001004 let test_client: Strong<dyn IATest<Tokio>> = binder_tokio::get_interface(service_name)
1005 .await
1006 .expect("Did not get manager binder service");
Alice Ryhl29a50262021-12-10 11:14:32 +00001007 // Should be true externally.
1008 assert!(test_client.get_is_handling_transaction().await.unwrap());
1009
1010 // Should be false locally.
1011 assert!(!binder::is_handling_transaction());
1012
1013 // Should also be false in spawned task.
1014 tokio::spawn(async {
1015 assert!(!binder::is_handling_transaction());
Matthew Maurere268a9f2022-07-26 09:31:30 -07001016 })
1017 .await
1018 .unwrap();
Alice Ryhl29a50262021-12-10 11:14:32 +00001019
1020 // And in spawn_blocking task.
1021 tokio::task::spawn_blocking(|| {
1022 assert!(!binder::is_handling_transaction());
Matthew Maurere268a9f2022-07-26 09:31:30 -07001023 })
1024 .await
1025 .unwrap();
Alice Ryhl29a50262021-12-10 11:14:32 +00001026 }
Stephen Crane2a3c2502020-06-16 17:48:35 -07001027}