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/Function.h"
20 #include "llvm/IRBuilder.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/Type.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/OwningPtr.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/DataTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Support/system_error.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Transforms/Instrumentation.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/ModuleUtils.h"
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 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
76 static const size_t kNumberOfAccessSizes = 5;
78 // Command-line flags.
80 // This flag may need to be replaced with -f[no-]asan-reads.
81 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
82 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
83 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
84 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
85 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
86 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
87 cl::Hidden, cl::init(true));
88 static cl::opt<bool> ClMergeCallbacks("asan-merge-callbacks",
89 cl::desc("merge __asan_report_ callbacks to create fewer BBs"),
90 cl::Hidden, cl::init(false));
91 // This flag limits the number of instructions to be instrumented
92 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
93 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
95 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
97 cl::desc("maximal number of instructions to instrument in any given BB"),
99 // This flag may need to be replaced with -f[no]asan-stack.
100 static cl::opt<bool> ClStack("asan-stack",
101 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
102 // This flag may need to be replaced with -f[no]asan-use-after-return.
103 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
104 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
105 // This flag may need to be replaced with -f[no]asan-globals.
106 static cl::opt<bool> ClGlobals("asan-globals",
107 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
108 static cl::opt<bool> ClMemIntrin("asan-memintrin",
109 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
110 // This flag may need to be replaced with -fasan-blacklist.
111 static cl::opt<std::string> ClBlackListFile("asan-blacklist",
112 cl::desc("File containing the list of functions to ignore "
113 "during instrumentation"), cl::Hidden);
115 // These flags allow to change the shadow mapping.
116 // The shadow mapping looks like
117 // Shadow = (Mem >> scale) + (1 << offset_log)
118 static cl::opt<int> ClMappingScale("asan-mapping-scale",
119 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
120 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
121 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
123 // Optimization flags. Not user visible, used mostly for testing
124 // and benchmarking the tool.
125 static cl::opt<bool> ClOpt("asan-opt",
126 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
127 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
128 cl::desc("Instrument the same temp just once"), cl::Hidden,
130 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
131 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
134 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
136 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
137 cl::Hidden, cl::init(0));
138 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
139 cl::Hidden, cl::desc("Debug func"));
140 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
141 cl::Hidden, cl::init(-1));
142 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
143 cl::Hidden, cl::init(-1));
147 /// When the crash callbacks are merged, they receive some amount of arguments
148 /// that are merged in a PHI node. This struct represents arguments from one
155 /// An object of this type is created while instrumenting every function.
156 struct AsanFunctionContext {
157 AsanFunctionContext(Function &Function) : F(Function), CrashBlock() { }
160 // These are initially zero. If we require at least one call to
161 // __asan_report_{read,write}{1,2,4,8,16}, an appropriate BB is created.
162 BasicBlock *CrashBlock[2][kNumberOfAccessSizes];
163 typedef SmallVector<CrashArg, 8> CrashArgsVec;
164 CrashArgsVec CrashArgs[2][kNumberOfAccessSizes];
167 /// AddressSanitizer: instrument the code in module to find memory bugs.
168 struct AddressSanitizer : public ModulePass {
170 virtual const char *getPassName() const;
171 void instrumentMop(AsanFunctionContext &AFC, Instruction *I);
172 void instrumentAddress(AsanFunctionContext &AFC,
173 Instruction *OrigIns, IRBuilder<> &IRB,
174 Value *Addr, uint32_t TypeSize, bool IsWrite);
175 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
176 Value *ShadowValue, uint32_t TypeSize);
177 Instruction *generateCrashCode(BasicBlock *BB, Value *Addr, Value *PC,
178 bool IsWrite, size_t AccessSizeIndex);
179 bool instrumentMemIntrinsic(AsanFunctionContext &AFC, MemIntrinsic *MI);
180 void instrumentMemIntrinsicParam(AsanFunctionContext &AFC,
181 Instruction *OrigIns, Value *Addr,
183 Instruction *InsertBefore, bool IsWrite);
184 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
185 bool handleFunction(Module &M, Function &F);
186 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
187 bool poisonStackInFunction(Module &M, Function &F);
188 virtual bool runOnModule(Module &M);
189 bool insertGlobalRedzones(Module &M);
190 static char ID; // Pass identification, replacement for typeid
194 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
195 Type *Ty = AI->getAllocatedType();
196 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
199 uint64_t getAlignedSize(uint64_t SizeInBytes) {
200 return ((SizeInBytes + RedzoneSize - 1)
201 / RedzoneSize) * RedzoneSize;
203 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
204 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
205 return getAlignedSize(SizeInBytes);
208 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
209 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
210 Value *ShadowBase, bool DoPoison);
211 bool LooksLikeCodeInBug11395(Instruction *I);
215 uint64_t MappingOffset;
221 Function *AsanCtorFunction;
222 Function *AsanInitFunction;
223 Instruction *CtorInsertBefore;
224 OwningPtr<FunctionBlackList> BL;
225 // This array is indexed by AccessIsWrite and log2(AccessSize).
226 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
231 char AddressSanitizer::ID = 0;
232 INITIALIZE_PASS(AddressSanitizer, "asan",
233 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
235 AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
236 ModulePass *llvm::createAddressSanitizerPass() {
237 return new AddressSanitizer();
240 const char *AddressSanitizer::getPassName() const {
241 return "AddressSanitizer";
244 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
245 size_t Res = CountTrailingZeros_32(TypeSize / 8);
246 assert(Res < kNumberOfAccessSizes);
250 // Create a constant for Str so that we can pass it to the run-time lib.
251 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
252 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
253 return new GlobalVariable(M, StrConst->getType(), true,
254 GlobalValue::PrivateLinkage, StrConst, "");
257 // Split the basic block and insert an if-then code.
268 // If ThenBlock is zero, a new block is created and its terminator is returned.
269 // Otherwize 0 is returned.
270 static BranchInst *splitBlockAndInsertIfThen(Value *Cmp,
271 BasicBlock *ThenBlock = 0) {
272 Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode();
273 BasicBlock *Head = SplitBefore->getParent();
274 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
275 TerminatorInst *HeadOldTerm = Head->getTerminator();
276 BranchInst *CheckTerm = 0;
278 LLVMContext &C = Head->getParent()->getParent()->getContext();
279 ThenBlock = BasicBlock::Create(C, "", Head->getParent());
280 CheckTerm = BranchInst::Create(Tail, ThenBlock);
282 BranchInst *HeadNewTerm =
283 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
284 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
289 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
291 Shadow = IRB.CreateLShr(Shadow, MappingScale);
292 if (MappingOffset == 0)
294 // (Shadow >> scale) | offset
295 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
299 void AddressSanitizer::instrumentMemIntrinsicParam(
300 AsanFunctionContext &AFC, Instruction *OrigIns,
301 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
302 // Check the first byte.
304 IRBuilder<> IRB(InsertBefore);
305 instrumentAddress(AFC, OrigIns, IRB, Addr, 8, IsWrite);
307 // Check the last byte.
309 IRBuilder<> IRB(InsertBefore);
310 Value *SizeMinusOne = IRB.CreateSub(
311 Size, ConstantInt::get(Size->getType(), 1));
312 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
313 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
314 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
315 instrumentAddress(AFC, OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
319 // Instrument memset/memmove/memcpy
320 bool AddressSanitizer::instrumentMemIntrinsic(AsanFunctionContext &AFC,
322 Value *Dst = MI->getDest();
323 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
324 Value *Src = MemTran ? MemTran->getSource() : 0;
325 Value *Length = MI->getLength();
327 Constant *ConstLength = dyn_cast<Constant>(Length);
328 Instruction *InsertBefore = MI;
330 if (ConstLength->isNullValue()) return false;
332 // The size is not a constant so it could be zero -- check at run-time.
333 IRBuilder<> IRB(InsertBefore);
335 Value *Cmp = IRB.CreateICmpNE(Length,
336 Constant::getNullValue(Length->getType()));
337 InsertBefore = splitBlockAndInsertIfThen(Cmp);
340 instrumentMemIntrinsicParam(AFC, MI, Dst, Length, InsertBefore, true);
342 instrumentMemIntrinsicParam(AFC, MI, Src, Length, InsertBefore, false);
346 // If I is an interesting memory access, return the PointerOperand
347 // and set IsWrite. Otherwise return NULL.
348 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
349 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
350 if (!ClInstrumentReads) return NULL;
352 return LI->getPointerOperand();
354 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
355 if (!ClInstrumentWrites) return NULL;
357 return SI->getPointerOperand();
359 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
360 if (!ClInstrumentAtomics) return NULL;
362 return RMW->getPointerOperand();
364 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
365 if (!ClInstrumentAtomics) return NULL;
367 return XCHG->getPointerOperand();
372 void AddressSanitizer::instrumentMop(AsanFunctionContext &AFC, Instruction *I) {
374 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
376 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
377 // We are accessing a global scalar variable. Nothing to catch here.
380 Type *OrigPtrTy = Addr->getType();
381 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
383 assert(OrigTy->isSized());
384 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
386 if (TypeSize != 8 && TypeSize != 16 &&
387 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
388 // Ignore all unusual sizes.
393 instrumentAddress(AFC, I, IRB, Addr, TypeSize, IsWrite);
396 // Validate the result of Module::getOrInsertFunction called for an interface
397 // function of AddressSanitizer. If the instrumented module defines a function
398 // with the same name, their prototypes must match, otherwise
399 // getOrInsertFunction returns a bitcast.
400 Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
401 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
402 FuncOrBitcast->dump();
403 report_fatal_error("trying to redefine an AddressSanitizer "
404 "interface function");
407 Instruction *AddressSanitizer::generateCrashCode(
408 BasicBlock *BB, Value *Addr, Value *PC,
409 bool IsWrite, size_t AccessSizeIndex) {
410 IRBuilder<> IRB(BB->getFirstNonPHI());
413 Call = IRB.CreateCall2(AsanErrorCallback[IsWrite][AccessSizeIndex],
416 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
417 Call->setDoesNotReturn();
421 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
424 size_t Granularity = 1 << MappingScale;
425 // Addr & (Granularity - 1)
426 Value *LastAccessedByte = IRB.CreateAnd(
427 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
428 // (Addr & (Granularity - 1)) + size - 1
429 if (TypeSize / 8 > 1)
430 LastAccessedByte = IRB.CreateAdd(
431 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
432 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
433 LastAccessedByte = IRB.CreateIntCast(
434 LastAccessedByte, IRB.getInt8Ty(), false);
435 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
436 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
439 void AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
440 Instruction *OrigIns,
441 IRBuilder<> &IRB, Value *Addr,
442 uint32_t TypeSize, bool IsWrite) {
443 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
445 Type *ShadowTy = IntegerType::get(
446 *C, std::max(8U, TypeSize >> MappingScale));
447 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
448 Value *ShadowPtr = memToShadow(AddrLong, IRB);
449 Value *CmpVal = Constant::getNullValue(ShadowTy);
450 Value *ShadowValue = IRB.CreateLoad(
451 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
453 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
455 BasicBlock *CrashBlock = 0;
456 if (ClMergeCallbacks) {
457 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
458 BasicBlock **Cached = &AFC.CrashBlock[IsWrite][AccessSizeIndex];
460 std::string BBName("crash_bb-");
461 BBName += (IsWrite ? "w-" : "r-") + itostr(1 << AccessSizeIndex);
462 BasicBlock *BB = BasicBlock::Create(*C, BBName, &AFC.F);
463 new UnreachableInst(*C, BB);
466 CrashBlock = *Cached;
467 // We need to pass the PC as the second parameter to __asan_report_*.
468 // There are few problems:
469 // - Some architectures (e.g. x86_32) don't have a cheap way to get the PC.
470 // - LLVM doesn't have the appropriate intrinsic.
471 // For now, put a random number into the PC, just to allow experiments.
472 Value *PC = ConstantInt::get(IntptrTy, rand());
473 CrashArg Arg = {AddrLong, PC};
474 AFC.CrashArgs[IsWrite][AccessSizeIndex].push_back(Arg);
476 CrashBlock = BasicBlock::Create(*C, "crash_bb", &AFC.F);
477 new UnreachableInst(*C, CrashBlock);
478 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
480 generateCrashCode(CrashBlock, AddrLong, 0, IsWrite, AccessSizeIndex);
481 Crash->setDebugLoc(OrigIns->getDebugLoc());
484 size_t Granularity = 1 << MappingScale;
485 if (TypeSize < 8 * Granularity) {
486 Instruction *CheckTerm = splitBlockAndInsertIfThen(Cmp);
487 IRB.SetInsertPoint(CheckTerm);
488 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
489 splitBlockAndInsertIfThen(Cmp2, CrashBlock);
491 splitBlockAndInsertIfThen(Cmp, CrashBlock);
495 // This function replaces all global variables with new variables that have
496 // trailing redzones. It also creates a function that poisons
497 // redzones and inserts this function into llvm.global_ctors.
498 bool AddressSanitizer::insertGlobalRedzones(Module &M) {
499 SmallVector<GlobalVariable *, 16> GlobalsToChange;
501 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
502 E = M.getGlobalList().end(); G != E; ++G) {
503 Type *Ty = cast<PointerType>(G->getType())->getElementType();
504 DEBUG(dbgs() << "GLOBAL: " << *G);
506 if (!Ty->isSized()) continue;
507 if (!G->hasInitializer()) continue;
508 // Touch only those globals that will not be defined in other modules.
509 // Don't handle ODR type linkages since other modules may be built w/o asan.
510 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
511 G->getLinkage() != GlobalVariable::PrivateLinkage &&
512 G->getLinkage() != GlobalVariable::InternalLinkage)
514 // Two problems with thread-locals:
515 // - The address of the main thread's copy can't be computed at link-time.
516 // - Need to poison all copies, not just the main thread's one.
517 if (G->isThreadLocal())
519 // For now, just ignore this Alloca if the alignment is large.
520 if (G->getAlignment() > RedzoneSize) continue;
522 // Ignore all the globals with the names starting with "\01L_OBJC_".
523 // Many of those are put into the .cstring section. The linker compresses
524 // that section by removing the spare \0s after the string terminator, so
525 // our redzones get broken.
526 if ((G->getName().find("\01L_OBJC_") == 0) ||
527 (G->getName().find("\01l_OBJC_") == 0)) {
528 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
532 if (G->hasSection()) {
533 StringRef Section(G->getSection());
534 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
535 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
537 if ((Section.find("__OBJC,") == 0) ||
538 (Section.find("__DATA, __objc_") == 0)) {
539 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
542 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
543 // Constant CFString instances are compiled in the following way:
544 // -- the string buffer is emitted into
545 // __TEXT,__cstring,cstring_literals
546 // -- the constant NSConstantString structure referencing that buffer
547 // is placed into __DATA,__cfstring
548 // Therefore there's no point in placing redzones into __DATA,__cfstring.
549 // Moreover, it causes the linker to crash on OS X 10.7
550 if (Section.find("__DATA,__cfstring") == 0) {
551 DEBUG(dbgs() << "Ignoring CFString: " << *G);
556 GlobalsToChange.push_back(G);
559 size_t n = GlobalsToChange.size();
560 if (n == 0) return false;
562 // A global is described by a structure
565 // size_t size_with_redzone;
567 // We initialize an array of such structures and pass it to a run-time call.
568 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
569 IntptrTy, IntptrTy, NULL);
570 SmallVector<Constant *, 16> Initializers(n);
572 IRBuilder<> IRB(CtorInsertBefore);
574 for (size_t i = 0; i < n; i++) {
575 GlobalVariable *G = GlobalsToChange[i];
576 PointerType *PtrTy = cast<PointerType>(G->getType());
577 Type *Ty = PtrTy->getElementType();
578 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
579 uint64_t RightRedzoneSize = RedzoneSize +
580 (RedzoneSize - (SizeInBytes % RedzoneSize));
581 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
583 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
584 Constant *NewInitializer = ConstantStruct::get(
585 NewTy, G->getInitializer(),
586 Constant::getNullValue(RightRedZoneTy), NULL);
588 SmallString<2048> DescriptionOfGlobal = G->getName();
589 DescriptionOfGlobal += " (";
590 DescriptionOfGlobal += M.getModuleIdentifier();
591 DescriptionOfGlobal += ")";
592 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
594 // Create a new global variable with enough space for a redzone.
595 GlobalVariable *NewGlobal = new GlobalVariable(
596 M, NewTy, G->isConstant(), G->getLinkage(),
597 NewInitializer, "", G, G->getThreadLocalMode());
598 NewGlobal->copyAttributesFrom(G);
599 NewGlobal->setAlignment(RedzoneSize);
602 Indices2[0] = IRB.getInt32(0);
603 Indices2[1] = IRB.getInt32(0);
605 G->replaceAllUsesWith(
606 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
607 NewGlobal->takeName(G);
608 G->eraseFromParent();
610 Initializers[i] = ConstantStruct::get(
612 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
613 ConstantInt::get(IntptrTy, SizeInBytes),
614 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
615 ConstantExpr::getPointerCast(Name, IntptrTy),
617 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
620 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
621 GlobalVariable *AllGlobals = new GlobalVariable(
622 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
623 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
625 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
626 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
627 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
629 IRB.CreateCall2(AsanRegisterGlobals,
630 IRB.CreatePointerCast(AllGlobals, IntptrTy),
631 ConstantInt::get(IntptrTy, n));
633 // We also need to unregister globals at the end, e.g. when a shared library
635 Function *AsanDtorFunction = Function::Create(
636 FunctionType::get(Type::getVoidTy(*C), false),
637 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
638 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
639 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
640 Function *AsanUnregisterGlobals =
641 checkInterfaceFunction(M.getOrInsertFunction(
642 kAsanUnregisterGlobalsName,
643 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
644 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
646 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
647 IRB.CreatePointerCast(AllGlobals, IntptrTy),
648 ConstantInt::get(IntptrTy, n));
649 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
656 bool AddressSanitizer::runOnModule(Module &M) {
657 // Initialize the private fields. No one has accessed them before.
658 TD = getAnalysisIfAvailable<TargetData>();
661 BL.reset(new FunctionBlackList(ClBlackListFile));
663 C = &(M.getContext());
664 LongSize = TD->getPointerSizeInBits();
665 IntptrTy = Type::getIntNTy(*C, LongSize);
666 IntptrPtrTy = PointerType::get(IntptrTy, 0);
668 AsanCtorFunction = Function::Create(
669 FunctionType::get(Type::getVoidTy(*C), false),
670 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
671 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
672 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
674 // call __asan_init in the module ctor.
675 IRBuilder<> IRB(CtorInsertBefore);
676 AsanInitFunction = checkInterfaceFunction(
677 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
678 AsanInitFunction->setLinkage(Function::ExternalLinkage);
679 IRB.CreateCall(AsanInitFunction);
681 // Create __asan_report* callbacks.
682 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
683 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
685 // IsWrite and TypeSize are encoded in the function name.
686 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
687 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
688 // If we are merging crash callbacks, they have two parameters.
689 if (ClMergeCallbacks)
690 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
691 M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy,
694 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
695 M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
699 llvm::Triple targetTriple(M.getTargetTriple());
700 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
702 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
703 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
704 if (ClMappingOffsetLog >= 0) {
705 if (ClMappingOffsetLog == 0) {
709 MappingOffset = 1ULL << ClMappingOffsetLog;
712 MappingScale = kDefaultShadowScale;
713 if (ClMappingScale) {
714 MappingScale = ClMappingScale;
716 // Redzone used for stack and globals is at least 32 bytes.
717 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
718 RedzoneSize = std::max(32, (int)(1 << MappingScale));
723 Res |= insertGlobalRedzones(M);
725 if (ClMappingOffsetLog >= 0) {
726 // Tell the run-time the current values of mapping offset and scale.
727 GlobalValue *asan_mapping_offset =
728 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
729 ConstantInt::get(IntptrTy, MappingOffset),
730 kAsanMappingOffsetName);
731 // Read the global, otherwise it may be optimized away.
732 IRB.CreateLoad(asan_mapping_offset, true);
734 if (ClMappingScale) {
735 GlobalValue *asan_mapping_scale =
736 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
737 ConstantInt::get(IntptrTy, MappingScale),
738 kAsanMappingScaleName);
739 // Read the global, otherwise it may be optimized away.
740 IRB.CreateLoad(asan_mapping_scale, true);
744 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
745 if (F->isDeclaration()) continue;
746 Res |= handleFunction(M, *F);
749 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
754 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
755 // For each NSObject descendant having a +load method, this method is invoked
756 // by the ObjC runtime before any of the static constructors is called.
757 // Therefore we need to instrument such methods with a call to __asan_init
758 // at the beginning in order to initialize our runtime before any access to
759 // the shadow memory.
760 // We cannot just ignore these methods, because they may call other
761 // instrumented functions.
762 if (F.getName().find(" load]") != std::string::npos) {
763 IRBuilder<> IRB(F.begin()->begin());
764 IRB.CreateCall(AsanInitFunction);
770 bool AddressSanitizer::handleFunction(Module &M, Function &F) {
771 if (BL->isIn(F)) return false;
772 if (&F == AsanCtorFunction) return false;
774 // If needed, insert __asan_init before checking for AddressSafety attr.
775 maybeInsertAsanInitAtFunctionEntry(F);
777 if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
779 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
781 // We want to instrument every address only once per basic block
782 // (unless there are calls between uses).
783 SmallSet<Value*, 16> TempsToInstrument;
784 SmallVector<Instruction*, 16> ToInstrument;
785 SmallVector<Instruction*, 8> NoReturnCalls;
788 // Fill the set of memory operations to instrument.
789 for (Function::iterator FI = F.begin(), FE = F.end();
791 TempsToInstrument.clear();
792 int NumInsnsPerBB = 0;
793 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
795 if (LooksLikeCodeInBug11395(BI)) return false;
796 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
797 if (ClOpt && ClOptSameTemp) {
798 if (!TempsToInstrument.insert(Addr))
799 continue; // We've seen this temp in the current BB.
801 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
804 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
806 TempsToInstrument.clear();
807 if (CI->doesNotReturn()) {
808 NoReturnCalls.push_back(CI);
813 ToInstrument.push_back(BI);
815 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
820 AsanFunctionContext AFC(F);
823 int NumInstrumented = 0;
824 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
825 Instruction *Inst = ToInstrument[i];
826 if (ClDebugMin < 0 || ClDebugMax < 0 ||
827 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
828 if (isInterestingMemoryAccess(Inst, &IsWrite))
829 instrumentMop(AFC, Inst);
831 instrumentMemIntrinsic(AFC, cast<MemIntrinsic>(Inst));
836 // Create PHI nodes and crash callbacks if we are merging crash callbacks.
837 if (NumInstrumented) {
838 for (size_t IsWrite = 0; IsWrite <= 1; IsWrite++) {
839 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
841 BasicBlock *BB = AFC.CrashBlock[IsWrite][AccessSizeIndex];
843 assert(ClMergeCallbacks);
844 AsanFunctionContext::CrashArgsVec &Args =
845 AFC.CrashArgs[IsWrite][AccessSizeIndex];
846 IRBuilder<> IRB(BB->getFirstNonPHI());
847 size_t n = Args.size();
848 PHINode *PN1 = IRB.CreatePHI(IntptrTy, n);
849 PHINode *PN2 = IRB.CreatePHI(IntptrTy, n);
850 // We need to match crash parameters and the predecessors.
851 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
854 PN1->addIncoming(Args[n].Arg1, *PI);
855 PN2->addIncoming(Args[n].Arg2, *PI);
858 generateCrashCode(BB, PN1, PN2, IsWrite, AccessSizeIndex);
865 bool ChangedStack = poisonStackInFunction(M, F);
867 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
868 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
869 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
870 Instruction *CI = NoReturnCalls[i];
872 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
873 IRB.getVoidTy(), NULL));
876 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
879 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
880 if (ShadowRedzoneSize == 1) return PoisonByte;
881 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
882 if (ShadowRedzoneSize == 4)
883 return (PoisonByte << 24) + (PoisonByte << 16) +
884 (PoisonByte << 8) + (PoisonByte);
885 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
888 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
891 size_t ShadowGranularity,
893 for (size_t i = 0; i < RedzoneSize;
894 i+= ShadowGranularity, Shadow++) {
895 if (i + ShadowGranularity <= Size) {
896 *Shadow = 0; // fully addressable
897 } else if (i >= Size) {
898 *Shadow = Magic; // unaddressable
900 *Shadow = Size - i; // first Size-i bytes are addressable
905 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
907 Value *ShadowBase, bool DoPoison) {
908 size_t ShadowRZSize = RedzoneSize >> MappingScale;
909 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
910 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
911 Type *RZPtrTy = PointerType::get(RZTy, 0);
913 Value *PoisonLeft = ConstantInt::get(RZTy,
914 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
915 Value *PoisonMid = ConstantInt::get(RZTy,
916 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
917 Value *PoisonRight = ConstantInt::get(RZTy,
918 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
920 // poison the first red zone.
921 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
923 // poison all other red zones.
924 uint64_t Pos = RedzoneSize;
925 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
926 AllocaInst *AI = AllocaVec[i];
927 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
928 uint64_t AlignedSize = getAlignedAllocaSize(AI);
929 assert(AlignedSize - SizeInBytes < RedzoneSize);
934 assert(ShadowBase->getType() == IntptrTy);
935 if (SizeInBytes < AlignedSize) {
936 // Poison the partial redzone at right
938 ShadowBase, ConstantInt::get(IntptrTy,
939 (Pos >> MappingScale) - ShadowRZSize));
940 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
943 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
945 1ULL << MappingScale,
946 kAsanStackPartialRedzoneMagic);
948 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
949 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
952 // Poison the full redzone at right.
953 Ptr = IRB.CreateAdd(ShadowBase,
954 ConstantInt::get(IntptrTy, Pos >> MappingScale));
955 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
956 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
962 // Workaround for bug 11395: we don't want to instrument stack in functions
963 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
964 // FIXME: remove once the bug 11395 is fixed.
965 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
966 if (LongSize != 32) return false;
967 CallInst *CI = dyn_cast<CallInst>(I);
968 if (!CI || !CI->isInlineAsm()) return false;
969 if (CI->getNumArgOperands() <= 5) return false;
970 // We have inline assembly with quite a few arguments.
974 // Find all static Alloca instructions and put
975 // poisoned red zones around all of them.
976 // Then unpoison everything back before the function returns.
978 // Stack poisoning does not play well with exception handling.
979 // When an exception is thrown, we essentially bypass the code
980 // that unpoisones the stack. This is why the run-time library has
981 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
982 // stack in the interceptor. This however does not work inside the
983 // actual function which catches the exception. Most likely because the
984 // compiler hoists the load of the shadow value somewhere too high.
985 // This causes asan to report a non-existing bug on 453.povray.
986 // It sounds like an LLVM bug.
987 bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
988 if (!ClStack) return false;
989 SmallVector<AllocaInst*, 16> AllocaVec;
990 SmallVector<Instruction*, 8> RetVec;
991 uint64_t TotalSize = 0;
993 // Filter out Alloca instructions we want (and can) handle.
994 // Collect Ret instructions.
995 for (Function::iterator FI = F.begin(), FE = F.end();
997 BasicBlock &BB = *FI;
998 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1000 if (isa<ReturnInst>(BI)) {
1001 RetVec.push_back(BI);
1005 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1007 if (AI->isArrayAllocation()) continue;
1008 if (!AI->isStaticAlloca()) continue;
1009 if (!AI->getAllocatedType()->isSized()) continue;
1010 if (AI->getAlignment() > RedzoneSize) continue;
1011 AllocaVec.push_back(AI);
1012 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1013 TotalSize += AlignedSize;
1017 if (AllocaVec.empty()) return false;
1019 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
1021 bool DoStackMalloc = ClUseAfterReturn
1022 && LocalStackSize <= kMaxStackMallocSize;
1024 Instruction *InsBefore = AllocaVec[0];
1025 IRBuilder<> IRB(InsBefore);
1028 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1029 AllocaInst *MyAlloca =
1030 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1031 MyAlloca->setAlignment(RedzoneSize);
1032 assert(MyAlloca->isStaticAlloca());
1033 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1034 Value *LocalStackBase = OrigStackBase;
1036 if (DoStackMalloc) {
1037 Value *AsanStackMallocFunc = M.getOrInsertFunction(
1038 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
1039 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1040 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1043 // This string will be parsed by the run-time (DescribeStackAddress).
1044 SmallString<2048> StackDescriptionStorage;
1045 raw_svector_ostream StackDescription(StackDescriptionStorage);
1046 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1048 uint64_t Pos = RedzoneSize;
1049 // Replace Alloca instructions with base+offset.
1050 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1051 AllocaInst *AI = AllocaVec[i];
1052 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1053 StringRef Name = AI->getName();
1054 StackDescription << Pos << " " << SizeInBytes << " "
1055 << Name.size() << " " << Name << " ";
1056 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1057 assert((AlignedSize % RedzoneSize) == 0);
1058 AI->replaceAllUsesWith(
1060 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1062 Pos += AlignedSize + RedzoneSize;
1064 assert(Pos == LocalStackSize);
1066 // Write the Magic value and the frame description constant to the redzone.
1067 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1068 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1070 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1071 ConstantInt::get(IntptrTy, LongSize/8));
1072 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1073 Value *Description = IRB.CreatePointerCast(
1074 createPrivateGlobalForString(M, StackDescription.str()),
1076 IRB.CreateStore(Description, BasePlus1);
1078 // Poison the stack redzones at the entry.
1079 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1080 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1082 Value *AsanStackFreeFunc = NULL;
1083 if (DoStackMalloc) {
1084 AsanStackFreeFunc = M.getOrInsertFunction(
1085 kAsanStackFreeName, IRB.getVoidTy(),
1086 IntptrTy, IntptrTy, IntptrTy, NULL);
1089 // Unpoison the stack before all ret instructions.
1090 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1091 Instruction *Ret = RetVec[i];
1092 IRBuilder<> IRBRet(Ret);
1094 // Mark the current frame as retired.
1095 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1097 // Unpoison the stack.
1098 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1100 if (DoStackMalloc) {
1101 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1102 ConstantInt::get(IntptrTy, LocalStackSize),