1use rustc_ast::LitKind;
2use rustc_errors::Applicability;
3use rustc_hir as hir;
4use rustc_hir::def::{DefKind, Res};
5use rustc_hir::def_id::LocalDefId;
6use rustc_lint_defs::{declare_lint, impl_lint_pass};
7use rustc_macros::Diagnostic;
8use rustc_middle::ty::{self, Ty};
9use rustc_span::sym;
10
11use crate::diagnostics::{
12 IntegerToPtrTransmutes, IntegerToPtrTransmutesSuggestion, IntegerToPtrWithoutProvHelp,
13};
14use crate::utils::std_or_core;
15use crate::{LateContext, LateLintPass};
16
17#[doc =
r" The `ptr_to_integer_transmute_in_consts` lint detects pointer to integer"]
#[doc = r" transmute in const functions and associated constants."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" const fn foo(ptr: *const u8) -> usize {"]
#[doc = r" unsafe {"]
#[doc = r" std::mem::transmute::<*const u8, usize>(ptr)"]
#[doc = r" }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Transmuting pointers to integers in a `const` context is undefined behavior."]
#[doc =
r" Any attempt to use the resulting integer will abort const-evaluation."]
#[doc = r""]
#[doc =
r" But sometimes the compiler might not emit an error for pointer to integer transmutes"]
#[doc =
r" inside const functions and associated consts because they are evaluated only when referenced."]
#[doc =
r" Therefore, this lint serves as an extra layer of defense to prevent any undefined behavior"]
#[doc = r" from compiling without any warnings or errors."]
#[doc = r""]
#[doc = r" See [std::mem::transmute] in the reference for more details."]
#[doc = r""]
#[doc =
r" [std::mem::transmute]: https://doc.rust-lang.org/std/mem/fn.transmute.html"]
pub static PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS",
default_level: ::rustc_lint_defs::Warn,
desc: "detects pointer to integer transmutes in const functions and associated constants",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
18 pub PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS,
47 Warn,
48 "detects pointer to integer transmutes in const functions and associated constants",
49}
50
51#[doc =
r" The `unnecessary_transmutes` lint detects transmutations that have safer alternatives."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn bytes_at_home(x: [u8; 4]) -> u32 {"]
#[doc = r" unsafe { std::mem::transmute(x) }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Using an explicit method is preferable over calls to"]
#[doc =
r" [`transmute`](https://doc.rust-lang.org/std/mem/fn.transmute.html) as"]
#[doc =
r" they more clearly communicate the intent, are easier to review, and"]
#[doc = r" are less likely to accidentally result in unsoundness."]
pub static UNNECESSARY_TRANSMUTES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNNECESSARY_TRANSMUTES",
default_level: ::rustc_lint_defs::Warn,
desc: "detects transmutes that can also be achieved by other operations",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
52 pub UNNECESSARY_TRANSMUTES,
71 Warn,
72 "detects transmutes that can also be achieved by other operations"
73}
74
75#[doc = r" The `integer_to_ptr_transmutes` lint detects integer to pointer"]
#[doc =
r" transmutes where the resulting pointers are undefined behavior to dereference."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn foo(a: usize) -> *const u8 {"]
#[doc = r" unsafe {"]
#[doc = r" std::mem::transmute::<usize, *const u8>(a)"]
#[doc = r" }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Any attempt to use the resulting pointers are undefined behavior as the resulting"]
#[doc = r" pointers won't have any provenance."]
#[doc = r""]
#[doc =
r" Alternatively, [`std::ptr::with_exposed_provenance`] should be used, as they do not"]
#[doc =
r" carry the provenance requirement. If wanting to create pointers without provenance"]
#[doc = r" [`std::ptr::without_provenance`] should be used instead."]
#[doc = r""]
#[doc = r" See [`std::mem::transmute`] in the reference for more details."]
#[doc = r""]
#[doc =
r" [`std::mem::transmute`]: https://doc.rust-lang.org/std/mem/fn.transmute.html"]
#[doc =
r" [`std::ptr::with_exposed_provenance`]: https://doc.rust-lang.org/std/ptr/fn.with_exposed_provenance.html"]
#[doc =
r" [`std::ptr::without_provenance`]: https://doc.rust-lang.org/std/ptr/fn.without_provenance.html"]
pub static INTEGER_TO_PTR_TRANSMUTES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "INTEGER_TO_PTR_TRANSMUTES",
default_level: ::rustc_lint_defs::Warn,
desc: "detects integer to pointer transmutes",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
76 pub INTEGER_TO_PTR_TRANSMUTES,
106 Warn,
107 "detects integer to pointer transmutes",
108}
109
110pub(crate) struct CheckTransmutes;
111
112impl ::rustc_lint_defs::LintPass for CheckTransmutes {
fn name(&self) -> &'static str { "CheckTransmutes" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS, UNNECESSARY_TRANSMUTES,
INTEGER_TO_PTR_TRANSMUTES]))
}
}
impl CheckTransmutes {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS, UNNECESSARY_TRANSMUTES,
INTEGER_TO_PTR_TRANSMUTES]))
}
}impl_lint_pass!(CheckTransmutes => [PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS, UNNECESSARY_TRANSMUTES, INTEGER_TO_PTR_TRANSMUTES]);
113
114impl<'tcx> LateLintPass<'tcx> for CheckTransmutes {
115 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
116 let hir::ExprKind::Call(callee, [arg]) = expr.kind else {
117 return;
118 };
119 let hir::ExprKind::Path(qpath) = callee.kind else {
120 return;
121 };
122 let Res::Def(DefKind::Fn, def_id) = cx.qpath_res(&qpath, callee.hir_id) else {
123 return;
124 };
125 if !cx.tcx.is_intrinsic(def_id, sym::transmute) {
126 return;
127 };
128 let body_owner_def_id = cx.tcx.hir_enclosing_body_owner(expr.hir_id);
129 let const_context = cx.tcx.hir_body_const_context(body_owner_def_id);
130 let args = cx.typeck_results().node_args(callee.hir_id);
131
132 let src = args.type_at(0);
133 let dst = args.type_at(1);
134
135 check_ptr_transmute_in_const(cx, expr, body_owner_def_id, const_context, src, dst);
136 check_unnecessary_transmute(cx, expr, callee, arg, const_context, src, dst);
137 check_int_to_ptr_transmute(cx, expr, arg, src, dst);
138 }
139}
140
141fn check_int_to_ptr_transmute<'tcx>(
145 cx: &LateContext<'tcx>,
146 expr: &'tcx hir::Expr<'tcx>,
147 arg: &'tcx hir::Expr<'tcx>,
148 src: Ty<'tcx>,
149 dst: Ty<'tcx>,
150) {
151 if !#[allow(non_exhaustive_omitted_patterns)] match src.kind() {
ty::Uint(_) | ty::Int(_) => true,
_ => false,
}matches!(src.kind(), ty::Uint(_) | ty::Int(_)) {
152 return;
153 }
154 let (ty::Ref(_, inner_ty, mutbl) | ty::RawPtr(inner_ty, mutbl)) = dst.kind() else {
155 return;
156 };
157 if let hir::ExprKind::Lit(hir::Lit { node: LitKind::Int(v, _), .. }) = arg.kind
159 && v == 0
160 {
161 return;
162 }
163 let Ok(layout_inner_ty) = cx.tcx.layout_of(cx.typing_env().as_query_input(*inner_ty)) else {
165 return;
166 };
167 if layout_inner_ty.is_1zst() {
168 return;
169 }
170
171 let suffix = if mutbl.is_mut() { "_mut" } else { "" };
172 let krate = std_or_core(cx);
173 cx.tcx.emit_node_span_lint(
174 INTEGER_TO_PTR_TRANSMUTES,
175 expr.hir_id,
176 expr.span,
177 IntegerToPtrTransmutes {
178 without_prov: krate.map(|krate| IntegerToPtrWithoutProvHelp { krate }),
179 suggestion: match (krate, layout_inner_ty.is_sized()) {
180 (Some(krate), true) if dst.is_ref() => {
181 Some(IntegerToPtrTransmutesSuggestion::ToRef {
182 krate,
183 dst: *inner_ty,
184 suffix,
185 ref_mutbl: mutbl.prefix_str(),
186 start_call: expr.span.shrink_to_lo().until(arg.span),
187 })
188 }
189 (Some(krate), true) => Some(IntegerToPtrTransmutesSuggestion::ToPtr {
190 krate,
191 dst: *inner_ty,
192 suffix,
193 start_call: expr.span.shrink_to_lo().until(arg.span),
194 }),
195 _ => None,
196 },
197 },
198 );
199}
200
201fn check_ptr_transmute_in_const<'tcx>(
214 cx: &LateContext<'tcx>,
215 expr: &'tcx hir::Expr<'tcx>,
216 body_owner_def_id: LocalDefId,
217 const_context: Option<hir::ConstContext>,
218 src: Ty<'tcx>,
219 dst: Ty<'tcx>,
220) {
221 if #[allow(non_exhaustive_omitted_patterns)] match const_context {
Some(hir::ConstContext::ConstFn) => true,
_ => false,
}matches!(const_context, Some(hir::ConstContext::ConstFn))
222 || cx.tcx.def_kind(body_owner_def_id) == DefKind::AssocConst
223 {
224 if src.is_raw_ptr() && dst.is_integral() {
225 cx.tcx.emit_node_span_lint(
226 PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS,
227 expr.hir_id,
228 expr.span,
229 UndefinedTransmuteLint,
230 );
231 }
232 }
233}
234
235fn check_unnecessary_transmute<'tcx>(
240 cx: &LateContext<'tcx>,
241 expr: &'tcx hir::Expr<'tcx>,
242 callee: &'tcx hir::Expr<'tcx>,
243 arg: &'tcx hir::Expr<'tcx>,
244 const_context: Option<hir::ConstContext>,
245 src: Ty<'tcx>,
246 dst: Ty<'tcx>,
247) {
248 let callee_span = callee.span.find_ancestor_inside(expr.span).unwrap_or(callee.span);
249 let (sugg, help) = match (src.kind(), dst.kind()) {
250 (ty::Array(t, _), ty::Uint(_) | ty::Float(_) | ty::Int(_))
253 if *t.kind() == ty::Uint(ty::UintTy::U8) =>
254 {
255 (
256 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::from_ne_bytes",
dst))
}))]))vec![(callee_span, format!("{dst}::from_ne_bytes"))]),
257 Some(
258 "there's also `from_le_bytes` and `from_be_bytes` if you expect a particular byte order",
259 ),
260 )
261 }
262 (ty::Uint(_) | ty::Float(_) | ty::Int(_), ty::Array(t, _))
264 if *t.kind() == ty::Uint(ty::UintTy::U8) =>
265 {
266 (
267 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::to_ne_bytes", src))
}))]))vec![(callee_span, format!("{src}::to_ne_bytes"))]),
268 Some(
269 "there's also `to_le_bytes` and `to_be_bytes` if you expect a particular byte order",
270 ),
271 )
272 }
273 (ty::Char, ty::Uint(ty::UintTy::U32)) => {
275 (Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span, "u32::from".to_string())]))vec![(callee_span, "u32::from".to_string())]), None)
276 }
277 (ty::Char, ty::Int(ty::IntTy::I32)) => (
279 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span, "u32::from".to_string()),
(expr.span.shrink_to_hi(), ".cast_signed()".to_string())]))vec![
280 (callee_span, "u32::from".to_string()),
281 (expr.span.shrink_to_hi(), ".cast_signed()".to_string()),
282 ]),
283 None,
284 ),
285 (ty::Uint(ty::UintTy::U32), ty::Char) => (
287 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span, "char::from_u32_unchecked".to_string())]))vec![(callee_span, "char::from_u32_unchecked".to_string())]),
288 Some("consider using `char::from_u32(…).unwrap()`"),
289 ),
290 (ty::Int(ty::IntTy::I32), ty::Char) => (
292 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
"char::from_u32_unchecked(i32::cast_unsigned".to_string()),
(expr.span.shrink_to_hi(), ")".to_string())]))vec![
293 (callee_span, "char::from_u32_unchecked(i32::cast_unsigned".to_string()),
294 (expr.span.shrink_to_hi(), ")".to_string()),
295 ]),
296 Some("consider using `char::from_u32(i32::cast_unsigned(…)).unwrap()`"),
297 ),
298 (ty::Uint(_), ty::Int(_)) => {
300 (Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::cast_signed", src))
}))]))vec![(callee_span, format!("{src}::cast_signed"))]), None)
301 }
302 (ty::Int(_), ty::Uint(_)) => {
304 (Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::cast_unsigned",
src))
}))]))vec![(callee_span, format!("{src}::cast_unsigned"))]), None)
305 }
306 (ty::Float(_), ty::Uint(ty::UintTy::Usize) | ty::Int(ty::IntTy::Isize)) => (
308 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::to_bits", src))
})),
(expr.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", dst))
}))]))vec![
309 (callee_span, format!("{src}::to_bits")),
310 (expr.span.shrink_to_hi(), format!(" as {dst}")),
311 ]),
312 None,
313 ),
314 (ty::Float(_), ty::Int(..)) => (
316 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::to_bits", src))
})),
(expr.span.shrink_to_hi(), ".cast_signed()".to_string())]))vec![
317 (callee_span, format!("{src}::to_bits")),
318 (expr.span.shrink_to_hi(), ".cast_signed()".to_string()),
319 ]),
320 None,
321 ),
322 (ty::Float(_), ty::Uint(..)) => {
324 (Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::to_bits", src))
}))]))vec![(callee_span, format!("{src}::to_bits"))]), None)
325 }
326 (ty::Uint(ty::UintTy::Usize) | ty::Int(ty::IntTy::Isize), ty::Float(_)) => (
328 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::from_bits", dst))
})), (arg.span.shrink_to_hi(), " as _".to_string())]))vec![
329 (callee_span, format!("{dst}::from_bits")),
330 (arg.span.shrink_to_hi(), " as _".to_string()),
331 ]),
332 None,
333 ),
334 (ty::Int(_), ty::Float(_)) => (
336 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::from_bits({1}::cast_unsigned",
dst, src))
})), (expr.span.shrink_to_hi(), ")".to_string())]))vec![
337 (callee_span, format!("{dst}::from_bits({src}::cast_unsigned")),
338 (expr.span.shrink_to_hi(), ")".to_string()),
339 ]),
340 None,
341 ),
342 (ty::Uint(_), ty::Float(_)) => {
344 (Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::from_bits", dst))
}))]))vec![(callee_span, format!("{dst}::from_bits"))]), None)
345 }
346 (ty::Bool, ty::Int(..) | ty::Uint(..)) if const_context.is_some() => (
350 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span, "".to_string()),
(expr.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", dst))
}))]))vec![
351 (callee_span, "".to_string()),
352 (expr.span.shrink_to_hi(), format!(" as {dst}")),
353 ]),
354 None,
355 ),
356 (ty::Bool, ty::Int(..) | ty::Uint(..)) => {
358 (Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(callee_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::from", dst))
}))]))vec![(callee_span, format!("{dst}::from"))]), None)
359 }
360 _ => return,
361 };
362
363 cx.tcx.emit_node_span_lint(
364 UNNECESSARY_TRANSMUTES,
365 expr.hir_id,
366 expr.span,
367 rustc_errors::DiagDecorator(|diag| {
368 diag.primary_message("unnecessary transmute");
369 if let Some(sugg) = sugg {
370 diag.multipart_suggestion(
371 "replace this with",
372 sugg,
373 Applicability::MachineApplicable,
374 );
375 }
376 if let Some(help) = help {
377 diag.help(help);
378 }
379 }),
380 );
381}
382
383#[derive(const _: () =
{
impl<'_sess> rustc_errors::Diagnostic<'_sess> for
UndefinedTransmuteLint {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
match self {
UndefinedTransmuteLint => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("pointers cannot be transmuted to integers during const eval")));
diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("at compile-time, pointers do not have an integer value")));
diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("avoiding this restriction via `union` or raw pointers leads to compile-time undefined behavior")));
diag.help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("for more information, see https://doc.rust-lang.org/std/mem/fn.transmute.html")));
;
diag
}
}
}
}
};Diagnostic)]
384#[diag("pointers cannot be transmuted to integers during const eval")]
385#[note("at compile-time, pointers do not have an integer value")]
386#[note(
387 "avoiding this restriction via `union` or raw pointers leads to compile-time undefined behavior"
388)]
389#[help("for more information, see https://doc.rust-lang.org/std/mem/fn.transmute.html")]
390pub(crate) struct UndefinedTransmuteLint;