use std::collections::BTreeSet;
use cpp_parser::CppAstNode;
use cpp_parser::CppSyntaxKind;
use super::{Check, CheckContext, DiagnosticCode};
pub struct UseAfterFree;
impl Check for UseAfterFree {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::UseAfterFree];
fn check(context: &mut CheckContext<'_>) {
let bodies: Vec<cpp_parser::CppSyntaxNode> = context
.own::<cpp_parser::CppDeclaration>()
.filter(|declaration| {
declaration
.syntax()
.children()
.any(|child| kind(&child) == CppSyntaxKind::CompoundStat)
})
.filter_map(|declaration| {
declaration
.syntax()
.children()
.find(|child| kind(child) == CppSyntaxKind::CompoundStat)
})
.collect();
for body in bodies {
let mut freed: Freed = BTreeSet::new();
walk(&body, &mut freed, context);
}
}
}
type Freed = BTreeSet<usize>;
fn walk(statement: &cpp_parser::CppSyntaxNode, freed: &mut Freed, context: &mut CheckContext<'_>) {
match kind(statement) {
CppSyntaxKind::CompoundStat | CppSyntaxKind::ElseStat => {
for child in statement.children() {
walk(&child, freed, context);
}
}
CppSyntaxKind::IfStat
| CppSyntaxKind::ForStat
| CppSyntaxKind::WhileStat
| CppSyntaxKind::DoWhileStat
| CppSyntaxKind::SwitchStat
| CppSyntaxKind::TryStat => {
let mut inside = freed.clone();
for child in statement.children() {
walk(&child, &mut inside, context);
}
}
CppSyntaxKind::ExpressionStat | CppSyntaxKind::ReturnStat | CppSyntaxKind::Declaration => {
check_uses(statement, freed, context);
apply_effects(statement, freed, context);
}
_ => check_uses(statement, freed, context),
}
}
fn check_uses(
statement: &cpp_parser::CppSyntaxNode,
freed: &Freed,
context: &mut CheckContext<'_>,
) {
for candidate in statement.descendants() {
let (base, reads_through_it) = match kind(&candidate) {
CppSyntaxKind::MemberExpr | CppSyntaxKind::IndexExpr => {
let arrow = candidate
.children_with_tokens()
.filter_map(|element| element.into_token())
.any(|token| {
cpp_parser::CppTokenKind::from(token.kind())
== cpp_parser::CppTokenKind::Arrow
});
let bracket = candidate
.children_with_tokens()
.filter_map(|element| element.into_token())
.any(|token| {
cpp_parser::CppTokenKind::from(token.kind())
== cpp_parser::CppTokenKind::LeftBracket
});
let Some(base) = candidate.children().next() else {
continue;
};
(base, arrow || bracket)
}
CppSyntaxKind::UnaryExpr => {
let star = candidate
.children_with_tokens()
.filter_map(|element| element.into_token())
.next()
.map(|token| cpp_parser::CppTokenKind::from(token.kind()))
== Some(cpp_parser::CppTokenKind::Star);
let Some(base) = candidate.children().next() else {
continue;
};
(base, star)
}
_ => continue,
};
if !reads_through_it {
continue;
}
let Some((offset, name)) = the_variable(&base, context) else {
continue;
};
if !freed.contains(&offset) {
continue;
}
let range = cpp_parser::source_range(base.text_range());
context.add(
DiagnosticCode::UseAfterFree,
range,
name.clone(),
format!("`{name}` is used after the memory it refers to was freed"),
);
}
}
fn apply_effects(
statement: &cpp_parser::CppSyntaxNode,
freed: &mut Freed,
context: &mut CheckContext<'_>,
) {
for candidate in statement.descendants() {
match kind(&candidate) {
CppSyntaxKind::UnaryExpr => {
let is_delete = candidate
.children_with_tokens()
.filter_map(|element| element.into_token())
.next()
.map(|token| cpp_parser::CppTokenKind::from(token.kind()))
== Some(cpp_parser::CppTokenKind::DeleteKeyword);
if is_delete
&& let Some(operand) = candidate.children().next()
&& let Some((offset, _)) = the_variable(&operand, context)
{
freed.insert(offset);
}
}
CppSyntaxKind::CallExpr => {
let Some(callee) = candidate.children().next() else {
continue;
};
let arguments: Vec<cpp_parser::CppSyntaxNode> =
candidate.children().skip(1).collect();
let name = the_last_identifier_of(&callee);
match name.as_deref() {
Some("free") => {
if let Some(argument) = arguments.first()
&& let Some((offset, _)) = the_variable(argument, context)
{
freed.insert(offset);
}
}
Some("destroy_at") => {
if let Some(argument) = arguments.first()
&& let Some((offset, _)) = the_variable(argument, context)
{
freed.insert(offset);
}
}
Some("reset") if is_a_member_access(&callee) => {
if let Some(receiver) = callee.children().next()
&& let Some((offset, _)) = the_variable(&receiver, context)
{
freed.insert(offset);
}
}
_ => {
if let Some(frees) = the_frees_of(context, &callee)
&& frees != 0
{
for (index, argument) in arguments.iter().enumerate() {
if index < 64
&& frees & (1 << index) != 0
&& let Some((offset, _)) = the_variable(argument, context)
{
freed.insert(offset);
}
}
}
}
}
}
CppSyntaxKind::BinaryExpr => {
let assignment = candidate
.children_with_tokens()
.filter_map(|element| element.into_token())
.any(|token| {
cpp_parser::CppTokenKind::from(token.kind())
== cpp_parser::CppTokenKind::Assign
});
if !assignment {
continue;
}
let mut children = candidate.children();
let (Some(target), Some(value)) = (children.next(), children.next()) else {
continue;
};
let Some((offset, _)) = the_variable(&target, context) else {
continue;
};
match the_variable(&value, context) {
Some((source, _)) if freed.contains(&source) => {
freed.insert(offset);
}
_ => {
freed.remove(&offset);
}
}
}
_ => {}
}
}
}
fn the_frees_of(context: &CheckContext<'_>, callee: &cpp_parser::CppSyntaxNode) -> Option<u64> {
if let Some(offset) = the_last_identifier_offset(callee)
&& let crate::Known::Yes(binding) =
crate::sema::resolve::definition_at(context.scopes(), context.tree(), offset)
{
let name = binding.name.text();
let scope = context.scopes().qualified_name_of(binding.scope);
if let Some(fact) = context.summary.declarations.iter().find(|fact| {
fact.name == name && fact.scope == scope && fact.kind == crate::DeclKind::Function
}) {
return Some(fact.frees);
}
let spelling = match scope.as_deref() {
Some(scope) if !scope.is_empty() => format!("{scope}::{name}"),
_ => name,
};
if let crate::Known::Yes(found) = context.index().definition(&spelling, context.path) {
return Some(found.fact.frees);
}
}
if is_a_member_access(callee) {
return None;
}
let name = the_last_identifier_of(callee)?;
match context.index().definition(&name, context.path) {
crate::Known::Yes(found) => Some(found.fact.frees),
_ => None,
}
}
fn the_variable(
expression: &cpp_parser::CppSyntaxNode,
context: &CheckContext<'_>,
) -> Option<(usize, String)> {
let expression = skip_parentheses(expression);
match kind(&expression) {
CppSyntaxKind::UnaryExpr => the_variable(&expression.children().next()?, context),
CppSyntaxKind::IdentifierExpr | CppSyntaxKind::NameExpr => {
let offset = the_last_identifier_offset(&expression)?;
let crate::Known::Yes(binding) =
crate::sema::resolve::definition_at(context.scopes(), context.tree(), offset)
else {
return None;
};
let scope = context.scopes().scope(binding.scope)?;
if !matches!(
scope.kind,
crate::ScopeKind::Function | crate::ScopeKind::Block | crate::ScopeKind::Lambda
) {
return None;
}
Some((binding.name_range.start_offset, binding.name.text()))
}
_ => None,
}
}
fn skip_parentheses(expression: &cpp_parser::CppSyntaxNode) -> cpp_parser::CppSyntaxNode {
if kind(expression) != CppSyntaxKind::ParenExpr {
return expression.clone();
}
expression
.children()
.next()
.map(|inner| skip_parentheses(&inner))
.unwrap_or_else(|| expression.clone())
}
fn is_a_member_access(expression: &cpp_parser::CppSyntaxNode) -> bool {
expression
.children_with_tokens()
.filter_map(|element| element.into_token())
.any(|token| {
matches!(
cpp_parser::CppTokenKind::from(token.kind()),
cpp_parser::CppTokenKind::Dot | cpp_parser::CppTokenKind::Arrow
)
})
}
fn the_last_identifier_offset(expression: &cpp_parser::CppSyntaxNode) -> Option<usize> {
expression
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.filter(|token| {
cpp_parser::CppTokenKind::from(token.kind()) == cpp_parser::CppTokenKind::Identifier
})
.last()
.map(|token| usize::from(token.text_range().start()))
}
fn the_last_identifier_of(expression: &cpp_parser::CppSyntaxNode) -> Option<String> {
expression
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.filter(|token| {
cpp_parser::CppTokenKind::from(token.kind()) == cpp_parser::CppTokenKind::Identifier
})
.last()
.map(|token| token.text().to_string())
}
fn kind(node: &cpp_parser::CppSyntaxNode) -> CppSyntaxKind {
CppSyntaxKind::from(node.kind())
}