Safer C arrays in the Linux kernel
Summary
Kees Cook describes converting fake flexible C arrays into unambiguous structures with checkable bounds. Real flexible array members use empty brackets at the end of the structure. GCC and Clang support -fstrict-flex-arrays.
Ideas
- Historical zero- and one-element arrays ambiguously simulate dynamic structure ends.
- Real C99 flexible arrays express the developer's intent unambiguously.
-fstrict-flex-arraysseparates dynamic and genuinely fixed trailing fields.- Compiler warnings can thus detect accesses outside fixed arrays.
- Counted-by annotations will in future link dynamic arrays with their element count.
Insights
- Security tools need unambiguous source code before they can check bounds reliably.
- Legacy conventions block compiler hardening far beyond their original purpose.
- Type precision partly turns run-time attacks into build errors.
Facts
DECLARE_FLEX_ARRAY()encapsulates flexible arrays within unions.
Recommendations
- Gradually replace zero- and one-element placeholders with real flexible arrays.
- Only enable strict array diagnostics together with a complete clean-up of the old forms.
References
Links to the original source and the Web Archive open in a new tab.