Skip to content

Commit 908815c

Browse files
committed
Auto merge of rust-lang#8001 - Jarcho:unprefixed_strlen, r=giraffate
Improve `strlen_on_c_string` fixes: rust-lang#7436 changelog: lint `strlen_on_c_string` when used without a fully-qualified path changelog: suggest removing the surrounding unsafe block for `strlen_on_c_string` when possible
2 parents 4e84dd1 + a135347 commit 908815c

File tree

7 files changed

+197
-47
lines changed

7 files changed

+197
-47
lines changed

clippy_lints/src/strlen_on_c_strings.rs

Lines changed: 36 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
use clippy_utils::diagnostics::span_lint_and_sugg;
2-
use clippy_utils::paths;
3-
use clippy_utils::source::snippet_with_macro_callsite;
4-
use clippy_utils::ty::{is_type_diagnostic_item, is_type_ref_to_diagnostic_item};
2+
use clippy_utils::source::snippet_with_context;
3+
use clippy_utils::ty::is_type_diagnostic_item;
4+
use clippy_utils::visitors::is_expr_unsafe;
5+
use clippy_utils::{get_parent_node, match_libc_symbol};
56
use if_chain::if_chain;
67
use rustc_errors::Applicability;
7-
use rustc_hir as hir;
8+
use rustc_hir::{Block, BlockCheckMode, Expr, ExprKind, Node, UnsafeSource};
89
use rustc_lint::{LateContext, LateLintPass};
910
use rustc_session::{declare_lint_pass, declare_tool_lint};
10-
use rustc_span::symbol::{sym, Symbol};
11+
use rustc_span::symbol::sym;
1112

1213
declare_clippy_lint! {
1314
/// ### What it does
@@ -39,41 +40,47 @@ declare_clippy_lint! {
3940
declare_lint_pass!(StrlenOnCStrings => [STRLEN_ON_C_STRINGS]);
4041

4142
impl LateLintPass<'tcx> for StrlenOnCStrings {
42-
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
43-
if expr.span.from_expansion() {
44-
return;
45-
}
46-
43+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
4744
if_chain! {
48-
if let hir::ExprKind::Call(func, [recv]) = expr.kind;
49-
if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = func.kind;
50-
51-
if (&paths::LIBC_STRLEN).iter().map(|x| Symbol::intern(x)).eq(
52-
path.segments.iter().map(|seg| seg.ident.name));
53-
if let hir::ExprKind::MethodCall(path, _, args, _) = recv.kind;
54-
if args.len() == 1;
55-
if !args.iter().any(|e| e.span.from_expansion());
45+
if !expr.span.from_expansion();
46+
if let ExprKind::Call(func, [recv]) = expr.kind;
47+
if let ExprKind::Path(path) = &func.kind;
48+
if let Some(did) = cx.qpath_res(path, func.hir_id).opt_def_id();
49+
if match_libc_symbol(cx, did, "strlen");
50+
if let ExprKind::MethodCall(path, _, [self_arg], _) = recv.kind;
51+
if !recv.span.from_expansion();
5652
if path.ident.name == sym::as_ptr;
5753
then {
58-
let cstring = &args[0];
59-
let ty = cx.typeck_results().expr_ty(cstring);
60-
let val_name = snippet_with_macro_callsite(cx, cstring.span, "..");
61-
let sugg = if is_type_diagnostic_item(cx, ty, sym::cstring_type){
62-
format!("{}.as_bytes().len()", val_name)
63-
} else if is_type_ref_to_diagnostic_item(cx, ty, sym::CStr){
64-
format!("{}.to_bytes().len()", val_name)
54+
let ctxt = expr.span.ctxt();
55+
let span = match get_parent_node(cx.tcx, expr.hir_id) {
56+
Some(Node::Block(&Block {
57+
rules: BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided), span, ..
58+
}))
59+
if span.ctxt() == ctxt && !is_expr_unsafe(cx, self_arg) => {
60+
span
61+
}
62+
_ => expr.span,
63+
};
64+
65+
let ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
66+
let mut app = Applicability::MachineApplicable;
67+
let val_name = snippet_with_context(cx, self_arg.span, ctxt, "..", &mut app).0;
68+
let method_name = if is_type_diagnostic_item(cx, ty, sym::cstring_type) {
69+
"as_bytes"
70+
} else if is_type_diagnostic_item(cx, ty, sym::CStr) {
71+
"to_bytes"
6572
} else {
6673
return;
6774
};
6875

6976
span_lint_and_sugg(
7077
cx,
7178
STRLEN_ON_C_STRINGS,
72-
expr.span,
79+
span,
7380
"using `libc::strlen` on a `CString` or `CStr` value",
74-
"try this (you might also need to get rid of `unsafe` block in some cases):",
75-
sugg,
76-
Applicability::Unspecified // Sometimes unnecessary `unsafe` block
81+
"try this",
82+
format!("{}.{}().len()", val_name, method_name),
83+
app,
7784
);
7885
}
7986
}

clippy_utils/src/lib.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1597,6 +1597,14 @@ pub fn match_def_path<'tcx>(cx: &LateContext<'tcx>, did: DefId, syms: &[&str]) -
15971597
syms.iter().map(|x| Symbol::intern(x)).eq(path.iter().copied())
15981598
}
15991599

1600+
/// Checks if the given `DefId` matches the `libc` item.
1601+
pub fn match_libc_symbol(cx: &LateContext<'_>, did: DefId, name: &str) -> bool {
1602+
let path = cx.get_def_path(did);
1603+
// libc is meant to be used as a flat list of names, but they're all actually defined in different
1604+
// modules based on the target platform. Ignore everything but crate name and the item name.
1605+
path.first().map_or(false, |s| s.as_str() == "libc") && path.last().map_or(false, |s| s.as_str() == name)
1606+
}
1607+
16001608
pub fn match_panic_call(cx: &LateContext<'_>, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
16011609
if let ExprKind::Call(func, [arg]) = expr.kind {
16021610
expr_path_res(cx, func)

clippy_utils/src/paths.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,6 @@ pub const ITERTOOLS_NEXT_TUPLE: [&str; 3] = ["itertools", "Itertools", "next_tup
8686
pub const KW_MODULE: [&str; 3] = ["rustc_span", "symbol", "kw"];
8787
#[cfg(feature = "internal-lints")]
8888
pub const LATE_CONTEXT: [&str; 2] = ["rustc_lint", "LateContext"];
89-
pub const LIBC_STRLEN: [&str; 2] = ["libc", "strlen"];
9089
#[cfg(any(feature = "internal-lints", feature = "metadata-collector-lint"))]
9190
pub const LINT: [&str; 2] = ["rustc_lint_defs", "Lint"];
9291
pub const MEM_DISCRIMINANT: [&str; 3] = ["core", "mem", "discriminant"];

clippy_utils/src/visitors.rs

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
use crate::path_to_local_id;
22
use rustc_hir as hir;
33
use rustc_hir::def::{DefKind, Res};
4-
use rustc_hir::intravisit::{self, walk_expr, NestedVisitorMap, Visitor};
5-
use rustc_hir::{Arm, Block, Body, BodyId, Expr, ExprKind, HirId, Stmt, UnOp};
4+
use rustc_hir::intravisit::{self, walk_block, walk_expr, NestedVisitorMap, Visitor};
5+
use rustc_hir::{
6+
Arm, Block, BlockCheckMode, Body, BodyId, Expr, ExprKind, HirId, ItemId, ItemKind, Stmt, UnOp, Unsafety,
7+
};
68
use rustc_lint::LateContext;
79
use rustc_middle::hir::map::Map;
810
use rustc_middle::ty;
@@ -317,3 +319,64 @@ pub fn is_const_evaluatable(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool {
317319
v.visit_expr(e);
318320
v.is_const
319321
}
322+
323+
/// Checks if the given expression performs an unsafe operation outside of an unsafe block.
324+
pub fn is_expr_unsafe(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool {
325+
struct V<'a, 'tcx> {
326+
cx: &'a LateContext<'tcx>,
327+
is_unsafe: bool,
328+
}
329+
impl<'tcx> Visitor<'tcx> for V<'_, 'tcx> {
330+
type Map = Map<'tcx>;
331+
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
332+
NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
333+
}
334+
fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
335+
if self.is_unsafe {
336+
return;
337+
}
338+
match e.kind {
339+
ExprKind::Unary(UnOp::Deref, e) if self.cx.typeck_results().expr_ty(e).is_unsafe_ptr() => {
340+
self.is_unsafe = true;
341+
},
342+
ExprKind::MethodCall(..)
343+
if self
344+
.cx
345+
.typeck_results()
346+
.type_dependent_def_id(e.hir_id)
347+
.map_or(false, |id| self.cx.tcx.fn_sig(id).unsafety() == Unsafety::Unsafe) =>
348+
{
349+
self.is_unsafe = true;
350+
},
351+
ExprKind::Call(func, _) => match *self.cx.typeck_results().expr_ty(func).peel_refs().kind() {
352+
ty::FnDef(id, _) if self.cx.tcx.fn_sig(id).unsafety() == Unsafety::Unsafe => self.is_unsafe = true,
353+
ty::FnPtr(sig) if sig.unsafety() == Unsafety::Unsafe => self.is_unsafe = true,
354+
_ => walk_expr(self, e),
355+
},
356+
ExprKind::Path(ref p)
357+
if self
358+
.cx
359+
.qpath_res(p, e.hir_id)
360+
.opt_def_id()
361+
.map_or(false, |id| self.cx.tcx.is_mutable_static(id)) =>
362+
{
363+
self.is_unsafe = true;
364+
},
365+
_ => walk_expr(self, e),
366+
}
367+
}
368+
fn visit_block(&mut self, b: &'tcx Block<'_>) {
369+
if !matches!(b.rules, BlockCheckMode::UnsafeBlock(_)) {
370+
walk_block(self, b);
371+
}
372+
}
373+
fn visit_nested_item(&mut self, id: ItemId) {
374+
if let ItemKind::Impl(i) = &self.cx.tcx.hir().item(id).kind {
375+
self.is_unsafe = i.unsafety == Unsafety::Unsafe;
376+
}
377+
}
378+
}
379+
let mut v = V { cx, is_unsafe: false };
380+
v.visit_expr(e);
381+
v.is_unsafe
382+
}

tests/ui/strlen_on_c_strings.fixed

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// run-rustfix
2+
3+
#![warn(clippy::strlen_on_c_strings)]
4+
#![allow(dead_code)]
5+
#![feature(rustc_private)]
6+
extern crate libc;
7+
8+
#[allow(unused)]
9+
use libc::strlen;
10+
use std::ffi::{CStr, CString};
11+
12+
fn main() {
13+
// CString
14+
let cstring = CString::new("foo").expect("CString::new failed");
15+
let _ = cstring.as_bytes().len();
16+
17+
// CStr
18+
let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
19+
let _ = cstr.to_bytes().len();
20+
21+
let _ = cstr.to_bytes().len();
22+
23+
let pcstr: *const &CStr = &cstr;
24+
let _ = unsafe { (*pcstr).to_bytes().len() };
25+
26+
unsafe fn unsafe_identity<T>(x: T) -> T {
27+
x
28+
}
29+
let _ = unsafe { unsafe_identity(cstr).to_bytes().len() };
30+
let _ = unsafe { unsafe_identity(cstr) }.to_bytes().len();
31+
32+
let f: unsafe fn(_) -> _ = unsafe_identity;
33+
let _ = unsafe { f(cstr).to_bytes().len() };
34+
}

tests/ui/strlen_on_c_strings.rs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,34 @@
1+
// run-rustfix
2+
13
#![warn(clippy::strlen_on_c_strings)]
24
#![allow(dead_code)]
35
#![feature(rustc_private)]
46
extern crate libc;
57

8+
#[allow(unused)]
9+
use libc::strlen;
610
use std::ffi::{CStr, CString};
711

812
fn main() {
913
// CString
1014
let cstring = CString::new("foo").expect("CString::new failed");
11-
let len = unsafe { libc::strlen(cstring.as_ptr()) };
15+
let _ = unsafe { libc::strlen(cstring.as_ptr()) };
1216

1317
// CStr
1418
let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
15-
let len = unsafe { libc::strlen(cstr.as_ptr()) };
19+
let _ = unsafe { libc::strlen(cstr.as_ptr()) };
20+
21+
let _ = unsafe { strlen(cstr.as_ptr()) };
22+
23+
let pcstr: *const &CStr = &cstr;
24+
let _ = unsafe { strlen((*pcstr).as_ptr()) };
25+
26+
unsafe fn unsafe_identity<T>(x: T) -> T {
27+
x
28+
}
29+
let _ = unsafe { strlen(unsafe_identity(cstr).as_ptr()) };
30+
let _ = unsafe { strlen(unsafe { unsafe_identity(cstr) }.as_ptr()) };
31+
32+
let f: unsafe fn(_) -> _ = unsafe_identity;
33+
let _ = unsafe { strlen(f(cstr).as_ptr()) };
1634
}

tests/ui/strlen_on_c_strings.stderr

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,46 @@
11
error: using `libc::strlen` on a `CString` or `CStr` value
2-
--> $DIR/strlen_on_c_strings.rs:11:24
2+
--> $DIR/strlen_on_c_strings.rs:15:13
33
|
4-
LL | let len = unsafe { libc::strlen(cstring.as_ptr()) };
5-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4+
LL | let _ = unsafe { libc::strlen(cstring.as_ptr()) };
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `cstring.as_bytes().len()`
66
|
77
= note: `-D clippy::strlen-on-c-strings` implied by `-D warnings`
8-
help: try this (you might also need to get rid of `unsafe` block in some cases):
8+
9+
error: using `libc::strlen` on a `CString` or `CStr` value
10+
--> $DIR/strlen_on_c_strings.rs:19:13
11+
|
12+
LL | let _ = unsafe { libc::strlen(cstr.as_ptr()) };
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `cstr.to_bytes().len()`
14+
15+
error: using `libc::strlen` on a `CString` or `CStr` value
16+
--> $DIR/strlen_on_c_strings.rs:21:13
17+
|
18+
LL | let _ = unsafe { strlen(cstr.as_ptr()) };
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `cstr.to_bytes().len()`
20+
21+
error: using `libc::strlen` on a `CString` or `CStr` value
22+
--> $DIR/strlen_on_c_strings.rs:24:22
923
|
10-
LL | let len = unsafe { cstring.as_bytes().len() };
11-
| ~~~~~~~~~~~~~~~~~~~~~~~~
24+
LL | let _ = unsafe { strlen((*pcstr).as_ptr()) };
25+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `(*pcstr).to_bytes().len()`
1226

1327
error: using `libc::strlen` on a `CString` or `CStr` value
14-
--> $DIR/strlen_on_c_strings.rs:15:24
28+
--> $DIR/strlen_on_c_strings.rs:29:22
1529
|
16-
LL | let len = unsafe { libc::strlen(cstr.as_ptr()) };
17-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
30+
LL | let _ = unsafe { strlen(unsafe_identity(cstr).as_ptr()) };
31+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unsafe_identity(cstr).to_bytes().len()`
32+
33+
error: using `libc::strlen` on a `CString` or `CStr` value
34+
--> $DIR/strlen_on_c_strings.rs:30:13
1835
|
19-
help: try this (you might also need to get rid of `unsafe` block in some cases):
36+
LL | let _ = unsafe { strlen(unsafe { unsafe_identity(cstr) }.as_ptr()) };
37+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unsafe { unsafe_identity(cstr) }.to_bytes().len()`
38+
39+
error: using `libc::strlen` on a `CString` or `CStr` value
40+
--> $DIR/strlen_on_c_strings.rs:33:22
2041
|
21-
LL | let len = unsafe { cstr.to_bytes().len() };
22-
| ~~~~~~~~~~~~~~~~~~~~~
42+
LL | let _ = unsafe { strlen(f(cstr).as_ptr()) };
43+
| ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `f(cstr).to_bytes().len()`
2344

24-
error: aborting due to 2 previous errors
45+
error: aborting due to 7 previous errors
2546

0 commit comments

Comments
 (0)