1 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};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::symbol::{sym, Symbol};
12 declare_clippy_lint! {
14 /// 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?
18 /// This avoids calling an unsafe `libc` function.
19 /// Currently, it also avoids calculating the length.
23 /// use std::ffi::CString;
24 /// let cstring = CString::new("foo").expect("CString::new failed");
25 /// let len = unsafe { libc::strlen(cstring.as_ptr()) };
29 /// use std::ffi::CString;
30 /// let cstring = CString::new("foo").expect("CString::new failed");
31 /// let len = cstring.as_bytes().len();
33 #[clippy::version = "1.55.0"]
34 pub STRLEN_ON_C_STRINGS,
36 "using `libc::strlen` on a `CString` or `CStr` value, while `as_bytes().len()` or `to_bytes().len()` respectively can be used instead"
39 declare_lint_pass!(StrlenOnCStrings => [STRLEN_ON_C_STRINGS]);
41 impl LateLintPass<'tcx> for StrlenOnCStrings {
42 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
43 if expr.span.from_expansion() {
48 if let hir::ExprKind::Call(func, [recv]) = expr.kind;
49 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = func.kind;
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;
55 if !args.iter().any(|e| e.span.from_expansion());
56 if path.ident.name == sym::as_ptr;
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)
73 "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):",
76 Applicability::Unspecified // Sometimes unnecessary `unsafe` block