Skip to content

Commit 91462db

Browse files
committed
[miri] Throw UB if target size and data size don't match
If an extern C function is defined as ``` extern "C" { fn malloc(size: u32) -> *mut std::ffi::c_void; } ``` on a 64-bit machine(ie. pointer sizes don't match), throw an undefined behaviour.
1 parent 659951c commit 91462db

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/librustc_middle/mir/interpret/error.rs

+10
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,11 @@ pub enum UndefinedBehaviorInfo {
361361
InvalidUndefBytes(Option<Pointer>),
362362
/// Working with a local that is not currently live.
363363
DeadLocal,
364+
/// Data size is not equal to target size
365+
ArgumentSizeMismatch {
366+
target_size: u64,
367+
data_size: u64,
368+
},
364369
}
365370

366371
impl fmt::Debug for UndefinedBehaviorInfo {
@@ -422,6 +427,11 @@ impl fmt::Debug for UndefinedBehaviorInfo {
422427
"using uninitialized data, but this operation requires initialized memory"
423428
),
424429
DeadLocal => write!(f, "accessing a dead local variable"),
430+
ArgumentSizeMismatch { target_size, data_size } => write!(
431+
f,
432+
"argument size mismatch: expected {} bytes but got {} bytes instead",
433+
target_size, data_size
434+
),
425435
}
426436
}
427437
}

src/librustc_middle/mir/interpret/value.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,12 @@ impl<'tcx, Tag> Scalar<Tag> {
393393
assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST");
394394
match self {
395395
Scalar::Raw { data, size } => {
396-
assert_eq!(target_size.bytes(), u64::from(size));
396+
if target_size.bytes() != u64::from(size) {
397+
throw_ub!(ArgumentSizeMismatch {
398+
target_size: target_size.bytes(),
399+
data_size: u64::from(size)
400+
});
401+
}
397402
Scalar::check_data(data, size);
398403
Ok(data)
399404
}

0 commit comments

Comments
 (0)