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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils;
use std::collections::HashSet;
use tree_sitter::Node;

pub struct Str30C;

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

    fn description(&self) -> &'static str {
        "Do not attempt to modify string literals"
    }

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

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

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

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

        // Analyze the current node and its subtree
        analyzer.analyze_node(node, source, &mut violations);

        violations
    }
}

struct StringLiteralAnalyzer {
    // Track variables that point to string literals
    string_literal_vars: HashSet<String>,
    // Track double pointers to string literals (char **ptr = &str)
    double_pointer_vars: HashSet<String>,
    // Track function parameters that might point to string literals (const char*)
    const_char_params: HashSet<String>,
    // Track results of strrchr/strchr on parameters
    search_result_vars: HashSet<String>,
}

impl StringLiteralAnalyzer {
    fn new() -> Self {
        Self {
            string_literal_vars: HashSet::new(),
            double_pointer_vars: HashSet::new(),
            const_char_params: HashSet::new(),
            search_result_vars: HashSet::new(),
        }
    }

    fn analyze_node(&mut self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
        match node.kind() {
            "function_definition" => {
                // Extract const char* parameters from function signature
                self.extract_const_params(node, source);
            }
            "declaration" => {
                self.process_declaration(node, source, violations);
            }
            "assignment_expression" => {
                self.process_assignment(node, source, violations);
            }
            "call_expression" => {
                self.check_function_call(node, source, violations);
            }
            "subscript_expression" => {
                self.check_array_modification(node, source, violations);
            }
            "pointer_expression" => {
                self.check_pointer_modification(node, source, violations);
            }
            _ => {}
        }

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

    /// Extract const char* parameters from function definition
    fn extract_const_params(&mut self, node: &Node, source: &str) {
        // Look for the declarator which contains the parameter_list
        if let Some(declarator) = node.child_by_field_name("declarator") {
            self.find_const_params_in_declarator(&declarator, source);
        }
    }

    fn find_const_params_in_declarator(&mut self, node: &Node, source: &str) {
        if node.kind() == "parameter_list" {
            for i in 0..node.child_count() {
                if let Some(param) = node.child(i) {
                    if param.kind() == "parameter_declaration" {
                        let param_text = ast_utils::get_node_text_owned(&param, source);
                        // Check for const char* pattern
                        if param_text.contains("const") && param_text.contains("char") {
                            // Extract parameter name
                            if let Some(decl) = param.child_by_field_name("declarator") {
                                let param_name = self.get_variable_name(&decl, source);
                                if param_name != "unknown" {
                                    self.const_char_params.insert(param_name);
                                }
                            }
                        }
                    }
                }
            }
        }

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

    fn process_declaration(
        &mut self,
        node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "init_declarator" {
                    if let Some(declarator) = child.child_by_field_name("declarator") {
                        // Check if this is an array declaration vs a pointer
                        let is_array = self.is_array_declarator(&declarator);
                        let var_name = self.get_variable_name(&declarator, source);

                        // Only track pointer variables pointing to string literals
                        // Arrays initialized with string literals are modifiable copies
                        if let Some(value) = child.child_by_field_name("value") {
                            if self.is_string_literal(&value, source) && !is_array {
                                // This is a pointer to a string literal
                                self.string_literal_vars.insert(var_name.clone());
                            }

                            // Track results of string search functions on literals
                            // e.g., char *ptr = strchr("Hello", 'W');
                            if self.is_search_result_of_literal(&value, source) && !is_array {
                                self.string_literal_vars.insert(var_name.clone());
                            }

                            // Track results of string search functions on const char* params
                            // e.g., char *ptr = strrchr(pathname, '/');
                            if self.is_search_result_of_const_param(&value, source) && !is_array {
                                self.search_result_vars.insert(var_name.clone());
                            }

                            // Track casting away const from string literal
                            // e.g., char *str = (char *)cstr; where cstr points to literal
                            if self.is_cast_from_literal_var(&value, source) && !is_array {
                                self.string_literal_vars.insert(var_name.clone());
                            }

                            // Track arrays of pointers initialized with string literals
                            // e.g., char *strings[] = { "first", "second" };
                            if self.is_array_of_literal_pointers(&declarator, &value, source) {
                                self.string_literal_vars.insert(var_name.clone());
                            }

                            // Track double pointers to string literal vars
                            // e.g., char **ptr = &str;
                            if self.is_double_pointer_to_literal(&value, source) {
                                self.double_pointer_vars.insert(var_name.clone());
                            }

                            // Track structs initialized with string literals
                            // e.g., struct data d = { "literal" };
                            if value.kind() == "initializer_list" {
                                if self.initializer_contains_string_literal(&value, source) {
                                    // Check if not a char array (which is a modifiable copy)
                                    if !is_array {
                                        self.string_literal_vars.insert(var_name.clone());
                                    }
                                }
                            }

                            // Track function call results that might return string literals
                            if self.is_function_returning_literal(&value, source) && !is_array {
                                self.string_literal_vars.insert(var_name.clone());
                            }
                        }
                    }
                }
            }
        }

        // Also check for uninitialized declarations that might be assigned later
        // For tracking purposes in assignment expressions
        let _ = violations; // silence unused warning
    }

    /// Check if declaration is an array of pointers initialized with string literals
    fn is_array_of_literal_pointers(&self, declarator: &Node, value: &Node, source: &str) -> bool {
        // Check if value is an initializer_list with string literals
        if value.kind() != "initializer_list" {
            return false;
        }

        if !self.initializer_contains_string_literal(value, source) {
            return false;
        }

        // Pattern 1: array_declarator with pointer_declarator inside
        // e.g., char *strings[] = {"a", "b"}
        if declarator.kind() == "array_declarator" {
            // Check via field name
            if let Some(inner_declarator) = declarator.child_by_field_name("declarator") {
                if inner_declarator.kind() == "pointer_declarator" {
                    return true;
                }
            }
            // Also check by iterating children
            for i in 0..declarator.child_count() {
                if let Some(child) = declarator.child(i) {
                    if child.kind() == "pointer_declarator" {
                        return true;
                    }
                }
            }
        }

        // Pattern 2: pointer_declarator with array_declarator inside
        // (alternative tree structure depending on parsing)
        if declarator.kind() == "pointer_declarator" {
            if let Some(inner_declarator) = declarator.child_by_field_name("declarator") {
                if inner_declarator.kind() == "array_declarator" {
                    return true;
                }
            }
            // Also check by iterating children
            for i in 0..declarator.child_count() {
                if let Some(child) = declarator.child(i) {
                    if child.kind() == "array_declarator" {
                        return true;
                    }
                }
            }
        }

        // Pattern 3: Check declarator text for pointer-array pattern
        // This handles edge cases where the tree structure varies
        let decl_text = ast_utils::get_node_text_owned(declarator, source);
        if decl_text.contains('*') && decl_text.contains('[') && decl_text.contains(']') {
            return true;
        }

        false
    }

    /// Check if value is a double pointer to a tracked string literal var
    /// e.g., char **ptr = &str; where str is in string_literal_vars
    fn is_double_pointer_to_literal(&self, node: &Node, source: &str) -> bool {
        if node.kind() == "pointer_expression" {
            // Check for & operator (address-of)
            let node_text = ast_utils::get_node_text_owned(node, source);
            if node_text.starts_with('&') {
                // Get the operand
                if let Some(argument) = node.child_by_field_name("argument") {
                    if argument.kind() == "identifier" {
                        let var_name = ast_utils::get_node_text_owned(&argument, source);
                        return self.string_literal_vars.contains(&var_name);
                    }
                }
            }
        }
        false
    }

    /// Check if strrchr/strchr is called on a const char* parameter
    fn is_search_result_of_const_param(&self, node: &Node, source: &str) -> bool {
        if node.kind() == "call_expression" {
            if let Some(function) = node.child_by_field_name("function") {
                let func_name = ast_utils::get_node_text_owned(&function, source);
                if is_string_search_function(&func_name) {
                    // Check first argument for const char* parameter
                    if let Some(arguments) = node.child_by_field_name("arguments") {
                        for i in 0..arguments.child_count() {
                            if let Some(arg) = arguments.child(i) {
                                if arg.kind() != "," && arg.kind() != "(" && arg.kind() != ")" {
                                    // First non-punctuation argument
                                    if arg.kind() == "identifier" {
                                        let arg_name = ast_utils::get_node_text_owned(&arg, source);
                                        if self.const_char_params.contains(&arg_name) {
                                            return true;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        false
    }

    /// Check if a function call might return a string literal
    /// Heuristic: functions named get_string, get_* returning char* are suspicious
    fn is_function_returning_literal(&self, node: &Node, source: &str) -> bool {
        if node.kind() == "call_expression" {
            if let Some(function) = node.child_by_field_name("function") {
                let func_name = ast_utils::get_node_text_owned(&function, source);
                // Heuristic: functions with "get" or "string" in name might return literals
                let func_lower = func_name.to_lowercase();
                if func_lower.contains("get_string")
                    || func_lower.contains("getstring")
                    || func_lower == "get_name"
                    || func_lower == "getname"
                {
                    return true;
                }
            }
        }
        false
    }

    /// Check if an initializer list contains string literals
    fn initializer_contains_string_literal(&self, node: &Node, source: &str) -> bool {
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "string_literal" {
                    return true;
                }
                if child.kind() == "initializer_list" {
                    if self.initializer_contains_string_literal(&child, source) {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Check if value is result of a string search function on a literal
    fn is_search_result_of_literal(&self, node: &Node, source: &str) -> bool {
        if node.kind() == "call_expression" {
            if let Some(function) = node.child_by_field_name("function") {
                let func_name = ast_utils::get_node_text_owned(&function, source);
                if is_string_search_function(&func_name) {
                    // Check first argument for string literal
                    if let Some(arguments) = node.child_by_field_name("arguments") {
                        for i in 0..arguments.child_count() {
                            if let Some(arg) = arguments.child(i) {
                                if arg.kind() != "," && arg.kind() != "(" && arg.kind() != ")" {
                                    // First non-punctuation argument
                                    if self.is_string_literal(&arg, source) {
                                        return true;
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        false
    }

    /// Check if value is a cast from a tracked string literal variable
    fn is_cast_from_literal_var(&self, node: &Node, source: &str) -> bool {
        if node.kind() == "cast_expression" {
            // Check the value being cast
            if let Some(value) = node.child_by_field_name("value") {
                if value.kind() == "identifier" {
                    let var_name = ast_utils::get_node_text_owned(&value, source);
                    return self.string_literal_vars.contains(&var_name);
                }
            }
        }
        false
    }

    fn is_array_declarator(&self, declarator: &Node) -> bool {
        match declarator.kind() {
            "array_declarator" => true,
            "pointer_declarator" => {
                // Check if the child is an array declarator
                for i in 0..declarator.child_count() {
                    if let Some(child) = declarator.child(i) {
                        if self.is_array_declarator(&child) {
                            return true;
                        }
                    }
                }
                false
            }
            _ => false,
        }
    }

    fn process_assignment(
        &mut self,
        node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        if let (Some(left), Some(right)) = (
            node.child_by_field_name("left"),
            node.child_by_field_name("right"),
        ) {
            // Check if assigning to a string literal element
            if left.kind() == "subscript_expression" {
                if let Some(array) = left.child(0) {
                    if self.is_string_literal(&array, source) {
                        self.flag_violation(
                            node,
                            "Attempting to modify a string literal through array subscript",
                            violations,
                        );
                    } else if array.kind() == "identifier" {
                        let var_name = ast_utils::get_node_text_owned(&array, source);
                        if self.string_literal_vars.contains(&var_name) {
                            self.flag_violation(
                                node,
                                &format!(
                                    "Attempting to modify string literal through variable '{}'",
                                    var_name
                                ),
                                violations,
                            );
                        }
                    }
                }
            }

            // Check if assigning through a pointer to string literal
            if left.kind() == "pointer_expression" {
                if let Some(argument) = left.child_by_field_name("argument") {
                    if self.is_string_literal(&argument, source) {
                        self.flag_violation(
                            node,
                            "Attempting to modify a string literal through pointer dereference",
                            violations,
                        );
                    }
                }
            }

            // Track new assignments
            if left.kind() == "identifier" {
                let var_name = ast_utils::get_node_text_owned(&left, source);
                if self.is_string_literal(&right, source) {
                    self.string_literal_vars.insert(var_name);
                } else if self.is_search_result_of_literal(&right, source) {
                    // Track strrchr/strchr on string literal
                    self.string_literal_vars.insert(var_name);
                } else if self.is_search_result_of_const_param(&right, source) {
                    // Track strrchr/strchr on const char* parameter
                    self.search_result_vars.insert(var_name);
                } else {
                    // If assigning non-string-literal, remove from tracking
                    self.string_literal_vars.remove(&var_name);
                    self.search_result_vars.remove(&var_name);
                }
            }
        }
    }

    fn check_function_call(
        &mut self,
        node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        if let Some(function) = node.child_by_field_name("function") {
            let func_name = ast_utils::get_node_text_owned(&function, source);

            // Check for functions that modify their arguments
            if is_string_modifying_function(&func_name) {
                if let Some(arguments) = node.child_by_field_name("arguments") {
                    // Get the first argument (destination for most string functions)
                    let mut arg_index = 0;
                    for i in 0..arguments.child_count() {
                        if let Some(arg) = arguments.child(i) {
                            if arg.kind() != "," && arg.kind() != "(" && arg.kind() != ")" {
                                if arg_index == 0 {
                                    // First argument is the destination
                                    if self.is_string_literal(&arg, source) {
                                        self.flag_violation(
                                            node,
                                            &format!(
                                                "Passing string literal as destination to '{}'",
                                                func_name
                                            ),
                                            violations,
                                        );
                                    } else if arg.kind() == "identifier" {
                                        let var_name = ast_utils::get_node_text_owned(&arg, source);
                                        if self.string_literal_vars.contains(&var_name) {
                                            self.flag_violation(
                                                node,
                                                &format!("Passing pointer to string literal as destination to '{}'", func_name),
                                                violations
                                            );
                                        }
                                    }
                                    break;
                                }
                                arg_index += 1;
                            }
                        }
                    }
                }
            }

            // Check for user-defined functions that might modify their char* argument
            // Heuristic: If passing a string literal to a non-const char* parameter
            if !is_string_modifying_function(&func_name)
                && !is_string_search_function(&func_name)
                && !is_safe_function(&func_name)
            {
                if let Some(arguments) = node.child_by_field_name("arguments") {
                    for i in 0..arguments.child_count() {
                        if let Some(arg) = arguments.child(i) {
                            if arg.kind() == "string_literal" {
                                // Heuristic: passing literal to unknown function with char* parameter
                                // Check if function name suggests modification
                                let func_lower = func_name.to_lowercase();
                                if func_lower.contains("modify")
                                    || func_lower.contains("change")
                                    || func_lower.contains("set")
                                    || func_lower.contains("update")
                                {
                                    self.flag_violation(
                                        node,
                                        &format!(
                                            "Passing string literal to function '{}' which may modify it",
                                            func_name
                                        ),
                                        violations,
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fn check_array_modification(
        &mut self,
        node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        // Check if this subscript expression is on the left side of an assignment
        if let Some(parent) = node.parent() {
            if parent.kind() == "assignment_expression" {
                if let Some(left) = parent.child_by_field_name("left") {
                    if left.byte_range() == node.byte_range() {
                        // This subscript is being assigned to
                        if let Some(array) = node.child(0) {
                            if self.is_string_literal(&array, source) {
                                self.flag_violation(
                                    node,
                                    "Attempting to modify a string literal through array subscript",
                                    violations,
                                );
                            } else if array.kind() == "identifier" {
                                let var_name = ast_utils::get_node_text_owned(&array, source);
                                if self.string_literal_vars.contains(&var_name) {
                                    self.flag_violation(
                                        node,
                                        &format!(
                                            "Attempting to modify string literal through variable '{}'",
                                            var_name
                                        ),
                                        violations,
                                    );
                                }
                                // Also check search result vars
                                if self.search_result_vars.contains(&var_name) {
                                    self.flag_violation(
                                        node,
                                        &format!(
                                            "Attempting to modify through '{}' which may point to a string literal",
                                            var_name
                                        ),
                                        violations,
                                    );
                                }
                            } else if array.kind() == "subscript_expression" {
                                // Double subscript like strings[1][0] = ...
                                // Check the base array
                                if let Some(base) = array.child(0) {
                                    if base.kind() == "identifier" {
                                        let var_name =
                                            ast_utils::get_node_text_owned(&base, source);
                                        if self.string_literal_vars.contains(&var_name) {
                                            self.flag_violation(
                                                node,
                                                &format!(
                                                    "Attempting to modify string literal through array '{}'",
                                                    var_name
                                                ),
                                                violations,
                                            );
                                        }
                                    }
                                }
                            } else if array.kind() == "field_expression" {
                                // Struct member access like d.name[0] = ...
                                // Check the struct variable
                                if let Some(argument) = array.child_by_field_name("argument") {
                                    let struct_name =
                                        ast_utils::get_node_text_owned(&argument, source);
                                    // Check if this struct was initialized with string literals
                                    if self.string_literal_vars.contains(&struct_name) {
                                        self.flag_violation(
                                            node,
                                            &format!(
                                                "Attempting to modify string literal through struct member in '{}'",
                                                struct_name
                                            ),
                                            violations,
                                        );
                                    }
                                }
                            } else if array.kind() == "parenthesized_expression" {
                                // Pattern: (*ptr)[n] = ... where ptr is a double pointer
                                // The parenthesized_expression contains a pointer_expression
                                if let Some(deref_var) =
                                    self.extract_deref_var_from_paren(&array, source)
                                {
                                    if self.double_pointer_vars.contains(&deref_var) {
                                        self.flag_violation(
                                            node,
                                            &format!(
                                                "Attempting to modify string literal through double pointer '{}'",
                                                deref_var
                                            ),
                                            violations,
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /// Extract variable name from (*ptr) pattern in parenthesized expression
    fn extract_deref_var_from_paren(&self, node: &Node, source: &str) -> Option<String> {
        // Look for pointer_expression inside the parentheses
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "pointer_expression" {
                    // Check if this is a dereference (*)
                    let expr_text = ast_utils::get_node_text_owned(&child, source);
                    if expr_text.starts_with('*') {
                        if let Some(argument) = child.child_by_field_name("argument") {
                            if argument.kind() == "identifier" {
                                return Some(ast_utils::get_node_text_owned(&argument, source));
                            }
                        }
                    }
                }
            }
        }
        None
    }

    fn check_pointer_modification(
        &mut self,
        node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        // Check if this pointer expression is on the left side of an assignment
        if let Some(parent) = node.parent() {
            if parent.kind() == "assignment_expression" {
                if let Some(left) = parent.child_by_field_name("left") {
                    if left.byte_range() == node.byte_range() {
                        // This pointer dereference is being assigned to
                        if let Some(argument) = node.child_by_field_name("argument") {
                            if self.is_string_literal(&argument, source) {
                                self.flag_violation(
                                    node,
                                    "Attempting to modify a string literal through pointer dereference",
                                    violations,
                                );
                            } else if argument.kind() == "identifier" {
                                let var_name = ast_utils::get_node_text_owned(&argument, source);
                                if self.string_literal_vars.contains(&var_name) {
                                    self.flag_violation(
                                        node,
                                        &format!(
                                            "Attempting to modify string literal through pointer '{}'",
                                            var_name
                                        ),
                                        violations,
                                    );
                                }
                                // Check if this is a search result var (e.g., strrchr result)
                                if self.search_result_vars.contains(&var_name) {
                                    self.flag_violation(
                                        node,
                                        &format!(
                                            "Attempting to modify string through '{}' which may point to a string literal",
                                            var_name
                                        ),
                                        violations,
                                    );
                                }
                            } else if argument.kind() == "subscript_expression" {
                                // Handle (*ptr)[n] pattern - dereference of double pointer
                                // We need to detect *ptr where ptr is a double pointer to literal
                                // Actually this is subscript on deref, handled differently
                            }
                        }
                    }
                }
            }
        }
    }

    fn is_string_literal(&self, node: &Node, source: &str) -> bool {
        match node.kind() {
            "string_literal" | "concatenated_string" => true,
            "cast_expression" => {
                // Check if casting a string literal
                if let Some(value) = node.child_by_field_name("value") {
                    self.is_string_literal(&value, source)
                } else {
                    false
                }
            }
            "identifier" => {
                // Check for predefined macros that expand to string literals
                let text = ast_utils::get_node_text_owned(node, source);
                matches!(
                    text.as_str(),
                    "__FILE__" | "__func__" | "__FUNCTION__" | "__PRETTY_FUNCTION__"
                )
            }
            "conditional_expression" => {
                // Ternary expression: condition ? consequent : alternative
                // If either branch is a string literal, the result may be a string literal
                if let Some(consequent) = node.child_by_field_name("consequence") {
                    if self.is_string_literal(&consequent, source) {
                        return true;
                    }
                }
                if let Some(alternative) = node.child_by_field_name("alternative") {
                    if self.is_string_literal(&alternative, source) {
                        return true;
                    }
                }
                false
            }
            "parenthesized_expression" => {
                // Check inside parentheses
                for i in 0..node.child_count() {
                    if let Some(child) = node.child(i) {
                        if child.kind() != "(" && child.kind() != ")" {
                            if self.is_string_literal(&child, source) {
                                return true;
                            }
                        }
                    }
                }
                false
            }
            _ => false,
        }
    }

    fn get_variable_name(&self, declarator: &Node, source: &str) -> String {
        match declarator.kind() {
            "identifier" => ast_utils::get_node_text_owned(declarator, source),
            "pointer_declarator" | "array_declarator" => {
                // Look for the identifier in declarators
                for i in 0..declarator.child_count() {
                    if let Some(child) = declarator.child(i) {
                        if child.kind() == "identifier" {
                            return ast_utils::get_node_text_owned(&child, source);
                        }
                        // Recursively search in nested declarators
                        let nested_name = self.get_variable_name(&child, source);
                        if nested_name != "unknown" {
                            return nested_name;
                        }
                    }
                }
                "unknown".to_string()
            }
            _ => "unknown".to_string(),
        }
    }

    fn flag_violation(&self, node: &Node, message: &str, violations: &mut Vec<RuleViolation>) {
        let start_point = node.start_position();
        violations.push(RuleViolation {
            rule_id: "STR30-C".to_string(),
            severity: Severity::High,
            message: message.to_string(),
            file_path: String::new(),
            line: start_point.row + 1,
            column: start_point.column + 1,
            suggestion: Some("Use a modifiable array instead of a string literal".to_string()),
            ..Default::default()
        });
    }
}

fn is_string_modifying_function(func_name: &str) -> bool {
    matches!(
        func_name,
        "strcpy"
            | "strncpy"
            | "strcat"
            | "strncat"
            | "sprintf"
            | "snprintf"
            | "vsprintf"
            | "vsnprintf"
            | "gets"
            | "fgets"
            | "scanf"
            | "fscanf"
            | "sscanf"
            | "strtok"
            | "memcpy"
            | "memmove"
            | "memset"
            | "bcopy"
            | "bzero"
            | "mkstemp"   // POSIX function that modifies template string
            | "mkdtemp" // Similar to mkstemp
    )
}

/// Functions that return a pointer into their string argument
fn is_string_search_function(func_name: &str) -> bool {
    matches!(
        func_name,
        "strchr" | "strrchr" | "strstr" | "strpbrk" | "memchr"
    )
}

/// Functions that are safe and don't modify their arguments
fn is_safe_function(func_name: &str) -> bool {
    matches!(
        func_name,
        "printf"
            | "fprintf"
            | "sprintf"
            | "snprintf"
            | "puts"
            | "fputs"
            | "strlen"
            | "strcmp"
            | "strncmp"
            | "strcasecmp"
            | "strncasecmp"
            | "atoi"
            | "atol"
            | "atof"
            | "strtol"
            | "strtoul"
            | "strtod"
            | "main"
            | "exit"
            | "abort"
    )
}