1 use clippy_utils::diagnostics::span_lint_and_sugg;
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};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{Block, BlockCheckMode, Expr, ExprKind, Node, UnsafeSource};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::symbol::sym;
13 declare_clippy_lint! {
15 /// Checks for usage of `libc::strlen` on a `CString` or `CStr` value,
16 /// and suggest calling `as_bytes().len()` or `to_bytes().len()` respectively instead.
18 /// ### Why is this bad?
19 /// This avoids calling an unsafe `libc` function.
20 /// Currently, it also avoids calculating the length.
24 /// use std::ffi::CString;
25 /// let cstring = CString::new("foo").expect("CString::new failed");
26 /// let len = unsafe { libc::strlen(cstring.as_ptr()) };
30 /// use std::ffi::CString;
31 /// let cstring = CString::new("foo").expect("CString::new failed");
32 /// let len = cstring.as_bytes().len();
34 #[clippy::version = "1.55.0"]
35 pub STRLEN_ON_C_STRINGS,
37 "using `libc::strlen` on a `CString` or `CStr` value, while `as_bytes().len()` or `to_bytes().len()` respectively can be used instead"
40 declare_lint_pass!(StrlenOnCStrings => [STRLEN_ON_C_STRINGS]);
42 impl LateLintPass<'tcx> for StrlenOnCStrings {
43 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
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();
52 if path.ident.name == sym::as_ptr;
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, ..
59 if span.ctxt() == ctxt && !is_expr_unsafe(cx, self_arg) => {
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) {
70 } else if is_type_diagnostic_item(cx, ty, sym::CStr) {
80 "using `libc::strlen` on a `CString` or `CStr` value",
82 format!("{}.{}().len()", val_name, method_name),