summary refs log tree commit diff
path: root/library/std/src/sys
diff options
context:
space:
mode:
authorTavian Barnes <tavianator@tavianator.com>2022-02-22 20:41:13 -0500
committerTavian Barnes <tavianator@tavianator.com>2022-02-23 09:51:02 -0500
commit478cf8b3a455db83473d89f8d856ae309974e4ee (patch)
tree7278228180517e8152233f899aa5b138c01e192d /library/std/src/sys
parent5bd1ec3283874b97b27da4539b2950fbd01c4b0e (diff)
downloadrust-478cf8b3a455db83473d89f8d856ae309974e4ee.tar.gz
rust-478cf8b3a455db83473d89f8d856ae309974e4ee.zip
fs: Don't dereference a pointer to a too-small allocation
ptr::addr_of!((*ptr).field) still requires ptr to point to an
appropriate allocation for its type.  Since the pointer returned by
readdir() can be smaller than sizeof(struct dirent), we need to entirely
avoid dereferencing it as that type.

Link: https://github.com/rust-lang/miri/pull/1981#issuecomment-1048278492
Link: https://github.com/rust-lang/rust/pull/93459#discussion_r795089971
Diffstat (limited to 'library/std/src/sys')
-rw-r--r--library/std/src/sys/unix/fs.rs14
1 files changed, 9 insertions, 5 deletions
diff --git a/library/std/src/sys/unix/fs.rs b/library/std/src/sys/unix/fs.rs
index 8bd0b9b14af..3d0162940a6 100644
--- a/library/std/src/sys/unix/fs.rs
+++ b/library/std/src/sys/unix/fs.rs
@@ -491,14 +491,18 @@ impl Iterator for ReadDir {
 
                 // Only d_reclen bytes of *entry_ptr are valid, so we can't just copy the
                 // whole thing (#93384).  Instead, copy everything except the name.
+                let mut copy: dirent64 = mem::zeroed();
+                // Can't dereference entry_ptr, so use the local entry to get
+                // offsetof(struct dirent, d_name)
+                let copy_bytes = &mut copy as *mut _ as *mut u8;
+                let copy_name = &mut copy.d_name as *mut _ as *mut u8;
+                let name_offset = copy_name.offset_from(copy_bytes) as usize;
                 let entry_bytes = entry_ptr as *const u8;
-                let entry_name = ptr::addr_of!((*entry_ptr).d_name) as *const u8;
-                let name_offset = entry_name.offset_from(entry_bytes) as usize;
-                let mut entry: dirent64 = mem::zeroed();
-                ptr::copy_nonoverlapping(entry_bytes, &mut entry as *mut _ as *mut u8, name_offset);
+                let entry_name = entry_bytes.add(name_offset);
+                ptr::copy_nonoverlapping(entry_bytes, copy_bytes, name_offset);
 
                 let ret = DirEntry {
-                    entry,
+                    entry: copy,
                     // d_name is guaranteed to be null-terminated.
                     name: CStr::from_ptr(entry_name as *const _).to_owned(),
                     dir: Arc::clone(&self.inner),