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/IntrinsicInst.h"
26 #include "llvm/LLVMContext.h"
27 #include "llvm/Module.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/DataTypes.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/IRBuilder.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/Regex.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/system_error.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Transforms/Instrumentation.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "llvm/Transforms/Utils/ModuleUtils.h"
41 #include "llvm/Type.h"
48 static const uint64_t kDefaultShadowScale = 3;
49 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
50 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
52 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
53 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
54 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
56 static const char *kAsanModuleCtorName = "asan.module_ctor";
57 static const char *kAsanModuleDtorName = "asan.module_dtor";
58 static const int kAsanCtorAndCtorPriority = 1;
59 static const char *kAsanReportErrorTemplate = "__asan_report_";
60 static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
61 static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
62 static const char *kAsanInitName = "__asan_init";
63 static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
64 static const char *kAsanMappingScaleName = "__asan_mapping_scale";
65 static const char *kAsanStackMallocName = "__asan_stack_malloc";
66 static const char *kAsanStackFreeName = "__asan_stack_free";
68 static const int kAsanStackLeftRedzoneMagic = 0xf1;
69 static const int kAsanStackMidRedzoneMagic = 0xf2;
70 static const int kAsanStackRightRedzoneMagic = 0xf3;
71 static const int kAsanStackPartialRedzoneMagic = 0xf4;
73 // Command-line flags.
75 // This flag may need to be replaced with -f[no-]asan-reads.
76 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
77 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
78 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
79 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
80 // This flag may need to be replaced with -f[no]asan-stack.
81 static cl::opt<bool> ClStack("asan-stack",
82 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
83 // This flag may need to be replaced with -f[no]asan-use-after-return.
84 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
85 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
86 // This flag may need to be replaced with -f[no]asan-globals.
87 static cl::opt<bool> ClGlobals("asan-globals",
88 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
89 static cl::opt<bool> ClMemIntrin("asan-memintrin",
90 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
91 // This flag may need to be replaced with -fasan-blacklist.
92 static cl::opt<std::string> ClBlackListFile("asan-blacklist",
93 cl::desc("File containing the list of functions to ignore "
94 "during instrumentation"), cl::Hidden);
96 // These flags allow to change the shadow mapping.
97 // The shadow mapping looks like
98 // Shadow = (Mem >> scale) + (1 << offset_log)
99 static cl::opt<int> ClMappingScale("asan-mapping-scale",
100 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
101 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
102 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
104 // Optimization flags. Not user visible, used mostly for testing
105 // and benchmarking the tool.
106 static cl::opt<bool> ClOpt("asan-opt",
107 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
108 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
109 cl::desc("Instrument the same temp just once"), cl::Hidden,
111 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
112 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
115 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
117 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
118 cl::Hidden, cl::init(0));
119 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
120 cl::Hidden, cl::desc("Debug func"));
121 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
122 cl::Hidden, cl::init(-1));
123 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
124 cl::Hidden, cl::init(-1));
128 // Blacklisted functions are not instrumented.
129 // The blacklist file contains one or more lines like this:
131 // fun:FunctionWildCard
133 // This is similar to the "ignore" feature of ThreadSanitizer.
134 // http://code.google.com/p/data-race-test/wiki/ThreadSanitizerIgnores
137 BlackList(const std::string &Path);
138 bool isIn(const Function &F);
143 /// AddressSanitizer: instrument the code in module to find memory bugs.
144 struct AddressSanitizer : public ModulePass {
146 void instrumentMop(Instruction *I);
147 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
148 Value *Addr, uint32_t TypeSize, bool IsWrite);
149 Instruction *generateCrashCode(IRBuilder<> &IRB, Value *Addr,
150 bool IsWrite, uint32_t TypeSize);
151 bool instrumentMemIntrinsic(MemIntrinsic *MI);
152 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
154 Instruction *InsertBefore, bool IsWrite);
155 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
156 bool handleFunction(Module &M, Function &F);
157 bool poisonStackInFunction(Module &M, Function &F);
158 virtual bool runOnModule(Module &M);
159 bool insertGlobalRedzones(Module &M);
160 BranchInst *splitBlockAndInsertIfThen(Instruction *SplitBefore, Value *Cmp);
161 static char ID; // Pass identification, replacement for typeid
165 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
166 Type *Ty = AI->getAllocatedType();
167 uint64_t SizeInBytes = TD->getTypeStoreSizeInBits(Ty) / 8;
170 uint64_t getAlignedSize(uint64_t SizeInBytes) {
171 return ((SizeInBytes + RedzoneSize - 1)
172 / RedzoneSize) * RedzoneSize;
174 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
175 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
176 return getAlignedSize(SizeInBytes);
179 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
180 Value *ShadowBase, bool DoPoison);
181 bool LooksLikeCodeInBug11395(Instruction *I);
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) {
331 // IsWrite and TypeSize are encoded in the function name.
332 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
333 (IsWrite ? "store" : "load") + itostr(TypeSize / 8);
334 Value *ReportWarningFunc = CurrentModule->getOrInsertFunction(
335 FunctionName, IRB.getVoidTy(), IntptrTy, NULL);
336 CallInst *Call = IRB.CreateCall(ReportWarningFunc, Addr);
337 Call->setDoesNotReturn();
341 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
342 IRBuilder<> &IRB, Value *Addr,
343 uint32_t TypeSize, bool IsWrite) {
344 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
346 Type *ShadowTy = IntegerType::get(
347 *C, std::max(8U, TypeSize >> MappingScale));
348 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
349 Value *ShadowPtr = memToShadow(AddrLong, IRB);
350 Value *CmpVal = Constant::getNullValue(ShadowTy);
351 Value *ShadowValue = IRB.CreateLoad(
352 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
354 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
356 Instruction *CheckTerm = splitBlockAndInsertIfThen(
357 cast<Instruction>(Cmp)->getNextNode(), Cmp);
358 IRBuilder<> IRB2(CheckTerm);
360 size_t Granularity = 1 << MappingScale;
361 if (TypeSize < 8 * Granularity) {
362 // Addr & (Granularity - 1)
363 Value *Lower3Bits = IRB2.CreateAnd(
364 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
365 // (Addr & (Granularity - 1)) + size - 1
366 Value *LastAccessedByte = IRB2.CreateAdd(
367 Lower3Bits, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
368 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
369 LastAccessedByte = IRB2.CreateIntCast(
370 LastAccessedByte, IRB.getInt8Ty(), false);
371 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
372 Value *Cmp2 = IRB2.CreateICmpSGE(LastAccessedByte, ShadowValue);
374 CheckTerm = splitBlockAndInsertIfThen(CheckTerm, Cmp2);
377 IRBuilder<> IRB1(CheckTerm);
378 Instruction *Crash = generateCrashCode(IRB1, AddrLong, IsWrite, TypeSize);
379 Crash->setDebugLoc(OrigIns->getDebugLoc());
380 ReplaceInstWithInst(CheckTerm, new UnreachableInst(*C));
383 // This function replaces all global variables with new variables that have
384 // trailing redzones. It also creates a function that poisons
385 // redzones and inserts this function into llvm.global_ctors.
386 bool AddressSanitizer::insertGlobalRedzones(Module &M) {
387 SmallVector<GlobalVariable *, 16> GlobalsToChange;
389 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
390 E = M.getGlobalList().end(); G != E; ++G) {
391 Type *Ty = cast<PointerType>(G->getType())->getElementType();
392 DEBUG(dbgs() << "GLOBAL: " << *G);
394 if (!Ty->isSized()) continue;
395 if (!G->hasInitializer()) continue;
396 // Touch only those globals that will not be defined in other modules.
397 // Don't handle ODR type linkages since other modules may be built w/o asan.
398 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
399 G->getLinkage() != GlobalVariable::PrivateLinkage &&
400 G->getLinkage() != GlobalVariable::InternalLinkage)
402 // Two problems with thread-locals:
403 // - The address of the main thread's copy can't be computed at link-time.
404 // - Need to poison all copies, not just the main thread's one.
405 if (G->isThreadLocal())
407 // For now, just ignore this Alloca if the alignment is large.
408 if (G->getAlignment() > RedzoneSize) continue;
410 // Ignore all the globals with the names starting with "\01L_OBJC_".
411 // Many of those are put into the .cstring section. The linker compresses
412 // that section by removing the spare \0s after the string terminator, so
413 // our redzones get broken.
414 if ((G->getName().find("\01L_OBJC_") == 0) ||
415 (G->getName().find("\01l_OBJC_") == 0)) {
416 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
420 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
421 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
423 if (G->hasSection()) {
424 StringRef Section(G->getSection());
425 if ((Section.find("__OBJC,") == 0) ||
426 (Section.find("__DATA, __objc_") == 0)) {
427 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
432 GlobalsToChange.push_back(G);
435 size_t n = GlobalsToChange.size();
436 if (n == 0) return false;
438 // A global is described by a structure
441 // size_t size_with_redzone;
443 // We initialize an array of such structures and pass it to a run-time call.
444 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
445 IntptrTy, IntptrTy, NULL);
446 SmallVector<Constant *, 16> Initializers(n);
448 IRBuilder<> IRB(CtorInsertBefore);
450 for (size_t i = 0; i < n; i++) {
451 GlobalVariable *G = GlobalsToChange[i];
452 PointerType *PtrTy = cast<PointerType>(G->getType());
453 Type *Ty = PtrTy->getElementType();
454 uint64_t SizeInBytes = TD->getTypeStoreSizeInBits(Ty) / 8;
455 uint64_t RightRedzoneSize = RedzoneSize +
456 (RedzoneSize - (SizeInBytes % RedzoneSize));
457 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
459 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
460 Constant *NewInitializer = ConstantStruct::get(
461 NewTy, G->getInitializer(),
462 Constant::getNullValue(RightRedZoneTy), NULL);
464 SmallString<2048> DescriptionOfGlobal = G->getName();
465 DescriptionOfGlobal += " (";
466 DescriptionOfGlobal += M.getModuleIdentifier();
467 DescriptionOfGlobal += ")";
468 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
470 // Create a new global variable with enough space for a redzone.
471 GlobalVariable *NewGlobal = new GlobalVariable(
472 M, NewTy, G->isConstant(), G->getLinkage(),
473 NewInitializer, "", G, G->isThreadLocal());
474 NewGlobal->copyAttributesFrom(G);
475 NewGlobal->setAlignment(RedzoneSize);
478 Indices2[0] = IRB.getInt32(0);
479 Indices2[1] = IRB.getInt32(0);
481 G->replaceAllUsesWith(
482 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, 2));
483 NewGlobal->takeName(G);
484 G->eraseFromParent();
486 Initializers[i] = ConstantStruct::get(
488 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
489 ConstantInt::get(IntptrTy, SizeInBytes),
490 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
491 ConstantExpr::getPointerCast(Name, IntptrTy),
493 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
496 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
497 GlobalVariable *AllGlobals = new GlobalVariable(
498 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
499 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
501 Function *AsanRegisterGlobals = cast<Function>(M.getOrInsertFunction(
502 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
503 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
505 IRB.CreateCall2(AsanRegisterGlobals,
506 IRB.CreatePointerCast(AllGlobals, IntptrTy),
507 ConstantInt::get(IntptrTy, n));
509 // We also need to unregister globals at the end, e.g. when a shared library
511 Function *AsanDtorFunction = Function::Create(
512 FunctionType::get(Type::getVoidTy(*C), false),
513 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
514 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
515 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
516 Function *AsanUnregisterGlobals = cast<Function>(M.getOrInsertFunction(
517 kAsanUnregisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
518 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
520 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
521 IRB.CreatePointerCast(AllGlobals, IntptrTy),
522 ConstantInt::get(IntptrTy, n));
523 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
530 bool AddressSanitizer::runOnModule(Module &M) {
531 // Initialize the private fields. No one has accessed them before.
532 TD = getAnalysisIfAvailable<TargetData>();
535 BL.reset(new BlackList(ClBlackListFile));
538 C = &(M.getContext());
539 LongSize = TD->getPointerSizeInBits();
540 IntptrTy = Type::getIntNTy(*C, LongSize);
541 IntptrPtrTy = PointerType::get(IntptrTy, 0);
543 AsanCtorFunction = Function::Create(
544 FunctionType::get(Type::getVoidTy(*C), false),
545 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
546 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
547 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
549 // call __asan_init in the module ctor.
550 IRBuilder<> IRB(CtorInsertBefore);
551 AsanInitFunction = cast<Function>(
552 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
553 AsanInitFunction->setLinkage(Function::ExternalLinkage);
554 IRB.CreateCall(AsanInitFunction);
556 MappingOffset = LongSize == 32
557 ? kDefaultShadowOffset32 : kDefaultShadowOffset64;
558 if (ClMappingOffsetLog >= 0) {
559 if (ClMappingOffsetLog == 0) {
563 MappingOffset = 1ULL << ClMappingOffsetLog;
566 MappingScale = kDefaultShadowScale;
567 if (ClMappingScale) {
568 MappingScale = ClMappingScale;
570 // Redzone used for stack and globals is at least 32 bytes.
571 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
572 RedzoneSize = std::max(32, (int)(1 << MappingScale));
577 Res |= insertGlobalRedzones(M);
579 // Tell the run-time the current values of mapping offset and scale.
580 GlobalValue *asan_mapping_offset =
581 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
582 ConstantInt::get(IntptrTy, MappingOffset),
583 kAsanMappingOffsetName);
584 GlobalValue *asan_mapping_scale =
585 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
586 ConstantInt::get(IntptrTy, MappingScale),
587 kAsanMappingScaleName);
588 // Read these globals, otherwise they may be optimized away.
589 IRB.CreateLoad(asan_mapping_scale, true);
590 IRB.CreateLoad(asan_mapping_offset, true);
593 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
594 if (F->isDeclaration()) continue;
595 Res |= handleFunction(M, *F);
598 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
603 bool AddressSanitizer::handleFunction(Module &M, Function &F) {
604 if (BL->isIn(F)) return false;
605 if (&F == AsanCtorFunction) return false;
607 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
609 // We want to instrument every address only once per basic block
610 // (unless there are calls between uses).
611 SmallSet<Value*, 16> TempsToInstrument;
612 SmallVector<Instruction*, 16> ToInstrument;
614 // Fill the set of memory operations to instrument.
615 for (Function::iterator FI = F.begin(), FE = F.end();
617 TempsToInstrument.clear();
618 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
620 if (LooksLikeCodeInBug11395(BI)) return false;
621 if ((isa<LoadInst>(BI) && ClInstrumentReads) ||
622 (isa<StoreInst>(BI) && ClInstrumentWrites)) {
623 Value *Addr = getLDSTOperand(BI);
624 if (ClOpt && ClOptSameTemp) {
625 if (!TempsToInstrument.insert(Addr))
626 continue; // We've seen this temp in the current BB.
628 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
631 if (isa<CallInst>(BI)) {
633 TempsToInstrument.clear();
637 ToInstrument.push_back(BI);
642 int NumInstrumented = 0;
643 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
644 Instruction *Inst = ToInstrument[i];
645 if (ClDebugMin < 0 || ClDebugMax < 0 ||
646 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
647 if (isa<StoreInst>(Inst) || isa<LoadInst>(Inst))
650 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
657 bool ChangedStack = poisonStackInFunction(M, F);
659 // For each NSObject descendant having a +load method, this method is invoked
660 // by the ObjC runtime before any of the static constructors is called.
661 // Therefore we need to instrument such methods with a call to __asan_init
662 // at the beginning in order to initialize our runtime before any access to
663 // the shadow memory.
664 // We cannot just ignore these methods, because they may call other
665 // instrumented functions.
666 if (F.getName().find(" load]") != std::string::npos) {
667 IRBuilder<> IRB(F.begin()->begin());
668 IRB.CreateCall(AsanInitFunction);
671 return NumInstrumented > 0 || ChangedStack;
674 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
675 if (ShadowRedzoneSize == 1) return PoisonByte;
676 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
677 if (ShadowRedzoneSize == 4)
678 return (PoisonByte << 24) + (PoisonByte << 16) +
679 (PoisonByte << 8) + (PoisonByte);
680 assert(0 && "ShadowRedzoneSize is either 1, 2 or 4");
684 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
687 size_t ShadowGranularity,
689 for (size_t i = 0; i < RedzoneSize;
690 i+= ShadowGranularity, Shadow++) {
691 if (i + ShadowGranularity <= Size) {
692 *Shadow = 0; // fully addressable
693 } else if (i >= Size) {
694 *Shadow = Magic; // unaddressable
696 *Shadow = Size - i; // first Size-i bytes are addressable
701 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
703 Value *ShadowBase, bool DoPoison) {
704 size_t ShadowRZSize = RedzoneSize >> MappingScale;
705 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
706 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
707 Type *RZPtrTy = PointerType::get(RZTy, 0);
709 Value *PoisonLeft = ConstantInt::get(RZTy,
710 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
711 Value *PoisonMid = ConstantInt::get(RZTy,
712 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
713 Value *PoisonRight = ConstantInt::get(RZTy,
714 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
716 // poison the first red zone.
717 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
719 // poison all other red zones.
720 uint64_t Pos = RedzoneSize;
721 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
722 AllocaInst *AI = AllocaVec[i];
723 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
724 uint64_t AlignedSize = getAlignedAllocaSize(AI);
725 assert(AlignedSize - SizeInBytes < RedzoneSize);
730 assert(ShadowBase->getType() == IntptrTy);
731 if (SizeInBytes < AlignedSize) {
732 // Poison the partial redzone at right
734 ShadowBase, ConstantInt::get(IntptrTy,
735 (Pos >> MappingScale) - ShadowRZSize));
736 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
739 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
741 1ULL << MappingScale,
742 kAsanStackPartialRedzoneMagic);
744 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
745 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
748 // Poison the full redzone at right.
749 Ptr = IRB.CreateAdd(ShadowBase,
750 ConstantInt::get(IntptrTy, Pos >> MappingScale));
751 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
752 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
758 // Workaround for bug 11395: we don't want to instrument stack in functions
759 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
760 // FIXME: remove once the bug 11395 is fixed.
761 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
762 if (LongSize != 32) return false;
763 CallInst *CI = dyn_cast<CallInst>(I);
764 if (!CI || !CI->isInlineAsm()) return false;
765 if (CI->getNumArgOperands() <= 5) return false;
766 // We have inline assembly with quite a few arguments.
770 // Find all static Alloca instructions and put
771 // poisoned red zones around all of them.
772 // Then unpoison everything back before the function returns.
774 // Stack poisoning does not play well with exception handling.
775 // When an exception is thrown, we essentially bypass the code
776 // that unpoisones the stack. This is why the run-time library has
777 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
778 // stack in the interceptor. This however does not work inside the
779 // actual function which catches the exception. Most likely because the
780 // compiler hoists the load of the shadow value somewhere too high.
781 // This causes asan to report a non-existing bug on 453.povray.
782 // It sounds like an LLVM bug.
783 bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
784 if (!ClStack) return false;
785 SmallVector<AllocaInst*, 16> AllocaVec;
786 SmallVector<Instruction*, 8> RetVec;
787 uint64_t TotalSize = 0;
789 // Filter out Alloca instructions we want (and can) handle.
790 // Collect Ret instructions.
791 for (Function::iterator FI = F.begin(), FE = F.end();
793 BasicBlock &BB = *FI;
794 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
796 if (isa<ReturnInst>(BI)) {
797 RetVec.push_back(BI);
801 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
803 if (AI->isArrayAllocation()) continue;
804 if (!AI->isStaticAlloca()) continue;
805 if (!AI->getAllocatedType()->isSized()) continue;
806 if (AI->getAlignment() > RedzoneSize) continue;
807 AllocaVec.push_back(AI);
808 uint64_t AlignedSize = getAlignedAllocaSize(AI);
809 TotalSize += AlignedSize;
813 if (AllocaVec.empty()) return false;
815 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
817 bool DoStackMalloc = ClUseAfterReturn
818 && LocalStackSize <= kMaxStackMallocSize;
820 Instruction *InsBefore = AllocaVec[0];
821 IRBuilder<> IRB(InsBefore);
824 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
825 AllocaInst *MyAlloca =
826 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
827 MyAlloca->setAlignment(RedzoneSize);
828 assert(MyAlloca->isStaticAlloca());
829 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
830 Value *LocalStackBase = OrigStackBase;
833 Value *AsanStackMallocFunc = M.getOrInsertFunction(
834 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
835 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
836 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
839 // This string will be parsed by the run-time (DescribeStackAddress).
840 SmallString<2048> StackDescriptionStorage;
841 raw_svector_ostream StackDescription(StackDescriptionStorage);
842 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
844 uint64_t Pos = RedzoneSize;
845 // Replace Alloca instructions with base+offset.
846 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
847 AllocaInst *AI = AllocaVec[i];
848 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
849 StringRef Name = AI->getName();
850 StackDescription << Pos << " " << SizeInBytes << " "
851 << Name.size() << " " << Name << " ";
852 uint64_t AlignedSize = getAlignedAllocaSize(AI);
853 assert((AlignedSize % RedzoneSize) == 0);
854 AI->replaceAllUsesWith(
856 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
858 Pos += AlignedSize + RedzoneSize;
860 assert(Pos == LocalStackSize);
862 // Write the Magic value and the frame description constant to the redzone.
863 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
864 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
866 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
867 ConstantInt::get(IntptrTy, LongSize/8));
868 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
869 Value *Description = IRB.CreatePointerCast(
870 createPrivateGlobalForString(M, StackDescription.str()),
872 IRB.CreateStore(Description, BasePlus1);
874 // Poison the stack redzones at the entry.
875 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
876 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
878 Value *AsanStackFreeFunc = NULL;
880 AsanStackFreeFunc = M.getOrInsertFunction(
881 kAsanStackFreeName, IRB.getVoidTy(),
882 IntptrTy, IntptrTy, IntptrTy, NULL);
885 // Unpoison the stack before all ret instructions.
886 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
887 Instruction *Ret = RetVec[i];
888 IRBuilder<> IRBRet(Ret);
890 // Mark the current frame as retired.
891 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
893 // Unpoison the stack.
894 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
897 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
898 ConstantInt::get(IntptrTy, LocalStackSize),
910 BlackList::BlackList(const std::string &Path) {
912 const char *kFunPrefix = "fun:";
913 if (!ClBlackListFile.size()) return;
916 OwningPtr<MemoryBuffer> File;
917 if (error_code EC = MemoryBuffer::getFile(ClBlackListFile.c_str(), File)) {
918 report_fatal_error("Can't open blacklist file " + ClBlackListFile + ": " +
921 MemoryBuffer *Buff = File.take();
922 const char *Data = Buff->getBufferStart();
923 size_t DataLen = Buff->getBufferSize();
924 SmallVector<StringRef, 16> Lines;
925 SplitString(StringRef(Data, DataLen), Lines, "\n\r");
926 for (size_t i = 0, numLines = Lines.size(); i < numLines; i++) {
927 if (Lines[i].startswith(kFunPrefix)) {
928 std::string ThisFunc = Lines[i].substr(strlen(kFunPrefix));
929 std::string ThisFuncRE;
930 // add ThisFunc replacing * with .*
931 for (size_t j = 0, n = ThisFunc.size(); j < n; j++) {
932 if (ThisFunc[j] == '*')
934 ThisFuncRE += ThisFunc[j];
936 // Check that the regexp is valid.
937 Regex CheckRE(ThisFuncRE);
939 if (!CheckRE.isValid(Error))
940 report_fatal_error("malformed blacklist regex: " + ThisFunc +
942 // Append to the final regexp.
949 Functions = new Regex(Fun);
953 bool BlackList::isIn(const Function &F) {
955 bool Res = Functions->match(F.getName());