|
| 1 | +use clippy_config::msrvs::{self, Msrv}; |
| 2 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 3 | +use clippy_utils::get_parent_expr; |
| 4 | +use clippy_utils::source::snippet; |
| 5 | +use rustc_ast::{LitKind, StrStyle}; |
| 6 | +use rustc_errors::Applicability; |
| 7 | +use rustc_hir::{Expr, ExprKind, Node, QPath, TyKind}; |
| 8 | +use rustc_lint::LateContext; |
| 9 | +use rustc_span::{sym, Span, Symbol}; |
| 10 | + |
| 11 | +use super::MANUAL_C_STR_LITERALS; |
| 12 | + |
| 13 | +/// Checks: |
| 14 | +/// - `b"...".as_ptr()` |
| 15 | +/// - `b"...".as_ptr().cast()` |
| 16 | +/// - `"...".as_ptr()` |
| 17 | +/// - `"...".as_ptr().cast()` |
| 18 | +/// |
| 19 | +/// Iff the parent call of `.cast()` isn't `CStr::from_ptr`, to avoid linting twice. |
| 20 | +pub(super) fn check_as_ptr<'tcx>( |
| 21 | + cx: &LateContext<'tcx>, |
| 22 | + expr: &'tcx Expr<'tcx>, |
| 23 | + receiver: &'tcx Expr<'tcx>, |
| 24 | + msrv: &Msrv, |
| 25 | +) { |
| 26 | + if let ExprKind::Lit(lit) = receiver.kind |
| 27 | + && let LitKind::ByteStr(_, StrStyle::Cooked) | LitKind::Str(_, StrStyle::Cooked) = lit.node |
| 28 | + && let casts_removed = peel_ptr_cast_ancestors(cx, expr) |
| 29 | + && !get_parent_expr(cx, casts_removed).is_some_and( |
| 30 | + |parent| matches!(parent.kind, ExprKind::Call(func, _) if is_c_str_function(cx, func).is_some()), |
| 31 | + ) |
| 32 | + && let Some(sugg) = rewrite_as_cstr(cx, lit.span) |
| 33 | + && msrv.meets(msrvs::C_STR_LITERALS) |
| 34 | + { |
| 35 | + span_lint_and_sugg( |
| 36 | + cx, |
| 37 | + MANUAL_C_STR_LITERALS, |
| 38 | + receiver.span, |
| 39 | + "manually constructing a nul-terminated string", |
| 40 | + r#"use a `c""` literal"#, |
| 41 | + sugg, |
| 42 | + // an additional cast may be needed, since the type of `CStr::as_ptr` and |
| 43 | + // `"".as_ptr()` can differ and is platform dependent |
| 44 | + Applicability::HasPlaceholders, |
| 45 | + ); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +/// Checks if the callee is a "relevant" `CStr` function considered by this lint. |
| 50 | +/// Returns the function name. |
| 51 | +fn is_c_str_function(cx: &LateContext<'_>, func: &Expr<'_>) -> Option<Symbol> { |
| 52 | + if let ExprKind::Path(QPath::TypeRelative(cstr, fn_name)) = &func.kind |
| 53 | + && let TyKind::Path(QPath::Resolved(_, ty_path)) = &cstr.kind |
| 54 | + && cx.tcx.lang_items().c_str() == ty_path.res.opt_def_id() |
| 55 | + { |
| 56 | + Some(fn_name.ident.name) |
| 57 | + } else { |
| 58 | + None |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +/// Checks calls to the `CStr` constructor functions: |
| 63 | +/// - `CStr::from_bytes_with_nul(..)` |
| 64 | +/// - `CStr::from_bytes_with_nul_unchecked(..)` |
| 65 | +/// - `CStr::from_ptr(..)` |
| 66 | +pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, func: &Expr<'_>, args: &[Expr<'_>], msrv: &Msrv) { |
| 67 | + if let Some(fn_name) = is_c_str_function(cx, func) |
| 68 | + && let [arg] = args |
| 69 | + && msrv.meets(msrvs::C_STR_LITERALS) |
| 70 | + { |
| 71 | + match fn_name.as_str() { |
| 72 | + name @ ("from_bytes_with_nul" | "from_bytes_with_nul_unchecked") |
| 73 | + if !arg.span.from_expansion() |
| 74 | + && let ExprKind::Lit(lit) = arg.kind |
| 75 | + && let LitKind::ByteStr(_, StrStyle::Cooked) | LitKind::Str(_, StrStyle::Cooked) = lit.node => |
| 76 | + { |
| 77 | + check_from_bytes(cx, expr, arg, name); |
| 78 | + }, |
| 79 | + "from_ptr" => check_from_ptr(cx, expr, arg), |
| 80 | + _ => {}, |
| 81 | + } |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +/// Checks `CStr::from_ptr(b"foo\0".as_ptr().cast())` |
| 86 | +fn check_from_ptr(cx: &LateContext<'_>, expr: &Expr<'_>, arg: &Expr<'_>) { |
| 87 | + if let ExprKind::MethodCall(method, lit, ..) = peel_ptr_cast(arg).kind |
| 88 | + && method.ident.name == sym::as_ptr |
| 89 | + && !lit.span.from_expansion() |
| 90 | + && let ExprKind::Lit(lit) = lit.kind |
| 91 | + && let LitKind::ByteStr(_, StrStyle::Cooked) = lit.node |
| 92 | + && let Some(sugg) = rewrite_as_cstr(cx, lit.span) |
| 93 | + { |
| 94 | + span_lint_and_sugg( |
| 95 | + cx, |
| 96 | + MANUAL_C_STR_LITERALS, |
| 97 | + expr.span, |
| 98 | + "calling `CStr::from_ptr` with a byte string literal", |
| 99 | + r#"use a `c""` literal"#, |
| 100 | + sugg, |
| 101 | + Applicability::MachineApplicable, |
| 102 | + ); |
| 103 | + } |
| 104 | +} |
| 105 | +/// Checks `CStr::from_bytes_with_nul(b"foo\0")` |
| 106 | +fn check_from_bytes(cx: &LateContext<'_>, expr: &Expr<'_>, arg: &Expr<'_>, method: &str) { |
| 107 | + let (span, applicability) = if let Some(parent) = get_parent_expr(cx, expr) |
| 108 | + && let ExprKind::MethodCall(method, ..) = parent.kind |
| 109 | + && [sym::unwrap, sym::expect].contains(&method.ident.name) |
| 110 | + { |
| 111 | + (parent.span, Applicability::MachineApplicable) |
| 112 | + } else if method == "from_bytes_with_nul_unchecked" { |
| 113 | + // `*_unchecked` returns `&CStr` directly, nothing needs to be changed |
| 114 | + (expr.span, Applicability::MachineApplicable) |
| 115 | + } else { |
| 116 | + // User needs to remove error handling, can't be machine applicable |
| 117 | + (expr.span, Applicability::HasPlaceholders) |
| 118 | + }; |
| 119 | + |
| 120 | + let Some(sugg) = rewrite_as_cstr(cx, arg.span) else { |
| 121 | + return; |
| 122 | + }; |
| 123 | + |
| 124 | + span_lint_and_sugg( |
| 125 | + cx, |
| 126 | + MANUAL_C_STR_LITERALS, |
| 127 | + span, |
| 128 | + "calling `CStr::new` with a byte string literal", |
| 129 | + r#"use a `c""` literal"#, |
| 130 | + sugg, |
| 131 | + applicability, |
| 132 | + ); |
| 133 | +} |
| 134 | + |
| 135 | +/// Rewrites a byte string literal to a c-str literal. |
| 136 | +/// `b"foo\0"` -> `c"foo"` |
| 137 | +/// |
| 138 | +/// Returns `None` if it doesn't end in a NUL byte. |
| 139 | +fn rewrite_as_cstr(cx: &LateContext<'_>, span: Span) -> Option<String> { |
| 140 | + let mut sugg = String::from("c") + snippet(cx, span.source_callsite(), "..").trim_start_matches('b'); |
| 141 | + |
| 142 | + // NUL byte should always be right before the closing quote. |
| 143 | + if let Some(quote_pos) = sugg.rfind('"') { |
| 144 | + // Possible values right before the quote: |
| 145 | + // - literal NUL value |
| 146 | + if sugg.as_bytes()[quote_pos - 1] == b'\0' { |
| 147 | + sugg.remove(quote_pos - 1); |
| 148 | + } |
| 149 | + // - \x00 |
| 150 | + else if sugg[..quote_pos].ends_with("\\x00") { |
| 151 | + sugg.replace_range(quote_pos - 4..quote_pos, ""); |
| 152 | + } |
| 153 | + // - \0 |
| 154 | + else if sugg[..quote_pos].ends_with("\\0") { |
| 155 | + sugg.replace_range(quote_pos - 2..quote_pos, ""); |
| 156 | + } |
| 157 | + // No known suffix, so assume it's not a C-string. |
| 158 | + else { |
| 159 | + return None; |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + Some(sugg) |
| 164 | +} |
| 165 | + |
| 166 | +fn get_cast_target<'tcx>(e: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> { |
| 167 | + match &e.kind { |
| 168 | + ExprKind::MethodCall(method, receiver, [], _) if method.ident.as_str() == "cast" => Some(receiver), |
| 169 | + ExprKind::Cast(expr, _) => Some(expr), |
| 170 | + _ => None, |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +/// `x.cast()` -> `x` |
| 175 | +/// `x as *const _` -> `x` |
| 176 | +/// `x` -> `x` (returns the same expression for non-cast exprs) |
| 177 | +fn peel_ptr_cast<'tcx>(e: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> { |
| 178 | + get_cast_target(e).map_or(e, peel_ptr_cast) |
| 179 | +} |
| 180 | + |
| 181 | +/// Same as `peel_ptr_cast`, but the other way around, by walking up the ancestor cast expressions: |
| 182 | +/// |
| 183 | +/// `foo(x.cast() as *const _)` |
| 184 | +/// ^ given this `x` expression, returns the `foo(...)` expression |
| 185 | +fn peel_ptr_cast_ancestors<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> { |
| 186 | + let mut prev = e; |
| 187 | + for (_, node) in cx.tcx.hir().parent_iter(e.hir_id) { |
| 188 | + if let Node::Expr(e) = node |
| 189 | + && get_cast_target(e).is_some() |
| 190 | + { |
| 191 | + prev = e; |
| 192 | + } else { |
| 193 | + break; |
| 194 | + } |
| 195 | + } |
| 196 | + prev |
| 197 | +} |
0 commit comments