Skip to content

Commit 573ee3f

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 3a85d3f commit 573ee3f

20 files changed

+1127
-93
lines changed

compiler/rustc_lint/messages.ftl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ 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}`
122123
123124
lint_builtin_no_mangle_fn = declaration of a `no_mangle` function
124125
lint_builtin_no_mangle_generic = functions generic over types or consts must be mangled
@@ -889,6 +890,11 @@ lint_unsafe_attr_outside_unsafe = unsafe attribute used without unsafe
889890
.label = usage of unsafe attribute
890891
lint_unsafe_attr_outside_unsafe_suggestion = wrap the attribute in `unsafe(...)`
891892
893+
lint_unsafe_cell_transmutes =
894+
transmuting &T to &UnsafeCell<T> is error-prone, rarely intentional and may cause undefined behavior
895+
.label = transmuting happend here
896+
.note = transmute from `{$from}` to `{$to}`
897+
892898
lint_unsupported_group = `{$lint_group}` lint group is not supported with ´--force-warn´
893899
894900
lint_untranslatable_diag = diagnostics should be created using translatable messages

compiler/rustc_lint/src/builtin.rs

Lines changed: 5 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,11 @@ use crate::lints::{
6161
BuiltinEllipsisInclusiveRangePatternsLint, BuiltinExplicitOutlives,
6262
BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote, BuiltinIncompleteFeatures,
6363
BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures, BuiltinKeywordIdents,
64-
BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc, BuiltinMutablesTransmutes,
65-
BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns, BuiltinSpecialModuleNameUsed,
66-
BuiltinTrivialBounds, BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller,
67-
BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub,
68-
BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub,
69-
BuiltinWhileTrue, InvalidAsmLabel,
64+
BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc, BuiltinNoMangleGeneric,
65+
BuiltinNonShorthandFieldPatterns, BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds,
66+
BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit,
67+
BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures,
68+
BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel,
7069
};
7170
use crate::nonstandard_style::{MethodLateContext, method_context};
7271
use crate::{
@@ -1082,72 +1081,6 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
10821081
}
10831082
}
10841083

1085-
declare_lint! {
1086-
/// The `mutable_transmutes` lint catches transmuting from `&T` to `&mut
1087-
/// T` because it is [undefined behavior].
1088-
///
1089-
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1090-
///
1091-
/// ### Example
1092-
///
1093-
/// ```rust,compile_fail
1094-
/// unsafe {
1095-
/// let y = std::mem::transmute::<&i32, &mut i32>(&5);
1096-
/// }
1097-
/// ```
1098-
///
1099-
/// {{produces}}
1100-
///
1101-
/// ### Explanation
1102-
///
1103-
/// Certain assumptions are made about aliasing of data, and this transmute
1104-
/// violates those assumptions. Consider using [`UnsafeCell`] instead.
1105-
///
1106-
/// [`UnsafeCell`]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html
1107-
MUTABLE_TRANSMUTES,
1108-
Deny,
1109-
"transmuting &T to &mut T is undefined behavior, even if the reference is unused"
1110-
}
1111-
1112-
declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
1113-
1114-
impl<'tcx> LateLintPass<'tcx> for MutableTransmutes {
1115-
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
1116-
if let Some((&ty::Ref(_, _, from_mutbl), &ty::Ref(_, _, to_mutbl))) =
1117-
get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind()))
1118-
{
1119-
if from_mutbl < to_mutbl {
1120-
cx.emit_span_lint(MUTABLE_TRANSMUTES, expr.span, BuiltinMutablesTransmutes);
1121-
}
1122-
}
1123-
1124-
fn get_transmute_from_to<'tcx>(
1125-
cx: &LateContext<'tcx>,
1126-
expr: &hir::Expr<'_>,
1127-
) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
1128-
let def = if let hir::ExprKind::Path(ref qpath) = expr.kind {
1129-
cx.qpath_res(qpath, expr.hir_id)
1130-
} else {
1131-
return None;
1132-
};
1133-
if let Res::Def(DefKind::Fn, did) = def {
1134-
if !def_id_is_transmute(cx, did) {
1135-
return None;
1136-
}
1137-
let sig = cx.typeck_results().node_type(expr.hir_id).fn_sig(cx.tcx);
1138-
let from = sig.inputs().skip_binder()[0];
1139-
let to = sig.output().skip_binder();
1140-
return Some((from, to));
1141-
}
1142-
None
1143-
}
1144-
1145-
fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool {
1146-
cx.tcx.is_intrinsic(def_id, sym::transmute)
1147-
}
1148-
}
1149-
}
1150-
11511084
declare_lint! {
11521085
/// The `unstable_features` lint detects uses of `#![feature]`.
11531086
///
@@ -1581,7 +1514,6 @@ declare_lint_pass!(
15811514
UNUSED_DOC_COMMENTS,
15821515
NO_MANGLE_CONST_ITEMS,
15831516
NO_MANGLE_GENERIC_ITEMS,
1584-
MUTABLE_TRANSMUTES,
15851517
UNSTABLE_FEATURES,
15861518
UNREACHABLE_PUB,
15871519
TYPE_ALIAS_BOUNDS,

compiler/rustc_lint/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ mod macro_expr_fragment_specifier_2024_migration;
6767
mod map_unit_fn;
6868
mod methods;
6969
mod multiple_supertrait_upcastable;
70+
mod mutable_transmutes;
7071
mod non_ascii_idents;
7172
mod non_fmt_panic;
7273
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::*;

compiler/rustc_lint/src/lints.rs

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ use std::num::NonZero;
55
use rustc_errors::codes::*;
66
use rustc_errors::{
77
Applicability, Diag, DiagArgValue, DiagMessage, DiagStyledString, ElidedLifetimeInPathSubdiag,
8-
EmissionGuarantee, LintDiagnostic, MultiSpan, SubdiagMessageOp, Subdiagnostic, SuggestionStyle,
8+
EmissionGuarantee, IntoDiagArg, LintDiagnostic, MultiSpan, SubdiagMessageOp, Subdiagnostic,
9+
SuggestionStyle,
910
};
1011
use rustc_hir::def::Namespace;
1112
use rustc_hir::def_id::DefId;
@@ -224,9 +225,39 @@ pub(crate) struct BuiltinConstNoMangle {
224225
pub suggestion: Span,
225226
}
226227

228+
// This would be more convenient as `from: String` and `to: String`, but then we'll ICE for formatting a `Ty`
229+
// when the lint is `#[allow]`ed.
230+
pub(crate) struct TransmuteBreadcrumbs<'a> {
231+
pub before_ty: &'static str,
232+
pub ty: Ty<'a>,
233+
pub after_ty: String,
234+
}
235+
236+
impl IntoDiagArg for TransmuteBreadcrumbs<'_> {
237+
fn into_diag_arg(self) -> DiagArgValue {
238+
format!("{}{}{}", self.before_ty, self.ty, self.after_ty).into_diag_arg()
239+
}
240+
}
241+
242+
// mutable_transmutes.rs
227243
#[derive(LintDiagnostic)]
228244
#[diag(lint_builtin_mutable_transmutes)]
229-
pub(crate) struct BuiltinMutablesTransmutes;
245+
#[note]
246+
pub(crate) struct BuiltinMutablesTransmutes<'a> {
247+
pub from: TransmuteBreadcrumbs<'a>,
248+
pub to: TransmuteBreadcrumbs<'a>,
249+
}
250+
251+
// mutable_transmutes.rs
252+
#[derive(LintDiagnostic)]
253+
#[diag(lint_unsafe_cell_transmutes)]
254+
#[note]
255+
pub(crate) struct UnsafeCellTransmutes<'a> {
256+
#[label]
257+
pub orig_cast: Option<Span>,
258+
pub from: TransmuteBreadcrumbs<'a>,
259+
pub to: TransmuteBreadcrumbs<'a>,
260+
}
230261

231262
#[derive(LintDiagnostic)]
232263
#[diag(lint_builtin_unstable_features)]

0 commit comments

Comments
 (0)