[clang] [compiler-rt] [UBSAN] add null and alignment checks for aggregates (PR #164548)

VASU SHARMA via cfe-commits cfe-commits at lists.llvm.org
Tue Oct 28 00:56:07 PDT 2025


================
@@ -2249,6 +2249,24 @@ void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty,
                                         bool isVolatile) {
   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
 
+  // Sanitizer checks to verify source and destination pointers are
+  // non-null and properly aligned before copying.
+  // Without these checks, undefined behavior from invalid pointers goes undetected.
+  if (SanOpts.hasOneOf(SanitizerKind::Null | SanitizerKind::Alignment)) {
+    Address SrcAddr = Src.getAddress();
+    Address DestAddr = Dest.getAddress();
+
+    // Check source pointer for null and alignment violations
+    EmitTypeCheck(TCK_Load, SourceLocation(),
----------------
vasu-the-sharma wrote:

Thanks for the suggestion @hubert-reinterpretcast 
I've reviewed the two `EmitCheckedLValue` usage sites in `CGExprAgg.cpp`:

Line 802 (`VisitCastExpr`): Uses `EmitCheckedLValue` with `TCK_Load` for dynamic_cast operations
Line 1313 (VisitBinAssign): Uses `EmitCheckedLValue` with `TCK_Store`, then calls `EmitCopy` which delegates to `EmitAggregateCopy`

Both cases are already covered:
`EmitCheckedLValue` performs type checking on the `LValue` expression itself
My changes to `EmitAggregateCopy` add sanitizer checks at the actual copy operation (the `memcpy` call)

These checks are complementary rather than redundant:
`EmitCheckedLValue`: Validates the expression evaluation produces a valid LValue
`EmitAggregateCopy`: Validates the source and destination pointers during the memory copy operation

The `EmitAggregateCopy` checks catch cases where pointers might become invalid between `LValue` emission and the actual copy (like array indexing or pointer arithmetic).
Do you see other specific cases in `EmitCheckedLValue` usage that would benefit from additional instrumentation?

https://github.com/llvm/llvm-project/pull/164548


More information about the cfe-commits mailing list