2019-05-14 03:06:21 -05:00
|
|
|
use crate::utils::{match_def_path, paths, span_help_and_lint};
|
2018-11-27 14:14:15 -06:00
|
|
|
use if_chain::if_chain;
|
2018-12-29 09:04:45 -06:00
|
|
|
use rustc::hir::*;
|
|
|
|
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
|
|
|
|
use rustc::ty;
|
2019-04-08 15:43:55 -05:00
|
|
|
use rustc::{declare_lint_pass, declare_tool_lint};
|
2017-09-28 21:24:31 -05:00
|
|
|
|
2018-03-28 08:24:26 -05:00
|
|
|
declare_clippy_lint! {
|
2019-03-05 10:50:33 -06:00
|
|
|
/// **What it does:** Checks for creation of references to zeroed or uninitialized memory.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** Creation of null references is undefined behavior.
|
|
|
|
///
|
|
|
|
/// **Known problems:** None.
|
|
|
|
///
|
|
|
|
/// **Example:**
|
2019-03-05 16:23:50 -06:00
|
|
|
/// ```no_run
|
|
|
|
/// let bad_ref: &usize = unsafe { std::mem::zeroed() };
|
2019-03-05 10:50:33 -06:00
|
|
|
/// ```
|
2017-09-28 21:24:31 -05:00
|
|
|
pub INVALID_REF,
|
2018-03-28 08:24:26 -05:00
|
|
|
correctness,
|
2017-09-28 21:24:31 -05:00
|
|
|
"creation of invalid reference"
|
|
|
|
}
|
|
|
|
|
|
|
|
const ZERO_REF_SUMMARY: &str = "reference to zeroed memory";
|
|
|
|
const UNINIT_REF_SUMMARY: &str = "reference to uninitialized memory";
|
2017-11-04 14:56:05 -05:00
|
|
|
const HELP: &str = "Creation of a null reference is undefined behavior; \
|
|
|
|
see https://doc.rust-lang.org/reference/behavior-considered-undefined.html";
|
2017-09-28 21:24:31 -05:00
|
|
|
|
2019-04-08 15:43:55 -05:00
|
|
|
declare_lint_pass!(InvalidRef => [INVALID_REF]);
|
2017-09-28 21:24:31 -05:00
|
|
|
|
|
|
|
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidRef {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
|
2017-10-23 14:18:02 -05:00
|
|
|
if_chain! {
|
2018-07-12 02:30:57 -05:00
|
|
|
if let ExprKind::Call(ref path, ref args) = expr.node;
|
|
|
|
if let ExprKind::Path(ref qpath) = path.node;
|
2017-10-23 14:18:02 -05:00
|
|
|
if args.len() == 0;
|
2018-08-22 16:34:52 -05:00
|
|
|
if let ty::Ref(..) = cx.tables.expr_ty(expr).sty;
|
2019-05-03 19:03:12 -05:00
|
|
|
if let Some(def_id) = cx.tables.qpath_res(qpath, path.hir_id).opt_def_id();
|
2017-10-23 14:18:02 -05:00
|
|
|
then {
|
2019-05-17 16:53:54 -05:00
|
|
|
let msg = if match_def_path(cx, def_id, &paths::MEM_ZEROED) |
|
|
|
|
match_def_path(cx, def_id, &paths::INIT)
|
2017-11-04 14:56:05 -05:00
|
|
|
{
|
2017-10-23 14:18:02 -05:00
|
|
|
ZERO_REF_SUMMARY
|
2019-05-17 16:53:54 -05:00
|
|
|
} else if match_def_path(cx, def_id, &paths::MEM_UNINIT) |
|
|
|
|
match_def_path(cx, def_id, &paths::UNINIT)
|
2017-11-04 14:56:05 -05:00
|
|
|
{
|
2017-10-23 14:18:02 -05:00
|
|
|
UNINIT_REF_SUMMARY
|
|
|
|
} else {
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
span_help_and_lint(cx, INVALID_REF, expr.span, msg, HELP);
|
|
|
|
}
|
2017-11-04 14:55:56 -05:00
|
|
|
}
|
2017-09-28 21:24:31 -05:00
|
|
|
}
|
|
|
|
}
|