[PATCH] D138945: [ModuleUtils][KCFI] Set !kcfi_type metadata for sanitizer constructors

Sami Tolvanen via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Tue Nov 29 13:07:03 PST 2022


samitolvanen created this revision.
Herald added a subscriber: hiraditya.
Herald added a project: All.
samitolvanen requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Set KCFI type metadata for the sanitizer constructors to prevent
runtime failures when these functions are indirectly called in
instrumented code. This fixes a compatibility issue with KASAN and
-fsanitize=kcfi in the Linux kernel.

Link: https://github.com/ClangBuiltLinux/linux/issues/1742


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138945

Files:
  llvm/lib/Transforms/Utils/ModuleUtils.cpp


Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp
===================================================================
--- llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -15,8 +15,10 @@
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/MDBuilder.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/xxhash.h"
 using namespace llvm;
 
 #define DEBUG_TYPE "moduleutils"
@@ -112,6 +114,19 @@
   appendToUsedList(M, "llvm.compiler.used", Values);
 }
 
+static void setKCFIType(Module &M, Function &F, StringRef MangledType) {
+  if (!M.getModuleFlag("kcfi"))
+    return;
+
+  LLVMContext &Ctx = M.getContext();
+  MDBuilder MDB(Ctx);
+  F.setMetadata(
+      LLVMContext::MD_kcfi_type,
+      MDNode::get(Ctx, MDB.createConstant(ConstantInt::get(
+                           Type::getInt32Ty(Ctx),
+                           static_cast<uint32_t>(xxHash64(MangledType))))));
+}
+
 FunctionCallee
 llvm::declareSanitizerInitFunction(Module &M, StringRef InitName,
                                    ArrayRef<Type *> InitArgTypes) {
@@ -128,6 +143,7 @@
       GlobalValue::InternalLinkage, M.getDataLayout().getProgramAddressSpace(),
       CtorName, &M);
   Ctor->addFnAttr(Attribute::NoUnwind);
+  setKCFIType(M, *Ctor, "_ZTSFvvE"); // void (*)(void)
   BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
   ReturnInst::Create(M.getContext(), CtorBB);
   // Ensure Ctor cannot be discarded, even if in a comdat.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D138945.478697.patch
Type: text/x-patch
Size: 1578 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20221129/4b7cc261/attachment.bin>


More information about the llvm-commits mailing list