thread.rs 61 KB

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