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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! INT16-C: Do not make assumptions about representation of signed integers
//!
//! The C Standard permits three different representations for signed integers:
//! - Two's complement
//! - One's complement
//! - Sign and magnitude
//!
//! Bitwise operations on signed integers produce implementation-defined results.
//! Always use unsigned integers for bitwise operations.
//!
//! ## Examples:
//!
//! **Non-compliant:**
//! ```c
//! int value;
//! if (value & 0x1 != 0) {  // Bitwise operation on signed int
//!     // Check if odd - fails on one's complement
//! }
//! ```
//!
//! **Compliant:**
//! ```c
//! // Option 1: Use modulo operator
//! if (value % 2 != 0) {
//!     // Correct way to check if odd
//! }
//!
//! // Option 2: Use unsigned integers
//! unsigned int value;
//! if (value & 0x1 != 0) {
//!     // Bitwise operations are safe on unsigned types
//! }
//! ```

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

pub struct Int16C;

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

    fn description(&self) -> &'static str {
        "Do not make assumptions about representation of signed integers"
    }

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

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

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

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

        // Track signed integer variables (name -> declaration location)
        let mut signed_int_vars: HashMap<String, (usize, usize)> = HashMap::new();

        // Find all signed integer variable declarations
        self.find_signed_int_vars(node, source, &mut signed_int_vars);

        // Find bitwise operations on signed integer variables
        self.find_bitwise_operations(node, source, &signed_int_vars, &mut violations);

        // Find signed-to-unsigned conversions without range check
        self.find_signed_to_unsigned_conversions(node, source, &signed_int_vars, &mut violations);

        violations
    }
}

impl Int16C {
    /// Find signed integer variable declarations (int, short, long, signed char)
    fn find_signed_int_vars(
        &self,
        node: &Node,
        source: &str,
        signed_int_vars: &mut HashMap<String, (usize, usize)>,
    ) {
        if node.kind() == "declaration" {
            let decl_text = get_node_text(node, source);

            // Check if this is a signed integer declaration
            if self.is_signed_int_declaration(&decl_text) {
                if let Some(var_name) = self.extract_var_name(node, source) {
                    signed_int_vars.insert(
                        var_name,
                        (
                            node.start_position().row + 1,
                            node.start_position().column + 1,
                        ),
                    );
                }
            }
        }

        // Check function parameters
        if node.kind() == "parameter_declaration" {
            let param_text = get_node_text(node, source);

            if self.is_signed_int_declaration(&param_text) {
                if let Some(var_name) = self.extract_param_name(node, source) {
                    signed_int_vars.insert(
                        var_name,
                        (
                            node.start_position().row + 1,
                            node.start_position().column + 1,
                        ),
                    );
                }
            }
        }

        // Recurse through children
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.find_signed_int_vars(&child, source, signed_int_vars);
            }
        }
    }

    /// Check if declaration text represents a signed integer type
    fn is_signed_int_declaration(&self, decl_text: &str) -> bool {
        // Unsigned integers are safe - do not track
        if decl_text.contains("unsigned") {
            return false;
        }

        // Check for signed integer types
        // Note: plain 'int', 'short', 'long' are signed by default
        let has_signed_type = decl_text.contains(" int ")
            || decl_text.contains(" int*")
            || decl_text.contains(" int[")
            || decl_text.contains("\\tint ")
            || decl_text.contains("\\tint*")
            || decl_text.contains("\\tint[")
            || decl_text.trim().starts_with("int ")
            || decl_text.trim().starts_with("int*")
            || decl_text.trim().starts_with("int[")
            || decl_text.contains(" short ")
            || decl_text.contains(" short*")
            || decl_text.contains(" long ")
            || decl_text.contains(" long*")
            || decl_text.contains("signed char")
            || decl_text.contains("signed int");

        has_signed_type
    }

    /// Find bitwise operations involving signed integer variables
    fn find_bitwise_operations(
        &self,
        node: &Node,
        source: &str,
        signed_int_vars: &HashMap<String, (usize, usize)>,
        violations: &mut Vec<RuleViolation>,
    ) {
        // Check binary bitwise operations: &, |, ^, <<, >>
        if node.kind() == "binary_expression" {
            if let Some(operator) = node.child_by_field_name("operator") {
                let op_text = get_node_text(&operator, source);

                // Bitwise operators
                let is_bitwise_op =
                    matches!(op_text, "&" | "|" | "^" | "<<" | ">>" | "&=" | "|=" | "^=");

                if is_bitwise_op {
                    // Check left and right operands
                    if let Some(left) = node.child_by_field_name("left") {
                        self.check_operand_for_violation(
                            &left,
                            source,
                            signed_int_vars,
                            violations,
                            op_text,
                        );
                    }
                    if let Some(right) = node.child_by_field_name("right") {
                        self.check_operand_for_violation(
                            &right,
                            source,
                            signed_int_vars,
                            violations,
                            op_text,
                        );
                    }
                }
            }
        }

        // Check unary bitwise NOT operation: ~
        if node.kind() == "unary_expression" {
            if let Some(operator) = node.child_by_field_name("operator") {
                let op_text = get_node_text(&operator, source);

                if op_text == "~" {
                    if let Some(argument) = node.child_by_field_name("argument") {
                        self.check_operand_for_violation(
                            &argument,
                            source,
                            signed_int_vars,
                            violations,
                            "~",
                        );
                    }
                }
            }
        }

        // Recurse through children
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.find_bitwise_operations(&child, source, signed_int_vars, violations);
            }
        }
    }

    /// Check if an operand is a signed integer variable and report violation
    fn check_operand_for_violation(
        &self,
        operand: &Node,
        source: &str,
        signed_int_vars: &HashMap<String, (usize, usize)>,
        violations: &mut Vec<RuleViolation>,
        operator: &str,
    ) {
        let operand_text = get_node_text(operand, source);

        // Check if this operand is a signed integer variable
        if signed_int_vars.contains_key(operand_text) {
            violations.push(RuleViolation {
                rule_id: self.rule_id().to_string(),
                message: format!(
                    "Bitwise operation '{}' on signed integer variable '{}'. \
                     Signed integer representation is implementation-defined. \
                     Use unsigned integers for bitwise operations or use arithmetic operators instead.",
                    operator, operand_text
                ),
                severity: self.severity(),
                line: operand.start_position().row + 1,
                column: operand.start_position().column + 1,
                file_path: String::new(),
                suggestion: Some(format!(
                    "Change '{}' to 'unsigned int {}' or avoid bitwise operations on signed integers",
                    operand_text, operand_text
                )),
                requires_manual_review: None,
            });
        }

        // Also check if operand itself is an identifier
        if operand.kind() == "identifier" {
            // Already handled above
        } else {
            // Recursively check children (for complex expressions)
            for i in 0..operand.child_count() {
                if let Some(child) = operand.child(i) {
                    if child.kind() == "identifier" {
                        let child_text = get_node_text(&child, source);
                        if signed_int_vars.contains_key(child_text) {
                            violations.push(RuleViolation {
                                rule_id: self.rule_id().to_string(),
                                message: format!(
                                    "Bitwise operation '{}' on signed integer variable '{}'. \
                                     Signed integer representation is implementation-defined. \
                                     Use unsigned integers for bitwise operations or use arithmetic operators instead.",
                                    operator, child_text
                                ),
                                severity: self.severity(),
                                line: child.start_position().row + 1,
                                column: child.start_position().column + 1,
                                file_path: String::new(),
                                suggestion: Some(format!(
                                    "Change '{}' to 'unsigned int {}' or avoid bitwise operations on signed integers",
                                    child_text, child_text
                                )),
                                requires_manual_review: None,
                            });
                        }
                    }
                }
            }
        }
    }

    /// Extract variable name from declaration
    fn extract_var_name(&self, decl: &Node, source: &str) -> Option<String> {
        for i in 0..decl.child_count() {
            if let Some(child) = decl.child(i) {
                if child.kind() == "init_declarator" {
                    return self.find_identifier(&child, source);
                } else if child.kind() == "identifier" {
                    return Some(get_node_text(&child, source).to_string());
                }
            }
        }
        None
    }

    /// Extract parameter name from parameter declaration
    fn extract_param_name(&self, param: &Node, source: &str) -> Option<String> {
        for i in 0..param.child_count() {
            if let Some(child) = param.child(i) {
                if child.kind() == "identifier" {
                    return Some(get_node_text(&child, source).to_string());
                }
            }
        }
        None
    }

    /// Find identifier in node tree
    fn find_identifier(&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.find_identifier(&child, source) {
                    return Some(name);
                }
            }
        }
        None
    }

    /// Detect signed-to-unsigned conversions without range checks.
    fn find_signed_to_unsigned_conversions(
        &self,
        node: &Node,
        source: &str,
        signed_int_vars: &HashMap<String, (usize, usize)>,
        violations: &mut Vec<RuleViolation>,
    ) {
        // Check function definitions for unsigned return type + signed return value
        if node.kind() == "function_definition" {
            if self.has_unsigned_return_type(node, source) {
                if let Some(body) = node.child_by_field_name("body") {
                    self.check_unsigned_return_signed(&body, source, signed_int_vars, violations);
                }
            }
        }

        // Check declarations: unsigned var = signed_var
        if node.kind() == "declaration" {
            self.check_unsigned_init_from_signed(node, source, signed_int_vars, violations);
        }

        // Check assignments: unsigned_var = signed_var
        if node.kind() == "assignment_expression" {
            self.check_unsigned_assign_from_signed(node, source, signed_int_vars, violations);
        }

        // Recurse
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.find_signed_to_unsigned_conversions(
                    &child,
                    source,
                    signed_int_vars,
                    violations,
                );
            }
        }
    }

    fn is_unsigned_type_text(text: &str) -> bool {
        text.contains("unsigned")
            || matches!(
                text.trim(),
                "size_t" | "uint8_t" | "uint16_t" | "uint32_t" | "uint64_t" | "uintptr_t"
            )
    }

    fn has_unsigned_return_type(&self, func_node: &Node, source: &str) -> bool {
        // Check type specifiers before the declarator
        let mut cursor = func_node.walk();
        for child in func_node.children(&mut cursor) {
            if matches!(
                child.kind(),
                "sized_type_specifier" | "primitive_type" | "type_identifier"
            ) {
                let type_text = get_node_text(&child, source);
                if Self::is_unsigned_type_text(type_text) {
                    return true;
                }
            }
            // Stop at declarator
            if child.kind() == "function_declarator" || child.kind() == "pointer_declarator" {
                break;
            }
        }
        false
    }

    /// Check return statements that return a signed variable from an unsigned function.
    fn check_unsigned_return_signed(
        &self,
        node: &Node,
        source: &str,
        signed_int_vars: &HashMap<String, (usize, usize)>,
        violations: &mut Vec<RuleViolation>,
    ) {
        if node.kind() == "return_statement" {
            // Get the returned expression (skip "return" keyword)
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "identifier" {
                        let name = get_node_text(&child, source).to_string();
                        if signed_int_vars.contains_key(&name) {
                            if !self.has_non_negative_guard(node, &name, source) {
                                violations.push(RuleViolation {
                                    rule_id: self.rule_id().to_string(),
                                    message: format!(
                                        "Signed variable '{}' returned as unsigned without range check",
                                        name
                                    ),
                                    severity: self.severity(),
                                    line: node.start_position().row + 1,
                                    column: node.start_position().column + 1,
                                    file_path: String::new(),
                                    suggestion: Some(format!(
                                        "Add a range check: if ({} >= 0) before returning as unsigned",
                                        name
                                    )),
                                    requires_manual_review: None,
                                });
                            }
                        }
                    }
                }
            }
        }

        // Recurse
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.check_unsigned_return_signed(&child, source, signed_int_vars, violations);
            }
        }
    }

    /// Check `unsigned int x = signed_var;` declarations.
    fn check_unsigned_init_from_signed(
        &self,
        decl_node: &Node,
        source: &str,
        signed_int_vars: &HashMap<String, (usize, usize)>,
        violations: &mut Vec<RuleViolation>,
    ) {
        let decl_text = get_node_text(decl_node, source);
        if !Self::is_unsigned_type_text(decl_text) {
            return;
        }

        // Look for init_declarator with an identifier initializer
        let mut cursor = decl_node.walk();
        for child in decl_node.children(&mut cursor) {
            if child.kind() == "init_declarator" {
                if let Some(value) = child.child_by_field_name("value") {
                    if value.kind() == "identifier" {
                        let init_name = get_node_text(&value, source).to_string();
                        if signed_int_vars.contains_key(&init_name) {
                            if !self.has_non_negative_guard(decl_node, &init_name, source) {
                                violations.push(RuleViolation {
                                    rule_id: self.rule_id().to_string(),
                                    message: format!(
                                        "Signed variable '{}' assigned to unsigned without range check",
                                        init_name
                                    ),
                                    severity: self.severity(),
                                    line: decl_node.start_position().row + 1,
                                    column: decl_node.start_position().column + 1,
                                    file_path: String::new(),
                                    suggestion: Some(format!(
                                        "Add a range check: if ({} >= 0) before assigning to unsigned",
                                        init_name
                                    )),
                                    requires_manual_review: None,
                                });
                            }
                        }
                    }
                }
            }
        }
    }

    /// Check `unsigned_var = signed_var;` assignments.
    fn check_unsigned_assign_from_signed(
        &self,
        assign_node: &Node,
        source: &str,
        signed_int_vars: &HashMap<String, (usize, usize)>,
        violations: &mut Vec<RuleViolation>,
    ) {
        if let Some(right) = assign_node.child_by_field_name("right") {
            if right.kind() == "identifier" {
                let right_name = get_node_text(&right, source).to_string();
                if !signed_int_vars.contains_key(&right_name) {
                    return;
                }

                // Check if left side is an unsigned variable (not in signed_int_vars, and declared as unsigned)
                if let Some(left) = assign_node.child_by_field_name("left") {
                    let left_name = get_node_text(&left, source).to_string();
                    // If left is known signed, skip (signed = signed is fine for this rule)
                    if signed_int_vars.contains_key(&left_name) {
                        return;
                    }
                    // If left is not in signed_int_vars, it might be unsigned
                    // We flag it and rely on the unsigned declaration check
                    if !self.has_non_negative_guard(assign_node, &right_name, source) {
                        violations.push(RuleViolation {
                            rule_id: self.rule_id().to_string(),
                            message: format!(
                                "Signed variable '{}' assigned to potentially unsigned variable without range check",
                                right_name
                            ),
                            severity: self.severity(),
                            line: assign_node.start_position().row + 1,
                            column: assign_node.start_position().column + 1,
                            file_path: String::new(),
                            suggestion: Some(format!(
                                "Add a range check: if ({} >= 0) before assigning to unsigned",
                                right_name
                            )),
                            requires_manual_review: None,
                        });
                    }
                }
            }
        }
    }

    /// Check if the node is inside a guard like `if (var >= 0)` or `if (var > 0)`.
    fn has_non_negative_guard(&self, node: &Node, var_name: &str, source: &str) -> bool {
        let mut current = node.parent();
        while let Some(ancestor) = current {
            if matches!(
                ancestor.kind(),
                "if_statement" | "while_statement" | "for_statement"
            ) {
                if let Some(condition) = ancestor.child_by_field_name("condition") {
                    let cond_text = get_node_text(&condition, source);
                    if cond_text.contains(var_name)
                        && (cond_text.contains(">= 0")
                            || cond_text.contains("> 0")
                            || cond_text.contains("!= -")
                            || cond_text.contains(">= 0"))
                    {
                        return true;
                    }
                }
            }
            if ancestor.kind() == "function_definition" {
                break;
            }
            current = ancestor.parent();
        }
        false
    }
}