-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Add a new lint that warns for pointers to stack memory #134218
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
1c3t3a
wants to merge
1
commit into
rust-lang:master
Choose a base branch
from
1c3t3a:stack-memory-warning
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+255
−4
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -55,10 +55,10 @@ use crate::lints::{ | |
BuiltinIncompleteFeatures, BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures, | ||
BuiltinKeywordIdents, BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc, | ||
BuiltinMutablesTransmutes, BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns, | ||
BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasBounds, | ||
BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub, | ||
BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment, | ||
BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel, | ||
BuiltinReturningPointersToLocalVariables, BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, | ||
BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, | ||
BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, | ||
BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel, | ||
}; | ||
use crate::nonstandard_style::{MethodLateContext, method_context}; | ||
use crate::{ | ||
|
@@ -3063,6 +3063,159 @@ impl<'tcx> LateLintPass<'tcx> for AsmLabels { | |
} | ||
} | ||
|
||
declare_lint! { | ||
/// The `returning_pointers_to_local_variables` lint detects when pointer | ||
/// to stack memory associated with a local variable is returned. That | ||
/// pointer is immediately dangling. | ||
/// | ||
/// ### Example | ||
/// | ||
/// ```rust,no_run | ||
/// fn foo() -> *const i32 { | ||
/// let x = 42; | ||
/// &x | ||
/// } | ||
/// ``` | ||
/// | ||
/// {{produces}} | ||
/// | ||
/// ### Explanation | ||
/// | ||
/// Returning a pointer to memory refering to a local variable will always | ||
/// end up in a dangling pointer after returning. | ||
pub RETURNING_POINTERS_TO_LOCAL_VARIABLES, | ||
Warn, | ||
"returning a pointer to stack memory associated with a local variable", | ||
} | ||
|
||
declare_lint_pass!(ReturningPointersToLocalVariables => [RETURNING_POINTERS_TO_LOCAL_VARIABLES]); | ||
|
||
impl<'tcx> LateLintPass<'tcx> for ReturningPointersToLocalVariables { | ||
fn check_fn( | ||
&mut self, | ||
cx: &LateContext<'tcx>, | ||
_: HirFnKind<'tcx>, | ||
fn_decl: &'tcx FnDecl<'tcx>, | ||
body: &'tcx Body<'tcx>, | ||
_: Span, | ||
_: LocalDefId, | ||
) { | ||
let hir::FnRetTy::Return(&hir::Ty { kind: hir::TyKind::Ptr(ptr_ty), .. }) = fn_decl.output | ||
else { | ||
return; | ||
}; | ||
if matches!(ptr_ty.ty.kind, hir::TyKind::Tup([])) { | ||
return; | ||
} | ||
|
||
// Check the block of the function that we're looking at. | ||
if let Some(block) = Self::get_enclosing_block(cx, body.value.hir_id) { | ||
match block { | ||
&hir::Block { | ||
stmts: | ||
&[ | ||
.., | ||
hir::Stmt { | ||
kind: | ||
hir::StmtKind::Semi(&hir::Expr { | ||
kind: hir::ExprKind::Ret(Some(return_expr)), | ||
.. | ||
}), | ||
.. | ||
}, | ||
], | ||
.. | ||
} => { | ||
Self::maybe_lint_return_expr(cx, return_expr, fn_decl.inputs); | ||
} | ||
hir::Block { expr: Some(return_expr), .. } => { | ||
Self::maybe_lint_return_expr(cx, return_expr, fn_decl.inputs); | ||
} | ||
_ => return, | ||
} | ||
} | ||
} | ||
} | ||
|
||
impl ReturningPointersToLocalVariables { | ||
/// Evaluates the return expression of a function and emits a lint if it | ||
/// returns a pointer to a local variable. | ||
fn maybe_lint_return_expr<'tcx>( | ||
cx: &LateContext<'tcx>, | ||
return_expr: &hir::Expr<'tcx>, | ||
params: &'tcx [hir::Ty<'tcx>], | ||
) { | ||
// Early exit if we see that this is a pointer to an input parameter. | ||
if Self::expr_is_param(cx.typeck_results(), return_expr, params) { | ||
return; | ||
} | ||
|
||
match return_expr { | ||
hir::Expr { kind: hir::ExprKind::AddrOf(_, _, addr_expr), .. } => { | ||
Self::maybe_lint_return_expr(cx, addr_expr, params) | ||
} | ||
hir::Expr { | ||
kind: | ||
hir::ExprKind::Cast( | ||
hir::Expr { kind: hir::ExprKind::AddrOf(_, _, addr_expr), .. }, | ||
_, | ||
), | ||
.. | ||
} => Self::maybe_lint_return_expr(cx, addr_expr, params), | ||
hir::Expr { kind: hir::ExprKind::Cast(expr, _), .. } => { | ||
Self::maybe_lint_return_expr(cx, expr, params) | ||
} | ||
hir::Expr { | ||
kind: | ||
hir::ExprKind::Path( | ||
hir::QPath::Resolved(_, hir::Path { res: hir::def::Res::Local(_), .. }), | ||
.., | ||
), | ||
.. | ||
} => cx.emit_span_lint( | ||
RETURNING_POINTERS_TO_LOCAL_VARIABLES, | ||
return_expr.span, | ||
BuiltinReturningPointersToLocalVariables, | ||
), | ||
Comment on lines
+3168
to
+3179
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. hum, doesn't this also catch fn foo() -> *const Something {
let x: *const Something = ...;
...
x
} ? |
||
_ => (), | ||
} | ||
} | ||
|
||
fn expr_is_param<'tcx>( | ||
typeck_results: &ty::TypeckResults<'tcx>, | ||
expr: &hir::Expr<'tcx>, | ||
params: &'tcx [hir::Ty<'tcx>], | ||
) -> bool { | ||
params | ||
.iter() | ||
.map(|param| typeck_results.type_dependent_def_id(param.hir_id)) | ||
.collect::<Vec<_>>() | ||
.contains(&typeck_results.type_dependent_def_id(expr.hir_id)) | ||
} | ||
|
||
/// Returns the enclosing block for a [hir::HirId], if available. | ||
fn get_enclosing_block<'tcx>( | ||
cx: &LateContext<'tcx>, | ||
hir_id: hir::HirId, | ||
) -> Option<&'tcx hir::Block<'tcx>> { | ||
let enclosing_node = cx | ||
.tcx | ||
.hir_get_enclosing_scope(hir_id) | ||
.map(|enclosing_id| cx.tcx.hir_node(enclosing_id)); | ||
enclosing_node.and_then(|node| match node { | ||
hir::Node::Block(block) => Some(block), | ||
hir::Node::Item(&hir::Item { kind: hir::ItemKind::Fn { body: eid, .. }, .. }) | ||
| hir::Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, eid), .. }) => { | ||
match cx.tcx.hir_body(eid).value.kind { | ||
hir::ExprKind::Block(block, _) => Some(block), | ||
_ => None, | ||
} | ||
} | ||
_ => None, | ||
}) | ||
} | ||
} | ||
|
||
declare_lint! { | ||
/// The `special_module_name` lint detects module | ||
/// declarations for files that have a special meaning. | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
52 changes: 52 additions & 0 deletions
52
tests/ui/lint/lint-returning-pointers-to-local-variables.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
//@ check-pass | ||
|
||
#![warn(returning_pointers_to_local_variables)] | ||
|
||
fn foo() -> *const u32 { | ||
let empty = 42u32; | ||
return &empty as *const _; | ||
//~^ WARN returning a pointer to stack memory associated with a local variable | ||
} | ||
|
||
fn bar() -> *const u32 { | ||
let empty = 42u32; | ||
&empty as *const _ | ||
//~^ WARN returning a pointer to stack memory associated with a local variable | ||
} | ||
|
||
fn baz() -> *const u32 { | ||
let empty = 42u32; | ||
return ∅ | ||
//~^ WARN returning a pointer to stack memory associated with a local variable | ||
} | ||
|
||
fn faa() -> *const u32 { | ||
let empty = 42u32; | ||
&empty | ||
//~^ WARN returning a pointer to stack memory associated with a local variable | ||
} | ||
|
||
fn pointer_to_pointer() -> *const *mut u32 { | ||
let mut empty = 42u32; | ||
&(&mut empty as *mut u32) as *const _ | ||
//~^ WARN returning a pointer to stack memory associated with a local variable | ||
} | ||
|
||
fn dont_lint_unit() -> *const () { | ||
let foo = (); | ||
&foo as *const _ | ||
} | ||
|
||
fn dont_lint_param(val: u32) -> *const u32 { | ||
&val | ||
} | ||
|
||
struct Foo {} | ||
|
||
impl Foo { | ||
fn dont_lint_self_param(&self) -> *const Foo { | ||
self | ||
} | ||
} | ||
|
||
fn main() {} |
38 changes: 38 additions & 0 deletions
38
tests/ui/lint/lint-returning-pointers-to-local-variables.stderr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
warning: returning a pointer to stack memory associated with a local variable | ||
--> $DIR/lint-returning-pointers-to-local-variables.rs:7:13 | ||
| | ||
LL | return &empty as *const _; | ||
| ^^^^^ | ||
| | ||
note: the lint level is defined here | ||
--> $DIR/lint-returning-pointers-to-local-variables.rs:3:9 | ||
| | ||
LL | #![warn(returning_pointers_to_local_variables)] | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
|
||
warning: returning a pointer to stack memory associated with a local variable | ||
--> $DIR/lint-returning-pointers-to-local-variables.rs:13:6 | ||
| | ||
LL | &empty as *const _ | ||
| ^^^^^ | ||
|
||
warning: returning a pointer to stack memory associated with a local variable | ||
--> $DIR/lint-returning-pointers-to-local-variables.rs:19:13 | ||
| | ||
LL | return ∅ | ||
| ^^^^^ | ||
|
||
warning: returning a pointer to stack memory associated with a local variable | ||
--> $DIR/lint-returning-pointers-to-local-variables.rs:25:6 | ||
| | ||
LL | &empty | ||
| ^^^^^ | ||
|
||
warning: returning a pointer to stack memory associated with a local variable | ||
--> $DIR/lint-returning-pointers-to-local-variables.rs:31:12 | ||
| | ||
LL | &(&mut empty as *mut u32) as *const _ | ||
| ^^^^^ | ||
|
||
warning: 5 warnings emitted | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There's no good reason to exclude the unit type from this analysis.