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
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 Str34C;
impl CertRule for Str34C {
fn rule_id(&self) -> &'static str {
"STR34-C"
}
fn description(&self) -> &'static str {
"Cast characters to unsigned char before converting to larger integer sizes"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Rule
}
fn cert_id(&self) -> &'static str {
"STR34-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
// Process each function independently to scope char_vars per function
self.check_translation_unit(node, source, &mut violations);
violations
}
}
impl Str34C {
/// Process each function definition with its own scoped char_vars
fn check_translation_unit(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
if node.kind() == "function_definition" {
// Collect char variables scoped to this function
let mut char_vars: HashMap<String, (usize, bool)> = HashMap::new();
self.collect_char_variables(node, source, &mut char_vars);
self.check_node(node, source, &char_vars, violations);
return; // Don't recurse further into this function
}
// For non-function nodes, also check with file-scope char_vars
// (handles global declarations)
if node.kind() == "translation_unit" {
let mut file_char_vars: HashMap<String, (usize, bool)> = HashMap::new();
// Collect only file-scope declarations (not inside functions)
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "declaration" {
self.collect_char_variables(&child, source, &mut file_char_vars);
}
}
}
// Check file-scope code with file-scope vars
if !file_char_vars.is_empty() {
self.check_node(node, source, &file_char_vars, violations);
}
}
// Recurse to find function_definitions
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.check_translation_unit(&child, source, violations);
}
}
}
/// Collect all char pointer variables (char *, signed char *, unsigned char *)
fn collect_char_variables(
&self,
node: &Node,
source: &str,
char_vars: &mut HashMap<String, (usize, bool)>,
) {
if node.kind() == "declaration" {
if let Some(type_node) = node.child_by_field_name("type") {
let type_text = get_node_text(&type_node, source);
let trimmed = type_text.trim();
// Check for any char type (signed, unsigned, or plain)
let is_signed_char = trimmed == "signed char";
let is_plain_char = trimmed == "char";
let _is_unsigned_char = trimmed == "unsigned char";
if is_signed_char || is_plain_char {
// Extract variable names from declarators
// Only track signed/plain char pointer variables — unsigned char
// doesn't need cast to unsigned char before widening
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 it's a pointer declarator
if declarator.kind() == "pointer_declarator" {
if let Some(var_name) =
self.get_declarator_name(&declarator, source)
{
char_vars.insert(
var_name,
(node.start_position().row, is_signed_char),
);
}
}
}
} else if child.kind() == "pointer_declarator" {
// Plain declarator without initialization
if let Some(var_name) = self.get_declarator_name(&child, source) {
char_vars.insert(
var_name,
(node.start_position().row, is_signed_char),
);
}
}
}
}
}
}
}
// Track char pointer/array function parameters
if node.kind() == "parameter_declaration" {
// Use full parameter text to check for unsigned char (tree-sitter may
// split "unsigned char" across type and qualifier nodes)
let full_param_text = get_node_text(node, source);
let has_unsigned = full_param_text.contains("unsigned");
if let Some(type_node) = node.child_by_field_name("type") {
let type_text = get_node_text(&type_node, source);
let trimmed = type_text.trim();
// Strip const/volatile qualifiers for matching
let base_type = trimmed
.replace("const ", "")
.replace("volatile ", "")
.trim()
.to_string();
let is_signed_char = base_type == "signed char";
let is_plain_char = base_type == "char" && !has_unsigned;
if is_signed_char || is_plain_char {
if let Some(declarator) = node.child_by_field_name("declarator") {
// pointer_declarator (char *str) or array_declarator (char buf[])
if declarator.kind() == "pointer_declarator"
|| declarator.kind() == "array_declarator"
{
if let Some(var_name) = self.get_declarator_name(&declarator, source) {
char_vars
.insert(var_name, (node.start_position().row, is_signed_char));
}
}
}
}
}
}
// Recurse into children
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
self.collect_char_variables(&child, source, char_vars);
}
}
/// Extract variable name from declarator
fn get_declarator_name(&self, node: &Node, source: &str) -> Option<String> {
match node.kind() {
"identifier" => Some(get_node_text(node, source).to_string()),
"array_declarator" | "pointer_declarator" => {
if let Some(declarator) = node.child_by_field_name("declarator") {
self.get_declarator_name(&declarator, source)
} else {
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
}
}
_ => None,
}
}
/// Check node and its children for violations
fn check_node(
&self,
node: &Node,
source: &str,
char_vars: &HashMap<String, (usize, bool)>,
violations: &mut Vec<RuleViolation>,
) {
// Check for direct assignment to larger integer types
if node.kind() == "init_declarator" {
self.check_init_declarator(node, source, char_vars, violations);
}
// Check for assignment expressions
if node.kind() == "assignment_expression" {
self.check_assignment_expression(node, source, char_vars, violations);
}
// Check for subscript expressions (array indexing)
if node.kind() == "subscript_expression" {
self.check_subscript_expression(node, source, char_vars, violations);
}
// Check for pointer dereferences assigned to larger types
if node.kind() == "pointer_expression" {
self.check_pointer_expression(node, source, char_vars, violations);
}
// Check for cast expressions that cast char to larger types
if node.kind() == "cast_expression" {
self.check_cast_expression(node, source, char_vars, violations);
}
// Recurse into children
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
self.check_node(&child, source, char_vars, violations);
}
}
/// Check init_declarator for problematic assignments
fn check_init_declarator(
&self,
node: &Node,
source: &str,
char_vars: &HashMap<String, (usize, bool)>,
violations: &mut Vec<RuleViolation>,
) {
if let Some(_declarator) = node.child_by_field_name("declarator") {
if let Some(value) = node.child_by_field_name("value") {
// Check if the declarator is a larger integer type
if let Some(parent) = node.parent() {
if parent.kind() == "declaration" {
if let Some(type_node) = parent.child_by_field_name("type") {
let type_text = get_node_text(&type_node, source);
if self.is_larger_integer_type(&type_text) {
// Check if value involves a char variable without proper cast
self.check_char_usage_in_expression(
&value, source, char_vars, violations,
);
}
}
}
}
}
}
}
/// Check assignment expressions
fn check_assignment_expression(
&self,
node: &Node,
source: &str,
char_vars: &HashMap<String, (usize, bool)>,
violations: &mut Vec<RuleViolation>,
) {
if let Some(_left) = node.child_by_field_name("left") {
if let Some(right) = node.child_by_field_name("right") {
// Only check if the right side is a pointer dereference WITHOUT a cast
// (If it has a cast, it will be checked by check_cast_expression)
if right.kind() == "pointer_expression" || right.kind() == "update_expression" {
// Check if it involves a char pointer dereference
self.check_pointer_dereference_in_expression(
&right, source, char_vars, violations,
);
}
}
}
}
/// Check for pointer dereferences in expressions
fn check_pointer_dereference_in_expression(
&self,
node: &Node,
source: &str,
char_vars: &HashMap<String, (usize, bool)>,
violations: &mut Vec<RuleViolation>,
) {
// Check if this is a pointer expression (*ptr)
if node.kind() == "pointer_expression" {
if let Some(argument) = node.child_by_field_name("argument") {
if let Some(base_name) = self.extract_identifier(&argument, source) {
if char_vars.contains_key(&base_name) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message: format!(
"Pointer dereference '*{}' (char type) assigned to larger type without cast to 'unsigned char' - may cause sign extension",
base_name
),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some("Cast to 'unsigned char' before assignment: (unsigned char)*ptr".to_string()),
..Default::default()
});
}
}
}
}
// Check if this is an update expression that contains a pointer dereference (*ptr++)
if node.kind() == "update_expression" {
if let Some(argument) = node.child_by_field_name("argument") {
// Recursively check the argument
self.check_pointer_dereference_in_expression(
&argument, source, char_vars, violations,
);
}
}
}
/// Check subscript expressions (array indexing)
fn check_subscript_expression(
&self,
node: &Node,
source: &str,
char_vars: &HashMap<String, (usize, bool)>,
violations: &mut Vec<RuleViolation>,
) {
if let Some(index) = node.child_by_field_name("index") {
// Check if index is a char variable without cast to unsigned char
if let Some(identifier) = self.extract_identifier(&index, source) {
if char_vars.contains_key(&identifier) {
// Check if there's a cast to unsigned char
if !self.has_unsigned_char_cast(&index, source) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message: format!(
"Array index uses '{}' (signed/plain char) without cast to 'unsigned char' - may cause negative index",
identifier
),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some("Cast to 'unsigned char' before using as array index".to_string()),
..Default::default()
});
}
}
}
}
}
/// Check pointer expressions
fn check_pointer_expression(
&self,
node: &Node,
source: &str,
char_vars: &HashMap<String, (usize, bool)>,
violations: &mut Vec<RuleViolation>,
) {
// Check if pointer dereference is of a char pointer
if let Some(argument) = node.child_by_field_name("argument") {
let arg_text = get_node_text(&argument, source);
// Check if it's a char pointer variable (ends with _str, _ptr, etc. or is tracked)
if let Some(base_name) = self.extract_identifier(&argument, source) {
// Look for char pointer types
if char_vars.contains_key(&base_name) {
// Check if this dereference is being assigned to a larger type
if let Some(parent) = node.parent() {
if parent.kind() == "init_declarator"
|| parent.kind() == "assignment_expression"
{
// Check if there's a cast to unsigned char
if !self.has_unsigned_char_cast(node, source) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message: format!(
"Pointer dereference '*{}' (char type) assigned without cast to 'unsigned char' - may cause sign extension",
arg_text
),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some("Cast to 'unsigned char' before assignment to larger type".to_string()),
..Default::default()
});
}
}
}
}
}
}
}
/// Check cast expressions for improper casting
fn check_cast_expression(
&self,
node: &Node,
source: &str,
char_vars: &HashMap<String, (usize, bool)>,
violations: &mut Vec<RuleViolation>,
) {
// Get the type being cast to
if let Some(type_node) = node.child_by_field_name("type") {
let type_text = get_node_text(&type_node, source);
// Check if casting to a larger integer type (not unsigned char)
if self.is_larger_integer_type(&type_text)
&& !type_text.contains("unsigned")
&& !type_text.contains("char")
{
// Get the value being cast
if let Some(value) = node.child_by_field_name("value") {
// Check if the value involves a char dereference
if value.kind() == "pointer_expression" {
if let Some(argument) = value.child_by_field_name("argument") {
if let Some(base_name) = self.extract_identifier(&argument, source) {
if char_vars.contains_key(&base_name) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message: format!(
"Cast from char pointer dereference to '{}' without intermediate cast to 'unsigned char' - may cause sign extension",
type_text.trim()
),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some("Cast to 'unsigned char' before casting to larger type: (type)(unsigned char)*ptr".to_string()),
..Default::default()
});
}
}
}
}
}
}
// Also check for unsigned int/long/etc. casts from char
if self.is_larger_integer_type(&type_text)
&& type_text.contains("unsigned")
&& !type_text.contains("char")
{
// Get the value being cast
if let Some(value) = node.child_by_field_name("value") {
// Check if the value involves a char dereference
if value.kind() == "pointer_expression" {
if let Some(argument) = value.child_by_field_name("argument") {
if let Some(base_name) = self.extract_identifier(&argument, source) {
if char_vars.contains_key(&base_name) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message: format!(
"Cast from char pointer dereference to '{}' without intermediate cast to 'unsigned char' - may cause sign extension",
type_text.trim()
),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some("Cast to 'unsigned char' before casting to larger type: (type)(unsigned char)*ptr".to_string()),
..Default::default()
});
}
}
}
}
}
}
}
}
/// Check if an expression involves char variables without proper casting
fn check_char_usage_in_expression(
&self,
node: &Node,
source: &str,
char_vars: &HashMap<String, (usize, bool)>,
violations: &mut Vec<RuleViolation>,
) {
// If the expression is a cast to unsigned char, it's compliant
if self.has_unsigned_char_cast(node, source) {
return;
}
// Check for identifiers that are char variables
if node.kind() == "identifier" {
let var_name = get_node_text(node, source);
if char_vars.contains_key(var_name) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message: format!(
"'{}' (signed/plain char) converted to larger integer type without cast to 'unsigned char' - may cause sign extension",
var_name
),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some("Cast to 'unsigned char' before conversion to larger type".to_string()),
..Default::default()
});
}
}
// Check for pointer dereferences
if node.kind() == "pointer_expression" {
if let Some(argument) = node.child_by_field_name("argument") {
if let Some(base_name) = self.extract_identifier(&argument, source) {
if char_vars.contains_key(&base_name) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message: format!(
"Pointer dereference '*{}' (char type) converted without cast to 'unsigned char' - may cause sign extension",
base_name
),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some("Cast to 'unsigned char' before conversion to larger type".to_string()),
..Default::default()
});
}
}
}
}
// Recurse into children
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
self.check_char_usage_in_expression(&child, source, char_vars, violations);
}
}
/// Check if a node has a cast to unsigned char in its ancestor chain
fn has_unsigned_char_cast(&self, node: &Node, source: &str) -> bool {
// Check if this node is a cast expression
if node.kind() == "cast_expression" {
if let Some(type_node) = node.child_by_field_name("type") {
let type_text = get_node_text(&type_node, source);
if type_text.contains("unsigned") && type_text.contains("char") {
return true;
}
}
}
// Check ancestors up the tree
let mut current = node.parent();
while let Some(ancestor) = current {
if ancestor.kind() == "cast_expression" {
if let Some(type_node) = ancestor.child_by_field_name("type") {
let type_text = get_node_text(&type_node, source);
if type_text.contains("unsigned") && type_text.contains("char") {
return true;
}
}
}
current = ancestor.parent();
}
false
}
/// Check if a type is a larger integer type (int, long, size_t, etc.)
fn is_larger_integer_type(&self, type_text: &str) -> bool {
let trimmed = type_text.trim();
// Check for integer types larger than char
trimmed == "int"
|| trimmed == "long"
|| trimmed == "long int"
|| trimmed == "long long"
|| trimmed == "long long int"
|| trimmed == "unsigned int"
|| trimmed == "unsigned long"
|| trimmed == "unsigned long int"
|| trimmed == "unsigned long long"
|| trimmed == "unsigned long long int"
|| trimmed == "size_t"
|| trimmed == "ptrdiff_t"
|| trimmed == "intptr_t"
|| trimmed == "uintptr_t"
|| trimmed.contains("int32")
|| trimmed.contains("int64")
|| trimmed.contains("uint32")
|| trimmed.contains("uint64")
}
/// Extract identifier from a node
fn extract_identifier(&self, node: &Node, source: &str) -> Option<String> {
match node.kind() {
"identifier" => Some(get_node_text(node, source).to_string()),
"subscript_expression" => {
if let Some(argument) = node.child_by_field_name("argument") {
self.extract_identifier(&argument, source)
} else {
None
}
}
"field_expression" => node
.child_by_field_name("field")
.map(|field| get_node_text(&field, source).to_string()),
"pointer_expression" => {
if let Some(argument) = node.child_by_field_name("argument") {
self.extract_identifier(&argument, source)
} else {
None
}
}
"update_expression" => {
// Handle c++, ++c, c--, --c patterns
if let Some(argument) = node.child_by_field_name("argument") {
self.extract_identifier(&argument, source)
} else {
None
}
}
"parenthesized_expression" => {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() != "(" && child.kind() != ")" {
return self.extract_identifier(&child, source);
}
}
}
None
}
_ => None,
}
}
}