1 mod crosspointer_transmute;
2 mod transmute_float_to_int;
3 mod transmute_int_to_bool;
4 mod transmute_int_to_char;
5 mod transmute_int_to_float;
6 mod transmute_null_to_fn;
7 mod transmute_num_to_bytes;
8 mod transmute_ptr_to_ptr;
9 mod transmute_ptr_to_ref;
10 mod transmute_ref_to_ref;
11 mod transmute_undefined_repr;
12 mod transmutes_expressible_as_ptr_casts;
14 mod unsound_collection_transmute;
15 mod useless_transmute;
19 use clippy_utils::in_constant;
20 use clippy_utils::msrvs::Msrv;
21 use if_chain::if_chain;
22 use rustc_hir::{Expr, ExprKind, QPath};
23 use rustc_lint::{LateContext, LateLintPass};
24 use rustc_session::{declare_tool_lint, impl_lint_pass};
25 use rustc_span::symbol::sym;
27 declare_clippy_lint! {
29 /// Checks for transmutes that can't ever be correct on any
32 /// ### Why is this bad?
33 /// It's basically guaranteed to be undefined behavior.
35 /// ### Known problems
36 /// When accessing C, users might want to store pointer
37 /// sized objects in `extradata` arguments to save an allocation.
41 /// let ptr: *const T = core::intrinsics::transmute('x')
43 #[clippy::version = "pre 1.29.0"]
46 "transmutes that are confusing at best, undefined behavior at worst and always useless"
49 // FIXME: Move this to `complexity` again, after #5343 is fixed
50 declare_clippy_lint! {
52 /// Checks for transmutes to the original type of the object
53 /// and transmutes that could be a cast.
55 /// ### Why is this bad?
56 /// Readability. The code tricks people into thinking that
57 /// something complex is going on.
61 /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
63 #[clippy::version = "pre 1.29.0"]
64 pub USELESS_TRANSMUTE,
66 "transmutes that have the same to and from types or could be a cast/coercion"
69 // FIXME: Merge this lint with USELESS_TRANSMUTE once that is out of the nursery.
70 declare_clippy_lint! {
72 ///Checks for transmutes that could be a pointer cast.
74 /// ### Why is this bad?
75 /// Readability. The code tricks people into thinking that
76 /// something complex is going on.
81 /// # let p: *const [i32] = &[];
82 /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
86 /// # let p: *const [i32] = &[];
87 /// p as *const [u16];
89 #[clippy::version = "1.47.0"]
90 pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
92 "transmutes that could be a pointer cast"
95 declare_clippy_lint! {
97 /// Checks for transmutes between a type `T` and `*T`.
99 /// ### Why is this bad?
100 /// It's easy to mistakenly transmute between a type and a
101 /// pointer to that type.
105 /// core::intrinsics::transmute(t) // where the result type is the same as
106 /// // `*t` or `&t`'s
108 #[clippy::version = "pre 1.29.0"]
109 pub CROSSPOINTER_TRANSMUTE,
111 "transmutes that have to or from types that are a pointer to the other"
114 declare_clippy_lint! {
116 /// Checks for transmutes from a pointer to a reference.
118 /// ### Why is this bad?
119 /// This can always be rewritten with `&` and `*`.
121 /// ### Known problems
122 /// - `mem::transmute` in statics and constants is stable from Rust 1.46.0,
123 /// while dereferencing raw pointer is not stable yet.
124 /// If you need to do this in those places,
125 /// you would have to use `transmute` instead.
130 /// let _: &T = std::mem::transmute(p); // where p: *const T
133 /// // can be written:
136 #[clippy::version = "pre 1.29.0"]
137 pub TRANSMUTE_PTR_TO_REF,
139 "transmutes from a pointer to a reference type"
142 declare_clippy_lint! {
144 /// Checks for transmutes from an integer to a `char`.
146 /// ### Why is this bad?
147 /// Not every integer is a Unicode scalar value.
149 /// ### Known problems
150 /// - [`from_u32`] which this lint suggests using is slower than `transmute`
151 /// as it needs to validate the input.
152 /// If you are certain that the input is always a valid Unicode scalar value,
153 /// use [`from_u32_unchecked`] which is as fast as `transmute`
154 /// but has a semantically meaningful name.
155 /// - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.
157 /// [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html
158 /// [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html
164 /// let _: char = std::mem::transmute(x); // where x: u32
168 /// let _ = std::char::from_u32(x).unwrap();
170 #[clippy::version = "pre 1.29.0"]
171 pub TRANSMUTE_INT_TO_CHAR,
173 "transmutes from an integer to a `char`"
176 declare_clippy_lint! {
178 /// Checks for transmutes from a `&[u8]` to a `&str`.
180 /// ### Why is this bad?
181 /// Not every byte slice is a valid UTF-8 string.
183 /// ### Known problems
184 /// - [`from_utf8`] which this lint suggests using is slower than `transmute`
185 /// as it needs to validate the input.
186 /// If you are certain that the input is always a valid UTF-8,
187 /// use [`from_utf8_unchecked`] which is as fast as `transmute`
188 /// but has a semantically meaningful name.
189 /// - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.
191 /// [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html
192 /// [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
196 /// let b: &[u8] = &[1_u8, 2_u8];
198 /// let _: &str = std::mem::transmute(b); // where b: &[u8]
202 /// let _ = std::str::from_utf8(b).unwrap();
204 #[clippy::version = "pre 1.29.0"]
205 pub TRANSMUTE_BYTES_TO_STR,
207 "transmutes from a `&[u8]` to a `&str`"
210 declare_clippy_lint! {
212 /// Checks for transmutes from an integer to a `bool`.
214 /// ### Why is this bad?
215 /// This might result in an invalid in-memory representation of a `bool`.
221 /// let _: bool = std::mem::transmute(x); // where x: u8
225 /// let _: bool = x != 0;
227 #[clippy::version = "pre 1.29.0"]
228 pub TRANSMUTE_INT_TO_BOOL,
230 "transmutes from an integer to a `bool`"
233 declare_clippy_lint! {
235 /// Checks for transmutes from an integer to a float.
237 /// ### Why is this bad?
238 /// Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive
244 /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
248 /// let _: f32 = f32::from_bits(1_u32);
250 #[clippy::version = "pre 1.29.0"]
251 pub TRANSMUTE_INT_TO_FLOAT,
253 "transmutes from an integer to a float"
256 declare_clippy_lint! {
258 /// Checks for transmutes from a float to an integer.
260 /// ### Why is this bad?
261 /// Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
267 /// let _: u32 = std::mem::transmute(1f32);
271 /// let _: u32 = 1f32.to_bits();
273 #[clippy::version = "1.41.0"]
274 pub TRANSMUTE_FLOAT_TO_INT,
276 "transmutes from a float to an integer"
279 declare_clippy_lint! {
281 /// Checks for transmutes from a number to an array of `u8`
283 /// ### Why this is bad?
284 /// Transmutes are dangerous and error-prone, whereas `to_ne_bytes`
285 /// is intuitive and safe.
290 /// let x: [u8; 8] = std::mem::transmute(1i64);
294 /// let x: [u8; 8] = 0i64.to_ne_bytes();
296 #[clippy::version = "1.58.0"]
297 pub TRANSMUTE_NUM_TO_BYTES,
299 "transmutes from a number to an array of `u8`"
302 declare_clippy_lint! {
304 /// Checks for transmutes from a pointer to a pointer, or
305 /// from a reference to a reference.
307 /// ### Why is this bad?
308 /// Transmutes are dangerous, and these can instead be
309 /// written as casts.
313 /// let ptr = &1u32 as *const u32;
315 /// // pointer-to-pointer transmute
316 /// let _: *const f32 = std::mem::transmute(ptr);
317 /// // ref-ref transmute
318 /// let _: &f32 = std::mem::transmute(&1u32);
320 /// // These can be respectively written:
321 /// let _ = ptr as *const f32;
322 /// let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };
324 #[clippy::version = "pre 1.29.0"]
325 pub TRANSMUTE_PTR_TO_PTR,
327 "transmutes from a pointer to a pointer / a reference to a reference"
330 declare_clippy_lint! {
332 /// Checks for transmutes between collections whose
333 /// types have different ABI, size or alignment.
335 /// ### Why is this bad?
336 /// This is undefined behavior.
338 /// ### Known problems
339 /// Currently, we cannot know whether a type is a
340 /// collection, so we just lint the ones that come with `std`.
344 /// // different size, therefore likely out-of-bounds memory access
345 /// // You absolutely do not want this in your code!
347 /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
351 /// You must always iterate, map and collect the values:
354 /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
356 #[clippy::version = "1.40.0"]
357 pub UNSOUND_COLLECTION_TRANSMUTE,
359 "transmute between collections of layout-incompatible types"
362 declare_clippy_lint! {
364 /// Checks for transmutes between types which do not have a representation defined relative to
367 /// ### Why is this bad?
368 /// The results of such a transmute are not defined.
370 /// ### Known problems
371 /// This lint has had multiple problems in the past and was moved to `nursery`. See issue
372 /// [#8496](https://github.com/rust-lang/rust-clippy/issues/8496) for more details.
376 /// struct Foo<T>(u32, T);
377 /// let _ = unsafe { core::mem::transmute::<Foo<u32>, Foo<i32>>(Foo(0u32, 0u32)) };
382 /// struct Foo<T>(u32, T);
383 /// let _ = unsafe { core::mem::transmute::<Foo<u32>, Foo<i32>>(Foo(0u32, 0u32)) };
385 #[clippy::version = "1.60.0"]
386 pub TRANSMUTE_UNDEFINED_REPR,
388 "transmute to or from a type with an undefined representation"
391 declare_clippy_lint! {
393 /// Checks for transmute calls which would receive a null pointer.
395 /// ### Why is this bad?
396 /// Transmuting a null pointer is undefined behavior.
398 /// ### Known problems
399 /// Not all cases can be detected at the moment of this writing.
400 /// For example, variables which hold a null pointer and are then fed to a `transmute`
401 /// call, aren't detectable yet.
405 /// let null_ref: &u64 = unsafe { std::mem::transmute(0 as *const u64) };
407 #[clippy::version = "1.35.0"]
408 pub TRANSMUTING_NULL,
410 "transmutes from a null pointer to a reference, which is undefined behavior"
413 declare_clippy_lint! {
415 /// Checks for null function pointer creation through transmute.
417 /// ### Why is this bad?
418 /// Creating a null function pointer is undefined behavior.
420 /// More info: https://doc.rust-lang.org/nomicon/ffi.html#the-nullable-pointer-optimization
422 /// ### Known problems
423 /// Not all cases can be detected at the moment of this writing.
424 /// For example, variables which hold a null pointer and are then fed to a `transmute`
425 /// call, aren't detectable yet.
429 /// let null_fn: fn() = unsafe { std::mem::transmute( std::ptr::null::<()>() ) };
433 /// let null_fn: Option<fn()> = None;
435 #[clippy::version = "1.67.0"]
436 pub TRANSMUTE_NULL_TO_FN,
438 "transmute results in a null function pointer, which is undefined behavior"
441 pub struct Transmute {
444 impl_lint_pass!(Transmute => [
445 CROSSPOINTER_TRANSMUTE,
446 TRANSMUTE_PTR_TO_REF,
447 TRANSMUTE_PTR_TO_PTR,
450 TRANSMUTE_INT_TO_CHAR,
451 TRANSMUTE_BYTES_TO_STR,
452 TRANSMUTE_INT_TO_BOOL,
453 TRANSMUTE_INT_TO_FLOAT,
454 TRANSMUTE_FLOAT_TO_INT,
455 TRANSMUTE_NUM_TO_BYTES,
456 UNSOUND_COLLECTION_TRANSMUTE,
457 TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
458 TRANSMUTE_UNDEFINED_REPR,
460 TRANSMUTE_NULL_TO_FN,
464 pub fn new(msrv: Msrv) -> Self {
468 impl<'tcx> LateLintPass<'tcx> for Transmute {
469 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
471 if let ExprKind::Call(path_expr, [arg]) = e.kind;
472 if let ExprKind::Path(QPath::Resolved(None, path)) = path_expr.kind;
473 if let Some(def_id) = path.res.opt_def_id();
474 if cx.tcx.is_diagnostic_item(sym::transmute, def_id);
476 // Avoid suggesting non-const operations in const contexts:
477 // - from/to bits (https://github.com/rust-lang/rust/issues/73736)
478 // - dereferencing raw pointers (https://github.com/rust-lang/rust/issues/51911)
479 // - char conversions (https://github.com/rust-lang/rust/issues/89259)
480 let const_context = in_constant(cx, e.hir_id);
482 let from_ty = cx.typeck_results().expr_ty_adjusted(arg);
483 // Adjustments for `to_ty` happen after the call to `transmute`, so don't use them.
484 let to_ty = cx.typeck_results().expr_ty(e);
486 // If useless_transmute is triggered, the other lints can be skipped.
487 if useless_transmute::check(cx, e, from_ty, to_ty, arg) {
491 let linted = wrong_transmute::check(cx, e, from_ty, to_ty)
492 | crosspointer_transmute::check(cx, e, from_ty, to_ty)
493 | transmuting_null::check(cx, e, arg, to_ty)
494 | transmute_null_to_fn::check(cx, e, arg, to_ty)
495 | transmute_ptr_to_ref::check(cx, e, from_ty, to_ty, arg, path, &self.msrv)
496 | transmute_int_to_char::check(cx, e, from_ty, to_ty, arg, const_context)
497 | transmute_ref_to_ref::check(cx, e, from_ty, to_ty, arg, const_context)
498 | transmute_ptr_to_ptr::check(cx, e, from_ty, to_ty, arg)
499 | transmute_int_to_bool::check(cx, e, from_ty, to_ty, arg)
500 | transmute_int_to_float::check(cx, e, from_ty, to_ty, arg, const_context)
501 | transmute_float_to_int::check(cx, e, from_ty, to_ty, arg, const_context)
502 | transmute_num_to_bytes::check(cx, e, from_ty, to_ty, arg, const_context)
504 unsound_collection_transmute::check(cx, e, from_ty, to_ty)
505 || transmute_undefined_repr::check(cx, e, from_ty, to_ty)
509 transmutes_expressible_as_ptr_casts::check(cx, e, from_ty, to_ty, arg);
515 extract_msrv_attr!(LateContext);