blob: 953d328d23a47a6673581b44f8eb656abf6545b4 [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
19use binder::declare_binder_interface;
20use binder::parcel::Parcel;
Janis Danisevskis798a09a2020-08-18 08:35:38 -070021use binder::{Binder, IBinder, Interface, SpIBinder, StatusCode, ThreadState, TransactionCode};
22use std::convert::{TryFrom, TryInto};
Stephen Crane2a3c2502020-06-16 17:48:35 -070023
24/// Name of service runner.
25///
26/// Must match the binary name in Android.bp
27const RUST_SERVICE_BINARY: &str = "rustBinderTestService";
28
29/// Binary to run a test service.
30///
31/// This needs to be in a separate process from the tests, so we spawn this
32/// binary as a child, providing the service name as an argument.
33fn main() -> Result<(), &'static str> {
34 // Ensure that we can handle all transactions on the main thread.
35 binder::ProcessState::set_thread_pool_max_thread_count(0);
36 binder::ProcessState::start_thread_pool();
37
38 let mut args = std::env::args().skip(1);
39 if args.len() < 1 || args.len() > 2 {
40 print_usage();
41 return Err("");
42 }
43 let service_name = args.next().ok_or_else(|| {
44 print_usage();
45 "Missing SERVICE_NAME argument"
46 })?;
47 let extension_name = args.next();
48
49 {
50 let mut service = Binder::new(BnTest(Box::new(TestService {
51 s: service_name.clone(),
52 })));
Janis Danisevskis798a09a2020-08-18 08:35:38 -070053 service.set_requesting_sid(true);
Stephen Crane2a3c2502020-06-16 17:48:35 -070054 if let Some(extension_name) = extension_name {
55 let extension = BnTest::new_binder(TestService { s: extension_name });
56 service
57 .set_extension(&mut extension.as_binder())
58 .expect("Could not add extension");
59 }
60 binder::add_service(&service_name, service.as_binder())
61 .expect("Could not register service");
62 }
63
64 binder::ProcessState::join_thread_pool();
65 Err("Unexpected exit after join_thread_pool")
66}
67
68fn print_usage() {
69 eprintln!(
70 "Usage: {} SERVICE_NAME [EXTENSION_NAME]",
71 RUST_SERVICE_BINARY
72 );
73 eprintln!(concat!(
74 "Spawn a Binder test service identified by SERVICE_NAME,",
75 " optionally with an extesion named EXTENSION_NAME",
76 ));
77}
78
79#[derive(Clone)]
80struct TestService {
81 s: String,
82}
83
Janis Danisevskis798a09a2020-08-18 08:35:38 -070084#[repr(u32)]
85enum TestTransactionCode {
86 Test = SpIBinder::FIRST_CALL_TRANSACTION,
87 GetSelinuxContext,
88}
89
90impl TryFrom<u32> for TestTransactionCode {
91 type Error = StatusCode;
92
93 fn try_from(c: u32) -> Result<Self, Self::Error> {
94 match c {
95 _ if c == TestTransactionCode::Test as u32 => Ok(TestTransactionCode::Test),
96 _ if c == TestTransactionCode::GetSelinuxContext as u32 => {
97 Ok(TestTransactionCode::GetSelinuxContext)
98 }
99 _ => Err(StatusCode::UNKNOWN_TRANSACTION),
100 }
101 }
102}
103
Stephen Crane2a3c2502020-06-16 17:48:35 -0700104impl Interface for TestService {}
105
106impl ITest for TestService {
107 fn test(&self) -> binder::Result<String> {
108 Ok(self.s.clone())
109 }
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700110
111 fn get_selinux_context(&self) -> binder::Result<String> {
112 let sid =
113 ThreadState::with_calling_sid(|sid| sid.map(|s| s.to_string_lossy().into_owned()));
114 sid.ok_or(StatusCode::UNEXPECTED_NULL)
115 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700116}
117
118/// Trivial testing binder interface
119pub trait ITest: Interface {
120 /// Returns a test string
121 fn test(&self) -> binder::Result<String>;
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700122
123 /// Returns the caller's SELinux context
124 fn get_selinux_context(&self) -> binder::Result<String>;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700125}
126
127declare_binder_interface! {
128 ITest["android.os.ITest"] {
129 native: BnTest(on_transact),
130 proxy: BpTest {
131 x: i32 = 100
132 },
133 }
134}
135
136fn on_transact(
137 service: &dyn ITest,
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700138 code: TransactionCode,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700139 _data: &Parcel,
140 reply: &mut Parcel,
141) -> binder::Result<()> {
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700142 match code.try_into()? {
143 TestTransactionCode::Test => reply.write(&service.test()?),
144 TestTransactionCode::GetSelinuxContext => reply.write(&service.get_selinux_context()?),
145 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700146}
147
148impl ITest for BpTest {
149 fn test(&self) -> binder::Result<String> {
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700150 let reply =
151 self.binder
152 .transact(TestTransactionCode::Test as TransactionCode, 0, |_| Ok(()))?;
153 reply.read()
154 }
155
156 fn get_selinux_context(&self) -> binder::Result<String> {
157 let reply = self.binder.transact(
158 TestTransactionCode::GetSelinuxContext as TransactionCode,
159 0,
160 |_| Ok(()),
161 )?;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700162 reply.read()
163 }
164}
165
166impl ITest for Binder<BnTest> {
167 fn test(&self) -> binder::Result<String> {
168 self.0.test()
169 }
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700170
171 fn get_selinux_context(&self) -> binder::Result<String> {
172 self.0.get_selinux_context()
173 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700174}
175
176#[cfg(test)]
177mod tests {
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700178 use selinux_bindgen as selinux_sys;
179 use std::ffi::CStr;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700180 use std::fs::File;
181 use std::process::{Child, Command};
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700182 use std::ptr;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700183 use std::sync::atomic::{AtomicBool, Ordering};
184 use std::sync::Arc;
185 use std::thread;
186 use std::time::Duration;
187
188 use binder::{DeathRecipient, FromIBinder, IBinder, SpIBinder, StatusCode};
189
190 use super::{ITest, RUST_SERVICE_BINARY};
191
192 pub struct ScopedServiceProcess(Child);
193
194 impl ScopedServiceProcess {
195 pub fn new(identifier: &str) -> Self {
196 Self::new_internal(identifier, None)
197 }
198
199 pub fn new_with_extension(identifier: &str, extension: &str) -> Self {
200 Self::new_internal(identifier, Some(extension))
201 }
202
203 fn new_internal(identifier: &str, extension: Option<&str>) -> Self {
204 let mut binary_path =
205 std::env::current_exe().expect("Could not retrieve current executable path");
206 binary_path.pop();
207 binary_path.push(RUST_SERVICE_BINARY);
208 let mut command = Command::new(&binary_path);
209 command.arg(identifier);
210 if let Some(ext) = extension {
211 command.arg(ext);
212 }
213 let child = command.spawn().expect("Could not start service");
214 Self(child)
215 }
216 }
217
218 impl Drop for ScopedServiceProcess {
219 fn drop(&mut self) {
220 self.0.kill().expect("Could not kill child process");
221 self.0
222 .wait()
223 .expect("Could not wait for child process to die");
224 }
225 }
226
227 #[test]
228 fn check_services() {
229 let mut sm = binder::get_service("manager").expect("Did not get manager binder service");
230 assert!(sm.is_binder_alive());
231 assert!(sm.ping_binder().is_ok());
232
233 assert!(binder::get_service("this_service_does_not_exist").is_none());
234 assert_eq!(
235 binder::get_interface::<dyn ITest>("this_service_does_not_exist").err(),
236 Some(StatusCode::NAME_NOT_FOUND)
237 );
238
239 // The service manager service isn't an ITest, so this must fail.
240 assert_eq!(
241 binder::get_interface::<dyn ITest>("manager").err(),
242 Some(StatusCode::BAD_TYPE)
243 );
244 }
245
246 #[test]
247 fn trivial_client() {
248 let service_name = "trivial_client_test";
249 let _process = ScopedServiceProcess::new(service_name);
250 let test_client: Box<dyn ITest> =
251 binder::get_interface(service_name).expect("Did not get manager binder service");
252 assert_eq!(test_client.test().unwrap(), "trivial_client_test");
253 }
254
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700255 #[test]
256 fn get_selinux_context() {
257 let service_name = "get_selinux_context";
258 let _process = ScopedServiceProcess::new(service_name);
259 let test_client: Box<dyn ITest> =
260 binder::get_interface(service_name).expect("Did not get manager binder service");
261 let expected_context = unsafe {
262 let mut out_ptr = ptr::null_mut();
263 assert_eq!(selinux_sys::getcon(&mut out_ptr), 0);
264 assert!(!out_ptr.is_null());
265 CStr::from_ptr(out_ptr)
266 };
267 assert_eq!(
268 test_client.get_selinux_context().unwrap(),
269 expected_context.to_str().expect("context was invalid UTF-8"),
270 );
271 }
272
Stephen Crane2a3c2502020-06-16 17:48:35 -0700273 fn register_death_notification(binder: &mut SpIBinder) -> (Arc<AtomicBool>, DeathRecipient) {
274 let binder_died = Arc::new(AtomicBool::new(false));
275
276 let mut death_recipient = {
277 let flag = binder_died.clone();
278 DeathRecipient::new(move || {
279 flag.store(true, Ordering::Relaxed);
280 })
281 };
282
283 binder
284 .link_to_death(&mut death_recipient)
285 .expect("link_to_death failed");
286
287 (binder_died, death_recipient)
288 }
289
290 /// Killing a remote service should unregister the service and trigger
291 /// death notifications.
292 #[test]
293 fn test_death_notifications() {
294 binder::ProcessState::start_thread_pool();
295
296 let service_name = "test_death_notifications";
297 let service_process = ScopedServiceProcess::new(service_name);
298 let mut remote = binder::get_service(service_name).expect("Could not retrieve service");
299
300 let (binder_died, _recipient) = register_death_notification(&mut remote);
301
302 drop(service_process);
303 remote
304 .ping_binder()
305 .expect_err("Service should have died already");
306
307 // Pause to ensure any death notifications get delivered
308 thread::sleep(Duration::from_secs(1));
309
310 assert!(
311 binder_died.load(Ordering::Relaxed),
312 "Did not receive death notification"
313 );
314 }
315
316 /// Test unregistering death notifications.
317 #[test]
318 fn test_unregister_death_notifications() {
319 binder::ProcessState::start_thread_pool();
320
321 let service_name = "test_unregister_death_notifications";
322 let service_process = ScopedServiceProcess::new(service_name);
323 let mut remote = binder::get_service(service_name).expect("Could not retrieve service");
324
325 let (binder_died, mut recipient) = register_death_notification(&mut remote);
326
327 remote
328 .unlink_to_death(&mut recipient)
329 .expect("Could not unlink death notifications");
330
331 drop(service_process);
332 remote
333 .ping_binder()
334 .expect_err("Service should have died already");
335
336 // Pause to ensure any death notifications get delivered
337 thread::sleep(Duration::from_secs(1));
338
339 assert!(
340 !binder_died.load(Ordering::Relaxed),
341 "Received unexpected death notification after unlinking",
342 );
343 }
344
345 /// Dropping a remote handle should unregister any death notifications.
346 #[test]
347 fn test_death_notification_registration_lifetime() {
348 binder::ProcessState::start_thread_pool();
349
350 let service_name = "test_death_notification_registration_lifetime";
351 let service_process = ScopedServiceProcess::new(service_name);
352 let mut remote = binder::get_service(service_name).expect("Could not retrieve service");
353
354 let (binder_died, _recipient) = register_death_notification(&mut remote);
355
356 // This should automatically unregister our death notification.
357 drop(remote);
358
359 drop(service_process);
360
361 // Pause to ensure any death notifications get delivered
362 thread::sleep(Duration::from_secs(1));
363
364 // We dropped the remote handle, so we should not receive the death
365 // notification when the remote process dies here.
366 assert!(
367 !binder_died.load(Ordering::Relaxed),
368 "Received unexpected death notification after dropping remote handle"
369 );
370 }
371
372 /// Test IBinder interface methods not exercised elsewhere.
373 #[test]
374 fn test_misc_ibinder() {
375 let service_name = "rust_test_ibinder";
376
377 {
378 let _process = ScopedServiceProcess::new(service_name);
379
380 let mut remote = binder::get_service(service_name);
381 assert!(remote.is_binder_alive());
382 remote.ping_binder().expect("Could not ping remote service");
383
384 // We're not testing the output of dump here, as that's really a
385 // property of the C++ implementation. There is the risk that the
386 // method just does nothing, but we don't want to depend on any
387 // particular output from the underlying library.
388 let null_out = File::open("/dev/null").expect("Could not open /dev/null");
389 remote
390 .dump(&null_out, &[])
391 .expect("Could not dump remote service");
392 }
393
394 // get/set_extensions is tested in test_extensions()
395
396 // transact is tested everywhere else, and we can't make raw
397 // transactions outside the [FIRST_CALL_TRANSACTION,
398 // LAST_CALL_TRANSACTION] range from the NDK anyway.
399
400 // link_to_death is tested in test_*_death_notification* tests.
401 }
402
403 #[test]
404 fn test_extensions() {
405 let service_name = "rust_test_extensions";
406 let extension_name = "rust_test_extensions_ext";
407
408 {
409 let _process = ScopedServiceProcess::new(service_name);
410
411 let mut remote = binder::get_service(service_name);
412 assert!(remote.is_binder_alive());
413
414 let extension = remote
415 .get_extension()
416 .expect("Could not check for an extension");
417 assert!(extension.is_none());
418 }
419
420 {
421 let _process = ScopedServiceProcess::new_with_extension(service_name, extension_name);
422
423 let mut remote = binder::get_service(service_name);
424 assert!(remote.is_binder_alive());
425
426 let maybe_extension = remote
427 .get_extension()
428 .expect("Could not check for an extension");
429
430 let extension = maybe_extension.expect("Remote binder did not have an extension");
431
432 let extension: Box<dyn ITest> = FromIBinder::try_from(extension)
433 .expect("Extension could not be converted to the expected interface");
434
435 assert_eq!(extension.test().unwrap(), extension_name);
436 }
437 }
438}