Skip to content

Commit 4e321b6

Browse files
committed
Add a new lint for catching unbound lifetimes in return values
This lint is based on some unsoundness found in Libra during security audits. Some function signatures can look sound, but based on the concrete types that end up being used, lifetimes may be unbound instead of anchored to the references of the arguments or the fields of a struct. When combined with unsafe code, this can cause transmuted lifetimes to be not what was intended.
1 parent b245fbd commit 4e321b6

File tree

8 files changed

+210
-2
lines changed

8 files changed

+210
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,6 +1226,7 @@ Released 2018-09-13
12261226
[`try_err`]: https://rust-lang.github.io/rust-clippy/master/index.html#try_err
12271227
[`type_complexity`]: https://rust-lang.github.io/rust-clippy/master/index.html#type_complexity
12281228
[`type_repetition_in_bounds`]: https://rust-lang.github.io/rust-clippy/master/index.html#type_repetition_in_bounds
1229+
[`unbound_return_lifetimes`]: https://rust-lang.github.io/rust-clippy/master/index.html#unbound_return_lifetimes
12291230
[`unicode_not_nfc`]: https://rust-lang.github.io/rust-clippy/master/index.html#unicode_not_nfc
12301231
[`unimplemented`]: https://rust-lang.github.io/rust-clippy/master/index.html#unimplemented
12311232
[`uninit_assumed_init`]: https://rust-lang.github.io/rust-clippy/master/index.html#uninit_assumed_init

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
88

9-
[There are 340 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
9+
[There are 341 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
1010

1111
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1212

clippy_lints/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,7 @@ pub mod transmuting_null;
290290
pub mod trivially_copy_pass_by_ref;
291291
pub mod try_err;
292292
pub mod types;
293+
pub mod unbound_return_lifetimes;
293294
pub mod unicode;
294295
pub mod unsafe_removed_from_name;
295296
pub mod unused_io_amount;
@@ -770,6 +771,7 @@ pub fn register_plugins(store: &mut lint::LintStore, sess: &Session, conf: &Conf
770771
&types::UNIT_CMP,
771772
&types::UNNECESSARY_CAST,
772773
&types::VEC_BOX,
774+
&unbound_return_lifetimes::UNBOUND_RETURN_LIFETIMES,
773775
&unicode::NON_ASCII_LITERAL,
774776
&unicode::UNICODE_NOT_NFC,
775777
&unicode::ZERO_WIDTH_SPACE,
@@ -937,6 +939,7 @@ pub fn register_plugins(store: &mut lint::LintStore, sess: &Session, conf: &Conf
937939
store.register_late_pass(|| box trait_bounds::TraitBounds);
938940
store.register_late_pass(|| box comparison_chain::ComparisonChain);
939941
store.register_late_pass(|| box mul_add::MulAddCheck);
942+
store.register_late_pass(|| box unbound_return_lifetimes::UnboundReturnLifetimes);
940943
store.register_early_pass(|| box reference::DerefAddrOf);
941944
store.register_early_pass(|| box reference::RefInDeref);
942945
store.register_early_pass(|| box double_parens::DoubleParens);
@@ -1300,6 +1303,7 @@ pub fn register_plugins(store: &mut lint::LintStore, sess: &Session, conf: &Conf
13001303
LintId::of(&types::UNIT_CMP),
13011304
LintId::of(&types::UNNECESSARY_CAST),
13021305
LintId::of(&types::VEC_BOX),
1306+
LintId::of(&unbound_return_lifetimes::UNBOUND_RETURN_LIFETIMES),
13031307
LintId::of(&unicode::ZERO_WIDTH_SPACE),
13041308
LintId::of(&unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME),
13051309
LintId::of(&unused_io_amount::UNUSED_IO_AMOUNT),
@@ -1547,6 +1551,7 @@ pub fn register_plugins(store: &mut lint::LintStore, sess: &Session, conf: &Conf
15471551
LintId::of(&types::CAST_PTR_ALIGNMENT),
15481552
LintId::of(&types::CAST_REF_TO_MUT),
15491553
LintId::of(&types::UNIT_CMP),
1554+
LintId::of(&unbound_return_lifetimes::UNBOUND_RETURN_LIFETIMES),
15501555
LintId::of(&unicode::ZERO_WIDTH_SPACE),
15511556
LintId::of(&unused_io_amount::UNUSED_IO_AMOUNT),
15521557
LintId::of(&unwrap::PANICKING_UNWRAP),
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
use if_chain::if_chain;
2+
use rustc::declare_lint_pass;
3+
use rustc::hir::*;
4+
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5+
use rustc_session::declare_tool_lint;
6+
7+
use crate::utils::span_lint;
8+
9+
declare_clippy_lint! {
10+
/// **What it does:** Checks for lifetime annotations on return values
11+
/// which might not always get bound.
12+
///
13+
/// **Why is this bad?** If the function contains unsafe code which
14+
/// transmutes to the lifetime, the resulting lifetime may live longer
15+
/// than was intended.
16+
///
17+
/// **Known problems*: None.
18+
///
19+
/// **Example:**
20+
/// ```rust
21+
/// // Bad: unbound return lifetime causing unsoundnes
22+
/// fn foo<'a>(x: impl AsRef<str> + 'a) -> &'a str {
23+
/// let s = x.as_ref();
24+
/// unsafe { &*(s as *const str) }
25+
/// }
26+
/// // Good: bound return lifetime is sound
27+
/// struct WrappedStr(str);
28+
/// fn foo<'a>(x: &'a str) -> &'a WrappedStr {
29+
/// unsafe { &*(x as *const str as *const WrappedStr) }
30+
/// }
31+
/// ```
32+
pub UNBOUND_RETURN_LIFETIMES,
33+
correctness,
34+
"unbound lifetimes in function return values"
35+
}
36+
37+
declare_lint_pass!(UnboundReturnLifetimes => [UNBOUND_RETURN_LIFETIMES]);
38+
39+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnboundReturnLifetimes {
40+
fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
41+
if let ItemKind::Fn(ref sig, ref generics, _id) = item.kind {
42+
check_fn_inner(cx, &sig.decl, generics, None);
43+
}
44+
}
45+
46+
fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
47+
if let ImplItemKind::Method(ref sig, _) = item.kind {
48+
let parent_generics = impl_generics(cx, item.hir_id);
49+
check_fn_inner(cx, &sig.decl, &item.generics, parent_generics);
50+
}
51+
}
52+
}
53+
54+
fn check_fn_inner<'a, 'tcx>(
55+
cx: &LateContext<'a, 'tcx>,
56+
decl: &'tcx FnDecl,
57+
generics: &'tcx Generics,
58+
parent_generics: Option<(&'tcx Generics, Option<&'tcx Generics>, Option<&'tcx Generics>)>,
59+
) {
60+
if let FunctionRetTy::Return(ref typ) = decl.output {
61+
if let TyKind::Rptr(ref lifetime, _) = typ.kind {
62+
if let LifetimeName::Param(_) = lifetime.name {
63+
let target_lifetime = lifetime;
64+
65+
// check function generics
66+
// the target lifetime parameter must appear on the left of some outlives relation
67+
if let Some(param) = generics.get_named(target_lifetime.name.ident().name) {
68+
if param.bounds.iter().any(|b| if let GenericBound::Outlives(_) = b { true } else { false }) {
69+
return;
70+
}
71+
}
72+
73+
// check parent generics
74+
// the target lifetime parameter must appear on the left of some outlives relation
75+
if let Some((ref parent_generics, _, _)) = parent_generics {
76+
if let Some(param) = parent_generics.get_named(target_lifetime.name.ident().name) {
77+
if param.bounds.iter().any(|b| if let GenericBound::Outlives(_) = b { true } else { false }) {
78+
return;
79+
}
80+
}
81+
}
82+
83+
// check type generics
84+
// the target lifetime parameter must be included in the struct
85+
if let Some((_, _, Some(ref typ_generics))) = parent_generics {
86+
if typ_generics.get_named(target_lifetime.name.ident().name).is_some() {
87+
return;
88+
}
89+
}
90+
91+
// check arguments
92+
// the target lifetime parameter must be included as a lifetime of a reference
93+
for input in decl.inputs.iter() {
94+
if let TyKind::Rptr(ref lifetime, _) = input.kind {
95+
if lifetime.name == target_lifetime.name {
96+
return;
97+
}
98+
}
99+
}
100+
101+
span_lint(
102+
cx,
103+
UNBOUND_RETURN_LIFETIMES,
104+
target_lifetime.span,
105+
"lifetime is unconstrained"
106+
);
107+
}
108+
}
109+
}
110+
}
111+
112+
fn impl_generics<'tcx>(cx: &LateContext<'_, 'tcx>, hir_id: HirId) -> Option<(&'tcx Generics, Option<&'tcx Generics>, Option<&'tcx Generics>)> {
113+
let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
114+
if_chain! {
115+
if parent_impl != CRATE_HIR_ID;
116+
if let Node::Item(item) = cx.tcx.hir().get(parent_impl);
117+
if let ItemKind::Impl(_, _, _, ref parent_generics, ref _trait_ref, ref ty, _) = item.kind;
118+
then {
119+
if let TyKind::Path(ref qpath) = ty.kind {
120+
if let Some(typ_def_id) = cx.tables.qpath_res(qpath, ty.hir_id).opt_def_id() {
121+
let typ_generics = cx.tcx.hir().get_generics(typ_def_id);
122+
return Some((parent_generics, None, typ_generics))
123+
}
124+
}
125+
}
126+
}
127+
None
128+
}

src/lintlist/mod.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ pub use lint::Lint;
66
pub use lint::LINT_LEVELS;
77

88
// begin lint list, do not remove this comment, it’s used in `update_lints`
9-
pub const ALL_LINTS: [Lint; 340] = [
9+
pub const ALL_LINTS: [Lint; 341] = [
1010
Lint {
1111
name: "absurd_extreme_comparisons",
1212
group: "correctness",
@@ -2037,6 +2037,13 @@ pub const ALL_LINTS: [Lint; 340] = [
20372037
deprecation: None,
20382038
module: "trait_bounds",
20392039
},
2040+
Lint {
2041+
name: "unbound_return_lifetimes",
2042+
group: "correctness",
2043+
desc: "unbound lifetimes in function return values",
2044+
deprecation: None,
2045+
module: "unbound_return_lifetimes",
2046+
},
20402047
Lint {
20412048
name: "unicode_not_nfc",
20422049
group: "pedantic",

tests/ui/unbound_return_lifetimes.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#![allow(
2+
unused,
3+
dead_code,
4+
clippy::needless_lifetimes,
5+
)]
6+
#![warn(clippy::unbound_return_lifetimes)]
7+
8+
use std::hash::Hash;
9+
use std::collections::HashMap;
10+
11+
struct FooStr(str);
12+
13+
fn unbound_fun<'a>(x: impl AsRef<str> + 'a) -> &'a FooStr {
14+
let x = x.as_ref();
15+
unsafe { &*(x as *const str as *const FooStr) }
16+
}
17+
18+
fn bound_fun<'a>(x: &'a str) -> &'a FooStr {
19+
unsafe { &*(x as *const str as *const FooStr) }
20+
}
21+
22+
fn bound_fun2<'a, 'b: 'a, S: 'b>(s: &'a S) -> &'b str {
23+
unreachable!()
24+
}
25+
26+
type BarType<'a, T> = Bar<'a, &'a T>;
27+
28+
struct Bar<'a, T> {
29+
baz: &'a T,
30+
}
31+
32+
impl<'a, T> BarType<'a, T> {
33+
fn bound_impl_fun(&self, _f: bool) -> &'a T {
34+
unreachable!()
35+
}
36+
}
37+
38+
pub struct BazMap<'a, K, V, W> {
39+
alloc: &'a Vec<V>,
40+
map: HashMap<K, W>,
41+
}
42+
43+
pub type BazRefMap<'a, K, V> = BazMap<'a, K, V, &'a V>;
44+
45+
impl<'a, K, V> BazRefMap<'a, K, V>
46+
where
47+
K: Hash + PartialEq,
48+
{
49+
pub fn or_insert(&self, key: K, value: V) -> &'a V {
50+
unreachable!()
51+
}
52+
}
53+
54+
55+
fn main() {}
56+
57+
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: lifetime is unconstrained
2+
--> $DIR/unbound_return_lifetimes.rs:13:49
3+
|
4+
LL | fn unbound_fun<'a>(x: impl AsRef<str> + 'a) -> &'a FooStr {
5+
| ^^
6+
|
7+
= note: `-D clippy::unbound-return-lifetimes` implied by `-D warnings`
8+
9+
error: aborting due to previous error
10+

tests/ui/unbound_return_lifetimes.stdout

Whitespace-only changes.

0 commit comments

Comments
 (0)