-fbounds-safety: Enforcing bounds safety for C
9 days ago
- #memory safety
- #C programming
- #compiler extensions
- -fbounds-safety is a C extension designed to enforce bounds safety and prevent out-of-bounds (OOB) memory accesses.
- The extension introduces bounds annotations (e.g., __counted_by, __sized_by, __ended_by) to attach bounds information to pointers.
- Compiler inserts bounds checks on pointer dereferences to ensure memory access remains within specified bounds.
- Reduces annotation burden by using implicit wide pointers (fat pointers) for local variables while preserving ABI compatibility.
- Supports incremental adoption, allowing partial implementation while still providing safety benefits.
- Ensures deterministic traps on bounds violations instead of undefined behavior.
- Includes annotations for single objects (__single), sentinel-delimited arrays (__null_terminated, __terminated_by), and interoperability with unsafe code (__unsafe_indexable).
- Default bounds annotations are applied based on ABI visibility (__single for ABI-visible pointers, __bidi_indexable for locals).
- Maintains correctness of bounds annotations through compile-time restrictions and run-time checks.
- Provides cast rules to prevent unsafe conversions between pointers with different bounds attributes.
- Includes portability mechanisms (e.g., toolchain header) for compatibility with non-supporting toolchains.
- Limitations include reliance on run-time checks and no guarantees for type safety beyond bounds violations.