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/ADT/Triple.h"
26 #include "llvm/Function.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/Module.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/DataTypes.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/IRBuilder.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;
51 static const uint64_t kDefaultShadowOffsetAndroid = 0;
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 *kAsanModuleDtorName = "asan.module_dtor";
59 static const int kAsanCtorAndCtorPriority = 1;
60 static const char *kAsanReportErrorTemplate = "__asan_report_";
61 static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
62 static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
63 static const char *kAsanInitName = "__asan_init";
64 static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
65 static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
66 static const char *kAsanMappingScaleName = "__asan_mapping_scale";
67 static const char *kAsanStackMallocName = "__asan_stack_malloc";
68 static const char *kAsanStackFreeName = "__asan_stack_free";
70 static const int kAsanStackLeftRedzoneMagic = 0xf1;
71 static const int kAsanStackMidRedzoneMagic = 0xf2;
72 static const int kAsanStackRightRedzoneMagic = 0xf3;
73 static const int kAsanStackPartialRedzoneMagic = 0xf4;
75 // Command-line flags.
77 // This flag may need to be replaced with -f[no-]asan-reads.
78 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
79 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
80 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
81 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
82 // This flag may need to be replaced with -f[no]asan-stack.
83 static cl::opt<bool> ClStack("asan-stack",
84 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
85 // This flag may need to be replaced with -f[no]asan-use-after-return.
86 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
87 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
88 // This flag may need to be replaced with -f[no]asan-globals.
89 static cl::opt<bool> ClGlobals("asan-globals",
90 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
91 static cl::opt<bool> ClMemIntrin("asan-memintrin",
92 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
93 // This flag may need to be replaced with -fasan-blacklist.
94 static cl::opt<std::string> ClBlackListFile("asan-blacklist",
95 cl::desc("File containing the list of functions to ignore "
96 "during instrumentation"), cl::Hidden);
98 // These flags allow to change the shadow mapping.
99 // The shadow mapping looks like
100 // Shadow = (Mem >> scale) + (1 << offset_log)
101 static cl::opt<int> ClMappingScale("asan-mapping-scale",
102 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
103 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
104 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
106 // Optimization flags. Not user visible, used mostly for testing
107 // and benchmarking the tool.
108 static cl::opt<bool> ClOpt("asan-opt",
109 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
110 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
111 cl::desc("Instrument the same temp just once"), cl::Hidden,
113 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
114 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
117 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
119 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
120 cl::Hidden, cl::init(0));
121 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
122 cl::Hidden, cl::desc("Debug func"));
123 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
124 cl::Hidden, cl::init(-1));
125 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
126 cl::Hidden, cl::init(-1));
130 /// AddressSanitizer: instrument the code in module to find memory bugs.
131 struct AddressSanitizer : public ModulePass {
133 virtual const char *getPassName() const;
134 void instrumentMop(Instruction *I);
135 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
136 Value *Addr, uint32_t TypeSize, bool IsWrite);
137 Instruction *generateCrashCode(IRBuilder<> &IRB, Value *Addr,
138 bool IsWrite, uint32_t TypeSize);
139 bool instrumentMemIntrinsic(MemIntrinsic *MI);
140 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
142 Instruction *InsertBefore, bool IsWrite);
143 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
144 bool handleFunction(Module &M, Function &F);
145 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
146 bool poisonStackInFunction(Module &M, Function &F);
147 virtual bool runOnModule(Module &M);
148 bool insertGlobalRedzones(Module &M);
149 BranchInst *splitBlockAndInsertIfThen(Instruction *SplitBefore, Value *Cmp);
150 static char ID; // Pass identification, replacement for typeid
154 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
155 Type *Ty = AI->getAllocatedType();
156 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
159 uint64_t getAlignedSize(uint64_t SizeInBytes) {
160 return ((SizeInBytes + RedzoneSize - 1)
161 / RedzoneSize) * RedzoneSize;
163 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
164 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
165 return getAlignedSize(SizeInBytes);
168 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
169 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
170 Value *ShadowBase, bool DoPoison);
171 bool LooksLikeCodeInBug11395(Instruction *I);
173 Module *CurrentModule;
176 uint64_t MappingOffset;
182 Function *AsanCtorFunction;
183 Function *AsanInitFunction;
184 Instruction *CtorInsertBefore;
185 OwningPtr<FunctionBlackList> BL;
189 char AddressSanitizer::ID = 0;
190 INITIALIZE_PASS(AddressSanitizer, "asan",
191 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
193 AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
194 ModulePass *llvm::createAddressSanitizerPass() {
195 return new AddressSanitizer();
198 const char *AddressSanitizer::getPassName() const {
199 return "AddressSanitizer";
202 // Create a constant for Str so that we can pass it to the run-time lib.
203 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
204 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
205 return new GlobalVariable(M, StrConst->getType(), true,
206 GlobalValue::PrivateLinkage, StrConst, "");
209 // Split the basic block and insert an if-then code.
221 // Returns the NewBasicBlock's terminator.
222 BranchInst *AddressSanitizer::splitBlockAndInsertIfThen(
223 Instruction *SplitBefore, Value *Cmp) {
224 BasicBlock *Head = SplitBefore->getParent();
225 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
226 TerminatorInst *HeadOldTerm = Head->getTerminator();
227 BasicBlock *NewBasicBlock =
228 BasicBlock::Create(*C, "", Head->getParent());
229 BranchInst *HeadNewTerm = BranchInst::Create(/*ifTrue*/NewBasicBlock,
232 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
234 BranchInst *CheckTerm = BranchInst::Create(Tail, NewBasicBlock);
238 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
240 Shadow = IRB.CreateLShr(Shadow, MappingScale);
241 if (MappingOffset == 0)
243 // (Shadow >> scale) | offset
244 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
248 void AddressSanitizer::instrumentMemIntrinsicParam(Instruction *OrigIns,
249 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
250 // Check the first byte.
252 IRBuilder<> IRB(InsertBefore);
253 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
255 // Check the last byte.
257 IRBuilder<> IRB(InsertBefore);
258 Value *SizeMinusOne = IRB.CreateSub(
259 Size, ConstantInt::get(Size->getType(), 1));
260 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
261 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
262 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
263 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
267 // Instrument memset/memmove/memcpy
268 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
269 Value *Dst = MI->getDest();
270 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
271 Value *Src = MemTran ? MemTran->getSource() : NULL;
272 Value *Length = MI->getLength();
274 Constant *ConstLength = dyn_cast<Constant>(Length);
275 Instruction *InsertBefore = MI;
277 if (ConstLength->isNullValue()) return false;
279 // The size is not a constant so it could be zero -- check at run-time.
280 IRBuilder<> IRB(InsertBefore);
282 Value *Cmp = IRB.CreateICmpNE(Length,
283 Constant::getNullValue(Length->getType()));
284 InsertBefore = splitBlockAndInsertIfThen(InsertBefore, Cmp);
287 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
289 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
293 static Value *getLDSTOperand(Instruction *I) {
294 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
295 return LI->getPointerOperand();
297 return cast<StoreInst>(*I).getPointerOperand();
300 void AddressSanitizer::instrumentMop(Instruction *I) {
301 int IsWrite = isa<StoreInst>(*I);
302 Value *Addr = getLDSTOperand(I);
303 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
304 // We are accessing a global scalar variable. Nothing to catch here.
307 Type *OrigPtrTy = Addr->getType();
308 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
310 assert(OrigTy->isSized());
311 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
313 if (TypeSize != 8 && TypeSize != 16 &&
314 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
315 // Ignore all unusual sizes.
320 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
323 // Validate the result of Module::getOrInsertFunction called for an interface
324 // function of AddressSanitizer. If the instrumented module defines a function
325 // with the same name, their prototypes must match, otherwise
326 // getOrInsertFunction returns a bitcast.
327 Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
328 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
329 FuncOrBitcast->dump();
330 report_fatal_error("trying to redefine an AddressSanitizer "
331 "interface function");
334 Instruction *AddressSanitizer::generateCrashCode(
335 IRBuilder<> &IRB, Value *Addr, bool IsWrite, uint32_t TypeSize) {
336 // IsWrite and TypeSize are encoded in the function name.
337 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
338 (IsWrite ? "store" : "load") + itostr(TypeSize / 8);
339 Value *ReportWarningFunc = CurrentModule->getOrInsertFunction(
340 FunctionName, IRB.getVoidTy(), IntptrTy, NULL);
341 CallInst *Call = IRB.CreateCall(ReportWarningFunc, Addr);
342 Call->setDoesNotReturn();
346 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
347 IRBuilder<> &IRB, Value *Addr,
348 uint32_t TypeSize, bool IsWrite) {
349 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
351 Type *ShadowTy = IntegerType::get(
352 *C, std::max(8U, TypeSize >> MappingScale));
353 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
354 Value *ShadowPtr = memToShadow(AddrLong, IRB);
355 Value *CmpVal = Constant::getNullValue(ShadowTy);
356 Value *ShadowValue = IRB.CreateLoad(
357 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
359 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
361 Instruction *CheckTerm = splitBlockAndInsertIfThen(
362 cast<Instruction>(Cmp)->getNextNode(), Cmp);
363 IRBuilder<> IRB2(CheckTerm);
365 size_t Granularity = 1 << MappingScale;
366 if (TypeSize < 8 * Granularity) {
367 // Addr & (Granularity - 1)
368 Value *LastAccessedByte = IRB2.CreateAnd(
369 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
370 // (Addr & (Granularity - 1)) + size - 1
371 if (TypeSize / 8 > 1)
372 LastAccessedByte = IRB2.CreateAdd(
373 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
374 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
375 LastAccessedByte = IRB2.CreateIntCast(
376 LastAccessedByte, IRB.getInt8Ty(), false);
377 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
378 Value *Cmp2 = IRB2.CreateICmpSGE(LastAccessedByte, ShadowValue);
380 CheckTerm = splitBlockAndInsertIfThen(CheckTerm, Cmp2);
383 IRBuilder<> IRB1(CheckTerm);
384 Instruction *Crash = generateCrashCode(IRB1, AddrLong, IsWrite, TypeSize);
385 Crash->setDebugLoc(OrigIns->getDebugLoc());
386 ReplaceInstWithInst(CheckTerm, new UnreachableInst(*C));
389 // This function replaces all global variables with new variables that have
390 // trailing redzones. It also creates a function that poisons
391 // redzones and inserts this function into llvm.global_ctors.
392 bool AddressSanitizer::insertGlobalRedzones(Module &M) {
393 SmallVector<GlobalVariable *, 16> GlobalsToChange;
395 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
396 E = M.getGlobalList().end(); G != E; ++G) {
397 Type *Ty = cast<PointerType>(G->getType())->getElementType();
398 DEBUG(dbgs() << "GLOBAL: " << *G);
400 if (!Ty->isSized()) continue;
401 if (!G->hasInitializer()) continue;
402 // Touch only those globals that will not be defined in other modules.
403 // Don't handle ODR type linkages since other modules may be built w/o asan.
404 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
405 G->getLinkage() != GlobalVariable::PrivateLinkage &&
406 G->getLinkage() != GlobalVariable::InternalLinkage)
408 // Two problems with thread-locals:
409 // - The address of the main thread's copy can't be computed at link-time.
410 // - Need to poison all copies, not just the main thread's one.
411 if (G->isThreadLocal())
413 // For now, just ignore this Alloca if the alignment is large.
414 if (G->getAlignment() > RedzoneSize) continue;
416 // Ignore all the globals with the names starting with "\01L_OBJC_".
417 // Many of those are put into the .cstring section. The linker compresses
418 // that section by removing the spare \0s after the string terminator, so
419 // our redzones get broken.
420 if ((G->getName().find("\01L_OBJC_") == 0) ||
421 (G->getName().find("\01l_OBJC_") == 0)) {
422 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
426 if (G->hasSection()) {
427 StringRef Section(G->getSection());
428 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
429 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
431 if ((Section.find("__OBJC,") == 0) ||
432 (Section.find("__DATA, __objc_") == 0)) {
433 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
436 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
437 // Constant CFString instances are compiled in the following way:
438 // -- the string buffer is emitted into
439 // __TEXT,__cstring,cstring_literals
440 // -- the constant NSConstantString structure referencing that buffer
441 // is placed into __DATA,__cfstring
442 // Therefore there's no point in placing redzones into __DATA,__cfstring.
443 // Moreover, it causes the linker to crash on OS X 10.7
444 if (Section.find("__DATA,__cfstring") == 0) {
445 DEBUG(dbgs() << "Ignoring CFString: " << *G);
450 GlobalsToChange.push_back(G);
453 size_t n = GlobalsToChange.size();
454 if (n == 0) return false;
456 // A global is described by a structure
459 // size_t size_with_redzone;
461 // We initialize an array of such structures and pass it to a run-time call.
462 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
463 IntptrTy, IntptrTy, NULL);
464 SmallVector<Constant *, 16> Initializers(n);
466 IRBuilder<> IRB(CtorInsertBefore);
468 for (size_t i = 0; i < n; i++) {
469 GlobalVariable *G = GlobalsToChange[i];
470 PointerType *PtrTy = cast<PointerType>(G->getType());
471 Type *Ty = PtrTy->getElementType();
472 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
473 uint64_t RightRedzoneSize = RedzoneSize +
474 (RedzoneSize - (SizeInBytes % RedzoneSize));
475 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
477 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
478 Constant *NewInitializer = ConstantStruct::get(
479 NewTy, G->getInitializer(),
480 Constant::getNullValue(RightRedZoneTy), NULL);
482 SmallString<2048> DescriptionOfGlobal = G->getName();
483 DescriptionOfGlobal += " (";
484 DescriptionOfGlobal += M.getModuleIdentifier();
485 DescriptionOfGlobal += ")";
486 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
488 // Create a new global variable with enough space for a redzone.
489 GlobalVariable *NewGlobal = new GlobalVariable(
490 M, NewTy, G->isConstant(), G->getLinkage(),
491 NewInitializer, "", G, G->isThreadLocal());
492 NewGlobal->copyAttributesFrom(G);
493 NewGlobal->setAlignment(RedzoneSize);
496 Indices2[0] = IRB.getInt32(0);
497 Indices2[1] = IRB.getInt32(0);
499 G->replaceAllUsesWith(
500 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
501 NewGlobal->takeName(G);
502 G->eraseFromParent();
504 Initializers[i] = ConstantStruct::get(
506 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
507 ConstantInt::get(IntptrTy, SizeInBytes),
508 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
509 ConstantExpr::getPointerCast(Name, IntptrTy),
511 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
514 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
515 GlobalVariable *AllGlobals = new GlobalVariable(
516 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
517 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
519 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
520 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
521 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
523 IRB.CreateCall2(AsanRegisterGlobals,
524 IRB.CreatePointerCast(AllGlobals, IntptrTy),
525 ConstantInt::get(IntptrTy, n));
527 // We also need to unregister globals at the end, e.g. when a shared library
529 Function *AsanDtorFunction = Function::Create(
530 FunctionType::get(Type::getVoidTy(*C), false),
531 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
532 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
533 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
534 Function *AsanUnregisterGlobals =
535 checkInterfaceFunction(M.getOrInsertFunction(
536 kAsanUnregisterGlobalsName,
537 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
538 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
540 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
541 IRB.CreatePointerCast(AllGlobals, IntptrTy),
542 ConstantInt::get(IntptrTy, n));
543 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
550 bool AddressSanitizer::runOnModule(Module &M) {
551 // Initialize the private fields. No one has accessed them before.
552 TD = getAnalysisIfAvailable<TargetData>();
555 BL.reset(new FunctionBlackList(ClBlackListFile));
558 C = &(M.getContext());
559 LongSize = TD->getPointerSizeInBits();
560 IntptrTy = Type::getIntNTy(*C, LongSize);
561 IntptrPtrTy = PointerType::get(IntptrTy, 0);
563 AsanCtorFunction = Function::Create(
564 FunctionType::get(Type::getVoidTy(*C), false),
565 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
566 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
567 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
569 // call __asan_init in the module ctor.
570 IRBuilder<> IRB(CtorInsertBefore);
571 AsanInitFunction = checkInterfaceFunction(
572 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
573 AsanInitFunction->setLinkage(Function::ExternalLinkage);
574 IRB.CreateCall(AsanInitFunction);
576 llvm::Triple targetTriple(M.getTargetTriple());
577 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
579 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
580 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
581 if (ClMappingOffsetLog >= 0) {
582 if (ClMappingOffsetLog == 0) {
586 MappingOffset = 1ULL << ClMappingOffsetLog;
589 MappingScale = kDefaultShadowScale;
590 if (ClMappingScale) {
591 MappingScale = ClMappingScale;
593 // Redzone used for stack and globals is at least 32 bytes.
594 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
595 RedzoneSize = std::max(32, (int)(1 << MappingScale));
600 Res |= insertGlobalRedzones(M);
602 if (ClMappingOffsetLog >= 0) {
603 // Tell the run-time the current values of mapping offset and scale.
604 GlobalValue *asan_mapping_offset =
605 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
606 ConstantInt::get(IntptrTy, MappingOffset),
607 kAsanMappingOffsetName);
608 // Read the global, otherwise it may be optimized away.
609 IRB.CreateLoad(asan_mapping_offset, true);
611 if (ClMappingScale) {
612 GlobalValue *asan_mapping_scale =
613 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
614 ConstantInt::get(IntptrTy, MappingScale),
615 kAsanMappingScaleName);
616 // Read the global, otherwise it may be optimized away.
617 IRB.CreateLoad(asan_mapping_scale, true);
621 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
622 if (F->isDeclaration()) continue;
623 Res |= handleFunction(M, *F);
626 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
631 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
632 // For each NSObject descendant having a +load method, this method is invoked
633 // by the ObjC runtime before any of the static constructors is called.
634 // Therefore we need to instrument such methods with a call to __asan_init
635 // at the beginning in order to initialize our runtime before any access to
636 // the shadow memory.
637 // We cannot just ignore these methods, because they may call other
638 // instrumented functions.
639 if (F.getName().find(" load]") != std::string::npos) {
640 IRBuilder<> IRB(F.begin()->begin());
641 IRB.CreateCall(AsanInitFunction);
647 bool AddressSanitizer::handleFunction(Module &M, Function &F) {
648 if (BL->isIn(F)) return false;
649 if (&F == AsanCtorFunction) return false;
651 // If needed, insert __asan_init before checking for AddressSafety attr.
652 maybeInsertAsanInitAtFunctionEntry(F);
654 if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
656 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
658 // We want to instrument every address only once per basic block
659 // (unless there are calls between uses).
660 SmallSet<Value*, 16> TempsToInstrument;
661 SmallVector<Instruction*, 16> ToInstrument;
662 SmallVector<Instruction*, 8> NoReturnCalls;
664 // Fill the set of memory operations to instrument.
665 for (Function::iterator FI = F.begin(), FE = F.end();
667 TempsToInstrument.clear();
668 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
670 if (LooksLikeCodeInBug11395(BI)) return false;
671 if ((isa<LoadInst>(BI) && ClInstrumentReads) ||
672 (isa<StoreInst>(BI) && ClInstrumentWrites)) {
673 Value *Addr = getLDSTOperand(BI);
674 if (ClOpt && ClOptSameTemp) {
675 if (!TempsToInstrument.insert(Addr))
676 continue; // We've seen this temp in the current BB.
678 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
681 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
683 TempsToInstrument.clear();
684 if (CI->doesNotReturn()) {
685 NoReturnCalls.push_back(CI);
690 ToInstrument.push_back(BI);
695 int NumInstrumented = 0;
696 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
697 Instruction *Inst = ToInstrument[i];
698 if (ClDebugMin < 0 || ClDebugMax < 0 ||
699 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
700 if (isa<StoreInst>(Inst) || isa<LoadInst>(Inst))
703 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
710 bool ChangedStack = poisonStackInFunction(M, F);
712 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
713 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
714 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
715 Instruction *CI = NoReturnCalls[i];
717 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
718 IRB.getVoidTy(), NULL));
721 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
724 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
725 if (ShadowRedzoneSize == 1) return PoisonByte;
726 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
727 if (ShadowRedzoneSize == 4)
728 return (PoisonByte << 24) + (PoisonByte << 16) +
729 (PoisonByte << 8) + (PoisonByte);
730 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
733 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
736 size_t ShadowGranularity,
738 for (size_t i = 0; i < RedzoneSize;
739 i+= ShadowGranularity, Shadow++) {
740 if (i + ShadowGranularity <= Size) {
741 *Shadow = 0; // fully addressable
742 } else if (i >= Size) {
743 *Shadow = Magic; // unaddressable
745 *Shadow = Size - i; // first Size-i bytes are addressable
750 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
752 Value *ShadowBase, bool DoPoison) {
753 size_t ShadowRZSize = RedzoneSize >> MappingScale;
754 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
755 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
756 Type *RZPtrTy = PointerType::get(RZTy, 0);
758 Value *PoisonLeft = ConstantInt::get(RZTy,
759 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
760 Value *PoisonMid = ConstantInt::get(RZTy,
761 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
762 Value *PoisonRight = ConstantInt::get(RZTy,
763 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
765 // poison the first red zone.
766 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
768 // poison all other red zones.
769 uint64_t Pos = RedzoneSize;
770 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
771 AllocaInst *AI = AllocaVec[i];
772 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
773 uint64_t AlignedSize = getAlignedAllocaSize(AI);
774 assert(AlignedSize - SizeInBytes < RedzoneSize);
779 assert(ShadowBase->getType() == IntptrTy);
780 if (SizeInBytes < AlignedSize) {
781 // Poison the partial redzone at right
783 ShadowBase, ConstantInt::get(IntptrTy,
784 (Pos >> MappingScale) - ShadowRZSize));
785 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
788 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
790 1ULL << MappingScale,
791 kAsanStackPartialRedzoneMagic);
793 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
794 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
797 // Poison the full redzone at right.
798 Ptr = IRB.CreateAdd(ShadowBase,
799 ConstantInt::get(IntptrTy, Pos >> MappingScale));
800 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
801 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
807 // Workaround for bug 11395: we don't want to instrument stack in functions
808 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
809 // FIXME: remove once the bug 11395 is fixed.
810 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
811 if (LongSize != 32) return false;
812 CallInst *CI = dyn_cast<CallInst>(I);
813 if (!CI || !CI->isInlineAsm()) return false;
814 if (CI->getNumArgOperands() <= 5) return false;
815 // We have inline assembly with quite a few arguments.
819 // Find all static Alloca instructions and put
820 // poisoned red zones around all of them.
821 // Then unpoison everything back before the function returns.
823 // Stack poisoning does not play well with exception handling.
824 // When an exception is thrown, we essentially bypass the code
825 // that unpoisones the stack. This is why the run-time library has
826 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
827 // stack in the interceptor. This however does not work inside the
828 // actual function which catches the exception. Most likely because the
829 // compiler hoists the load of the shadow value somewhere too high.
830 // This causes asan to report a non-existing bug on 453.povray.
831 // It sounds like an LLVM bug.
832 bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
833 if (!ClStack) return false;
834 SmallVector<AllocaInst*, 16> AllocaVec;
835 SmallVector<Instruction*, 8> RetVec;
836 uint64_t TotalSize = 0;
838 // Filter out Alloca instructions we want (and can) handle.
839 // Collect Ret instructions.
840 for (Function::iterator FI = F.begin(), FE = F.end();
842 BasicBlock &BB = *FI;
843 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
845 if (isa<ReturnInst>(BI)) {
846 RetVec.push_back(BI);
850 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
852 if (AI->isArrayAllocation()) continue;
853 if (!AI->isStaticAlloca()) continue;
854 if (!AI->getAllocatedType()->isSized()) continue;
855 if (AI->getAlignment() > RedzoneSize) continue;
856 AllocaVec.push_back(AI);
857 uint64_t AlignedSize = getAlignedAllocaSize(AI);
858 TotalSize += AlignedSize;
862 if (AllocaVec.empty()) return false;
864 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
866 bool DoStackMalloc = ClUseAfterReturn
867 && LocalStackSize <= kMaxStackMallocSize;
869 Instruction *InsBefore = AllocaVec[0];
870 IRBuilder<> IRB(InsBefore);
873 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
874 AllocaInst *MyAlloca =
875 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
876 MyAlloca->setAlignment(RedzoneSize);
877 assert(MyAlloca->isStaticAlloca());
878 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
879 Value *LocalStackBase = OrigStackBase;
882 Value *AsanStackMallocFunc = M.getOrInsertFunction(
883 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
884 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
885 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
888 // This string will be parsed by the run-time (DescribeStackAddress).
889 SmallString<2048> StackDescriptionStorage;
890 raw_svector_ostream StackDescription(StackDescriptionStorage);
891 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
893 uint64_t Pos = RedzoneSize;
894 // Replace Alloca instructions with base+offset.
895 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
896 AllocaInst *AI = AllocaVec[i];
897 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
898 StringRef Name = AI->getName();
899 StackDescription << Pos << " " << SizeInBytes << " "
900 << Name.size() << " " << Name << " ";
901 uint64_t AlignedSize = getAlignedAllocaSize(AI);
902 assert((AlignedSize % RedzoneSize) == 0);
903 AI->replaceAllUsesWith(
905 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
907 Pos += AlignedSize + RedzoneSize;
909 assert(Pos == LocalStackSize);
911 // Write the Magic value and the frame description constant to the redzone.
912 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
913 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
915 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
916 ConstantInt::get(IntptrTy, LongSize/8));
917 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
918 Value *Description = IRB.CreatePointerCast(
919 createPrivateGlobalForString(M, StackDescription.str()),
921 IRB.CreateStore(Description, BasePlus1);
923 // Poison the stack redzones at the entry.
924 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
925 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
927 Value *AsanStackFreeFunc = NULL;
929 AsanStackFreeFunc = M.getOrInsertFunction(
930 kAsanStackFreeName, IRB.getVoidTy(),
931 IntptrTy, IntptrTy, IntptrTy, NULL);
934 // Unpoison the stack before all ret instructions.
935 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
936 Instruction *Ret = RetVec[i];
937 IRBuilder<> IRBRet(Ret);
939 // Mark the current frame as retired.
940 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
942 // Unpoison the stack.
943 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
946 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
947 ConstantInt::get(IntptrTy, LocalStackSize),