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
//! CON32-C: Prevent data races when accessing bit-fields from multiple threads
//!
//! When accessing a bit-field, a thread may inadvertently access a separate bit-field
//! in adjacent memory. This is because compilers are required to store multiple adjacent
//! bit-fields in one storage unit whenever they fit. Consequently, data races may exist
//! not just on a bit-field accessed by multiple threads but also on other bit-fields
//! sharing the same byte or word.
//!
//! ## Examples:
//!
//! **Non-compliant:**
//! ```c
//! struct multi_threaded_flags {
//!   unsigned int flag1 : 2;
//!   unsigned int flag2 : 2;
//! };
//!
//! struct multi_threaded_flags flags;
//!
//! int thread1(void *arg) {
//!   flags.flag1 = 1;  // Data race: may access same memory as flag2
//!   return 0;
//! }
//!
//! int thread2(void *arg) {
//!   flags.flag2 = 2;  // Data race: may access same memory as flag1
//!   return 0;
//! }
//! ```
//!
//! **Compliant (Mutex):**
//! ```c
//! #include <threads.h>
//!
//! struct multi_threaded_flags {
//!   unsigned int flag1 : 2;
//!   unsigned int flag2 : 2;
//! };
//!
//! struct mtf_mutex {
//!   struct multi_threaded_flags s;
//!   mtx_t mutex;
//! };
//!
//! int thread1(void *arg) {
//!   mtx_lock(&flags.mutex);
//!   flags.s.flag1 = 1;
//!   mtx_unlock(&flags.mutex);
//!   return 0;
//! }
//! ```
//!
//! **Compliant (Separate bytes):**
//! ```c
//! struct multi_threaded_flags {
//!   unsigned char flag1;  // No bit-fields
//!   unsigned char flag2;
//! };
//! ```
//!
//! ## Detection Strategy:
//! - Find struct definitions containing bit-fields
//! - Track accesses to bit-field members
//! - Check if bit-field accesses are in functions that look like thread functions
//! - Check if bit-field accesses are protected by mutex locks
//! - Flag unprotected bit-field accesses in potential thread functions

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

pub struct Con32C;

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

    fn description(&self) -> &'static str {
        "Prevent data races when accessing bit-fields from multiple threads"
    }

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

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

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

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

        // First pass: collect structs that contain bit-fields
        let bitfield_structs = self.collect_bitfield_structs(node, source);

        // Second pass: find accesses to bit-field members without mutex protection
        self.check_node(node, source, &bitfield_structs, &mut violations);

        violations
    }
}

impl Con32C {
    /// Collect struct names that contain bit-fields and their bit-field member names
    fn collect_bitfield_structs(
        &self,
        node: &Node,
        source: &str,
    ) -> HashMap<String, HashSet<String>> {
        let mut bitfield_structs = HashMap::new();
        self.find_bitfield_structs(node, source, &mut bitfield_structs);
        bitfield_structs
    }

    fn find_bitfield_structs(
        &self,
        node: &Node,
        source: &str,
        bitfield_structs: &mut HashMap<String, HashSet<String>>,
    ) {
        if node.kind() == "struct_specifier" {
            if let Some(name_node) = node.child_by_field_name("name") {
                let struct_name = get_node_text(&name_node, source).to_string();

                // Check if this struct has bit-fields
                if let Some(body) = node.child_by_field_name("body") {
                    let bitfield_members = self.find_bitfield_members(&body, source);
                    if !bitfield_members.is_empty() {
                        bitfield_structs.insert(struct_name, bitfield_members);
                    }
                }
            }
        }

        // Recursively check children
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.find_bitfield_structs(&child, source, bitfield_structs);
            }
        }
    }

    fn find_bitfield_members(&self, body: &Node, source: &str) -> HashSet<String> {
        let mut members = HashSet::new();

        for i in 0..body.child_count() {
            if let Some(child) = body.child(i) {
                if child.kind() == "field_declaration" {
                    // Check if this field has a bit-field width
                    if self.is_bitfield_declaration(&child, source) {
                        // Extract the field name
                        if let Some(name) = self.get_field_name(&child, source) {
                            members.insert(name);
                        }
                    }
                }
            }
        }

        members
    }

    fn is_bitfield_declaration(&self, node: &Node, _source: &str) -> bool {
        // A bit-field declaration has a bitfield_clause child (e.g., ": 2")
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "bitfield_clause" {
                    return true;
                }
            }
        }
        false
    }

    fn get_field_name(&self, node: &Node, source: &str) -> Option<String> {
        // Look for field_identifier, field_declarator or identifier in the declaration
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                match child.kind() {
                    "field_identifier" => {
                        return Some(get_node_text(&child, source).to_string());
                    }
                    "field_declarator" => {
                        if let Some(name) = self.get_identifier_name(&child, source) {
                            return Some(name);
                        }
                    }
                    "identifier" => {
                        return Some(get_node_text(&child, source).to_string());
                    }
                    _ => {}
                }
            }
        }
        None
    }

    fn get_identifier_name(&self, node: &Node, source: &str) -> Option<String> {
        if node.kind() == "identifier" {
            return Some(get_node_text(node, source).to_string());
        }

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if let Some(name) = self.get_identifier_name(&child, source) {
                    return Some(name);
                }
            }
        }

        None
    }

    fn check_node(
        &self,
        node: &Node,
        source: &str,
        bitfield_structs: &HashMap<String, HashSet<String>>,
        violations: &mut Vec<RuleViolation>,
    ) {
        // Look for function definitions that might be thread functions
        if node.kind() == "function_definition" {
            self.check_function_for_bitfield_access(node, source, bitfield_structs, violations);
        }

        // Recursively check child nodes
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.check_node(&child, source, bitfield_structs, violations);
            }
        }
    }

    fn check_function_for_bitfield_access(
        &self,
        function_node: &Node,
        source: &str,
        bitfield_structs: &HashMap<String, HashSet<String>>,
        violations: &mut Vec<RuleViolation>,
    ) {
        let func_name = self
            .get_function_name(function_node, source)
            .unwrap_or_else(|| "<unknown>".to_string());

        // Check if this looks like a thread function (has void* parameter or named "thread*")
        if !self.is_potential_thread_function(function_node, source, &func_name) {
            return;
        }

        // Get function body
        let body = match function_node.child_by_field_name("body") {
            Some(b) => b,
            None => return,
        };

        // Check if function uses mutex locks
        let has_mutex = self.uses_mutex_lock(&body, source);

        // Find bit-field accesses in the function
        let bitfield_accesses = self.find_bitfield_accesses(&body, source, bitfield_structs);

        // If function accesses bit-fields without mutex protection, flag it
        if !bitfield_accesses.is_empty() && !has_mutex {
            for (struct_name, member_name, line) in bitfield_accesses {
                violations.push(RuleViolation {
                    rule_id: self.rule_id().to_string(),
                    severity: Severity::Medium,
                    message: format!(
                        "Function '{}' accesses bit-field '{}.{}' without mutex protection in a multi-threaded context",
                        func_name, struct_name, member_name
                    ),
                    file_path: String::new(),
                    line,
                    column: 0,
                    suggestion: Some(
                        "Protect bit-field accesses with mutex locks or use separate byte-sized members instead of bit-fields".to_string()
                    ),
                    ..Default::default()
                });
            }
        }
    }

    fn get_function_name(&self, function_node: &Node, source: &str) -> Option<String> {
        for i in 0..function_node.child_count() {
            if let Some(child) = function_node.child(i) {
                if child.kind() == "function_declarator" {
                    if let Some(name) = self.get_identifier_name(&child, source) {
                        return Some(name);
                    }
                }
            }
        }
        None
    }

    fn is_potential_thread_function(
        &self,
        function_node: &Node,
        source: &str,
        func_name: &str,
    ) -> bool {
        // Check if function name suggests it's a thread function
        if func_name.to_lowercase().contains("thread") {
            return true;
        }

        // Check if function has void* parameter (common for thread functions)
        for i in 0..function_node.child_count() {
            if let Some(child) = function_node.child(i) {
                if child.kind() == "function_declarator" {
                    if let Some(params) = child.child_by_field_name("parameters") {
                        for j in 0..params.child_count() {
                            if let Some(param) = params.child(j) {
                                if param.kind() == "parameter_declaration" {
                                    let param_text = get_node_text(&param, source);
                                    if param_text.contains("void") && param_text.contains("*") {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        false
    }

    fn uses_mutex_lock(&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);
                if matches!(
                    func_name,
                    "mtx_lock" | "mtx_unlock" | "pthread_mutex_lock" | "pthread_mutex_unlock"
                ) {
                    return true;
                }
            }
        }

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if self.uses_mutex_lock(&child, source) {
                    return true;
                }
            }
        }

        false
    }

    fn find_bitfield_accesses(
        &self,
        node: &Node,
        source: &str,
        bitfield_structs: &HashMap<String, HashSet<String>>,
    ) -> Vec<(String, String, usize)> {
        let mut accesses = Vec::new();
        self.collect_bitfield_accesses(node, source, bitfield_structs, &mut accesses);
        accesses
    }

    fn collect_bitfield_accesses(
        &self,
        node: &Node,
        source: &str,
        bitfield_structs: &HashMap<String, HashSet<String>>,
        accesses: &mut Vec<(String, String, usize)>,
    ) {
        // Look for field_expression (e.g., flags.flag1)
        if node.kind() == "field_expression" {
            if let Some(field_node) = node.child_by_field_name("field") {
                let field_name = get_node_text(&field_node, source).to_string();

                // Try to determine the struct type
                if let Some(object) = node.child_by_field_name("argument") {
                    let object_text = get_node_text(&object, source);

                    // Check if this field belongs to a bit-field struct
                    for (struct_name, members) in bitfield_structs {
                        if members.contains(&field_name) {
                            // Found a bit-field access
                            let line = node.start_position().row + 1;
                            accesses.push((struct_name.clone(), field_name.clone(), line));
                            break;
                        }
                    }

                    // Also check for nested access like flags.s.flag1
                    if object_text.contains('.') {
                        // This is a nested field access
                        for (struct_name, members) in bitfield_structs {
                            if members.contains(&field_name) {
                                let line = node.start_position().row + 1;
                                accesses.push((struct_name.clone(), field_name.clone(), line));
                                break;
                            }
                        }
                    }
                }
            }
        }

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.collect_bitfield_accesses(&child, source, bitfield_structs, accesses);
            }
        }
    }
}