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 "FunctionBlackList.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Function.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/raw_ostream.h"
34 #include "llvm/Support/system_error.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Transforms/Instrumentation.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/ModuleUtils.h"
40 #include "llvm/Type.h"
47 static const uint64_t kDefaultShadowScale = 3;
48 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
49 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
51 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
52 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
53 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
55 static const char *kAsanModuleCtorName = "asan.module_ctor";
56 static const char *kAsanModuleDtorName = "asan.module_dtor";
57 static const int kAsanCtorAndCtorPriority = 1;
58 static const char *kAsanReportErrorTemplate = "__asan_report_";
59 static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
60 static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
61 static const char *kAsanInitName = "__asan_init";
62 static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
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 /// AddressSanitizer: instrument the code in module to find memory bugs.
129 struct AddressSanitizer : public ModulePass {
131 virtual const char *getPassName() const;
132 void instrumentMop(Instruction *I);
133 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
134 Value *Addr, uint32_t TypeSize, bool IsWrite);
135 Instruction *generateCrashCode(IRBuilder<> &IRB, Value *Addr,
136 bool IsWrite, uint32_t TypeSize);
137 bool instrumentMemIntrinsic(MemIntrinsic *MI);
138 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
140 Instruction *InsertBefore, bool IsWrite);
141 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
142 bool handleFunction(Module &M, Function &F);
143 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
144 bool poisonStackInFunction(Module &M, Function &F);
145 virtual bool runOnModule(Module &M);
146 bool insertGlobalRedzones(Module &M);
147 BranchInst *splitBlockAndInsertIfThen(Instruction *SplitBefore, Value *Cmp);
148 static char ID; // Pass identification, replacement for typeid
152 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
153 Type *Ty = AI->getAllocatedType();
154 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
157 uint64_t getAlignedSize(uint64_t SizeInBytes) {
158 return ((SizeInBytes + RedzoneSize - 1)
159 / RedzoneSize) * RedzoneSize;
161 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
162 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
163 return getAlignedSize(SizeInBytes);
166 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
167 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
168 Value *ShadowBase, bool DoPoison);
169 bool LooksLikeCodeInBug11395(Instruction *I);
171 Module *CurrentModule;
174 uint64_t MappingOffset;
180 Function *AsanCtorFunction;
181 Function *AsanInitFunction;
182 Instruction *CtorInsertBefore;
183 OwningPtr<FunctionBlackList> BL;
187 char AddressSanitizer::ID = 0;
188 INITIALIZE_PASS(AddressSanitizer, "asan",
189 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
191 AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
192 ModulePass *llvm::createAddressSanitizerPass() {
193 return new AddressSanitizer();
196 const char *AddressSanitizer::getPassName() const {
197 return "AddressSanitizer";
200 // Create a constant for Str so that we can pass it to the run-time lib.
201 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
202 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
203 return new GlobalVariable(M, StrConst->getType(), true,
204 GlobalValue::PrivateLinkage, StrConst, "");
207 // Split the basic block and insert an if-then code.
219 // Returns the NewBasicBlock's terminator.
220 BranchInst *AddressSanitizer::splitBlockAndInsertIfThen(
221 Instruction *SplitBefore, Value *Cmp) {
222 BasicBlock *Head = SplitBefore->getParent();
223 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
224 TerminatorInst *HeadOldTerm = Head->getTerminator();
225 BasicBlock *NewBasicBlock =
226 BasicBlock::Create(*C, "", Head->getParent());
227 BranchInst *HeadNewTerm = BranchInst::Create(/*ifTrue*/NewBasicBlock,
230 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
232 BranchInst *CheckTerm = BranchInst::Create(Tail, NewBasicBlock);
236 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
238 Shadow = IRB.CreateLShr(Shadow, MappingScale);
239 if (MappingOffset == 0)
241 // (Shadow >> scale) | offset
242 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
246 void AddressSanitizer::instrumentMemIntrinsicParam(Instruction *OrigIns,
247 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
248 // Check the first byte.
250 IRBuilder<> IRB(InsertBefore);
251 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
253 // Check the last byte.
255 IRBuilder<> IRB(InsertBefore);
256 Value *SizeMinusOne = IRB.CreateSub(
257 Size, ConstantInt::get(Size->getType(), 1));
258 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
259 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
260 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
261 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
265 // Instrument memset/memmove/memcpy
266 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
267 Value *Dst = MI->getDest();
268 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
269 Value *Src = MemTran ? MemTran->getSource() : NULL;
270 Value *Length = MI->getLength();
272 Constant *ConstLength = dyn_cast<Constant>(Length);
273 Instruction *InsertBefore = MI;
275 if (ConstLength->isNullValue()) return false;
277 // The size is not a constant so it could be zero -- check at run-time.
278 IRBuilder<> IRB(InsertBefore);
280 Value *Cmp = IRB.CreateICmpNE(Length,
281 Constant::getNullValue(Length->getType()));
282 InsertBefore = splitBlockAndInsertIfThen(InsertBefore, Cmp);
285 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
287 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
291 static Value *getLDSTOperand(Instruction *I) {
292 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
293 return LI->getPointerOperand();
295 return cast<StoreInst>(*I).getPointerOperand();
298 void AddressSanitizer::instrumentMop(Instruction *I) {
299 int IsWrite = isa<StoreInst>(*I);
300 Value *Addr = getLDSTOperand(I);
301 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
302 // We are accessing a global scalar variable. Nothing to catch here.
305 Type *OrigPtrTy = Addr->getType();
306 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
308 assert(OrigTy->isSized());
309 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
311 if (TypeSize != 8 && TypeSize != 16 &&
312 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
313 // Ignore all unusual sizes.
318 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
321 // Validate the result of Module::getOrInsertFunction called for an interface
322 // function of AddressSanitizer. If the instrumented module defines a function
323 // with the same name, their prototypes must match, otherwise
324 // getOrInsertFunction returns a bitcast.
325 Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
326 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
327 FuncOrBitcast->dump();
328 report_fatal_error("trying to redefine an AddressSanitizer "
329 "interface function");
332 Instruction *AddressSanitizer::generateCrashCode(
333 IRBuilder<> &IRB, Value *Addr, bool IsWrite, uint32_t TypeSize) {
334 // IsWrite and TypeSize are encoded in the function name.
335 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
336 (IsWrite ? "store" : "load") + itostr(TypeSize / 8);
337 Value *ReportWarningFunc = CurrentModule->getOrInsertFunction(
338 FunctionName, IRB.getVoidTy(), IntptrTy, NULL);
339 CallInst *Call = IRB.CreateCall(ReportWarningFunc, Addr);
340 Call->setDoesNotReturn();
344 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
345 IRBuilder<> &IRB, Value *Addr,
346 uint32_t TypeSize, bool IsWrite) {
347 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
349 Type *ShadowTy = IntegerType::get(
350 *C, std::max(8U, TypeSize >> MappingScale));
351 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
352 Value *ShadowPtr = memToShadow(AddrLong, IRB);
353 Value *CmpVal = Constant::getNullValue(ShadowTy);
354 Value *ShadowValue = IRB.CreateLoad(
355 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
357 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
359 Instruction *CheckTerm = splitBlockAndInsertIfThen(
360 cast<Instruction>(Cmp)->getNextNode(), Cmp);
361 IRBuilder<> IRB2(CheckTerm);
363 size_t Granularity = 1 << MappingScale;
364 if (TypeSize < 8 * Granularity) {
365 // Addr & (Granularity - 1)
366 Value *Lower3Bits = IRB2.CreateAnd(
367 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
368 // (Addr & (Granularity - 1)) + size - 1
369 Value *LastAccessedByte = IRB2.CreateAdd(
370 Lower3Bits, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
371 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
372 LastAccessedByte = IRB2.CreateIntCast(
373 LastAccessedByte, IRB.getInt8Ty(), false);
374 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
375 Value *Cmp2 = IRB2.CreateICmpSGE(LastAccessedByte, ShadowValue);
377 CheckTerm = splitBlockAndInsertIfThen(CheckTerm, Cmp2);
380 IRBuilder<> IRB1(CheckTerm);
381 Instruction *Crash = generateCrashCode(IRB1, AddrLong, IsWrite, TypeSize);
382 Crash->setDebugLoc(OrigIns->getDebugLoc());
383 ReplaceInstWithInst(CheckTerm, new UnreachableInst(*C));
386 // This function replaces all global variables with new variables that have
387 // trailing redzones. It also creates a function that poisons
388 // redzones and inserts this function into llvm.global_ctors.
389 bool AddressSanitizer::insertGlobalRedzones(Module &M) {
390 SmallVector<GlobalVariable *, 16> GlobalsToChange;
392 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
393 E = M.getGlobalList().end(); G != E; ++G) {
394 Type *Ty = cast<PointerType>(G->getType())->getElementType();
395 DEBUG(dbgs() << "GLOBAL: " << *G);
397 if (!Ty->isSized()) continue;
398 if (!G->hasInitializer()) continue;
399 // Touch only those globals that will not be defined in other modules.
400 // Don't handle ODR type linkages since other modules may be built w/o asan.
401 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
402 G->getLinkage() != GlobalVariable::PrivateLinkage &&
403 G->getLinkage() != GlobalVariable::InternalLinkage)
405 // Two problems with thread-locals:
406 // - The address of the main thread's copy can't be computed at link-time.
407 // - Need to poison all copies, not just the main thread's one.
408 if (G->isThreadLocal())
410 // For now, just ignore this Alloca if the alignment is large.
411 if (G->getAlignment() > RedzoneSize) continue;
413 // Ignore all the globals with the names starting with "\01L_OBJC_".
414 // Many of those are put into the .cstring section. The linker compresses
415 // that section by removing the spare \0s after the string terminator, so
416 // our redzones get broken.
417 if ((G->getName().find("\01L_OBJC_") == 0) ||
418 (G->getName().find("\01l_OBJC_") == 0)) {
419 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
423 if (G->hasSection()) {
424 StringRef Section(G->getSection());
425 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
426 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
428 if ((Section.find("__OBJC,") == 0) ||
429 (Section.find("__DATA, __objc_") == 0)) {
430 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
433 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
434 // Constant CFString instances are compiled in the following way:
435 // -- the string buffer is emitted into
436 // __TEXT,__cstring,cstring_literals
437 // -- the constant NSConstantString structure referencing that buffer
438 // is placed into __DATA,__cfstring
439 // Therefore there's no point in placing redzones into __DATA,__cfstring.
440 // Moreover, it causes the linker to crash on OS X 10.7
441 if (Section.find("__DATA,__cfstring") == 0) {
442 DEBUG(dbgs() << "Ignoring CFString: " << *G);
447 GlobalsToChange.push_back(G);
450 size_t n = GlobalsToChange.size();
451 if (n == 0) return false;
453 // A global is described by a structure
456 // size_t size_with_redzone;
458 // We initialize an array of such structures and pass it to a run-time call.
459 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
460 IntptrTy, IntptrTy, NULL);
461 SmallVector<Constant *, 16> Initializers(n);
463 IRBuilder<> IRB(CtorInsertBefore);
465 for (size_t i = 0; i < n; i++) {
466 GlobalVariable *G = GlobalsToChange[i];
467 PointerType *PtrTy = cast<PointerType>(G->getType());
468 Type *Ty = PtrTy->getElementType();
469 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
470 uint64_t RightRedzoneSize = RedzoneSize +
471 (RedzoneSize - (SizeInBytes % RedzoneSize));
472 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
474 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
475 Constant *NewInitializer = ConstantStruct::get(
476 NewTy, G->getInitializer(),
477 Constant::getNullValue(RightRedZoneTy), NULL);
479 SmallString<2048> DescriptionOfGlobal = G->getName();
480 DescriptionOfGlobal += " (";
481 DescriptionOfGlobal += M.getModuleIdentifier();
482 DescriptionOfGlobal += ")";
483 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
485 // Create a new global variable with enough space for a redzone.
486 GlobalVariable *NewGlobal = new GlobalVariable(
487 M, NewTy, G->isConstant(), G->getLinkage(),
488 NewInitializer, "", G, G->isThreadLocal());
489 NewGlobal->copyAttributesFrom(G);
490 NewGlobal->setAlignment(RedzoneSize);
493 Indices2[0] = IRB.getInt32(0);
494 Indices2[1] = IRB.getInt32(0);
496 G->replaceAllUsesWith(
497 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
498 NewGlobal->takeName(G);
499 G->eraseFromParent();
501 Initializers[i] = ConstantStruct::get(
503 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
504 ConstantInt::get(IntptrTy, SizeInBytes),
505 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
506 ConstantExpr::getPointerCast(Name, IntptrTy),
508 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
511 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
512 GlobalVariable *AllGlobals = new GlobalVariable(
513 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
514 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
516 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
517 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
518 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
520 IRB.CreateCall2(AsanRegisterGlobals,
521 IRB.CreatePointerCast(AllGlobals, IntptrTy),
522 ConstantInt::get(IntptrTy, n));
524 // We also need to unregister globals at the end, e.g. when a shared library
526 Function *AsanDtorFunction = Function::Create(
527 FunctionType::get(Type::getVoidTy(*C), false),
528 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
529 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
530 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
531 Function *AsanUnregisterGlobals =
532 checkInterfaceFunction(M.getOrInsertFunction(
533 kAsanUnregisterGlobalsName,
534 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
535 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
537 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
538 IRB.CreatePointerCast(AllGlobals, IntptrTy),
539 ConstantInt::get(IntptrTy, n));
540 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
547 bool AddressSanitizer::runOnModule(Module &M) {
548 // Initialize the private fields. No one has accessed them before.
549 TD = getAnalysisIfAvailable<TargetData>();
552 BL.reset(new FunctionBlackList(ClBlackListFile));
555 C = &(M.getContext());
556 LongSize = TD->getPointerSizeInBits();
557 IntptrTy = Type::getIntNTy(*C, LongSize);
558 IntptrPtrTy = PointerType::get(IntptrTy, 0);
560 AsanCtorFunction = Function::Create(
561 FunctionType::get(Type::getVoidTy(*C), false),
562 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
563 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
564 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
566 // call __asan_init in the module ctor.
567 IRBuilder<> IRB(CtorInsertBefore);
568 AsanInitFunction = checkInterfaceFunction(
569 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
570 AsanInitFunction->setLinkage(Function::ExternalLinkage);
571 IRB.CreateCall(AsanInitFunction);
573 MappingOffset = LongSize == 32
574 ? kDefaultShadowOffset32 : kDefaultShadowOffset64;
575 if (ClMappingOffsetLog >= 0) {
576 if (ClMappingOffsetLog == 0) {
580 MappingOffset = 1ULL << ClMappingOffsetLog;
583 MappingScale = kDefaultShadowScale;
584 if (ClMappingScale) {
585 MappingScale = ClMappingScale;
587 // Redzone used for stack and globals is at least 32 bytes.
588 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
589 RedzoneSize = std::max(32, (int)(1 << MappingScale));
594 Res |= insertGlobalRedzones(M);
596 if (ClMappingOffsetLog >= 0) {
597 // Tell the run-time the current values of mapping offset and scale.
598 GlobalValue *asan_mapping_offset =
599 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
600 ConstantInt::get(IntptrTy, MappingOffset),
601 kAsanMappingOffsetName);
602 // Read the global, otherwise it may be optimized away.
603 IRB.CreateLoad(asan_mapping_offset, true);
605 if (ClMappingScale) {
606 GlobalValue *asan_mapping_scale =
607 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
608 ConstantInt::get(IntptrTy, MappingScale),
609 kAsanMappingScaleName);
610 // Read the global, otherwise it may be optimized away.
611 IRB.CreateLoad(asan_mapping_scale, true);
615 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
616 if (F->isDeclaration()) continue;
617 Res |= handleFunction(M, *F);
620 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
625 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
626 // For each NSObject descendant having a +load method, this method is invoked
627 // by the ObjC runtime before any of the static constructors is called.
628 // Therefore we need to instrument such methods with a call to __asan_init
629 // at the beginning in order to initialize our runtime before any access to
630 // the shadow memory.
631 // We cannot just ignore these methods, because they may call other
632 // instrumented functions.
633 if (F.getName().find(" load]") != std::string::npos) {
634 IRBuilder<> IRB(F.begin()->begin());
635 IRB.CreateCall(AsanInitFunction);
641 bool AddressSanitizer::handleFunction(Module &M, Function &F) {
642 if (BL->isIn(F)) return false;
643 if (&F == AsanCtorFunction) return false;
645 // If needed, insert __asan_init before checking for AddressSafety attr.
646 maybeInsertAsanInitAtFunctionEntry(F);
648 if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
650 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
652 // We want to instrument every address only once per basic block
653 // (unless there are calls between uses).
654 SmallSet<Value*, 16> TempsToInstrument;
655 SmallVector<Instruction*, 16> ToInstrument;
656 SmallVector<Instruction*, 8> NoReturnCalls;
658 // Fill the set of memory operations to instrument.
659 for (Function::iterator FI = F.begin(), FE = F.end();
661 TempsToInstrument.clear();
662 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
664 if (LooksLikeCodeInBug11395(BI)) return false;
665 if ((isa<LoadInst>(BI) && ClInstrumentReads) ||
666 (isa<StoreInst>(BI) && ClInstrumentWrites)) {
667 Value *Addr = getLDSTOperand(BI);
668 if (ClOpt && ClOptSameTemp) {
669 if (!TempsToInstrument.insert(Addr))
670 continue; // We've seen this temp in the current BB.
672 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
675 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
677 TempsToInstrument.clear();
678 if (CI->doesNotReturn()) {
679 NoReturnCalls.push_back(CI);
684 ToInstrument.push_back(BI);
689 int NumInstrumented = 0;
690 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
691 Instruction *Inst = ToInstrument[i];
692 if (ClDebugMin < 0 || ClDebugMax < 0 ||
693 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
694 if (isa<StoreInst>(Inst) || isa<LoadInst>(Inst))
697 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
704 bool ChangedStack = poisonStackInFunction(M, F);
706 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
707 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
708 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
709 Instruction *CI = NoReturnCalls[i];
711 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
712 IRB.getVoidTy(), NULL));
715 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
718 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
719 if (ShadowRedzoneSize == 1) return PoisonByte;
720 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
721 if (ShadowRedzoneSize == 4)
722 return (PoisonByte << 24) + (PoisonByte << 16) +
723 (PoisonByte << 8) + (PoisonByte);
724 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
727 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
730 size_t ShadowGranularity,
732 for (size_t i = 0; i < RedzoneSize;
733 i+= ShadowGranularity, Shadow++) {
734 if (i + ShadowGranularity <= Size) {
735 *Shadow = 0; // fully addressable
736 } else if (i >= Size) {
737 *Shadow = Magic; // unaddressable
739 *Shadow = Size - i; // first Size-i bytes are addressable
744 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
746 Value *ShadowBase, bool DoPoison) {
747 size_t ShadowRZSize = RedzoneSize >> MappingScale;
748 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
749 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
750 Type *RZPtrTy = PointerType::get(RZTy, 0);
752 Value *PoisonLeft = ConstantInt::get(RZTy,
753 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
754 Value *PoisonMid = ConstantInt::get(RZTy,
755 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
756 Value *PoisonRight = ConstantInt::get(RZTy,
757 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
759 // poison the first red zone.
760 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
762 // poison all other red zones.
763 uint64_t Pos = RedzoneSize;
764 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
765 AllocaInst *AI = AllocaVec[i];
766 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
767 uint64_t AlignedSize = getAlignedAllocaSize(AI);
768 assert(AlignedSize - SizeInBytes < RedzoneSize);
773 assert(ShadowBase->getType() == IntptrTy);
774 if (SizeInBytes < AlignedSize) {
775 // Poison the partial redzone at right
777 ShadowBase, ConstantInt::get(IntptrTy,
778 (Pos >> MappingScale) - ShadowRZSize));
779 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
782 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
784 1ULL << MappingScale,
785 kAsanStackPartialRedzoneMagic);
787 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
788 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
791 // Poison the full redzone at right.
792 Ptr = IRB.CreateAdd(ShadowBase,
793 ConstantInt::get(IntptrTy, Pos >> MappingScale));
794 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
795 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
801 // Workaround for bug 11395: we don't want to instrument stack in functions
802 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
803 // FIXME: remove once the bug 11395 is fixed.
804 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
805 if (LongSize != 32) return false;
806 CallInst *CI = dyn_cast<CallInst>(I);
807 if (!CI || !CI->isInlineAsm()) return false;
808 if (CI->getNumArgOperands() <= 5) return false;
809 // We have inline assembly with quite a few arguments.
813 // Find all static Alloca instructions and put
814 // poisoned red zones around all of them.
815 // Then unpoison everything back before the function returns.
817 // Stack poisoning does not play well with exception handling.
818 // When an exception is thrown, we essentially bypass the code
819 // that unpoisones the stack. This is why the run-time library has
820 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
821 // stack in the interceptor. This however does not work inside the
822 // actual function which catches the exception. Most likely because the
823 // compiler hoists the load of the shadow value somewhere too high.
824 // This causes asan to report a non-existing bug on 453.povray.
825 // It sounds like an LLVM bug.
826 bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
827 if (!ClStack) return false;
828 SmallVector<AllocaInst*, 16> AllocaVec;
829 SmallVector<Instruction*, 8> RetVec;
830 uint64_t TotalSize = 0;
832 // Filter out Alloca instructions we want (and can) handle.
833 // Collect Ret instructions.
834 for (Function::iterator FI = F.begin(), FE = F.end();
836 BasicBlock &BB = *FI;
837 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
839 if (isa<ReturnInst>(BI)) {
840 RetVec.push_back(BI);
844 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
846 if (AI->isArrayAllocation()) continue;
847 if (!AI->isStaticAlloca()) continue;
848 if (!AI->getAllocatedType()->isSized()) continue;
849 if (AI->getAlignment() > RedzoneSize) continue;
850 AllocaVec.push_back(AI);
851 uint64_t AlignedSize = getAlignedAllocaSize(AI);
852 TotalSize += AlignedSize;
856 if (AllocaVec.empty()) return false;
858 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
860 bool DoStackMalloc = ClUseAfterReturn
861 && LocalStackSize <= kMaxStackMallocSize;
863 Instruction *InsBefore = AllocaVec[0];
864 IRBuilder<> IRB(InsBefore);
867 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
868 AllocaInst *MyAlloca =
869 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
870 MyAlloca->setAlignment(RedzoneSize);
871 assert(MyAlloca->isStaticAlloca());
872 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
873 Value *LocalStackBase = OrigStackBase;
876 Value *AsanStackMallocFunc = M.getOrInsertFunction(
877 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
878 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
879 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
882 // This string will be parsed by the run-time (DescribeStackAddress).
883 SmallString<2048> StackDescriptionStorage;
884 raw_svector_ostream StackDescription(StackDescriptionStorage);
885 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
887 uint64_t Pos = RedzoneSize;
888 // Replace Alloca instructions with base+offset.
889 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
890 AllocaInst *AI = AllocaVec[i];
891 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
892 StringRef Name = AI->getName();
893 StackDescription << Pos << " " << SizeInBytes << " "
894 << Name.size() << " " << Name << " ";
895 uint64_t AlignedSize = getAlignedAllocaSize(AI);
896 assert((AlignedSize % RedzoneSize) == 0);
897 AI->replaceAllUsesWith(
899 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
901 Pos += AlignedSize + RedzoneSize;
903 assert(Pos == LocalStackSize);
905 // Write the Magic value and the frame description constant to the redzone.
906 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
907 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
909 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
910 ConstantInt::get(IntptrTy, LongSize/8));
911 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
912 Value *Description = IRB.CreatePointerCast(
913 createPrivateGlobalForString(M, StackDescription.str()),
915 IRB.CreateStore(Description, BasePlus1);
917 // Poison the stack redzones at the entry.
918 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
919 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
921 Value *AsanStackFreeFunc = NULL;
923 AsanStackFreeFunc = M.getOrInsertFunction(
924 kAsanStackFreeName, IRB.getVoidTy(),
925 IntptrTy, IntptrTy, IntptrTy, NULL);
928 // Unpoison the stack before all ret instructions.
929 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
930 Instruction *Ret = RetVec[i];
931 IRBuilder<> IRBRet(Ret);
933 // Mark the current frame as retired.
934 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
936 // Unpoison the stack.
937 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
940 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
941 ConstantInt::get(IntptrTy, LocalStackSize),