Skip to content

Commit f710327

Browse files
committed
Implement a readdir64() shim for Linux
Partial fix for #1966.
1 parent a25d905 commit f710327

File tree

3 files changed

+71
-65
lines changed

3 files changed

+71
-65
lines changed

src/shims/posix/fs.rs

+61-55
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,21 @@ 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 { read_dir, entry: Pointer::null() }
437+
}
438+
}
439+
424440
#[derive(Debug)]
425441
pub struct DirHandler {
426442
/// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
@@ -432,7 +448,7 @@ pub struct DirHandler {
432448
/// the corresponding ReadDir iterator from this map, and information from the next
433449
/// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
434450
/// the map.
435-
streams: FxHashMap<u64, ReadDir>,
451+
streams: FxHashMap<u64, OpenDir>,
436452
/// ID number to be used by the next call to opendir
437453
next_id: u64,
438454
}
@@ -441,7 +457,7 @@ impl DirHandler {
441457
fn insert_new(&mut self, read_dir: ReadDir) -> u64 {
442458
let id = self.next_id;
443459
self.next_id += 1;
444-
self.streams.try_insert(id, read_dir).unwrap();
460+
self.streams.try_insert(id, OpenDir::new(read_dir)).unwrap();
445461
id
446462
}
447463
}
@@ -1207,32 +1223,29 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
12071223
}
12081224
}
12091225

1210-
fn linux_readdir64_r(
1211-
&mut self,
1212-
dirp_op: &OpTy<'tcx, Tag>,
1213-
entry_op: &OpTy<'tcx, Tag>,
1214-
result_op: &OpTy<'tcx, Tag>,
1215-
) -> InterpResult<'tcx, i32> {
1226+
fn linux_readdir64(&mut self, dirp_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
12161227
let this = self.eval_context_mut();
12171228

1218-
this.assert_target_os("linux", "readdir64_r");
1229+
this.assert_target_os("linux", "readdir64");
12191230

12201231
let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
12211232

12221233
// Reject if isolation is enabled.
12231234
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1224-
this.reject_in_isolation("`readdir64_r`", reject_with)?;
1225-
// Set error code as "EBADF" (bad fd)
1226-
return this.handle_not_found();
1235+
this.reject_in_isolation("`readdir`", reject_with)?;
1236+
let eacc = this.eval_libc("EACCES")?;
1237+
this.set_last_error(eacc)?;
1238+
return Ok(Scalar::null_ptr(this));
12271239
}
12281240

1229-
let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1230-
err_unsup_format!("the DIR pointer passed to readdir64_r did not come from opendir")
1241+
let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1242+
err_unsup_format!("the DIR pointer passed to readdir64 did not come from opendir")
12311243
})?;
1232-
match dir_iter.next() {
1244+
1245+
let entry = match open_dir.read_dir.next() {
12331246
Some(Ok(dir_entry)) => {
1234-
// Write into entry, write pointer to result, return 0 on success.
1235-
// The name is written with write_os_str_to_c_str, while the rest of the
1247+
// Write the directory entry into a newly allocated buffer.
1248+
// The name is written with write_bytes, while the rest of the
12361249
// dirent64 struct is written using write_packed_immediates.
12371250

12381251
// For reference:
@@ -1244,22 +1257,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
12441257
// pub d_name: [c_char; 256],
12451258
// }
12461259

1247-
let entry_place = this.deref_operand(entry_op)?;
1248-
let name_place = this.mplace_field(&entry_place, 4)?;
1249-
1250-
let file_name = dir_entry.file_name(); // not a Path as there are no separators!
1251-
let (name_fits, _) = this.write_os_str_to_c_str(
1252-
&file_name,
1253-
name_place.ptr,
1254-
name_place.layout.size.bytes(),
1255-
)?;
1256-
if !name_fits {
1257-
throw_unsup_format!(
1258-
"a directory entry had a name too large to fit in libc::dirent64"
1259-
);
1260-
}
1261-
1262-
let entry_place = this.deref_operand(entry_op)?;
12631260
let ino64_t_layout = this.libc_ty_layout("ino64_t")?;
12641261
let off64_t_layout = this.libc_ty_layout("off64_t")?;
12651262
let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
@@ -1280,30 +1277,38 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
12801277
immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
12811278
immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
12821279
];
1280+
let mut name = dir_entry.file_name(); // not a Path as there are no separators!
1281+
name.push("\0"); // Add a NUL terminator
1282+
let name_bytes = os_str_to_bytes(&name)?;
1283+
let name_offset = imms.iter().map(|imm| imm.layout.size.bytes()).sum::<u64>();
1284+
let size =
1285+
name_offset.checked_add(u64::try_from(name_bytes.len()).unwrap()).unwrap();
1286+
1287+
let entry = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C)?;
1288+
let entry_layout = this.layout_of(this.tcx.mk_array(this.tcx.types.u8, size))?;
1289+
let entry_place = MPlaceTy::from_aligned_ptr(entry, entry_layout);
12831290
this.write_packed_immediates(&entry_place, &imms)?;
12841291

1285-
let result_place = this.deref_operand(result_op)?;
1286-
this.write_scalar(this.read_scalar(entry_op)?, &result_place.into())?;
1292+
let name_ptr = entry.offset(Size::from_bytes(name_offset), this)?;
1293+
this.memory.write_bytes(name_ptr, name_bytes.iter().copied())?;
12871294

1288-
Ok(0)
1295+
entry
12891296
}
12901297
None => {
1291-
// end of stream: return 0, assign *result=NULL
1292-
this.write_null(&this.deref_operand(result_op)?.into())?;
1293-
Ok(0)
1298+
// end of stream: return NULL
1299+
Pointer::null()
12941300
}
1295-
Some(Err(e)) =>
1296-
match e.raw_os_error() {
1297-
// return positive error number on error
1298-
Some(error) => Ok(error),
1299-
None => {
1300-
throw_unsup_format!(
1301-
"the error {} couldn't be converted to a return value",
1302-
e
1303-
)
1304-
}
1305-
},
1306-
}
1301+
Some(Err(e)) => {
1302+
this.set_last_error_from_io_error(e.kind())?;
1303+
Pointer::null()
1304+
}
1305+
};
1306+
1307+
let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).unwrap();
1308+
let old_entry = std::mem::replace(&mut open_dir.entry, entry);
1309+
this.free(old_entry, MiriMemoryKind::C)?;
1310+
1311+
Ok(Scalar::from_maybe_pointer(entry, this))
13071312
}
13081313

13091314
fn macos_readdir_r(
@@ -1325,10 +1330,10 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
13251330
return this.handle_not_found();
13261331
}
13271332

1328-
let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1333+
let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
13291334
err_unsup_format!("the DIR pointer passed to readdir_r did not come from opendir")
13301335
})?;
1331-
match dir_iter.next() {
1336+
match open_dir.read_dir.next() {
13321337
Some(Ok(dir_entry)) => {
13331338
// Write into entry, write pointer to result, return 0 on success.
13341339
// The name is written with write_os_str_to_c_str, while the rest of the
@@ -1419,8 +1424,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
14191424
return this.handle_not_found();
14201425
}
14211426

1422-
if let Some(dir_iter) = this.machine.dir_handler.streams.remove(&dirp) {
1423-
drop(dir_iter);
1427+
if let Some(open_dir) = this.machine.dir_handler.streams.remove(&dirp) {
1428+
this.free(open_dir.entry, MiriMemoryKind::C)?;
1429+
drop(open_dir);
14241430
Ok(0)
14251431
} else {
14261432
this.handle_not_found()

src/shims/posix/linux/foreign_items.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -43,11 +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_r" => {
47-
let &[ref dirp, ref entry, ref result] =
46+
"readdir64" => {
47+
let &[ref dirp] =
4848
this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
49-
let result = this.linux_readdir64_r(dirp, entry, result)?;
50-
this.write_scalar(Scalar::from_i32(result), dest)?;
49+
let result = this.linux_readdir64(dirp)?;
50+
this.write_scalar(result, dest)?;
5151
}
5252
"ftruncate64" => {
5353
let &[ref fd, ref length] =

tests/run-pass/fs.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
extern crate libc;
77

88
use std::ffi::CString;
9-
use std::fs::{create_dir, remove_dir, remove_dir_all, remove_file, rename, File, OpenOptions};
9+
use std::fs::{
10+
create_dir, read_dir, remove_dir, remove_dir_all, remove_file, rename, File, OpenOptions,
11+
};
1012
use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom, Write};
1113
use std::path::{Path, PathBuf};
1214

@@ -374,19 +376,17 @@ fn test_directory() {
374376
let path_2 = dir_path.join("test_file_2");
375377
drop(File::create(&path_2).unwrap());
376378
// Test that the files are present inside the directory
377-
/* FIXME(1966) disabled due to missing readdir support
378379
let dir_iter = read_dir(&dir_path).unwrap();
379380
let mut file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
380381
file_names.sort_unstable();
381-
assert_eq!(file_names, vec!["test_file_1", "test_file_2"]); */
382+
assert_eq!(file_names, vec!["test_file_1", "test_file_2"]);
382383
// Clean up the files in the directory
383384
remove_file(&path_1).unwrap();
384385
remove_file(&path_2).unwrap();
385386
// Now there should be nothing left in the directory.
386-
/* FIXME(1966) disabled due to missing readdir support
387-
dir_iter = read_dir(&dir_path).unwrap();
387+
let dir_iter = read_dir(&dir_path).unwrap();
388388
let file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
389-
assert!(file_names.is_empty());*/
389+
assert!(file_names.is_empty());
390390

391391
// Deleting the directory should succeed.
392392
remove_dir(&dir_path).unwrap();

0 commit comments

Comments
 (0)