[clang] [Clang][Sema] Add fortify warnings for realpath (PR #230695)
Venkatesh Srinivasan via cfe-commits
cfe-commits at lists.llvm.org
Thu Dec 3 14:48:18 PST 2026
================
@@ -1326,6 +1326,17 @@ class FortifiedBufferChecker {
const DiagnoseAsBuiltinAttr *DABAttr;
unsigned SizeTypeWidth;
};
+
+// Returns the target OS's fixed PATH_MAX value from <limits.h>, or std::nullopt
+// for targets where PATH_MAX is unbounded (e.g., Hurd) or unknown.
----------------
venk-ks wrote:
Agreed — the earlier round here already caught wrong values for Haiku and AIX, which reinforced how error-prone an 8-OS table is to verify. In `5fea558006b6`, I narrowed `getTargetPathMax` to just the two ABI-frozen targets (`Linux`: `4096` from UAPI `<linux/limits.h>`, `Darwin`: `1024` from XNU `<sys/syslimits.h>`) and added `clang/test/Sema/warn-fortify-source-realpath.c` covering every branch (`x86_64-unknown-linux-gnu`, `aarch64-linux-android`, `arm64-apple-macosx11.0`, plus unbounded `i686-unknown-gnu` and unlisted `x86_64-unknown-freebsd` expecting no diagnostics). Other platform maintainers can add their OS with verified values and tests if wanted.
For alternatives to hardcoding `PATH_MAX` here, I checked a few options and each has trade-offs:
- **Reading `PATH_MAX` via `Preprocessor`:** POSIX doesn't require `<stdlib.h>` to define `PATH_MAX` (glibc `<stdlib.h>` doesn't, even with `_GNU_SOURCE`, and glibc's own `bits/stdlib.h` fortify wrapper has to gate on `#if defined _LIBC_LIMITS_H_ && defined PATH_MAX`). Callers who hardcode a small buffer (`char buf[128]; realpath(p, buf);`) are the most likely to omit `<limits.h>`, so macro lookup would miss those cases; it also doesn't cross C++20 named modules, would need expression evaluation/guarding against user `#define`/`#undef`, and has no precedent in `Sema`.
- **`_POSIX_PATH_MAX` (`256`):** Reporting "at least 256 bytes are required" on Linux/Darwin would mislead users into resizing to 256, which can still overflow.
- **`TargetInfo` hook:** Just relocates the same two constants to `TargetInfo`/`OSTargets.h` for a single caller (happy to move it there if another consumer emerges, e.g. `StdLibraryFunctionsChecker`).
- **Header annotations (`[static PATH_MAX]` / `diagnose_if`):** `[static N]` rejects valid null pointers (`-Wnonnull`), and `diagnose_if` requires `-D_FORTIFY_SOURCE` + `<limits.h>`, which #142230 is trying to move into Clang.
If you'd still rather avoid duplicating even Linux/Darwin `PATH_MAX` in Clang, the main fallbacks would be (1) reading `PATH_MAX` from `Preprocessor` when defined in a system header (accepting the `<stdlib.h>`-only blind spot), or (2) leaving `realpath` checks to libc headers via `diagnose_if`. Let me know what you prefer.
https://github.com/llvm/llvm-project/pull/230695
More information about the cfe-commits
mailing list