Skip to content

Commit f27dba0

Browse files
Lint against &T to &mut T and &T to &UnsafeCell<T> transmutes
This adds the lint against `&T`->`&UnsafeCell<T>` transmutes, and also check in struct fields, and reference casts (`&*(&a as *const u8 as *const UnsafeCell<u8>)`). The code is quite complex; I've tried my best to simplify and comment it. This is missing one parts: array transmutes. When transmuting an array, this only consider the first element. The reason for that is that the code is already quite complex, and I didn't want to complicate it more. This catches the most common pattern of transmuting an array into an array of the same length with type of the same size; more complex cases are likely not properly handled. We could take a bigger sample, for example the first and last elements to increase the chance that the lint will catch mistakes, but then the runtime complexity becomes exponential with the nesting of the arrays (`[[[[[T; 2]; 2]; 2]; 2]; 2]` has complexity of O(2**5), for instance).
1 parent 78c8573 commit f27dba0

33 files changed

+1062
-73
lines changed

compiler/rustc_lint/messages.ftl

+10
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,12 @@ lint_builtin_missing_doc = missing documentation for {$article} {$desc}
119119
120120
lint_builtin_mutable_transmutes =
121121
transmuting &T to &mut T is undefined behavior, even if the reference is unused, consider instead using an UnsafeCell
122+
.note = transmute from `{$from}` to `{$to}`
123+
124+
lint_unsafe_cell_reference_casting =
125+
casting `&T` to `&UnsafeCell<T>` is undefined behavior, even if the reference is unused, consider using an `UnsafeCell` on the original data
126+
.label = casting happend here
127+
.note = cast from `{$from}` to `{$to}`
122128
123129
lint_builtin_no_mangle_fn = declaration of a `no_mangle` function
124130
lint_builtin_no_mangle_generic = functions generic over types or consts must be mangled
@@ -169,6 +175,10 @@ lint_builtin_unreachable_pub = unreachable `pub` {$what}
169175
170176
lint_builtin_unsafe_block = usage of an `unsafe` block
171177
178+
lint_builtin_unsafe_cell_transmutes =
179+
transmuting &T to &UnsafeCell<T> is undefined behavior, even if the reference is unused, consider using UnsafeCell on the original data
180+
.note = transmute from `{$from}` to `{$to}`
181+
172182
lint_builtin_unsafe_extern_block = usage of an `unsafe extern` block
173183
174184
lint_builtin_unsafe_impl = implementation of an `unsafe` trait

compiler/rustc_lint/src/builtin.rs

+3-71
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,9 @@ use crate::{
2929
BuiltinEllipsisInclusiveRangePatternsLint, BuiltinExplicitOutlives,
3030
BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote, BuiltinIncompleteFeatures,
3131
BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures, BuiltinKeywordIdents,
32-
BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc,
33-
BuiltinMutablesTransmutes, BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns,
34-
BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasBounds,
35-
BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit,
32+
BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc, BuiltinNoMangleGeneric,
33+
BuiltinNonShorthandFieldPatterns, BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds,
34+
BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit,
3635
BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub, BuiltinUnsafe,
3736
BuiltinUnstableFeatures, BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub,
3837
BuiltinWhileTrue, InvalidAsmLabel,
@@ -1103,72 +1102,6 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
11031102
}
11041103
}
11051104

1106-
declare_lint! {
1107-
/// The `mutable_transmutes` lint catches transmuting from `&T` to `&mut
1108-
/// T` because it is [undefined behavior].
1109-
///
1110-
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1111-
///
1112-
/// ### Example
1113-
///
1114-
/// ```rust,compile_fail
1115-
/// unsafe {
1116-
/// let y = std::mem::transmute::<&i32, &mut i32>(&5);
1117-
/// }
1118-
/// ```
1119-
///
1120-
/// {{produces}}
1121-
///
1122-
/// ### Explanation
1123-
///
1124-
/// Certain assumptions are made about aliasing of data, and this transmute
1125-
/// violates those assumptions. Consider using [`UnsafeCell`] instead.
1126-
///
1127-
/// [`UnsafeCell`]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html
1128-
MUTABLE_TRANSMUTES,
1129-
Deny,
1130-
"transmuting &T to &mut T is undefined behavior, even if the reference is unused"
1131-
}
1132-
1133-
declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
1134-
1135-
impl<'tcx> LateLintPass<'tcx> for MutableTransmutes {
1136-
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
1137-
if let Some((&ty::Ref(_, _, from_mutbl), &ty::Ref(_, _, to_mutbl))) =
1138-
get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind()))
1139-
{
1140-
if from_mutbl < to_mutbl {
1141-
cx.emit_span_lint(MUTABLE_TRANSMUTES, expr.span, BuiltinMutablesTransmutes);
1142-
}
1143-
}
1144-
1145-
fn get_transmute_from_to<'tcx>(
1146-
cx: &LateContext<'tcx>,
1147-
expr: &hir::Expr<'_>,
1148-
) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
1149-
let def = if let hir::ExprKind::Path(ref qpath) = expr.kind {
1150-
cx.qpath_res(qpath, expr.hir_id)
1151-
} else {
1152-
return None;
1153-
};
1154-
if let Res::Def(DefKind::Fn, did) = def {
1155-
if !def_id_is_transmute(cx, did) {
1156-
return None;
1157-
}
1158-
let sig = cx.typeck_results().node_type(expr.hir_id).fn_sig(cx.tcx);
1159-
let from = sig.inputs().skip_binder()[0];
1160-
let to = sig.output().skip_binder();
1161-
return Some((from, to));
1162-
}
1163-
None
1164-
}
1165-
1166-
fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool {
1167-
cx.tcx.is_intrinsic(def_id, sym::transmute)
1168-
}
1169-
}
1170-
}
1171-
11721105
declare_lint! {
11731106
/// The `unstable_features` lint detects uses of `#![feature]`.
11741107
///
@@ -1615,7 +1548,6 @@ declare_lint_pass!(
16151548
UNUSED_DOC_COMMENTS,
16161549
NO_MANGLE_CONST_ITEMS,
16171550
NO_MANGLE_GENERIC_ITEMS,
1618-
MUTABLE_TRANSMUTES,
16191551
UNSTABLE_FEATURES,
16201552
UNREACHABLE_PUB,
16211553
TYPE_ALIAS_BOUNDS,

compiler/rustc_lint/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ mod macro_expr_fragment_specifier_2024_migration;
6565
mod map_unit_fn;
6666
mod methods;
6767
mod multiple_supertrait_upcastable;
68+
mod mutable_transmutes;
6869
mod non_ascii_idents;
6970
mod non_fmt_panic;
7071
mod non_local_def;
@@ -105,6 +106,7 @@ use macro_expr_fragment_specifier_2024_migration::*;
105106
use map_unit_fn::*;
106107
use methods::*;
107108
use multiple_supertrait_upcastable::*;
109+
use mutable_transmutes::*;
108110
use non_ascii_idents::*;
109111
use non_fmt_panic::NonPanicFmt;
110112
use non_local_def::*;
@@ -209,6 +211,7 @@ late_lint_methods!(
209211
// Depends on referenced function signatures in expressions
210212
PtrNullChecks: PtrNullChecks,
211213
MutableTransmutes: MutableTransmutes,
214+
UnsafeCellReferenceCasting: UnsafeCellReferenceCasting,
212215
TypeAliasBounds: TypeAliasBounds,
213216
TrivialConstraints: TrivialConstraints,
214217
TypeLimits: TypeLimits::new(),

compiler/rustc_lint/src/lints.rs

+26-1
Original file line numberDiff line numberDiff line change
@@ -225,9 +225,34 @@ pub struct BuiltinConstNoMangle {
225225
pub suggestion: Span,
226226
}
227227

228+
// mutable_transmutes.rs
228229
#[derive(LintDiagnostic)]
229230
#[diag(lint_builtin_mutable_transmutes)]
230-
pub struct BuiltinMutablesTransmutes;
231+
#[note]
232+
pub struct BuiltinMutablesTransmutes {
233+
pub from: String,
234+
pub to: String,
235+
}
236+
237+
// mutable_transmutes.rs
238+
#[derive(LintDiagnostic)]
239+
#[diag(lint_builtin_unsafe_cell_transmutes)]
240+
#[note]
241+
pub struct BuiltinUnsafeCellTransmutes {
242+
pub from: String,
243+
pub to: String,
244+
}
245+
246+
// mutable_transmutes.rs
247+
#[derive(LintDiagnostic)]
248+
#[diag(lint_unsafe_cell_reference_casting)]
249+
#[note]
250+
pub struct UnsafeCellReferenceCastingDiag {
251+
#[label]
252+
pub orig_cast: Option<Span>,
253+
pub from: String,
254+
pub to: String,
255+
}
231256

232257
#[derive(LintDiagnostic)]
233258
#[diag(lint_builtin_unstable_features)]

0 commit comments

Comments
 (0)