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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
//! API00-C: Functions should validate their parameters
//!
//! This rule detects functions that use parameters without validating them first.
//! This includes:
//! - Pointer parameters used without NULL checks
//! - Integer parameters used in arithmetic without overflow checks
//!
//! ## Examples:
//!
//! **Non-compliant:**
//! ```c
//! void setfile(FILE *file) {
//! myFile = file; // No validation of file parameter
//! }
//!
//! int string_length(const char *str) {
//! return strlen(str); // No NULL check before use
//! }
//! ```
//!
//! **Compliant:**
//! ```c
//! errno_t setfile(FILE *file) {
//! if (file && !ferror(file) && !feof(file)) {
//! myFile = file;
//! return 0;
//! }
//! return -1; // Error handling
//! }
//!
//! int safe_string_copy(char *dest, const char *src) {
//! if (!dest || !src) {
//! return -1; // Validation before use
//! }
//! strcpy(dest, src);
//! return 0;
//! }
//! ```
//!
//! ## Detection Strategy:
//! - Find function definitions with pointer parameters
//! - Check if pointer parameters are validated (NULL check) before being used
//! - Report violation if a pointer parameter is used without prior validation
use super::super::{CertRule, RuleViolation};
use crate::analyze::context::ProjectContext;
use crate::analyze::function_summary::FunctionSummary;
use crate::analyze::null_state::NullState;
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::{get_function_parameters, get_node_text, is_pointer_type};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use tree_sitter::Node;
pub struct Api00C {
function_summaries: RefCell<HashMap<String, FunctionSummary>>,
}
impl Api00C {
pub fn new() -> Self {
Self {
function_summaries: RefCell::new(HashMap::new()),
}
}
}
impl CertRule for Api00C {
fn rule_id(&self) -> &'static str {
"API00-C"
}
fn description(&self) -> &'static str {
"Functions should validate their parameters"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"API00-C"
}
fn set_project_context(&self, context: &ProjectContext) {
*self.function_summaries.borrow_mut() = context.function_summaries.clone();
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
self.check_node(node, source, &mut violations);
violations
}
}
impl Api00C {
fn check_node(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
// Look for function definitions
if node.kind() == "function_definition" {
self.check_function_parameter_validation(node, source, violations);
}
// Recursively check child nodes
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.check_node(&child, source, violations);
}
}
}
fn check_function_parameter_validation(
&self,
function_node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
// Skip static functions — API00-C is about public API contracts
if Self::is_static_function(function_node, source) {
return;
}
// Get function parameters (handle nested declarators for pointer-returning functions)
let params = match self.extract_function_parameters(function_node, source) {
Some(p) => p,
None => return, // No parameters
};
// Check if this is a debug/logging function (has both file AND line parameters)
let has_debug_params = params
.iter()
.any(|(name, _)| matches!(name.to_lowercase().as_str(), "file" | "filename"))
&& params
.iter()
.any(|(name, _)| matches!(name.to_lowercase().as_str(), "line" | "lineno"));
// Check if this is a qsort-style comparator function
// Pattern: int func(const void* a, const void* b, ...)
let is_comparator = params.len() >= 2
&& params.iter().take(2).all(|(_, param_type)| {
param_type.contains("const void *") || param_type.contains("const void*")
});
if is_comparator {
return; // Skip validation for qsort-style comparators
}
// Filter for pointer parameters, excluding debug parameters only if this is a debug function
let pointer_params: Vec<String> = params
.iter()
.filter(|(name, param_type)| {
is_pointer_type(param_type)
&& !(has_debug_params && self.is_debug_parameter(name))
&& !self.is_callback_context_parameter(name)
})
.map(|(name, _)| name.clone())
.collect();
// Map param name → type text for downstream type-aware checks.
let param_types: HashMap<&str, &str> = params
.iter()
.map(|(name, ty)| (name.as_str(), ty.as_str()))
.collect();
// Filter for integer parameters that could overflow
let integer_params: Vec<String> = params
.iter()
.filter(|(_, param_type)| self.is_integer_type(param_type))
.map(|(name, _)| name.clone())
.collect();
// Get function body
let body = match function_node.child_by_field_name("body") {
Some(b) => b,
None => return, // No body (declaration only)
};
// Check pointer parameters
if !pointer_params.is_empty() {
// Find validated parameters (those that appear in validation checks)
let validated_params = self.find_validated_parameters(&body, &pointer_params, source);
// Look up callsite null states from prescan (if available)
let func_name = self.get_function_name(function_node, source);
let summaries = self.function_summaries.borrow();
let summary = summaries.get(&func_name);
// Build param name → index mapping
let param_indices: HashMap<&str, usize> = params
.iter()
.enumerate()
.map(|(i, (name, _))| (name.as_str(), i))
.collect();
// Check which pointer parameters are used without validation
for param_name in &pointer_params {
if !validated_params.contains(param_name) {
// Suppress if all callers pass NotNull for this parameter
if let (Some(s), Some(&idx)) = (summary, param_indices.get(param_name.as_str()))
{
if let Some(&state) = s.callsite_param_null_states.get(&idx) {
if state == NullState::NotNull {
continue; // All callers pass non-null → skip
}
}
}
// Suppress relay-only parameters: if the parameter is only
// passed as an argument to other function calls (never
// dereferenced, indexed, or member-accessed locally), the
// function is a relay and validation is the callee's concern.
if self.is_relay_only_parameter(&body, param_name, source) {
continue;
}
// Suppress `void *` parameters that are never dereferenced
// locally and pass through only to null-safe sinks. Typical
// generic-container slot parameter (e.g., ArrayList_Append's
// `void *item`) — NULL is a valid value.
if let Some(param_type) = param_types.get(param_name.as_str()) {
if Self::is_generic_void_pointer_type(param_type)
&& self.is_void_ptr_storage_safe(&body, param_name, source, &summaries)
{
continue;
}
}
// Check if the parameter is actually used in the function
if self.is_parameter_used(&body, param_name, source) {
self.report_violation(
function_node,
param_name,
"pointer",
source,
violations,
);
}
}
}
}
// Check integer parameters for overflow validation
if !integer_params.is_empty() {
self.check_integer_overflow_validation(
function_node,
&body,
&integer_params,
source,
violations,
);
}
}
/// Check if integer parameters are validated for overflow before arithmetic operations
fn check_integer_overflow_validation(
&self,
function_node: &Node,
body: &Node,
integer_params: &[String],
source: &str,
violations: &mut Vec<RuleViolation>,
) {
// Look for arithmetic operations using integer parameters without overflow checks
for param_name in integer_params {
if self.has_unchecked_arithmetic(body, param_name, source) {
self.report_violation(function_node, param_name, "integer", source, violations);
}
}
}
/// Check if an integer parameter is used in arithmetic without overflow validation
fn has_unchecked_arithmetic(&self, body: &Node, param_name: &str, source: &str) -> bool {
// Check if there's overflow validation before arithmetic use
let body_text = get_node_text(body, source);
// Remove comments from body text to avoid false positives
let body_no_comments = self.remove_comments(&body_text);
// Look for arithmetic operators with the parameter
let arithmetic_patterns = [
format!("{} +", param_name),
format!("{} -", param_name),
format!("{} *", param_name),
format!("{}+", param_name),
format!("{}-", param_name),
format!("{}*", param_name),
format!("+ {}", param_name),
format!("- {}", param_name),
format!("* {}", param_name),
format!("+{}", param_name),
format!("-{}", param_name),
format!("*{}", param_name),
format!("{} <<", param_name),
format!("{}<<", param_name),
format!("<< {}", param_name),
format!("<<{}", param_name),
];
let has_arithmetic = arithmetic_patterns
.iter()
.any(|p| body_no_comments.contains(p));
if !has_arithmetic {
return false;
}
// Check for overflow validation patterns
let overflow_check_patterns = [
// Check for INT_MAX/INT_MIN comparisons
format!("{} > INT_MAX", param_name),
format!("{} < INT_MIN", param_name),
format!("{} >= INT_MAX", param_name),
format!("{} <= INT_MIN", param_name),
// Check for SIZE_MAX comparisons
format!("{} > SIZE_MAX", param_name),
format!("{} >= SIZE_MAX", param_name),
format!("SIZE_MAX - {}", param_name),
format!("SIZE_MAX -{}", param_name),
// Check for UINT_MAX comparisons
format!("{} > UINT_MAX", param_name),
format!("{} >= UINT_MAX", param_name),
// Check for division overflow check (result / divisor != dividend)
"will overflow".to_string(),
"overflow check".to_string(),
// Wrapped arithmetic check
"__builtin_add_overflow".to_string(),
"__builtin_sub_overflow".to_string(),
"__builtin_mul_overflow".to_string(),
];
let has_overflow_check = overflow_check_patterns
.iter()
.any(|p| body_text.contains(p));
// Also check for basic parameter validation (if param == 0, if param < X, etc.)
let basic_validation_patterns = [
format!("if ({} == 0)", param_name),
format!("if ({}==0)", param_name),
format!("if ({} == 0", param_name),
format!("if (0 == {})", param_name),
format!("if (!{})", param_name),
format!("if ({} < ", param_name),
format!("if ({} > ", param_name),
format!("if ({} <= ", param_name),
format!("if ({} >= ", param_name),
// Handle || patterns
format!("|| {} == 0", param_name),
format!("||{} == 0", param_name),
format!("{} == 0 ||", param_name),
format!("{} == 0||", param_name),
format!("|| {} > ", param_name),
format!("|| {} < ", param_name),
format!("{} > ", param_name),
format!("{} < ", param_name),
];
let has_basic_validation = basic_validation_patterns
.iter()
.any(|p| body_text.contains(p));
// Return true if there's arithmetic but no overflow check AND no basic validation
!has_overflow_check && !has_basic_validation
}
/// Remove C-style comments from text to avoid false positives
fn remove_comments(&self, text: &str) -> String {
let mut result = String::with_capacity(text.len());
let chars: Vec<char> = text.chars().collect();
let mut i = 0;
while i < chars.len() {
if i + 1 < chars.len() && chars[i] == '/' && chars[i + 1] == '*' {
// Skip block comment
i += 2;
while i + 1 < chars.len() && !(chars[i] == '*' && chars[i + 1] == '/') {
i += 1;
}
i += 2; // Skip closing */
} else if i + 1 < chars.len() && chars[i] == '/' && chars[i + 1] == '/' {
// Skip line comment
while i < chars.len() && chars[i] != '\n' {
i += 1;
}
} else {
result.push(chars[i]);
i += 1;
}
}
result
}
/// Check if a type is an integer type (not floating point)
fn is_integer_type(&self, type_str: &str) -> bool {
let normalized = type_str.to_lowercase();
// Exclude pointers
if type_str.contains('*') {
return false;
}
// Exclude floating point types
if normalized.contains("float") || normalized.contains("double") {
return false;
}
// Exclude char types — single-byte types used for character/byte processing
// where arithmetic is on known-range values (e.g., c - '0', c - 'a')
if normalized.contains("char") {
return false;
}
// Check for integer types
normalized.contains("int")
|| (normalized.contains("long") && !normalized.contains("double"))
|| normalized.contains("short")
|| normalized.contains("size_t")
|| (normalized.contains("unsigned")
&& !normalized.contains("double")
&& !normalized.contains("float"))
|| (normalized.contains("signed")
&& !normalized.contains("double")
&& !normalized.contains("float"))
}
/// Find parameters that are validated (checked for NULL) before use
fn find_validated_parameters(
&self,
body: &Node,
pointer_params: &[String],
source: &str,
) -> HashSet<String> {
let mut validated = HashSet::new();
// Look for validation patterns at the start of the function
self.check_validation_patterns(body, pointer_params, source, &mut validated);
validated
}
/// Check for common validation patterns like:
/// - if (!ptr) return;
/// - if (ptr == NULL) return;
/// - if (!ptr || !ptr2) return;
/// - assert(ptr != NULL);
fn check_validation_patterns(
&self,
node: &Node,
pointer_params: &[String],
source: &str,
validated: &mut HashSet<String>,
) {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
match child.kind() {
"if_statement" => {
// Check if this is a validation pattern
if let Some(condition) = child.child_by_field_name("condition") {
let condition_text = get_node_text(&condition, source);
// Case 1: early-return / early-exit pattern
// if (!ptr) { return; }
// if (ptr == NULL) { return; }
// if (isNullOrEmpty(ptr)) { return; } (helper fn call)
if self.is_early_return_pattern(&child, source) {
// Use broad match: any param appearing in the condition
// of an early-return guard is considered validated.
// This handles both direct null checks and helper fn calls.
for param in pointer_params {
if condition_text.contains(param.as_str()) {
validated.insert(param.clone());
}
}
} else if child.child_by_field_name("alternative").is_some() {
// Case 3: if/else chain — param is checked in condition and
// actual work is in the else branch.
// if (NULL == ptr) { result = ERR; } else { work(ptr); }
// Also handles if/else-if/else chains:
// if (NULL == a) { err; } else if (NULL == b) { err; } else { work(a,b); }
let validated_in_condition = self
.extract_validated_params_from_condition(
&condition,
pointer_params,
source,
);
for param in validated_in_condition {
validated.insert(param);
}
// Walk into chained else-if conditions to collect more validated params
self.collect_else_if_chain_validations(
&child,
pointer_params,
source,
validated,
);
} else {
// Case 2: positive guard pattern
// if (ptr != NULL) { /* all usage inside */ }
// The parameter is only accessed inside the guarded block,
// so it is safely validated even without an early return.
let validated_in_condition = self
.extract_validated_params_from_condition(
&condition,
pointer_params,
source,
);
for param in validated_in_condition {
if self.is_positive_null_guard(&condition_text, ¶m) {
validated.insert(param);
}
}
}
}
}
"return_statement" => {
// Case 4: return expression contains null check
// return (str == NULL || str[0] == '\0');
// The null check IS the validation in short-circuit boolean returns.
let stmt_text = get_node_text(&child, source);
for param in pointer_params {
if stmt_text.contains(&format!("{} == NULL", param))
|| stmt_text.contains(&format!("NULL == {}", param))
|| stmt_text.contains(&format!("!{}", param))
|| stmt_text.contains(&format!("! {}", param))
{
validated.insert(param.clone());
}
}
}
"expression_statement" => {
// Check for assert() or similar validation macros
let stmt_text = get_node_text(&child, source);
if stmt_text.contains("assert") || stmt_text.contains("ASSERT") {
for param in pointer_params {
if stmt_text.contains(param) && stmt_text.contains("NULL") {
validated.insert(param.clone());
}
}
}
}
// Recurse into preprocessor blocks — validation may be
// inside #ifdef/#if/#else branches
"preproc_ifdef"
| "preproc_if"
| "preproc_else"
| "preproc_elif"
| "preproc_function_def" => {
self.check_validation_patterns(&child, pointer_params, source, validated);
}
_ => {}
}
}
}
}
/// Walk an if/else-if chain to collect validated params from all conditions.
/// For `if (NULL == a) { err; } else if (NULL == b) { err; } else { work(a,b); }`,
/// both `a` and `b` are validated in the final else block.
/// Tree-sitter wraps else-if in `else_clause { if_statement { ... } }`.
fn collect_else_if_chain_validations(
&self,
if_node: &Node,
pointer_params: &[String],
source: &str,
validated: &mut HashSet<String>,
) {
let mut current = *if_node;
while let Some(alternative) = current.child_by_field_name("alternative") {
// Tree-sitter wraps `else if` in an else_clause node
let next_if = if alternative.kind() == "else_clause" {
// Look for an if_statement inside the else_clause
let mut inner_if = None;
for i in 0..alternative.child_count() {
if let Some(child) = alternative.child(i) {
if child.kind() == "if_statement" {
inner_if = Some(child);
break;
}
}
}
match inner_if {
Some(if_stmt) => if_stmt,
None => break, // Plain else { ... } — end of chain
}
} else if alternative.kind() == "if_statement" {
alternative
} else {
break;
};
if let Some(condition) = next_if.child_by_field_name("condition") {
let params_in_cond = self.extract_validated_params_from_condition(
&condition,
pointer_params,
source,
);
for param in params_in_cond {
validated.insert(param);
}
}
current = next_if;
}
}
/// Extract parameter names that are being validated in a condition
fn extract_validated_params_from_condition(
&self,
condition: &Node,
pointer_params: &[String],
source: &str,
) -> Vec<String> {
let mut validated_params = Vec::new();
let condition_text = get_node_text(condition, source);
for param in pointer_params {
// Check for common validation patterns:
// !param, param == NULL, param != NULL (when combined with early return)
// NULL == param, NULL != param
// Also handle patterns with || separators
// Create patterns to match
let patterns = vec![
format!("!{}", param), // !ptr
format!("! {}", param), // ! ptr (with space)
format!("{} == NULL", param), // ptr == NULL
format!("NULL == {}", param), // NULL == ptr
format!("{} == 0", param), // ptr == 0
format!("0 == {}", param), // 0 == ptr
format!("{}==NULL", param), // ptr==NULL (no spaces)
format!("NULL=={}", param), // NULL==ptr
format!("{} != NULL", param), // ptr != NULL (positive check)
format!("NULL != {}", param), // NULL != ptr
format!("{}!=NULL", param), // ptr!=NULL
format!("NULL!={}", param), // NULL!=ptr
];
let mut is_validated = false;
for pattern in &patterns {
if condition_text.contains(pattern) {
is_validated = true;
break;
}
}
// Also check for parameter appearing in logical expressions
// This handles: if (!a || !b || !c)
if !is_validated {
// Check if param appears with ! before it (possibly after ||)
let search_patterns = vec![
format!("||!{}", param), // ||!ptr
format!("|| !{}", param), // || !ptr
format!("(!{}", param), // (!ptr
format!("( !{}", param), // ( !ptr
format!("!{}||", param), // !ptr||
format!("!{} ||", param), // !ptr ||
format!("!{})", param), // !ptr)
format!("!{} )", param), // !ptr )
];
for pattern in &search_patterns {
if condition_text.contains(pattern) {
is_validated = true;
break;
}
}
}
// Check for positive validation (parameter being checked for truthiness)
// e.g., if (file && !ferror(file)), or bare if(ptr) / if (ptr)
if !is_validated {
let positive_patterns = vec![
format!("{} &&", param), // ptr &&
format!("({}&&", param), // (ptr&&
format!("({} &&", param), // (ptr &&
format!("&& {}", param), // && ptr
format!("&&{}", param), // &&ptr
];
for pattern in &positive_patterns {
if condition_text.contains(pattern) {
is_validated = true;
break;
}
}
// Bare truthiness: condition IS the parameter itself
// e.g., if(ptr) { use } else { return NULL; }
if !is_validated {
let trimmed = condition_text.trim();
// Strip outer parens: "(ptr)" → "ptr"
let inner = if trimmed.starts_with('(') && trimmed.ends_with(')') {
trimmed[1..trimmed.len() - 1].trim()
} else {
trimmed
};
if inner == param {
is_validated = true;
}
}
}
if is_validated {
validated_params.push(param.clone());
}
}
validated_params
}
/// Check if an if statement represents an early return/error pattern
fn is_early_return_pattern(&self, if_node: &Node, source: &str) -> bool {
// Get the consequence (then branch)
if let Some(consequence) = if_node.child_by_field_name("consequence") {
return self.contains_return_or_error(&consequence, source);
}
false
}
/// Check if a node contains a return statement or error handling
fn contains_return_or_error(&self, node: &Node, source: &str) -> bool {
match node.kind() {
"return_statement" => true,
"compound_statement" => {
// Check ALL statements for return or noreturn function calls
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "return_statement" {
return true;
}
// Check for noreturn functions (longjmp, exit, abort)
if child.kind() == "expression_statement" {
if self.is_noreturn_call(&child, source) {
return true;
}
}
}
}
false
}
_ => false,
}
}
/// Check if an expression statement contains a noreturn function call
fn is_noreturn_call(&self, expr_stmt: &Node, source: &str) -> bool {
for i in 0..expr_stmt.child_count() {
if let Some(child) = expr_stmt.child(i) {
if child.kind() == "call_expression" {
if let Some(func) = child.child_by_field_name("function") {
let func_name = get_node_text(&func, source);
// Check for common noreturn functions
if matches!(
func_name,
"longjmp" | "exit" | "abort" | "_Exit" | "quick_exit" | "thrd_exit"
) {
return true;
}
}
}
}
}
false
}
/// Check if a parameter is actually used in the function body
/// Check if a parameter is only relayed to callees that validate it.
/// Returns true when the parameter is never directly used and every callee
/// that receives it either checks for null or itself relays to a checker.
fn is_relay_only_parameter(&self, body: &Node, param_name: &str, source: &str) -> bool {
let summaries = self.function_summaries.borrow();
let mut relay_callees: Vec<(String, usize)> = Vec::new();
let mut found_direct_use = false;
self.classify_param_uses(
body,
param_name,
source,
&mut relay_callees,
&mut found_direct_use,
);
if found_direct_use || relay_callees.is_empty() {
return false;
}
// Every callee that receives this parameter must validate it or accept NULL
for (callee_name, arg_idx) in &relay_callees {
// Standard library functions that accept NULL pointers — no validation needed
if Self::is_null_accepting_stdlib(callee_name, *arg_idx) {
continue;
}
if let Some(callee_summary) = summaries.get(callee_name.as_str()) {
if !callee_summary.checks_null_params.contains(arg_idx) {
return false; // Callee doesn't validate → not safe to suppress
}
} else {
return false; // Unknown callee → not safe
}
}
true
}
fn classify_param_uses(
&self,
node: &Node,
param_name: &str,
source: &str,
relay_callees: &mut Vec<(String, usize)>,
found_direct_use: &mut bool,
) {
if node.kind() == "identifier" {
let text = get_node_text(node, source);
if text == param_name {
if let Some(parent) = node.parent() {
// Check: is this inside a call_expression's argument list?
if parent.kind() == "argument_list" {
if let Some(call_expr) = parent.parent() {
if call_expr.kind() == "call_expression" {
if let Some(func) = call_expr.child_by_field_name("function") {
let callee = get_node_text(&func, source);
// Determine which positional arg this is
let arg_idx = self.get_arg_index(node, &parent);
relay_callees.push((callee.to_string(), arg_idx));
return;
}
}
}
*found_direct_use = true;
return;
}
if self.is_in_validation_context(node) || self.is_in_void_cast(node, source) {
return;
}
}
*found_direct_use = true;
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.classify_param_uses(
&child,
param_name,
source,
relay_callees,
found_direct_use,
);
}
}
}
/// Get the positional index of an argument within an argument_list.
/// Standard library functions that accept NULL pointer arguments by design.
/// free(NULL) is a no-op per C11 7.22.3.3. realloc(NULL, size) is equivalent
/// to malloc(size) per C11 7.22.3.5. These functions do NOT need callers to
/// validate pointer arguments before calling.
fn is_null_accepting_stdlib(func_name: &str, arg_idx: usize) -> bool {
matches!(
(func_name, arg_idx),
("free", 0)
| ("realloc", 0)
| ("cfree", 0)
| ("Memory_Free", 0)
| ("Memory_Realloc", 0)
)
}
/// Return true if `param_type` is a bare `void *` (optionally const-qualified).
/// Rejects `void **`, arrays, and anything with a concrete type name.
fn is_generic_void_pointer_type(param_type: &str) -> bool {
let trimmed = param_type.trim();
if trimmed.contains('[') {
return false;
}
if trimmed.chars().filter(|c| *c == '*').count() != 1 {
return false;
}
if !trimmed.contains("void") {
return false;
}
// The text before the `*` must contain only void / const / volatile tokens.
let before_star = trimmed.split('*').next().unwrap_or("").trim();
for token in before_star.split_whitespace() {
if !matches!(token, "const" | "volatile" | "void") {
return false;
}
}
true
}
/// Walk the body and decide whether every use of a `void *` parameter is
/// safe for a NULL value. Safe uses: stored as RHS of an assignment, used
/// as a local initializer, passed to a null-accepting stdlib function, or
/// passed to a callee whose summary validates the corresponding argument.
/// A single dereference (`*item`, `item->x`, `item[i]`) or a call to a
/// callee of unknown null-handling behavior makes the parameter unsafe.
fn is_void_ptr_storage_safe(
&self,
body: &Node,
param_name: &str,
source: &str,
summaries: &HashMap<String, FunctionSummary>,
) -> bool {
let mut saw_any_use = false;
let mut safe = true;
self.void_ptr_storage_walk(
body,
param_name,
source,
summaries,
&mut safe,
&mut saw_any_use,
);
// If the parameter never appears, `is_parameter_used` will return false
// anyway; don't claim responsibility for that path.
saw_any_use && safe
}
fn void_ptr_storage_walk(
&self,
node: &Node,
param_name: &str,
source: &str,
summaries: &HashMap<String, FunctionSummary>,
safe: &mut bool,
saw_any_use: &mut bool,
) {
if !*safe {
return;
}
if node.kind() == "identifier" {
let text = get_node_text(node, source);
if text == param_name {
*saw_any_use = true;
if let Some(parent) = node.parent() {
// Skip identifiers that are used as a struct field name or
// subscript index rather than as the dereference target —
// those are unrelated uses of the same identifier text.
let is_self_as_target = |field: &str| {
parent
.child_by_field_name(field)
.map(|t| t.id() == node.id())
.unwrap_or(false)
};
match parent.kind() {
"pointer_expression" => {
// Could be `*item` (deref) or `&item` (address-of).
// Address-of a pointer itself doesn't deref it, but
// the resulting `void **` is highly atypical and we
// treat it as unsafe conservatively.
*safe = false;
return;
}
"field_expression" if is_self_as_target("argument") => {
*safe = false;
return;
}
"subscript_expression" if is_self_as_target("argument") => {
*safe = false;
return;
}
"argument_list" => {
if let Some(call_expr) = parent.parent() {
if call_expr.kind() == "call_expression" {
if let Some(func) = call_expr.child_by_field_name("function") {
let callee = get_node_text(&func, source);
let arg_idx = self.get_arg_index(node, &parent);
if Self::is_null_accepting_stdlib(callee, arg_idx) {
// ok
} else if let Some(s) = summaries.get(callee) {
if !s.checks_null_params.contains(&arg_idx) {
*safe = false;
return;
}
} else {
*safe = false;
return;
}
}
}
}
}
"cast_expression" => {
// `(void *)item` or `(T *)item` — a cast is still just a
// value read, treat it as storage-like and keep walking.
}
_ => {
// Other parents: assignment RHS, initializer in a
// declaration, return expression, comparison, etc.
// All safe for a NULL value.
}
}
}
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.void_ptr_storage_walk(
&child,
param_name,
source,
summaries,
safe,
saw_any_use,
);
}
}
}
fn get_arg_index(&self, arg_node: &Node, arg_list: &Node) -> usize {
let mut idx = 0;
for i in 0..arg_list.child_count() {
if let Some(child) = arg_list.child(i) {
if child.kind() == "(" || child.kind() == ")" || child.kind() == "," {
continue;
}
if child.id() == arg_node.id() {
return idx;
}
idx += 1;
}
}
idx
}
fn is_parameter_used(&self, body: &Node, param_name: &str, source: &str) -> bool {
self.check_parameter_usage(body, param_name, source)
}
fn check_parameter_usage(&self, node: &Node, param_name: &str, source: &str) -> bool {
// Check if this node is an identifier matching the parameter name
if node.kind() == "identifier" {
let text = get_node_text(node, source);
if text == param_name {
// Skip (void)param / UNUSED(param) patterns — these explicitly mark
// a parameter as intentionally unused (e.g., callback signature match)
if self.is_in_void_cast(node, source) {
return false;
}
// Check if it's actually being used (not just in a validation check)
if let Some(parent) = node.parent() {
// Skip if this is part of a validation check condition
if !self.is_in_validation_context(node) {
return true;
}
// Still count dereference as usage even in validation context
if parent.kind() == "pointer_expression"
|| parent.kind() == "field_expression"
|| parent.kind() == "subscript_expression"
{
return true;
}
}
}
}
// Recursively check children
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if self.check_parameter_usage(&child, param_name, source) {
return true;
}
}
}
false
}
/// Check if a node is part of a validation context (if condition checking for NULL)
fn is_in_validation_context(&self, node: &Node) -> bool {
let mut current = node.parent();
let mut depth = 0;
while let Some(parent) = current {
depth += 1;
if depth > 10 {
break; // Avoid infinite loops
}
// If we're in a parenthesized expression within an if condition
if parent.kind() == "if_statement" {
return true;
}
// Check for binary expressions that are comparisons to NULL
if parent.kind() == "binary_expression" {
return true;
}
// Check for unary not operator
if parent.kind() == "unary_expression" {
return true;
}
current = parent.parent();
}
false
}
/// Check if an identifier is inside a (void)param or UNUSED(param) cast.
/// These patterns explicitly suppress unused-parameter warnings and indicate
/// the parameter is intentionally not used.
fn is_in_void_cast(&self, node: &Node, source: &str) -> bool {
let mut current = node.parent();
let mut depth = 0;
while let Some(parent) = current {
depth += 1;
if depth > 5 {
break;
}
if parent.kind() == "cast_expression" {
// Check if the cast target type is "void"
for i in 0..parent.child_count() {
if let Some(child) = parent.child(i) {
if child.kind() == "type_descriptor" {
let type_text = get_node_text(&child, source);
if type_text.trim() == "void" {
return true;
}
}
}
}
}
// Handle UNUSED(param) macro — parsed as call_expression before preprocessing
if parent.kind() == "call_expression" {
if let Some(func) = parent.child_by_field_name("function") {
let func_name = get_node_text(&func, source);
if matches!(
func_name,
"UNUSED"
| "UNREFERENCED_PARAMETER"
| "UNUSED_PARAM"
| "UNUSED_PARAMETER"
| "Q_UNUSED"
) {
return true;
}
}
}
// Stop at expression_statement boundary
if parent.kind() == "expression_statement" {
break;
}
current = parent.parent();
}
false
}
/// Check if a function_definition has `static` storage class or a STATIC macro prefix.
fn is_static_function(function_node: &Node, source: &str) -> bool {
for i in 0..function_node.child_count() {
if let Some(child) = function_node.child(i) {
if child.kind() == "storage_class_specifier" {
if let Ok(text) = child.utf8_text(source.as_bytes()) {
if text == "static" {
return true;
}
}
}
}
}
// Check for STATIC macro prefix (tree-sitter sees unexpanded macro as first tokens).
// Match any token in the declaration prefix that contains "STATIC" as a
// substring — covers project-specific macros like LIN_STATIC_INLINE,
// MY_STATIC_FUNC, etc.
let func_text = function_node.utf8_text(source.as_bytes()).unwrap_or("");
let before_paren = func_text.split('(').next().unwrap_or("");
before_paren.split_whitespace().any(|token| {
let t = token.trim_start_matches('*');
t.contains("STATIC") || matches!(t, "PRIVATE" | "INTERNAL" | "LOCAL")
})
}
fn report_violation(
&self,
function_node: &Node,
param_name: &str,
param_type: &str,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
// Get function name
let func_name = self.get_function_name(function_node, source);
let (message, suggestion) = if param_type == "pointer" {
(
format!(
"Function '{}' does not validate pointer parameter '{}' before use",
func_name, param_name
),
format!(
"Add validation check for '{}' at the start of the function, e.g., 'if (!{}) {{ return error_code; }}'",
param_name, param_name
),
)
} else {
(
format!(
"Function '{}' does not validate integer parameter '{}' for overflow before arithmetic operations",
func_name, param_name
),
format!(
"Add overflow validation for '{}' before arithmetic, e.g., check against INT_MAX/INT_MIN or use __builtin_*_overflow()",
param_name
),
)
};
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message,
file_path: String::new(),
line: function_node.start_position().row + 1,
column: function_node.start_position().column + 1,
suggestion: Some(suggestion),
..Default::default()
});
}
fn get_function_name(&self, function_node: &Node, source: &str) -> String {
// Find the function declarator
for i in 0..function_node.child_count() {
if let Some(child) = function_node.child(i) {
if child.kind() == "function_declarator" {
// Get the identifier from the declarator
for j in 0..child.child_count() {
if let Some(declarator_child) = child.child(j) {
if declarator_child.kind() == "identifier" {
return get_node_text(&declarator_child, source).to_string();
}
// Handle pointer declarators like void (*func)(...)
if declarator_child.kind() == "parenthesized_declarator" {
if let Some(inner) = self.find_identifier(&declarator_child, source)
{
return inner;
}
}
}
}
} else if child.kind() == "pointer_declarator" {
// Handle functions returning pointers
if let Some(name) = self.find_identifier(&child, source) {
return name;
}
}
}
}
"unknown".to_string()
}
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(id) = self.find_identifier(&child, source) {
return Some(id);
}
}
}
None
}
/// Extract function parameters, handling nested declarators for pointer-returning functions
fn extract_function_parameters(
&self,
function_node: &Node,
source: &str,
) -> Option<Vec<(String, String)>> {
// First try the standard utility
if let Some(params) = get_function_parameters(function_node, source) {
return Some(params);
}
// Handle pointer-returning functions (e.g., URL *parse_url(...))
// The structure is: function_definition > pointer_declarator > function_declarator
for i in 0..function_node.child_count() {
if let Some(child) = function_node.child(i) {
if child.kind() == "pointer_declarator" {
// Look for function_declarator inside
if let Some(params) = self.find_params_in_declarator(&child, source) {
return Some(params);
}
}
}
}
None
}
fn find_params_in_declarator(
&self,
node: &Node,
source: &str,
) -> Option<Vec<(String, String)>> {
if node.kind() == "function_declarator" {
// Found it, extract parameters
return self.extract_params_from_declarator(node, source);
}
// Recurse into children
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if let Some(params) = self.find_params_in_declarator(&child, source) {
return Some(params);
}
}
}
None
}
fn extract_params_from_declarator(
&self,
declarator_node: &Node,
source: &str,
) -> Option<Vec<(String, String)>> {
let mut parameters = Vec::new();
// Find parameter_list node
for i in 0..declarator_node.child_count() {
if let Some(child) = declarator_node.child(i) {
if child.kind() == "parameter_list" {
// Extract each parameter
for j in 0..child.child_count() {
if let Some(param) = child.child(j) {
if param.kind() == "parameter_declaration" {
let param_text = get_node_text(¶m, source);
if let Some(name) = self.extract_param_name(¶m, source) {
parameters.push((name, param_text.to_string()));
}
}
}
}
}
}
}
if parameters.is_empty() {
None
} else {
Some(parameters)
}
}
fn extract_param_name(&self, param_node: &Node, source: &str) -> Option<String> {
// Look for identifier or declarator pattern
for i in 0..param_node.child_count() {
if let Some(child) = param_node.child(i) {
if child.kind() == "identifier" {
return Some(get_node_text(&child, source).to_string());
} else if matches!(
child.kind(),
"array_declarator" | "pointer_declarator" | "function_declarator"
) {
// Recursively find identifier in declarator
if let Some(id) = self.find_identifier(&child, source) {
return Some(id);
}
}
}
}
None
}
/// Returns true if the condition text is a positive NULL guard for `param`,
/// i.e. the if-block is only entered when the pointer is non-NULL.
/// Examples: `ptr != NULL`, `NULL != ptr`, `ptr != 0`, `ptr` (bare truthiness)
fn is_positive_null_guard(&self, condition_text: &str, param: &str) -> bool {
let patterns: &[&str] = &["!= NULL", "!=NULL", "!= 0", "!=0"];
for suffix in patterns {
if condition_text.contains(&format!("{} {}", param, suffix))
|| condition_text.contains(&format!("{}{}", param, suffix))
{
return true;
}
}
// NULL/0 on the left: NULL != ptr, 0 != ptr
let prefixes: &[&str] = &["NULL !=", "NULL!=", "0 !=", "0!="];
for prefix in prefixes {
if condition_text.contains(&format!("{} {}", prefix, param))
|| condition_text.contains(&format!("{}{}", prefix, param))
{
return true;
}
}
// Bare truthiness check: if (ptr) or if (ptr && ...)
// but NOT if (!ptr) which is the early-return form already handled above
let bare_patterns: &[&str] = &[
&format!("({})", param),
&format!("({} ", param),
&format!("({} &&", param),
&format!("({}&& ", param),
];
for p in bare_patterns {
if condition_text.contains(*p) {
return true;
}
}
false
}
/// Check if a parameter is a debug/logging parameter (e.g., __FILE__, __func__)
/// These are commonly passed without validation
fn is_debug_parameter(&self, param_name: &str) -> bool {
matches!(
param_name.to_lowercase().as_str(),
"file" | "filename" | "func" | "function" | "function_name" | "line" | "lineno"
)
}
/// Check if a parameter is a callback/handler context parameter.
/// These are opaque data pointers passed through event dispatch systems
/// and are not intended to be validated by the handler itself.
fn is_callback_context_parameter(&self, param_name: &str) -> bool {
let lower = param_name.to_lowercase();
matches!(
lower.as_str(),
"userdata"
| "user_data"
| "cb_arg"
| "cb_data"
| "cb_ctx"
| "callback_data"
| "callback_context"
| "priv"
| "opaque"
| "closure"
| "functor_context"
)
}
}