Skip to content

Commit 59de63e

Browse files
committed
Add lint against integer to pointer transmutes
1 parent 1ae7c49 commit 59de63e

File tree

6 files changed

+398
-1
lines changed

6 files changed

+398
-1
lines changed

compiler/rustc_lint/messages.ftl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,14 @@ lint_invalid_reference_casting_note_book = for more information, visit <https://
483483
484484
lint_invalid_reference_casting_note_ty_has_interior_mutability = even for types with interior mutability, the only legal way to obtain a mutable pointer from a shared reference is through `UnsafeCell::get`
485485
486+
lint_int_to_ptr_transmutes = transmuting an integer to a pointer creates a pointer without provenance
487+
.note = this is dangerous because dereferencing the resulting pointer is undefined behavior
488+
.note_exposed_provenance = exposed provenance semantics can be used to create a pointer based on some previously exposed provenance
489+
.help_transmute = for more information about transmute, see <https://doc.rust-lang.org/std/mem/fn.transmute.html#transmutation-between-pointers-and-integers>
490+
.help_exposed_provenance = for more information about exposed provenance, see <https://doc.rust-lang.org/std/ptr/index.html#exposed-provenance>
491+
.suggestion_with_exposed_provenance = use `std::ptr::with_exposed_provenance{$suffix}` instead to use a previously exposed provenance
492+
.suggestion_without_provenance_mut = if you truly mean to create a pointer without provenance, use `std::ptr::without_provenance_mut`
493+
486494
lint_legacy_derive_helpers = derive helper attribute is used before it is introduced
487495
.label = the attribute is introduced here
488496

compiler/rustc_lint/src/lints.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// ignore-tidy-filelength
2+
13
#![allow(rustc::untranslatable_diagnostic)]
24
use std::num::NonZero;
35

@@ -1618,6 +1620,46 @@ impl<'a> LintDiagnostic<'a, ()> for DropGlue<'_> {
16181620
}
16191621
}
16201622

1623+
// transmute.rs
1624+
#[derive(LintDiagnostic)]
1625+
#[diag(lint_int_to_ptr_transmutes)]
1626+
#[note]
1627+
#[note(lint_note_exposed_provenance)]
1628+
#[help(lint_suggestion_without_provenance_mut)]
1629+
#[help(lint_help_transmute)]
1630+
#[help(lint_help_exposed_provenance)]
1631+
pub(crate) struct IntegerToPtrTransmutes<'tcx> {
1632+
#[subdiagnostic]
1633+
pub suggestion: IntegerToPtrTransmutesSuggestion<'tcx>,
1634+
}
1635+
1636+
#[derive(Subdiagnostic)]
1637+
pub(crate) enum IntegerToPtrTransmutesSuggestion<'tcx> {
1638+
#[multipart_suggestion(
1639+
lint_suggestion_with_exposed_provenance,
1640+
applicability = "machine-applicable"
1641+
)]
1642+
ToPtr {
1643+
dst: Ty<'tcx>,
1644+
suffix: &'static str,
1645+
#[suggestion_part(code = "std::ptr::with_exposed_provenance{suffix}::<{dst}>(")]
1646+
start_call: Span,
1647+
},
1648+
#[multipart_suggestion(
1649+
lint_suggestion_with_exposed_provenance,
1650+
applicability = "machine-applicable"
1651+
)]
1652+
ToRef {
1653+
dst: Ty<'tcx>,
1654+
suffix: &'static str,
1655+
ref_mutbl: &'static str,
1656+
#[suggestion_part(
1657+
code = "&{ref_mutbl}*std::ptr::with_exposed_provenance{suffix}::<{dst}>("
1658+
)]
1659+
start_call: Span,
1660+
},
1661+
}
1662+
16211663
// types.rs
16221664
#[derive(LintDiagnostic)]
16231665
#[diag(lint_range_endpoint_out_of_range)]

compiler/rustc_lint/src/transmute.rs

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use rustc_ast::LitKind;
12
use rustc_errors::Applicability;
23
use rustc_hir::def::{DefKind, Res};
34
use rustc_hir::def_id::LocalDefId;
@@ -7,6 +8,7 @@ use rustc_middle::ty::{self, Ty};
78
use rustc_session::{declare_lint, impl_lint_pass};
89
use rustc_span::sym;
910

11+
use crate::lints::{IntegerToPtrTransmutes, IntegerToPtrTransmutesSuggestion};
1012
use crate::{LateContext, LateLintPass};
1113

1214
declare_lint! {
@@ -67,9 +69,44 @@ declare_lint! {
6769
"detects transmutes that can also be achieved by other operations"
6870
}
6971

72+
declare_lint! {
73+
/// The `integer_to_ptr_transmutes` lint detects integer to pointer
74+
/// transmutes where the resulting pointers are undefined behavior to dereference.
75+
///
76+
/// ### Example
77+
///
78+
/// ```rust
79+
/// fn foo(a: usize) -> *const u8 {
80+
/// unsafe {
81+
/// std::mem::transmute::<usize, *const u8>(a)
82+
/// }
83+
/// }
84+
/// ```
85+
///
86+
/// {{produces}}
87+
///
88+
/// ### Explanation
89+
///
90+
/// Any attempt to use the resulting pointers are undefined behavior as the resulting
91+
/// pointers won't have any provenance.
92+
///
93+
/// Alternatively, [`std::ptr::with_exposed_provenance`] should be used, as they do not
94+
/// carry the provenance requirement. If wanting to create pointers without provenance
95+
/// [`std::ptr::without_provenance`] should be used instead.
96+
///
97+
/// See [`std::mem::transmute`] in the reference for more details.
98+
///
99+
/// [`std::mem::transmute`]: https://doc.rust-lang.org/std/mem/fn.transmute.html
100+
/// [`std::ptr::with_exposed_provenance`]: https://doc.rust-lang.org/std/ptr/fn.with_exposed_provenance.html
101+
/// [`std::ptr::without_provenance`]: https://doc.rust-lang.org/std/ptr/fn.without_provenance.html
102+
pub INTEGER_TO_PTR_TRANSMUTES,
103+
Warn,
104+
"detects integer to pointer transmutes",
105+
}
106+
70107
pub(crate) struct CheckTransmutes;
71108

72-
impl_lint_pass!(CheckTransmutes => [PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS, UNNECESSARY_TRANSMUTES]);
109+
impl_lint_pass!(CheckTransmutes => [PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS, UNNECESSARY_TRANSMUTES, INTEGER_TO_PTR_TRANSMUTES]);
73110

74111
impl<'tcx> LateLintPass<'tcx> for CheckTransmutes {
75112
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
@@ -94,6 +131,51 @@ impl<'tcx> LateLintPass<'tcx> for CheckTransmutes {
94131

95132
check_ptr_transmute_in_const(cx, expr, body_owner_def_id, const_context, src, dst);
96133
check_unnecessary_transmute(cx, expr, callee, arg, const_context, src, dst);
134+
check_int_to_ptr_transmute(cx, expr, arg, src, dst);
135+
}
136+
}
137+
138+
/// Check for transmutes from integer to pointers (*const/*mut, &/&mut and fn()).
139+
///
140+
/// Using the resulting pointers would be undefined behavior.
141+
fn check_int_to_ptr_transmute<'tcx>(
142+
cx: &LateContext<'tcx>,
143+
expr: &'tcx hir::Expr<'tcx>,
144+
arg: &'tcx hir::Expr<'tcx>,
145+
src: Ty<'tcx>,
146+
dst: Ty<'tcx>,
147+
) {
148+
if matches!(src.kind(), ty::Uint(_) | ty::Int(_))
149+
&& let ty::Ref(_, inner_ty, mutbl) | ty::RawPtr(inner_ty, mutbl) = dst.kind()
150+
// bail-out if the argument is literal 0 as we have other lints for those cases
151+
&& !matches!(arg.kind, hir::ExprKind::Lit(hir::Lit { node: LitKind::Int(v, _), .. }) if v == 0)
152+
// bail-out if the inner type if a ZST
153+
&& cx.tcx
154+
.layout_of(cx.typing_env().as_query_input(*inner_ty))
155+
.is_ok_and(|layout| !layout.is_1zst())
156+
{
157+
let suffix = if mutbl.is_mut() { "_mut" } else { "" };
158+
cx.tcx.emit_node_span_lint(
159+
INTEGER_TO_PTR_TRANSMUTES,
160+
expr.hir_id,
161+
expr.span,
162+
IntegerToPtrTransmutes {
163+
suggestion: if dst.is_ref() {
164+
IntegerToPtrTransmutesSuggestion::ToRef {
165+
dst: *inner_ty,
166+
suffix,
167+
ref_mutbl: mutbl.prefix_str(),
168+
start_call: expr.span.shrink_to_lo().until(arg.span),
169+
}
170+
} else {
171+
IntegerToPtrTransmutesSuggestion::ToPtr {
172+
dst: *inner_ty,
173+
suffix,
174+
start_call: expr.span.shrink_to_lo().until(arg.span),
175+
}
176+
},
177+
},
178+
);
97179
}
98180
}
99181

tests/ui/lint/int_to_ptr.fixed

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Checks for the `integer_to_pointer_transmutes` lint
2+
3+
//@ check-pass
4+
//@ run-rustfix
5+
6+
#![allow(unused_unsafe)]
7+
#![allow(dead_code)]
8+
9+
unsafe fn should_lint(a: usize) {
10+
let _ptr: *const u8 = unsafe { std::ptr::with_exposed_provenance::<u8>(a) };
11+
//~^ WARN transmuting an integer to a pointer
12+
let _ptr: *mut u8 = unsafe { std::ptr::with_exposed_provenance_mut::<u8>(a) };
13+
//~^ WARN transmuting an integer to a pointer
14+
let _ref: &'static u8 = unsafe { &*std::ptr::with_exposed_provenance::<u8>(a) };
15+
//~^ WARN transmuting an integer to a pointer
16+
let _ref: &'static mut u8 = unsafe { &mut *std::ptr::with_exposed_provenance_mut::<u8>(a) };
17+
//~^ WARN transmuting an integer to a pointer
18+
19+
let _ptr = unsafe { std::ptr::with_exposed_provenance::<u8>(42usize) };
20+
//~^ WARN transmuting an integer to a pointer
21+
let _ptr = unsafe { std::ptr::with_exposed_provenance::<u8>(a + a) };
22+
//~^ WARN transmuting an integer to a pointer
23+
}
24+
25+
const unsafe fn should_lintin_const(a: usize) {
26+
let _ptr: *const u8 = unsafe { std::ptr::with_exposed_provenance::<u8>(a) };
27+
//~^ WARN transmuting an integer to a pointer
28+
let _ptr: *mut u8 = unsafe { std::ptr::with_exposed_provenance_mut::<u8>(a) };
29+
//~^ WARN transmuting an integer to a pointer
30+
let _ref: &'static u8 = unsafe { &*std::ptr::with_exposed_provenance::<u8>(a) };
31+
//~^ WARN transmuting an integer to a pointer
32+
let _ref: &'static mut u8 = unsafe { &mut *std::ptr::with_exposed_provenance_mut::<u8>(a) };
33+
//~^ WARN transmuting an integer to a pointer
34+
35+
let _ptr = unsafe { std::ptr::with_exposed_provenance::<u8>(42usize) };
36+
//~^ WARN transmuting an integer to a pointer
37+
let _ptr = unsafe { std::ptr::with_exposed_provenance::<u8>(a + a) };
38+
//~^ WARN transmuting an integer to a pointer
39+
}
40+
41+
unsafe fn should_not_lint(a: usize) {
42+
let _ptr = unsafe { std::mem::transmute::<usize, *const u8>(0usize) }; // linted by other lints
43+
let _ptr = unsafe { std::mem::transmute::<usize, *const ()>(a) }; // inner type is a ZST
44+
let _ptr = unsafe { std::mem::transmute::<usize, fn()>(a) }; // omit fn-ptr for now
45+
}
46+
47+
fn main() {}

tests/ui/lint/int_to_ptr.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Checks for the `integer_to_pointer_transmutes` lint
2+
3+
//@ check-pass
4+
//@ run-rustfix
5+
6+
#![allow(unused_unsafe)]
7+
#![allow(dead_code)]
8+
9+
unsafe fn should_lint(a: usize) {
10+
let _ptr: *const u8 = unsafe { std::mem::transmute::<usize, *const u8>(a) };
11+
//~^ WARN transmuting an integer to a pointer
12+
let _ptr: *mut u8 = unsafe { std::mem::transmute::<usize, *mut u8>(a) };
13+
//~^ WARN transmuting an integer to a pointer
14+
let _ref: &'static u8 = unsafe { std::mem::transmute::<usize, &'static u8>(a) };
15+
//~^ WARN transmuting an integer to a pointer
16+
let _ref: &'static mut u8 = unsafe { std::mem::transmute::<usize, &'static mut u8>(a) };
17+
//~^ WARN transmuting an integer to a pointer
18+
19+
let _ptr = unsafe { std::mem::transmute::<usize, *const u8>(42usize) };
20+
//~^ WARN transmuting an integer to a pointer
21+
let _ptr = unsafe { std::mem::transmute::<usize, *const u8>(a + a) };
22+
//~^ WARN transmuting an integer to a pointer
23+
}
24+
25+
const unsafe fn should_lintin_const(a: usize) {
26+
let _ptr: *const u8 = unsafe { std::mem::transmute::<usize, *const u8>(a) };
27+
//~^ WARN transmuting an integer to a pointer
28+
let _ptr: *mut u8 = unsafe { std::mem::transmute::<usize, *mut u8>(a) };
29+
//~^ WARN transmuting an integer to a pointer
30+
let _ref: &'static u8 = unsafe { std::mem::transmute::<usize, &'static u8>(a) };
31+
//~^ WARN transmuting an integer to a pointer
32+
let _ref: &'static mut u8 = unsafe { std::mem::transmute::<usize, &'static mut u8>(a) };
33+
//~^ WARN transmuting an integer to a pointer
34+
35+
let _ptr = unsafe { std::mem::transmute::<usize, *const u8>(42usize) };
36+
//~^ WARN transmuting an integer to a pointer
37+
let _ptr = unsafe { std::mem::transmute::<usize, *const u8>(a + a) };
38+
//~^ WARN transmuting an integer to a pointer
39+
}
40+
41+
unsafe fn should_not_lint(a: usize) {
42+
let _ptr = unsafe { std::mem::transmute::<usize, *const u8>(0usize) }; // linted by other lints
43+
let _ptr = unsafe { std::mem::transmute::<usize, *const ()>(a) }; // inner type is a ZST
44+
let _ptr = unsafe { std::mem::transmute::<usize, fn()>(a) }; // omit fn-ptr for now
45+
}
46+
47+
fn main() {}

0 commit comments

Comments
 (0)