use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
use std::collections::HashSet;
use tree_sitter::Node;
pub struct Mem12C;
impl CertRule for Mem12C {
fn rule_id(&self) -> &'static str {
"MEM12-C"
}
fn description(&self) -> &'static str {
"Consider using a goto chain when leaving a function on error when using and releasing resources"
}
fn severity(&self) -> Severity {
Severity::Low
}
fn category(&self) -> RuleCategory {
RuleCategory::Rule
}
fn cert_id(&self) -> &'static str {
"MEM12-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
if node.kind() == "function_definition" {
self.check_function(node, source, &mut violations);
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
violations.extend(self.check(&child, source));
}
}
violations
}
}
impl Mem12C {
fn check_function(&self, func_node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
let body = match func_node.child_by_field_name("body") {
Some(b) => b,
None => return,
};
let mut allocations: Vec<(String, usize)> = Vec::new(); let mut deallocations: Vec<(String, usize)> = Vec::new();
self.find_allocations(&body, source, &mut allocations);
self.find_deallocations(&body, source, &mut deallocations);
self.check_early_returns(&body, source, &allocations, &deallocations, violations);
}
fn find_allocations(&self, node: &Node, source: &str, allocations: &mut Vec<(String, usize)>) {
if node.kind() == "assignment_expression" {
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let var_name = get_node_text(&left, source).trim().to_string();
let right_text = get_node_text(&right, source);
if self.is_allocation_call(&right_text) {
let line = node.start_position().row;
allocations.push((var_name, line));
}
}
} else if node.kind() == "init_declarator" {
if let Some(value) = node.child_by_field_name("value") {
if let Some(declarator) = node.child_by_field_name("declarator") {
let var_name = get_node_text(&declarator, source).trim().to_string();
let value_text = get_node_text(&value, source);
if self.is_allocation_call(&value_text) {
let line = node.start_position().row;
allocations.push((var_name, line));
}
}
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.find_allocations(&child, source, allocations);
}
}
}
fn find_deallocations(
&self,
node: &Node,
source: &str,
deallocations: &mut Vec<(String, usize)>,
) {
if node.kind() == "call_expression" {
if let Some(function) = node.child_by_field_name("function") {
let func_name = get_node_text(&function, source);
if func_name == "fclose" || func_name == "free" || func_name == "close" {
if let Some(arguments) = node.child_by_field_name("arguments") {
for i in 0..arguments.child_count() {
if let Some(arg) = arguments.child(i) {
if arg.kind() != "(" && arg.kind() != ")" && arg.kind() != "," {
let resource_name =
get_node_text(&arg, source).trim().to_string();
let line = node.start_position().row;
deallocations.push((resource_name, line));
break;
}
}
}
}
}
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.find_deallocations(&child, source, deallocations);
}
}
}
fn check_early_returns(
&self,
node: &Node,
source: &str,
allocations: &[(String, usize)],
deallocations: &[(String, usize)],
violations: &mut Vec<RuleViolation>,
) {
if node.kind() == "return_statement" {
let return_line = node.start_position().row;
let allocated_before: Vec<&String> = allocations
.iter()
.filter(|(_, alloc_line)| *alloc_line < return_line)
.map(|(name, _)| name)
.collect();
let deallocated_before: HashSet<&str> = deallocations
.iter()
.filter(|(_, dealloc_line)| *dealloc_line < return_line)
.map(|(name, _)| name.as_str())
.collect();
let leaked: Vec<&str> = allocated_before
.iter()
.filter(|name| !deallocated_before.contains(name.as_str()))
.map(|s| s.as_str())
.collect();
if !leaked.is_empty() && allocated_before.len() > 1 {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
message: format!(
"Function returns without releasing all resources. Leaked: {}. \
Consider using goto chain for proper resource cleanup.",
leaked.join(", ")
),
severity: self.severity(),
line: return_line + 1,
column: node.start_position().column + 1,
file_path: String::new(),
suggestion: Some(
"Use goto chain pattern with cleanup labels to ensure all resources are released"
.to_string(),
),
requires_manual_review: None,
});
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.check_early_returns(&child, source, allocations, deallocations, violations);
}
}
}
fn is_allocation_call(&self, expr: &str) -> bool {
expr.contains("fopen(")
|| expr.contains("malloc(")
|| expr.contains("calloc(")
|| expr.contains("realloc(")
|| expr.contains("open(")
|| expr.contains("socket(")
}
}