Auto merge of #8632 - Jarcho:cast_ptr_alignment, r=llogiq

Don't lint `cast_ptr_alignment` when used for unaligned reads and writes

fixes #2881

Ideally this would trace the usage of the value rather than only looking at the parent expression, but that would require dataflow analysis. e.g.
```rust
let x = ptr as *const u16;
c.read_unaligned(x);
```

Arch specific intrinsic functions need to be checked for ones which could take an unaligned pointer. This can be another PR.

changelog: Don't lint `cast_ptr_alignment` when used for unaligned reads and writes
This commit is contained in:
bors 2022-04-04 18:47:27 +00:00
commit 9fd1cdeada
4 changed files with 86 additions and 38 deletions

View File

@ -1,7 +1,6 @@
use clippy_utils::diagnostics::span_lint;
use clippy_utils::is_hir_ty_cfg_dependant;
use clippy_utils::ty::is_c_void;
use if_chain::if_chain;
use clippy_utils::{get_parent_expr, is_hir_ty_cfg_dependant, match_any_def_paths, paths};
use rustc_hir::{Expr, ExprKind, GenericArg};
use rustc_lint::LateContext;
use rustc_middle::ty::layout::LayoutOf;
@ -20,45 +19,78 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>) {
);
lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
} else if let ExprKind::MethodCall(method_path, [self_arg, ..], _) = &expr.kind {
if_chain! {
if method_path.ident.name == sym!(cast);
if let Some(generic_args) = method_path.args;
if let [GenericArg::Type(cast_to)] = generic_args.args;
if method_path.ident.name == sym!(cast)
&& let Some(generic_args) = method_path.args
&& let [GenericArg::Type(cast_to)] = generic_args.args
// There probably is no obvious reason to do this, just to be consistent with `as` cases.
if !is_hir_ty_cfg_dependant(cx, cast_to);
then {
let (cast_from, cast_to) =
(cx.typeck_results().expr_ty(self_arg), cx.typeck_results().expr_ty(expr));
lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
}
&& !is_hir_ty_cfg_dependant(cx, cast_to)
{
let (cast_from, cast_to) =
(cx.typeck_results().expr_ty(self_arg), cx.typeck_results().expr_ty(expr));
lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
}
}
}
fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
if_chain! {
if let ty::RawPtr(from_ptr_ty) = &cast_from.kind();
if let ty::RawPtr(to_ptr_ty) = &cast_to.kind();
if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
if from_layout.align.abi < to_layout.align.abi;
if let ty::RawPtr(from_ptr_ty) = &cast_from.kind()
&& let ty::RawPtr(to_ptr_ty) = &cast_to.kind()
&& let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty)
&& let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty)
&& from_layout.align.abi < to_layout.align.abi
// with c_void, we inherently need to trust the user
if !is_c_void(cx, from_ptr_ty.ty);
&& !is_c_void(cx, from_ptr_ty.ty)
// when casting from a ZST, we don't know enough to properly lint
if !from_layout.is_zst();
then {
span_lint(
cx,
CAST_PTR_ALIGNMENT,
expr.span,
&format!(
"casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
cast_from,
cast_to,
from_layout.align.abi.bytes(),
to_layout.align.abi.bytes(),
),
);
}
&& !from_layout.is_zst()
&& !is_used_as_unaligned(cx, expr)
{
span_lint(
cx,
CAST_PTR_ALIGNMENT,
expr.span,
&format!(
"casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
cast_from,
cast_to,
from_layout.align.abi.bytes(),
to_layout.align.abi.bytes(),
),
);
}
}
fn is_used_as_unaligned(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
let Some(parent) = get_parent_expr(cx, e) else {
return false;
};
match parent.kind {
ExprKind::MethodCall(name, [self_arg, ..], _) if self_arg.hir_id == e.hir_id => {
if matches!(name.ident.as_str(), "read_unaligned" | "write_unaligned")
&& let Some(def_id) = cx.typeck_results().type_dependent_def_id(parent.hir_id)
&& let Some(def_id) = cx.tcx.impl_of_method(def_id)
&& cx.tcx.type_of(def_id).is_unsafe_ptr()
{
true
} else {
false
}
},
ExprKind::Call(func, [arg, ..]) if arg.hir_id == e.hir_id => {
static PATHS: &[&[&str]] = &[
paths::PTR_READ_UNALIGNED.as_slice(),
paths::PTR_WRITE_UNALIGNED.as_slice(),
paths::PTR_UNALIGNED_VOLATILE_LOAD.as_slice(),
paths::PTR_UNALIGNED_VOLATILE_STORE.as_slice(),
];
if let ExprKind::Path(path) = &func.kind
&& let Some(def_id) = cx.qpath_res(path, func.hir_id).opt_def_id()
&& match_any_def_paths(cx, def_id, PATHS).is_some()
{
true
} else {
false
}
},
_ => false,
}
}

View File

@ -105,6 +105,8 @@
pub const PTR_READ_VOLATILE: [&str; 3] = ["core", "ptr", "read_volatile"];
pub const PTR_REPLACE: [&str; 3] = ["core", "ptr", "replace"];
pub const PTR_SWAP: [&str; 3] = ["core", "ptr", "swap"];
pub const PTR_UNALIGNED_VOLATILE_LOAD: [&str; 3] = ["core", "intrinsics", "unaligned_volatile_load"];
pub const PTR_UNALIGNED_VOLATILE_STORE: [&str; 3] = ["core", "intrinsics", "unaligned_volatile_store"];
pub const PTR_WRITE: [&str; 3] = ["core", "ptr", "write"];
pub const PTR_WRITE_BYTES: [&str; 3] = ["core", "intrinsics", "write_bytes"];
pub const PTR_WRITE_UNALIGNED: [&str; 3] = ["core", "ptr", "write_unaligned"];

View File

@ -1,6 +1,7 @@
//! Test casts for alignment issues
#![feature(rustc_private)]
#![feature(core_intrinsics)]
extern crate libc;
#[warn(clippy::cast_ptr_alignment)]
@ -34,4 +35,17 @@ fn main() {
(&1u32 as *const u32 as *const libc::c_void) as *const u32;
// For ZST, we should trust the user. See #4256
(&1u32 as *const u32 as *const ()) as *const u32;
// Issue #2881
let mut data = [0u8, 0u8];
unsafe {
let ptr = &data as *const [u8; 2] as *const u8;
let _ = (ptr as *const u16).read_unaligned();
let _ = core::ptr::read_unaligned(ptr as *const u16);
let _ = core::intrinsics::unaligned_volatile_load(ptr as *const u16);
let ptr = &mut data as *mut [u8; 2] as *mut u8;
let _ = (ptr as *mut u16).write_unaligned(0);
let _ = core::ptr::write_unaligned(ptr as *mut u16, 0);
let _ = core::intrinsics::unaligned_volatile_store(ptr as *mut u16, 0);
}
}

View File

@ -1,5 +1,5 @@
error: casting from `*const u8` to a more-strictly-aligned pointer (`*const u16`) (1 < 2 bytes)
--> $DIR/cast_alignment.rs:18:5
--> $DIR/cast_alignment.rs:19:5
|
LL | (&1u8 as *const u8) as *const u16;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@ -7,19 +7,19 @@ LL | (&1u8 as *const u8) as *const u16;
= note: `-D clippy::cast-ptr-alignment` implied by `-D warnings`
error: casting from `*mut u8` to a more-strictly-aligned pointer (`*mut u16`) (1 < 2 bytes)
--> $DIR/cast_alignment.rs:19:5
--> $DIR/cast_alignment.rs:20:5
|
LL | (&mut 1u8 as *mut u8) as *mut u16;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: casting from `*const u8` to a more-strictly-aligned pointer (`*const u16`) (1 < 2 bytes)
--> $DIR/cast_alignment.rs:22:5
--> $DIR/cast_alignment.rs:23:5
|
LL | (&1u8 as *const u8).cast::<u16>();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: casting from `*mut u8` to a more-strictly-aligned pointer (`*mut u16`) (1 < 2 bytes)
--> $DIR/cast_alignment.rs:23:5
--> $DIR/cast_alignment.rs:24:5
|
LL | (&mut 1u8 as *mut u8).cast::<u16>();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^