Auto merge of #9635 - smoelius:fix-9386-bug, r=Jarcho

Fix bug introduced by #9386

#9386 introduced a potential out-of-bounds array access. Specifically, a location returned by `local_assignments` could have  [`location.statement_index` equal to `mir.basic_blocks[location.block].statements.len()`](b8a9a507bf/clippy_utils/src/mir/mod.rs (L129)), in which case the location would refer to the block terminator:
b8a9a507bf/clippy_lints/src/dereference.rs (L1204-L1206)
I suspect the bug is not triggerable now, because of checks leading up to where it occurs. But a future code change could make it triggerable. Hence, it should be fixed.

r? `@Jarcho`

changelog: none
This commit is contained in:
bors 2022-10-20 15:18:31 +00:00
commit 967f172e25
2 changed files with 5 additions and 6 deletions

View file

@ -1192,16 +1192,16 @@ fn has_ref_mut_self_method(cx: &LateContext<'_>, trait_def_id: DefId) -> bool {
})
}
fn referent_used_exactly_once<'a, 'tcx>(
cx: &'a LateContext<'tcx>,
fn referent_used_exactly_once<'tcx>(
cx: &LateContext<'tcx>,
possible_borrowers: &mut Vec<(LocalDefId, PossibleBorrowerMap<'tcx, 'tcx>)>,
reference: &Expr<'tcx>,
) -> bool {
let mir = enclosing_mir(cx.tcx, reference.hir_id);
if let Some(local) = expr_local(cx.tcx, reference)
&& let [location] = *local_assignments(mir, local).as_slice()
&& let StatementKind::Assign(box (_, Rvalue::Ref(_, _, place))) =
mir.basic_blocks[location.block].statements[location.statement_index].kind
&& let Some(statement) = mir.basic_blocks[location.block].statements.get(location.statement_index)
&& let StatementKind::Assign(box (_, Rvalue::Ref(_, _, place))) = statement.kind
&& !place.has_deref()
{
let body_owner_local_def_id = cx.tcx.hir().enclosing_body_owner(reference.hir_id);

View file

@ -121,8 +121,7 @@ pub fn expr_local(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> Option<Local> {
})
}
/// Returns a vector of `mir::Location` where `local` is assigned. Each statement referred to has
/// kind `StatementKind::Assign`.
/// Returns a vector of `mir::Location` where `local` is assigned.
pub fn local_assignments(mir: &Body<'_>, local: Local) -> Vec<Location> {
let mut locations = Vec::new();
for (block, data) in mir.basic_blocks.iter_enumerated() {