Skip to content

Commit a59e155

Browse files
committed
Tidy up calloc code
1 parent d1d05c8 commit a59e155

File tree

1 file changed

+7
-16
lines changed

1 file changed

+7
-16
lines changed

src/fn_call.rs

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -95,25 +95,16 @@ pub trait EvalContextExt<'a, 'mir, 'tcx: 'a + 'mir>: crate::MiriEvalContextExt<'
9595
}
9696
"calloc" => {
9797
let items = this.read_scalar(args[0])?.to_usize(this)?;
98-
let count = this.read_scalar(args[1])?.to_usize(this)?;
99-
let size = if let Some(size) = items.checked_add(count) {
100-
size
101-
} else {
102-
return err!(MachineError(format!(
103-
"calloc: overflow of items * count: {} * {}",
104-
items, count,
105-
)));
106-
};
107-
if size == 0 {
98+
let len = this.read_scalar(args[1])?.to_usize(this)?;
99+
let bytes = items.checked_mul(len).ok_or_else(|| InterpError::Overflow(mir::BinOp::Mul))?;
100+
101+
if bytes== 0 {
108102
this.write_null(dest)?;
109103
} else {
104+
let size = Size::from_bytes(bytes);
110105
let align = this.tcx.data_layout.pointer_align.abi;
111-
let ptr = this.memory_mut()
112-
.allocate(Size::from_bytes(size), align, MiriMemoryKind::C.into())
113-
.with_default_tag();
114-
this.memory_mut()
115-
.get_mut(ptr.alloc_id)?
116-
.write_repeat(tcx, ptr, 0, Size::from_bytes(size))?;
106+
let ptr = this.memory_mut().allocate(size, align, MiriMemoryKind::C.into()).with_default_tag();
107+
this.memory_mut().get_mut(ptr.alloc_id)?.write_repeat(tcx, ptr, 0, size)?;
117108
this.write_scalar(Scalar::Ptr(ptr), dest)?;
118109
}
119110
}

0 commit comments

Comments
 (0)