Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 8cf1b0e

Browse files
committed
Uplift temporary-cstring-as-ptr into rustc
1 parent c96e11c commit 8cf1b0e

File tree

2 files changed

+105
-0
lines changed

2 files changed

+105
-0
lines changed

compiler/rustc_lint/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ mod early;
4949
mod internal;
5050
mod late;
5151
mod levels;
52+
mod methods;
5253
mod non_ascii_idents;
5354
mod nonstandard_style;
5455
mod passes;
@@ -73,6 +74,7 @@ use rustc_span::Span;
7374
use array_into_iter::ArrayIntoIter;
7475
use builtin::*;
7576
use internal::*;
77+
use methods::*;
7678
use non_ascii_idents::*;
7779
use nonstandard_style::*;
7880
use redundant_semicolon::*;
@@ -160,6 +162,7 @@ macro_rules! late_lint_passes {
160162
ArrayIntoIter: ArrayIntoIter,
161163
ClashingExternDeclarations: ClashingExternDeclarations::new(),
162164
DropTraitConstraints: DropTraitConstraints,
165+
TemporaryCStringAsPtr: TemporaryCStringAsPtr,
163166
]
164167
);
165168
};

compiler/rustc_lint/src/methods.rs

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
use crate::LateContext;
2+
use crate::LateLintPass;
3+
use crate::LintContext;
4+
use rustc_hir::{Expr, ExprKind};
5+
use rustc_middle::ty;
6+
use rustc_span::{
7+
symbol::{sym, Symbol, SymbolStr},
8+
ExpnKind, Span,
9+
};
10+
11+
declare_lint! {
12+
pub TEMPORARY_CSTRING_AS_PTR,
13+
Deny,
14+
"detects getting the inner pointer of a temporary `CString`"
15+
}
16+
17+
declare_lint_pass!(TemporaryCStringAsPtr => [TEMPORARY_CSTRING_AS_PTR]);
18+
19+
/// Returns the method names and argument list of nested method call expressions that make up
20+
/// `expr`. method/span lists are sorted with the most recent call first.
21+
pub fn method_calls<'tcx>(
22+
expr: &'tcx Expr<'tcx>,
23+
max_depth: usize,
24+
) -> (Vec<Symbol>, Vec<&'tcx [Expr<'tcx>]>, Vec<Span>) {
25+
let mut method_names = Vec::with_capacity(max_depth);
26+
let mut arg_lists = Vec::with_capacity(max_depth);
27+
let mut spans = Vec::with_capacity(max_depth);
28+
29+
let mut current = expr;
30+
for _ in 0..max_depth {
31+
if let ExprKind::MethodCall(path, span, args, _) = &current.kind {
32+
if args.iter().any(|e| e.span.from_expansion()) {
33+
break;
34+
}
35+
method_names.push(path.ident.name);
36+
arg_lists.push(&**args);
37+
spans.push(*span);
38+
current = &args[0];
39+
} else {
40+
break;
41+
}
42+
}
43+
44+
(method_names, arg_lists, spans)
45+
}
46+
47+
fn in_macro(span: Span) -> bool {
48+
if span.from_expansion() {
49+
!matches!(span.ctxt().outer_expn_data().kind, ExpnKind::Desugaring(..))
50+
} else {
51+
false
52+
}
53+
}
54+
55+
impl<'tcx> LateLintPass<'tcx> for TemporaryCStringAsPtr {
56+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
57+
if in_macro(expr.span) {
58+
return;
59+
}
60+
61+
let (method_names, arg_lists, _) = method_calls(expr, 2);
62+
let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
63+
let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
64+
65+
if let ["as_ptr", "unwrap" | "expect"] = method_names.as_slice() {
66+
lint_cstring_as_ptr(cx, expr, &arg_lists[1][0], &arg_lists[0][0]);
67+
}
68+
}
69+
}
70+
71+
fn lint_cstring_as_ptr(
72+
cx: &LateContext<'_>,
73+
expr: &rustc_hir::Expr<'_>,
74+
source: &rustc_hir::Expr<'_>,
75+
unwrap: &rustc_hir::Expr<'_>,
76+
) {
77+
let source_type = cx.typeck_results().expr_ty(source);
78+
if let ty::Adt(def, substs) = source_type.kind {
79+
if cx.tcx.is_diagnostic_item(Symbol::intern("result_type"), def.did) {
80+
if let ty::Adt(adt, _) = substs.type_at(0).kind {
81+
let path = [
82+
sym::std,
83+
Symbol::intern("ffi"),
84+
Symbol::intern("c_str"),
85+
Symbol::intern("CString"),
86+
];
87+
if cx.match_def_path(adt.did, &path) {
88+
cx.struct_span_lint(TEMPORARY_CSTRING_AS_PTR, expr.span, |diag| {
89+
let mut diag = diag
90+
.build("you are getting the inner pointer of a temporary `CString`");
91+
diag.note("that pointer will be invalid outside this expression");
92+
diag.span_help(
93+
unwrap.span,
94+
"assign the `CString` to a variable to extend its lifetime",
95+
);
96+
diag.emit();
97+
});
98+
}
99+
}
100+
}
101+
}
102+
}

0 commit comments

Comments
 (0)