-
-
Notifications
You must be signed in to change notification settings - Fork 14.8k
invalid_reference_casting lint catches some patterns that aren't UB #116410
Copy link
Copy link
Open
Labels
A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.Area: Lints (warnings about flaws in source code) such as unused_mut.C-bugCategory: This is a bug.Category: This is a bug.L-invalid_reference_castingLint: invalid_reference_castingLint: invalid_reference_castingT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.T-opsemRelevant to the opsem teamRelevant to the opsem team
Metadata
Metadata
Assignees
Labels
A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.Area: Lints (warnings about flaws in source code) such as unused_mut.C-bugCategory: This is a bug.Category: This is a bug.L-invalid_reference_castingLint: invalid_reference_castingLint: invalid_reference_castingT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.T-opsemRelevant to the opsem teamRelevant to the opsem team
Type
Fields
Give feedbackNo fields configured for issues without a type.
When reading the 1.73.0 release notes, I noticed that the
invalid_reference_castinglint was made deny-by-default in #112431, under the premise that casting&Tto&mut Tvia raw pointers is always UB under Stacked Borrows. However, the lint appears a bit overly strict, since such a cast does not cause UB whenTis a zero-sized type:Without
#![allow(invalid_reference_casting)], this cast triggers the lint in 1.75.0-nightly (187b813 2023-10-03):However, when the lint is disabled, Miri runs the program successfully, under both Stacked Borrows and Tree Borrows. This makes sense looking at the rules: the reference doesn't point to any bytes, so it doesn't need to perform any access or be granted any permissions.
This pattern looks a bit dubious when expressed as a reference cast, but it is not UB. Therefore, I would suggest downgrading or turning off the lint when the destination type is a ZST.
Note: An earlier version of this issue also considered directly casting from
&UnsafeCell<i32>to&mut i32, which is legal under Stacked Borrows and Tree Borrows, but explicitly called out as UB in theUnsafeCelldocumentation. It was decided that linting on this case, as well as the related case of casting from&UnsafeCell<i32>to&mut UnsafeCell<i32>which isn't explicitly mentioned, is permissible as an enforcement of library UB until the aliasing rules are ultimately finalized. This was clarified in the diagnostic by #116421.