Skip to content

Commit 2631aee

Browse files
committed
Auto merge of #94272 - tavianator:readdir-reclen-for-real, r=cuviper
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: rust-lang/miri#1981 (comment) Link: #93459 (comment)
2 parents 3d1eaf4 + 478cf8b commit 2631aee

File tree

1 file changed

+9
-5
lines changed
  • library/std/src/sys/unix

1 file changed

+9
-5
lines changed

library/std/src/sys/unix/fs.rs

+9-5
Original file line numberDiff line numberDiff line change
@@ -491,14 +491,18 @@ impl Iterator for ReadDir {
491491

492492
// Only d_reclen bytes of *entry_ptr are valid, so we can't just copy the
493493
// whole thing (#93384). Instead, copy everything except the name.
494+
let mut copy: dirent64 = mem::zeroed();
495+
// Can't dereference entry_ptr, so use the local entry to get
496+
// offsetof(struct dirent, d_name)
497+
let copy_bytes = &mut copy as *mut _ as *mut u8;
498+
let copy_name = &mut copy.d_name as *mut _ as *mut u8;
499+
let name_offset = copy_name.offset_from(copy_bytes) as usize;
494500
let entry_bytes = entry_ptr as *const u8;
495-
let entry_name = ptr::addr_of!((*entry_ptr).d_name) as *const u8;
496-
let name_offset = entry_name.offset_from(entry_bytes) as usize;
497-
let mut entry: dirent64 = mem::zeroed();
498-
ptr::copy_nonoverlapping(entry_bytes, &mut entry as *mut _ as *mut u8, name_offset);
501+
let entry_name = entry_bytes.add(name_offset);
502+
ptr::copy_nonoverlapping(entry_bytes, copy_bytes, name_offset);
499503

500504
let ret = DirEntry {
501-
entry,
505+
entry: copy,
502506
// d_name is guaranteed to be null-terminated.
503507
name: CStr::from_ptr(entry_name as *const _).to_owned(),
504508
dir: Arc::clone(&self.inner),

0 commit comments

Comments
 (0)