]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/methods.rs
migrate: `array_into_iter.rs`
[rust.git] / compiler / rustc_lint / src / methods.rs
1 #![deny(rustc::untranslatable_diagnostic)]
2 #![deny(rustc::diagnostic_outside_of_impl)]
3 use crate::lints::CStringPtr;
4 use crate::LateContext;
5 use crate::LateLintPass;
6 use crate::LintContext;
7 use rustc_hir::{Expr, ExprKind, PathSegment};
8 use rustc_middle::ty;
9 use rustc_span::{symbol::sym, ExpnKind, Span};
10
11 declare_lint! {
12     /// The `temporary_cstring_as_ptr` lint detects getting the inner pointer of
13     /// a temporary `CString`.
14     ///
15     /// ### Example
16     ///
17     /// ```rust
18     /// # #![allow(unused)]
19     /// # use std::ffi::CString;
20     /// let c_str = CString::new("foo").unwrap().as_ptr();
21     /// ```
22     ///
23     /// {{produces}}
24     ///
25     /// ### Explanation
26     ///
27     /// The inner pointer of a `CString` lives only as long as the `CString` it
28     /// points to. Getting the inner pointer of a *temporary* `CString` allows the `CString`
29     /// to be dropped at the end of the statement, as it is not being referenced as far as the typesystem
30     /// is concerned. This means outside of the statement the pointer will point to freed memory, which
31     /// causes undefined behavior if the pointer is later dereferenced.
32     pub TEMPORARY_CSTRING_AS_PTR,
33     Warn,
34     "detects getting the inner pointer of a temporary `CString`"
35 }
36
37 declare_lint_pass!(TemporaryCStringAsPtr => [TEMPORARY_CSTRING_AS_PTR]);
38
39 fn in_macro(span: Span) -> bool {
40     if span.from_expansion() {
41         !matches!(span.ctxt().outer_expn_data().kind, ExpnKind::Desugaring(..))
42     } else {
43         false
44     }
45 }
46
47 fn first_method_call<'tcx>(
48     expr: &'tcx Expr<'tcx>,
49 ) -> Option<(&'tcx PathSegment<'tcx>, &'tcx Expr<'tcx>)> {
50     if let ExprKind::MethodCall(path, receiver, args, ..) = &expr.kind {
51         if args.iter().any(|e| e.span.from_expansion()) || receiver.span.from_expansion() {
52             None
53         } else {
54             Some((path, *receiver))
55         }
56     } else {
57         None
58     }
59 }
60
61 impl<'tcx> LateLintPass<'tcx> for TemporaryCStringAsPtr {
62     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
63         if in_macro(expr.span) {
64             return;
65         }
66
67         match first_method_call(expr) {
68             Some((path, unwrap_arg)) if path.ident.name == sym::as_ptr => {
69                 let as_ptr_span = path.ident.span;
70                 match first_method_call(unwrap_arg) {
71                     Some((path, receiver))
72                         if path.ident.name == sym::unwrap || path.ident.name == sym::expect =>
73                     {
74                         lint_cstring_as_ptr(cx, as_ptr_span, receiver, unwrap_arg);
75                     }
76                     _ => return,
77                 }
78             }
79             _ => return,
80         }
81     }
82 }
83
84 fn lint_cstring_as_ptr(
85     cx: &LateContext<'_>,
86     as_ptr_span: Span,
87     source: &rustc_hir::Expr<'_>,
88     unwrap: &rustc_hir::Expr<'_>,
89 ) {
90     let source_type = cx.typeck_results().expr_ty(source);
91     if let ty::Adt(def, substs) = source_type.kind() {
92         if cx.tcx.is_diagnostic_item(sym::Result, def.did()) {
93             if let ty::Adt(adt, _) = substs.type_at(0).kind() {
94                 if cx.tcx.is_diagnostic_item(sym::cstring_type, adt.did()) {
95                     cx.emit_spanned_lint(
96                         TEMPORARY_CSTRING_AS_PTR,
97                         as_ptr_span,
98                         CStringPtr { as_ptr: as_ptr_span, unwrap: unwrap.span },
99                     );
100                 }
101             }
102         }
103     }
104 }