error.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // SPDX-License-Identifier: GPL-2.0
  2. // Copyright (C) 2025 Google LLC.
  3. use kernel::fmt;
  4. use kernel::prelude::*;
  5. use crate::defs::*;
  6. pub(crate) type BinderResult<T = ()> = core::result::Result<T, BinderError>;
  7. /// An error that will be returned to userspace via the `BINDER_WRITE_READ` ioctl rather than via
  8. /// errno.
  9. pub(crate) struct BinderError {
  10. pub(crate) reply: u32,
  11. source: Option<Error>,
  12. }
  13. impl BinderError {
  14. pub(crate) fn new_dead() -> Self {
  15. Self {
  16. reply: BR_DEAD_REPLY,
  17. source: None,
  18. }
  19. }
  20. pub(crate) fn new_frozen() -> Self {
  21. Self {
  22. reply: BR_FROZEN_REPLY,
  23. source: None,
  24. }
  25. }
  26. pub(crate) fn new_frozen_oneway() -> Self {
  27. Self {
  28. reply: BR_TRANSACTION_PENDING_FROZEN,
  29. source: None,
  30. }
  31. }
  32. pub(crate) fn is_dead(&self) -> bool {
  33. self.reply == BR_DEAD_REPLY
  34. }
  35. pub(crate) fn as_errno(&self) -> kernel::ffi::c_int {
  36. self.source.unwrap_or(EINVAL).to_errno()
  37. }
  38. pub(crate) fn should_pr_warn(&self) -> bool {
  39. self.source.is_some()
  40. }
  41. }
  42. /// Convert an errno into a `BinderError` and store the errno used to construct it. The errno
  43. /// should be stored as the thread's extended error when given to userspace.
  44. impl From<Error> for BinderError {
  45. fn from(source: Error) -> Self {
  46. Self {
  47. reply: BR_FAILED_REPLY,
  48. source: Some(source),
  49. }
  50. }
  51. }
  52. impl From<kernel::fs::file::BadFdError> for BinderError {
  53. fn from(source: kernel::fs::file::BadFdError) -> Self {
  54. BinderError::from(Error::from(source))
  55. }
  56. }
  57. impl From<kernel::alloc::AllocError> for BinderError {
  58. fn from(_: kernel::alloc::AllocError) -> Self {
  59. Self {
  60. reply: BR_FAILED_REPLY,
  61. source: Some(ENOMEM),
  62. }
  63. }
  64. }
  65. impl fmt::Debug for BinderError {
  66. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  67. match self.reply {
  68. BR_FAILED_REPLY => match self.source.as_ref() {
  69. Some(source) => f
  70. .debug_struct("BR_FAILED_REPLY")
  71. .field("source", source)
  72. .finish(),
  73. None => f.pad("BR_FAILED_REPLY"),
  74. },
  75. BR_DEAD_REPLY => f.pad("BR_DEAD_REPLY"),
  76. BR_FROZEN_REPLY => f.pad("BR_FROZEN_REPLY"),
  77. BR_TRANSACTION_PENDING_FROZEN => f.pad("BR_TRANSACTION_PENDING_FROZEN"),
  78. BR_TRANSACTION_COMPLETE => f.pad("BR_TRANSACTION_COMPLETE"),
  79. _ => f
  80. .debug_struct("BinderError")
  81. .field("reply", &self.reply)
  82. .finish(),
  83. }
  84. }
  85. }