use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
use tree_sitter::Node;
pub struct Err06C;
impl CertRule for Err06C {
fn rule_id(&self) -> &'static str {
"ERR06-C"
}
fn description(&self) -> &'static str {
"Understand the termination behavior of assert() and abort()"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"ERR06-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
let has_atexit = self.find_atexit_calls(node, source);
if has_atexit {
self.find_assert_calls(node, source, &mut violations);
}
violations
}
}
impl Err06C {
fn find_atexit_calls(&self, node: &Node, source: &str) -> bool {
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 == "atexit" || func_name == "at_quick_exit" {
return true;
}
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if self.find_atexit_calls(&child, source) {
return true;
}
}
}
false
}
fn find_assert_calls(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
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 == "assert" {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
message: "assert() used when atexit() cleanup handlers are registered. \
assert() calls abort() which bypasses atexit cleanup."
.to_string(),
severity: self.severity(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
file_path: String::new(),
suggestion: Some(
"Replace assert() with explicit error checking: \
if (!condition) { exit(EXIT_FAILURE); }"
.to_string(),
),
requires_manual_review: None,
});
}
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.find_assert_calls(&child, source, violations);
}
}
}
}