linux-gpio.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: Erik Wierich <erik@riscstar.com>
To: Linux-GPIO <linux-gpio@vger.kernel.org>,
	 Bartosz Golaszewski <brgl@bgdev.pl>,
	Viresh Kumar <viresh.kumar@linaro.org>
Cc: Erik Wierich <erik@riscstar.com>
Subject: [PATCH libgpiod 1/2] bindings: rust: mark constructors that take raw pointers unsafe
Date: Mon, 21 Jul 2025 09:41:53 +0200	[thread overview]
Message-ID: <20250721-rust-unsafe-consistency-v1-1-aa1b42ed5983@riscstar.com> (raw)
In-Reply-To: <20250721-rust-unsafe-consistency-v1-0-aa1b42ed5983@riscstar.com>

The functions take raw pointers and expose safe API that operates on
them. Thus, invariants have to be upheld by these constructors to ensure
safe operation of later API.

Signed-off-by: Erik Wierich <erik@riscstar.com>
---
 bindings/rust/libgpiod/src/chip.rs          | 10 ++++++++--
 bindings/rust/libgpiod/src/info_event.rs    |  7 ++++++-
 bindings/rust/libgpiod/src/line_config.rs   |  7 ++++++-
 bindings/rust/libgpiod/src/line_request.rs  |  7 ++++++-
 bindings/rust/libgpiod/src/line_settings.rs | 10 +++++++++-
 5 files changed, 35 insertions(+), 6 deletions(-)

diff --git a/bindings/rust/libgpiod/src/chip.rs b/bindings/rust/libgpiod/src/chip.rs
index bbb962f0390469b3193deec9388b5b56efab07ce..f39beab58363beaebe2ba2dcfb846178b7b595e5 100644
--- a/bindings/rust/libgpiod/src/chip.rs
+++ b/bindings/rust/libgpiod/src/chip.rs
@@ -146,15 +146,18 @@ impl Chip {
         if event.is_null() {
             return Err(Error::OperationFailed(
                 OperationType::ChipReadInfoEvent,
                 errno::errno(),
             ));
         }
 
-        Ok(info::Event::new(event))
+        // SAFETY: `gpiod_chip_read_info_event` returned a standalone `event`
+        // over which we have sole ownership. We won't use the raw pointer
+        // directly after passing it here.
+        Ok(unsafe { info::Event::new(event) })
     }
 
     /// Map a GPIO line's name to its offset within the chip.
     pub fn line_offset_from_name(&self, name: &str) -> Result<Offset> {
         let name = CString::new(name).map_err(|_| Error::InvalidString)?;
 
         // SAFETY: `gpiod_chip` is guaranteed to be valid here.
@@ -191,15 +194,18 @@ impl Chip {
         if request.is_null() {
             return Err(Error::OperationFailed(
                 OperationType::ChipRequestLines,
                 errno::errno(),
             ));
         }
 
-        request::Request::new(request)
+        // SAFETY: `gpiod_chip_request_lines` returned an object over which we
+        // have sole ownership. We never use it again after constructing the
+        // wrapper.
+        unsafe { request::Request::new(request) }
     }
 }
 
 impl Drop for Chip {
     /// Close the chip and release all associated resources.
     fn drop(&mut self) {
         // SAFETY: `gpiod_chip` is guaranteed to be valid here.
diff --git a/bindings/rust/libgpiod/src/info_event.rs b/bindings/rust/libgpiod/src/info_event.rs
index 472c8915a316f6dfdd184ff52e33754c0805f880..e59de89a0507aa224fc5f473f321a0817fe29980 100644
--- a/bindings/rust/libgpiod/src/info_event.rs
+++ b/bindings/rust/libgpiod/src/info_event.rs
@@ -27,15 +27,20 @@ pub struct Event {
 
 // SAFETY: Event models a wrapper around an owned gpiod_info_event and may be
 // safely sent to other threads.
 unsafe impl Send for Event {}
 
 impl Event {
     /// Get a single chip's line's status change event.
-    pub(crate) fn new(event: *mut gpiod::gpiod_info_event) -> Self {
+    ///
+    /// SAFETY: The pointer must point to an instance that is valid. After
+    /// constructing an [Event] the pointer MUST NOT be used for any other
+    /// purpose anymore. All interactions with the libgpiod API have to happen
+    /// through this object.
+    pub(crate) unsafe fn new(event: *mut gpiod::gpiod_info_event) -> Self {
         Self { event }
     }
 
     /// Get the event type of the status change event.
     pub fn event_type(&self) -> Result<InfoChangeKind> {
         // SAFETY: `gpiod_info_event` is guaranteed to be valid here.
         InfoChangeKind::new(unsafe { gpiod::gpiod_info_event_get_event_type(self.event) })
diff --git a/bindings/rust/libgpiod/src/line_config.rs b/bindings/rust/libgpiod/src/line_config.rs
index d0a4abae5ae7e0d5e111cf7778eaf3cd0c07ca53..09a65514748d0a85fb39a3d37a18f19fc9f4af1b 100644
--- a/bindings/rust/libgpiod/src/line_config.rs
+++ b/bindings/rust/libgpiod/src/line_config.rs
@@ -130,15 +130,20 @@ impl Config {
             if settings.is_null() {
                 return Err(Error::OperationFailed(
                     OperationType::LineConfigGetSettings,
                     errno::errno(),
                 ));
             }
 
-            map.insert(*offset as u64, Settings::new_with_settings(settings));
+            // SAFETY: The above `gpiod_line_config_get_line_settings` call
+            // returns a copy of the line_settings. We thus have sole ownership.
+            // We no longer use the pointer for any other purpose.
+            let settings = unsafe { Settings::new_with_settings(settings) };
+
+            map.insert(*offset as u64, settings);
         }
 
         Ok(map)
     }
 }
 
 impl Drop for Config {
diff --git a/bindings/rust/libgpiod/src/line_request.rs b/bindings/rust/libgpiod/src/line_request.rs
index d7b62a1a083ff589aaa4fa3edb1b1269e7aafaf5..c73943da9b42a12b35adf5234c80e62f4c7785a7 100644
--- a/bindings/rust/libgpiod/src/line_request.rs
+++ b/bindings/rust/libgpiod/src/line_request.rs
@@ -23,15 +23,20 @@ pub struct Request {
 
 // SAFETY: Request models a wrapper around an owned gpiod_line_request and may
 // be safely sent to other threads.
 unsafe impl Send for Request {}
 
 impl Request {
     /// Request a set of lines for exclusive usage.
-    pub(crate) fn new(request: *mut gpiod::gpiod_line_request) -> Result<Self> {
+    ///
+    /// SAFETY: The pointer must point to an instance that is valid. After
+    /// constructing a [Request] the pointer MUST NOT be used for any other
+    /// purpose anymore. All interactions with the libgpiod API have to happen
+    /// through this object.
+    pub(crate) unsafe fn new(request: *mut gpiod::gpiod_line_request) -> Result<Self> {
         Ok(Self { request })
     }
 
     /// Get the name of the chip this request was made on.
     #[cfg(feature = "v2_1")]
     pub fn chip_name(&self) -> Result<&str> {
         // SAFETY: The `gpiod_line_request` is guaranteed to be live as long
diff --git a/bindings/rust/libgpiod/src/line_settings.rs b/bindings/rust/libgpiod/src/line_settings.rs
index 7f271c3b7397c81d4d2e15fc8050582306ad2b5b..6445a4756b1f12932e266148a4ac9528c7ac1d06 100644
--- a/bindings/rust/libgpiod/src/line_settings.rs
+++ b/bindings/rust/libgpiod/src/line_settings.rs
@@ -42,15 +42,23 @@ impl Settings {
                 errno::errno(),
             ));
         }
 
         Ok(Self { settings })
     }
 
-    pub(crate) fn new_with_settings(settings: *mut gpiod::gpiod_line_settings) -> Self {
+    /// Converts a owned pointer into an owned instance
+    ///
+    /// Assumes sole ownership over a [gpiod::gpiod_line_settings] instance.
+    ///
+    /// SAFETY: The pointer must point to an instance that is valid. After
+    /// constructing a [Settings] the pointer MUST NOT be used for any other
+    /// purpose anymore. All interactions with the libgpiod API have to happen
+    /// through this object.
+    pub(crate) unsafe fn new_with_settings(settings: *mut gpiod::gpiod_line_settings) -> Self {
         Self { settings }
     }
 
     /// Resets the line settings object to its default values.
     pub fn reset(&mut self) {
         // SAFETY: `gpiod_line_settings` is guaranteed to be valid here.
         unsafe { gpiod::gpiod_line_settings_reset(self.settings) }

-- 
2.50.0


  reply	other threads:[~2025-07-21  7:42 UTC|newest]

Thread overview: 5+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2025-07-21  7:41 [PATCH libgpiod 0/2] bindings: rust: mark raw constructors as unsafe + rename to `from_raw` Erik Wierich
2025-07-21  7:41 ` Erik Wierich [this message]
2025-07-21  7:41 ` [PATCH libgpiod 2/2] bindings: rust: rename constructors that wrap raw objects " Erik Wierich
2025-07-21  7:48 ` [PATCH libgpiod 0/2] bindings: rust: mark raw constructors as unsafe + rename " Viresh Kumar
2025-07-21 13:20 ` Bartosz Golaszewski

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20250721-rust-unsafe-consistency-v1-1-aa1b42ed5983@riscstar.com \
    --to=erik@riscstar.com \
    --cc=brgl@bgdev.pl \
    --cc=linux-gpio@vger.kernel.org \
    --cc=viresh.kumar@linaro.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).