summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--sys_util/src/file_flags.rs53
-rw-r--r--sys_util/src/lib.rs2
2 files changed, 55 insertions, 0 deletions
diff --git a/sys_util/src/file_flags.rs b/sys_util/src/file_flags.rs
new file mode 100644
index 0000000..c8a3637
--- /dev/null
+++ b/sys_util/src/file_flags.rs
@@ -0,0 +1,53 @@
+// Copyright 2018 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+use std::os::unix::io::AsRawFd;
+
+use libc::{fcntl, F_GETFL, O_ACCMODE, O_RDONLY, O_WRONLY, O_RDWR, EINVAL};
+
+use {Error, Result, errno_result};
+
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub enum FileFlags {
+    Read,
+    Write,
+    ReadWrite,
+}
+
+impl FileFlags {
+    pub fn from_file(file: &AsRawFd) -> Result<FileFlags> {
+        // Trivially safe because fcntl with the F_GETFL command is totally safe and we check for
+        // error.
+        let flags = unsafe { fcntl(file.as_raw_fd(), F_GETFL) };
+        if flags == -1 {
+            errno_result()
+        } else {
+            match flags & O_ACCMODE {
+                O_RDONLY => Ok(FileFlags::Read),
+                O_WRONLY => Ok(FileFlags::Write),
+                O_RDWR => Ok(FileFlags::ReadWrite),
+                _ => Err(Error::new(EINVAL)),
+            }
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use {pipe, EventFd};
+
+    #[test]
+    fn pipe_pair() {
+        let (read_pipe, write_pipe) = pipe(true).unwrap();
+        assert_eq!(FileFlags::from_file(&read_pipe).unwrap(), FileFlags::Read);
+        assert_eq!(FileFlags::from_file(&write_pipe).unwrap(), FileFlags::Write);
+    }
+
+    #[test]
+    fn eventfd() {
+        let evt = EventFd::new().unwrap();
+        assert_eq!(FileFlags::from_file(&evt).unwrap(), FileFlags::ReadWrite);
+    }
+}
diff --git a/sys_util/src/lib.rs b/sys_util/src/lib.rs
index d9c5825..701622b 100644
--- a/sys_util/src/lib.rs
+++ b/sys_util/src/lib.rs
@@ -32,6 +32,7 @@ mod fork;
 mod signalfd;
 mod sock_ctrl_msg;
 mod passwd;
+mod file_flags;
 
 pub use mmap::*;
 pub use shm::*;
@@ -51,6 +52,7 @@ pub use ioctl::*;
 pub use sock_ctrl_msg::*;
 pub use passwd::*;
 pub use poll_token_derive::*;
+pub use file_flags::*;
 
 pub use mmap::Error as MmapError;
 pub use guest_memory::Error as GuestMemoryError;