Skip to content

Commit 4971c51

Browse files
authored
Fix Mode::from_raw_mode to mask out the S_IFMT bits. (#1124)
The `S_IFMT` bits in a `st_mode` field value hold the file type; mask them out when converting the value to a `Mode`. `Mode` can tolerate bits it doesn't recognize, however this does prevent it from being compared for equality in the obvious way. Fixes #1104.
1 parent 3b8ffeb commit 4971c51

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

src/backend/libc/fs/types.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ impl Mode {
162162
/// `Mode`.
163163
#[inline]
164164
pub const fn from_raw_mode(st_mode: RawMode) -> Self {
165-
Self::from_bits_truncate(st_mode)
165+
Self::from_bits_truncate(st_mode & !c::S_IFMT as RawMode)
166166
}
167167

168168
/// Construct an `st_mode` value from a `Mode`.

src/backend/linux_raw/fs/types.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ impl Mode {
130130
/// `Mode`.
131131
#[inline]
132132
pub const fn from_raw_mode(st_mode: RawMode) -> Self {
133-
Self::from_bits_truncate(st_mode)
133+
Self::from_bits_truncate(st_mode & !linux_raw_sys::general::S_IFMT)
134134
}
135135

136136
/// Construct an `st_mode` value from a `Mode`.

tests/fs/file.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,3 +185,16 @@ fn test_setfl_append() {
185185
assert_eq!(rustix::io::read(&file, &mut buf), Ok(19));
186186
assert_eq!(&buf, b"uvwdefghijklmnopxyz\0\0\0\0\0\0\0\0\0\0\0\0\0");
187187
}
188+
189+
#[test]
190+
fn test_mode() {
191+
use rustix::fs::{Mode, RawMode};
192+
193+
let mode = Mode::from_raw_mode((libc::S_IFSOCK | libc::S_IRUSR) as RawMode);
194+
assert_eq!(mode, Mode::RUSR);
195+
assert_eq!(mode.bits(), libc::S_IRUSR as RawMode);
196+
197+
let mode = Mode::from_raw_mode((libc::S_IFSOCK | libc::S_IRWXU) as RawMode);
198+
assert_eq!(mode, Mode::RWXU);
199+
assert_eq!(mode.bits(), libc::S_IRWXU as RawMode);
200+
}

0 commit comments

Comments
 (0)