Skip to content

Commit 1871d90

Browse files
Rollup merge of rust-lang#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 rust-lang#53224). r? @oli-obk
2 parents 0da5800 + 4cc16db commit 1871d90

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;
@@ -72,6 +73,7 @@ use rustc_span::Span;
7273
use array_into_iter::ArrayIntoIter;
7374
use builtin::*;
7475
use internal::*;
76+
use methods::*;
7577
use non_ascii_idents::*;
7678
use nonstandard_style::*;
7779
use redundant_semicolon::*;
@@ -157,6 +159,7 @@ macro_rules! late_lint_passes {
157159
MissingDebugImplementations: MissingDebugImplementations::default(),
158160
ArrayIntoIter: ArrayIntoIter,
159161
ClashingExternDeclarations: ClashingExternDeclarations::new(),
162+
TemporaryCStringAsPtr: TemporaryCStringAsPtr,
160163
]
161164
);
162165
};

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,
@@ -259,6 +260,7 @@ symbols! {
259260
arm_target_feature,
260261
array,
261262
arrays,
263+
as_ptr,
262264
as_str,
263265
asm,
264266
assert,
@@ -308,6 +310,7 @@ symbols! {
308310
breakpoint,
309311
bridge,
310312
bswap,
313+
c_str,
311314
c_variadic,
312315
call,
313316
call_mut,
@@ -388,6 +391,7 @@ symbols! {
388391
crate_type,
389392
crate_visibility_modifier,
390393
crt_dash_static: "crt-static",
394+
cstring_type,
391395
ctlz,
392396
ctlz_nonzero,
393397
ctpop,
@@ -474,6 +478,7 @@ symbols! {
474478
existential_type,
475479
exp2f32,
476480
exp2f64,
481+
expect,
477482
expected,
478483
expf32,
479484
expf64,
@@ -497,6 +502,7 @@ symbols! {
497502
fadd_fast,
498503
fdiv_fast,
499504
feature,
505+
ffi,
500506
ffi_const,
501507
ffi_pure,
502508
ffi_returns_twice,
@@ -1156,6 +1162,7 @@ symbols! {
11561162
unused_qualifications,
11571163
unwind,
11581164
unwind_attributes,
1165+
unwrap,
11591166
unwrap_or,
11601167
use_extern_macros,
11611168
use_nested_groups,

library/std/src/ffi/c_str.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,9 @@ use crate::sys;
109109
/// documentation of `CString` before use, as improper ownership management
110110
/// of `CString` instances can lead to invalid memory accesses, memory leaks,
111111
/// and other memory errors.
112+
112113
#[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
114+
#[cfg_attr(not(test), rustc_diagnostic_item = "cstring_type")]
113115
#[stable(feature = "rust1", since = "1.0.0")]
114116
pub struct CString {
115117
// Invariant 1: the slice ends with a zero byte and has a length of at least one.
@@ -1265,7 +1267,7 @@ impl CStr {
12651267
/// behavior when `ptr` is used inside the `unsafe` block:
12661268
///
12671269
/// ```no_run
1268-
/// # #![allow(unused_must_use)]
1270+
/// # #![allow(unused_must_use, temporary_cstring_as_ptr)]
12691271
/// use std::ffi::CString;
12701272
///
12711273
/// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// ignore-tidy-linelength
2+
#![deny(temporary_cstring_as_ptr)]
3+
4+
use std::ffi::CString;
5+
6+
fn some_function(data: *const i8) {}
7+
8+
fn main() {
9+
some_function(CString::new("").unwrap().as_ptr()); //~ ERROR getting the inner pointer of a temporary `CString`
10+
}
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: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+
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// ignore-tidy-linelength
2+
// this program is not technically incorrect, but is an obscure enough style to be worth linting
3+
#![deny(temporary_cstring_as_ptr)]
4+
5+
use std::ffi::CString;
6+
7+
fn main() {
8+
let s = CString::new("some text").unwrap().as_ptr(); //~ 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:8: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:3: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
@@ -689,7 +689,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
689689
&methods::SKIP_WHILE_NEXT,
690690
&methods::STRING_EXTEND_CHARS,
691691
&methods::SUSPICIOUS_MAP,
692-
&methods::TEMPORARY_CSTRING_AS_PTR,
693692
&methods::UNINIT_ASSUMED_INIT,
694693
&methods::UNNECESSARY_FILTER_MAP,
695694
&methods::UNNECESSARY_FOLD,
@@ -1376,7 +1375,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13761375
LintId::of(&methods::SKIP_WHILE_NEXT),
13771376
LintId::of(&methods::STRING_EXTEND_CHARS),
13781377
LintId::of(&methods::SUSPICIOUS_MAP),
1379-
LintId::of(&methods::TEMPORARY_CSTRING_AS_PTR),
13801378
LintId::of(&methods::UNINIT_ASSUMED_INIT),
13811379
LintId::of(&methods::UNNECESSARY_FILTER_MAP),
13821380
LintId::of(&methods::UNNECESSARY_FOLD),
@@ -1721,7 +1719,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
17211719
LintId::of(&mem_replace::MEM_REPLACE_WITH_UNINIT),
17221720
LintId::of(&methods::CLONE_DOUBLE_REF),
17231721
LintId::of(&methods::ITERATOR_STEP_BY_ZERO),
1724-
LintId::of(&methods::TEMPORARY_CSTRING_AS_PTR),
17251722
LintId::of(&methods::UNINIT_ASSUMED_INIT),
17261723
LintId::of(&methods::ZST_OFFSET),
17271724
LintId::of(&minmax::MIN_MAX),

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

Lines changed: 0 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -797,40 +797,6 @@ declare_clippy_lint! {
797797
"using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
798798
}
799799

800-
declare_clippy_lint! {
801-
/// **What it does:** Checks for getting the inner pointer of a temporary
802-
/// `CString`.
803-
///
804-
/// **Why is this bad?** The inner pointer of a `CString` is only valid as long
805-
/// as the `CString` is alive.
806-
///
807-
/// **Known problems:** None.
808-
///
809-
/// **Example:**
810-
/// ```rust
811-
/// # use std::ffi::CString;
812-
/// # fn call_some_ffi_func(_: *const i8) {}
813-
/// #
814-
/// let c_str = CString::new("foo").unwrap().as_ptr();
815-
/// unsafe {
816-
/// call_some_ffi_func(c_str);
817-
/// }
818-
/// ```
819-
/// Here `c_str` points to a freed address. The correct use would be:
820-
/// ```rust
821-
/// # use std::ffi::CString;
822-
/// # fn call_some_ffi_func(_: *const i8) {}
823-
/// #
824-
/// let c_str = CString::new("foo").unwrap();
825-
/// unsafe {
826-
/// call_some_ffi_func(c_str.as_ptr());
827-
/// }
828-
/// ```
829-
pub TEMPORARY_CSTRING_AS_PTR,
830-
correctness,
831-
"getting the inner pointer of a temporary `CString`"
832-
}
833-
834800
declare_clippy_lint! {
835801
/// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
836802
///
@@ -1405,7 +1371,6 @@ declare_lint_pass!(Methods => [
14051371
SINGLE_CHAR_PATTERN,
14061372
SINGLE_CHAR_PUSH_STR,
14071373
SEARCH_IS_SOME,
1408-
TEMPORARY_CSTRING_AS_PTR,
14091374
FILTER_NEXT,
14101375
SKIP_WHILE_NEXT,
14111376
FILTER_MAP,
@@ -1486,7 +1451,6 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
14861451
lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
14871452
},
14881453
["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1489-
["as_ptr", "unwrap" | "expect"] => lint_cstring_as_ptr(cx, expr, &arg_lists[1][0], &arg_lists[0][0]),
14901454
["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
14911455
["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
14921456
["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
@@ -2235,26 +2199,6 @@ fn lint_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>
22352199
}
22362200
}
22372201

2238-
fn lint_cstring_as_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, source: &hir::Expr<'_>, unwrap: &hir::Expr<'_>) {
2239-
if_chain! {
2240-
let source_type = cx.typeck_results().expr_ty(source);
2241-
if let ty::Adt(def, substs) = source_type.kind();
2242-
if cx.tcx.is_diagnostic_item(sym!(result_type), def.did);
2243-
if match_type(cx, substs.type_at(0), &paths::CSTRING);
2244-
then {
2245-
span_lint_and_then(
2246-
cx,
2247-
TEMPORARY_CSTRING_AS_PTR,
2248-
expr.span,
2249-
"you are getting the inner pointer of a temporary `CString`",
2250-
|diag| {
2251-
diag.note("that pointer will be invalid outside this expression");
2252-
diag.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
2253-
});
2254-
}
2255-
}
2256-
}
2257-
22582202
fn lint_iter_cloned_collect<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
22592203
if_chain! {
22602204
if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym!(vec_type));

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

Lines changed: 0 additions & 1 deletion
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)