Skip to content

Commit fc15f96

Browse files
committed
Auto merge of #1981 - tavianator:readdir, r=RalfJung
Implement a readdir64() shim for Linux Partial fix for #1966.
2 parents ccaf720 + 0886419 commit fc15f96

File tree

7 files changed

+96
-82
lines changed

7 files changed

+96
-82
lines changed

src/data_race.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -743,7 +743,7 @@ impl VClockAlloc {
743743
MemoryKind::Machine(
744744
MiriMemoryKind::Global
745745
| MiriMemoryKind::Machine
746-
| MiriMemoryKind::Env
746+
| MiriMemoryKind::Runtime
747747
| MiriMemoryKind::ExternStatic
748748
| MiriMemoryKind::Tls,
749749
)

src/machine.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,9 @@ pub enum MiriMemoryKind {
7171
/// Memory for args, errno, and other parts of the machine-managed environment.
7272
/// This memory may leak.
7373
Machine,
74-
/// Memory for env vars. Separate from `Machine` because we clean it up and leak-check it.
75-
Env,
74+
/// Memory allocated by the runtime (e.g. env vars). Separate from `Machine`
75+
/// because we clean it up and leak-check it.
76+
Runtime,
7677
/// Globals copied from `tcx`.
7778
/// This memory may leak.
7879
Global,
@@ -96,7 +97,7 @@ impl MayLeak for MiriMemoryKind {
9697
fn may_leak(self) -> bool {
9798
use self::MiriMemoryKind::*;
9899
match self {
99-
Rust | C | WinHeap | Env => false,
100+
Rust | C | WinHeap | Runtime => false,
100101
Machine | Global | ExternStatic | Tls => true,
101102
}
102103
}
@@ -110,7 +111,7 @@ impl fmt::Display for MiriMemoryKind {
110111
C => write!(f, "C heap"),
111112
WinHeap => write!(f, "Windows heap"),
112113
Machine => write!(f, "machine-managed memory"),
113-
Env => write!(f, "environment variable"),
114+
Runtime => write!(f, "language runtime memory"),
114115
Global => write!(f, "global (static or const)"),
115116
ExternStatic => write!(f, "extern static"),
116117
Tls => write!(f, "thread-local static"),

src/shims/env.rs

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,12 @@ impl<'tcx> EnvVars<'tcx> {
7878
) -> InterpResult<'tcx> {
7979
// Deallocate individual env vars.
8080
for (_name, ptr) in ecx.machine.env_vars.map.drain() {
81-
ecx.memory.deallocate(ptr, None, MiriMemoryKind::Env.into())?;
81+
ecx.memory.deallocate(ptr, None, MiriMemoryKind::Runtime.into())?;
8282
}
8383
// Deallocate environ var list.
8484
let environ = ecx.machine.env_vars.environ.unwrap();
8585
let old_vars_ptr = ecx.read_pointer(&environ.into())?;
86-
ecx.memory.deallocate(old_vars_ptr, None, MiriMemoryKind::Env.into())?;
86+
ecx.memory.deallocate(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
8787
Ok(())
8888
}
8989
}
@@ -96,7 +96,7 @@ fn alloc_env_var_as_c_str<'mir, 'tcx>(
9696
let mut name_osstring = name.to_os_string();
9797
name_osstring.push("=");
9898
name_osstring.push(value);
99-
ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into())
99+
ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Runtime.into())
100100
}
101101

102102
fn alloc_env_var_as_wide_str<'mir, 'tcx>(
@@ -107,7 +107,7 @@ fn alloc_env_var_as_wide_str<'mir, 'tcx>(
107107
let mut name_osstring = name.to_os_string();
108108
name_osstring.push("=");
109109
name_osstring.push(value);
110-
ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into())
110+
ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Runtime.into())
111111
}
112112

113113
impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
@@ -186,7 +186,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
186186
}
187187
// Allocate environment block & Store environment variables to environment block.
188188
// Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
189-
let envblock_ptr = this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Env.into())?;
189+
let envblock_ptr =
190+
this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Runtime.into())?;
190191
// If the function succeeds, the return value is a pointer to the environment block of the current process.
191192
Ok(envblock_ptr)
192193
}
@@ -200,7 +201,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
200201
this.assert_target_os("windows", "FreeEnvironmentStringsW");
201202

202203
let env_block_ptr = this.read_pointer(env_block_op)?;
203-
let result = this.memory.deallocate(env_block_ptr, None, MiriMemoryKind::Env.into());
204+
let result = this.memory.deallocate(env_block_ptr, None, MiriMemoryKind::Runtime.into());
204205
// If the function succeeds, the return value is nonzero.
205206
Ok(result.is_ok() as i32)
206207
}
@@ -231,7 +232,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
231232
if let Some((name, value)) = new {
232233
let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this)?;
233234
if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
234-
this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
235+
this.memory.deallocate(var, None, MiriMemoryKind::Runtime.into())?;
235236
}
236237
this.update_environ()?;
237238
Ok(0) // return zero on success
@@ -268,15 +269,15 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
268269
} else if this.ptr_is_null(value_ptr)? {
269270
// Delete environment variable `{name}`
270271
if let Some(var) = this.machine.env_vars.map.remove(&name) {
271-
this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
272+
this.memory.deallocate(var, None, MiriMemoryKind::Runtime.into())?;
272273
this.update_environ()?;
273274
}
274275
Ok(1) // return non-zero on success
275276
} else {
276277
let value = this.read_os_str_from_wide_str(value_ptr)?;
277278
let var_ptr = alloc_env_var_as_wide_str(&name, &value, &mut this)?;
278279
if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
279-
this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
280+
this.memory.deallocate(var, None, MiriMemoryKind::Runtime.into())?;
280281
}
281282
this.update_environ()?;
282283
Ok(1) // return non-zero on success
@@ -301,7 +302,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
301302
}
302303
if let Some(old) = success {
303304
if let Some(var) = old {
304-
this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
305+
this.memory.deallocate(var, None, MiriMemoryKind::Runtime.into())?;
305306
}
306307
this.update_environ()?;
307308
Ok(0)
@@ -437,7 +438,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
437438
// Deallocate the old environ list, if any.
438439
if let Some(environ) = this.machine.env_vars.environ {
439440
let old_vars_ptr = this.read_pointer(&environ.into())?;
440-
this.memory.deallocate(old_vars_ptr, None, MiriMemoryKind::Env.into())?;
441+
this.memory.deallocate(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
441442
} else {
442443
// No `environ` allocated yet, let's do that.
443444
// This is memory backing an extern static, hence `ExternStatic`, not `Env`.
@@ -455,7 +456,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
455456
let tcx = this.tcx;
456457
let vars_layout =
457458
this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
458-
let vars_place = this.allocate(vars_layout, MiriMemoryKind::Env.into())?;
459+
let vars_place = this.allocate(vars_layout, MiriMemoryKind::Runtime.into())?;
459460
for (idx, var) in vars.into_iter().enumerate() {
460461
let place = this.mplace_field(&vars_place, idx)?;
461462
this.write_pointer(var, &place.into())?;

src/shims/posix/fs.rs

Lines changed: 66 additions & 54 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,22 @@ 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+
// We rely on `free` being a NOP on null pointers.
437+
Self { read_dir, entry: Pointer::null() }
438+
}
439+
}
440+
424441
#[derive(Debug)]
425442
pub struct DirHandler {
426443
/// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
@@ -432,7 +449,7 @@ pub struct DirHandler {
432449
/// the corresponding ReadDir iterator from this map, and information from the next
433450
/// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
434451
/// the map.
435-
streams: FxHashMap<u64, ReadDir>,
452+
streams: FxHashMap<u64, OpenDir>,
436453
/// ID number to be used by the next call to opendir
437454
next_id: u64,
438455
}
@@ -441,7 +458,7 @@ impl DirHandler {
441458
fn insert_new(&mut self, read_dir: ReadDir) -> u64 {
442459
let id = self.next_id;
443460
self.next_id += 1;
444-
self.streams.try_insert(id, read_dir).unwrap();
461+
self.streams.try_insert(id, OpenDir::new(read_dir)).unwrap();
445462
id
446463
}
447464
}
@@ -1207,32 +1224,29 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
12071224
}
12081225
}
12091226

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> {
1227+
fn linux_readdir64(&mut self, dirp_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
12161228
let this = self.eval_context_mut();
12171229

1218-
this.assert_target_os("linux", "readdir64_r");
1230+
this.assert_target_os("linux", "readdir64");
12191231

12201232
let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
12211233

12221234
// Reject if isolation is enabled.
12231235
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();
1236+
this.reject_in_isolation("`readdir`", reject_with)?;
1237+
let eacc = this.eval_libc("EBADF")?;
1238+
this.set_last_error(eacc)?;
1239+
return Ok(Scalar::null_ptr(this));
12271240
}
12281241

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")
1242+
let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1243+
err_unsup_format!("the DIR pointer passed to readdir64 did not come from opendir")
12311244
})?;
1232-
match dir_iter.next() {
1245+
1246+
let entry = match open_dir.read_dir.next() {
12331247
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
1248+
// Write the directory entry into a newly allocated buffer.
1249+
// The name is written with write_bytes, while the rest of the
12361250
// dirent64 struct is written using write_packed_immediates.
12371251

12381252
// For reference:
@@ -1244,22 +1258,19 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
12441258
// pub d_name: [c_char; 256],
12451259
// }
12461260

1247-
let entry_place = this.deref_operand(entry_op)?;
1248-
let name_place = this.mplace_field(&entry_place, 4)?;
1261+
let mut name = dir_entry.file_name(); // not a Path as there are no separators!
1262+
name.push("\0"); // Add a NUL terminator
1263+
let name_bytes = os_str_to_bytes(&name)?;
1264+
let name_len = u64::try_from(name_bytes.len()).unwrap();
12491265

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-
}
1266+
let dirent64_layout = this.libc_ty_layout("dirent64")?;
1267+
let d_name_offset = dirent64_layout.fields.offset(4 /* d_name */).bytes();
1268+
let size = d_name_offset.checked_add(name_len).unwrap();
12611269

1262-
let entry_place = this.deref_operand(entry_op)?;
1270+
let entry =
1271+
this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::Runtime)?;
1272+
1273+
// FIXME: make use of dirent64_layout
12631274
let ino64_t_layout = this.libc_ty_layout("ino64_t")?;
12641275
let off64_t_layout = this.libc_ty_layout("off64_t")?;
12651276
let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
@@ -1277,33 +1288,33 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
12771288
let imms = [
12781289
immty_from_uint_checked(ino, ino64_t_layout)?, // d_ino
12791290
immty_from_uint_checked(0u128, off64_t_layout)?, // d_off
1280-
immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
1291+
immty_from_uint_checked(size, c_ushort_layout)?, // d_reclen
12811292
immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
12821293
];
1294+
let entry_layout = this.layout_of(this.tcx.mk_array(this.tcx.types.u8, size))?;
1295+
let entry_place = MPlaceTy::from_aligned_ptr(entry, entry_layout);
12831296
this.write_packed_immediates(&entry_place, &imms)?;
12841297

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

1288-
Ok(0)
1301+
entry
12891302
}
12901303
None => {
1291-
// end of stream: return 0, assign *result=NULL
1292-
this.write_null(&this.deref_operand(result_op)?.into())?;
1293-
Ok(0)
1304+
// end of stream: return NULL
1305+
Pointer::null()
12941306
}
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-
}
1307+
Some(Err(e)) => {
1308+
this.set_last_error_from_io_error(e.kind())?;
1309+
Pointer::null()
1310+
}
1311+
};
1312+
1313+
let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).unwrap();
1314+
let old_entry = std::mem::replace(&mut open_dir.entry, entry);
1315+
this.free(old_entry, MiriMemoryKind::Runtime)?;
1316+
1317+
Ok(Scalar::from_maybe_pointer(entry, this))
13071318
}
13081319

13091320
fn macos_readdir_r(
@@ -1325,10 +1336,10 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
13251336
return this.handle_not_found();
13261337
}
13271338

1328-
let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1339+
let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
13291340
err_unsup_format!("the DIR pointer passed to readdir_r did not come from opendir")
13301341
})?;
1331-
match dir_iter.next() {
1342+
match open_dir.read_dir.next() {
13321343
Some(Ok(dir_entry)) => {
13331344
// Write into entry, write pointer to result, return 0 on success.
13341345
// The name is written with write_os_str_to_c_str, while the rest of the
@@ -1419,8 +1430,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
14191430
return this.handle_not_found();
14201431
}
14211432

1422-
if let Some(dir_iter) = this.machine.dir_handler.streams.remove(&dirp) {
1423-
drop(dir_iter);
1433+
if let Some(open_dir) = this.machine.dir_handler.streams.remove(&dirp) {
1434+
this.free(open_dir.entry, MiriMemoryKind::Runtime)?;
1435+
drop(open_dir);
14241436
Ok(0)
14251437
} else {
14261438
this.handle_not_found()

src/shims/posix/linux/foreign_items.rs

Lines changed: 4 additions & 4 deletions
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] =

src/stacked_borrows.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -535,7 +535,7 @@ impl Stacks {
535535
MiriMemoryKind::Global
536536
| MiriMemoryKind::ExternStatic
537537
| MiriMemoryKind::Tls
538-
| MiriMemoryKind::Env
538+
| MiriMemoryKind::Runtime
539539
| MiriMemoryKind::Machine,
540540
) => (extra.base_tag(id), Permission::SharedReadWrite),
541541
// Heap allocations we only track precisely when raw pointers are tagged, for now.

0 commit comments

Comments
 (0)