Category: Coding Mistakes
Undefined behavior due to invalid reference casting in AccountInfo::assign
Medium Impact
Medium Severity
Medium Likelihood
Description
The assign function casts a reference to a const ptr and then to a mut ptr, before writing to it.
#[inline(always)]
pub unsafe fn assign(&self, new_owner: &Pubkey) {
#[allow(invalid_reference_casting)]
core::ptr::write_volatile(&(*self.raw).owner as *const _ as *mut Pubkey, *new_owner);
}Casting an immutable reference & to a mutable one &mut, or a mut ptr, is always undefined behavior, as pointed out by the Rustonomicon↗. Here the #[allow(invalid_reference_casting)] attribute is used to silence the error the compiler throws otherwise, indicating the undefined behavior.
Impact
This may lead to undefined behavior resulting from casting an immutable reference to a mutable pointer.
Recommendations
Avoid taking an immutable reference, and directly cast a mutable reference to the mutable pointer first. Additionally, consider using core::ptr::write(..) over write_volatile as there is no direct need for a volatile write.