Auto merge of #130540 - veera-sivarajan:fix-87525, r=estebank
Add a Lint for Pointer to Integer Transmutes in Consts Fixes #87525 This PR adds a MirLint for pointer to integer transmutes in const functions and associated consts. The implementation closely follows this comment: https://github.com/rust-lang/rust/pull/85769#issuecomment-880969112. More details about the implementation can be found in the comments. Note: This could break some sound code as mentioned by RalfJung in https://github.com/rust-lang/rust/pull/85769#issuecomment-886491680: > ... technically const-code could transmute/cast an int to a ptr and then transmute it back and that would be correct -- so the lint will deny some sound code. Does not seem terribly likely though. References: 1. https://doc.rust-lang.org/std/mem/fn.transmute.html 2. https://doc.rust-lang.org/reference/items/associated-items.html#associated-constants
This commit is contained in:
commit
daebce4247
10 changed files with 262 additions and 6 deletions
|
@ -81,6 +81,7 @@ declare_lint_pass! {
|
|||
PRIVATE_INTERFACES,
|
||||
PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
|
||||
PTR_CAST_ADD_AUTO_TO_OBJECT,
|
||||
PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS,
|
||||
PUB_USE_OF_PRIVATE_EXTERN_CRATE,
|
||||
REDUNDANT_IMPORTS,
|
||||
REDUNDANT_LIFETIMES,
|
||||
|
@ -4998,3 +4999,37 @@ declare_lint! {
|
|||
reference: "issue #124535 <https://github.com/rust-lang/rust/issues/124535>",
|
||||
};
|
||||
}
|
||||
|
||||
declare_lint! {
|
||||
/// The `ptr_to_integer_transmute_in_consts` lint detects pointer to integer
|
||||
/// transmute in const functions and associated constants.
|
||||
///
|
||||
/// ### Example
|
||||
///
|
||||
/// ```rust
|
||||
/// const fn foo(ptr: *const u8) -> usize {
|
||||
/// unsafe {
|
||||
/// std::mem::transmute::<*const u8, usize>(ptr)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// {{produces}}
|
||||
///
|
||||
/// ### Explanation
|
||||
///
|
||||
/// Transmuting pointers to integers in a `const` context is undefined behavior.
|
||||
/// Any attempt to use the resulting integer will abort const-evaluation.
|
||||
///
|
||||
/// But sometimes the compiler might not emit an error for pointer to integer transmutes
|
||||
/// inside const functions and associated consts because they are evaluated only when referenced.
|
||||
/// Therefore, this lint serves as an extra layer of defense to prevent any undefined behavior
|
||||
/// from compiling without any warnings or errors.
|
||||
///
|
||||
/// See [std::mem::transmute] in the reference for more details.
|
||||
///
|
||||
/// [std::mem::transmute]: https://doc.rust-lang.org/std/mem/fn.transmute.html
|
||||
pub PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS,
|
||||
Warn,
|
||||
"detects pointer to integer transmutes in const functions and associated constants",
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue