Skip to content

Commit c443f8f

Browse files
committed
Fix strlen_on_c_strings when not used with a full path
1 parent 38bd251 commit c443f8f

File tree

5 files changed

+43
-27
lines changed

5 files changed

+43
-27
lines changed

clippy_lints/src/strlen_on_c_strings.rs

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
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::match_libc_symbol;
3+
use clippy_utils::source::snippet_with_context;
4+
use clippy_utils::ty::is_type_diagnostic_item;
55
use if_chain::if_chain;
66
use rustc_errors::Applicability;
77
use rustc_hir as hir;
88
use rustc_lint::{LateContext, LateLintPass};
99
use rustc_session::{declare_lint_pass, declare_tool_lint};
10-
use rustc_span::symbol::{sym, Symbol};
10+
use rustc_span::symbol::sym;
1111

1212
declare_clippy_lint! {
1313
/// ### What it does
@@ -40,28 +40,23 @@ declare_lint_pass!(StrlenOnCStrings => [STRLEN_ON_C_STRINGS]);
4040

4141
impl LateLintPass<'tcx> for StrlenOnCStrings {
4242
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
43-
if expr.span.from_expansion() {
44-
return;
45-
}
46-
4743
if_chain! {
44+
if !expr.span.from_expansion();
4845
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());
46+
if let hir::ExprKind::Path(path) = &func.kind;
47+
if let Some(did) = cx.qpath_res(path, func.hir_id).opt_def_id();
48+
if match_libc_symbol(cx, did, "strlen");
49+
if let hir::ExprKind::MethodCall(path, _, [self_arg], _) = recv.kind;
50+
if !recv.span.from_expansion();
5651
if path.ident.name == sym::as_ptr;
5752
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)
53+
let ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
54+
let mut app = Applicability::Unspecified;
55+
let val_name = snippet_with_context(cx, self_arg.span, expr.span.ctxt(), "..", &mut app).0;
56+
let method_name = if is_type_diagnostic_item(cx, ty, sym::cstring_type) {
57+
"as_bytes"
58+
} else if is_type_diagnostic_item(cx, ty, sym::CStr) {
59+
"to_bytes"
6560
} else {
6661
return;
6762
};
@@ -72,7 +67,7 @@ impl LateLintPass<'tcx> for StrlenOnCStrings {
7267
expr.span,
7368
"using `libc::strlen` on a `CString` or `CStr` value",
7469
"try this (you might also need to get rid of `unsafe` block in some cases):",
75-
sugg,
70+
format!("{}.{}().len()", val_name, method_name),
7671
Applicability::Unspecified // Sometimes unnecessary `unsafe` block
7772
);
7873
}

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"];

tests/ui/strlen_on_c_strings.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#![feature(rustc_private)]
44
extern crate libc;
55

6+
use libc::strlen;
67
use std::ffi::{CStr, CString};
78

89
fn main() {
@@ -13,4 +14,6 @@ fn main() {
1314
// CStr
1415
let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1516
let len = unsafe { libc::strlen(cstr.as_ptr()) };
17+
18+
let len = unsafe { strlen(cstr.as_ptr()) };
1619
}

tests/ui/strlen_on_c_strings.stderr

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
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:12:24
33
|
44
LL | let len = unsafe { libc::strlen(cstring.as_ptr()) };
55
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -11,7 +11,7 @@ LL | let len = unsafe { cstring.as_bytes().len() };
1111
| ~~~~~~~~~~~~~~~~~~~~~~~~
1212

1313
error: using `libc::strlen` on a `CString` or `CStr` value
14-
--> $DIR/strlen_on_c_strings.rs:15:24
14+
--> $DIR/strlen_on_c_strings.rs:16:24
1515
|
1616
LL | let len = unsafe { libc::strlen(cstr.as_ptr()) };
1717
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -21,5 +21,16 @@ help: try this (you might also need to get rid of `unsafe` block in some cases):
2121
LL | let len = unsafe { cstr.to_bytes().len() };
2222
| ~~~~~~~~~~~~~~~~~~~~~
2323

24-
error: aborting due to 2 previous errors
24+
error: using `libc::strlen` on a `CString` or `CStr` value
25+
--> $DIR/strlen_on_c_strings.rs:18:24
26+
|
27+
LL | let len = unsafe { strlen(cstr.as_ptr()) };
28+
| ^^^^^^^^^^^^^^^^^^^^^
29+
|
30+
help: try this (you might also need to get rid of `unsafe` block in some cases):
31+
|
32+
LL | let len = unsafe { cstr.to_bytes().len() };
33+
| ~~~~~~~~~~~~~~~~~~~~~
34+
35+
error: aborting due to 3 previous errors
2536

0 commit comments

Comments
 (0)