sqc 0.4.13

Software Code Quality - CERT C compliance checker
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! POS38-C: Beware of race conditions when using fork and file descriptors
//!
//! This rule detects race conditions that occur when:
//! 1. A file descriptor is opened (via open(), fopen(), etc.)
//! 2. fork() is called, duplicating the file descriptor
//! 3. Both parent and child processes use the same file descriptor
//!
//! When a process forks, file descriptors are duplicated, meaning both parent
//! and child share the same file offset and status flags. Concurrent operations
//! on the shared file descriptor create race conditions.
//!
//! ## Examples:
//!
//! **Non-compliant:**
//! ```c
//! int fd = open("file.txt", O_RDWR);
//! if (fd == -1) { /* Handle error */ }
//! read(fd, &c, 1);
//!
//! pid_t pid = fork();
//! if (pid == 0) {
//!     read(fd, &c, 1);  // Child reads - RACE CONDITION
//! } else {
//!     read(fd, &c, 1);  // Parent reads - RACE CONDITION
//! }
//! ```
//!
//! **Compliant:**
//! ```c
//! int fd = open("file.txt", O_RDWR);
//! if (fd == -1) { /* Handle error */ }
//! read(fd, &c, 1);
//!
//! pid_t pid = fork();
//! if (pid == 0) {
//!     close(fd);  // Child closes parent's fd
//!     fd = open("file.txt", O_RDWR);  // Child opens its own fd
//!     read(fd, &c, 1);
//! } else {
//!     read(fd, &c, 1);  // Parent uses original fd
//! }
//! ```
//!
//! ## Detection Strategy:
//! - Track file descriptors from open/fopen calls
//! - Detect fork() calls
//! - Check if file descriptors are used after fork in both parent/child branches
//! - Report violations when shared file descriptor usage is detected

use crate::manifest::{RuleCategory, Severity};
use crate::prelude::RuleViolation;
use crate::rules::cert_c::CertRule;
use crate::utility::cert_c::ast_utils::get_node_text;
use std::collections::HashSet;
use tree_sitter::Node;

pub struct Pos38C;

impl CertRule for Pos38C {
    fn rule_id(&self) -> &'static str {
        "POS38-C"
    }

    fn cert_id(&self) -> &'static str {
        "POS38"
    }

    fn description(&self) -> &'static str {
        "Beware of race conditions when using fork and file descriptors"
    }

    fn severity(&self) -> Severity {
        Severity::Medium
    }

    fn category(&self) -> RuleCategory {
        RuleCategory::Rule
    }

    fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
        let mut violations = Vec::new();
        self.check_node(node, source, &mut violations);
        violations
    }
}

impl Pos38C {
    fn check_node(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
        // Only check at function_definition level to avoid nested traversals
        // (translation_unit would cause redundant checks on function children)
        if node.kind() == "function_definition" {
            self.check_scope_for_fork_pattern(node, source, violations);
            // Don't recurse into function body - we've already checked it
            return;
        }

        // Recurse through children to find function definitions
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            self.check_node(&child, source, violations);
        }
    }

    fn check_scope_for_fork_pattern(
        &self,
        node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        // Get the body node to check (function body or translation unit itself)
        let scope_node = if node.kind() == "function_definition" {
            if let Some(body) = node.child_by_field_name("body") {
                body
            } else {
                return;
            }
        } else {
            *node // translation_unit - check the whole file
        };

        // Collect file descriptors opened in this scope
        let mut file_descriptors = HashSet::new();
        self.collect_file_descriptors(&scope_node, source, &mut file_descriptors);

        // Check for fork() calls and subsequent fd usage
        self.check_for_fork_with_fd_usage(&scope_node, source, &file_descriptors, violations);
    }

    fn collect_file_descriptors(
        &self,
        node: &Node,
        source: &str,
        file_descriptors: &mut HashSet<String>,
    ) {
        // Look for variable declarations with file opening calls
        if node.kind() == "declaration" {
            // Get the full declaration text to check for open() calls
            let decl_text = get_node_text(node, source);
            if self.is_file_opening_call(&decl_text) {
                // Find init_declarator children
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if child.kind() == "init_declarator" {
                        // Get the declarator to extract variable name
                        if let Some(declarator) = child.child_by_field_name("declarator") {
                            if let Some(var_name) = self.extract_variable_name(&declarator, source)
                            {
                                file_descriptors.insert(var_name);
                            }
                        }
                    }
                }
            }
        } else if node.kind() == "assignment_expression" {
            if let Some(left) = node.child_by_field_name("left") {
                if let Some(right) = node.child_by_field_name("right") {
                    let right_text = get_node_text(&right, source);
                    if self.is_file_opening_call(&right_text) {
                        let var_name = get_node_text(&left, source).trim().to_string();
                        file_descriptors.insert(var_name);
                    }
                }
            }
        }

        // Recurse through children
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            self.collect_file_descriptors(&child, source, file_descriptors);
        }
    }

    fn is_file_opening_call(&self, text: &str) -> bool {
        let text = text.trim();
        text.contains("open(")
            || text.contains("fopen(")
            || text.contains("fdopen(")
            || text.contains("creat(")
            || text.contains("openat(")
    }

    #[allow(dead_code)]
    fn find_declarator<'a>(&self, node: &'a Node) -> Option<Node<'a>> {
        if node.kind() == "init_declarator" {
            node.child_by_field_name("declarator")
        } else if node.kind() == "declaration" {
            // Look for init_declarator child
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "init_declarator" {
                    if let Some(declarator) = child.child_by_field_name("declarator") {
                        return Some(declarator);
                    }
                }
            }
            None
        } else {
            None
        }
    }

    fn extract_variable_name(&self, declarator: &Node, source: &str) -> Option<String> {
        // Handle different declarator types
        match declarator.kind() {
            "identifier" => Some(get_node_text(declarator, source).trim().to_string()),
            "pointer_declarator" => {
                // Look for the identifier in the pointer declarator
                let mut cursor = declarator.walk();
                for child in declarator.children(&mut cursor) {
                    if child.kind() == "identifier" {
                        return Some(get_node_text(&child, source).trim().to_string());
                    }
                }
                None
            }
            _ => None,
        }
    }

    fn check_for_fork_with_fd_usage(
        &self,
        node: &Node,
        source: &str,
        file_descriptors: &HashSet<String>,
        violations: &mut Vec<RuleViolation>,
    ) {
        // Look for fork() calls
        if node.kind() == "call_expression" {
            if let Some(function) = node.child_by_field_name("function") {
                let func_text = get_node_text(&function, source);
                if func_text.trim() == "fork" {
                    // Found a fork() call - check for fd usage in subsequent code
                    self.check_fd_usage_after_fork(node, source, file_descriptors, violations);
                    return; // Don't recurse further as we've handled this subtree
                }
            }
        }

        // Recurse through children
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            self.check_for_fork_with_fd_usage(&child, source, file_descriptors, violations);
        }
    }

    fn check_fd_usage_after_fork(
        &self,
        fork_node: &Node,
        source: &str,
        file_descriptors: &HashSet<String>,
        violations: &mut Vec<RuleViolation>,
    ) {
        // Look for the parent statement containing the fork call
        if let Some(parent_stmt) = self.find_parent_statement(fork_node) {
            // Find all following if statements and check them
            if let Some(parent) = parent_stmt.parent() {
                let mut found_stmt = false;
                let mut cursor = parent.walk();
                for sibling in parent.children(&mut cursor) {
                    if found_stmt && sibling.kind() == "if_statement" {
                        // Check if this if statement has both branches (consequence and alternative)
                        // Skip error-handling if statements (e.g., `if (pid == -1)`) that don't have else
                        let has_else_branch = sibling.child_by_field_name("alternative").is_some();

                        if has_else_branch {
                            // Check both branches for fd usage
                            let parent_branch_uses_fd = self.branch_uses_file_descriptor(
                                &sibling,
                                source,
                                file_descriptors,
                                true,
                            );
                            let child_branch_uses_fd = self.branch_uses_file_descriptor(
                                &sibling,
                                source,
                                file_descriptors,
                                false,
                            );

                            if parent_branch_uses_fd && child_branch_uses_fd {
                                // Both branches use a file descriptor - potential race condition
                                let start_point = fork_node.start_position();
                                violations.push(RuleViolation {
                                    rule_id: self.rule_id().to_string(),
                                    severity: Severity::Medium,
                                    message: "Race condition detected: file descriptor used after fork() in both parent and child processes. File descriptors are shared after fork(), leading to nondeterministic behavior.".to_string(),
                                    file_path: String::new(),
                                    line: start_point.row + 1,
                                    column: start_point.column + 1,
                                    suggestion: Some(
                                        "Close the file descriptor in one process and reopen it, or use separate file descriptors for parent and child.".to_string()
                                    ),
                                    ..Default::default()
                                });
                                return; // Found the violation, no need to check further
                            }
                        }
                        // Continue checking other if statements (don't return early)
                    }
                    if sibling.id() == parent_stmt.id() {
                        found_stmt = true;
                    }
                }
            }
        }
    }

    fn find_parent_statement<'a>(&self, node: &'a Node) -> Option<Node<'a>> {
        // Find the statement-level parent (expression_statement or declaration)
        // that is a direct child of a compound_statement
        let mut current = *node;
        while let Some(parent) = current.parent() {
            if parent.kind() == "expression_statement" || parent.kind() == "declaration" {
                // Verify this is a direct child of compound_statement
                if let Some(grandparent) = parent.parent() {
                    if grandparent.kind() == "compound_statement" {
                        return Some(parent);
                    }
                }
            }
            current = parent;
        }
        None
    }

    #[allow(dead_code)]
    fn find_following_if_statement<'a>(&self, stmt_node: &'a Node) -> Option<Node<'a>> {
        // Look for a sibling if statement
        if let Some(parent) = stmt_node.parent() {
            let mut found_stmt = false;
            let mut cursor = parent.walk();
            for sibling in parent.children(&mut cursor) {
                if found_stmt && sibling.kind() == "if_statement" {
                    return Some(sibling);
                }
                if sibling.id() == stmt_node.id() {
                    found_stmt = true;
                }
            }
        }
        None
    }

    fn branch_uses_file_descriptor(
        &self,
        if_stmt: &Node,
        source: &str,
        file_descriptors: &HashSet<String>,
        check_else: bool,
    ) -> bool {
        let branch = if check_else {
            // Check else/alternative branch (parent process)
            if_stmt.child_by_field_name("alternative")
        } else {
            // Check consequence branch (child process - pid == 0)
            if_stmt.child_by_field_name("consequence")
        };

        if let Some(branch_node) = branch {
            self.subtree_uses_file_descriptor(&branch_node, source, file_descriptors)
        } else {
            false
        }
    }

    fn subtree_uses_file_descriptor(
        &self,
        node: &Node,
        source: &str,
        file_descriptors: &HashSet<String>,
    ) -> bool {
        // Check for close() calls first - if fd is closed, it's not being used (safe pattern)
        if self.subtree_closes_file_descriptor(node, source, file_descriptors) {
            return false;
        }

        let node_text = get_node_text(node, source);

        // Check if any of the file descriptors are mentioned in this subtree
        // in a context that uses them (not just closes them)
        for fd in file_descriptors {
            if node_text.contains(fd) {
                return true;
            }
        }

        false
    }

    fn subtree_closes_file_descriptor(
        &self,
        node: &Node,
        source: &str,
        file_descriptors: &HashSet<String>,
    ) -> bool {
        // Look for close() calls on the file descriptors
        if node.kind() == "call_expression" {
            if let Some(function) = node.child_by_field_name("function") {
                let func_text = get_node_text(&function, source);
                if func_text.trim() == "close" {
                    // Check if the argument is one of our file descriptors
                    if let Some(args) = node.child_by_field_name("arguments") {
                        let args_text = get_node_text(&args, source);
                        for fd in file_descriptors {
                            if args_text.contains(fd) {
                                return true;
                            }
                        }
                    }
                }
            }
        }

        // Recurse through children
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if self.subtree_closes_file_descriptor(&child, source, file_descriptors) {
                return true;
            }
        }

        false
    }
}