Skip to content

Commit 9f77926

Browse files
committed
Implement a readdir64() shim for Linux
Partial fix for #1966.
1 parent c710067 commit 9f77926

File tree

3 files changed

+114
-12
lines changed

3 files changed

+114
-12
lines changed

src/shims/posix/fs.rs

Lines changed: 107 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use rustc_target::abi::{Align, Size};
1616

1717
use crate::*;
1818
use helpers::{check_arg_count, immty_from_int_checked, immty_from_uint_checked};
19+
use shims::os_str::os_str_to_bytes;
1920
use shims::time::system_time_to_duration;
2021

2122
#[derive(Debug)]
@@ -421,6 +422,24 @@ trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, '
421422
}
422423
}
423424

425+
/// An open directory, tracked by DirHandler.
426+
#[derive(Debug)]
427+
pub struct OpenDir {
428+
/// The directory reader on the host.
429+
read_dir: ReadDir,
430+
/// The most recent entry returned by readdir()
431+
entry: Pointer<Option<Tag>>,
432+
}
433+
434+
impl OpenDir {
435+
fn new(read_dir: ReadDir) -> Self {
436+
Self {
437+
read_dir,
438+
entry: Pointer::null(),
439+
}
440+
}
441+
}
442+
424443
#[derive(Debug)]
425444
pub struct DirHandler {
426445
/// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
@@ -432,7 +451,7 @@ pub struct DirHandler {
432451
/// the corresponding ReadDir iterator from this map, and information from the next
433452
/// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
434453
/// the map.
435-
streams: FxHashMap<u64, ReadDir>,
454+
streams: FxHashMap<u64, OpenDir>,
436455
/// ID number to be used by the next call to opendir
437456
next_id: u64,
438457
}
@@ -441,7 +460,7 @@ impl DirHandler {
441460
fn insert_new(&mut self, read_dir: ReadDir) -> u64 {
442461
let id = self.next_id;
443462
self.next_id += 1;
444-
self.streams.try_insert(id, read_dir).unwrap();
463+
self.streams.try_insert(id, OpenDir::new(read_dir)).unwrap();
445464
id
446465
}
447466
}
@@ -1196,6 +1215,85 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
11961215
}
11971216
}
11981217

1218+
fn linux_readdir64(&mut self, dirp_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
1219+
let this = self.eval_context_mut();
1220+
1221+
this.assert_target_os("linux", "readdir64");
1222+
1223+
let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1224+
1225+
// Reject if isolation is enabled.
1226+
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1227+
this.reject_in_isolation("`readdir`", reject_with)?;
1228+
let eacc = this.eval_libc("EACCES")?;
1229+
this.set_last_error(eacc)?;
1230+
return Ok(Scalar::null_ptr(this));
1231+
}
1232+
1233+
let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1234+
err_unsup_format!("the DIR pointer passed to readdir64 did not come from opendir")
1235+
})?;
1236+
1237+
let entry = match open_dir.read_dir.next() {
1238+
Some(Ok(dir_entry)) => {
1239+
let ino64_t_layout = this.libc_ty_layout("ino64_t")?;
1240+
let off64_t_layout = this.libc_ty_layout("off64_t")?;
1241+
let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
1242+
let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
1243+
1244+
// If the host is a Unix system, fill in the inode number with its real value.
1245+
// If not, use 0 as a fallback value.
1246+
#[cfg(unix)]
1247+
let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
1248+
#[cfg(not(unix))]
1249+
let ino = 0u64;
1250+
1251+
let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
1252+
1253+
let imms = [
1254+
immty_from_uint_checked(ino, ino64_t_layout)?, // d_ino
1255+
immty_from_uint_checked(0u128, off64_t_layout)?, // d_off
1256+
immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
1257+
immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
1258+
];
1259+
let name = dir_entry.file_name();
1260+
let name_bytes = os_str_to_bytes(&name)?;
1261+
let name_offset = imms.iter()
1262+
.map(|imm| imm.layout.size.bytes())
1263+
.sum::<u64>();
1264+
let size = name_offset
1265+
.checked_add(u64::try_from(name_bytes.len()).unwrap())
1266+
.unwrap()
1267+
.checked_add(1)
1268+
.unwrap();
1269+
1270+
let entry = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C)?;
1271+
let entry_layout = this.layout_of(this.tcx.mk_array(this.tcx.types.u8, size))?;
1272+
let entry_place = MPlaceTy::from_aligned_ptr(entry, entry_layout);
1273+
this.write_packed_immediates(&entry_place, &imms)?;
1274+
1275+
let name_ptr = entry.offset(Size::from_bytes(name_offset), this)?;
1276+
this.memory.write_bytes(name_ptr, name_bytes.iter().copied().chain(std::iter::once(0)))?;
1277+
1278+
entry
1279+
},
1280+
None => {
1281+
// end of stream: return NULL
1282+
Pointer::null()
1283+
}
1284+
Some(Err(e)) => {
1285+
this.set_last_error_from_io_error(e.kind())?;
1286+
Pointer::null()
1287+
}
1288+
};
1289+
1290+
let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).unwrap();
1291+
let old_entry = std::mem::replace(&mut open_dir.entry, entry);
1292+
this.free(old_entry, MiriMemoryKind::C)?;
1293+
1294+
Ok(Scalar::from_maybe_pointer(entry, this))
1295+
}
1296+
11991297
fn linux_readdir64_r(
12001298
&mut self,
12011299
dirp_op: &OpTy<'tcx, Tag>,
@@ -1215,10 +1313,10 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
12151313
return this.handle_not_found();
12161314
}
12171315

1218-
let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1316+
let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
12191317
err_unsup_format!("the DIR pointer passed to readdir64_r did not come from opendir")
12201318
})?;
1221-
match dir_iter.next() {
1319+
match open_dir.read_dir.next() {
12221320
Some(Ok(dir_entry)) => {
12231321
// Write into entry, write pointer to result, return 0 on success.
12241322
// The name is written with write_os_str_to_c_str, while the rest of the
@@ -1314,10 +1412,10 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
13141412
return this.handle_not_found();
13151413
}
13161414

1317-
let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1415+
let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
13181416
err_unsup_format!("the DIR pointer passed to readdir_r did not come from opendir")
13191417
})?;
1320-
match dir_iter.next() {
1418+
match open_dir.read_dir.next() {
13211419
Some(Ok(dir_entry)) => {
13221420
// Write into entry, write pointer to result, return 0 on success.
13231421
// The name is written with write_os_str_to_c_str, while the rest of the
@@ -1408,8 +1506,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
14081506
return this.handle_not_found();
14091507
}
14101508

1411-
if let Some(dir_iter) = this.machine.dir_handler.streams.remove(&dirp) {
1412-
drop(dir_iter);
1509+
if let Some(open_dir) = this.machine.dir_handler.streams.remove(&dirp) {
1510+
this.free(open_dir.entry, MiriMemoryKind::C)?;
1511+
drop(open_dir);
14131512
Ok(0)
14141513
} else {
14151514
this.handle_not_found()

src/shims/posix/linux/foreign_items.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,11 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
4343
let result = this.opendir(name)?;
4444
this.write_scalar(result, dest)?;
4545
}
46+
"readdir64" => {
47+
let &[ref dirp] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
48+
let result = this.linux_readdir64(dirp)?;
49+
this.write_scalar(result, dest)?;
50+
}
4651
"readdir64_r" => {
4752
let &[ref dirp, ref entry, ref result] =
4853
this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;

tests/run-pass/fs.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -331,19 +331,17 @@ fn test_directory() {
331331
let path_2 = dir_path.join("test_file_2");
332332
drop(File::create(&path_2).unwrap());
333333
// Test that the files are present inside the directory
334-
/* FIXME(1966) disabled due to missing readdir support
335334
let dir_iter = read_dir(&dir_path).unwrap();
336335
let mut file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
337336
file_names.sort_unstable();
338-
assert_eq!(file_names, vec!["test_file_1", "test_file_2"]); */
337+
assert_eq!(file_names, vec!["test_file_1", "test_file_2"]);
339338
// Clean up the files in the directory
340339
remove_file(&path_1).unwrap();
341340
remove_file(&path_2).unwrap();
342341
// Now there should be nothing left in the directory.
343-
/* FIXME(1966) disabled due to missing readdir support
344342
dir_iter = read_dir(&dir_path).unwrap();
345343
let file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
346-
assert!(file_names.is_empty());*/
344+
assert!(file_names.is_empty());
347345

348346
// Deleting the directory should succeed.
349347
remove_dir(&dir_path).unwrap();

0 commit comments

Comments
 (0)