diff --git a/clippy_lints/src/strlen_on_c_strings.rs b/clippy_lints/src/strlen_on_c_strings.rs index dc28bb97400..fee01fb0bd1 100644 --- a/clippy_lints/src/strlen_on_c_strings.rs +++ b/clippy_lints/src/strlen_on_c_strings.rs @@ -1,10 +1,11 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::match_libc_symbol; use clippy_utils::source::snippet_with_context; use clippy_utils::ty::is_type_diagnostic_item; +use clippy_utils::visitors::is_expr_unsafe; +use clippy_utils::{get_parent_node, match_libc_symbol}; use if_chain::if_chain; use rustc_errors::Applicability; -use rustc_hir as hir; +use rustc_hir::{Block, BlockCheckMode, Expr, ExprKind, Node, UnsafeSource}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::sym; @@ -39,20 +40,31 @@ declare_lint_pass!(StrlenOnCStrings => [STRLEN_ON_C_STRINGS]); impl LateLintPass<'tcx> for StrlenOnCStrings { - fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if_chain! { if !expr.span.from_expansion(); - if let hir::ExprKind::Call(func, [recv]) = expr.kind; - if let hir::ExprKind::Path(path) = &func.kind; + if let ExprKind::Call(func, [recv]) = expr.kind; + if let ExprKind::Path(path) = &func.kind; if let Some(did) = cx.qpath_res(path, func.hir_id).opt_def_id(); if match_libc_symbol(cx, did, "strlen"); - if let hir::ExprKind::MethodCall(path, _, [self_arg], _) = recv.kind; + if let ExprKind::MethodCall(path, _, [self_arg], _) = recv.kind; if !recv.span.from_expansion(); if path.ident.name == sym::as_ptr; then { + let ctxt = expr.span.ctxt(); + let span = match get_parent_node(cx.tcx, expr.hir_id) { + Some(Node::Block(&Block { + rules: BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided), span, .. + })) + if span.ctxt() == ctxt && !is_expr_unsafe(cx, self_arg) => { + span + } + _ => expr.span, + }; + let ty = cx.typeck_results().expr_ty(self_arg).peel_refs(); - let mut app = Applicability::Unspecified; - let val_name = snippet_with_context(cx, self_arg.span, expr.span.ctxt(), "..", &mut app).0; + let mut app = Applicability::MachineApplicable; + let val_name = snippet_with_context(cx, self_arg.span, ctxt, "..", &mut app).0; let method_name = if is_type_diagnostic_item(cx, ty, sym::cstring_type) { "as_bytes" } else if is_type_diagnostic_item(cx, ty, sym::CStr) { @@ -64,11 +76,11 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { span_lint_and_sugg( cx, STRLEN_ON_C_STRINGS, - expr.span, + span, "using `libc::strlen` on a `CString` or `CStr` value", - "try this (you might also need to get rid of `unsafe` block in some cases):", + "try this", format!("{}.{}().len()", val_name, method_name), - Applicability::Unspecified // Sometimes unnecessary `unsafe` block + app, ); } } diff --git a/clippy_utils/src/visitors.rs b/clippy_utils/src/visitors.rs index 823df5cb751..4bfd3c64b9c 100644 --- a/clippy_utils/src/visitors.rs +++ b/clippy_utils/src/visitors.rs @@ -1,8 +1,10 @@ use crate::path_to_local_id; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::intravisit::{self, walk_expr, NestedVisitorMap, Visitor}; -use rustc_hir::{Arm, Block, Body, BodyId, Expr, ExprKind, HirId, Stmt, UnOp}; +use rustc_hir::intravisit::{self, walk_block, walk_expr, NestedVisitorMap, Visitor}; +use rustc_hir::{ + Arm, Block, BlockCheckMode, Body, BodyId, Expr, ExprKind, HirId, ItemId, ItemKind, Stmt, UnOp, Unsafety, +}; use rustc_lint::LateContext; use rustc_middle::hir::map::Map; use rustc_middle::ty; @@ -317,3 +319,64 @@ fn visit_expr(&mut self, e: &'tcx Expr<'_>) { v.visit_expr(e); v.is_const } + +/// Checks if the given expression performs an unsafe operation outside of an unsafe block. +pub fn is_expr_unsafe(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool { + struct V<'a, 'tcx> { + cx: &'a LateContext<'tcx>, + is_unsafe: bool, + } + impl<'tcx> Visitor<'tcx> for V<'_, 'tcx> { + type Map = Map<'tcx>; + fn nested_visit_map(&mut self) -> NestedVisitorMap { + NestedVisitorMap::OnlyBodies(self.cx.tcx.hir()) + } + fn visit_expr(&mut self, e: &'tcx Expr<'_>) { + if self.is_unsafe { + return; + } + match e.kind { + ExprKind::Unary(UnOp::Deref, e) if self.cx.typeck_results().expr_ty(e).is_unsafe_ptr() => { + self.is_unsafe = true; + }, + ExprKind::MethodCall(..) + if self + .cx + .typeck_results() + .type_dependent_def_id(e.hir_id) + .map_or(false, |id| self.cx.tcx.fn_sig(id).unsafety() == Unsafety::Unsafe) => + { + self.is_unsafe = true; + }, + ExprKind::Call(func, _) => match *self.cx.typeck_results().expr_ty(func).peel_refs().kind() { + ty::FnDef(id, _) if self.cx.tcx.fn_sig(id).unsafety() == Unsafety::Unsafe => self.is_unsafe = true, + ty::FnPtr(sig) if sig.unsafety() == Unsafety::Unsafe => self.is_unsafe = true, + _ => walk_expr(self, e), + }, + ExprKind::Path(ref p) + if self + .cx + .qpath_res(p, e.hir_id) + .opt_def_id() + .map_or(false, |id| self.cx.tcx.is_mutable_static(id)) => + { + self.is_unsafe = true; + }, + _ => walk_expr(self, e), + } + } + fn visit_block(&mut self, b: &'tcx Block<'_>) { + if !matches!(b.rules, BlockCheckMode::UnsafeBlock(_)) { + walk_block(self, b); + } + } + fn visit_nested_item(&mut self, id: ItemId) { + if let ItemKind::Impl(i) = &self.cx.tcx.hir().item(id).kind { + self.is_unsafe = i.unsafety == Unsafety::Unsafe; + } + } + } + let mut v = V { cx, is_unsafe: false }; + v.visit_expr(e); + v.is_unsafe +} diff --git a/tests/ui/strlen_on_c_strings.rs b/tests/ui/strlen_on_c_strings.rs index 121ddf1b9b1..a3451d992a0 100644 --- a/tests/ui/strlen_on_c_strings.rs +++ b/tests/ui/strlen_on_c_strings.rs @@ -16,4 +16,16 @@ fn main() { let len = unsafe { libc::strlen(cstr.as_ptr()) }; let len = unsafe { strlen(cstr.as_ptr()) }; + + let pcstr: *const &CStr = &cstr; + let len = unsafe { strlen((*pcstr).as_ptr()) }; + + unsafe fn unsafe_identity(x: T) -> T { + x + } + let len = unsafe { strlen(unsafe_identity(cstr).as_ptr()) }; + let len = unsafe { strlen(unsafe { unsafe_identity(cstr) }.as_ptr()) }; + + let f: unsafe fn(_) -> _ = unsafe_identity; + let len = unsafe { strlen(f(cstr).as_ptr()) }; } diff --git a/tests/ui/strlen_on_c_strings.stderr b/tests/ui/strlen_on_c_strings.stderr index 5576d9d2676..0dbecda62e3 100644 --- a/tests/ui/strlen_on_c_strings.stderr +++ b/tests/ui/strlen_on_c_strings.stderr @@ -1,36 +1,46 @@ error: using `libc::strlen` on a `CString` or `CStr` value - --> $DIR/strlen_on_c_strings.rs:12:24 + --> $DIR/strlen_on_c_strings.rs:12:15 | LL | let len = unsafe { libc::strlen(cstring.as_ptr()) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `cstring.as_bytes().len()` | = note: `-D clippy::strlen-on-c-strings` implied by `-D warnings` -help: try this (you might also need to get rid of `unsafe` block in some cases): - | -LL | let len = unsafe { cstring.as_bytes().len() }; - | ~~~~~~~~~~~~~~~~~~~~~~~~ error: using `libc::strlen` on a `CString` or `CStr` value - --> $DIR/strlen_on_c_strings.rs:16:24 + --> $DIR/strlen_on_c_strings.rs:16:15 | LL | let len = unsafe { libc::strlen(cstr.as_ptr()) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | -help: try this (you might also need to get rid of `unsafe` block in some cases): - | -LL | let len = unsafe { cstr.to_bytes().len() }; - | ~~~~~~~~~~~~~~~~~~~~~ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `cstr.to_bytes().len()` error: using `libc::strlen` on a `CString` or `CStr` value - --> $DIR/strlen_on_c_strings.rs:18:24 + --> $DIR/strlen_on_c_strings.rs:18:15 | LL | let len = unsafe { strlen(cstr.as_ptr()) }; - | ^^^^^^^^^^^^^^^^^^^^^ - | -help: try this (you might also need to get rid of `unsafe` block in some cases): - | -LL | let len = unsafe { cstr.to_bytes().len() }; - | ~~~~~~~~~~~~~~~~~~~~~ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `cstr.to_bytes().len()` -error: aborting due to 3 previous errors +error: using `libc::strlen` on a `CString` or `CStr` value + --> $DIR/strlen_on_c_strings.rs:21:24 + | +LL | let len = unsafe { strlen((*pcstr).as_ptr()) }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `(*pcstr).to_bytes().len()` + +error: using `libc::strlen` on a `CString` or `CStr` value + --> $DIR/strlen_on_c_strings.rs:26:24 + | +LL | let len = unsafe { strlen(unsafe_identity(cstr).as_ptr()) }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unsafe_identity(cstr).to_bytes().len()` + +error: using `libc::strlen` on a `CString` or `CStr` value + --> $DIR/strlen_on_c_strings.rs:27:15 + | +LL | let len = unsafe { strlen(unsafe { unsafe_identity(cstr) }.as_ptr()) }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unsafe { unsafe_identity(cstr) }.to_bytes().len()` + +error: using `libc::strlen` on a `CString` or `CStr` value + --> $DIR/strlen_on_c_strings.rs:30:24 + | +LL | let len = unsafe { strlen(f(cstr).as_ptr()) }; + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `f(cstr).to_bytes().len()` + +error: aborting due to 7 previous errors