aurora-lint 0.4.336

aurora-lint - a fast CERT C static analyzer
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
//! CON34-C: Declare objects shared between threads with appropriate storage durations
//!
//! Accessing the automatic or thread-local variables of one thread from another thread
//! is undefined behavior and can cause invalid memory accesses. When variables are
//! shared between threads, they must have:
//! - Static storage duration (static variables)
//! - Allocated storage duration (heap-allocated via malloc/calloc)
//!
//! Do NOT share:
//! - Automatic storage duration (local/stack variables)
//! - Thread-specific storage (tss_t) without proper synchronization
//!
//! ## Examples:
//!
//! **Non-compliant (Automatic Storage Duration):**
//! ```c
//! void create_thread(thrd_t *tid, int *val) {
//!   if (thrd_success != thrd_create(tid, child_thread, val)) {
//!     /* Handle error */
//!   }
//! }
//!
//! int main(void) {
//!   int val = 1;  // Automatic (local) variable
//!   thrd_t tid;
//!   create_thread(&tid, &val);  // Passing address of local variable to thread
//!   if (thrd_success != thrd_join(tid, NULL)) {
//!     /* Handle error */
//!   }
//!   return 0;
//! }
//! ```
//!
//! **Compliant (Static Storage Duration):**
//! ```c
//! void create_thread(thrd_t *tid) {
//!   static int val = 1;  // Static storage - safe to share
//!   if (thrd_success != thrd_create(tid, child_thread, &val)) {
//!     /* Handle error */
//!   }
//! }
//! ```
//!
//! **Compliant (Allocated Storage Duration):**
//! ```c
//! int main(void) {
//!   thrd_t tid;
//!   int *value = (int *)malloc(sizeof(int));  // Heap allocation
//!   if (!value) {
//!     /* Handle error */
//!   }
//!   create_thread(&tid, value);
//!   if (thrd_success != thrd_join(tid, NULL)) {
//!     /* Handle error */
//!   }
//!   free(value);
//!   return 0;
//! }
//! ```
//!
//! ## Detection Strategy:
//! - Find thrd_create() calls
//! - Check if the argument passed is an address of a local variable (&local_var)
//! - Find tss_set() calls within functions that create threads
//! - Detect if thread-specific storage is set in a parent thread but accessed by child

use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::{
    self, find_containing_function, get_function_parameters, get_identifier_from_declarator,
    get_node_text, is_function_parameter, is_pointer_type,
};
use crate::utility::cert_c::call_roles;
use lang_parsing_substrate::query;
use tree_sitter::Node;

pub struct Con34C;

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

    fn description(&self) -> &'static str {
        "Declare objects shared between threads with appropriate storage durations"
    }

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

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

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

    fn scan(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
        self.check_node(node, source, violations);
    }
}

/// Functions that use internal static storage and are not thread-safe.
/// Each entry is (function_name, thread-safe_alternative).
const THREAD_UNSAFE_FUNCTIONS: &[(&str, &str)] = &[
    ("localtime", "localtime_r"),
    ("gmtime", "gmtime_r"),
    ("ctime", "ctime_r"),
    ("asctime", "asctime_r"),
    ("strtok", "strtok_r"),
    ("rand", "rand_r or a thread-local PRNG"),
    ("getenv", "secure_getenv or a cached copy"),
    ("strerror", "strerror_r"),
    ("readdir", "readdir_r"),
    ("tmpnam", "mkstemp"),
    ("setlocale", "uselocale"),
    ("inet_ntoa", "inet_ntop"),
    ("gethostbyname", "getaddrinfo"),
    ("gethostbyaddr", "getnameinfo"),
];

/// `ast_utils::get_identifier_from_declarator` as an `Option`, matching the
/// call shape the rest of this file wants. NOT the same as
/// `ast_utils::find_identifier_in_declarator`: that function only searches a
/// declarator's *children* for an identifier, so it misses the extremely
/// common case where the declarator field itself already IS a bare
/// `identifier` node (`int j = 0;`, no pointer/array wrapper) --
/// `get_identifier_from_declarator` handles that case by matching on the
/// node's own kind first.
fn declarator_identifier(declarator: &Node, source: &str) -> Option<String> {
    let name = get_identifier_from_declarator(declarator, source);
    (!name.is_empty()).then_some(name)
}

impl Con34C {
    fn check_node(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
        for n in query::find_descendants_of_kinds(*node, &["call_expression", "compound_statement"])
        {
            // Check for thrd_create() calls and thread-unsafe function calls
            if n.kind() == "call_expression" {
                if let Some(func) = n.child_by_field_name("function") {
                    let func_name = get_node_text(&func, source);
                    if func_name == "thrd_create" {
                        self.check_thrd_create_call(&n, source, violations);
                    } else if func_name == "tss_set" {
                        self.check_tss_set_call(&n, source, violations);
                    } else {
                        self.check_thread_unsafe_call(&func_name, &n, violations);
                    }
                }
            }

            // Check for OpenMP parallel regions
            if n.kind() == "compound_statement" {
                self.check_openmp_parallel_region(&n, source, violations);
            }
        }
    }

    fn check_thrd_create_call(
        &self,
        call_node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        // thrd_create(thrd_t *thr, thrd_start_t func, void *arg)
        // We need to check the third argument (arg) - the data pointer, NOT the function pointer

        if let Some(args) = call_node.child_by_field_name("arguments") {
            let mut arg_list = Vec::new();

            // Collect all non-comma arguments
            for i in 0..args.child_count() {
                if let Some(child) = args.child(i) {
                    if child.kind() != "," && child.kind() != "(" && child.kind() != ")" {
                        arg_list.push(child);
                    }
                }
            }

            // We want the 3rd argument (index 2) - the data pointer
            if arg_list.len() >= 3 {
                let arg_node = arg_list[2];
                let arg_text = get_node_text(&arg_node, source);

                // Check various problematic patterns
                let is_violation = self.is_address_of_local_var(&arg_node, source, call_node)
                    || (self.is_pointer_parameter(&arg_node, source, call_node)
                        && !self.is_allocated_pointer(arg_text, call_node, source)
                        && !self.is_likely_allocated_param(arg_text))
                    || (arg_node.kind() == "identifier"
                        && !self.is_static_variable(&arg_node, arg_text, source)
                        && !self.is_allocated_pointer(arg_text, call_node, source)
                        && !self.is_likely_allocated_param(arg_text)
                        && !arg_text.starts_with("&"));

                if is_violation {
                    let message = if self.is_address_of_local_var(&arg_node, source, call_node) {
                        "Passing address of automatic (local) variable to thrd_create()".to_string()
                    } else {
                        format!(
                            "Passing '{}' to thrd_create() may reference automatic storage",
                            arg_text
                        )
                    };

                    violations.push(RuleViolation {
                        rule_id: self.rule_id().to_string(),
                        severity: Severity::Medium,
                        message,
                        file_path: String::new(),
                        line: call_node.start_position().row + 1,
                        column: call_node.start_position().column + 1,
                        suggestion: Some(
                            "Use static or heap-allocated storage for data shared between threads"
                                .to_string(),
                        ),
                        ..Default::default()
                    });
                }
            }
        }
    }

    fn check_tss_set_call(
        &self,
        call_node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        // tss_set() within a function that also calls thrd_create() is problematic
        // ONLY if the value being set is not retrieved with tss_get before passing to the thread

        // Find the enclosing function
        if let Some(function) = find_containing_function(call_node) {
            // Check if this function also creates threads
            if self.function_creates_threads(&function, source) {
                // Check if there's a tss_get between tss_set and thrd_create
                // If tss_get is used to retrieve the value before passing to thread, it's compliant
                if self.has_tss_get_before_thread_create(&function, source) {
                    // This is compliant - using tss_get to retrieve allocated storage
                    return;
                }

                violations.push(RuleViolation {
                    rule_id: self.rule_id().to_string(),
                    severity: Severity::Medium,
                    message: "Thread-specific storage (tss_set) used in function that creates threads. Child thread may access parent's thread-specific data".to_string(),
                    file_path: String::new(),
                    line: call_node.start_position().row + 1,
                    column: call_node.start_position().column + 1,
                    suggestion: Some(
                        "Use static or allocated storage for data shared between threads".to_string()
                    ),
                    ..Default::default()
                });
            }
        }
    }

    fn is_address_of_local_var(&self, node: &Node, source: &str, context: &Node) -> bool {
        // Address-of (`&x`) is a "pointer_expression" in this tree-sitter-c
        // grammar (distinct from "unary_expression", which covers !, -, ~,
        // etc.) — check both so this doesn't silently break again if the
        // grammar version changes.
        if matches!(node.kind(), "unary_expression" | "pointer_expression") {
            if let Some(operator) = node.child_by_field_name("operator") {
                if get_node_text(&operator, source) == "&" {
                    if let Some(argument) = node.child_by_field_name("argument") {
                        let var_name = get_node_text(&argument, source).to_string();

                        // A local thrd_t (thread-handle) variable passed
                        // this way is the standard, unavoidable idiom for
                        // tracking a nested thread's ID -- thrd_create is
                        // the only way to obtain one, and CERT's own
                        // compliant example does exactly this (main joins
                        // on it before returning, so the storage is
                        // guaranteed live for as long as it matters). This
                        // is categorically different from sharing ordinary
                        // local DATA (e.g. `int val`) across the thread
                        // boundary, which is what this rule targets.
                        if self.is_thrd_t_variable(&var_name, context, source) {
                            return false;
                        }

                        // Check if this variable is a local (automatic) variable
                        return self.is_local_variable(&argument, &var_name, source);
                    }
                }
            }
        }

        false
    }

    fn is_pointer_parameter(&self, node: &Node, source: &str, context: &Node) -> bool {
        // Extract the base identifier from the node (might be wrapped in casts, etc.)
        let var_name = self.extract_base_identifier(node, source);

        if let Some(var_name) = var_name {
            // Find the enclosing function
            if let Some(function) = find_containing_function(context) {
                // Check if this is a pointer parameter
                if let Some(params) = get_function_parameters(&function, source) {
                    return params
                        .iter()
                        .any(|(name, ptype)| name == &var_name && is_pointer_type(ptype));
                }
            }
        }

        false
    }

    #[allow(clippy::only_used_in_recursion)]
    fn extract_base_identifier(&self, node: &Node, source: &str) -> Option<String> {
        // Handle direct identifiers
        if node.kind() == "identifier" {
            return Some(get_node_text(node, source).to_string());
        }

        // Handle cast expressions: (type)var
        if node.kind() == "cast_expression" {
            if let Some(value) = node.child_by_field_name("value") {
                return self.extract_base_identifier(&value, source);
            }
        }

        // Handle parenthesized expressions: (var)
        if node.kind() == "parenthesized_expression" {
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() != "(" && child.kind() != ")" {
                        return self.extract_base_identifier(&child, source);
                    }
                }
            }
        }

        // Recursively search for identifier in child nodes
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "identifier" {
                    return Some(get_node_text(&child, source).to_string());
                }
            }
        }

        None
    }

    fn is_allocated_pointer(&self, var_name: &str, context: &Node, source: &str) -> bool {
        // Check if this pointer was assigned from malloc/calloc in the current function
        if let Some(function) = find_containing_function(context) {
            if let Some(body) = function.child_by_field_name("body") {
                return self.find_malloc_assignment(&body, var_name, source);
            }
        }
        false
    }

    /// True if `ident_node` (occurrence of `var_name`) resolves to a `static`
    /// declaration -- either the enclosing function's local static, or a
    /// file-scope global. Uses `ast_utils::find_enclosing_declaration_for_identifier`
    /// (scope/shadowing-aware) instead of a raw text search, which could
    /// match an unrelated declaration of the same name in a different
    /// function, or an ordinary comment/string mentioning "static name".
    fn is_static_variable(&self, ident_node: &Node, var_name: &str, source: &str) -> bool {
        if let Some(decl) =
            ast_utils::find_enclosing_declaration_for_identifier(ident_node, var_name, source)
        {
            return Self::declaration_is_static(&decl, source);
        }
        // Fallback for file-scope (global) declarations, which
        // `find_enclosing_declaration_for_identifier` intentionally does not
        // resolve to (it only walks enclosing `compound_statement` blocks).
        ast_utils::find_global_declaration_for_identifier(ident_node, var_name, source)
            .is_some_and(|decl| Self::declaration_is_static(&decl, source))
    }

    /// True if a `declaration` node carries the `static` storage-class specifier.
    fn declaration_is_static(decl: &Node, source: &str) -> bool {
        ast_utils::declaration_has_storage_class(decl, "static", source)
    }

    fn is_likely_allocated_param(&self, var_name: &str) -> bool {
        // Heuristic: parameters named 'value', 'v', 'data', 'buffer', 'mem' are often heap-allocated
        // This is a pragmatic workaround for lack of inter-procedural analysis
        matches!(
            var_name,
            "value" | "v" | "data" | "buffer" | "mem" | "ptr" | "p"
        )
    }

    fn find_malloc_assignment(&self, node: &Node, var_name: &str, source: &str) -> bool {
        // Find the first node that either assigns to var_name or declares it with
        // an initializer, matching the same node exactly like the original
        // recursive walk (which stopped the entire search at the first such node,
        // regardless of whether that particular node turned out to be an
        // allocation call).
        let candidate = query::find_first_descendant(*node, |n| {
            if n.kind() == "assignment_expression" {
                if let Some(left) = n.child_by_field_name("left") {
                    if get_node_text(&left, source) == var_name {
                        return true;
                    }
                }
                return false;
            }

            if n.kind() == "init_declarator" {
                if let Some(declarator) = n.child_by_field_name("declarator") {
                    if let Some(name) = declarator_identifier(&declarator, source) {
                        if name == var_name {
                            return true;
                        }
                    }
                }
            }

            false
        });

        match candidate {
            Some(n) if n.kind() == "assignment_expression" => n
                .child_by_field_name("right")
                .map(|right| self.is_allocation_call(&right, source))
                .unwrap_or(false),
            Some(n) => n
                .child_by_field_name("value")
                .map(|value| self.is_allocation_call(&value, source))
                .unwrap_or(false),
            None => false,
        }
    }

    #[allow(clippy::only_used_in_recursion)]
    fn is_allocation_call(&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);
                return call_roles::is_allocator_call(func_name);
            }
        }

        // Handle cast expressions: (type*)malloc(...)
        if node.kind() == "cast_expression" {
            if let Some(value) = node.child_by_field_name("value") {
                return self.is_allocation_call(&value, source);
            }
        }

        false
    }

    /// True if `var_name` is declared with type `thrd_t` in the function
    /// enclosing `context`.
    fn is_thrd_t_variable(&self, var_name: &str, context: &Node, source: &str) -> bool {
        let Some(function) = find_containing_function(context) else {
            return false;
        };
        let Some(body) = function.child_by_field_name("body") else {
            return false;
        };

        query::find_first_descendant(body, |n| {
            if n.kind() != "declaration" {
                return false;
            }

            let declares_var = (0..n.child_count()).any(|i| {
                n.child(i)
                    .map(|c| match c.kind() {
                        "identifier" => get_node_text(&c, source) == var_name,
                        "init_declarator" => c
                            .child_by_field_name("declarator")
                            .and_then(|d| declarator_identifier(&d, source))
                            .map(|name| name == var_name)
                            .unwrap_or(false),
                        _ => false,
                    })
                    .unwrap_or(false)
            });
            if !declares_var {
                return false;
            }

            (0..n.child_count()).any(|i| {
                n.child(i)
                    .map(|c| c.kind() == "type_identifier" && get_node_text(&c, source) == "thrd_t")
                    .unwrap_or(false)
            })
        })
        .is_some()
    }

    /// True if `ident_node` (occurrence of `var_name`) has automatic
    /// (local/stack) storage duration: declared without `static` in the
    /// enclosing function, or a plain function parameter. Uses
    /// `ast_utils::find_enclosing_declaration_for_identifier`
    /// (scope/shadowing-aware) rather than a flat function-body scan --
    /// this rule's entire purpose is telling automatic-duration objects
    /// apart from static/heap ones, so scope-correctness here matters more
    /// than almost anywhere else in the codebase.
    fn is_local_variable(&self, ident_node: &Node, var_name: &str, source: &str) -> bool {
        if let Some(decl) =
            ast_utils::find_enclosing_declaration_for_identifier(ident_node, var_name, source)
        {
            return !Self::declaration_is_static(&decl, source);
        }

        if let Some(function) = find_containing_function(ident_node) {
            if is_function_parameter(&function, var_name, source) {
                return true;
            }
        }

        false
    }

    fn function_creates_threads(&self, function: &Node, source: &str) -> bool {
        if let Some(body) = function.child_by_field_name("body") {
            return self.has_thrd_create(&body, source);
        }
        false
    }

    fn has_thrd_create(&self, node: &Node, source: &str) -> bool {
        query::find_first_descendant(*node, |n| {
            if n.kind() != "call_expression" {
                return false;
            }
            n.child_by_field_name("function")
                .map(|func| {
                    let name = get_node_text(&func, source);
                    name == "thrd_create" || name == "pthread_create"
                })
                .unwrap_or(false)
        })
        .is_some()
    }

    fn has_tss_get_before_thread_create(&self, function: &Node, source: &str) -> bool {
        // Check if the function uses tss_get() to retrieve the value before thrd_create
        if let Some(body) = function.child_by_field_name("body") {
            return self.has_tss_get(&body, source);
        }
        false
    }

    fn has_tss_get(&self, node: &Node, source: &str) -> bool {
        query::find_first_descendant(*node, |n| {
            if n.kind() != "call_expression" {
                return false;
            }
            n.child_by_field_name("function")
                .map(|func| get_node_text(&func, source) == "tss_get")
                .unwrap_or(false)
        })
        .is_some()
    }

    fn check_openmp_parallel_region(
        &self,
        compound_stmt: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        // Check if this compound statement is preceded by an OpenMP parallel pragma
        let start_byte = compound_stmt.start_byte();

        // Check the source text before this compound statement for #pragma omp parallel
        if start_byte > 0 {
            // Look back up to 200 bytes for the pragma; snap to char boundary
            let start_search = if start_byte > 200 {
                let mut idx = start_byte - 200;
                while !source.is_char_boundary(idx) {
                    idx += 1;
                }
                idx
            } else {
                0
            };
            let preceding_text = &source[start_search..start_byte];

            // Check if this section contains an OpenMP parallel pragma without private clause
            if preceding_text.contains("#pragma omp parallel")
                && !preceding_text.contains("private(")
            {
                // Make sure the pragma is close to this compound statement (not from earlier code)
                let lines: Vec<&str> = preceding_text.lines().collect();
                if let Some(last_few_lines) = lines.iter().rev().take(3).find(|line| {
                    let trimmed = line.trim();
                    trimmed.starts_with("#pragma omp parallel")
                }) {
                    // Found the pragma close to this block
                    if !last_few_lines.contains("private(") {
                        self.check_parallel_region_variables(compound_stmt, source, violations);
                    }
                }
            }
        }
    }

    fn check_parallel_region_variables(
        &self,
        region: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        // Find variables declared outside this parallel region that are accessed inside
        // For simplicity, look for common patterns like j++ in loops

        // Get the function containing this region
        if let Some(function) = find_containing_function(region) {
            // Get function-local variables
            let local_vars = self.find_local_vars_before_node(&function, region, source);

            // Check if any of these are modified in the parallel region
            for var in &local_vars {
                if self.is_var_modified_in_node(region, var, source) {
                    violations.push(RuleViolation {
                        rule_id: self.rule_id().to_string(),
                        severity: Severity::Medium,
                        message: format!(
                            "Variable '{}' is shared between threads in OpenMP parallel region without private clause",
                            var
                        ),
                        file_path: String::new(),
                        line: region.start_position().row + 1,
                        column: region.start_position().column + 1,
                        suggestion: Some(
                            format!("Add 'private({})' to the #pragma omp parallel directive", var)
                        ),
                        ..Default::default()
                    });
                }
            }
        }
    }

    fn find_local_vars_before_node(
        &self,
        function: &Node,
        before_node: &Node,
        source: &str,
    ) -> Vec<String> {
        let mut vars = Vec::new();

        if let Some(body) = function.child_by_field_name("body") {
            let target_start = before_node.start_byte();
            self.collect_local_vars_before(&body, target_start, source, &mut vars);
        }

        vars
    }

    fn collect_local_vars_before(
        &self,
        node: &Node,
        before_byte: usize,
        source: &str,
        vars: &mut Vec<String>,
    ) {
        // Explicit-stack walk: pruning is by byte position, not node kind, so
        // substrate::query::find_descendants (kind-based, no positional skip)
        // can't express this. A plain recursive walk here can stack-overflow
        // on pathologically deep-nested statement prefixes (e.g. hostap-style
        // nested if/else chains), so we thread our own stack instead.
        let mut stack = vec![*node];

        while let Some(current) = stack.pop() {
            // Don't traverse into the target node itself
            if current.start_byte() >= before_byte {
                continue;
            }

            if current.kind() == "declaration" {
                // Check if it's NOT static
                let mut is_static = false;
                let mut var_names = Vec::new();

                for i in 0..current.child_count() {
                    if let Some(child) = current.child(i) {
                        if child.kind() == "storage_class_specifier"
                            && get_node_text(&child, source) == "static"
                        {
                            is_static = true;
                        }

                        if child.kind() == "init_declarator" {
                            if let Some(declarator) = child.child_by_field_name("declarator") {
                                if let Some(name) = declarator_identifier(&declarator, source) {
                                    var_names.push(name);
                                }
                            }
                        }
                    }
                }

                if !is_static {
                    vars.extend(var_names);
                }
            }

            // Push children in reverse so they're visited in original order
            for i in (0..current.child_count()).rev() {
                if let Some(child) = current.child(i) {
                    stack.push(child);
                }
            }
        }
    }

    fn is_var_modified_in_node(&self, node: &Node, var_name: &str, source: &str) -> bool {
        // Check for assignment or update expressions involving this variable
        query::find_first_descendant(*node, |n| {
            matches!(n.kind(), "update_expression" | "assignment_expression")
                && get_node_text(&n, source).contains(var_name)
        })
        .is_some()
    }

    fn check_thread_unsafe_call(
        &self,
        func_name: &str,
        call_node: &Node,
        violations: &mut Vec<RuleViolation>,
    ) {
        for &(unsafe_fn, alternative) in THREAD_UNSAFE_FUNCTIONS {
            if func_name == unsafe_fn {
                violations.push(RuleViolation {
                    rule_id: self.rule_id().to_string(),
                    severity: Severity::Medium,
                    message: format!(
                        "'{}()' uses internal static storage that is shared between threads",
                        func_name
                    ),
                    file_path: String::new(),
                    line: call_node.start_position().row + 1,
                    column: call_node.start_position().column + 1,
                    suggestion: Some(format!("Use '{}' instead for thread safety", alternative)),
                    ..Default::default()
                });
                return;
            }
        }
    }
}