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

+3
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

+106
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

+7
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

+2-1
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();
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+
}
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+
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+
}
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

+3-3
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

-3
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),

src/tools/clippy/clippy_lints/src/methods/mod.rs

-56
Original file line numberDiff line numberDiff line change
@@ -798,40 +798,6 @@ declare_clippy_lint! {
798798
"using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
799799
}
800800

801-
declare_clippy_lint! {
802-
/// **What it does:** Checks for getting the inner pointer of a temporary
803-
/// `CString`.
804-
///
805-
/// **Why is this bad?** The inner pointer of a `CString` is only valid as long
806-
/// as the `CString` is alive.
807-
///
808-
/// **Known problems:** None.
809-
///
810-
/// **Example:**
811-
/// ```rust
812-
/// # use std::ffi::CString;
813-
/// # fn call_some_ffi_func(_: *const i8) {}
814-
/// #
815-
/// let c_str = CString::new("foo").unwrap().as_ptr();
816-
/// unsafe {
817-
/// call_some_ffi_func(c_str);
818-
/// }
819-
/// ```
820-
/// Here `c_str` points to a freed address. The correct use would be:
821-
/// ```rust
822-
/// # use std::ffi::CString;
823-
/// # fn call_some_ffi_func(_: *const i8) {}
824-
/// #
825-
/// let c_str = CString::new("foo").unwrap();
826-
/// unsafe {
827-
/// call_some_ffi_func(c_str.as_ptr());
828-
/// }
829-
/// ```
830-
pub TEMPORARY_CSTRING_AS_PTR,
831-
correctness,
832-
"getting the inner pointer of a temporary `CString`"
833-
}
834-
835801
declare_clippy_lint! {
836802
/// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
837803
///
@@ -1406,7 +1372,6 @@ declare_lint_pass!(Methods => [
14061372
SINGLE_CHAR_PATTERN,
14071373
SINGLE_CHAR_PUSH_STR,
14081374
SEARCH_IS_SOME,
1409-
TEMPORARY_CSTRING_AS_PTR,
14101375
FILTER_NEXT,
14111376
SKIP_WHILE_NEXT,
14121377
FILTER_MAP,
@@ -1490,7 +1455,6 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
14901455
lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
14911456
},
14921457
["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1493-
["as_ptr", "unwrap" | "expect"] => lint_cstring_as_ptr(cx, expr, &arg_lists[1][0], &arg_lists[0][0]),
14941458
["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
14951459
["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
14961460
["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
@@ -2207,26 +2171,6 @@ fn lint_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>
22072171
}
22082172
}
22092173

2210-
fn lint_cstring_as_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, source: &hir::Expr<'_>, unwrap: &hir::Expr<'_>) {
2211-
if_chain! {
2212-
let source_type = cx.typeck_results().expr_ty(source);
2213-
if let ty::Adt(def, substs) = source_type.kind();
2214-
if cx.tcx.is_diagnostic_item(sym!(result_type), def.did);
2215-
if match_type(cx, substs.type_at(0), &paths::CSTRING);
2216-
then {
2217-
span_lint_and_then(
2218-
cx,
2219-
TEMPORARY_CSTRING_AS_PTR,
2220-
expr.span,
2221-
"you are getting the inner pointer of a temporary `CString`",
2222-
|diag| {
2223-
diag.note("that pointer will be invalid outside this expression");
2224-
diag.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
2225-
});
2226-
}
2227-
}
2228-
}
2229-
22302174
fn lint_iter_cloned_collect<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
22312175
if_chain! {
22322176
if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym!(vec_type));

src/tools/clippy/clippy_lints/src/utils/paths.rs

-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ pub const CLONE_TRAIT_METHOD: [&str; 4] = ["core", "clone", "Clone", "clone"];
2121
pub const CMP_MAX: [&str; 3] = ["core", "cmp", "max"];
2222
pub const CMP_MIN: [&str; 3] = ["core", "cmp", "min"];
2323
pub const COW: [&str; 3] = ["alloc", "borrow", "Cow"];
24-
pub const CSTRING: [&str; 4] = ["std", "ffi", "c_str", "CString"];
2524
pub const CSTRING_AS_C_STR: [&str; 5] = ["std", "ffi", "c_str", "CString", "as_c_str"];
2625
pub const DEFAULT_TRAIT: [&str; 3] = ["core", "default", "Default"];
2726
pub const DEFAULT_TRAIT_METHOD: [&str; 4] = ["core", "default", "Default", "default"];

0 commit comments

Comments
 (0)