xref: /linux/drivers/android/binder/rust_binder_main.rs (revision 20bed0d6ff62d985fe8222958825504b8aad4e88)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 // Copyright (C) 2025 Google LLC.
4 
5 //! Binder -- the Android IPC mechanism.
6 
7 #![crate_name = "rust_binder"]
8 #![recursion_limit = "256"]
9 
10 use kernel::{
11     bindings::{self, seq_file},
12     fs::File,
13     list::{ListArc, ListArcSafe, ListLinksSelfPtr, TryNewListArc},
14     module::this_module,
15     prelude::*,
16     seq_file::SeqFile,
17     seq_print,
18     sync::atomic::{ordering::Relaxed, Atomic},
19     sync::poll::PollTable,
20     sync::Arc,
21     task::Pid,
22     transmute::AsBytes,
23     types::ForeignOwnable,
24     uaccess::UserSliceWriter,
25 };
26 
27 use crate::{context::Context, page_range::Shrinker, process::Process, thread::Thread};
28 
29 use core::ptr::NonNull;
30 
31 mod allocation;
32 mod context;
33 mod deferred_close;
34 mod defs;
35 #[macro_use]
36 mod debug;
37 mod error;
38 mod netlink;
39 mod node;
40 mod page_range;
41 mod process;
42 mod range_alloc;
43 mod stats;
44 mod thread;
45 mod trace;
46 mod transaction;
47 
48 #[allow(warnings)] // generated bindgen code
49 mod binderfs {
50     use kernel::bindings::{dentry, inode};
51 
52     extern "C" {
53         pub fn init_rust_binderfs() -> kernel::ffi::c_int;
54     }
55     extern "C" {
56         pub fn rust_binderfs_create_proc_file(
57             nodp: *mut inode,
58             pid: kernel::ffi::c_int,
59         ) -> *mut dentry;
60     }
61     extern "C" {
62         pub fn rust_binderfs_remove_file(dentry: *mut dentry);
63     }
64     pub type rust_binder_context = *mut kernel::ffi::c_void;
65     #[repr(C)]
66     #[derive(Copy, Clone)]
67     pub struct binder_device {
68         pub minor: kernel::ffi::c_int,
69         pub ctx: rust_binder_context,
70     }
71     impl Default for binder_device {
72         fn default() -> Self {
73             let mut s = ::core::mem::MaybeUninit::<Self>::uninit();
74             unsafe {
75                 ::core::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
76                 s.assume_init()
77             }
78         }
79     }
80 }
81 
82 module! {
83     type: BinderModule,
84     name: "binder",
85     authors: ["Wedson Almeida Filho", "Alice Ryhl"],
86     description: "Android Binder",
87     license: "GPL",
88 }
89 
90 use kernel::bindings::rust_binder_layout;
91 #[no_mangle]
92 static RUST_BINDER_LAYOUT: rust_binder_layout = rust_binder_layout {
93     t: transaction::TRANSACTION_LAYOUT,
94     p: process::PROCESS_LAYOUT,
95     n: node::NODE_LAYOUT,
96 };
97 
98 fn next_debug_id() -> usize {
99     static NEXT_DEBUG_ID: Atomic<usize> = Atomic::new(0);
100 
101     loop {
102         let id = NEXT_DEBUG_ID.fetch_add(1, Relaxed);
103         if id != 0 {
104             return id;
105         }
106     }
107 }
108 
109 /// Provides a single place to write Binder return values via the
110 /// supplied `UserSliceWriter`.
111 pub(crate) struct BinderReturnWriter<'a> {
112     writer: UserSliceWriter,
113     thread: &'a Thread,
114 }
115 
116 impl<'a> BinderReturnWriter<'a> {
117     fn new(writer: UserSliceWriter, thread: &'a Thread) -> Self {
118         BinderReturnWriter { writer, thread }
119     }
120 
121     /// Write a return code back to user space.
122     /// Should be a `BR_` constant from [`defs`] e.g. [`defs::BR_TRANSACTION_COMPLETE`].
123     fn write_code(&mut self, code: u32) -> Result {
124         crate::trace::trace_return(code);
125         stats::GLOBAL_STATS.inc_br(code);
126         self.thread.process.stats.inc_br(code);
127         self.writer.write(&code)
128     }
129 
130     /// Write something *other than* a return code to user space.
131     fn write_payload<T: AsBytes>(&mut self, payload: &T) -> Result {
132         self.writer.write(payload)
133     }
134 
135     fn len(&self) -> usize {
136         self.writer.len()
137     }
138 }
139 
140 /// Specifies how a type should be delivered to the read part of a BINDER_WRITE_READ ioctl.
141 ///
142 /// When a value is pushed to the todo list for a process or thread, it is stored as a trait object
143 /// with the type `Arc<dyn DeliverToRead>`. Trait objects are a Rust feature that lets you
144 /// implement dynamic dispatch over many different types. This lets us store many different types
145 /// in the todo list.
146 trait DeliverToRead: ListArcSafe + Send + Sync {
147     /// Performs work. Returns true if remaining work items in the queue should be processed
148     /// immediately, or false if it should return to caller before processing additional work
149     /// items.
150     fn do_work(
151         self: DArc<Self>,
152         thread: &Thread,
153         writer: &mut BinderReturnWriter<'_>,
154     ) -> Result<bool>;
155 
156     /// Cancels the given work item. This is called instead of [`DeliverToRead::do_work`] when work
157     /// won't be delivered.
158     fn cancel(self: DArc<Self>);
159 
160     /// Should we use `wake_up_interruptible_sync` or `wake_up_interruptible` when scheduling this
161     /// work item?
162     ///
163     /// Generally only set to true for non-oneway transactions.
164     fn should_sync_wakeup(&self) -> bool;
165 
166     fn debug_print(&self, m: &SeqFile, prefix: &str, transaction_prefix: &str) -> Result;
167 }
168 
169 // Wrapper around a `DeliverToRead` with linked list links.
170 #[pin_data]
171 struct DTRWrap<T: ?Sized> {
172     #[pin]
173     links: ListLinksSelfPtr<DTRWrap<dyn DeliverToRead>>,
174     #[pin]
175     wrapped: T,
176 }
177 kernel::list::impl_list_arc_safe! {
178     impl{T: ListArcSafe + ?Sized} ListArcSafe<0> for DTRWrap<T> {
179         tracked_by wrapped: T;
180     }
181 }
182 kernel::list::impl_list_item! {
183     impl ListItem<0> for DTRWrap<dyn DeliverToRead> {
184         using ListLinksSelfPtr { self.links };
185     }
186 }
187 
188 impl<T: ?Sized> core::ops::Deref for DTRWrap<T> {
189     type Target = T;
190     fn deref(&self) -> &T {
191         &self.wrapped
192     }
193 }
194 
195 type DArc<T> = kernel::sync::Arc<DTRWrap<T>>;
196 type DLArc<T> = kernel::list::ListArc<DTRWrap<T>>;
197 
198 impl<T: ListArcSafe> DTRWrap<T> {
199     fn new(val: impl PinInit<T>) -> impl PinInit<Self> {
200         pin_init!(Self {
201             links <- ListLinksSelfPtr::new(),
202             wrapped <- val,
203         })
204     }
205 
206     fn arc_try_new(val: T) -> Result<DLArc<T>, kernel::alloc::AllocError> {
207         ListArc::pin_init(
208             try_pin_init!(Self {
209                 links <- ListLinksSelfPtr::new(),
210                 wrapped: val,
211             }),
212             GFP_KERNEL,
213         )
214         .map_err(|_| kernel::alloc::AllocError)
215     }
216 
217     fn arc_pin_init(init: impl PinInit<T>) -> Result<DLArc<T>, kernel::error::Error> {
218         ListArc::pin_init(
219             try_pin_init!(Self {
220                 links <- ListLinksSelfPtr::new(),
221                 wrapped <- init,
222             }),
223             GFP_KERNEL,
224         )
225     }
226 }
227 
228 struct DeliverCode {
229     code: u32,
230     skip: Atomic<bool>,
231     pid: i32,
232 }
233 
234 kernel::list::impl_list_arc_safe! {
235     impl ListArcSafe<0> for DeliverCode { untracked; }
236 }
237 
238 impl DeliverCode {
239     fn new(code: u32, pid: i32) -> Self {
240         Self {
241             code,
242             skip: Atomic::new(false),
243             pid,
244         }
245     }
246 
247     /// Disable this DeliverCode and make it do nothing.
248     ///
249     /// This is used instead of removing it from the work list, since `LinkedList::remove` is
250     /// unsafe, whereas this method is not.
251     fn skip(&self) {
252         self.skip.store(true, Relaxed);
253     }
254 }
255 
256 impl DeliverToRead for DeliverCode {
257     fn do_work(
258         self: DArc<Self>,
259         _thread: &Thread,
260         writer: &mut BinderReturnWriter<'_>,
261     ) -> Result<bool> {
262         if !self.skip.load(Relaxed) {
263             writer.write_code(self.code)?;
264         }
265         Ok(true)
266     }
267 
268     fn cancel(self: DArc<Self>) {
269         if !self.skip.load(Relaxed) {
270             binder_debug!(
271                 pid = self.pid,
272                 DeadTransaction,
273                 "undelivered TRANSACTION_COMPLETE"
274             );
275         }
276     }
277 
278     fn should_sync_wakeup(&self) -> bool {
279         false
280     }
281 
282     fn debug_print(&self, m: &SeqFile, prefix: &str, _tprefix: &str) -> Result {
283         seq_print!(m, "{}", prefix);
284         if self.skip.load(Relaxed) {
285             seq_print!(m, "(skipped) ");
286         }
287         if self.code == defs::BR_TRANSACTION_COMPLETE {
288             seq_print!(m, "transaction complete\n");
289         } else {
290             seq_print!(m, "transaction error: {}\n", self.code);
291         }
292         Ok(())
293     }
294 }
295 
296 fn ptr_align(value: usize) -> Option<usize> {
297     let size = core::mem::size_of::<usize>() - 1;
298     Some(value.checked_add(size)? & !size)
299 }
300 
301 // SAFETY: We call register in `init`.
302 static BINDER_SHRINKER: Shrinker = unsafe { Shrinker::new() };
303 
304 struct BinderModule {
305     _netlink: kernel::net::netlink::Registration,
306 }
307 
308 impl kernel::Module for BinderModule {
309     fn init(_module: &'static kernel::ThisModule) -> Result<Self> {
310         // SAFETY: The module initializer never runs twice, so we only call this once.
311         unsafe { crate::context::CONTEXTS.init() };
312 
313         crate::transaction::TRANSACTION_LOG.init()?;
314         crate::transaction::FAILED_TRANSACTION_LOG.init()?;
315 
316         let netlink = crate::netlink::BINDER_NL_FAMILY.register()?;
317         BINDER_SHRINKER.register(c"android-binder")?;
318 
319         // SAFETY: The module is being loaded, so we can initialize binderfs.
320         unsafe { kernel::error::to_result(binderfs::init_rust_binderfs())? };
321 
322         Ok(Self { _netlink: netlink })
323     }
324 }
325 
326 /// Makes the inner type Sync.
327 #[repr(transparent)]
328 pub struct AssertSync<T>(T);
329 // SAFETY: Used only to insert C bindings types into globals, which is safe.
330 unsafe impl<T> Sync for AssertSync<T> {}
331 
332 /// File operations that rust_binderfs.c can use.
333 #[no_mangle]
334 #[used]
335 pub static rust_binder_fops: AssertSync<kernel::bindings::file_operations> = {
336     let ops = kernel::bindings::file_operations {
337         owner: this_module::<LocalModule>().as_ptr(),
338         poll: Some(rust_binder_poll),
339         unlocked_ioctl: Some(rust_binder_ioctl),
340         compat_ioctl: bindings::compat_ptr_ioctl,
341         mmap: Some(rust_binder_mmap),
342         open: Some(rust_binder_open),
343         release: Some(rust_binder_release),
344         flush: Some(rust_binder_flush),
345         ..pin_init::zeroed()
346     };
347     AssertSync(ops)
348 };
349 
350 /// # Safety
351 /// Only called by binderfs.
352 #[no_mangle]
353 unsafe extern "C" fn rust_binder_new_context(
354     name: *const kernel::ffi::c_char,
355 ) -> *mut kernel::ffi::c_void {
356     // SAFETY: The caller will always provide a valid c string here.
357     let name = unsafe { kernel::str::CStr::from_char_ptr(name) };
358     match Context::new(name) {
359         Ok(ctx) => Arc::into_foreign(ctx),
360         Err(_err) => core::ptr::null_mut(),
361     }
362 }
363 
364 /// # Safety
365 /// Only called by binderfs.
366 #[no_mangle]
367 unsafe extern "C" fn rust_binder_remove_context(device: *mut kernel::ffi::c_void) {
368     if !device.is_null() {
369         // SAFETY: The caller ensures that the `device` pointer came from a previous call to
370         // `rust_binder_new_device`.
371         let ctx = unsafe { Arc::<Context>::from_foreign(device) };
372         ctx.deregister();
373         drop(ctx);
374     }
375 }
376 
377 /// # Safety
378 /// Only called by binderfs.
379 unsafe extern "C" fn rust_binder_open(
380     inode: *mut bindings::inode,
381     file_ptr: *mut bindings::file,
382 ) -> kernel::ffi::c_int {
383     // SAFETY: The `rust_binderfs.c` file ensures that `i_private` is set to a
384     // `struct binder_device`.
385     let device = unsafe { (*inode).i_private } as *const binderfs::binder_device;
386 
387     assert!(!device.is_null());
388 
389     // SAFETY: The `rust_binderfs.c` file ensures that `device->ctx` holds a binder context when
390     // using the rust binder fops.
391     let ctx = unsafe { Arc::<Context>::borrow((*device).ctx) };
392 
393     // SAFETY: The caller provides a valid file pointer to a new `struct file`.
394     let file = unsafe { File::from_raw_file(file_ptr) };
395     let process = match Process::open(ctx, file) {
396         Ok(process) => process,
397         Err(err) => return err.to_errno(),
398     };
399 
400     // SAFETY: This is an `inode` for a newly created binder file.
401     match unsafe { BinderfsProcFile::new(inode, process.task.pid()) } {
402         Ok(Some(file)) => process.inner.lock().binderfs_file = Some(file),
403         Ok(None) => { /* pid already exists */ }
404         Err(err) => return err.to_errno(),
405     }
406 
407     // SAFETY: This file is associated with Rust binder, so we own the `private_data` field.
408     unsafe { (*file_ptr).private_data = process.into_foreign() };
409     0
410 }
411 
412 /// # Safety
413 /// Only called by binderfs.
414 unsafe extern "C" fn rust_binder_release(
415     _inode: *mut bindings::inode,
416     file: *mut bindings::file,
417 ) -> kernel::ffi::c_int {
418     // SAFETY: We previously set `private_data` in `rust_binder_open`.
419     let process = unsafe { Arc::<Process>::from_foreign((*file).private_data) };
420     // SAFETY: The caller ensures that the file is valid.
421     let file = unsafe { File::from_raw_file(file) };
422     Process::release(process, file);
423     0
424 }
425 
426 /// # Safety
427 /// Only called by binderfs.
428 unsafe extern "C" fn rust_binder_ioctl(
429     file: *mut bindings::file,
430     cmd: kernel::ffi::c_uint,
431     arg: kernel::ffi::c_ulong,
432 ) -> kernel::ffi::c_long {
433     // SAFETY: We previously set `private_data` in `rust_binder_open`.
434     let f = unsafe { Arc::<Process>::borrow((*file).private_data) };
435     // SAFETY: The caller ensures that the file is valid.
436     match Process::ioctl(f, unsafe { File::from_raw_file(file) }, cmd, arg) {
437         Ok(()) => 0,
438         Err(err) => err.to_errno() as isize,
439     }
440 }
441 
442 /// # Safety
443 /// Only called by binderfs.
444 unsafe extern "C" fn rust_binder_mmap(
445     file: *mut bindings::file,
446     vma: *mut bindings::vm_area_struct,
447 ) -> kernel::ffi::c_int {
448     // SAFETY: We previously set `private_data` in `rust_binder_open`.
449     let f = unsafe { Arc::<Process>::borrow((*file).private_data) };
450     // SAFETY: The caller ensures that the vma is valid.
451     let area = unsafe { kernel::mm::virt::VmaNew::from_raw(vma) };
452     // SAFETY: The caller ensures that the file is valid.
453     match Process::mmap(f, unsafe { File::from_raw_file(file) }, area) {
454         Ok(()) => 0,
455         Err(err) => err.to_errno(),
456     }
457 }
458 
459 /// # Safety
460 /// Only called by binderfs.
461 unsafe extern "C" fn rust_binder_poll(
462     file: *mut bindings::file,
463     wait: *mut bindings::poll_table_struct,
464 ) -> bindings::__poll_t {
465     // SAFETY: We previously set `private_data` in `rust_binder_open`.
466     let f = unsafe { Arc::<Process>::borrow((*file).private_data) };
467     // SAFETY: The caller ensures that the file is valid.
468     let fileref = unsafe { File::from_raw_file(file) };
469     // SAFETY: The caller ensures that the `PollTable` is valid.
470     match Process::poll(f, fileref, unsafe { PollTable::from_raw(wait) }) {
471         Ok(v) => v,
472         Err(_) => bindings::POLLERR,
473     }
474 }
475 
476 /// # Safety
477 /// Only called by binderfs.
478 unsafe extern "C" fn rust_binder_flush(
479     file: *mut bindings::file,
480     _id: bindings::fl_owner_t,
481 ) -> kernel::ffi::c_int {
482     // SAFETY: We previously set `private_data` in `rust_binder_open`.
483     let f = unsafe { Arc::<Process>::borrow((*file).private_data) };
484     match Process::flush(f) {
485         Ok(()) => 0,
486         Err(err) => err.to_errno(),
487     }
488 }
489 
490 /// # Safety
491 /// Only called by binderfs.
492 #[no_mangle]
493 unsafe extern "C" fn rust_binder_stats_show(
494     ptr: *mut seq_file,
495     _: *mut kernel::ffi::c_void,
496 ) -> kernel::ffi::c_int {
497     // SAFETY: The caller ensures that the pointer is valid and exclusive for the duration in which
498     // this method is called.
499     let m = unsafe { SeqFile::from_raw(ptr) };
500     if let Err(err) = rust_binder_stats_show_impl(m) {
501         seq_print!(m, "failed to generate state: {:?}\n", err);
502     }
503     0
504 }
505 
506 /// # Safety
507 /// Only called by binderfs.
508 #[no_mangle]
509 unsafe extern "C" fn rust_binder_state_show(
510     ptr: *mut seq_file,
511     _: *mut kernel::ffi::c_void,
512 ) -> kernel::ffi::c_int {
513     // SAFETY: The caller ensures that the pointer is valid and exclusive for the duration in which
514     // this method is called.
515     let m = unsafe { SeqFile::from_raw(ptr) };
516     if let Err(err) = rust_binder_state_show_impl(m) {
517         seq_print!(m, "failed to generate state: {:?}\n", err);
518     }
519     0
520 }
521 
522 /// # Safety
523 /// Only called by binderfs.
524 #[no_mangle]
525 unsafe extern "C" fn rust_binder_proc_show(
526     ptr: *mut seq_file,
527     _: *mut kernel::ffi::c_void,
528 ) -> kernel::ffi::c_int {
529     // SAFETY: Accessing the private field of `seq_file` is okay.
530     let pid = unsafe { (*ptr).private }.addr() as Pid;
531     // SAFETY: The caller ensures that the pointer is valid and exclusive for the duration in which
532     // this method is called.
533     let m = unsafe { SeqFile::from_raw(ptr) };
534     if let Err(err) = rust_binder_proc_show_impl(m, pid) {
535         seq_print!(m, "failed to generate state: {:?}\n", err);
536     }
537     0
538 }
539 
540 /// # Safety
541 /// Only called by binderfs.
542 #[no_mangle]
543 unsafe extern "C" fn rust_binder_transactions_show(
544     ptr: *mut seq_file,
545     _: *mut kernel::ffi::c_void,
546 ) -> kernel::ffi::c_int {
547     // SAFETY: The caller ensures that the pointer is valid and exclusive for the duration in which
548     // this method is called.
549     let m = unsafe { SeqFile::from_raw(ptr) };
550     if let Err(err) = rust_binder_transactions_show_impl(m) {
551         seq_print!(m, "failed to generate state: {:?}\n", err);
552     }
553     0
554 }
555 
556 /// # Safety
557 /// Only called by binderfs.
558 #[no_mangle]
559 unsafe extern "C" fn rust_binder_transaction_log_show(
560     ptr: *mut seq_file,
561     _: *mut kernel::ffi::c_void,
562 ) -> kernel::ffi::c_int {
563     // SAFETY: Accessing the private field of `seq_file` is okay.
564     let is_failed = !unsafe { (*ptr).private }.is_null();
565     // SAFETY: The caller ensures that the pointer is valid and exclusive for the duration in which
566     // this method is called.
567     let m = unsafe { SeqFile::from_raw(ptr) };
568     let log = if is_failed {
569         &transaction::FAILED_TRANSACTION_LOG
570     } else {
571         &transaction::TRANSACTION_LOG
572     };
573     log.debug_print(m);
574     0
575 }
576 
577 fn rust_binder_transactions_show_impl(m: &SeqFile) -> Result {
578     seq_print!(m, "binder transactions:\n");
579     let contexts = context::get_all_contexts()?;
580     for ctx in contexts {
581         let procs = ctx.get_all_procs()?;
582         for proc in procs {
583             proc.debug_print(m, &ctx, false)?;
584             seq_print!(m, "\n");
585         }
586     }
587     Ok(())
588 }
589 
590 fn rust_binder_stats_show_impl(m: &SeqFile) -> Result {
591     seq_print!(m, "binder stats:\n");
592     stats::GLOBAL_STATS.debug_print("", m);
593     let contexts = context::get_all_contexts()?;
594     for ctx in contexts {
595         let procs = ctx.get_all_procs()?;
596         for proc in procs {
597             proc.debug_print_stats(m, &ctx)?;
598             seq_print!(m, "\n");
599         }
600     }
601     Ok(())
602 }
603 
604 fn rust_binder_state_show_impl(m: &SeqFile) -> Result {
605     seq_print!(m, "binder state:\n");
606     let contexts = context::get_all_contexts()?;
607     for ctx in contexts {
608         let procs = ctx.get_all_procs()?;
609         for proc in procs {
610             proc.debug_print(m, &ctx, true)?;
611             seq_print!(m, "\n");
612         }
613     }
614     Ok(())
615 }
616 
617 fn rust_binder_proc_show_impl(m: &SeqFile, pid: Pid) -> Result {
618     seq_print!(m, "binder proc state:\n");
619     let contexts = context::get_all_contexts()?;
620     for ctx in contexts {
621         let procs = ctx.get_procs_with_pid(pid)?;
622         for proc in procs {
623             proc.debug_print(m, &ctx, true)?;
624             seq_print!(m, "\n");
625         }
626     }
627     Ok(())
628 }
629 
630 struct BinderfsProcFile(NonNull<bindings::dentry>);
631 
632 // SAFETY: Safe to drop any thread.
633 unsafe impl Send for BinderfsProcFile {}
634 
635 impl BinderfsProcFile {
636     /// # Safety
637     ///
638     /// Takes an inode from a newly created binder file.
639     unsafe fn new(nodp: *mut bindings::inode, pid: i32) -> Result<Option<Self>> {
640         // SAFETY: The caller passes an `inode` for a newly created binder file.
641         let dentry = unsafe { binderfs::rust_binderfs_create_proc_file(nodp, pid) };
642         match kernel::error::from_err_ptr(dentry) {
643             Ok(dentry) => Ok(NonNull::new(dentry).map(Self)),
644             Err(err) if err == EEXIST => Ok(None),
645             Err(err) => Err(err),
646         }
647     }
648 }
649 
650 impl Drop for BinderfsProcFile {
651     fn drop(&mut self) {
652         // SAFETY: This is a dentry from `rust_binderfs_remove_file` that has not been deleted yet.
653         unsafe { binderfs::rust_binderfs_remove_file(self.0.as_ptr()) };
654     }
655 }
656