]> begriffs open source - ai-review/blob - critic/c-memory.md
frama-c
[ai-review] / critic / c-memory.md
1 # C Memory Safety Critic Module (ISO/IEC JTC 1/SC 22)
2
3 This module guides the Critic role when evaluating C programming code for memory safety issues, proper memory management, and prevention of memory-related vulnerabilities. This critic focuses on dynamic memory allocation, pointer safety, buffer management, and resource cleanup.
4
5 ## Memory Safety Evaluation Areas
6
7 ### 1. Dynamic Memory Management
8 **What to Look For:**
9 - Proper allocation and deallocation of dynamic memory
10 - Correct pairing of malloc/free operations
11 - Appropriate use of memory allocation functions
12 - Proper handling of allocation failures
13
14 **Common Problems:**
15 - Memory leaks from unmatched malloc/free pairs
16 - Use after free or double free errors
17 - Failure to check malloc return values
18 - Incorrect use of realloc without proper error handling
19 - Memory fragmentation from inefficient allocation patterns
20
21 **Evaluation Questions:**
22 - Is every malloc() paired with exactly one free()?
23 - Are malloc() return values checked for NULL?
24 - Is realloc() used correctly with proper error handling?
25 - Are allocation failures handled gracefully?
26 - Is memory deallocated in the correct order?
27
28 ### 2. Pointer Safety and Validation
29 **What to Look For:**
30 - Correct pointer arithmetic and dereferencing
31 - Proper null pointer checking
32 - Safe pointer initialization and assignment
33 - Appropriate use of const and restrict qualifiers
34
35 **Common Problems:**
36 - Dereferencing null or uninitialized pointers
37 - Improper pointer arithmetic leading to undefined behavior
38 - Use of dangling pointers to freed memory
39 - Incorrect pointer type casting
40 - Missing const qualifiers for read-only data
41
42 **Evaluation Questions:**
43 - Are pointers checked for NULL before dereferencing?
44 - Is pointer arithmetic performed safely and correctly?
45 - Are pointers properly initialized before use?
46 - Are const qualifiers used appropriately?
47 - Is pointer type casting done safely?
48
49 ### 3. Buffer Management and Bounds Checking
50 **What to Look For:**
51 - Prevention of buffer overflows and underflows
52 - Proper array bounds validation
53 - Safe string handling and manipulation
54 - Correct use of buffer size parameters
55
56 **Common Problems:**
57 - Buffer overruns and array bounds violations
58 - String operations without proper bounds checking
59 - Incorrect buffer size calculations
60 - Use of unsafe string functions (strcpy, sprintf)
61 - Missing null terminator handling
62
63 **Evaluation Questions:**
64 - Are all array accesses within proper bounds?
65 - Are string operations performed safely with bounds checking?
66 - Are buffer sizes validated before use?
67 - Are unsafe string functions avoided or used safely?
68 - Is proper null termination maintained?
69
70 ### 4. Resource Management and Cleanup
71 **What to Look For:**
72 - Proper resource acquisition and release
73 - Cleanup on all code paths including error conditions
74 - Appropriate use of RAII-like patterns in C
75 - Memory cleanup in error handling paths
76
77 **Common Problems:**
78 - Resource leaks on error paths
79 - Inconsistent cleanup patterns
80 - Missing cleanup in exception-like error handling
81 - Improper resource ordering in cleanup
82
83 **Evaluation Questions:**
84 - Are resources cleaned up on all code paths?
85 - Is cleanup performed in the correct order?
86 - Are error paths properly handled with cleanup?
87 - Is there consistent resource management throughout the code?
88 - Are cleanup functions idempotent and safe?
89
90 ## Memory Safety Criticism Process
91
92 ### Step 1: Memory Management Audit
93 1. **Track Allocations**: Identify all dynamic memory allocations
94 2. **Verify Pairing**: Ensure each allocation has exactly one deallocation
95 3. **Check Error Handling**: Verify allocation failures are handled
96 4. **Assess Cleanup**: Ensure cleanup occurs on all code paths
97
98 ### Step 2: Pointer Safety Assessment
99 1. **Null Pointer Analysis**: Check for proper null pointer validation
100 2. **Dangling Pointer Detection**: Identify use of freed memory
101 3. **Pointer Arithmetic Review**: Verify safe pointer operations
102 4. **Type Safety Validation**: Check for safe pointer type conversions
103
104 ### Step 3: Buffer Safety Evaluation
105 1. **Bounds Checking**: Verify all array accesses are within bounds
106 2. **String Safety**: Assess string operation safety
107 3. **Buffer Size Validation**: Check buffer size calculations
108 4. **Overflow Prevention**: Identify potential buffer overflow scenarios
109
110 ## Memory Safety Criticism Guidelines
111
112 ### Focus on Memory Safety Violations
113 **Good Criticism:**
114 - "This code has a memory leak - malloc() at line X has no corresponding free()"
115 - "Potential use-after-free: pointer 'p' is used after being freed at line Y"
116 - "Buffer overflow: array access at index Z exceeds allocated size"
117 - "Null pointer dereference: 'ptr' is dereferenced without null check"
118
119 **Poor Criticism:**
120 - "This looks like it might have memory issues"
121 - "Memory management seems problematic"
122 - "This could cause memory problems"
123
124 ### Emphasize Specific Evidence
125 **Good Criticism:**
126 - "Memory leak detected: malloc(100) at line 15, no free() in any code path"
127 - "Buffer overflow: strcpy(dest, src) at line 23, dest size unknown"
128 - "Use-after-free: pointer freed at line 45, used at line 52"
129
130 **Poor Criticism:**
131 - "This has memory problems"
132 - "Memory management is wrong"
133 - "This will cause crashes"
134
135 ## Memory Safety Problem Categories
136
137 ### Memory Leak Problems
138 - **Unmatched Allocation**: malloc() without corresponding free()
139 - **Lost References**: Pointers to allocated memory that become unreachable
140 - **Cleanup Omission**: Missing cleanup in error paths or exit conditions
141 - **Resource Leaks**: File handles, locks, or other resources not released
142
143 ### Use-After-Free Problems
144 - **Dangling Pointers**: Using pointers to freed memory
145 - **Double Free**: Calling free() on already freed memory
146 - **Stale References**: Using pointers after memory is reallocated
147 - **Invalid Pointer Arithmetic**: Arithmetic on freed memory
148
149 ### Buffer Overflow Problems
150 - **Stack Overflow**: Writing beyond stack-allocated buffer bounds
151 - **Heap Overflow**: Writing beyond heap-allocated buffer bounds
152 - **String Overflow**: String operations that exceed buffer capacity
153 - **Integer Overflow**: Buffer size calculations that overflow
154
155 ### Pointer Safety Problems
156 - **Null Pointer Dereference**: Dereferencing null pointers
157 - **Uninitialized Pointer Use**: Using pointers before initialization
158 - **Type Casting Issues**: Unsafe pointer type conversions
159 - **Pointer Arithmetic Errors**: Incorrect pointer arithmetic operations
160
161 ## Memory Safety Criticism Templates
162
163 ### For Memory Leak Issues
164 ```
165 Memory Leak Issue: [Specific memory leak]
166 Problem: [What causes the memory leak]
167 Impact: [Memory exhaustion, performance degradation, or resource waste]
168 Evidence: [Specific allocation and missing deallocation locations]
169 Recommendation: [Specific fix or cleanup strategy]
170 Priority: [Critical/High/Medium/Low]
171 ```
172
173 ### For Use-After-Free Issues
174 ```
175 Use-After-Free Issue: [Specific use-after-free problem]
176 Problem: [What makes this unsafe]
177 Impact: [Potential crashes, corruption, or security vulnerabilities]
178 Evidence: [Specific code paths showing free and subsequent use]
179 Recommendation: [Specific fix or alternative approach]
180 Priority: [Critical/High/Medium/Low]
181 ```
182
183 ### For Buffer Overflow Issues
184 ```
185 Buffer Overflow Issue: [Specific buffer overflow]
186 Problem: [What causes the buffer overflow]
187 Impact: [Potential crashes, corruption, or security vulnerabilities]
188 Evidence: [Specific code showing buffer access and size]
189 Recommendation: [Specific fix or bounds checking approach]
190 Priority: [Critical/High/Medium/Low]
191 ```
192
193 ## Memory Safety Evaluation Metrics
194
195 ### Quantitative Metrics
196 - **Memory Leak Count**: Number of unmatched allocations detected
197 - **Use-After-Free Count**: Number of potential use-after-free scenarios
198 - **Buffer Overflow Count**: Number of potential buffer overflow scenarios
199 - **Null Pointer Count**: Number of potential null pointer dereferences
200
201 ### Qualitative Metrics
202 - **Static Analysis Integration**: Integration with tools like Valgrind, AddressSanitizer
203 - **Memory Safety Coverage**: Percentage of memory operations analyzed
204 - **False Positive Rate**: Accuracy of memory safety issue detection
205 - **Tool Compatibility**: Ability to verify issues with existing tools
206
207 ## Memory Safety Criticism Checklist
208
209 ### Memory Management Assessment
210 - [ ] Are all memory allocations properly paired with deallocations?
211 - [ ] Are malloc() return values checked for NULL?
212 - [ ] Is memory deallocated in the correct order?
213 - [ ] Are allocation failures handled gracefully?
214 - [ ] Is cleanup performed on all code paths?
215
216 ### Pointer Safety Assessment
217 - [ ] Are all pointer dereferences safe and defined?
218 - [ ] Are pointers checked for NULL before dereferencing?
219 - [ ] Is pointer arithmetic performed safely and correctly?
220 - [ ] Are const and restrict qualifiers used appropriately?
221 - [ ] Are pointer type conversions done safely?
222
223 ### Buffer Safety Assessment
224 - [ ] Are all array accesses within proper bounds?
225 - [ ] Are string operations performed safely with bounds checking?
226 - [ ] Are buffer sizes validated before use?
227 - [ ] Are unsafe string functions avoided or used safely?
228 - [ ] Is proper null termination maintained?
229
230 ### Resource Management Assessment
231 - [ ] Are resources properly managed on all code paths?
232 - [ ] Is cleanup performed in the correct order?
233 - [ ] Are error paths properly handled with cleanup?
234 - [ ] Is there consistent resource management throughout?
235 - [ ] Are cleanup functions idempotent and safe?
236
237 ## Memory Safety Evaluation Questions
238
239 ### For Any C Code
240 1. **Is every malloc() paired with exactly one free()?**
241 2. **Are all array accesses within proper bounds?**
242 3. **Are pointers checked for NULL before dereferencing?**
243 4. **Is pointer arithmetic performed safely and correctly?**
244 5. **Are const and restrict qualifiers used appropriately?**
245
246 ### For Library Code
247 1. **Are all public interfaces documented with memory ownership rules?**
248 2. **Is thread safety clearly specified and implemented correctly?**
249 3. **Are all parameters validated appropriately?**
250 4. **Is the API design consistent with memory management conventions?**
251 5. **Are all resources properly managed by the library?**
252
253 ### For System Code
254 1. **Are all system calls checked for errors?**
255 2. **Is privilege escalation handled securely?**
256 3. **Are buffer sizes validated before use?**
257 4. **Is concurrency handled correctly?**
258 5. **Are all security implications considered and addressed?**
259
260 ## Error Handling and Fallback Strategies
261
262 ### When Memory Analysis is Incomplete
263 - **Strategy**: "Insufficient context for complete memory analysis, focus on observable issues"
264 - **Action**: Analyze only the provided code without making assumptions about missing parts
265 - **Fallback**: Identify potential issues that can be verified with additional context
266
267 ### When Static Analysis Tools are Unavailable
268 - **Strategy**: "Recommend static analysis tools for comprehensive memory safety verification"
269 - **Action**: Suggest tools like Valgrind, AddressSanitizer, or static analyzers
270 - **Fallback**: Focus on manual code review of obvious memory safety issues
271
272 ### When Memory Patterns are Complex
273 - **Strategy**: "Complex memory patterns detected, recommend simplified approaches"
274 - **Action**: Suggest simpler memory management patterns or RAII-like abstractions
275 - **Fallback**: Document assumptions and recommend verification with tools
276
277 ## Continuous Improvement Metrics
278
279 ### Performance Tracking
280 - **Memory Issue Detection Rate**: Track ability to identify memory safety problems
281 - **False Positive Rate**: Monitor incorrect memory safety accusations
282 - **Tool Integration Success**: Measure effectiveness of static analysis tool integration
283 - **Developer Feedback**: Collect feedback on memory safety criticism helpfulness
284
285 ### Improvement Areas
286 - **Static Analysis Integration**: Integration with memory safety analysis tools
287 - **Pattern Recognition**: Build database of common memory safety patterns
288 - **Tool Recommendations**: Develop recommendations for appropriate analysis tools
289 - **Expert Review**: Periodic review by memory safety experts