use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
use std::cell::RefCell;
use tree_sitter::Node;
#[derive(Debug)]
pub struct Err01C {
file_stream_functions_seen: RefCell<bool>,
}
impl Err01C {
pub fn new() -> Self {
Err01C {
file_stream_functions_seen: RefCell::new(false),
}
}
fn is_file_stream_function(&self, name: &str) -> bool {
matches!(
name,
"printf"
| "fprintf"
| "sprintf"
| "snprintf"
| "vprintf"
| "vfprintf"
| "vsprintf"
| "vsnprintf"
| "scanf"
| "fscanf"
| "sscanf"
| "vscanf"
| "vfscanf"
| "vsscanf"
| "fgetc"
| "fgets"
| "getc"
| "getchar"
| "gets"
| "fputc"
| "fputs"
| "putc"
| "putchar"
| "puts"
| "ungetc"
| "fread"
| "fwrite"
| "fseek"
| "ftell"
| "rewind"
| "fgetpos"
| "fsetpos"
| "fflush"
| "fclose"
| "fopen"
| "freopen"
| "setbuf"
| "setvbuf"
)
}
fn is_errno(&self, node: &Node, source: &str) -> bool {
node.kind() == "identifier" && get_node_text(node, source) == "errno"
}
fn contains_errno(&self, node: &Node, source: &str) -> bool {
if self.is_errno(node, source) {
return true;
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if self.contains_errno(&child, source) {
return true;
}
}
false
}
fn is_errno_check(&self, node: &Node, source: &str) -> bool {
match node.kind() {
"if_statement" | "while_statement" | "do_statement" | "for_statement" => {
if let Some(condition) = node.child_by_field_name("condition") {
return self.contains_errno(&condition, source);
}
}
"binary_expression" | "unary_expression" | "parenthesized_expression" => {
return self.contains_errno(node, source);
}
_ => {}
}
false
}
fn check_call_expression(&self, node: &Node, source: &str) {
if node.kind() != "call_expression" {
return;
}
if let Some(function) = node.child_by_field_name("function") {
let func_name = get_node_text(&function, source);
if self.is_file_stream_function(func_name) {
*self.file_stream_functions_seen.borrow_mut() = true;
}
}
}
fn is_errno_setting_function(&self, name: &str) -> bool {
matches!(
name,
"strtol"
| "strtoll"
| "strtoul"
| "strtoull"
| "strtod"
| "strtof"
| "strtold"
| "strtoimax"
| "strtoumax"
| "sqrt"
| "pow"
| "log"
| "log10"
| "log2"
| "exp"
| "fmod"
| "asin"
| "acos"
)
}
fn check_errno_usage(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
if self.is_errno_check(node, source) && *self.file_stream_functions_seen.borrow() {
violations.push(RuleViolation {
rule_id: "ERR01-C".to_string(),
severity: Severity::Low,
line: node.start_position().row + 1,
column: node.start_position().column + 1,
message: "errno is checked after FILE stream operations; use ferror() instead"
.to_string(),
file_path: String::new(),
suggestion: Some(
"Use ferror() to check for errors on FILE streams instead of checking errno"
.to_string(),
),
requires_manual_review: Some(false),
});
}
}
fn process_function(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
if node.kind() != "function_definition" {
return;
}
*self.file_stream_functions_seen.borrow_mut() = false;
if let Some(body) = node.child_by_field_name("body") {
self.traverse_block(&body, source, violations);
self.check_errno_setting_functions(&body, source, violations);
}
}
fn check_errno_setting_functions(
&self,
body: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
let mut errno_calls = Vec::new();
self.collect_errno_setting_calls(body, source, &mut errno_calls);
if errno_calls.is_empty() {
return;
}
let body_has_errno = self.contains_errno(body, source);
if !body_has_errno {
for (line, col, func_name) in errno_calls {
violations.push(RuleViolation {
rule_id: "ERR01-C".to_string(),
severity: Severity::Low,
line,
column: col,
message: format!(
"{}() can set errno but errno is not checked after the call",
func_name
),
file_path: String::new(),
suggestion: Some(format!(
"Set errno to 0 before calling {}() and check errno afterward to detect errors",
func_name
)),
requires_manual_review: Some(false),
});
}
}
}
fn collect_errno_setting_calls(
&self,
node: &Node,
source: &str,
calls: &mut Vec<(usize, usize, String)>,
) {
if node.kind() == "call_expression" {
if let Some(function) = node.child_by_field_name("function") {
let func_name = get_node_text(&function, source);
if self.is_errno_setting_function(func_name) {
calls.push((
node.start_position().row + 1,
node.start_position().column + 1,
func_name.to_string(),
));
}
}
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
self.collect_errno_setting_calls(&child, source, calls);
}
}
fn traverse_block(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
self.check_call_expression(&child, source);
self.check_errno_usage(&child, source, violations);
if child.kind() == "compound_statement" {
self.traverse_block(&child, source, violations);
} else {
let mut child_cursor = child.walk();
for grandchild in child.children(&mut child_cursor) {
if grandchild.kind() == "call_expression" {
self.check_call_expression(&grandchild, source);
}
}
}
}
}
fn traverse(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
if node.kind() == "function_definition" {
self.process_function(node, source, violations);
} else if node.kind() == "translation_unit" {
*self.file_stream_functions_seen.borrow_mut() = false;
self.traverse_top_level(node, source, violations);
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
self.traverse(&child, source, violations);
}
}
fn traverse_top_level(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "function_definition" {
continue;
}
if child.kind() == "expression_statement" {
self.check_expression_statement(&child, source, violations);
}
if child.kind() == "if_statement" {
self.check_errno_usage(&child, source, violations);
}
}
}
fn check_expression_statement(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "call_expression" {
self.check_call_expression(&child, source);
}
self.check_errno_usage(&child, source, violations);
self.find_calls_recursive(&child, source);
}
}
fn find_calls_recursive(&self, node: &Node, source: &str) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "call_expression" {
self.check_call_expression(&child, source);
}
self.find_calls_recursive(&child, source);
}
}
}
impl CertRule for Err01C {
fn rule_id(&self) -> &'static str {
"ERR01-C"
}
fn description(&self) -> &'static str {
"Use ferror() rather than errno to check for FILE stream errors"
}
fn category(&self) -> RuleCategory {
RuleCategory::Rule
}
fn severity(&self) -> Severity {
Severity::Low
}
fn cert_id(&self) -> &'static str {
"ERR01-C"
}
fn check(&self, root: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
self.traverse(root, source, &mut violations);
violations
}
}