================
@@ -5062,7 +5063,29 @@ Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
     divisor = CGF.CGM.getSize(elementSize);
   }
 
-  if (CGF.getLangOpts().StablePointerSubtraction)
+  // If the pointer-subtraction sanitizer is on, verify at runtime that the
+  // byte distance is an exact multiple of the element size. Zero-sized element
+  // types (a GNU extension) have no meaningful multiple, so don't emit a
+  // remainder by zero for them.
+  bool CheckSubtraction = CGF.SanOpts.has(SanitizerKind::PointerSubtraction);
+  auto *ConstDivisor = dyn_cast<llvm::ConstantInt>(divisor);
+  if (CheckSubtraction && !(ConstDivisor && ConstDivisor->isZero())) {
+    auto CheckOrdinal = SanitizerKind::SO_PointerSubtraction;
+    auto CheckHandler = SanitizerHandler::PointerSubtraction;
+    SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler);
+
+    llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
+    llvm::Value *Rem = Builder.CreateSRem(diffInChars, divisor, "sub.ptr.rem");
+    llvm::Value *IsExact = Builder.CreateICmpEQ(Rem, Zero, "sub.ptr.exact");
+
+    llvm::Constant *StaticArgs[] = {
+        CGF.EmitCheckSourceLocation(op.E->getExprLoc())};
+    llvm::Value *DynamicArgs[] = {diffInChars, divisor};
+    CGF.EmitCheck({{IsExact, CheckOrdinal}}, CheckHandler, StaticArgs,
+                  DynamicArgs);
+  }
+
+  if (CGF.getLangOpts().StablePointerSubtraction || CheckSubtraction)
----------------
kuroyukiasuna wrote:

Makes sense. Only recover mode needs it: the handler returns, and with `exact` 
the quotient is poison after the report. In trap and abort modes the check 
guarantees exactness, so the division is `exact` there again.

https://github.com/llvm/llvm-project/pull/210635
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to