1use crate::CoreError;
23
24#[cfg(target_os = "android")]
29mod imp {
30 use super::*;
31 use crate::dex;
32 use std::os::raw::{c_char, c_void};
33 use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
34
35 const STATUS_OK: i32 = 0;
38 const STATUS_UNKNOWN_TRANSACTION: i32 = -2;
39 const EX_NONE: i32 = 0;
40
41 const AM_DESCRIPTOR: &[u8] = b"android.app.IActivityManager\0";
44 const OBS_DESCRIPTOR: &[u8] = b"android.app.IProcessObserver\0";
45 const ACTIVITY_SERVICE: &[u8] = b"activity\0";
46 const LIBBINDER_PATH: &[u8] = b"/system/lib64/libbinder_ndk.so\0";
47
48 static OBS_FG_CODE: AtomicU32 = AtomicU32::new(0);
57 static OBS_EVENTFD: AtomicI32 = AtomicI32::new(-1);
58
59 type AIBinder = c_void;
62 #[allow(non_camel_case_types)]
63 type AIBinder_Class = c_void;
64 type AParcel = c_void;
65 type BinderStatus = i32;
66 type StringAllocator = unsafe extern "C" fn(*mut c_void, i32, *mut *mut c_char) -> bool;
67
68 unsafe extern "C" fn am_on_create(_: *mut c_void) -> *mut c_void { std::ptr::null_mut() }
72 unsafe extern "C" fn am_on_destroy(_: *mut c_void) {}
73 unsafe extern "C" fn am_on_transact(
74 _: *mut AIBinder, _: u32, _: *const AParcel, _: *mut AParcel,
75 ) -> BinderStatus { STATUS_UNKNOWN_TRANSACTION }
76
77 unsafe extern "C" fn obs_on_create(_: *mut c_void) -> *mut c_void { std::ptr::null_mut() }
79 unsafe extern "C" fn obs_on_destroy(_: *mut c_void) {}
80 unsafe extern "C" fn obs_on_transact(
81 _: *mut AIBinder, code: u32, _: *const AParcel, _: *mut AParcel,
82 ) -> BinderStatus {
83 if code == OBS_FG_CODE.load(Ordering::Relaxed) {
84 let efd = OBS_EVENTFD.load(Ordering::Relaxed);
85 if efd >= 0 {
86 let val: u64 = 1;
87 unsafe { libc::write(efd, &val as *const u64 as *const c_void, 8) };
88 }
89 }
90 STATUS_OK
91 }
92
93 unsafe extern "C" fn string_alloc(
96 cookie: *mut c_void, length: i32, buffer: *mut *mut c_char,
97 ) -> bool {
98 if length < 0 { return true; }
99 let s = unsafe { &mut *(cookie as *mut StringBuf) };
100 s.0.reserve_exact(length as usize + 1);
101 unsafe { s.0.as_mut_vec().resize(length as usize + 1, 0) };
102 unsafe { *buffer = s.0.as_mut_ptr() as *mut c_char };
103 true
104 }
105
106 struct StringBuf(String);
107 impl StringBuf {
108 fn new() -> Self { Self(String::new()) }
109 fn finish(mut self) -> Option<String> {
110 if let Some(pos) = self.0.as_bytes().iter().position(|&b| b == 0) {
111 unsafe { self.0.as_mut_vec().truncate(pos) };
112 }
113 if self.0.is_empty() { None } else { Some(self.0) }
114 }
115 }
116
117 struct Vtable {
120 get_service: unsafe extern "C" fn(*const c_char) -> *mut AIBinder,
121 class_define: unsafe extern "C" fn(
122 *const c_char,
123 unsafe extern "C" fn(*mut c_void) -> *mut c_void,
124 unsafe extern "C" fn(*mut c_void),
125 unsafe extern "C" fn(*mut AIBinder, u32, *const AParcel, *mut AParcel) -> BinderStatus,
126 ) -> *mut AIBinder_Class,
127 associate_class: unsafe extern "C" fn(*mut AIBinder, *mut AIBinder_Class) -> bool,
128 new_binder: unsafe extern "C" fn(*const AIBinder_Class, *mut c_void) -> *mut AIBinder,
129 prepare_transaction: unsafe extern "C" fn(*mut AIBinder, *mut *mut AParcel) -> BinderStatus,
130 transact: unsafe extern "C" fn(*mut AIBinder, u32, *mut *mut AParcel, *mut *mut AParcel, u32) -> BinderStatus,
131 dec_strong: unsafe extern "C" fn(*mut AIBinder),
132 parcel_delete: unsafe extern "C" fn(*mut AParcel),
133 read_int32: unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus,
134 read_string: unsafe extern "C" fn(*const AParcel, *mut c_void, StringAllocator) -> BinderStatus,
135 write_strong_binder: unsafe extern "C" fn(*mut AParcel, *mut AIBinder) -> BinderStatus,
136 set_thread_pool_max: unsafe extern "C" fn(u32),
137 join_thread_pool: unsafe extern "C" fn(),
138 #[allow(dead_code)]
140 read_bool: Option<unsafe extern "C" fn(*const AParcel, *mut bool) -> BinderStatus>,
141 }
142
143 struct DlHandle(*mut c_void);
146 unsafe impl Send for DlHandle {}
147 impl Drop for DlHandle {
148 fn drop(&mut self) {
149 }
155 }
156
157 struct OwnedParcel { ptr: *mut AParcel, delete: unsafe extern "C" fn(*mut AParcel) }
158 impl Drop for OwnedParcel {
159 fn drop(&mut self) { if !self.ptr.is_null() { unsafe { (self.delete)(self.ptr) }; } }
160 }
161
162 struct OwnedBinder { ptr: *mut AIBinder, dec_strong: unsafe extern "C" fn(*mut AIBinder) }
163 unsafe impl Send for OwnedBinder {}
164 impl Drop for OwnedBinder {
165 fn drop(&mut self) { if !self.ptr.is_null() { unsafe { (self.dec_strong)(self.ptr) }; } }
166 }
167
168 macro_rules! dlsym_fn {
171 ($handle:expr, $name:literal, $ty:ty) => {{
172 let sym = unsafe {
173 libc::dlsym($handle, concat!($name, "\0").as_ptr() as *const c_char)
174 };
175 if sym.is_null() {
176 return Err(CoreError::binder(-1, concat!("dlsym:", $name)));
177 }
178 unsafe { std::mem::transmute::<*mut c_void, $ty>(sym) }
179 }};
180 }
181
182 macro_rules! dlsym_opt {
183 ($handle:expr, $name:literal, $ty:ty) => {{
184 let sym = unsafe {
185 libc::dlsym($handle, concat!($name, "\0").as_ptr() as *const c_char)
186 };
187 if sym.is_null() { None }
188 else { Some(unsafe { std::mem::transmute::<*mut c_void, $ty>(sym) }) }
189 }};
190 }
191
192 fn load_vtable(handle: *mut c_void) -> Result<Vtable, CoreError> {
193 Ok(Vtable {
194 get_service: dlsym_fn!(handle, "AServiceManager_getService",
195 unsafe extern "C" fn(*const c_char) -> *mut AIBinder),
196 class_define: dlsym_fn!(handle, "AIBinder_Class_define",
197 unsafe extern "C" fn(
198 *const c_char,
199 unsafe extern "C" fn(*mut c_void) -> *mut c_void,
200 unsafe extern "C" fn(*mut c_void),
201 unsafe extern "C" fn(*mut AIBinder, u32, *const AParcel, *mut AParcel) -> BinderStatus,
202 ) -> *mut AIBinder_Class),
203 associate_class: dlsym_fn!(handle, "AIBinder_associateClass",
204 unsafe extern "C" fn(*mut AIBinder, *mut AIBinder_Class) -> bool),
205 new_binder: dlsym_fn!(handle, "AIBinder_new",
206 unsafe extern "C" fn(*const AIBinder_Class, *mut c_void) -> *mut AIBinder),
207 prepare_transaction: dlsym_fn!(handle, "AIBinder_prepareTransaction",
208 unsafe extern "C" fn(*mut AIBinder, *mut *mut AParcel) -> BinderStatus),
209 transact: dlsym_fn!(handle, "AIBinder_transact",
210 unsafe extern "C" fn(*mut AIBinder, u32, *mut *mut AParcel, *mut *mut AParcel, u32) -> BinderStatus),
211 dec_strong: dlsym_fn!(handle, "AIBinder_decStrong",
212 unsafe extern "C" fn(*mut AIBinder)),
213 parcel_delete: dlsym_fn!(handle, "AParcel_delete",
214 unsafe extern "C" fn(*mut AParcel)),
215 read_int32: dlsym_fn!(handle, "AParcel_readInt32",
216 unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus),
217 read_string: dlsym_fn!(handle, "AParcel_readString",
218 unsafe extern "C" fn(*const AParcel, *mut c_void, StringAllocator) -> BinderStatus),
219 write_strong_binder: dlsym_fn!(handle, "AParcel_writeStrongBinder",
220 unsafe extern "C" fn(*mut AParcel, *mut AIBinder) -> BinderStatus),
221 set_thread_pool_max: dlsym_fn!(handle, "ABinderProcess_setThreadPoolMaxThreadCount",
222 unsafe extern "C" fn(u32)),
223 join_thread_pool: dlsym_fn!(handle, "ABinderProcess_joinThreadPool",
224 unsafe extern "C" fn()),
225 read_bool: dlsym_opt!(handle, "AParcel_readBool",
226 unsafe extern "C" fn(*const AParcel, *mut bool) -> BinderStatus),
227 })
228 }
229
230 struct ParcelReader<'a> { vt: &'a Vtable, parcel: &'a OwnedParcel }
233
234 impl<'a> ParcelReader<'a> {
235 fn read_i32(&self) -> Result<i32, CoreError> {
236 let mut v = 0i32;
237 let s = unsafe { (self.vt.read_int32)(self.parcel.ptr, &mut v) };
238 if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_readInt32")); }
239 Ok(v)
240 }
241 fn read_string(&self) -> Result<Option<String>, CoreError> {
242 let mut buf = StringBuf::new();
243 let s = unsafe {
244 (self.vt.read_string)(self.parcel.ptr, &mut buf as *mut StringBuf as *mut c_void, string_alloc)
245 };
246 if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_readString")); }
247 Ok(buf.finish())
248 }
249 fn skip_i32s(&self, n: usize) -> Result<(), CoreError> {
250 for _ in 0..n { self.read_i32()?; }
251 Ok(())
252 }
253 fn skip_int_array(&self) -> Result<(), CoreError> {
254 let count = self.read_i32()?.max(0) as usize;
255 self.skip_i32s(count)
256 }
257 fn read_first_package_from_names(&self) -> Result<Option<String>, CoreError> {
258 let count = self.read_i32()?.max(0) as usize;
259 let mut first: Option<String> = None;
260 for _ in 0..count {
261 let s = self.read_string()?;
262 if first.is_none() {
263 first = s.and_then(|c| c.split('/').next().map(str::to_owned));
264 }
265 }
266 Ok(first)
267 }
268 }
269
270 fn parse_root_task_info_body(r: &ParcelReader<'_>) -> Result<Option<String>, CoreError> {
273 let scratch = r.read_i32()?;
274 if scratch != 0 { r.skip_i32s(4)?; }
275 r.skip_int_array()?;
276 r.read_first_package_from_names()
277 }
278
279 fn parse_stack_info_body(r: &ParcelReader<'_>) -> Result<Option<String>, CoreError> {
280 r.skip_i32s(5)?;
281 r.skip_int_array()?;
282 r.read_first_package_from_names()
283 }
284
285 pub struct TxCodes {
288 pub observer_code: u32,
289 pub query_code: u32,
290 pub api_mode: u8, pub fg_code: u32,
292 }
293
294 pub fn read_tx_cache(cache_path: &str) -> Option<TxCodes> {
295 let text = std::fs::read_to_string(cache_path).ok()?;
296 let mut parts = text.split_whitespace();
297 let obs: u32 = parts.next()?.parse().ok()?;
298 let query: u32 = parts.next()?.parse().ok()?;
299 let api: u8 = parts.next()?.parse().ok()?;
300 let fg: u32 = parts.next()?.parse().ok()?;
301 if obs == 0 || query == 0 || fg == 0 || (api != 1 && api != 2) { return None; }
303 Some(TxCodes { observer_code: obs, query_code: query, api_mode: api, fg_code: fg })
304 }
305
306 pub fn write_tx_cache(cache_path: &str, codes: &TxCodes) {
307 let _ = std::fs::create_dir_all(
308 std::path::Path::new(cache_path).parent().unwrap_or(std::path::Path::new("/"))
309 );
310 let _ = std::fs::write(
311 cache_path,
312 format!("{} {} {} {}\n", codes.observer_code, codes.query_code, codes.api_mode, codes.fg_code),
313 );
314 }
315
316 pub fn resolve_tx_codes(_cache_path: &str) -> Result<TxCodes, CoreError> {
317 let (obs, query, api, fg) = dex::resolve_tx_codes_from_dex()
318 .ok_or_else(|| CoreError::binder(-1, "tx_code_resolution:dex_parse_failed"))?;
319 Ok(TxCodes { observer_code: obs, query_code: query, api_mode: api, fg_code: fg })
320 }
321
322 pub struct ActivityManagerBinder {
325 _lib: DlHandle,
326 vt: Vtable,
327 _class: *mut AIBinder_Class,
328 service: OwnedBinder,
329 tx_code: u32,
330 legacy: bool,
331 }
332 unsafe impl Send for ActivityManagerBinder {}
333
334 impl ActivityManagerBinder {
335 fn open_inner(handle: *mut c_void) -> Result<(DlHandle, Vtable, *mut AIBinder_Class, OwnedBinder), CoreError> {
336 let lib = DlHandle(handle);
337 let vt = load_vtable(handle)?;
338
339 let am_class = unsafe {
340 (vt.class_define)(
341 AM_DESCRIPTOR.as_ptr() as *const c_char,
342 am_on_create, am_on_destroy, am_on_transact,
343 )
344 };
345 if am_class.is_null() { return Err(CoreError::binder(-1, "AIBinder_Class_define:AM")); }
346
347 let raw = unsafe { (vt.get_service)(ACTIVITY_SERVICE.as_ptr() as *const c_char) };
348 if raw.is_null() { return Err(CoreError::binder(-1, "AServiceManager_getService:activity")); }
349 unsafe { (vt.associate_class)(raw, am_class) };
350
351 let service = OwnedBinder { ptr: raw, dec_strong: vt.dec_strong };
352 Ok((lib, vt, am_class, service))
353 }
354
355 fn dlopen_libbinder() -> Result<*mut c_void, CoreError> {
356 use std::os::raw::c_char;
357 let handle = unsafe {
358 libc::dlopen(LIBBINDER_PATH.as_ptr() as *const c_char, libc::RTLD_NOW | libc::RTLD_LOCAL)
359 };
360 if handle.is_null() { return Err(CoreError::binder(-1, "dlopen:libbinder_ndk.so")); }
361 Ok(handle)
362 }
363
364 pub fn open(cache_path: &str) -> Result<Self, CoreError> {
367 let handle = Self::dlopen_libbinder()?;
368 let (lib, vt, class, service) = Self::open_inner(handle)?;
369 let codes = resolve_tx_codes(cache_path)?;
370 let legacy = codes.api_mode == 2;
371 Ok(Self { _lib: lib, vt, _class: class, service, tx_code: codes.query_code, legacy })
372 }
373
374 pub fn open_with_observer(cache_path: &str) -> Result<(Self, i32), CoreError> {
380 let handle = Self::dlopen_libbinder()?;
381 let (lib, vt, am_class, service) = Self::open_inner(handle)?;
382 let codes = resolve_tx_codes(cache_path)?;
383 let legacy = codes.api_mode == 2;
384
385 let efd = unsafe { libc::eventfd(0, libc::EFD_NONBLOCK | libc::EFD_CLOEXEC) };
387 if efd < 0 { return Err(CoreError::sys(unsafe { *libc::__errno() }, "eventfd")); }
388
389 OBS_FG_CODE.store(codes.fg_code, Ordering::Relaxed);
391 OBS_EVENTFD.store(efd, Ordering::Relaxed);
392
393 let obs_class = unsafe {
395 (vt.class_define)(
396 OBS_DESCRIPTOR.as_ptr() as *const c_char,
397 obs_on_create, obs_on_destroy, obs_on_transact,
398 )
399 };
400 if obs_class.is_null() {
401 unsafe { libc::close(efd) };
402 return Err(CoreError::binder(-1, "AIBinder_Class_define:Observer"));
403 }
404
405 let obs_binder = unsafe { (vt.new_binder)(obs_class, std::ptr::null_mut()) };
407 if obs_binder.is_null() {
408 unsafe { libc::close(efd) };
409 return Err(CoreError::binder(-1, "AIBinder_new:Observer"));
410 }
411 unsafe { (vt.associate_class)(obs_binder, obs_class) };
412
413 let mut in_ptr: *mut AParcel = std::ptr::null_mut();
415 let s = unsafe { (vt.prepare_transaction)(service.ptr, &mut in_ptr) };
416 if s != STATUS_OK {
417 unsafe { libc::close(efd) };
418 return Err(CoreError::binder(s, "prepareTransaction:registerObserver"));
419 }
420 unsafe { (vt.write_strong_binder)(in_ptr, obs_binder) };
421 let mut out_ptr: *mut AParcel = std::ptr::null_mut();
422 let s = unsafe {
423 (vt.transact)(service.ptr, codes.observer_code, &mut in_ptr, &mut out_ptr, 0)
424 };
425 if !out_ptr.is_null() { unsafe { (vt.parcel_delete)(out_ptr) }; }
426 if s != STATUS_OK {
427 unsafe { libc::close(efd) };
428 return Err(CoreError::binder(s, "transact:registerProcessObserver"));
429 }
430
431 unsafe { (vt.set_thread_pool_max)(0) };
433 let join_fn = vt.join_thread_pool;
434 std::thread::spawn(move || unsafe { join_fn() });
435
436 let binder = Self { _lib: lib, vt, _class: am_class, service, tx_code: codes.query_code, legacy };
437 Ok((binder, efd))
438 }
439
440 fn do_transact(&self) -> Result<OwnedParcel, CoreError> {
441 let mut in_ptr: *mut AParcel = std::ptr::null_mut();
442 let s = unsafe { (self.vt.prepare_transaction)(self.service.ptr, &mut in_ptr) };
443 if s != STATUS_OK { return Err(CoreError::binder(s, "AIBinder_prepareTransaction")); }
444 let mut out_ptr: *mut AParcel = std::ptr::null_mut();
445 let s = unsafe {
446 (self.vt.transact)(self.service.ptr, self.tx_code, &mut in_ptr, &mut out_ptr, 0)
447 };
448 let out = OwnedParcel { ptr: out_ptr, delete: self.vt.parcel_delete };
449 if s != STATUS_OK { return Err(CoreError::binder(s, "AIBinder_transact")); }
450 Ok(out)
451 }
452
453 pub fn get_focused_package(&self) -> Result<Option<String>, CoreError> {
454 let out = self.do_transact()?;
455 let r = ParcelReader { vt: &self.vt, parcel: &out };
456 let ex = r.read_i32()?;
457 if ex != EX_NONE { return Err(CoreError::binder(ex, "getFocusedTask:exception")); }
458 let present = r.read_i32()?;
459 if present == 0 { return Ok(None); }
460 if self.legacy { parse_stack_info_body(&r) } else { parse_root_task_info_body(&r) }
461 }
462 }
463}
464
465#[cfg(target_os = "android")]
468pub use imp::{ActivityManagerBinder, TxCodes, read_tx_cache, write_tx_cache, resolve_tx_codes};
469
470#[cfg(not(target_os = "android"))]
473pub struct ActivityManagerBinder;
474
475#[cfg(not(target_os = "android"))]
476impl ActivityManagerBinder {
477 pub fn open(_cache_path: &str) -> Result<Self, crate::CoreError> {
478 Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
479 }
480 pub fn open_with_observer(_cache_path: &str) -> Result<(Self, i32), crate::CoreError> {
481 Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
482 }
483 pub fn get_focused_package(&self) -> Result<Option<String>, crate::CoreError> {
484 Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
485 }
486}
487
488#[cfg(not(target_os = "android"))]
489pub struct TxCodes { pub observer_code: u32, pub query_code: u32, pub api_mode: u8, pub fg_code: u32 }
490
491#[cfg(not(target_os = "android"))]
492pub fn read_tx_cache(_: &str) -> Option<TxCodes> { None }
493#[cfg(not(target_os = "android"))]
494pub fn write_tx_cache(_: &str, _: &TxCodes) {}
495#[cfg(not(target_os = "android"))]
496pub fn resolve_tx_codes(_: &str) -> Result<TxCodes, crate::CoreError> {
497 Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
498}