Skip to content

Commit 4626b69

Browse files
authored
Document that negative pids aren't UB, but may cause unexpected behavior. (#1443)
As discussed in #1433, allow `Pid` values to be negative without invoking UB, because they can occur on systems configured with seccomp-bpf to make syscalls like `getpid` fail. However, also document that while this doesn't invoke UB, it isn't useful.
1 parent ca41f0a commit 4626b69

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

src/pid.rs

+9-2
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,21 @@ impl Pid {
2727

2828
/// Converts a `RawPid` into a `Pid`.
2929
///
30-
/// Returns `Some` for positive `RawPid`s. Otherwise, returns `None`.
30+
/// Returns `Some` for positive values, and `None` for zero values.
3131
///
3232
/// This is safe because a `Pid` is a number without any guarantees for the
3333
/// kernel. Non-child `Pid`s are always racy for any syscalls, but can only
3434
/// cause logic errors. If you want race-free access to or control of
3535
/// non-child processes, please consider other mechanisms like [pidfd] on
3636
/// Linux.
3737
///
38+
/// Passing a negative number doesn't invoke undefined behavior, but it
39+
/// may cause unexpected behavior.
40+
///
3841
/// [pidfd]: https://man7.org/linux/man-pages/man2/pidfd_open.2.html
3942
#[inline]
4043
pub const fn from_raw(raw: RawPid) -> Option<Self> {
44+
debug_assert!(raw > 0);
4145
match NonZeroI32::new(raw) {
4246
Some(non_zero) => Some(Self(non_zero)),
4347
None => None,
@@ -46,9 +50,12 @@ impl Pid {
4650

4751
/// Converts a known positive `RawPid` into a `Pid`.
4852
///
53+
/// Passing a negative number doesn't invoke undefined behavior, but it
54+
/// may cause unexpected behavior.
55+
///
4956
/// # Safety
5057
///
51-
/// The caller must guarantee `raw` is positive.
58+
/// The caller must guarantee `raw` is non-zero.
5259
#[inline]
5360
pub const unsafe fn from_raw_unchecked(raw: RawPid) -> Self {
5461
debug_assert!(raw > 0);

0 commit comments

Comments
 (0)