about summary refs log tree commit diff
path: root/compiler/rustc_lint/src/methods.rs
blob: 7b595dd18ff6b497a9f2cd50a359e999cc75d857 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use crate::LateContext;
use crate::LateLintPass;
use crate::LintContext;
use rustc_hir::{Expr, ExprKind, PathSegment};
use rustc_middle::ty;
use rustc_span::{
    symbol::{sym, Symbol},
    ExpnKind, Span,
};

declare_lint! {
    pub TEMPORARY_CSTRING_AS_PTR,
    Deny,
    "detects getting the inner pointer of a temporary `CString`"
}

declare_lint_pass!(TemporaryCStringAsPtr => [TEMPORARY_CSTRING_AS_PTR]);

fn in_macro(span: Span) -> bool {
    if span.from_expansion() {
        !matches!(span.ctxt().outer_expn_data().kind, ExpnKind::Desugaring(..))
    } else {
        false
    }
}

fn first_method_call<'tcx>(
    expr: &'tcx Expr<'tcx>,
) -> Option<(&'tcx PathSegment<'tcx>, &'tcx [Expr<'tcx>])> {
    if let ExprKind::MethodCall(path, _, args, _) = &expr.kind {
        if args.iter().any(|e| e.span.from_expansion()) { None } else { Some((path, *args)) }
    } else {
        None
    }
}

impl<'tcx> LateLintPass<'tcx> for TemporaryCStringAsPtr {
    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
        if in_macro(expr.span) {
            return;
        }

        match first_method_call(expr) {
            Some((path, args)) if path.ident.name == sym::as_ptr => {
                let unwrap_arg = &args[0];
                match first_method_call(unwrap_arg) {
                    Some((path, args))
                        if path.ident.name == sym::unwrap || path.ident.name == sym::expect =>
                    {
                        let source_arg = &args[0];
                        lint_cstring_as_ptr(cx, source_arg, unwrap_arg);
                    }
                    _ => return,
                }
            }
            _ => return,
        }
    }
}

const CSTRING_PATH: [Symbol; 4] = [sym::std, sym::ffi, sym::c_str, sym::CString];

fn lint_cstring_as_ptr(
    cx: &LateContext<'_>,
    source: &rustc_hir::Expr<'_>,
    unwrap: &rustc_hir::Expr<'_>,
) {
    let source_type = cx.typeck_results().expr_ty(source);
    if let ty::Adt(def, substs) = source_type.kind {
        if cx.tcx.is_diagnostic_item(sym::result_type, def.did) {
            if let ty::Adt(adt, _) = substs.type_at(0).kind {
                if cx.match_def_path(adt.did, &CSTRING_PATH) {
                    cx.struct_span_lint(TEMPORARY_CSTRING_AS_PTR, source.span, |diag| {
                        let mut diag = diag
                            .build("getting the inner pointer of a temporary `CString`");
                        diag.span_label(source.span, "this pointer will be invalid");
                        diag.span_help(
                            unwrap.span,
                            "this `CString` is deallocated at the end of the expression, bind it to a variable to extend its lifetime",
                        );
                        diag.note("pointers do not have a lifetime; when calling `as_ptr` the `CString` is deallocated because nothing is referencing it as far as the type system is concerned");
                        diag.emit();
                    });
                }
            }
        }
    }
}