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};
9 use rustc_span::{symbol::sym, ExpnKind, Span};
12 /// The `temporary_cstring_as_ptr` lint detects getting the inner pointer of
13 /// a temporary `CString`.
18 /// # #![allow(unused)]
19 /// # use std::ffi::CString;
20 /// let c_str = CString::new("foo").unwrap().as_ptr();
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,
34 "detects getting the inner pointer of a temporary `CString`"
37 declare_lint_pass!(TemporaryCStringAsPtr => [TEMPORARY_CSTRING_AS_PTR]);
39 fn in_macro(span: Span) -> bool {
40 if span.from_expansion() {
41 !matches!(span.ctxt().outer_expn_data().kind, ExpnKind::Desugaring(..))
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() {
54 Some((path, *receiver))
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) {
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 =>
74 lint_cstring_as_ptr(cx, as_ptr_span, receiver, unwrap_arg);
84 fn lint_cstring_as_ptr(
87 source: &rustc_hir::Expr<'_>,
88 unwrap: &rustc_hir::Expr<'_>,
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()) {
96 TEMPORARY_CSTRING_AS_PTR,
98 CStringPtr { as_ptr: as_ptr_span, unwrap: unwrap.span },