50 #define DEBUG_TYPE "hwasan" 56 "__hwasan_shadow_memory_dynamic_address";
67 "hwasan-memory-access-callback-prefix",
73 cl::desc(
"instrument reads and writes with callbacks"),
77 cl::desc(
"instrument read instructions"),
81 "hwasan-instrument-writes",
cl::desc(
"instrument write instructions"),
85 "hwasan-instrument-atomics",
91 cl::desc(
"Enable recovery mode (continue-after-error)."),
95 cl::desc(
"instrument stack (allocas)"),
99 "hwasan-uar-retag-to-zero",
100 cl::desc(
"Clear alloca tags before returning from the function to allow " 101 "non-instrumented and instrumented function calls mix. When set " 102 "to false, allocas are retagged before returning from the " 103 "function to detect use after return."),
107 "hwasan-generate-tags-with-calls",
112 "hwasan-match-all-tag",
113 cl::desc(
"don't report bad accesses via pointers with this tag"),
118 cl::desc(
"Enable KernelHWAddressSanitizer instrumentation"),
126 "hwasan-mapping-offset",
139 explicit HWAddressSanitizer(
bool CompileKernel =
false,
bool Recover =
false)
146 StringRef getPassName()
const override {
return "HWAddressSanitizer"; }
149 bool doInitialization(
Module &M)
override;
151 void initializeCallbacks(
Module &M);
153 void maybeInsertDynamicShadowAtFunctionEntry(
Function &
F);
157 void instrumentMemAccessInline(
Value *PtrLong,
bool IsWrite,
158 unsigned AccessSizeIndex,
162 uint64_t *TypeSize,
unsigned *Alignment,
165 bool isInterestingAlloca(
const AllocaInst &AI);
186 struct ShadowMapping {
192 unsigned getAllocaAlignment()
const {
return 1U << Scale; }
194 ShadowMapping Mapping;
205 Function *HwasanMemoryAccessCallbackSized[2];
212 Value *LocalDynamicShadow =
nullptr;
220 HWAddressSanitizer,
"hwasan",
221 "HWAddressSanitizer: detect memory bugs using tagged addressing.",
false,
225 "HWAddressSanitizer: detect memory bugs using tagged addressing.",
false,
230 assert(!CompileKernel || Recover);
231 return new HWAddressSanitizer(CompileKernel, Recover);
237 bool HWAddressSanitizer::doInitialization(
Module &M) {
243 Mapping.init(TargetTriple);
250 HwasanCtorFunction =
nullptr;
251 if (!CompileKernel) {
252 std::tie(HwasanCtorFunction, std::ignore) =
262 void HWAddressSanitizer::initializeCallbacks(
Module &M) {
264 for (
size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
265 const std::string TypeStr = AccessIsWrite ?
"store" :
"load";
266 const std::string EndingStr = Recover ?
"_noabort" :
"";
268 HwasanMemoryAccessCallbackSized[AccessIsWrite] =
275 HwasanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
278 itostr(1ULL << AccessSizeIndex) + EndingStr,
284 "__hwasan_tag_memory", IRB.
getVoidTy(), IntptrTy, Int8Ty, IntptrTy));
288 if (Mapping.InGlobal)
293 void HWAddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(
Function &
F) {
299 if (Mapping.InGlobal) {
306 LocalDynamicShadow = IRB.CreateCall(Asm, {ShadowGlobal},
".hwasan.shadow");
309 kHwasanShadowMemoryDynamicAddress, IntptrTy);
310 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
323 if (LocalDynamicShadow == I)
326 Value *PtrOperand =
nullptr;
328 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
332 *Alignment = LI->getAlignment();
333 PtrOperand = LI->getPointerOperand();
334 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(I)) {
338 *Alignment =
SI->getAlignment();
339 PtrOperand =
SI->getPointerOperand();
340 }
else if (
AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
345 PtrOperand = RMW->getPointerOperand();
351 PtrOperand = XCHG->getPointerOperand();
373 if (
LoadInst *LI = dyn_cast<LoadInst>(I))
374 return LI->getPointerOperandIndex();
376 return SI->getPointerOperandIndex();
378 return RMW->getPointerOperandIndex();
380 return XCHG->getPointerOperandIndex();
392 if (TargetTriple.isAArch64())
405 if (Mapping.Offset == 0)
409 if (LocalDynamicShadow)
410 ShadowBase = LocalDynamicShadow;
413 return IRB.
CreateAdd(Shadow, ShadowBase);
416 void HWAddressSanitizer::instrumentMemAccessInline(
Value *PtrLong,
bool IsWrite,
417 unsigned AccessSizeIndex,
422 Value *AddrLong = untagPointer(IRB, PtrLong);
423 Value *ShadowLong = memToShadow(AddrLong, PtrLong->
getType(), IRB);
430 if (matchAllTag != -1) {
433 TagMismatch = IRB.
CreateAnd(TagMismatch, TagNotIgnored);
441 const int64_t AccessInfo = Recover * 0x20 + IsWrite * 0x10 + AccessSizeIndex;
443 switch (TargetTriple.getArch()) {
448 "int3\nnopl " +
itostr(0x40 + AccessInfo) +
"(%rax)",
457 "brk #" +
itostr(0x900 + AccessInfo),
467 bool HWAddressSanitizer::instrumentMemAccess(
Instruction *I) {
469 bool IsWrite =
false;
470 unsigned Alignment = 0;
471 uint64_t TypeSize = 0;
472 Value *MaybeMask =
nullptr;
474 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
486 (Alignment >= (1UL << Mapping.Scale) || Alignment == 0 ||
487 Alignment >= TypeSize / 8)) {
490 IRB.
CreateCall(HwasanMemoryAccessCallback[IsWrite][AccessSizeIndex],
493 instrumentMemAccessInline(AddrLong, IsWrite, AccessSizeIndex, I);
496 IRB.
CreateCall(HwasanMemoryAccessCallbackSized[IsWrite],
499 untagPointerOperand(I, Addr);
505 uint64_t ArraySize = 1;
508 assert(CI &&
"non-constant array size");
513 return SizeInBytes * ArraySize;
519 ~(Mapping.getAllocaAlignment() - 1);
527 size_t ShadowSize = Size >> Mapping.Scale;
547 static unsigned FastMasks[] = {
548 0, 1, 2, 3, 4, 6, 7, 8, 12, 14, 15, 16, 24,
549 28, 30, 31, 32, 48, 56, 60, 62, 63, 64, 96, 112, 120,
550 124, 126, 127, 128, 192, 224, 240, 248, 252, 254};
551 return FastMasks[AllocaNo % (
sizeof(FastMasks) /
sizeof(FastMasks[0]))];
564 auto GetStackPointerFn =
575 "hwasan.stack.base.tag");
582 return getNextTagWithCall(IRB);
591 return getNextTagWithCall(IRB);
598 Value *TaggedPtrLong;
604 TaggedPtrLong = IRB.
CreateAnd(PtrLong, ShiftedTag);
608 TaggedPtrLong = IRB.
CreateOr(PtrLong, ShiftedTag);
615 Value *UntaggedPtrLong;
618 UntaggedPtrLong = IRB.
CreateOr(PtrLong,
625 return UntaggedPtrLong;
628 bool HWAddressSanitizer::instrumentStack(
631 Function *F = Allocas[0]->getParent()->getParent();
635 Value *StackTag = getStackBaseTag(IRB);
642 for (
unsigned N = 0;
N < Allocas.
size(); ++
N) {
643 auto *AI = Allocas[
N];
647 Value *Tag = getAllocaTag(IRB, StackTag, AI,
N);
652 Replacement->
setName(Name +
".hwasan");
660 tagAlloca(IRB, AI, Tag);
662 for (
auto RI : RetVec) {
666 Value *Tag = getUARTag(IRB, StackTag);
667 tagAlloca(IRB, AI, Tag);
674 bool HWAddressSanitizer::isInterestingAlloca(
const AllocaInst &AI) {
691 if (&F == HwasanCtorFunction)
701 assert(!LocalDynamicShadow);
702 maybeInsertDynamicShadowAtFunctionEntry(F);
704 bool Changed =
false;
709 for (
auto &Inst : BB) {
711 if (
AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
717 if (isInterestingAlloca(*AI))
722 if (isa<ReturnInst>(Inst) || isa<ResumeInst>(Inst) ||
723 isa<CleanupReturnInst>(Inst))
726 Value *MaybeMask =
nullptr;
730 Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
731 &Alignment, &MaybeMask);
732 if (Addr || isa<MemIntrinsic>(Inst))
737 if (!AllocasToInstrument.
empty())
738 Changed |= instrumentStack(AllocasToInstrument, RetVec);
740 for (
auto Inst : ToInstrument)
741 Changed |= instrumentMemAccess(Inst);
743 LocalDynamicShadow =
nullptr;
749 const bool IsAndroid = TargetTriple.
isAndroid();
750 const bool IsAndroidWithIfuncSupport =
762 InGlobal = IsAndroidWithIfuncSupport;
static cl::opt< int > ClMatchAllTag("hwasan-match-all-tag", cl::desc("don't report bad accesses via pointers with this tag"), cl::Hidden, cl::init(-1))
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Function * checkSanitizerInterfaceFunction(Constant *FuncOrBitcast)
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Compute iterated dominance frontiers using a linear time algorithm.
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
A Module instance is used to store all the information related to an LLVM module. ...
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
void setAlignment(unsigned Align)
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
static cl::opt< bool > ClRecover("hwasan-recover", cl::desc("Enable recovery mode (continue-after-error)."), cl::Hidden, cl::init(false))
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
StringRef getName() const
Get a short "name" for the module.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memset to the specified pointer and the specified value.
An instruction for reading from memory.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
static const char *const kHwasanInitName
static unsigned getPointerOperandIndex(Instruction *I)
static const size_t kDefaultShadowScale
bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
static const char *const kHwasanShadowMemoryDynamicAddress
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
LLVMContext & getContext() const
Get the global data context.
static cl::opt< bool > ClInstrumentWrites("hwasan-instrument-writes", cl::desc("instrument write instructions"), cl::Hidden, cl::init(true))
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
IntegerType * getIntPtrTy(const DataLayout &DL, unsigned AddrSpace=0)
Fetch the type representing a pointer to an integer value.
This file contains the simple types necessary to represent the attributes associated with functions a...
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void setName(const Twine &Name)
Change the name of the value.
Type * getVoidTy()
Fetch the type representing void.
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Type * getType() const
All values are typed, get the type of this value.
std::string itostr(int64_t X)
bool isSwiftError() const
Return true if this value is a swifterror value.
BasicBlock * GetInsertBlock() const
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static const unsigned kPointerTagShift
An instruction for storing to memory.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
static cl::opt< bool > ClInstrumentStack("hwasan-instrument-stack", cl::desc("instrument stack (allocas)"), cl::Hidden, cl::init(true))
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
const BasicBlock & getEntryBlock() const
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of converting the string to 'bool' fo...
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Subclasses of this class are all able to terminate a basic block.
std::size_t countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
The instances of the Type class are immutable: once they are created, they are never changed...
std::pair< Function *, Function * > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type *> InitArgTypes, ArrayRef< Value *> InitArgs, StringRef VersionCheckName=StringRef())
Creates sanitizer constructor function, and calls sanitizer's init function from it.
This is an important class for using LLVM in a threaded context.
Constant * getOrInsertGlobal(StringRef Name, Type *Ty)
Look up the specified global in the module symbol table.
static cl::opt< std::string > ClMemoryAccessCallbackPrefix("hwasan-memory-access-callback-prefix", cl::desc("Prefix for memory access callbacks"), cl::Hidden, cl::init("__hwasan_"))
This is an important base class in LLVM.
INITIALIZE_PASS_BEGIN(HWAddressSanitizer, "hwasan", "HWAddressSanitizer: detect memory bugs using tagged addressing.", false, false) INITIALIZE_PASS_END(HWAddressSanitizer
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
static cl::opt< bool > ClGenerateTagsWithCalls("hwasan-generate-tags-with-calls", cl::desc("generate new tags with runtime library calls"), cl::Hidden, cl::init(false))
static const size_t kNumberOfAccessSizes
static cl::opt< bool > ClInstrumentAtomics("hwasan-instrument-atomics", cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden, cl::init(true))
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
bool isAndroidVersionLT(unsigned Major) const
FunctionPass class - This class is used to implement most global optimizations.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
const Value * getArraySize() const
Get the number of elements allocated.
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Triple - Helper class for working with autoconf configuration names.
This is the shared class of boolean and integer constants.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
TerminatorInst * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
static size_t TypeSizeToSizeIndex(uint32_t TypeSize)
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
static cl::opt< bool > ClEnableKhwasan("hwasan-kernel", cl::desc("Enable KernelHWAddressSanitizer instrumentation"), cl::Hidden, cl::init(false))
LLVM_NODISCARD bool empty() const
static const uint64_t kDynamicShadowSentinel
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
static unsigned RetagMask(unsigned AllocaNo)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
static cl::opt< bool > ClInstrumentWithCalls("hwasan-instrument-with-calls", cl::desc("instrument reads and writes with callbacks"), cl::Hidden, cl::init(false))
FunctionPass * createHWAddressSanitizerPass(bool CompileKernel=false, bool Recover=false)
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
static uint64_t getAllocaSizeInBytes(const AllocaInst &AI)
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
bool isAndroid() const
Tests whether the target is Android.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
StringRef - Represent a constant reference to a string, i.e.
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
static cl::opt< unsigned long long > ClMappingOffset("hwasan-mapping-offset", cl::desc("HWASan shadow mapping offset [EXPERIMENTAL]"), cl::Hidden, cl::init(0))
static const char *const kHwasanModuleCtorName
an instruction to allocate memory on the stack
static cl::opt< bool > ClUARRetagToZero("hwasan-uar-retag-to-zero", cl::desc("Clear alloca tags before returning from the function to allow " "non-instrumented and instrumented function calls mix. When set " "to false, allocas are retagged before returning from the " "function to detect use after return."), cl::Hidden, cl::init(true))
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
static cl::opt< bool > ClInstrumentReads("hwasan-instrument-reads", cl::desc("instrument read instructions"), cl::Hidden, cl::init(true))