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
//! INT01-C: Use size_t or rsize_t for all integer values representing the size of an object
//!
//! Variables that hold object sizes should be size_t, not int or other types,
//! to avoid overflow and ensure sufficient precision.
//!
//! ## Examples:
//!
//! **Non-compliant:**
//! ```c
//! void copy(size_t n) {
//! int i; // Wrong type for size
//! for (i = 0; i < n; ++i) { ... } // int compared with size_t
//! }
//! ```
//!
//! **Compliant:**
//! ```c
//! void copy(size_t n) {
//! size_t i; // Correct type
//! for (i = 0; i < n; ++i) { ... }
//! }
//! ```
use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
use std::collections::{HashMap, HashSet};
use tree_sitter::Node;
pub struct Int01C;
impl CertRule for Int01C {
fn rule_id(&self) -> &'static str {
"INT01-C"
}
fn description(&self) -> &'static str {
"Use size_t or rsize_t for all integer values representing the size of an object"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"INT01-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
// Track size_t/rsize_t parameters and variables
let mut size_t_vars: HashSet<String> = HashSet::new();
// Track int variables
let mut int_vars: HashMap<String, (usize, usize)> = HashMap::new();
// Find size_t/rsize_t variables (parameters and locals)
self.find_size_t_vars(node, source, &mut size_t_vars);
// Find int variables
self.find_int_vars(node, source, &mut int_vars);
// Find comparisons between int and size_t
self.find_int_size_t_comparisons(node, source, &size_t_vars, &int_vars, &mut violations);
// Check for function parameters representing sizes that don't use size_t
self.check_size_params(node, source, &mut violations);
// Check for variables used as sizes (in malloc/alloc calls) that aren't size_t
self.check_size_variable_usage(node, source, &size_t_vars, &mut violations);
violations
}
}
impl Int01C {
/// Find size_t/rsize_t variables (parameters and declarations)
fn find_size_t_vars(&self, node: &Node, source: &str, size_t_vars: &mut HashSet<String>) {
// Check function parameters
if node.kind() == "parameter_declaration" {
let decl_text = get_node_text(node, source);
// Check for size_t or rsize_t
if decl_text.contains("size_t") || decl_text.contains("rsize_t") {
if let Some(var_name) = self.extract_param_name(node, source) {
size_t_vars.insert(var_name);
}
}
}
// Check variable declarations
if node.kind() == "declaration" {
let decl_text = get_node_text(node, source);
// Check for size_t or rsize_t
if decl_text.contains("size_t") || decl_text.contains("rsize_t") {
if let Some(var_name) = self.extract_var_name(node, source) {
size_t_vars.insert(var_name);
}
}
}
// Recurse
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.find_size_t_vars(&child, source, size_t_vars);
}
}
}
/// Find int variable declarations
fn find_int_vars(
&self,
node: &Node,
source: &str,
int_vars: &mut HashMap<String, (usize, usize)>,
) {
if node.kind() == "declaration" {
let decl_text = get_node_text(node, source);
// Check for int but not unsigned int, not size_t, not uint*
if decl_text.trim().starts_with("int ")
|| decl_text.contains(" int ")
|| decl_text.contains("\tint ")
{
if !decl_text.contains("unsigned")
&& !decl_text.contains("size_t")
&& !decl_text.contains("uint")
{
if let Some(var_name) = self.extract_var_name(node, source) {
int_vars.insert(
var_name,
(
node.start_position().row + 1,
node.start_position().column + 1,
),
);
}
}
}
}
// Recurse
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.find_int_vars(&child, source, int_vars);
}
}
}
/// Find comparisons between int variables and size_t variables
fn find_int_size_t_comparisons(
&self,
node: &Node,
source: &str,
size_t_vars: &HashSet<String>,
int_vars: &HashMap<String, (usize, usize)>,
violations: &mut Vec<RuleViolation>,
) {
if node.kind() == "binary_expression" {
if let Some(operator) = node.child_by_field_name("operator") {
let op_text = get_node_text(&operator, source);
// Check comparison operators
if op_text == "<" || op_text == "<=" || op_text == ">" || op_text == ">=" {
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let left_text = get_node_text(&left, source);
let right_text = get_node_text(&right, source);
// Check if int var is compared with size_t var
if (int_vars.contains_key(left_text) && size_t_vars.contains(right_text))
|| (int_vars.contains_key(right_text)
&& size_t_vars.contains(left_text))
{
let int_var = if int_vars.contains_key(left_text) {
left_text
} else {
right_text
};
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
message: format!(
"Variable '{}' of type int compared with size_t. \
Use size_t for variables representing object sizes.",
int_var
),
severity: self.severity(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
file_path: String::new(),
suggestion: Some(format!(
"Change declaration of '{}' from int to size_t",
int_var
)),
requires_manual_review: None,
});
}
}
}
}
}
// Recurse
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.find_int_size_t_comparisons(&child, source, size_t_vars, int_vars, violations);
}
}
}
/// Extract parameter name
fn extract_param_name(&self, param: &Node, source: &str) -> Option<String> {
for i in 0..param.child_count() {
if let Some(child) = param.child(i) {
if child.kind() == "identifier" {
return Some(get_node_text(&child, source).to_string());
}
}
}
None
}
/// Extract variable name from declaration
fn extract_var_name(&self, decl: &Node, source: &str) -> Option<String> {
for i in 0..decl.child_count() {
if let Some(child) = decl.child(i) {
if child.kind() == "init_declarator" || child.kind() == "identifier" {
return self.find_identifier(&child, source);
}
}
}
None
}
/// Find identifier in node
fn find_identifier(&self, node: &Node, source: &str) -> Option<String> {
if node.kind() == "identifier" {
return Some(get_node_text(node, source).to_string());
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if let Some(name) = self.find_identifier(&child, source) {
return Some(name);
}
}
}
None
}
/// Check for function parameters representing sizes that don't use size_t
fn check_size_params(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
// Look for function declarations with size-related parameter names
if node.kind() == "function_definition" || node.kind() == "function_declarator" {
// Find parameter_list
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "function_declarator" {
self.check_size_params(&child, source, violations);
} else if child.kind() == "parameter_list" {
self.check_param_list(&child, source, violations);
}
}
}
}
// Recurse — skip function_declarator children of function_definition
// to avoid double-visiting (already handled above)
let dominated =
node.kind() == "function_definition" || node.kind() == "function_declarator";
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if dominated
&& (child.kind() == "function_declarator" || child.kind() == "parameter_list")
{
continue;
}
self.check_size_params(&child, source, violations);
}
}
}
/// Check parameters in a parameter list for size-related names without size_t
fn check_param_list(
&self,
param_list: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
for i in 0..param_list.child_count() {
if let Some(param) = param_list.child(i) {
if param.kind() == "parameter_declaration" {
let param_text = get_node_text(¶m, source);
// Skip if already using size_t or rsize_t
if param_text.contains("size_t") || param_text.contains("rsize_t") {
continue;
}
// Skip fixed-width integer types — on small/embedded targets (8/16-bit MCUs)
// uint8_t or uint16_t is the correct type for size parameters; size_t
// would waste scarce registers and uint8_t/uint16_t is intentional.
if param_text.contains("uint8_t")
|| param_text.contains("uint16_t")
|| param_text.contains("int8_t")
|| param_text.contains("int16_t")
{
continue;
}
// Check for size-related parameter names
let size_names = [
"size",
"blocksize",
"len",
"length",
"count",
"bufsize",
"sz",
];
let param_lower = param_text.to_lowercase();
for size_name in &size_names {
if param_lower.contains(size_name) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
message: format!(
"Parameter '{}' appears to represent a size but doesn't use size_t",
param_text.trim()
),
severity: self.severity(),
line: param.start_position().row + 1,
column: param.start_position().column + 1,
file_path: String::new(),
suggestion: Some("Use size_t for parameters representing object sizes".to_string()),
requires_manual_review: None,
});
break;
}
}
}
}
}
}
/// Check for variables used as sizes in malloc/alloc calls that aren't size_t
fn check_size_variable_usage(
&self,
node: &Node,
source: &str,
size_t_vars: &HashSet<String>,
violations: &mut Vec<RuleViolation>,
) {
// Look for call expressions to allocation functions
if node.kind() == "call_expression" {
if let Some(function) = node.child_by_field_name("function") {
let func_name = get_node_text(&function, source);
// Check if this is an allocation function
let alloc_funcs = ["malloc", "calloc", "realloc", "alloc", "aligned_alloc"];
if alloc_funcs
.iter()
.any(|&f| func_name == f || func_name.ends_with("alloc"))
{
// Check arguments for non-size_t size expressions
if let Some(args) = node.child_by_field_name("arguments") {
self.check_alloc_args(&args, source, size_t_vars, violations);
}
}
}
}
// Recurse
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.check_size_variable_usage(&child, source, size_t_vars, violations);
}
}
}
/// Check allocation function arguments for non-size_t types
fn check_alloc_args(
&self,
args: &Node,
source: &str,
size_t_vars: &HashSet<String>,
violations: &mut Vec<RuleViolation>,
) {
// The size argument is typically the first (malloc) or second (calloc)
// We flag variables that represent sizes but aren't size_t
for i in 0..args.child_count() {
if let Some(arg) = args.child(i) {
// Skip parentheses, commas
if arg.kind() == "(" || arg.kind() == ")" || arg.kind() == "," {
continue;
}
// sizeof() returns size_t by definition (C99 §6.5.3.4 ¶5) —
// always the correct type, never flag it.
if arg.kind() == "sizeof_expression" {
continue;
}
// sizeof(...) * N or N * sizeof(...) — the result is size_t
if arg.kind() == "binary_expression" {
if let Some(op) = arg.child_by_field_name("operator") {
let op_text = get_node_text(&op, source);
if op_text == "*" {
let left = arg.child_by_field_name("left");
let right = arg.child_by_field_name("right");
let has_sizeof = left
.as_ref()
.is_some_and(|n| n.kind() == "sizeof_expression")
|| right
.as_ref()
.is_some_and(|n| n.kind() == "sizeof_expression");
if has_sizeof {
continue;
}
}
}
}
// Check if the argument contains an identifier (variable)
let arg_text = get_node_text(&arg, source);
// Extract the base variable name from expressions like "length+1"
let base_var = self.extract_base_var_name(&arg, source);
// Skip if the base variable is already declared as size_t/rsize_t
if let Some(ref var_name) = base_var {
if size_t_vars.contains(var_name) {
continue;
}
}
// If it's a variable name that looks like a size but isn't size_t
// We detect this by checking if it's used in allocation context
// and has a size-related name
let size_related = ["length", "len", "size", "count", "sz", "n"]
.iter()
.any(|&name| arg_text.to_lowercase().contains(name));
if size_related {
// This is a heuristic - the variable name suggests a size
// but we're using it in an allocation function
// The rule says all such values should be size_t
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
message: format!(
"Expression '{}' used as size argument to allocation function should use size_t type",
arg_text
),
severity: self.severity(),
line: arg.start_position().row + 1,
column: arg.start_position().column + 1,
file_path: String::new(),
suggestion: Some("Ensure the variable used for size is declared as size_t".to_string()),
requires_manual_review: None,
});
return; // Only report once per call
}
}
}
}
/// Extract the base variable name from an expression (e.g., "length+1" -> "length")
fn extract_base_var_name(&self, node: &Node, source: &str) -> Option<String> {
// If it's a simple identifier, return it
if node.kind() == "identifier" {
return Some(get_node_text(node, source).to_string());
}
// If it's a binary expression, check the left side first
if node.kind() == "binary_expression" {
if let Some(left) = node.child_by_field_name("left") {
return self.extract_base_var_name(&left, source);
}
}
// Recurse into children to find an identifier
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if let Some(name) = self.extract_base_var_name(&child, source) {
return Some(name);
}
}
}
None
}
}