xref: /linux/drivers/android/binder/thread.rs (revision c16ce856e422e73a54c41131e0332de1afe09b8b)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 // Copyright (C) 2025 Google LLC.
4 
5 //! This module defines the `Thread` type, which represents a userspace thread that is using
6 //! binder.
7 //!
8 //! The `Process` object stores all of the threads in an rb tree.
9 
10 use kernel::{
11     bindings,
12     bits::bit_u32,
13     fs::LocalFile,
14     list::{AtomicTracker, List, ListArc, ListLinks, TryNewListArc},
15     prelude::*,
16     security,
17     seq_file::SeqFile,
18     seq_print,
19     sync::atomic::{ordering::Relaxed, Atomic},
20     sync::{aref::ARef, Arc, CondVar, SpinLock},
21     task::Task,
22     uaccess::{UserPtr, UserSlice, UserSliceReader},
23     uapi,
24 };
25 
26 use crate::{
27     allocation::{Allocation, AllocationView, BinderObject, BinderObjectRef, NewAllocation},
28     defs::*,
29     error::BinderResult,
30     process::{GetWorkOrRegister, Process},
31     ptr_align,
32     stats::GLOBAL_STATS,
33     transaction::{Transaction, TransactionFlag, TransactionFlags, TransactionInfo},
34     BinderReturnWriter, DArc, DLArc, DTRWrap, DeliverCode, DeliverToRead,
35 };
36 
37 use core::mem::size_of;
38 
39 fn is_aligned(value: usize, to: usize) -> bool {
40     value % to == 0
41 }
42 
43 /// Stores the layout of the scatter-gather entries. This is used during the `translate_objects`
44 /// call and is discarded when it returns.
45 struct ScatterGatherState {
46     /// A struct that tracks the amount of unused buffer space.
47     unused_buffer_space: UnusedBufferSpace,
48     /// Scatter-gather entries to copy.
49     sg_entries: KVec<ScatterGatherEntry>,
50     /// Indexes into `sg_entries` corresponding to the last binder_buffer_object that
51     /// was processed and all of its ancestors. The array is in sorted order.
52     ancestors: KVec<usize>,
53 }
54 
55 /// This entry specifies an additional buffer that should be copied using the scatter-gather
56 /// mechanism.
57 struct ScatterGatherEntry {
58     /// The index in the offset array of the BINDER_TYPE_PTR that this entry originates from.
59     obj_index: usize,
60     /// Offset in target buffer.
61     offset: usize,
62     /// User address in source buffer.
63     sender_uaddr: usize,
64     /// Number of bytes to copy.
65     length: usize,
66     /// The minimum offset of the next fixup in this buffer.
67     fixup_min_offset: usize,
68     /// The offsets within this buffer that contain pointers which should be translated.
69     pointer_fixups: KVec<PointerFixupEntry>,
70 }
71 
72 /// This entry specifies that a fixup should happen at `target_offset` of the
73 /// buffer.
74 enum PointerFixupEntry {
75     /// A fixup for a `binder_buffer_object`.
76     Fixup {
77         /// The translated pointer to write.
78         pointer_value: u64,
79         /// The offset at which the value should be written. The offset is relative
80         /// to the original buffer.
81         target_offset: usize,
82     },
83     /// A skip for a `binder_fd_array_object`.
84     Skip {
85         /// The number of bytes to skip.
86         skip: usize,
87         /// The offset at which the skip should happen. The offset is relative
88         /// to the original buffer.
89         target_offset: usize,
90     },
91 }
92 
93 /// Return type of `apply_and_validate_fixup_in_parent`.
94 struct ParentFixupInfo {
95     /// The index of the parent buffer in `sg_entries`.
96     parent_sg_index: usize,
97     /// The number of ancestors of the buffer.
98     ///
99     /// The buffer is considered an ancestor of itself, so this is always at
100     /// least one.
101     num_ancestors: usize,
102     /// New value of `fixup_min_offset` if this fixup is applied.
103     new_min_offset: usize,
104     /// The offset of the fixup in the target buffer.
105     target_offset: usize,
106 }
107 
108 impl ScatterGatherState {
109     /// Called when a `binder_buffer_object` or `binder_fd_array_object` tries
110     /// to access a region in its parent buffer. These accesses have various
111     /// restrictions, which this method verifies.
112     ///
113     /// The `parent_offset` and `length` arguments describe the offset and
114     /// length of the access in the parent buffer.
115     ///
116     /// # Detailed restrictions
117     ///
118     /// Obviously the fixup must be in-bounds for the parent buffer.
119     ///
120     /// For safety reasons, we only allow fixups inside a buffer to happen
121     /// at increasing offsets; additionally, we only allow fixup on the last
122     /// buffer object that was verified, or one of its parents.
123     ///
124     /// Example of what is allowed:
125     ///
126     /// A
127     ///   B (parent = A, offset = 0)
128     ///   C (parent = A, offset = 16)
129     ///     D (parent = C, offset = 0)
130     ///   E (parent = A, offset = 32) // min_offset is 16 (C.parent_offset)
131     ///
132     /// Examples of what is not allowed:
133     ///
134     /// Decreasing offsets within the same parent:
135     /// A
136     ///   C (parent = A, offset = 16)
137     ///   B (parent = A, offset = 0) // decreasing offset within A
138     ///
139     /// Arcerring to a parent that wasn't the last object or any of its parents:
140     /// A
141     ///   B (parent = A, offset = 0)
142     ///   C (parent = A, offset = 0)
143     ///   C (parent = A, offset = 16)
144     ///     D (parent = B, offset = 0) // B is not A or any of A's parents
145     fn validate_parent_fixup(
146         &self,
147         parent: usize,
148         parent_offset: usize,
149         length: usize,
150     ) -> Result<ParentFixupInfo> {
151         // Using `position` would also be correct, but `rposition` avoids
152         // quadratic running times.
153         let ancestors_i = self
154             .ancestors
155             .iter()
156             .copied()
157             .rposition(|sg_idx| self.sg_entries[sg_idx].obj_index == parent)
158             .ok_or(EINVAL)?;
159         let sg_idx = self.ancestors[ancestors_i];
160         let sg_entry = match self.sg_entries.get(sg_idx) {
161             Some(sg_entry) => sg_entry,
162             None => {
163                 pr_err!(
164                     "self.ancestors[{}] is {}, but self.sg_entries.len() is {}",
165                     ancestors_i,
166                     sg_idx,
167                     self.sg_entries.len()
168                 );
169                 return Err(EINVAL);
170             }
171         };
172         if sg_entry.fixup_min_offset > parent_offset {
173             pr_warn!(
174                 "validate_parent_fixup: fixup_min_offset={}, parent_offset={}",
175                 sg_entry.fixup_min_offset,
176                 parent_offset
177             );
178             return Err(EINVAL);
179         }
180         let new_min_offset = parent_offset.checked_add(length).ok_or(EINVAL)?;
181         if new_min_offset > sg_entry.length {
182             pr_warn!(
183                 "validate_parent_fixup: new_min_offset={}, sg_entry.length={}",
184                 new_min_offset,
185                 sg_entry.length
186             );
187             return Err(EINVAL);
188         }
189         let target_offset = sg_entry.offset.checked_add(parent_offset).ok_or(EINVAL)?;
190         // The `ancestors_i + 1` operation can't overflow since the output of the addition is at
191         // most `self.ancestors.len()`, which also fits in a usize.
192         Ok(ParentFixupInfo {
193             parent_sg_index: sg_idx,
194             num_ancestors: ancestors_i + 1,
195             new_min_offset,
196             target_offset,
197         })
198     }
199 }
200 
201 /// Keeps track of how much unused buffer space is left. The initial amount is the number of bytes
202 /// requested by the user using the `buffers_size` field of `binder_transaction_data_sg`. Each time
203 /// we translate an object of type `BINDER_TYPE_PTR`, some of the unused buffer space is consumed.
204 struct UnusedBufferSpace {
205     /// The start of the remaining space.
206     offset: usize,
207     /// The end of the remaining space.
208     limit: usize,
209 }
210 impl UnusedBufferSpace {
211     /// Claim the next `size` bytes from the unused buffer space. The offset for the claimed chunk
212     /// into the buffer is returned.
213     fn claim_next(&mut self, size: usize) -> Result<usize> {
214         // We require every chunk to be aligned.
215         let size = ptr_align(size).ok_or(EINVAL)?;
216         let new_offset = self.offset.checked_add(size).ok_or(EINVAL)?;
217 
218         if new_offset <= self.limit {
219             let offset = self.offset;
220             self.offset = new_offset;
221             Ok(offset)
222         } else {
223             Err(EINVAL)
224         }
225     }
226 }
227 
228 #[must_use]
229 pub(crate) enum PushWorkRes {
230     Ok,
231     OkNotifyPoll,
232     FailedDead(DLArc<dyn DeliverToRead>),
233 }
234 
235 impl PushWorkRes {
236     fn is_ok(&self) -> bool {
237         match self {
238             PushWorkRes::Ok => true,
239             PushWorkRes::OkNotifyPoll => true,
240             PushWorkRes::FailedDead(_) => false,
241         }
242     }
243 }
244 
245 /// The fields of `Thread` protected by the spinlock.
246 struct InnerThread {
247     /// Determines the looper state of the thread. It is a bit-wise combination of the constants
248     /// prefixed with `LOOPER_`.
249     looper_flags: LooperFlags,
250 
251     /// Determines whether the looper should return.
252     looper_need_return: bool,
253 
254     /// Determines if thread is dead.
255     is_dead: bool,
256 
257     /// Work item used to deliver error codes to the thread that started a transaction. Stored here
258     /// so that it can be reused.
259     reply_work: DArc<ThreadError>,
260 
261     /// Work item used to deliver error codes to the current thread. Stored here so that it can be
262     /// reused.
263     return_work: DArc<ThreadError>,
264 
265     /// Determines whether the work list below should be processed. When set to false, `work_list`
266     /// is treated as if it were empty.
267     process_work_list: bool,
268     /// List of work items to deliver to userspace.
269     work_list: List<DTRWrap<dyn DeliverToRead>>,
270     current_transaction: Option<DArc<Transaction>>,
271 
272     /// Extended error information for this thread.
273     extended_error: ExtendedError,
274 }
275 
276 kernel::impl_flags!(
277     /// Represents multiple looper flags.
278     #[derive(Debug, Clone, Default, Copy, PartialEq, Eq)]
279     pub struct LooperFlags(u32);
280 
281     /// Represents a single looper flag.
282     #[derive(Debug, Clone, Copy, PartialEq, Eq)]
283     pub enum LooperFlag {
284         Registered = bit_u32(0),
285         Entered = bit_u32(1),
286         Exited = bit_u32(2),
287         Invalid = bit_u32(3),
288         Waiting = bit_u32(4),
289         WaitingProc = bit_u32(5),
290         Poll = bit_u32(6),
291     }
292 );
293 
294 impl InnerThread {
295     fn new(pid: i32) -> Result<Self> {
296         fn next_err_id() -> u32 {
297             static EE_ID: Atomic<u32> = Atomic::new(0);
298             EE_ID.fetch_add(1, Relaxed)
299         }
300 
301         Ok(Self {
302             looper_flags: LooperFlags::default(),
303             looper_need_return: false,
304             is_dead: false,
305             process_work_list: false,
306             reply_work: ThreadError::try_new(pid)?,
307             return_work: ThreadError::try_new(pid)?,
308             work_list: List::new(),
309             current_transaction: None,
310             extended_error: ExtendedError::new(next_err_id(), BR_OK, 0),
311         })
312     }
313 
314     fn pop_work(&mut self) -> Option<DLArc<dyn DeliverToRead>> {
315         if !self.process_work_list {
316             return None;
317         }
318 
319         let ret = self.work_list.pop_front();
320         self.process_work_list = !self.work_list.is_empty();
321         ret
322     }
323 
324     fn push_work(&mut self, work: DLArc<dyn DeliverToRead>) -> PushWorkRes {
325         if self.is_dead {
326             return PushWorkRes::FailedDead(work);
327         }
328         self.work_list.push_back(work);
329         self.process_work_list = true;
330         if self.looper_flags.contains(LooperFlag::Poll) {
331             PushWorkRes::OkNotifyPoll
332         } else {
333             PushWorkRes::Ok
334         }
335     }
336 
337     fn push_reply_work(&mut self, code: u32) -> PushWorkRes {
338         if let Ok(work) = ListArc::try_from_arc(self.reply_work.clone()) {
339             work.set_error_code(code);
340             self.push_work(work)
341         } else {
342             pr_warn!("Thread reply work is already in use.");
343             PushWorkRes::Ok
344         }
345     }
346 
347     fn push_return_work(&mut self, reply: u32) {
348         if let Ok(work) = ListArc::try_from_arc(self.return_work.clone()) {
349             work.set_error_code(reply);
350             // Not notifying: Reply to current thread.
351             let _ = self.push_work(work);
352         } else {
353             pr_warn!("Thread return work is already in use.");
354         }
355     }
356 
357     /// Used to push work items that do not need to be processed immediately and can wait until the
358     /// thread gets another work item.
359     fn push_work_deferred(&mut self, work: DLArc<dyn DeliverToRead>) {
360         self.work_list.push_back(work);
361     }
362 
363     /// Fetches the transaction this thread can reply to. If the thread has a pending transaction
364     /// (that it could respond to) but it has also issued a transaction, it must first wait for the
365     /// previously-issued transaction to complete.
366     ///
367     /// The `thread` parameter should be the thread containing this `ThreadInner`.
368     fn pop_transaction_to_reply(&mut self, thread: &Thread) -> Result<DArc<Transaction>> {
369         let transaction = self.current_transaction.take().ok_or(EINVAL)?;
370         if core::ptr::eq(thread, transaction.from.as_ref()) {
371             self.current_transaction = Some(transaction);
372             return Err(EINVAL);
373         }
374         // Find a new current transaction for this thread.
375         self.current_transaction = transaction.find_from(thread).cloned();
376         Ok(transaction)
377     }
378 
379     fn pop_transaction_replied(&mut self, transaction: &DArc<Transaction>) -> bool {
380         match self.current_transaction.take() {
381             None => false,
382             Some(old) => {
383                 if !Arc::ptr_eq(transaction, &old) {
384                     self.current_transaction = Some(old);
385                     return false;
386                 }
387                 self.current_transaction = old.clone_next();
388                 true
389             }
390         }
391     }
392 
393     fn looper_enter(&mut self) {
394         self.looper_flags |= LooperFlag::Entered;
395         if self.looper_flags.contains(LooperFlag::Registered) {
396             self.looper_flags |= LooperFlag::Invalid;
397         }
398     }
399 
400     fn looper_register(&mut self, valid: bool) {
401         self.looper_flags |= LooperFlag::Registered;
402         if !valid || self.looper_flags.contains(LooperFlag::Entered) {
403             self.looper_flags |= LooperFlag::Invalid;
404         }
405     }
406 
407     fn looper_exit(&mut self) {
408         self.looper_flags |= LooperFlag::Exited;
409     }
410 
411     /// Determines whether the thread is part of a pool, i.e., if it is a looper.
412     fn is_looper(&self) -> bool {
413         self.looper_flags
414             .contains_any(LooperFlag::Entered | LooperFlag::Registered)
415     }
416 
417     /// Determines whether the thread should attempt to fetch work items from the process queue.
418     /// This is generally case when the thread is registered as a looper and not part of a
419     /// transaction stack. But if there is local work, we want to return to userspace before we
420     /// deliver any remote work.
421     fn should_use_process_work_queue(&self) -> bool {
422         self.current_transaction.is_none() && !self.process_work_list && self.is_looper()
423     }
424 
425     fn poll(&mut self) -> u32 {
426         self.looper_flags |= LooperFlag::Poll;
427         if self.process_work_list || self.looper_need_return {
428             bindings::POLLIN
429         } else {
430             0
431         }
432     }
433 }
434 
435 /// This represents a thread that's used with binder.
436 #[pin_data]
437 pub(crate) struct Thread {
438     pub(crate) id: i32,
439     pub(crate) process: Arc<Process>,
440     pub(crate) task: ARef<Task>,
441     #[pin]
442     inner: SpinLock<InnerThread>,
443     #[pin]
444     work_condvar: CondVar,
445     /// Used to insert this thread into the process' `ready_threads` list.
446     ///
447     /// INVARIANT: May never be used for any other list than the `self.process.ready_threads`.
448     #[pin]
449     links: ListLinks,
450     #[pin]
451     links_track: AtomicTracker,
452 }
453 
454 kernel::list::impl_list_arc_safe! {
455     impl ListArcSafe<0> for Thread {
456         tracked_by links_track: AtomicTracker;
457     }
458 }
459 kernel::list::impl_list_item! {
460     impl ListItem<0> for Thread {
461         using ListLinks { self.links };
462     }
463 }
464 
465 impl Thread {
466     pub(crate) fn new(id: i32, process: Arc<Process>) -> Result<Arc<Self>> {
467         let inner = InnerThread::new(process.task.pid())?;
468 
469         Arc::pin_init(
470             try_pin_init!(Thread {
471                 id,
472                 process,
473                 task: ARef::from(&**kernel::current!()),
474                 inner <- kernel::new_spinlock!(inner, "Thread::inner"),
475                 work_condvar <- kernel::new_condvar!("Thread::work_condvar"),
476                 links <- ListLinks::new(),
477                 links_track <- AtomicTracker::new(),
478             }),
479             GFP_KERNEL,
480         )
481     }
482 
483     #[inline(never)]
484     pub(crate) fn debug_print(self: &Arc<Self>, m: &SeqFile, print_all: bool) -> Result<()> {
485         let inner = self.inner.lock();
486 
487         if print_all || inner.current_transaction.is_some() || !inner.work_list.is_empty() {
488             seq_print!(
489                 m,
490                 "  thread {}: l {:02x} need_return {}\n",
491                 self.id,
492                 u32::from(inner.looper_flags),
493                 inner.looper_need_return,
494             );
495         }
496 
497         let mut t_opt = inner.current_transaction.as_ref();
498         while let Some(t) = t_opt {
499             if Arc::ptr_eq(&t.from, self) {
500                 t.debug_print_inner(m, "    outgoing transaction ");
501                 t_opt = t.from_parent.as_ref();
502             } else if Arc::ptr_eq(&t.to, &self.process) {
503                 t.debug_print_inner(m, "    incoming transaction ");
504                 t_opt = t.find_from(self);
505             } else {
506                 t.debug_print_inner(m, "    bad transaction ");
507                 t_opt = None;
508             }
509         }
510 
511         for work in &inner.work_list {
512             work.debug_print(m, "    ", "    pending transaction ")?;
513         }
514         Ok(())
515     }
516 
517     pub(crate) fn clear_extended_error(&self, debug_id: usize) {
518         self.inner.lock().extended_error = ExtendedError::new(debug_id as u32, BR_OK, 0);
519     }
520 
521     pub(crate) fn get_extended_error(&self, data: UserSlice) -> Result {
522         let mut writer = data.writer();
523         let mut inner = self.inner.lock();
524         let ee = inner.extended_error;
525         inner.extended_error = ExtendedError::new(0, BR_OK, 0);
526         drop(inner);
527         writer.write(&ee)?;
528         Ok(())
529     }
530 
531     pub(crate) fn set_current_transaction(&self, transaction: DArc<Transaction>) {
532         self.inner.lock().current_transaction = Some(transaction);
533     }
534 
535     pub(crate) fn has_current_transaction(&self) -> bool {
536         self.inner.lock().current_transaction.is_some()
537     }
538 
539     /// Attempts to fetch a work item from the thread-local queue. The behaviour if the queue is
540     /// empty depends on `wait`: if it is true, the function waits for some work to be queued (or a
541     /// signal); otherwise it returns indicating that none is available.
542     // #[export_name] is a temporary workaround so that ps output does not become unreadable from
543     // mangled symbol names.
544     #[export_name = "rust_binder_waitlcl"]
545     fn get_work_local(self: &Arc<Self>, wait: bool) -> Result<Option<DLArc<dyn DeliverToRead>>> {
546         {
547             let mut inner = self.inner.lock();
548             if inner.looper_need_return {
549                 return Ok(inner.pop_work());
550             }
551         }
552 
553         // Try once if the caller does not want to wait.
554         if !wait {
555             return self.inner.lock().pop_work().ok_or(EAGAIN).map(Some);
556         }
557 
558         // Loop waiting only on the local queue (i.e., not registering with the process queue).
559         let mut inner = self.inner.lock();
560         loop {
561             if let Some(work) = inner.pop_work() {
562                 return Ok(Some(work));
563             }
564 
565             inner.looper_flags |= LooperFlag::Waiting;
566             let signal_pending = self.work_condvar.wait_interruptible_freezable(&mut inner);
567             inner.looper_flags &= !LooperFlag::Waiting;
568 
569             if signal_pending {
570                 return Err(EINTR);
571             }
572             if inner.looper_need_return {
573                 return Ok(None);
574             }
575         }
576     }
577 
578     /// Attempts to fetch a work item from the thread-local queue, falling back to the process-wide
579     /// queue if none is available locally.
580     ///
581     /// This must only be called when the thread is not participating in a transaction chain. If it
582     /// is, the local version (`get_work_local`) should be used instead.
583     // #[export_name] is a temporary workaround so that ps output does not become unreadable from
584     // mangled symbol names.
585     #[export_name = "rust_binder_wait"]
586     fn get_work(self: &Arc<Self>, wait: bool) -> Result<Option<DLArc<dyn DeliverToRead>>> {
587         // Try to get work from the thread's work queue, using only a local lock.
588         {
589             let mut inner = self.inner.lock();
590             if let Some(work) = inner.pop_work() {
591                 return Ok(Some(work));
592             }
593             if inner.looper_need_return {
594                 drop(inner);
595                 return Ok(self.process.get_work());
596             }
597         }
598 
599         // If the caller doesn't want to wait, try to grab work from the process queue.
600         //
601         // We know nothing will have been queued directly to the thread queue because it is not in
602         // a transaction and it is not in the process' ready list.
603         if !wait {
604             return self.process.get_work().ok_or(EAGAIN).map(Some);
605         }
606 
607         // Get work from the process queue. If none is available, atomically register as ready.
608         let reg = match self.process.get_work_or_register(self) {
609             GetWorkOrRegister::Work(work) => return Ok(Some(work)),
610             GetWorkOrRegister::Register(reg) => reg,
611         };
612 
613         let mut inner = self.inner.lock();
614         loop {
615             if let Some(work) = inner.pop_work() {
616                 return Ok(Some(work));
617             }
618 
619             inner.looper_flags |= LooperFlag::Waiting | LooperFlag::WaitingProc;
620             let signal_pending = self.work_condvar.wait_interruptible_freezable(&mut inner);
621             inner.looper_flags &= !(LooperFlag::Waiting | LooperFlag::WaitingProc);
622 
623             if signal_pending || inner.looper_need_return {
624                 // We need to return now. We need to pull the thread off the list of ready threads
625                 // (by dropping `reg`), then check the state again after it's off the list to
626                 // ensure that something was not queued in the meantime. If something has been
627                 // queued, we just return it (instead of the error).
628                 drop(inner);
629                 drop(reg);
630 
631                 let res = match self.inner.lock().pop_work() {
632                     Some(work) => Ok(Some(work)),
633                     None if signal_pending => Err(EINTR),
634                     None => Ok(None),
635                 };
636                 return res;
637             }
638         }
639     }
640 
641     /// Push the provided work item to be delivered to user space via this thread.
642     ///
643     /// Returns whether the item was successfully pushed. This can only fail if the thread is dead.
644     pub(crate) fn push_work(&self, work: DLArc<dyn DeliverToRead>) -> PushWorkRes {
645         let sync = work.should_sync_wakeup();
646         self.push_work_inner(work, sync)
647     }
648 
649     pub(crate) fn push_work_inner(
650         &self,
651         work: DLArc<dyn DeliverToRead>,
652         sync: bool,
653     ) -> PushWorkRes {
654         let res = self.inner.lock().push_work(work);
655 
656         if res.is_ok() {
657             if sync {
658                 self.work_condvar.notify_sync();
659             } else {
660                 self.work_condvar.notify_one();
661             }
662         }
663 
664         res
665     }
666 
667     /// Attempts to push to given work item to the thread if it's a looper thread (i.e., if it's
668     /// part of a thread pool) and is alive. Otherwise, push the work item to the process instead.
669     pub(crate) fn push_work_if_looper(&self, work: DLArc<dyn DeliverToRead>) -> BinderResult {
670         let mut inner = self.inner.lock();
671         if inner.is_looper() && !inner.is_dead {
672             // Not notifying: Reply to current thread.
673             let _ = inner.push_work(work);
674             Ok(())
675         } else {
676             drop(inner);
677             self.process.push_work(work)
678         }
679     }
680 
681     pub(crate) fn push_work_deferred(&self, work: DLArc<dyn DeliverToRead>) {
682         self.inner.lock().push_work_deferred(work);
683     }
684 
685     pub(crate) fn push_return_work(&self, reply: u32) {
686         self.inner.lock().push_return_work(reply);
687     }
688 
689     fn translate_object(
690         &self,
691         obj_index: usize,
692         offset: usize,
693         object: BinderObjectRef<'_>,
694         view: &mut AllocationView<'_>,
695         allow_fds: bool,
696         sg_state: &mut ScatterGatherState,
697     ) -> BinderResult {
698         match object {
699             BinderObjectRef::Binder(obj) => {
700                 let strong = obj.hdr.type_ == BINDER_TYPE_BINDER;
701                 // SAFETY: `binder` is a `binder_uintptr_t`; any bit pattern is a valid
702                 // representation.
703                 let ptr = unsafe { obj.__bindgen_anon_1.binder };
704                 let cookie = obj.cookie;
705                 let flags = obj.flags;
706                 let node = self
707                     .process
708                     .as_arc_borrow()
709                     .get_node(ptr, cookie, flags, strong, self)?;
710                 security::binder_transfer_binder(&self.process.cred, &view.alloc.process.cred)?;
711                 view.transfer_binder_object(offset, obj, strong, node)?;
712             }
713             BinderObjectRef::Handle(obj) => {
714                 let strong = obj.hdr.type_ == BINDER_TYPE_HANDLE;
715                 // SAFETY: `handle` is a `u32`; any bit pattern is a valid representation.
716                 let handle = unsafe { obj.__bindgen_anon_1.handle };
717                 let node = self.process.get_node_from_handle(handle, strong)?;
718                 security::binder_transfer_binder(&self.process.cred, &view.alloc.process.cred)?;
719                 view.transfer_binder_object(offset, obj, strong, node)?;
720             }
721             BinderObjectRef::Fd(obj) => {
722                 if !allow_fds {
723                     return Err(EPERM.into());
724                 }
725 
726                 // SAFETY: `fd` is a `u32`; any bit pattern is a valid representation.
727                 let fd = unsafe { obj.__bindgen_anon_1.fd };
728                 let file = LocalFile::fget(fd)?;
729                 // SAFETY: The binder driver never calls `fdget_pos` and this code runs from an
730                 // ioctl, so there are no active calls to `fdget_pos` on this thread.
731                 let file = unsafe { LocalFile::assume_no_fdget_pos(file) };
732                 security::binder_transfer_file(
733                     &self.process.cred,
734                     &view.alloc.process.cred,
735                     &file,
736                 )?;
737 
738                 let mut obj_write = BinderFdObject::default();
739                 obj_write.hdr.type_ = BINDER_TYPE_FD;
740                 // This will be overwritten with the actual fd when the transaction is received.
741                 obj_write.__bindgen_anon_1.fd = u32::MAX;
742                 obj_write.cookie = obj.cookie;
743                 view.write::<BinderFdObject>(offset, &obj_write)?;
744 
745                 const FD_FIELD_OFFSET: usize =
746                     core::mem::offset_of!(uapi::binder_fd_object, __bindgen_anon_1.fd);
747 
748                 let field_offset = offset + FD_FIELD_OFFSET;
749                 crate::trace::trace_transaction_fd_send(view.alloc.debug_id, fd, field_offset);
750 
751                 view.alloc.info_add_fd(file, field_offset, false)?;
752             }
753             BinderObjectRef::Ptr(obj) => {
754                 let obj_length = obj.length.try_into().map_err(|_| EINVAL)?;
755                 let alloc_offset = match sg_state.unused_buffer_space.claim_next(obj_length) {
756                     Ok(alloc_offset) => alloc_offset,
757                     Err(err) => {
758                         binder_debug!(
759                             UserError,
760                             "failed to claim space for a BINDER_TYPE_PTR (offset: {}, limit: {}, size: {})",
761                             sg_state.unused_buffer_space.offset,
762                             sg_state.unused_buffer_space.limit,
763                             obj_length
764                         );
765                         return Err(err.into());
766                     }
767                 };
768 
769                 let sg_state_idx = sg_state.sg_entries.len();
770                 sg_state.sg_entries.push(
771                     ScatterGatherEntry {
772                         obj_index,
773                         offset: alloc_offset,
774                         sender_uaddr: obj.buffer as usize,
775                         length: obj_length,
776                         pointer_fixups: KVec::new(),
777                         fixup_min_offset: 0,
778                     },
779                     GFP_KERNEL,
780                 )?;
781 
782                 let buffer_ptr_in_user_space = (view.alloc.ptr + alloc_offset) as u64;
783 
784                 if obj.flags & uapi::BINDER_BUFFER_FLAG_HAS_PARENT == 0 {
785                     sg_state.ancestors.clear();
786                     sg_state.ancestors.push(sg_state_idx, GFP_KERNEL)?;
787                 } else {
788                     // Another buffer also has a pointer to this buffer, and we need to fixup that
789                     // pointer too.
790 
791                     let parent_index = usize::try_from(obj.parent).map_err(|_| EINVAL)?;
792                     let parent_offset = usize::try_from(obj.parent_offset).map_err(|_| EINVAL)?;
793 
794                     let info = sg_state.validate_parent_fixup(
795                         parent_index,
796                         parent_offset,
797                         size_of::<u64>(),
798                     )?;
799 
800                     sg_state.ancestors.truncate(info.num_ancestors);
801                     sg_state.ancestors.push(sg_state_idx, GFP_KERNEL)?;
802 
803                     let parent_entry = match sg_state.sg_entries.get_mut(info.parent_sg_index) {
804                         Some(parent_entry) => parent_entry,
805                         None => {
806                             pr_err!(
807                                 "validate_parent_fixup returned index out of bounds for sg.entries"
808                             );
809                             return Err(EINVAL.into());
810                         }
811                     };
812 
813                     parent_entry.fixup_min_offset = info.new_min_offset;
814                     parent_entry.pointer_fixups.push(
815                         PointerFixupEntry::Fixup {
816                             pointer_value: buffer_ptr_in_user_space,
817                             target_offset: info.target_offset,
818                         },
819                         GFP_KERNEL,
820                     )?;
821                 }
822 
823                 let mut obj_write = BinderBufferObject::default();
824                 obj_write.hdr.type_ = BINDER_TYPE_PTR;
825                 obj_write.flags = obj.flags;
826                 obj_write.buffer = buffer_ptr_in_user_space;
827                 obj_write.length = obj.length;
828                 obj_write.parent = obj.parent;
829                 obj_write.parent_offset = obj.parent_offset;
830                 view.write::<BinderBufferObject>(offset, &obj_write)?;
831             }
832             BinderObjectRef::Fda(obj) => {
833                 if !allow_fds {
834                     return Err(EPERM.into());
835                 }
836                 let parent_index = usize::try_from(obj.parent).map_err(|_| EINVAL)?;
837                 let parent_offset = usize::try_from(obj.parent_offset).map_err(|_| EINVAL)?;
838                 let num_fds = usize::try_from(obj.num_fds).map_err(|_| EINVAL)?;
839                 let fds_len = num_fds.checked_mul(size_of::<u32>()).ok_or(EINVAL)?;
840 
841                 if !is_aligned(parent_offset, size_of::<u32>()) {
842                     binder_debug!(UserError, "FDA parent offset not aligned correctly");
843                     return Err(EINVAL.into());
844                 }
845 
846                 let info = sg_state.validate_parent_fixup(parent_index, parent_offset, fds_len)?;
847                 view.alloc.info_add_fd_reserve(num_fds)?;
848 
849                 sg_state.ancestors.truncate(info.num_ancestors);
850                 let parent_entry = match sg_state.sg_entries.get_mut(info.parent_sg_index) {
851                     Some(parent_entry) => parent_entry,
852                     None => {
853                         pr_err!(
854                             "validate_parent_fixup returned index out of bounds for sg.entries"
855                         );
856                         return Err(EINVAL.into());
857                     }
858                 };
859 
860                 if !is_aligned(parent_entry.sender_uaddr, size_of::<u32>()) {
861                     binder_debug!(UserError, "FDA parent buffer not aligned correctly");
862                     return Err(EINVAL.into());
863                 }
864 
865                 parent_entry.fixup_min_offset = info.new_min_offset;
866                 parent_entry
867                     .pointer_fixups
868                     .push(
869                         PointerFixupEntry::Skip {
870                             skip: fds_len,
871                             target_offset: info.target_offset,
872                         },
873                         GFP_KERNEL,
874                     )
875                     .map_err(|_| ENOMEM)?;
876 
877                 let fda_uaddr = parent_entry
878                     .sender_uaddr
879                     .checked_add(parent_offset)
880                     .ok_or(EINVAL)?;
881 
882                 let mut fda_bytes = KVec::new();
883                 UserSlice::new(UserPtr::from_addr(fda_uaddr as usize), fds_len)
884                     .read_all(&mut fda_bytes, GFP_KERNEL)?;
885 
886                 if fds_len != fda_bytes.len() {
887                     pr_err!("UserSlice::read_all returned wrong length in BINDER_TYPE_FDA");
888                     return Err(EINVAL.into());
889                 }
890 
891                 for i in (0..fds_len).step_by(size_of::<u32>()) {
892                     let fd = {
893                         let mut fd_bytes = [0u8; size_of::<u32>()];
894                         fd_bytes.copy_from_slice(&fda_bytes[i..i + size_of::<u32>()]);
895                         u32::from_ne_bytes(fd_bytes)
896                     };
897 
898                     let file = LocalFile::fget(fd)?;
899                     // SAFETY: The binder driver never calls `fdget_pos` and this code runs from an
900                     // ioctl, so there are no active calls to `fdget_pos` on this thread.
901                     let file = unsafe { LocalFile::assume_no_fdget_pos(file) };
902                     security::binder_transfer_file(
903                         &self.process.cred,
904                         &view.alloc.process.cred,
905                         &file,
906                     )?;
907 
908                     // The `validate_parent_fixup` call ensuers that this addition will not
909                     // overflow.
910                     view.alloc.info_add_fd(file, info.target_offset + i, true)?;
911                 }
912                 drop(fda_bytes);
913 
914                 let mut obj_write = BinderFdArrayObject::default();
915                 obj_write.hdr.type_ = BINDER_TYPE_FDA;
916                 obj_write.num_fds = obj.num_fds;
917                 obj_write.parent = obj.parent;
918                 obj_write.parent_offset = obj.parent_offset;
919                 view.write::<BinderFdArrayObject>(offset, &obj_write)?;
920             }
921         }
922         Ok(())
923     }
924 
925     fn apply_sg(&self, alloc: &mut Allocation, sg_state: &mut ScatterGatherState) -> BinderResult {
926         for sg_entry in &mut sg_state.sg_entries {
927             let mut end_of_previous_fixup = sg_entry.offset;
928             let offset_end = sg_entry.offset.checked_add(sg_entry.length).ok_or(EINVAL)?;
929 
930             let mut reader =
931                 UserSlice::new(UserPtr::from_addr(sg_entry.sender_uaddr), sg_entry.length).reader();
932             for fixup in &mut sg_entry.pointer_fixups {
933                 let (fixup_len, fixup_offset) = match fixup {
934                     PointerFixupEntry::Fixup { target_offset, .. } => {
935                         (size_of::<u64>(), *target_offset)
936                     }
937                     PointerFixupEntry::Skip {
938                         skip,
939                         target_offset,
940                     } => (*skip, *target_offset),
941                 };
942 
943                 let target_offset_end = fixup_offset.checked_add(fixup_len).ok_or(EINVAL)?;
944                 if fixup_offset < end_of_previous_fixup || offset_end < target_offset_end {
945                     binder_debug!(
946                         UserError,
947                         "fixups oob {fixup_offset} {end_of_previous_fixup} {offset_end} {target_offset_end}"
948                     );
949                     return Err(EINVAL.into());
950                 }
951 
952                 let copy_off = end_of_previous_fixup;
953                 let copy_len = fixup_offset - end_of_previous_fixup;
954                 if let Err(err) = alloc.copy_into(&mut reader, copy_off, copy_len) {
955                     binder_debug!(UserError, "failed copying into alloc: {err:?}");
956                     return Err(err.into());
957                 }
958                 if let PointerFixupEntry::Fixup { pointer_value, .. } = fixup {
959                     let res = alloc.write::<u64>(fixup_offset, pointer_value);
960                     if let Err(err) = res {
961                         binder_debug!(UserError, "failed copying ptr into alloc: {err:?}");
962                         return Err(err.into());
963                     }
964                 }
965                 if let Err(err) = reader.skip(fixup_len) {
966                     binder_debug!(
967                         UserError,
968                         "failed skipping {fixup_len} from reader: {err:?}"
969                     );
970                     return Err(err.into());
971                 }
972                 end_of_previous_fixup = target_offset_end;
973             }
974             let copy_off = end_of_previous_fixup;
975             let copy_len = offset_end - end_of_previous_fixup;
976             if let Err(err) = alloc.copy_into(&mut reader, copy_off, copy_len) {
977                 binder_debug!(UserError, "failed copying remainder into alloc: {err:?}");
978                 return Err(err.into());
979             }
980         }
981         Ok(())
982     }
983 
984     /// This method copies the payload of a transaction into the target process.
985     ///
986     /// The resulting payload will have several different components, which will be stored next to
987     /// each other in the allocation. Furthermore, various objects can be embedded in the payload,
988     /// and those objects have to be translated so that they make sense to the target transaction.
989     pub(crate) fn copy_transaction_data(
990         &self,
991         to_process: Arc<Process>,
992         info: &mut TransactionInfo,
993         debug_id: usize,
994         allow_fds: bool,
995         txn_security_ctx_offset: Option<&mut usize>,
996     ) -> BinderResult<NewAllocation> {
997         let mut secctx = if let Some(offset) = txn_security_ctx_offset {
998             let secid = self.process.cred.get_secid();
999             let ctx = match security::SecurityCtx::from_secid(secid) {
1000                 Ok(ctx) => ctx,
1001                 Err(err) => {
1002                     pr_warn!("Failed to get security ctx for id {}: {:?}", secid, err);
1003                     return Err(err.into());
1004                 }
1005             };
1006             Some((offset, ctx))
1007         } else {
1008             None
1009         };
1010 
1011         let data_size = info.data_size;
1012         let aligned_data_size = ptr_align(data_size).ok_or(EINVAL)?;
1013         let offsets_size = info.offsets_size;
1014         let buffers_size = info.buffers_size;
1015         let aligned_secctx_size = match secctx.as_ref() {
1016             Some((_offset, ctx)) => ptr_align(ctx.len()).ok_or(EINVAL)?,
1017             None => 0,
1018         };
1019 
1020         if !is_aligned(offsets_size, size_of::<u64>()) {
1021             return Err(EINVAL.into());
1022         }
1023         if !is_aligned(buffers_size, size_of::<u64>()) {
1024             return Err(EINVAL.into());
1025         }
1026 
1027         // This guarantees that at least `sizeof(usize)` bytes will be allocated.
1028         let len = usize::max(
1029             aligned_data_size
1030                 .checked_add(offsets_size)
1031                 .and_then(|sum| sum.checked_add(buffers_size))
1032                 .and_then(|sum| sum.checked_add(aligned_secctx_size))
1033                 .ok_or(ENOMEM)?,
1034             size_of::<u64>(),
1035         );
1036         let secctx_off = aligned_data_size + offsets_size + buffers_size;
1037         let mut alloc = match to_process.buffer_alloc(debug_id, len, info) {
1038             Ok(alloc) => alloc,
1039             Err(err) => {
1040                 pr_warn!(
1041                     "Failed to allocate buffer. len:{}, is_oneway:{}",
1042                     len,
1043                     info.is_oneway(),
1044                 );
1045                 return Err(err);
1046             }
1047         };
1048 
1049         let mut buffer_reader = UserSlice::new(info.data_ptr, data_size).reader();
1050         let mut end_of_previous_object = 0;
1051         let mut sg_state = None;
1052 
1053         // Copy offsets if there are any.
1054         if offsets_size > 0 {
1055             let mut offsets_reader = UserSlice::new(info.offsets_ptr, offsets_size).reader();
1056 
1057             let offsets_start = aligned_data_size;
1058             let offsets_end = aligned_data_size + offsets_size;
1059 
1060             // This state is used for BINDER_TYPE_PTR objects.
1061             let sg_state = sg_state.insert(ScatterGatherState {
1062                 unused_buffer_space: UnusedBufferSpace {
1063                     offset: offsets_end,
1064                     limit: offsets_end + buffers_size,
1065                 },
1066                 sg_entries: KVec::new(),
1067                 ancestors: KVec::new(),
1068             });
1069 
1070             // Traverse the objects specified.
1071             let mut view = AllocationView::new(&mut alloc, data_size);
1072             for (index, index_offset) in (offsets_start..offsets_end)
1073                 .step_by(size_of::<u64>())
1074                 .enumerate()
1075             {
1076                 let offset = offsets_reader.read::<u64>()?;
1077                 view.alloc.write(index_offset, &offset)?;
1078                 let offset: usize = offset.try_into().map_err(|_| EINVAL)?;
1079 
1080                 if offset < end_of_previous_object || !is_aligned(offset, size_of::<u32>()) {
1081                     binder_debug!(UserError, "got transaction with invalid offset");
1082                     return Err(EINVAL.into());
1083                 }
1084 
1085                 // Copy data between two objects.
1086                 if end_of_previous_object < offset {
1087                     view.copy_into(
1088                         &mut buffer_reader,
1089                         end_of_previous_object,
1090                         offset - end_of_previous_object,
1091                     )?;
1092                 }
1093 
1094                 let mut object = BinderObject::read_from(&mut buffer_reader)?;
1095 
1096                 match self.translate_object(
1097                     index,
1098                     offset,
1099                     object.as_ref(),
1100                     &mut view,
1101                     allow_fds,
1102                     sg_state,
1103                 ) {
1104                     Ok(()) => end_of_previous_object = offset + object.size(),
1105                     Err(err) => {
1106                         binder_debug!(UserError, "error while translating object: {err:?}");
1107                         return Err(err);
1108                     }
1109                 }
1110 
1111                 // Update the indexes containing objects to clean up.
1112                 let offset_after_object = index_offset + size_of::<u64>();
1113                 view.alloc
1114                     .set_info_offsets(offsets_start..offset_after_object);
1115             }
1116         }
1117 
1118         // Copy remaining raw data.
1119         alloc.copy_into(
1120             &mut buffer_reader,
1121             end_of_previous_object,
1122             data_size - end_of_previous_object,
1123         )?;
1124 
1125         if let Some(sg_state) = sg_state.as_mut() {
1126             self.apply_sg(&mut alloc, sg_state)?;
1127         }
1128 
1129         if let Some((off_out, secctx)) = secctx.as_mut() {
1130             if let Err(err) = alloc.write(secctx_off, secctx.as_bytes()) {
1131                 binder_debug!(UserError, "failed to write security context: {err:?}");
1132                 return Err(err.into());
1133             }
1134             **off_out = secctx_off;
1135         }
1136         Ok(alloc)
1137     }
1138 
1139     fn unwind_transaction_stack(self: &Arc<Self>) {
1140         let mut thread = self.clone();
1141         while let Ok(transaction) = {
1142             let mut inner = thread.inner.lock();
1143             inner.pop_transaction_to_reply(thread.as_ref())
1144         } {
1145             binder_debug!(
1146                 DeadTransaction,
1147                 "release transaction {} in, still active",
1148                 transaction.debug_id
1149             );
1150 
1151             let reply = Err(BR_DEAD_REPLY);
1152             if !transaction
1153                 .from
1154                 .deliver_single_reply(reply, &transaction, None)
1155             {
1156                 break;
1157             }
1158 
1159             thread = transaction.from.clone();
1160         }
1161     }
1162 
1163     pub(crate) fn deliver_reply(
1164         &self,
1165         reply: Result<DLArc<Transaction>, u32>,
1166         transaction: &DArc<Transaction>,
1167         extended_error: Option<ExtendedError>,
1168     ) {
1169         if self.deliver_single_reply(reply, transaction, extended_error) {
1170             transaction.from.unwind_transaction_stack();
1171         }
1172     }
1173 
1174     /// Delivers a reply to the thread that started a transaction. The reply can either be a
1175     /// reply-transaction or an error code to be delivered instead.
1176     ///
1177     /// Returns whether the thread is dead. If it is, the caller is expected to unwind the
1178     /// transaction stack by completing transactions for threads that are dead.
1179     fn deliver_single_reply(
1180         &self,
1181         reply: Result<DLArc<Transaction>, u32>,
1182         transaction: &DArc<Transaction>,
1183         extended_error: Option<ExtendedError>,
1184     ) -> bool {
1185         if let Ok(transaction) = &reply {
1186             crate::trace::trace_transaction(true, transaction, Some(&self.task));
1187             transaction.set_outstanding(&mut self.process.inner.lock());
1188         }
1189 
1190         let ret = {
1191             let mut inner = self.inner.lock();
1192             if !inner.pop_transaction_replied(transaction) {
1193                 return false;
1194             }
1195 
1196             if inner.is_dead {
1197                 return true;
1198             }
1199 
1200             if let Some(ee) = extended_error {
1201                 if inner.extended_error.command == BR_OK {
1202                     inner.extended_error = ee;
1203                 }
1204             }
1205 
1206             match reply {
1207                 Ok(work) => inner.push_work(work),
1208                 Err(code) => inner.push_reply_work(code),
1209             }
1210         };
1211 
1212         // Notify the thread now that we've released the inner lock.
1213         self.work_condvar.notify_sync();
1214         if matches!(ret, PushWorkRes::OkNotifyPoll) {
1215             self.process.notify_poll(true);
1216         }
1217         false
1218     }
1219 
1220     /// Determines if the given transaction is the current transaction for this thread.
1221     fn is_current_transaction(&self, transaction: &DArc<Transaction>) -> bool {
1222         let inner = self.inner.lock();
1223         match &inner.current_transaction {
1224             None => false,
1225             Some(current) => Arc::ptr_eq(current, transaction),
1226         }
1227     }
1228 
1229     /// Determines the current top of the transaction stack. It fails if the top is in another
1230     /// thread (i.e., this thread belongs to a stack but it has called another thread). The top is
1231     /// [`None`] if the thread is not currently participating in a transaction stack.
1232     fn top_of_transaction_stack(&self) -> Result<Option<DArc<Transaction>>> {
1233         let inner = self.inner.lock();
1234         if let Some(cur) = &inner.current_transaction {
1235             if core::ptr::eq(self, cur.from.as_ref()) {
1236                 pr_warn!("got new transaction with bad transaction stack");
1237                 return Err(EINVAL);
1238             }
1239             Ok(Some(cur.clone()))
1240         } else {
1241             Ok(None)
1242         }
1243     }
1244 
1245     // No inlining avoids allocating stack space for `BinderTransactionData` for the entire
1246     // duration of `transaction()`.
1247     #[inline(never)]
1248     fn read_transaction_info(
1249         &self,
1250         cmd: u32,
1251         reader: &mut UserSliceReader,
1252         info: &mut TransactionInfo,
1253     ) -> Result<()> {
1254         let td = match cmd {
1255             BC_TRANSACTION | BC_REPLY => {
1256                 reader.read::<BinderTransactionData>()?.with_buffers_size(0)
1257             }
1258             BC_TRANSACTION_SG | BC_REPLY_SG => reader.read::<BinderTransactionDataSg>()?,
1259             _ => return Err(EINVAL),
1260         };
1261 
1262         // SAFETY: Above `read` call initializes all bytes, so this union read is ok.
1263         let trd_data_ptr = unsafe { &td.transaction_data.data.ptr };
1264 
1265         info.is_reply = matches!(cmd, BC_REPLY | BC_REPLY_SG);
1266         info.from_pid = self.process.task.pid();
1267         info.from_tid = self.id;
1268         info.code = td.transaction_data.code;
1269         info.flags = TransactionFlags::from_bits(td.transaction_data.flags);
1270         info.data_ptr = UserPtr::from_addr(trd_data_ptr.buffer as usize);
1271         info.data_size = td.transaction_data.data_size as usize;
1272         info.offsets_ptr = UserPtr::from_addr(trd_data_ptr.offsets as usize);
1273         info.offsets_size = td.transaction_data.offsets_size as usize;
1274         info.buffers_size = td.buffers_size as usize;
1275         // SAFETY: Above `read` call initializes all bytes, so this union read is ok.
1276         info.target_handle = unsafe { td.transaction_data.target.handle };
1277 
1278         info.debug_id = super::next_debug_id();
1279 
1280         Ok(())
1281     }
1282 
1283     #[inline(never)]
1284     fn transaction(self: &Arc<Self>, cmd: u32, reader: &mut UserSliceReader) -> Result<()> {
1285         let mut info = TransactionInfo::zeroed();
1286         self.read_transaction_info(cmd, reader, &mut info)?;
1287 
1288         self.clear_extended_error(info.debug_id);
1289 
1290         let ret = if info.is_reply {
1291             self.reply_inner(&mut info)
1292         } else if info.is_oneway() {
1293             self.oneway_transaction_inner(&mut info)
1294         } else {
1295             self.transaction_inner(&mut info)
1296         };
1297 
1298         if let Err(err) = ret {
1299             self.push_return_work(err.reply);
1300             if err.reply != BR_TRANSACTION_COMPLETE {
1301                 info.reply = err.reply;
1302                 if let Some(source) = &err.source {
1303                     info.errno = source.to_errno();
1304 
1305                     {
1306                         let mut inner = self.inner.lock();
1307                         inner.extended_error =
1308                             ExtendedError::new(info.debug_id as u32, err.reply, source.to_errno());
1309                     }
1310 
1311                     binder_debug!(
1312                         FailedTransaction,
1313                         "transaction {} to {}:{} failed {:?}, code {} size {}-{}",
1314                         if info.is_reply {
1315                             "reply"
1316                         } else if info.is_oneway() {
1317                             "async"
1318                         } else {
1319                             "call"
1320                         },
1321                         info.to_pid,
1322                         info.to_tid,
1323                         err,
1324                         info.code,
1325                         info.data_size,
1326                         info.offsets_size
1327                     );
1328                 }
1329             }
1330         }
1331 
1332         if info.oneway_spam_suspect {
1333             // If this is both a oneway spam suspect and a failure, we report it twice. This is
1334             // useful in case the transaction failed with BR_TRANSACTION_PENDING_FROZEN.
1335             info.report_netlink(BR_ONEWAY_SPAM_SUSPECT, &self.process.ctx);
1336         }
1337         if info.reply != 0 {
1338             info.report_netlink(info.reply, &self.process.ctx);
1339         }
1340 
1341         Ok(())
1342     }
1343 
1344     fn transaction_inner(self: &Arc<Self>, info: &mut TransactionInfo) -> BinderResult {
1345         let node_ref = self.process.get_transaction_node(info.target_handle)?;
1346         info.to_pid = node_ref.node.owner.task.pid();
1347         security::binder_transaction(&self.process.cred, &node_ref.node.owner.cred)?;
1348         // TODO: We need to ensure that there isn't a pending transaction in the work queue. How
1349         // could this happen?
1350         let top = self.top_of_transaction_stack()?;
1351         let list_completion = DTRWrap::arc_try_new(DeliverCode::new(
1352             BR_TRANSACTION_COMPLETE,
1353             self.process.task.pid(),
1354         ))?;
1355         let completion = list_completion.clone_arc();
1356         let transaction = Transaction::new(node_ref, top, self, info)?;
1357 
1358         // Check that the transaction stack hasn't changed while the lock was released, then update
1359         // it with the new transaction.
1360         {
1361             let mut inner = self.inner.lock();
1362             if !transaction.is_stacked_on(&inner.current_transaction) {
1363                 binder_debug!(UserError, "got new transaction with bad transaction stack");
1364                 return Err(EINVAL.into());
1365             }
1366             inner.current_transaction = Some(transaction.clone_arc());
1367             // We push the completion as a deferred work so that we wait for the reply before
1368             // returning to userland.
1369             inner.push_work_deferred(list_completion);
1370         }
1371 
1372         if let Err(e) = transaction.submit(info) {
1373             completion.skip();
1374             // Define `transaction` first to drop it after `inner`.
1375             let transaction;
1376             let mut inner = self.inner.lock();
1377             transaction = inner.current_transaction.take().unwrap();
1378             inner.current_transaction = transaction.clone_next();
1379             Err(e)
1380         } else {
1381             Ok(())
1382         }
1383     }
1384 
1385     fn reply_inner(self: &Arc<Self>, info: &mut TransactionInfo) -> BinderResult {
1386         let orig = match self.inner.lock().pop_transaction_to_reply(self) {
1387             Ok(orig) => orig,
1388             Err(err) => {
1389                 binder_debug!(UserError, "got reply transaction with no transaction stack");
1390                 return Err(err.into());
1391             }
1392         };
1393         if !orig.from.is_current_transaction(&orig) {
1394             binder_debug!(
1395                 UserError,
1396                 "got reply transaction with bad transaction stack"
1397             );
1398             return Err(EINVAL.into());
1399         }
1400 
1401         info.to_tid = orig.from.id;
1402         info.to_pid = orig.from.process.task.pid();
1403 
1404         // We need to complete the transaction even if we cannot complete building the reply.
1405         let out = (|| -> BinderResult<_> {
1406             let completion = DTRWrap::arc_try_new(DeliverCode::new(
1407                 BR_TRANSACTION_COMPLETE,
1408                 self.process.task.pid(),
1409             ))?;
1410             let process = orig.from.process.clone();
1411             let allow_fds = orig.flags.contains(TransactionFlag::AcceptFds);
1412             let reply = Transaction::new_reply(self, process, info, allow_fds)?;
1413             // Not notifying: Reply to current thread.
1414             let _ = self.inner.lock().push_work(completion);
1415             orig.from.deliver_reply(Ok(reply), &orig, None);
1416             Ok(())
1417         })()
1418         .map_err(|mut err| {
1419             // At this point we only return `BR_TRANSACTION_COMPLETE` to the caller, and we must let
1420             // the sender know that the transaction has completed (with an error in this case).
1421 
1422             pr_warn!(
1423                 "{}:{} reply to {} failed: {err:?}",
1424                 info.from_pid,
1425                 info.from_tid,
1426                 info.to_pid
1427             );
1428             let param = err.source.as_ref().map_or(0, |e| e.to_errno());
1429             let ee = ExtendedError::new(info.debug_id as u32, err.reply, param);
1430             orig.from
1431                 .deliver_reply(Err(BR_FAILED_REPLY), &orig, Some(ee));
1432             info.reply = BR_FAILED_REPLY;
1433             err.reply = BR_TRANSACTION_COMPLETE;
1434             err
1435         });
1436 
1437         out
1438     }
1439 
1440     fn oneway_transaction_inner(self: &Arc<Self>, info: &mut TransactionInfo) -> BinderResult {
1441         let node_ref = self.process.get_transaction_node(info.target_handle)?;
1442         info.to_pid = node_ref.node.owner.task.pid();
1443         security::binder_transaction(&self.process.cred, &node_ref.node.owner.cred)?;
1444         let transaction = Transaction::new(node_ref, None, self, info)?;
1445         let code = if self.process.is_oneway_spam_detection_enabled() && info.oneway_spam_suspect {
1446             BR_ONEWAY_SPAM_SUSPECT
1447         } else {
1448             BR_TRANSACTION_COMPLETE
1449         };
1450         let list_completion =
1451             DTRWrap::arc_try_new(DeliverCode::new(code, self.process.task.pid()))?;
1452         let completion = list_completion.clone_arc();
1453         // Not notifying: Reply to current thread.
1454         let _ = self.inner.lock().push_work(list_completion);
1455         match transaction.submit(info) {
1456             Ok(()) => Ok(()),
1457             Err(err) => {
1458                 completion.skip();
1459                 Err(err)
1460             }
1461         }
1462     }
1463 
1464     fn write(self: &Arc<Self>, req: &mut BinderWriteRead) -> Result {
1465         let write_start = req.write_buffer.wrapping_add(req.write_consumed);
1466         let write_len = req.write_size.saturating_sub(req.write_consumed);
1467         let mut reader =
1468             UserSlice::new(UserPtr::from_addr(write_start as usize), write_len as usize).reader();
1469 
1470         while reader.len() >= size_of::<u32>() && self.inner.lock().return_work.is_unused() {
1471             let before = reader.len();
1472             let cmd = reader.read::<u32>()?;
1473             crate::trace::trace_command(cmd);
1474             GLOBAL_STATS.inc_bc(cmd);
1475             self.process.stats.inc_bc(cmd);
1476             match cmd {
1477                 BC_TRANSACTION | BC_TRANSACTION_SG | BC_REPLY | BC_REPLY_SG => {
1478                     self.transaction(cmd, &mut reader)?;
1479                 }
1480                 BC_FREE_BUFFER => {
1481                     let buffer = self.process.buffer_get(reader.read()?);
1482                     if let Some(buffer) = buffer {
1483                         if buffer.looper_need_return_on_free() {
1484                             self.inner.lock().looper_need_return = true;
1485                         }
1486                         drop(buffer);
1487                     }
1488                 }
1489                 BC_INCREFS => {
1490                     self.process
1491                         .as_arc_borrow()
1492                         .update_ref(reader.read()?, true, false)?
1493                 }
1494                 BC_ACQUIRE => {
1495                     self.process
1496                         .as_arc_borrow()
1497                         .update_ref(reader.read()?, true, true)?
1498                 }
1499                 BC_RELEASE => {
1500                     self.process
1501                         .as_arc_borrow()
1502                         .update_ref(reader.read()?, false, true)?
1503                 }
1504                 BC_DECREFS => {
1505                     self.process
1506                         .as_arc_borrow()
1507                         .update_ref(reader.read()?, false, false)?
1508                 }
1509                 BC_INCREFS_DONE => self.process.inc_ref_done(&mut reader, false)?,
1510                 BC_ACQUIRE_DONE => self.process.inc_ref_done(&mut reader, true)?,
1511                 BC_REQUEST_DEATH_NOTIFICATION => self.process.request_death(&mut reader, self)?,
1512                 BC_CLEAR_DEATH_NOTIFICATION => self.process.clear_death(&mut reader, self)?,
1513                 BC_DEAD_BINDER_DONE => self.process.dead_binder_done(reader.read()?, self),
1514                 BC_REGISTER_LOOPER => {
1515                     let valid = self.process.register_thread();
1516                     self.inner.lock().looper_register(valid);
1517                 }
1518                 BC_ENTER_LOOPER => self.inner.lock().looper_enter(),
1519                 BC_EXIT_LOOPER => self.inner.lock().looper_exit(),
1520                 BC_REQUEST_FREEZE_NOTIFICATION => self.process.request_freeze_notif(&mut reader)?,
1521                 BC_CLEAR_FREEZE_NOTIFICATION => self.process.clear_freeze_notif(&mut reader)?,
1522                 BC_FREEZE_NOTIFICATION_DONE => self.process.freeze_notif_done(&mut reader)?,
1523 
1524                 // Fail if given an unknown error code.
1525                 // BC_ATTEMPT_ACQUIRE and BC_ACQUIRE_RESULT are no longer supported.
1526                 _ => return Err(EINVAL),
1527             }
1528             // Update the number of write bytes consumed.
1529             req.write_consumed += (before - reader.len()) as u64;
1530         }
1531 
1532         Ok(())
1533     }
1534 
1535     fn read(self: &Arc<Self>, req: &mut BinderWriteRead, wait: bool) -> Result {
1536         let read_start = req.read_buffer.wrapping_add(req.read_consumed);
1537         let read_len = req.read_size.saturating_sub(req.read_consumed);
1538         let mut writer = BinderReturnWriter::new(
1539             UserSlice::new(UserPtr::from_addr(read_start as usize), read_len as usize).writer(),
1540             self,
1541         );
1542         let (in_pool, has_transaction, thread_todo, use_proc_queue) = {
1543             let inner = self.inner.lock();
1544             (
1545                 inner.is_looper(),
1546                 inner.current_transaction.is_some(),
1547                 !inner.work_list.is_empty(),
1548                 inner.should_use_process_work_queue(),
1549             )
1550         };
1551 
1552         crate::trace::trace_wait_for_work(use_proc_queue, has_transaction, thread_todo);
1553 
1554         let getter = if use_proc_queue {
1555             Self::get_work
1556         } else {
1557             Self::get_work_local
1558         };
1559 
1560         // Reserve some room at the beginning of the read buffer so that we can send a
1561         // BR_SPAWN_LOOPER if we need to.
1562         let mut has_noop_placeholder = false;
1563         if req.read_consumed == 0 {
1564             if let Err(err) = writer.write_code(BR_NOOP) {
1565                 pr_warn!("Failure when writing BR_NOOP at beginning of buffer.");
1566                 return Err(err);
1567             }
1568             has_noop_placeholder = true;
1569         }
1570 
1571         // Loop doing work while there is room in the buffer.
1572         let initial_len = writer.len();
1573         while writer.len() >= size_of::<uapi::binder_transaction_data_secctx>() + 4 {
1574             match getter(self, wait && initial_len == writer.len()) {
1575                 Ok(Some(work)) => match work.into_arc().do_work(self, &mut writer) {
1576                     Ok(true) => {}
1577                     Ok(false) => break,
1578                     Err(err) => {
1579                         return Err(err);
1580                     }
1581                 },
1582                 Ok(None) => {
1583                     break;
1584                 }
1585                 Err(err) => {
1586                     // Propagate the error if we haven't written anything else.
1587                     if err != EINTR && err != EAGAIN {
1588                         pr_warn!("Failure in work getter: {:?}", err);
1589                     }
1590                     if initial_len == writer.len() {
1591                         return Err(err);
1592                     } else {
1593                         break;
1594                     }
1595                 }
1596             }
1597         }
1598 
1599         req.read_consumed += read_len - writer.len() as u64;
1600 
1601         // Write BR_SPAWN_LOOPER if the process needs more threads for its pool.
1602         if has_noop_placeholder && in_pool && self.process.needs_thread() {
1603             let mut writer = UserSlice::new(
1604                 UserPtr::from_addr(req.read_buffer as usize),
1605                 req.read_size as usize,
1606             )
1607             .writer();
1608             writer.write(&BR_SPAWN_LOOPER)?;
1609         }
1610         Ok(())
1611     }
1612 
1613     pub(crate) fn write_read(self: &Arc<Self>, data: UserSlice, wait: bool) -> Result {
1614         let (mut reader, mut writer) = data.reader_writer();
1615         let mut req = reader.read::<BinderWriteRead>()?;
1616 
1617         // Go through the write buffer.
1618         let mut ret = Ok(());
1619         if req.write_size > 0 {
1620             ret = self.write(&mut req);
1621             crate::trace::trace_write_done(ret);
1622             if let Err(err) = ret {
1623                 pr_warn!(
1624                     "Write failure {:?} in pid:{}",
1625                     err,
1626                     self.process.pid_in_current_ns()
1627                 );
1628                 req.read_consumed = 0;
1629                 writer.write(&req)?;
1630                 self.inner.lock().looper_need_return = false;
1631                 return ret;
1632             }
1633         }
1634 
1635         // Go through the work queue.
1636         if req.read_size > 0 {
1637             ret = self.read(&mut req, wait);
1638             crate::trace::trace_read_done(ret);
1639             if ret.is_err() && ret != Err(EINTR) {
1640                 pr_warn!(
1641                     "Read failure {:?} in pid:{}",
1642                     ret,
1643                     self.process.pid_in_current_ns()
1644                 );
1645             }
1646         }
1647 
1648         // Write the request back so that the consumed fields are visible to the caller.
1649         writer.write(&req)?;
1650 
1651         self.inner.lock().looper_need_return = false;
1652 
1653         ret
1654     }
1655 
1656     pub(crate) fn poll(&self) -> Result<(bool, u32)> {
1657         let mut inner = self.inner.lock();
1658         Ok((inner.should_use_process_work_queue(), inner.poll()))
1659     }
1660 
1661     /// Make the call to `get_work` or `get_work_local` return immediately, if any.
1662     pub(crate) fn exit_looper(&self) {
1663         let mut inner = self.inner.lock();
1664         let should_notify = inner.looper_flags.contains(LooperFlag::Waiting);
1665         if should_notify {
1666             inner.looper_need_return = true;
1667         }
1668         drop(inner);
1669 
1670         if should_notify {
1671             self.work_condvar.notify_one();
1672         }
1673     }
1674 
1675     pub(crate) fn release(self: &Arc<Self>) {
1676         self.inner.lock().is_dead = true;
1677 
1678         self.unwind_transaction_stack();
1679 
1680         // Cancel all pending work items.
1681         while let Ok(Some(work)) = self.get_work_local(false) {
1682             work.into_arc().cancel();
1683         }
1684     }
1685 }
1686 
1687 #[pin_data]
1688 struct ThreadError {
1689     error_code: Atomic<u32>,
1690     pid: i32,
1691     #[pin]
1692     links_track: AtomicTracker,
1693 }
1694 
1695 impl ThreadError {
1696     fn try_new(pid: i32) -> Result<DArc<Self>> {
1697         DTRWrap::arc_pin_init(pin_init!(Self {
1698             error_code: Atomic::new(BR_OK),
1699             pid,
1700             links_track <- AtomicTracker::new(),
1701         }))
1702         .map(ListArc::into_arc)
1703     }
1704 
1705     fn set_error_code(&self, code: u32) {
1706         self.error_code.store(code, Relaxed);
1707     }
1708 
1709     fn is_unused(&self) -> bool {
1710         self.error_code.load(Relaxed) == BR_OK
1711     }
1712 }
1713 
1714 impl DeliverToRead for ThreadError {
1715     fn do_work(
1716         self: DArc<Self>,
1717         _thread: &Thread,
1718         writer: &mut BinderReturnWriter<'_>,
1719     ) -> Result<bool> {
1720         let code = self.error_code.load(Relaxed);
1721         self.error_code.store(BR_OK, Relaxed);
1722         writer.write_code(code)?;
1723         Ok(true)
1724     }
1725 
1726     fn cancel(self: DArc<Self>) {
1727         let code = self.error_code.load(Relaxed);
1728         if code != BR_OK {
1729             binder_debug!(
1730                 pid = self.pid,
1731                 DeadTransaction,
1732                 "undelivered TRANSACTION_ERROR: {code}"
1733             );
1734         }
1735     }
1736 
1737     fn should_sync_wakeup(&self) -> bool {
1738         false
1739     }
1740 
1741     fn debug_print(&self, m: &SeqFile, prefix: &str, _tprefix: &str) -> Result<()> {
1742         seq_print!(
1743             m,
1744             "{}transaction error: {}\n",
1745             prefix,
1746             self.error_code.load(Relaxed)
1747         );
1748         Ok(())
1749     }
1750 }
1751 
1752 kernel::list::impl_list_arc_safe! {
1753     impl ListArcSafe<0> for ThreadError {
1754         tracked_by links_track: AtomicTracker;
1755     }
1756 }
1757