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 Con36C;
impl CertRule for Con36C {
fn rule_id(&self) -> &'static str {
"CON36-C"
}
fn description(&self) -> &'static str {
"Wrap functions that can spuriously wake up in a loop"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Rule
}
fn cert_id(&self) -> &'static str {
"CON36-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
self.check_node(node, source, &mut violations);
violations
}
}
impl Con36C {
fn check_node(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
if node.kind() == "call_expression" {
self.check_cnd_wait_call(node, source, violations);
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.check_node(&child, source, violations);
}
}
}
fn check_cnd_wait_call(
&self,
call_node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
if let Some(function) = call_node.child_by_field_name("function") {
let func_name = get_node_text(&function, source);
if func_name == "cnd_wait" || func_name == "cnd_timedwait" {
if self.is_inside_if_not_while(call_node) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message: format!(
"Call to '{}' is wrapped in an 'if' statement. Use 'while' loop to handle spurious wake-ups.",
func_name
),
file_path: String::new(),
line: call_node.start_position().row + 1,
column: call_node.start_position().column + 1,
suggestion: Some(
"Replace the 'if' statement with a 'while' loop to re-check the condition after wake-up".to_string()
),
..Default::default()
});
}
}
}
}
fn is_inside_if_not_while(&self, node: &Node) -> bool {
let mut current = node.parent();
let mut found_if = false;
while let Some(parent) = current {
match parent.kind() {
"if_statement" => {
found_if = true;
}
"while_statement" | "do_statement" | "for_statement" => {
return false;
}
"function_definition" => {
break;
}
_ => {}
}
current = parent.parent();
}
found_if
}
}