1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 // Details of the algorithm:
12 // http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asan"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/Function.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/Module.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DataTypes.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/IRBuilder.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Regex.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Support/system_error.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Transforms/Instrumentation.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/ModuleUtils.h"
42 #include "llvm/Type.h"
49 static const uint64_t kDefaultShadowScale = 3;
50 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
51 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
53 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
54 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
55 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
57 static const char *kAsanModuleCtorName = "asan.module_ctor";
58 static const char *kAsanReportErrorTemplate = "__asan_report_";
59 static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
60 static const char *kAsanInitName = "__asan_init";
61 static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
62 static const char *kAsanMappingScaleName = "__asan_mapping_scale";
63 static const char *kAsanStackMallocName = "__asan_stack_malloc";
64 static const char *kAsanStackFreeName = "__asan_stack_free";
66 static const int kAsanStackLeftRedzoneMagic = 0xf1;
67 static const int kAsanStackMidRedzoneMagic = 0xf2;
68 static const int kAsanStackRightRedzoneMagic = 0xf3;
69 static const int kAsanStackPartialRedzoneMagic = 0xf4;
71 // Command-line flags.
73 // This flag may need to be replaced with -f[no-]asan-reads.
74 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
75 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
76 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
77 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
78 // This flag may need to be replaced with -f[no]asan-stack.
79 static cl::opt<bool> ClStack("asan-stack",
80 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
81 // This flag may need to be replaced with -f[no]asan-use-after-return.
82 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
83 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
84 // This flag may need to be replaced with -f[no]asan-globals.
85 static cl::opt<bool> ClGlobals("asan-globals",
86 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
87 static cl::opt<bool> ClMemIntrin("asan-memintrin",
88 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
89 // This flag may need to be replaced with -fasan-blacklist.
90 static cl::opt<std::string> ClBlackListFile("asan-blacklist",
91 cl::desc("File containing the list of functions to ignore "
92 "during instrumentation"), cl::Hidden);
93 static cl::opt<bool> ClUseCall("asan-use-call",
94 cl::desc("Use function call to generate a crash"), cl::Hidden,
97 // These flags allow to change the shadow mapping.
98 // The shadow mapping looks like
99 // Shadow = (Mem >> scale) + (1 << offset_log)
100 static cl::opt<int> ClMappingScale("asan-mapping-scale",
101 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
102 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
103 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
105 // Optimization flags. Not user visible, used mostly for testing
106 // and benchmarking the tool.
107 static cl::opt<bool> ClOpt("asan-opt",
108 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
109 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
110 cl::desc("Instrument the same temp just once"), cl::Hidden,
112 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
113 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
116 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
118 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
119 cl::Hidden, cl::init(0));
120 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
121 cl::Hidden, cl::desc("Debug func"));
122 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
123 cl::Hidden, cl::init(-1));
124 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
125 cl::Hidden, cl::init(-1));
129 // Blacklisted functions are not instrumented.
130 // The blacklist file contains one or more lines like this:
132 // fun:FunctionWildCard
134 // This is similar to the "ignore" feature of ThreadSanitizer.
135 // http://code.google.com/p/data-race-test/wiki/ThreadSanitizerIgnores
138 BlackList(const std::string &Path);
139 bool isIn(const Function &F);
144 /// AddressSanitizer: instrument the code in module to find memory bugs.
145 struct AddressSanitizer : public ModulePass {
147 void instrumentMop(Instruction *I);
148 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
149 Value *Addr, uint32_t TypeSize, bool IsWrite);
150 Instruction *generateCrashCode(IRBuilder<> &IRB, Value *Addr,
151 bool IsWrite, uint32_t TypeSize);
152 bool instrumentMemIntrinsic(MemIntrinsic *MI);
153 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
155 Instruction *InsertBefore, bool IsWrite);
156 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
157 bool handleFunction(Module &M, Function &F);
158 bool poisonStackInFunction(Module &M, Function &F);
159 virtual bool runOnModule(Module &M);
160 bool insertGlobalRedzones(Module &M);
161 BranchInst *splitBlockAndInsertIfThen(Instruction *SplitBefore, Value *Cmp);
162 static char ID; // Pass identification, replacement for typeid
166 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
167 Type *Ty = AI->getAllocatedType();
168 uint64_t SizeInBytes = TD->getTypeStoreSizeInBits(Ty) / 8;
171 uint64_t getAlignedSize(uint64_t SizeInBytes) {
172 return ((SizeInBytes + RedzoneSize - 1)
173 / RedzoneSize) * RedzoneSize;
175 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
176 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
177 return getAlignedSize(SizeInBytes);
180 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
181 Value *ShadowBase, bool DoPoison);
183 Module *CurrentModule;
186 uint64_t MappingOffset;
192 Function *AsanCtorFunction;
193 Function *AsanInitFunction;
194 Instruction *CtorInsertBefore;
195 OwningPtr<BlackList> BL;
199 char AddressSanitizer::ID = 0;
200 INITIALIZE_PASS(AddressSanitizer, "asan",
201 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
203 AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
204 ModulePass *llvm::createAddressSanitizerPass() {
205 return new AddressSanitizer();
208 // Create a constant for Str so that we can pass it to the run-time lib.
209 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
210 Constant *StrConst = ConstantArray::get(M.getContext(), Str);
211 return new GlobalVariable(M, StrConst->getType(), true,
212 GlobalValue::PrivateLinkage, StrConst, "");
215 // Split the basic block and insert an if-then code.
227 // Returns the NewBasicBlock's terminator.
228 BranchInst *AddressSanitizer::splitBlockAndInsertIfThen(
229 Instruction *SplitBefore, Value *Cmp) {
230 BasicBlock *Head = SplitBefore->getParent();
231 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
232 TerminatorInst *HeadOldTerm = Head->getTerminator();
233 BasicBlock *NewBasicBlock =
234 BasicBlock::Create(*C, "", Head->getParent());
235 BranchInst *HeadNewTerm = BranchInst::Create(/*ifTrue*/NewBasicBlock,
238 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
240 BranchInst *CheckTerm = BranchInst::Create(Tail, NewBasicBlock);
244 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
246 Shadow = IRB.CreateLShr(Shadow, MappingScale);
247 if (MappingOffset == 0)
249 // (Shadow >> scale) | offset
250 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
254 void AddressSanitizer::instrumentMemIntrinsicParam(Instruction *OrigIns,
255 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
256 // Check the first byte.
258 IRBuilder<> IRB(InsertBefore);
259 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
261 // Check the last byte.
263 IRBuilder<> IRB(InsertBefore);
264 Value *SizeMinusOne = IRB.CreateSub(
265 Size, ConstantInt::get(Size->getType(), 1));
266 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
267 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
268 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
269 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
273 // Instrument memset/memmove/memcpy
274 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
275 Value *Dst = MI->getDest();
276 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
277 Value *Src = MemTran ? MemTran->getSource() : NULL;
278 Value *Length = MI->getLength();
280 Constant *ConstLength = dyn_cast<Constant>(Length);
281 Instruction *InsertBefore = MI;
283 if (ConstLength->isNullValue()) return false;
285 // The size is not a constant so it could be zero -- check at run-time.
286 IRBuilder<> IRB(InsertBefore);
288 Value *Cmp = IRB.CreateICmpNE(Length,
289 Constant::getNullValue(Length->getType()));
290 InsertBefore = splitBlockAndInsertIfThen(InsertBefore, Cmp);
293 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
295 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
299 static Value *getLDSTOperand(Instruction *I) {
300 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
301 return LI->getPointerOperand();
303 return cast<StoreInst>(*I).getPointerOperand();
306 void AddressSanitizer::instrumentMop(Instruction *I) {
307 int IsWrite = isa<StoreInst>(*I);
308 Value *Addr = getLDSTOperand(I);
309 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
310 // We are accessing a global scalar variable. Nothing to catch here.
313 Type *OrigPtrTy = Addr->getType();
314 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
316 assert(OrigTy->isSized());
317 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
319 if (TypeSize != 8 && TypeSize != 16 &&
320 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
321 // Ignore all unusual sizes.
326 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
329 Instruction *AddressSanitizer::generateCrashCode(
330 IRBuilder<> &IRB, Value *Addr, bool IsWrite, uint32_t TypeSize) {
333 // Here we use a call instead of arch-specific asm to report an error.
334 // This is almost always slower (because the codegen needs to generate
335 // prologue/epilogue for otherwise leaf functions) and generates more code.
336 // This mode could be useful if we can not use SIGILL for some reason.
338 // IsWrite and TypeSize are encoded in the function name.
339 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
340 (IsWrite ? "store" : "load") + itostr(TypeSize / 8);
341 Value *ReportWarningFunc = CurrentModule->getOrInsertFunction(
342 FunctionName, IRB.getVoidTy(), IntptrTy, NULL);
343 CallInst *Call = IRB.CreateCall(ReportWarningFunc, Addr);
344 Call->setDoesNotReturn();
348 uint32_t LogOfSizeInBytes = CountTrailingZeros_32(TypeSize / 8);
349 assert(8U * (1 << LogOfSizeInBytes) == TypeSize);
350 uint8_t TelltaleValue = IsWrite * 8 + LogOfSizeInBytes;
351 assert(TelltaleValue < 16);
353 // Move the failing address to %rax/%eax
354 FunctionType *Fn1Ty = FunctionType::get(
355 IRB.getVoidTy(), ArrayRef<Type*>(IntptrTy), false);
356 const char *MovStr = LongSize == 32
357 ? "mov $0, %eax" : "mov $0, %rax";
358 Value *AsmMov = InlineAsm::get(
359 Fn1Ty, StringRef(MovStr), StringRef("r"), true);
360 IRB.CreateCall(AsmMov, Addr);
362 // crash with ud2; could use int3, but it is less friendly to gdb.
363 // after ud2 put a 1-byte instruction that encodes the access type and size.
365 const char *TelltaleInsns[16] = {
384 std::string AsmStr = "ud2;";
385 AsmStr += TelltaleInsns[TelltaleValue];
386 Value *MyAsm = InlineAsm::get(FunctionType::get(Type::getVoidTy(*C), false),
387 StringRef(AsmStr), StringRef(""), true);
388 CallInst *AsmCall = IRB.CreateCall(MyAsm);
390 // This saves us one jump, but triggers a bug in RA (or somewhere else):
391 // while building 483.xalancbmk the compiler goes into infinite loop in
392 // llvm::SpillPlacement::iterate() / RAGreedy::growRegion
393 // AsmCall->setDoesNotReturn();
397 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
398 IRBuilder<> &IRB, Value *Addr,
399 uint32_t TypeSize, bool IsWrite) {
400 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
402 Type *ShadowTy = IntegerType::get(
403 *C, std::max(8U, TypeSize >> MappingScale));
404 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
405 Value *ShadowPtr = memToShadow(AddrLong, IRB);
406 Value *CmpVal = Constant::getNullValue(ShadowTy);
407 Value *ShadowValue = IRB.CreateLoad(
408 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
410 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
412 Instruction *CheckTerm = splitBlockAndInsertIfThen(
413 cast<Instruction>(Cmp)->getNextNode(), Cmp);
414 IRBuilder<> IRB2(CheckTerm);
416 size_t Granularity = 1 << MappingScale;
417 if (TypeSize < 8 * Granularity) {
418 // Addr & (Granularity - 1)
419 Value *Lower3Bits = IRB2.CreateAnd(
420 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
421 // (Addr & (Granularity - 1)) + size - 1
422 Value *LastAccessedByte = IRB2.CreateAdd(
423 Lower3Bits, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
424 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
425 LastAccessedByte = IRB2.CreateIntCast(
426 LastAccessedByte, IRB.getInt8Ty(), false);
427 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
428 Value *Cmp2 = IRB2.CreateICmpSGE(LastAccessedByte, ShadowValue);
430 CheckTerm = splitBlockAndInsertIfThen(CheckTerm, Cmp2);
433 IRBuilder<> IRB1(CheckTerm);
434 Instruction *Crash = generateCrashCode(IRB1, AddrLong, IsWrite, TypeSize);
435 Crash->setDebugLoc(OrigIns->getDebugLoc());
438 // This function replaces all global variables with new variables that have
439 // trailing redzones. It also creates a function that poisons
440 // redzones and inserts this function into llvm.global_ctors.
441 bool AddressSanitizer::insertGlobalRedzones(Module &M) {
442 SmallVector<GlobalVariable *, 16> GlobalsToChange;
444 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
445 E = M.getGlobalList().end(); G != E; ++G) {
446 Type *Ty = cast<PointerType>(G->getType())->getElementType();
447 DEBUG(dbgs() << "GLOBAL: " << *G);
449 if (!Ty->isSized()) continue;
450 if (!G->hasInitializer()) continue;
451 if (GlobalVariable::mayBeOverridden(G->getLinkage()) ||
452 G->getLinkage() == GlobalVariable::AppendingLinkage)
454 // For now, just ignore this Alloca if the alignment is large.
455 if (G->getAlignment() > RedzoneSize) continue;
457 // Ignore all the globals with the names starting with "\01L_OBJC_".
458 // Many of those are put into the .cstring section. The linker compresses
459 // that section by removing the spare \0s after the string terminator, so
460 // our redzones get broken.
461 if ((G->getName().find("\01L_OBJC_") == 0) ||
462 (G->getName().find("\01l_OBJC_") == 0)) {
463 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
467 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
468 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
470 if (G->hasSection()) {
471 StringRef Section(G->getSection());
472 if ((Section.find("__OBJC,") == 0) ||
473 (Section.find("__DATA, __objc_") == 0)) {
474 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
479 GlobalsToChange.push_back(G);
482 size_t n = GlobalsToChange.size();
483 if (n == 0) return false;
485 // A global is described by a structure
488 // size_t size_with_redzone;
490 // We initialize an array of such structures and pass it to a run-time call.
491 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
492 IntptrTy, IntptrTy, NULL);
493 SmallVector<Constant *, 16> Initializers(n);
495 IRBuilder<> IRB(CtorInsertBefore);
497 for (size_t i = 0; i < n; i++) {
498 GlobalVariable *G = GlobalsToChange[i];
499 PointerType *PtrTy = cast<PointerType>(G->getType());
500 Type *Ty = PtrTy->getElementType();
501 uint64_t SizeInBytes = TD->getTypeStoreSizeInBits(Ty) / 8;
502 uint64_t RightRedzoneSize = RedzoneSize +
503 (RedzoneSize - (SizeInBytes % RedzoneSize));
504 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
506 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
507 Constant *NewInitializer = ConstantStruct::get(
508 NewTy, G->getInitializer(),
509 Constant::getNullValue(RightRedZoneTy), NULL);
511 GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
513 // Create a new global variable with enough space for a redzone.
514 GlobalVariable *NewGlobal = new GlobalVariable(
515 M, NewTy, G->isConstant(), G->getLinkage(),
516 NewInitializer, "", G, G->isThreadLocal());
517 NewGlobal->copyAttributesFrom(G);
518 NewGlobal->setAlignment(RedzoneSize);
521 Indices2[0] = IRB.getInt32(0);
522 Indices2[1] = IRB.getInt32(0);
524 G->replaceAllUsesWith(
525 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, 2));
526 NewGlobal->takeName(G);
527 G->eraseFromParent();
529 Initializers[i] = ConstantStruct::get(
531 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
532 ConstantInt::get(IntptrTy, SizeInBytes),
533 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
534 ConstantExpr::getPointerCast(Name, IntptrTy),
536 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
539 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
540 GlobalVariable *AllGlobals = new GlobalVariable(
541 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
542 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
544 Function *AsanRegisterGlobals = cast<Function>(M.getOrInsertFunction(
545 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
546 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
548 IRB.CreateCall2(AsanRegisterGlobals,
549 IRB.CreatePointerCast(AllGlobals, IntptrTy),
550 ConstantInt::get(IntptrTy, n));
557 bool AddressSanitizer::runOnModule(Module &M) {
558 // Initialize the private fields. No one has accessed them before.
559 TD = getAnalysisIfAvailable<TargetData>();
562 BL.reset(new BlackList(ClBlackListFile));
565 C = &(M.getContext());
566 LongSize = TD->getPointerSizeInBits();
567 IntptrTy = Type::getIntNTy(*C, LongSize);
568 IntptrPtrTy = PointerType::get(IntptrTy, 0);
570 AsanCtorFunction = Function::Create(
571 FunctionType::get(Type::getVoidTy(*C), false),
572 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
573 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
574 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
576 // call __asan_init in the module ctor.
577 IRBuilder<> IRB(CtorInsertBefore);
578 AsanInitFunction = cast<Function>(
579 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
580 AsanInitFunction->setLinkage(Function::ExternalLinkage);
581 IRB.CreateCall(AsanInitFunction);
583 MappingOffset = LongSize == 32
584 ? kDefaultShadowOffset32 : kDefaultShadowOffset64;
585 if (ClMappingOffsetLog >= 0) {
586 if (ClMappingOffsetLog == 0) {
590 MappingOffset = 1ULL << ClMappingOffsetLog;
593 MappingScale = kDefaultShadowScale;
594 if (ClMappingScale) {
595 MappingScale = ClMappingScale;
597 // Redzone used for stack and globals is at least 32 bytes.
598 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
599 RedzoneSize = std::max(32, (int)(1 << MappingScale));
604 Res |= insertGlobalRedzones(M);
606 // Tell the run-time the current values of mapping offset and scale.
607 GlobalValue *asan_mapping_offset =
608 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
609 ConstantInt::get(IntptrTy, MappingOffset),
610 kAsanMappingOffsetName);
611 GlobalValue *asan_mapping_scale =
612 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
613 ConstantInt::get(IntptrTy, MappingScale),
614 kAsanMappingScaleName);
615 // Read these globals, otherwise they may be optimized away.
616 IRB.CreateLoad(asan_mapping_scale, true);
617 IRB.CreateLoad(asan_mapping_offset, true);
620 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
621 if (F->isDeclaration()) continue;
622 Res |= handleFunction(M, *F);
625 appendToGlobalCtors(M, AsanCtorFunction, 1 /*high priority*/);
630 bool AddressSanitizer::handleFunction(Module &M, Function &F) {
631 if (BL->isIn(F)) return false;
632 if (&F == AsanCtorFunction) return false;
634 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
636 // We want to instrument every address only once per basic block
637 // (unless there are calls between uses).
638 SmallSet<Value*, 16> TempsToInstrument;
639 SmallVector<Instruction*, 16> ToInstrument;
641 // Fill the set of memory operations to instrument.
642 for (Function::iterator FI = F.begin(), FE = F.end();
644 TempsToInstrument.clear();
645 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
647 if ((isa<LoadInst>(BI) && ClInstrumentReads) ||
648 (isa<StoreInst>(BI) && ClInstrumentWrites)) {
649 Value *Addr = getLDSTOperand(BI);
650 if (ClOpt && ClOptSameTemp) {
651 if (!TempsToInstrument.insert(Addr))
652 continue; // We've seen this temp in the current BB.
654 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
657 if (isa<CallInst>(BI)) {
659 TempsToInstrument.clear();
663 ToInstrument.push_back(BI);
668 int NumInstrumented = 0;
669 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
670 Instruction *Inst = ToInstrument[i];
671 if (ClDebugMin < 0 || ClDebugMax < 0 ||
672 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
673 if (isa<StoreInst>(Inst) || isa<LoadInst>(Inst))
676 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
683 bool ChangedStack = poisonStackInFunction(M, F);
685 // For each NSObject descendant having a +load method, this method is invoked
686 // by the ObjC runtime before any of the static constructors is called.
687 // Therefore we need to instrument such methods with a call to __asan_init
688 // at the beginning in order to initialize our runtime before any access to
689 // the shadow memory.
690 // We cannot just ignore these methods, because they may call other
691 // instrumented functions.
692 if (F.getName().find(" load]") != std::string::npos) {
693 IRBuilder<> IRB(F.begin()->begin());
694 IRB.CreateCall(AsanInitFunction);
697 return NumInstrumented > 0 || ChangedStack;
700 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
701 if (ShadowRedzoneSize == 1) return PoisonByte;
702 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
703 if (ShadowRedzoneSize == 4)
704 return (PoisonByte << 24) + (PoisonByte << 16) +
705 (PoisonByte << 8) + (PoisonByte);
706 assert(0 && "ShadowRedzoneSize is either 1, 2 or 4");
710 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
713 size_t ShadowGranularity,
715 for (size_t i = 0; i < RedzoneSize;
716 i+= ShadowGranularity, Shadow++) {
717 if (i + ShadowGranularity <= Size) {
718 *Shadow = 0; // fully addressable
719 } else if (i >= Size) {
720 *Shadow = Magic; // unaddressable
722 *Shadow = Size - i; // first Size-i bytes are addressable
727 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
729 Value *ShadowBase, bool DoPoison) {
730 size_t ShadowRZSize = RedzoneSize >> MappingScale;
731 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
732 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
733 Type *RZPtrTy = PointerType::get(RZTy, 0);
735 Value *PoisonLeft = ConstantInt::get(RZTy,
736 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
737 Value *PoisonMid = ConstantInt::get(RZTy,
738 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
739 Value *PoisonRight = ConstantInt::get(RZTy,
740 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
742 // poison the first red zone.
743 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
745 // poison all other red zones.
746 uint64_t Pos = RedzoneSize;
747 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
748 AllocaInst *AI = AllocaVec[i];
749 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
750 uint64_t AlignedSize = getAlignedAllocaSize(AI);
751 assert(AlignedSize - SizeInBytes < RedzoneSize);
756 assert(ShadowBase->getType() == IntptrTy);
757 if (SizeInBytes < AlignedSize) {
758 // Poison the partial redzone at right
760 ShadowBase, ConstantInt::get(IntptrTy,
761 (Pos >> MappingScale) - ShadowRZSize));
762 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
765 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
767 1ULL << MappingScale,
768 kAsanStackPartialRedzoneMagic);
770 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
771 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
774 // Poison the full redzone at right.
775 Ptr = IRB.CreateAdd(ShadowBase,
776 ConstantInt::get(IntptrTy, Pos >> MappingScale));
777 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
778 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
784 // Find all static Alloca instructions and put
785 // poisoned red zones around all of them.
786 // Then unpoison everything back before the function returns.
788 // Stack poisoning does not play well with exception handling.
789 // When an exception is thrown, we essentially bypass the code
790 // that unpoisones the stack. This is why the run-time library has
791 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
792 // stack in the interceptor. This however does not work inside the
793 // actual function which catches the exception. Most likely because the
794 // compiler hoists the load of the shadow value somewhere too high.
795 // This causes asan to report a non-existing bug on 453.povray.
796 // It sounds like an LLVM bug.
797 bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
798 if (!ClStack) return false;
799 SmallVector<AllocaInst*, 16> AllocaVec;
800 SmallVector<Instruction*, 8> RetVec;
801 uint64_t TotalSize = 0;
803 // Filter out Alloca instructions we want (and can) handle.
804 // Collect Ret instructions.
805 for (Function::iterator FI = F.begin(), FE = F.end();
807 BasicBlock &BB = *FI;
808 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
810 if (isa<ReturnInst>(BI)) {
811 RetVec.push_back(BI);
815 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
817 if (AI->isArrayAllocation()) continue;
818 if (!AI->isStaticAlloca()) continue;
819 if (!AI->getAllocatedType()->isSized()) continue;
820 if (AI->getAlignment() > RedzoneSize) continue;
821 AllocaVec.push_back(AI);
822 uint64_t AlignedSize = getAlignedAllocaSize(AI);
823 TotalSize += AlignedSize;
827 if (AllocaVec.empty()) return false;
829 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
831 bool DoStackMalloc = ClUseAfterReturn
832 && LocalStackSize <= kMaxStackMallocSize;
834 Instruction *InsBefore = AllocaVec[0];
835 IRBuilder<> IRB(InsBefore);
838 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
839 AllocaInst *MyAlloca =
840 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
841 MyAlloca->setAlignment(RedzoneSize);
842 assert(MyAlloca->isStaticAlloca());
843 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
844 Value *LocalStackBase = OrigStackBase;
847 Value *AsanStackMallocFunc = M.getOrInsertFunction(
848 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
849 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
850 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
853 // This string will be parsed by the run-time (DescribeStackAddress).
854 SmallString<2048> StackDescriptionStorage;
855 raw_svector_ostream StackDescription(StackDescriptionStorage);
856 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
858 uint64_t Pos = RedzoneSize;
859 // Replace Alloca instructions with base+offset.
860 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
861 AllocaInst *AI = AllocaVec[i];
862 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
863 StringRef Name = AI->getName();
864 StackDescription << Pos << " " << SizeInBytes << " "
865 << Name.size() << " " << Name << " ";
866 uint64_t AlignedSize = getAlignedAllocaSize(AI);
867 assert((AlignedSize % RedzoneSize) == 0);
868 AI->replaceAllUsesWith(
870 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
872 Pos += AlignedSize + RedzoneSize;
874 assert(Pos == LocalStackSize);
876 // Write the Magic value and the frame description constant to the redzone.
877 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
878 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
880 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
881 ConstantInt::get(IntptrTy, LongSize/8));
882 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
883 Value *Description = IRB.CreatePointerCast(
884 createPrivateGlobalForString(M, StackDescription.str()),
886 IRB.CreateStore(Description, BasePlus1);
888 // Poison the stack redzones at the entry.
889 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
890 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
892 Value *AsanStackFreeFunc = NULL;
894 AsanStackFreeFunc = M.getOrInsertFunction(
895 kAsanStackFreeName, IRB.getVoidTy(),
896 IntptrTy, IntptrTy, IntptrTy, NULL);
899 // Unpoison the stack before all ret instructions.
900 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
901 Instruction *Ret = RetVec[i];
902 IRBuilder<> IRBRet(Ret);
904 // Mark the current frame as retired.
905 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
907 // Unpoison the stack.
908 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
911 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
912 ConstantInt::get(IntptrTy, LocalStackSize),
924 BlackList::BlackList(const std::string &Path) {
926 const char *kFunPrefix = "fun:";
927 if (!ClBlackListFile.size()) return;
930 OwningPtr<MemoryBuffer> File;
931 if (error_code EC = MemoryBuffer::getFile(ClBlackListFile.c_str(), File)) {
932 errs() << EC.message();
935 MemoryBuffer *Buff = File.take();
936 const char *Data = Buff->getBufferStart();
937 size_t DataLen = Buff->getBufferSize();
938 SmallVector<StringRef, 16> Lines;
939 SplitString(StringRef(Data, DataLen), Lines, "\n\r");
940 for (size_t i = 0, numLines = Lines.size(); i < numLines; i++) {
941 if (Lines[i].startswith(kFunPrefix)) {
942 std::string ThisFunc = Lines[i].substr(strlen(kFunPrefix));
946 // add ThisFunc replacing * with .*
947 for (size_t j = 0, n = ThisFunc.size(); j < n; j++) {
948 if (ThisFunc[j] == '*')
955 Functions = new Regex(Fun);
959 bool BlackList::isIn(const Function &F) {
961 bool Res = Functions->match(F.getName());