1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
//! # Bindings to `statx` syscall.
//!
//! Note that `statx()` was added to Linux in kernel 4.11 .
//!
//! # See also
//! http://man7.org/linux/man-pages/man2/statx.2.html
#![deny(warnings)]

use libc::syscall;
use libc::{__s32, __u16, __u32, __u64, c_char, c_int, c_long, c_uint};

/// Timestamp structure for the timestamps in struct statx.
///
/// tv_sec holds the number of seconds before (negative) or after (positive)
/// 00:00:00 1st January 1970 UTC.
///
/// tv_nsec holds a number of nanoseconds (0..999,999,999) after the tv_sec time.
///
/// __reserved is held in case we need a yet finer resolution.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct statx_timestamp {
    pub tv_sec: i64,
    pub tc_nsec: __u32,
    pub __reserved: __s32,
}

/// Structures for the extended file attribute retrieval system call
/// (statx()).
///
/// The caller passes a mask of what they're specifically interested in as a
/// parameter to statx().  What statx() actually got will be indicated in
/// st_mask upon return.
///
/// For each bit in the mask argument:
///
/// - if the datum is not supported:
///
///   - the bit will be cleared, and
///
///   - the datum will be set to an appropriate fabricated value if one is
///     available (eg. CIFS can take a default uid and gid), otherwise
///
///   - the field will be cleared;
///
/// - otherwise, if explicitly requested:
///
///   - the datum will be synchronised to the server if AT_STATX_FORCE_SYNC is
///     set or if the datum is considered out of date, and
///
///   - the field will be filled in and the bit will be set;
///
/// - otherwise, if not requested, but available in approximate form without any
///   effort, it will be filled in anyway, and the bit will be set upon return
///   (it might not be up to date, however, and no attempt will be made to
///   synchronise the internal state first);
///
/// - otherwise the field and the bit will be cleared before returning.
///
/// Items in STATX_BASIC_STATS may be marked unavailable on return, but they
/// will have values installed for compatibility purposes so that stat() and
/// co. can be emulated in userspace.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct statx {
    // 0x00
    /// What results were written [uncond]
    pub stx_mask: __u32,
    /// Preferred general I/O size [uncond]
    pub stx_blksize: __u32,
    /// Flags conveying information about the file [uncond]
    pub stx_attributes: __u64,

    // 0x10
    /// Number of hard links
    pub stx_nlink: __u32,
    /// User ID of owner
    pub stx_uid: __u32,
    /// Group ID of owner
    pub stx_gid: __u32,
    /// File mode
    pub stx_mode: __u16,
    pub __spare0: [__u16; 1],

    // 0x20
    /// Inode number
    pub stx_ino: __u64,
    /// File size
    pub stx_size: __u64,
    /// Number of 512-byte blocks allocated
    pub stx_blocks: __u64,
    /// Mask to show what's supported in stx_attributes
    pub stx_attributes_mask: __u64,

    // 0x40
    pub stx_atime: statx_timestamp, /* Last access time */
    pub stx_btime: statx_timestamp, /* File creation time */
    pub stx_ctime: statx_timestamp, /* Last attribute change time */
    pub stx_mtime: statx_timestamp, /* Last data modification time */

    /* 0x80 */
    /// Device ID of special file [if bdev/cdev]
    pub stx_rdev_major: __u32,
    pub stx_rdev_minor: __u32,
    /// ID of device containing file [uncond]
    pub stx_dev_major: __u32,
    pub stx_dev_minor: __u32,

    // 0x90
    /// Spare space for future expansion
    pub __spare2: [__u64; 14],
    // 0x100
}

#[allow(non_upper_case_globals)]
pub const SYS_statx: c_long = 332;

// Flags

pub const AT_STATX_SYNC_AS_STAT: c_uint = 0x0000_0000;
pub const AT_STATX_FORCE_SYNC: c_uint = 0x0000_2000;
pub const AT_STATX_DONT_SYNC: c_uint = 0x0000_4000;

pub const STATX_TYPE: c_uint = 0x0000_0001;
pub const STATX_MODE: c_uint = 0x0000_0002;
pub const STATX_NLINK: c_uint = 0x0000_0004;
pub const STATX_UID: c_uint = 0x0000_0008;
pub const STATX_GID: c_uint = 0x0000_0010;
pub const STATX_ATIME: c_uint = 0x0000_0020;
pub const STATX_MTIME: c_uint = 0x0000_0040;
pub const STATX_CTIME: c_uint = 0x0000_0080;
pub const STATX_INO: c_uint = 0x0000_0100;
pub const STATX_SIZE: c_uint = 0x0000_0200;
pub const STATX_BLOCKS: c_uint = 0x0000_0400;
pub const STATX_BASIC_STATS: c_uint = 0x0000_07ff;
pub const STATX_BTIME: c_uint = 0x0000_0800;
pub const STATX_ALL: c_uint = 0x0000_0fff;
pub const STATX__RESERVED: c_uint = 0x8000_0000;

// File attributes.

pub const STATX_ATTR_COMPRESSED: __u64 = 0x0000_0004;
pub const STATX_ATTR_IMMUTABLE: __u64 = 0x0000_0010;
pub const STATX_ATTR_APPEND: __u64 = 0x0000_0020;
pub const STATX_ATTR_NODUMP: __u64 = 0x0000_0040;
pub const STATX_ATTR_ENCRYPTED: __u64 = 0x0000_0800;

pub const STATX_ATTR_AUTOMOUNT: __u64 = 0x0000_1000;

/// statx - get file status (extended)
///
/// See also:
/// http://man7.org/linux/man-pages/man2/statx.2.html
pub unsafe fn statx(
    dirfd: c_int,
    pathname: *const c_char,
    flags: c_int,
    mask: c_uint,
    statxbuf: *mut statx,
) -> c_int {
    syscall(SYS_statx, dirfd, pathname, flags, mask, statxbuf) as c_int
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn check_struct_layout() {
        use memoffset::offset_of;
        use std::mem::size_of;

        assert_eq!(size_of::<statx>(), 0x100);
        assert_eq!(size_of::<statx_timestamp>(), 16);

        assert_eq!(offset_of!(statx, stx_mask), 0);
        assert_eq!(offset_of!(statx, stx_nlink), 0x10);
        assert_eq!(offset_of!(statx, stx_ino), 0x20);
        assert_eq!(offset_of!(statx, stx_atime), 0x40);
        assert_eq!(offset_of!(statx, stx_rdev_major), 0x80);
        assert_eq!(offset_of!(statx, __spare2), 0x90);
    }

    #[test]
    #[ignore]
    fn test_stat() {
        use libc::{__errno_location, strerror, AT_FDCWD};
        use std::cell::UnsafeCell;
        use std::mem::zeroed;
        use std::os::unix::ffi::OsStrExt;
        use std::path::Path;

        const PATH: &str = "."; // Working dir.

        let mut c_path_buf: Vec<u8> = Path::new(PATH).as_os_str().as_bytes().to_owned();
        c_path_buf.push(0); // '\0'
        let c_path = c_path_buf.as_ptr() as *mut c_char;

        let buf = UnsafeCell::new(unsafe { zeroed::<statx>() });
        let ret = unsafe { statx(AT_FDCWD, c_path, 0, STATX_ALL, buf.get()) };
        if ret != 0 {
            let errno = unsafe { *__errno_location() };
            let err_str: String = unsafe {
                let pstr = strerror(errno);
                assert!(!pstr.is_null());
                (0..)
                    .map(|i| *pstr.offset(i) as u8 as char)
                    .take_while(|c| *c != '\0')
                    .collect()
            };
            panic!("statx() failed: {}", err_str);
        } else {
            println!("statx() success: {:?}", buf.into_inner());
        }
    }
}