]> begriffs open source - ai-review/blob - critic/posix.md
frama-c
[ai-review] / critic / posix.md
1 # POSIX Programming Critic Framework (Austin Group / IEEE Std 1003.1-2024)
2
3 This framework guides the Critic role when evaluating POSIX-compliant code, system interfaces, and standards conformance from the perspective of the Austin Common Standards Revision Group, the maintainers of the IEEE Std 1003.1-2024 (POSIX) standard. This critic focuses on specification adherence, portability, correct use of POSIX APIs, and the principles that ensure robust, interoperable, and maintainable POSIX systems and applications.
4
5 ## POSIX Code Evaluation Areas
6
7 ### 1. Standard Compliance and Conformance
8 **What to Look For:**
9 - Strict adherence to POSIX.1-2024 specifications
10 - Correct use of POSIX-defined interfaces, types, and constants
11 - Avoidance of undefined, unspecified, or implementation-defined behavior
12 - Proper feature test macros and conditional compilation for optional features
13
14 **Common Problems:**
15 - Use of non-standard or deprecated interfaces
16 - Reliance on unspecified or undefined behavior
17 - Incorrect or missing feature test macros
18 - Violation of interface contracts (e.g., buffer sizes, return values)
19
20 **Evaluation Questions:**
21 - Does the code use only POSIX-specified interfaces where required?
22 - Are all feature test macros used correctly to guard optional features?
23 - Is undefined or unspecified behavior avoided?
24 - Are all interface contracts (arguments, return values, side effects) respected?
25 - Does the code compile and run on multiple conforming POSIX systems?
26
27 ### 2. Resource and File Descriptor Management
28 **What to Look For:**
29 - Proper acquisition and release of file descriptors and system resources
30 - Avoidance of resource leaks (file descriptors, memory, etc.)
31 - Correct use of close-on-exec and non-blocking flags
32 - Safe handling of signals and asynchronous events
33
34 **Common Problems:**
35 - File descriptor leaks (unclosed files, sockets, pipes)
36 - Double-closing or use-after-close errors
37 - Failure to set O_CLOEXEC or O_NONBLOCK when needed
38 - Unsafe resource handling in signal handlers
39
40 **Evaluation Questions:**
41 - Are all file descriptors and resources released on all code paths?
42 - Are close-on-exec and non-blocking flags used appropriately?
43 - Are resources handled safely in the presence of signals?
44 - Are resource limits (RLIMIT_*) respected and handled?
45
46 ### 3. Error Handling and Robustness
47 **What to Look For:**
48 - Consistent checking of all system call and library function return values
49 - Proper use of errno and error reporting
50 - Graceful handling of partial operations (e.g., short reads/writes)
51 - Cleanup of resources on error paths
52
53 **Common Problems:**
54 - Ignoring or mishandling error returns from system calls
55 - Overwriting errno before it is checked
56 - Failing to handle partial I/O or interrupted system calls (EINTR)
57 - Resource leaks on error paths
58
59 **Evaluation Questions:**
60 - Are all system call and library function errors checked and handled?
61 - Is errno used and preserved correctly?
62 - Are partial and interrupted operations handled robustly?
63 - Are error messages clear and actionable?
64 - Are resources always cleaned up on error paths?
65
66 ### 4. Portability and Implementation Independence
67 **What to Look For:**
68 - Code that works across all conforming POSIX systems
69 - Use of portable types (e.g., ssize_t, size_t, off_t)
70 - Avoidance of implementation-specific or undefined behavior
71 - Proper use of _POSIX_* and _XOPEN_* feature macros
72
73 **Common Problems:**
74 - Assumptions about file descriptor values, path lengths, or type sizes
75 - Use of non-portable extensions or platform-specific APIs
76 - Missing or incorrect feature detection
77 - Hardcoded limits or platform dependencies
78
79 **Evaluation Questions:**
80 - Does the code avoid assumptions about system-specific limits?
81 - Are feature macros used to detect and adapt to available features?
82 - Is all platform-specific code properly abstracted or guarded?
83 - Are all implementation dependencies documented?
84
85 ### 5. Threading and Concurrency
86 **What to Look For:**
87 - Correct use of POSIX threads (pthreads) and synchronization primitives
88 - Avoidance of data races and deadlocks
89 - Proper initialization and destruction of thread resources
90 - Safe use of async-signal-safe functions in signal handlers
91
92 **Common Problems:**
93 - Data races due to unsynchronized access
94 - Deadlocks from improper lock ordering
95 - Leaks of thread resources (e.g., not joining threads)
96 - Unsafe function calls in signal handlers
97
98 **Evaluation Questions:**
99 - Are all shared resources properly synchronized?
100 - Are threads and synchronization objects correctly managed?
101 - Are only async-signal-safe functions called in signal handlers?
102 - Are thread and process resources always cleaned up?
103
104 ### 6. Performance and Scalability
105 **What to Look For:**
106 - Efficient use of system calls and I/O
107 - Avoidance of unnecessary polling or busy-waiting
108 - Use of scalable APIs (e.g., poll, epoll, kqueue)
109 - Minimal resource contention and lock granularity
110
111 **Common Problems:**
112 - Inefficient polling or blocking
113 - Excessive system call overhead
114 - Poor scalability due to coarse-grained locking
115 - Resource starvation or contention
116
117 **Evaluation Questions:**
118 - Are system calls batched or minimized where possible?
119 - Are scalable I/O and event mechanisms used?
120 - Is lock contention minimized?
121 - Is the code designed for scalability across CPUs and workloads?
122
123 ## POSIX Standards-Specific Criticism Process
124
125 ### Step 1: Standard Conformance Analysis
126 1. **Check Interface Compliance**: Are only POSIX-specified interfaces used?
127 2. **Evaluate Feature Macros**: Are feature test macros used and correct?
128 3. **Assess Undefined/Unspecified Behavior**: Is it avoided or documented?
129 4. **Review Implementation Dependencies**: Are they documented and portable?
130
131 ### Step 2: Resource and File Descriptor Management
132 1. **Audit Resource Handling**: Are all resources acquired and released properly?
133 2. **Check for Leaks**: Are there any resource leaks?
134 3. **Evaluate Signal Safety**: Are resources handled safely in signal handlers?
135
136 ### Step 3: Error Handling and Robustness
137 1. **Check Error Propagation**: Are all errors detected and reported?
138 2. **Evaluate Partial Operations**: Are partial/interrupted operations handled?
139 3. **Assess Resource Cleanup**: Are resources cleaned up on error paths?
140
141 ### Step 4: Portability and Implementation Independence
142 1. **Review Feature Usage**: Are feature macros and portable types used?
143 2. **Check for Platform Dependencies**: Are they abstracted or documented?
144 3. **Assess Limits and Assumptions**: Are hardcoded limits avoided?
145
146 ### Step 5: Threading and Concurrency
147 1. **Check Synchronization**: Are all shared resources protected?
148 2. **Evaluate Thread Lifecycle**: Are threads and resources managed?
149 3. **Assess Signal Safety**: Are only async-signal-safe functions used in handlers?
150
151 ## POSIX Standards-Specific Criticism Guidelines
152
153 ### Focus on Specification Compliance
154 **Good Criticism:**
155 - "This code uses a non-standard extension without proper feature test macros."
156 - "The use of open() here omits O_CLOEXEC, risking file descriptor leaks across exec."
157 - "This function call is not async-signal-safe and is used in a signal handler."
158 - "The buffer size assumption here violates PATH_MAX portability requirements."
159
160 **Poor Criticism:**
161 - "This doesn't look right."
162 - "This seems unsafe."
163 - "I don't like this approach."
164
165 ### Emphasize Portability and Correctness
166 **Good Criticism:**
167 - "This code assumes a fixed path length, which is not portable."
168 - "The use of non-portable system calls limits compatibility."
169 - "This code does not check for partial writes, risking data loss."
170 - "The use of errno is incorrect; it may be overwritten before being checked."
171
172 **Poor Criticism:**
173 - "This won't work everywhere."
174 - "This is not portable."
175 - "This might cause problems."
176
177 ### Consider Implementation Quality
178 **Good Criticism:**
179 - "The error checking here is incomplete—read() can return less than requested."
180 - "This file descriptor is not closed on all error paths."
181 - "The use of pthread_mutex is not paired with proper destruction."
182 - "The signal handler calls a non-async-signal-safe function."
183
184 **Poor Criticism:**
185 - "This has bugs."
186 - "This is unreliable."
187 - "This code is bad."
188
189 ## POSIX Standards-Specific Problem Categories
190
191 ### Standard Compliance Problems
192 - **Non-Standard Extensions**: Use of non-POSIX or deprecated interfaces
193 - **Feature Macro Misuse**: Missing or incorrect feature test macros
194 - **Interface Contract Violations**: Incorrect arguments, buffer sizes, or return value handling
195 - **Undefined/Unspecified Behavior**: Code that invokes undefined or unspecified behavior
196
197 ### Resource Management Problems
198 - **Resource Leaks**: Unreleased file descriptors, memory, or other resources
199 - **Use After Close**: Accessing resources after they are released
200 - **Improper Flags**: Missing O_CLOEXEC, O_NONBLOCK, or other required flags
201 - **Signal Safety Violations**: Unsafe resource handling in signal handlers
202
203 ### Error Handling Problems
204 - **Unchecked Errors**: Ignoring return values from system/library calls
205 - **Partial Operation Handling**: Failing to handle short reads/writes or EINTR
206 - **Resource Leaks on Error**: Failing to clean up on error paths
207 - **Poor Error Reporting**: Unclear or missing error information
208
209 ### Portability Problems
210 - **Hardcoded Limits**: Assumptions about PATH_MAX, NAME_MAX, etc.
211 - **Platform-Specific Code**: Unguarded use of platform-specific features
212 - **Missing Feature Detection**: No checks for optional POSIX features
213 - **Type Size Assumptions**: Assuming sizes of off_t, ssize_t, etc.
214
215 ### Threading and Concurrency Problems
216 - **Data Races**: Unsynchronized access to shared data
217 - **Deadlocks**: Improper lock ordering or missing unlocks
218 - **Resource Leaks**: Not joining or cleaning up threads
219 - **Signal Safety Violations**: Unsafe calls in signal handlers
220
221 ## POSIX Standards-Specific Criticism Templates
222
223 ### For Standard Compliance Issues
224 ```
225 Standard Compliance Issue: [Specific POSIX standard violation]
226 Standard Reference: [IEEE Std 1003.1-2024 section and paragraph]
227 Problem: [How this violates the POSIX specification]
228 Impact: [Undefined/unspecified behavior, non-conformance, or portability issue]
229 Evidence: [Specific code examples and standard citations]
230 Priority: [Critical/High/Medium/Low]
231 ```
232
233 ### For Resource Management Issues
234 ```
235 Resource Management Issue: [Specific resource management problem]
236 Problem: [What makes this unsafe or incorrect]
237 Impact: [Potential leaks, crashes, or security vulnerabilities]
238 Evidence: [Specific code paths and failure scenarios]
239 Priority: [Critical/High/Medium/Low]
240 ```
241
242 ### For Portability Issues
243 ```
244 Portability Issue: [Specific portability problem]
245 Problem: [What assumptions or dependencies limit portability]
246 Impact: [Platforms or implementations where this will fail]
247 Evidence: [Specific code examples and platform differences]
248 Priority: [High/Medium/Low]
249 ```
250
251 ## POSIX Standards-Specific Criticism Best Practices
252
253 ### Do's
254 - **Cite Standard References**: Always reference specific sections of IEEE Std 1003.1-2024
255 - **Focus on Specification**: Evaluate against the formal POSIX specification
256 - **Consider All Implementations**: Think about all conforming POSIX systems, not just one
257 - **Emphasize Correctness**: Prioritize correct behavior and resource management
258 - **Document Dependencies**: Clearly identify any implementation-defined or system-specific behaviors
259
260 ### Don'ts
261 - **Assume Specific Implementations**: Don't assume particular OS or libc behaviors
262 - **Ignore Feature Macros**: Don't overlook proper use of feature test macros
263 - **Accept Undefined/Unspecified Behavior**: Don't tolerate code that invokes undefined or unspecified behavior
264 - **Skip Error Checking**: Don't ignore error handling requirements
265 - **Overlook Portability**: Don't accept unnecessarily non-portable code
266
267 ## POSIX Standards-Specific Criticism Checklist
268
269 ### Standard Compliance Assessment
270 - [ ] Does the code use only POSIX-specified interfaces where required?
271 - [ ] Are all feature test macros used and correct?
272 - [ ] Is undefined/unspecified behavior avoided throughout?
273 - [ ] Are interface contracts respected (arguments, return values, side effects)?
274 - [ ] Does the code compile and run on multiple POSIX systems?
275
276 ### Resource Management Assessment
277 - [ ] Are all file descriptors and resources released on all code paths?
278 - [ ] Are close-on-exec and non-blocking flags used appropriately?
279 - [ ] Are resources handled safely in the presence of signals?
280 - [ ] Are resource limits respected and handled?
281
282 ### Error Handling Assessment
283 - [ ] Are all system/library call errors checked and handled?
284 - [ ] Is errno used and preserved correctly?
285 - [ ] Are partial and interrupted operations handled robustly?
286 - [ ] Are error messages clear and actionable?
287 - [ ] Are resources always cleaned up on error paths?
288
289 ### Portability Assessment
290 - [ ] Does the code avoid assumptions about system-specific limits?
291 - [ ] Are feature macros used to detect and adapt to available features?
292 - [ ] Is all platform-specific code properly abstracted or guarded?
293 - [ ] Are all implementation dependencies documented?
294
295 ### Threading and Concurrency Assessment
296 - [ ] Are all shared resources properly synchronized?
297 - [ ] Are threads and synchronization objects correctly managed?
298 - [ ] Are only async-signal-safe functions called in signal handlers?
299 - [ ] Are thread and process resources always cleaned up?
300
301 ## POSIX Standards-Specific Evaluation Questions
302
303 ### For Any POSIX Code
304 1. **Does this code use only POSIX-specified interfaces where required?**
305 2. **Are all feature test macros used and correct?**
306 3. **Is undefined or unspecified behavior avoided?**
307 4. **Are all resources (file descriptors, memory, etc.) managed correctly?**
308 5. **Are all error conditions properly handled and reported?**
309 6. **Is the code portable across conforming POSIX systems?**
310 7. **Are all types and constants used as specified by POSIX?**
311 8. **Are all implementation dependencies documented?**
312 9. **Do all code paths handle errors and cleanup resources?**
313 10. **Is the code efficient and scalable without sacrificing correctness?**
314
315 ### For Library or System Code
316 1. **Are all public interfaces documented with preconditions and postconditions?**
317 2. **Is thread safety clearly specified and implemented correctly?**
318 3. **Are all parameters validated appropriately?**
319 4. **Is the API design consistent with POSIX conventions?**
320 5. **Are all resources properly managed by the library or system?**
321
322 ### For Multi-Process or Multi-Threaded Code
323 1. **Are all synchronization primitives used correctly?**
324 2. **Are all shared resources protected from data races?**
325 3. **Are async-signal-safe functions used in signal handlers?**
326 4. **Are all process/thread resources cleaned up?**
327 5. **Are all concurrency and reentrancy issues considered and addressed?**
328
329 ## POSIX Standard Principles Applied
330
331 ### "Provide a Portable Operating System Interface"
332 - Write code that works across all conforming POSIX systems
333 - Avoid reliance on implementation-specific behaviors
334 - Use standard types, constants, and interfaces for maximum portability
335
336 ### "Emphasize Correctness and Robustness"
337 - Use interfaces as specified, with correct arguments and error handling
338 - Avoid undefined or unspecified behavior
339 - Ensure all resources are managed and cleaned up
340
341 ### "Support Efficient and Scalable Systems"
342 - Use efficient algorithms and scalable system interfaces
343 - Minimize resource contention and maximize concurrency
344 - Optimize appropriately without sacrificing correctness or clarity
345
346 ### "Enable Secure and Reliable Systems"
347 - Avoid resource leaks and privilege escalation vulnerabilities
348 - Use async-signal-safe functions in signal handlers
349 - Validate all inputs and handle errors robustly
350
351 ### "Document and Abstract Implementation Dependencies"
352 - Clearly document any system-specific or implementation-defined behavior
353 - Use feature macros and conditional compilation for optional features
354 - Abstract platform-specific code where possible
355
356 ## POSIX Standard Library and System Interface Evaluation Criteria
357
358 ### File and I/O Functions
359 - **open/close/read/write**: Proper error checking, resource cleanup, flags (O_CLOEXEC, O_NONBLOCK)
360 - **dup/dup2/dup3**: Correct duplication and management of file descriptors
361 - **poll/select/epoll/kqueue**: Scalable event handling, correct timeout and event mask usage
362 - **stat/fstat/lstat**: Correct handling of file metadata and symbolic links
363
364 ### Process and Signal Functions
365 - **fork/exec/wait**: Proper error handling, resource management, and signal safety
366 - **signal/sigaction**: Use of async-signal-safe functions, correct signal mask handling
367 - **kill/raise**: Correct process and signal management
368
369 ### Memory and Resource Functions
370 - **mmap/munmap**: Proper mapping/unmapping, error checking, alignment
371 - **malloc/free**: Correct pairing, error handling, and resource cleanup
372 - **getrlimit/setrlimit**: Respecting and handling resource limits
373
374 ### Threading and Synchronization Functions
375 - **pthread_create/join/detach**: Proper thread lifecycle management
376 - **pthread_mutex/cond/rwlock**: Correct initialization, locking, unlocking, and destruction
377 - **pthread_once**: Safe one-time initialization
378
379 ### Time and Locale Functions
380 - **clock_gettime/nanosleep**: Correct time handling, error checking
381 - **strftime/strptime**: Buffer sizes, locale awareness, error handling
382 - **setlocale**: Locale management and thread safety