use tree_sitter::Node;
use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
pub struct Con37C;
impl CertRule for Con37C {
fn rule_id(&self) -> &'static str {
"CON37-C"
}
fn description(&self) -> &'static str {
"Do not call signal() in a multithreaded program"
}
fn severity(&self) -> Severity {
Severity::High
}
fn category(&self) -> RuleCategory {
RuleCategory::Rule
}
fn cert_id(&self) -> &'static str {
"CON37-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
let has_threading = self.has_threading_functions(node, source);
if has_threading {
self.check_signal_calls(node, source, &mut violations);
}
violations
}
}
impl Con37C {
fn has_threading_functions(&self, node: &Node, source: &str) -> bool {
if node.kind() == "call_expression" {
if let Some(func) = node.child_by_field_name("function") {
let func_name = get_node_text(&func, source).trim();
if matches!(
func_name,
"thrd_create"
| "pthread_create"
| "CreateThread"
| "_beginthread"
| "_beginthreadex"
| "thrd_join"
| "pthread_join"
| "mtx_init"
| "pthread_mutex_init"
) {
return true;
}
}
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if self.has_threading_functions(&child, source) {
return true;
}
}
false
}
fn check_signal_calls(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
if node.kind() == "call_expression" {
if let Some(func) = node.child_by_field_name("function") {
let func_name = get_node_text(&func, source).trim();
if func_name == "signal" {
let line = node.start_position().row + 1;
let column = node.start_position().column + 1;
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: "Calling signal() in a multithreaded program causes undefined behavior."
.to_string(),
file_path: String::new(),
line,
column,
suggestion: Some(
"Use sigaction() on POSIX systems or platform-specific thread-safe alternatives."
.to_string(),
),
requires_manual_review: None,
});
}
}
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
self.check_signal_calls(&child, source, violations);
}
}
}