Skip to content

Commit 90e6d0d

Browse files
committed
Auto merge of #75671 - nathanwhit:cstring-temp-lint, r=oli-obk
Uplift `temporary-cstring-as-ptr` lint from `clippy` into rustc The general consensus seems to be that this lint covers a common enough mistake to warrant inclusion in rustc. The diagnostic message might need some tweaking, as I'm not sure the use of second-person perspective matches the rest of rustc, but I'd like to hear others' thoughts on that. (cc #53224). r? `@oli-obk`
2 parents 07e968b + 572cd35 commit 90e6d0d

File tree

15 files changed

+177
-141
lines changed

15 files changed

+177
-141
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: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
use crate::LateContext;
2+
use crate::LateLintPass;
3+
use crate::LintContext;
4+
use rustc_hir::{Expr, ExprKind, PathSegment};
5+
use rustc_middle::ty;
6+
use rustc_span::{symbol::sym, ExpnKind, Span};
7+
8+
declare_lint! {
9+
/// The `temporary_cstring_as_ptr` lint detects getting the inner pointer of
10+
/// a temporary `CString`.
11+
///
12+
/// ### Example
13+
///
14+
/// ```rust
15+
/// # #![allow(unused)]
16+
/// # use std::ffi::CString;
17+
/// let c_str = CString::new("foo").unwrap().as_ptr();
18+
/// ```
19+
///
20+
/// {{produces}}
21+
///
22+
/// ### Explanation
23+
///
24+
/// The inner pointer of a `CString` lives only as long as the `CString` it
25+
/// points to. Getting the inner pointer of a *temporary* `CString` allows the `CString`
26+
/// to be dropped at the end of the statement, as it is not being referenced as far as the typesystem
27+
/// is concerned. This means outside of the statement the pointer will point to freed memory, which
28+
/// causes undefined behavior if the pointer is later dereferenced.
29+
pub TEMPORARY_CSTRING_AS_PTR,
30+
Warn,
31+
"detects getting the inner pointer of a temporary `CString`"
32+
}
33+
34+
declare_lint_pass!(TemporaryCStringAsPtr => [TEMPORARY_CSTRING_AS_PTR]);
35+
36+
fn in_macro(span: Span) -> bool {
37+
if span.from_expansion() {
38+
!matches!(span.ctxt().outer_expn_data().kind, ExpnKind::Desugaring(..))
39+
} else {
40+
false
41+
}
42+
}
43+
44+
fn first_method_call<'tcx>(
45+
expr: &'tcx Expr<'tcx>,
46+
) -> Option<(&'tcx PathSegment<'tcx>, &'tcx [Expr<'tcx>])> {
47+
if let ExprKind::MethodCall(path, _, args, _) = &expr.kind {
48+
if args.iter().any(|e| e.span.from_expansion()) { None } else { Some((path, *args)) }
49+
} else {
50+
None
51+
}
52+
}
53+
54+
impl<'tcx> LateLintPass<'tcx> for TemporaryCStringAsPtr {
55+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
56+
if in_macro(expr.span) {
57+
return;
58+
}
59+
60+
match first_method_call(expr) {
61+
Some((path, args)) if path.ident.name == sym::as_ptr => {
62+
let unwrap_arg = &args[0];
63+
let as_ptr_span = path.ident.span;
64+
match first_method_call(unwrap_arg) {
65+
Some((path, args))
66+
if path.ident.name == sym::unwrap || path.ident.name == sym::expect =>
67+
{
68+
let source_arg = &args[0];
69+
lint_cstring_as_ptr(cx, as_ptr_span, source_arg, unwrap_arg);
70+
}
71+
_ => return,
72+
}
73+
}
74+
_ => return,
75+
}
76+
}
77+
}
78+
79+
fn lint_cstring_as_ptr(
80+
cx: &LateContext<'_>,
81+
as_ptr_span: Span,
82+
source: &rustc_hir::Expr<'_>,
83+
unwrap: &rustc_hir::Expr<'_>,
84+
) {
85+
let source_type = cx.typeck_results().expr_ty(source);
86+
if let ty::Adt(def, substs) = source_type.kind() {
87+
if cx.tcx.is_diagnostic_item(sym::result_type, def.did) {
88+
if let ty::Adt(adt, _) = substs.type_at(0).kind() {
89+
if cx.tcx.is_diagnostic_item(sym::cstring_type, adt.did) {
90+
cx.struct_span_lint(TEMPORARY_CSTRING_AS_PTR, as_ptr_span, |diag| {
91+
let mut diag = diag
92+
.build("getting the inner pointer of a temporary `CString`");
93+
diag.span_label(as_ptr_span, "this pointer will be invalid");
94+
diag.span_label(
95+
unwrap.span,
96+
"this `CString` is deallocated at the end of the statement, bind it to a variable to extend its lifetime",
97+
);
98+
diag.note("pointers do not have a lifetime; when calling `as_ptr` the `CString` will be deallocated at the end of the statement because nothing is referencing it as far as the type system is concerned");
99+
diag.help("for more information, see https://doc.rust-lang.org/reference/destructors.html");
100+
diag.emit();
101+
});
102+
}
103+
}
104+
}
105+
}
106+
}

compiler/rustc_span/src/symbol.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ symbols! {
127127
ArgumentV1,
128128
Arguments,
129129
C,
130+
CString,
130131
Center,
131132
Clone,
132133
Copy,
@@ -261,6 +262,7 @@ symbols! {
261262
arm_target_feature,
262263
array,
263264
arrays,
265+
as_ptr,
264266
as_str,
265267
asm,
266268
assert,
@@ -310,6 +312,7 @@ symbols! {
310312
breakpoint,
311313
bridge,
312314
bswap,
315+
c_str,
313316
c_variadic,
314317
call,
315318
call_mut,
@@ -397,6 +400,7 @@ symbols! {
397400
crate_type,
398401
crate_visibility_modifier,
399402
crt_dash_static: "crt-static",
403+
cstring_type,
400404
ctlz,
401405
ctlz_nonzero,
402406
ctpop,
@@ -478,6 +482,7 @@ symbols! {
478482
existential_type,
479483
exp2f32,
480484
exp2f64,
485+
expect,
481486
expected,
482487
expf32,
483488
expf64,
@@ -501,6 +506,7 @@ symbols! {
501506
fadd_fast,
502507
fdiv_fast,
503508
feature,
509+
ffi,
504510
ffi_const,
505511
ffi_pure,
506512
ffi_returns_twice,
@@ -1170,6 +1176,7 @@ symbols! {
11701176
unused_qualifications,
11711177
unwind,
11721178
unwind_attributes,
1179+
unwrap,
11731180
unwrap_or,
11741181
use_extern_macros,
11751182
use_nested_groups,

library/std/src/ffi/c_str.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ use crate::sys;
110110
/// of `CString` instances can lead to invalid memory accesses, memory leaks,
111111
/// and other memory errors.
112112
#[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
113+
#[cfg_attr(not(test), rustc_diagnostic_item = "cstring_type")]
113114
#[stable(feature = "rust1", since = "1.0.0")]
114115
pub struct CString {
115116
// Invariant 1: the slice ends with a zero byte and has a length of at least one.
@@ -1265,7 +1266,7 @@ impl CStr {
12651266
/// behavior when `ptr` is used inside the `unsafe` block:
12661267
///
12671268
/// ```no_run
1268-
/// # #![allow(unused_must_use)]
1269+
/// # #![allow(unused_must_use)] #![cfg_attr(not(bootstrap), allow(temporary_cstring_as_ptr))]
12691270
/// use std::ffi::CString;
12701271
///
12711272
/// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#![deny(temporary_cstring_as_ptr)]
2+
3+
use std::ffi::CString;
4+
use std::os::raw::c_char;
5+
6+
fn some_function(data: *const c_char) {}
7+
8+
fn main() {
9+
some_function(CString::new("").unwrap().as_ptr());
10+
//~^ ERROR getting the inner pointer of a temporary `CString`
11+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
error: getting the inner pointer of a temporary `CString`
2+
--> $DIR/lint-temporary-cstring-as-param.rs:9:45
3+
|
4+
LL | some_function(CString::new("").unwrap().as_ptr());
5+
| ------------------------- ^^^^^^ this pointer will be invalid
6+
| |
7+
| this `CString` is deallocated at the end of the statement, bind it to a variable to extend its lifetime
8+
|
9+
note: the lint level is defined here
10+
--> $DIR/lint-temporary-cstring-as-param.rs:1:9
11+
|
12+
LL | #![deny(temporary_cstring_as_ptr)]
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^
14+
= note: pointers do not have a lifetime; when calling `as_ptr` the `CString` will be deallocated at the end of the statement because nothing is referencing it as far as the type system is concerned
15+
= help: for more information, see https://doc.rust-lang.org/reference/destructors.html
16+
17+
error: aborting due to previous error
18+
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// this program is not technically incorrect, but is an obscure enough style to be worth linting
2+
#![deny(temporary_cstring_as_ptr)]
3+
4+
use std::ffi::CString;
5+
6+
fn main() {
7+
let s = CString::new("some text").unwrap().as_ptr();
8+
//~^ ERROR getting the inner pointer of a temporary `CString`
9+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
error: getting the inner pointer of a temporary `CString`
2+
--> $DIR/lint-temporary-cstring-as-ptr.rs:7:48
3+
|
4+
LL | let s = CString::new("some text").unwrap().as_ptr();
5+
| ---------------------------------- ^^^^^^ this pointer will be invalid
6+
| |
7+
| this `CString` is deallocated at the end of the statement, bind it to a variable to extend its lifetime
8+
|
9+
note: the lint level is defined here
10+
--> $DIR/lint-temporary-cstring-as-ptr.rs:2:9
11+
|
12+
LL | #![deny(temporary_cstring_as_ptr)]
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^
14+
= note: pointers do not have a lifetime; when calling `as_ptr` the `CString` will be deallocated at the end of the statement because nothing is referencing it as far as the type system is concerned
15+
= help: for more information, see https://doc.rust-lang.org/reference/destructors.html
16+
17+
error: aborting due to previous error
18+

src/tools/clippy/.github/driver.sh

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ unset CARGO_MANIFEST_DIR
2222

2323
# Run a lint and make sure it produces the expected output. It's also expected to exit with code 1
2424
# FIXME: How to match the clippy invocation in compile-test.rs?
25-
./target/debug/clippy-driver -Dwarnings -Aunused -Zui-testing --emit metadata --crate-type bin tests/ui/cstring.rs 2> cstring.stderr && exit 1
26-
sed -e "s,tests/ui,\$DIR," -e "/= help/d" cstring.stderr > normalized.stderr
27-
diff normalized.stderr tests/ui/cstring.stderr
25+
./target/debug/clippy-driver -Dwarnings -Aunused -Zui-testing --emit metadata --crate-type bin tests/ui/cast.rs 2> cast.stderr && exit 1
26+
sed -e "s,tests/ui,\$DIR," -e "/= help/d" cast.stderr > normalized.stderr
27+
diff normalized.stderr tests/ui/cast.stderr
2828

2929

3030
# make sure "clippy-driver --rustc --arg" and "rustc --arg" behave the same

src/tools/clippy/clippy_lints/src/lib.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -707,7 +707,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
707707
&methods::SKIP_WHILE_NEXT,
708708
&methods::STRING_EXTEND_CHARS,
709709
&methods::SUSPICIOUS_MAP,
710-
&methods::TEMPORARY_CSTRING_AS_PTR,
711710
&methods::UNINIT_ASSUMED_INIT,
712711
&methods::UNNECESSARY_FILTER_MAP,
713712
&methods::UNNECESSARY_FOLD,
@@ -1417,7 +1416,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
14171416
LintId::of(&methods::SKIP_WHILE_NEXT),
14181417
LintId::of(&methods::STRING_EXTEND_CHARS),
14191418
LintId::of(&methods::SUSPICIOUS_MAP),
1420-
LintId::of(&methods::TEMPORARY_CSTRING_AS_PTR),
14211419
LintId::of(&methods::UNINIT_ASSUMED_INIT),
14221420
LintId::of(&methods::UNNECESSARY_FILTER_MAP),
14231421
LintId::of(&methods::UNNECESSARY_FOLD),
@@ -1765,7 +1763,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
17651763
LintId::of(&mem_replace::MEM_REPLACE_WITH_UNINIT),
17661764
LintId::of(&methods::CLONE_DOUBLE_REF),
17671765
LintId::of(&methods::ITERATOR_STEP_BY_ZERO),
1768-
LintId::of(&methods::TEMPORARY_CSTRING_AS_PTR),
17691766
LintId::of(&methods::UNINIT_ASSUMED_INIT),
17701767
LintId::of(&methods::ZST_OFFSET),
17711768
LintId::of(&minmax::MIN_MAX),

0 commit comments

Comments
 (0)