Skip to content

Commit

Permalink
SigSet: A new unsafe helper method to create a SigSet from a sigset_t
Browse files Browse the repository at this point in the history
Currently,  the only way to create a `SigSet` from a `sigset_t` object
is by using pointer casts, like:

```
unsafe {
    let sigset = *(&sigset as *const libc::sigset_t as *const SigSet)
};
```

This is un-ergonomic for library creators with interfaces to C.
So, let's add a new unsafe method that creates a SigSet from a sigset_t
object.

We can't implement `From` since converting from sigset_t to
SigSet is unsafe because objects of type sigset_t must be initialized
by calling either sigemptyset(3) or sigfillset(3) before being used.
In other case, the results are undefined.
Ee cannot implement `TryFrom` either, because there is no way to check
if an object of type sigset_t is initialized.

Signed-off-by: German Maglione <gmaglione@redhat.com>
  • Loading branch information
germag committed Jun 8, 2022
1 parent 5dedbc7 commit 57c79cb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).
(#[1703](https://github.com/nix-rust/nix/pull/1703))
- Added `ptrace::read_user` and `ptrace::write_user` for Linux.
(#[1697](https://github.com/nix-rust/nix/pull/1697))
- Added `from_sigset_t_unchecked()` to `signal::SigSet`.

### Changed

Expand Down
25 changes: 25 additions & 0 deletions src/sys/signal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,13 @@ impl SigSet {
Signal::try_from(signum.assume_init()).unwrap()
})
}

/// Converts a sigset_t object to a SigSet without checking whether the sigset_t is already
/// initialized. Objects of type sigset_t must be initialized by calling either sigemptyset(3)
/// or sigfillset(3) before being used. In other case, the results are undefined.
pub unsafe fn from_sigset_t_unchecked(sigset: libc::sigset_t) -> SigSet {
SigSet { sigset }
}
}

impl AsRef<libc::sigset_t> for SigSet {
Expand Down Expand Up @@ -1344,4 +1351,22 @@ mod tests {
assert_eq!(mask.wait().unwrap(), SIGUSR1);
}).join().unwrap();
}

#[test]
fn test_from_sigset_t_unchecked() {
let src_set = SigSet::empty();
let set = unsafe { SigSet::from_sigset_t_unchecked(src_set.sigset) };

for signal in Signal::iterator() {
assert!(!set.contains(signal));
}

let src_set = SigSet::all();
let set = unsafe { SigSet::from_sigset_t_unchecked(src_set.sigset) };

for signal in Signal::iterator() {
assert!(set.contains(signal));
}
}

}

0 comments on commit 57c79cb

Please sign in to comment.