1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::in_macro;
3 use clippy_utils::paths;
4 use clippy_utils::source::snippet_with_macro_callsite;
5 use clippy_utils::ty::{is_type_diagnostic_item, is_type_ref_to_diagnostic_item};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::symbol::{sym, Symbol};
13 declare_clippy_lint! {
14 /// **What it does:** Checks for usage of `libc::strlen` on a `CString` or `CStr` value,
15 /// and suggest calling `as_bytes().len()` or `to_bytes().len()` respectively instead.
17 /// **Why is this bad?** This avoids calling an unsafe `libc` function.
18 /// Currently, it also avoids calculating the length.
20 /// **Known problems:** None.
25 /// use std::ffi::CString;
26 /// let cstring = CString::new("foo").expect("CString::new failed");
27 /// let len = unsafe { libc::strlen(cstring.as_ptr()) };
31 /// use std::ffi::CString;
32 /// let cstring = CString::new("foo").expect("CString::new failed");
33 /// let len = cstring.as_bytes().len();
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 hir::Expr<'_>) {
44 if in_macro(expr.span) {
49 if let hir::ExprKind::Call(func, [recv]) = expr.kind;
50 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = func.kind;
52 if (&paths::LIBC_STRLEN).iter().map(|x| Symbol::intern(x)).eq(
53 path.segments.iter().map(|seg| seg.ident.name));
54 if let hir::ExprKind::MethodCall(path, _, args, _) = recv.kind;
56 if !args.iter().any(|e| e.span.from_expansion());
57 if path.ident.name == sym::as_ptr;
59 let cstring = &args[0];
60 let ty = cx.typeck_results().expr_ty(cstring);
61 let val_name = snippet_with_macro_callsite(cx, cstring.span, "..");
62 let sugg = if is_type_diagnostic_item(cx, ty, sym::cstring_type){
63 format!("{}.as_bytes().len()", val_name)
64 } else if is_type_ref_to_diagnostic_item(cx, ty, sym::CStr){
65 format!("{}.to_bytes().len()", val_name)
74 "using `libc::strlen` on a `CString` or `CStr` value",
75 "try this (you might also need to get rid of `unsafe` block in some cases):",
77 Applicability::Unspecified // Sometimes unnecessary `unsafe` block