1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 // Details of the algorithm:
12 // http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asan"
18 #include "llvm/Transforms/Instrumentation.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/OwningPtr.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/InstVisitor.h"
38 #include "llvm/Support/CallSite.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/DataTypes.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/system_error.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Cloning.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Transforms/Utils/ModuleUtils.h"
49 #include "llvm/Transforms/Utils/SpecialCaseList.h"
55 static const uint64_t kDefaultShadowScale = 3;
56 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
57 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
58 static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000; // < 2G.
59 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
60 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
62 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
63 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
64 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
66 static const char *const kAsanModuleCtorName = "asan.module_ctor";
67 static const char *const kAsanModuleDtorName = "asan.module_dtor";
68 static const int kAsanCtorAndCtorPriority = 1;
69 static const char *const kAsanReportErrorTemplate = "__asan_report_";
70 static const char *const kAsanReportLoadN = "__asan_report_load_n";
71 static const char *const kAsanReportStoreN = "__asan_report_store_n";
72 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
73 static const char *const kAsanUnregisterGlobalsName =
74 "__asan_unregister_globals";
75 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
76 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
77 static const char *const kAsanInitName = "__asan_init_v3";
78 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
79 static const char *const kAsanMappingOffsetName = "__asan_mapping_offset";
80 static const char *const kAsanMappingScaleName = "__asan_mapping_scale";
81 static const char *const kAsanStackMallocName = "__asan_stack_malloc";
82 static const char *const kAsanStackFreeName = "__asan_stack_free";
83 static const char *const kAsanGenPrefix = "__asan_gen_";
84 static const char *const kAsanPoisonStackMemoryName =
85 "__asan_poison_stack_memory";
86 static const char *const kAsanUnpoisonStackMemoryName =
87 "__asan_unpoison_stack_memory";
89 static const int kAsanStackLeftRedzoneMagic = 0xf1;
90 static const int kAsanStackMidRedzoneMagic = 0xf2;
91 static const int kAsanStackRightRedzoneMagic = 0xf3;
92 static const int kAsanStackPartialRedzoneMagic = 0xf4;
94 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
95 static const size_t kNumberOfAccessSizes = 5;
97 // Command-line flags.
99 // This flag may need to be replaced with -f[no-]asan-reads.
100 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
101 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
102 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
103 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
104 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
105 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
106 cl::Hidden, cl::init(true));
107 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
108 cl::desc("use instrumentation with slow path for all accesses"),
109 cl::Hidden, cl::init(false));
110 // This flag limits the number of instructions to be instrumented
111 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
112 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
114 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
116 cl::desc("maximal number of instructions to instrument in any given BB"),
118 // This flag may need to be replaced with -f[no]asan-stack.
119 static cl::opt<bool> ClStack("asan-stack",
120 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
121 // This flag may need to be replaced with -f[no]asan-use-after-return.
122 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
123 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
124 // This flag may need to be replaced with -f[no]asan-globals.
125 static cl::opt<bool> ClGlobals("asan-globals",
126 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
127 static cl::opt<bool> ClInitializers("asan-initialization-order",
128 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
129 static cl::opt<bool> ClMemIntrin("asan-memintrin",
130 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
131 static cl::opt<bool> ClRealignStack("asan-realign-stack",
132 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
133 static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
134 cl::desc("File containing the list of objects to ignore "
135 "during instrumentation"), cl::Hidden);
137 // This is an experimental feature that will allow to choose between
138 // instrumented and non-instrumented code at link-time.
139 // If this option is on, just before instrumenting a function we create its
140 // clone; if the function is not changed by asan the clone is deleted.
141 // If we end up with a clone, we put the instrumented function into a section
142 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
144 // This is still a prototype, we need to figure out a way to keep two copies of
145 // a function so that the linker can easily choose one of them.
146 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
147 cl::desc("Keep uninstrumented copies of functions"),
148 cl::Hidden, cl::init(false));
150 // These flags allow to change the shadow mapping.
151 // The shadow mapping looks like
152 // Shadow = (Mem >> scale) + (1 << offset_log)
153 static cl::opt<int> ClMappingScale("asan-mapping-scale",
154 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
155 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
156 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
157 static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
158 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
159 cl::Hidden, cl::init(true));
161 // Optimization flags. Not user visible, used mostly for testing
162 // and benchmarking the tool.
163 static cl::opt<bool> ClOpt("asan-opt",
164 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
165 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
166 cl::desc("Instrument the same temp just once"), cl::Hidden,
168 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
169 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
171 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
172 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
173 cl::Hidden, cl::init(false));
176 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
178 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
179 cl::Hidden, cl::init(0));
180 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
181 cl::Hidden, cl::desc("Debug func"));
182 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
183 cl::Hidden, cl::init(-1));
184 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
185 cl::Hidden, cl::init(-1));
188 /// A set of dynamically initialized globals extracted from metadata.
189 class SetOfDynamicallyInitializedGlobals {
191 void Init(Module& M) {
192 // Clang generates metadata identifying all dynamically initialized globals.
193 NamedMDNode *DynamicGlobals =
194 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
197 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
198 MDNode *MDN = DynamicGlobals->getOperand(i);
199 assert(MDN->getNumOperands() == 1);
200 Value *VG = MDN->getOperand(0);
201 // The optimizer may optimize away a global entirely, in which case we
202 // cannot instrument access to it.
205 DynInitGlobals.insert(cast<GlobalVariable>(VG));
208 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
210 SmallSet<GlobalValue*, 32> DynInitGlobals;
213 /// This struct defines the shadow mapping using the rule:
214 /// shadow = (mem >> Scale) ADD-or-OR Offset.
215 struct ShadowMapping {
221 static ShadowMapping getShadowMapping(const Module &M, int LongSize,
222 bool ZeroBaseShadow) {
223 llvm::Triple TargetTriple(M.getTargetTriple());
224 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
225 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
226 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
227 TargetTriple.getArch() == llvm::Triple::ppc64le;
228 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
229 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
230 TargetTriple.getArch() == llvm::Triple::mipsel;
232 ShadowMapping Mapping;
234 // OR-ing shadow offset if more efficient (at least on x86),
235 // but on ppc64 we have to use add since the shadow offset is not neccesary
236 // 1/8-th of the address space.
237 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
239 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
241 (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
242 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
243 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
244 assert(LongSize == 64);
245 Mapping.Offset = kDefaultShort64bitShadowOffset;
247 if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
248 // Zero offset log is the special case.
249 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
252 Mapping.Scale = kDefaultShadowScale;
253 if (ClMappingScale) {
254 Mapping.Scale = ClMappingScale;
260 static size_t RedzoneSizeForScale(int MappingScale) {
261 // Redzone used for stack and globals is at least 32 bytes.
262 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
263 return std::max(32U, 1U << MappingScale);
266 /// AddressSanitizer: instrument the code in module to find memory bugs.
267 struct AddressSanitizer : public FunctionPass {
268 AddressSanitizer(bool CheckInitOrder = true,
269 bool CheckUseAfterReturn = false,
270 bool CheckLifetime = false,
271 StringRef BlacklistFile = StringRef(),
272 bool ZeroBaseShadow = false)
274 CheckInitOrder(CheckInitOrder || ClInitializers),
275 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
276 CheckLifetime(CheckLifetime || ClCheckLifetime),
277 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
279 ZeroBaseShadow(ZeroBaseShadow) {}
280 virtual const char *getPassName() const {
281 return "AddressSanitizerFunctionPass";
283 void instrumentMop(Instruction *I);
284 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
285 Value *Addr, uint32_t TypeSize, bool IsWrite,
286 Value *SizeArgument);
287 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
288 Value *ShadowValue, uint32_t TypeSize);
289 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
290 bool IsWrite, size_t AccessSizeIndex,
291 Value *SizeArgument);
292 bool instrumentMemIntrinsic(MemIntrinsic *MI);
293 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
295 Instruction *InsertBefore, bool IsWrite);
296 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
297 bool runOnFunction(Function &F);
298 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
299 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
300 virtual bool doInitialization(Module &M);
301 static char ID; // Pass identification, replacement for typeid
304 void initializeCallbacks(Module &M);
306 bool ShouldInstrumentGlobal(GlobalVariable *G);
307 bool LooksLikeCodeInBug11395(Instruction *I);
308 void FindDynamicInitializers(Module &M);
311 bool CheckUseAfterReturn;
313 SmallString<64> BlacklistFile;
320 ShadowMapping Mapping;
321 Function *AsanCtorFunction;
322 Function *AsanInitFunction;
323 Function *AsanHandleNoReturnFunc;
324 OwningPtr<SpecialCaseList> BL;
325 // This array is indexed by AccessIsWrite and log2(AccessSize).
326 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
327 // This array is indexed by AccessIsWrite.
328 Function *AsanErrorCallbackSized[2];
330 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
332 friend struct FunctionStackPoisoner;
335 class AddressSanitizerModule : public ModulePass {
337 AddressSanitizerModule(bool CheckInitOrder = true,
338 StringRef BlacklistFile = StringRef(),
339 bool ZeroBaseShadow = false)
341 CheckInitOrder(CheckInitOrder || ClInitializers),
342 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
344 ZeroBaseShadow(ZeroBaseShadow) {}
345 bool runOnModule(Module &M);
346 static char ID; // Pass identification, replacement for typeid
347 virtual const char *getPassName() const {
348 return "AddressSanitizerModule";
352 void initializeCallbacks(Module &M);
354 bool ShouldInstrumentGlobal(GlobalVariable *G);
355 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
356 size_t RedzoneSize() const {
357 return RedzoneSizeForScale(Mapping.Scale);
361 SmallString<64> BlacklistFile;
364 OwningPtr<SpecialCaseList> BL;
365 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
369 ShadowMapping Mapping;
370 Function *AsanPoisonGlobals;
371 Function *AsanUnpoisonGlobals;
372 Function *AsanRegisterGlobals;
373 Function *AsanUnregisterGlobals;
376 // Stack poisoning does not play well with exception handling.
377 // When an exception is thrown, we essentially bypass the code
378 // that unpoisones the stack. This is why the run-time library has
379 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
380 // stack in the interceptor. This however does not work inside the
381 // actual function which catches the exception. Most likely because the
382 // compiler hoists the load of the shadow value somewhere too high.
383 // This causes asan to report a non-existing bug on 453.povray.
384 // It sounds like an LLVM bug.
385 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
387 AddressSanitizer &ASan;
392 ShadowMapping Mapping;
394 SmallVector<AllocaInst*, 16> AllocaVec;
395 SmallVector<Instruction*, 8> RetVec;
396 uint64_t TotalStackSize;
397 unsigned StackAlignment;
399 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
400 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
402 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
403 struct AllocaPoisonCall {
404 IntrinsicInst *InsBefore;
408 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
410 // Maps Value to an AllocaInst from which the Value is originated.
411 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
412 AllocaForValueMapTy AllocaForValue;
414 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
415 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
416 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
417 Mapping(ASan.Mapping),
418 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
420 bool runOnFunction() {
421 if (!ClStack) return false;
422 // Collect alloca, ret, lifetime instructions etc.
423 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
424 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
425 BasicBlock *BB = *DI;
428 if (AllocaVec.empty()) return false;
430 initializeCallbacks(*F.getParent());
440 // Finds all static Alloca instructions and puts
441 // poisoned red zones around all of them.
442 // Then unpoison everything back before the function returns.
445 // ----------------------- Visitors.
446 /// \brief Collect all Ret instructions.
447 void visitReturnInst(ReturnInst &RI) {
448 RetVec.push_back(&RI);
451 /// \brief Collect Alloca instructions we want (and can) handle.
452 void visitAllocaInst(AllocaInst &AI) {
453 if (!isInterestingAlloca(AI)) return;
455 StackAlignment = std::max(StackAlignment, AI.getAlignment());
456 AllocaVec.push_back(&AI);
457 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
458 TotalStackSize += AlignedSize;
461 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
463 void visitIntrinsicInst(IntrinsicInst &II) {
464 if (!ASan.CheckLifetime) return;
465 Intrinsic::ID ID = II.getIntrinsicID();
466 if (ID != Intrinsic::lifetime_start &&
467 ID != Intrinsic::lifetime_end)
469 // Found lifetime intrinsic, add ASan instrumentation if necessary.
470 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
471 // If size argument is undefined, don't do anything.
472 if (Size->isMinusOne()) return;
473 // Check that size doesn't saturate uint64_t and can
474 // be stored in IntptrTy.
475 const uint64_t SizeValue = Size->getValue().getLimitedValue();
476 if (SizeValue == ~0ULL ||
477 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
479 // Find alloca instruction that corresponds to llvm.lifetime argument.
480 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
482 bool DoPoison = (ID == Intrinsic::lifetime_end);
483 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
484 AllocaPoisonCallVec.push_back(APC);
487 // ---------------------- Helpers.
488 void initializeCallbacks(Module &M);
490 // Check if we want (and can) handle this alloca.
491 bool isInterestingAlloca(AllocaInst &AI) {
492 return (!AI.isArrayAllocation() &&
493 AI.isStaticAlloca() &&
494 AI.getAlignment() <= RedzoneSize() &&
495 AI.getAllocatedType()->isSized());
498 size_t RedzoneSize() const {
499 return RedzoneSizeForScale(Mapping.Scale);
501 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
502 Type *Ty = AI->getAllocatedType();
503 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
506 uint64_t getAlignedSize(uint64_t SizeInBytes) {
507 size_t RZ = RedzoneSize();
508 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
510 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
511 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
512 return getAlignedSize(SizeInBytes);
514 /// Finds alloca where the value comes from.
515 AllocaInst *findAllocaForValue(Value *V);
516 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
517 Value *ShadowBase, bool DoPoison);
518 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
523 char AddressSanitizer::ID = 0;
524 INITIALIZE_PASS(AddressSanitizer, "asan",
525 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
527 FunctionPass *llvm::createAddressSanitizerFunctionPass(
528 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
529 StringRef BlacklistFile, bool ZeroBaseShadow) {
530 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
531 CheckLifetime, BlacklistFile, ZeroBaseShadow);
534 char AddressSanitizerModule::ID = 0;
535 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
536 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
537 "ModulePass", false, false)
538 ModulePass *llvm::createAddressSanitizerModulePass(
539 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
540 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
544 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
545 size_t Res = countTrailingZeros(TypeSize / 8);
546 assert(Res < kNumberOfAccessSizes);
550 // Create a constant for Str so that we can pass it to the run-time lib.
551 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
552 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
553 GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
554 GlobalValue::PrivateLinkage, StrConst,
556 GV->setUnnamedAddr(true); // Ok to merge these.
557 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
561 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
562 return G->getName().find(kAsanGenPrefix) == 0;
565 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
567 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
568 if (Mapping.Offset == 0)
570 // (Shadow >> scale) | offset
571 if (Mapping.OrShadowOffset)
572 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
574 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
577 void AddressSanitizer::instrumentMemIntrinsicParam(
578 Instruction *OrigIns,
579 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
580 IRBuilder<> IRB(InsertBefore);
581 if (Size->getType() != IntptrTy)
582 Size = IRB.CreateIntCast(Size, IntptrTy, false);
583 // Check the first byte.
584 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
585 // Check the last byte.
586 IRB.SetInsertPoint(InsertBefore);
587 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
588 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
589 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
590 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
593 // Instrument memset/memmove/memcpy
594 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
595 Value *Dst = MI->getDest();
596 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
597 Value *Src = MemTran ? MemTran->getSource() : 0;
598 Value *Length = MI->getLength();
600 Constant *ConstLength = dyn_cast<Constant>(Length);
601 Instruction *InsertBefore = MI;
603 if (ConstLength->isNullValue()) return false;
605 // The size is not a constant so it could be zero -- check at run-time.
606 IRBuilder<> IRB(InsertBefore);
608 Value *Cmp = IRB.CreateICmpNE(Length,
609 Constant::getNullValue(Length->getType()));
610 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
613 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
615 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
619 // If I is an interesting memory access, return the PointerOperand
620 // and set IsWrite. Otherwise return NULL.
621 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
622 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
623 if (!ClInstrumentReads) return NULL;
625 return LI->getPointerOperand();
627 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
628 if (!ClInstrumentWrites) return NULL;
630 return SI->getPointerOperand();
632 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
633 if (!ClInstrumentAtomics) return NULL;
635 return RMW->getPointerOperand();
637 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
638 if (!ClInstrumentAtomics) return NULL;
640 return XCHG->getPointerOperand();
645 void AddressSanitizer::instrumentMop(Instruction *I) {
646 bool IsWrite = false;
647 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
649 if (ClOpt && ClOptGlobals) {
650 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
651 // If initialization order checking is disabled, a simple access to a
652 // dynamically initialized global is always valid.
655 // If a global variable does not have dynamic initialization we don't
656 // have to instrument it. However, if a global does not have initailizer
657 // at all, we assume it has dynamic initializer (in other TU).
658 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
663 Type *OrigPtrTy = Addr->getType();
664 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
666 assert(OrigTy->isSized());
667 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
669 assert((TypeSize % 8) == 0);
671 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
672 if (TypeSize == 8 || TypeSize == 16 ||
673 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
674 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
675 // Instrument unusual size (but still multiple of 8).
676 // We can not do it with a single check, so we do 1-byte check for the first
677 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
678 // to report the actual access size.
680 Value *LastByte = IRB.CreateIntToPtr(
681 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
682 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
684 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
685 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
686 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
689 // Validate the result of Module::getOrInsertFunction called for an interface
690 // function of AddressSanitizer. If the instrumented module defines a function
691 // with the same name, their prototypes must match, otherwise
692 // getOrInsertFunction returns a bitcast.
693 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
694 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
695 FuncOrBitcast->dump();
696 report_fatal_error("trying to redefine an AddressSanitizer "
697 "interface function");
700 Instruction *AddressSanitizer::generateCrashCode(
701 Instruction *InsertBefore, Value *Addr,
702 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
703 IRBuilder<> IRB(InsertBefore);
704 CallInst *Call = SizeArgument
705 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
706 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
708 // We don't do Call->setDoesNotReturn() because the BB already has
709 // UnreachableInst at the end.
710 // This EmptyAsm is required to avoid callback merge.
711 IRB.CreateCall(EmptyAsm);
715 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
718 size_t Granularity = 1 << Mapping.Scale;
719 // Addr & (Granularity - 1)
720 Value *LastAccessedByte = IRB.CreateAnd(
721 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
722 // (Addr & (Granularity - 1)) + size - 1
723 if (TypeSize / 8 > 1)
724 LastAccessedByte = IRB.CreateAdd(
725 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
726 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
727 LastAccessedByte = IRB.CreateIntCast(
728 LastAccessedByte, ShadowValue->getType(), false);
729 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
730 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
733 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
734 Instruction *InsertBefore,
735 Value *Addr, uint32_t TypeSize,
736 bool IsWrite, Value *SizeArgument) {
737 IRBuilder<> IRB(InsertBefore);
738 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
740 Type *ShadowTy = IntegerType::get(
741 *C, std::max(8U, TypeSize >> Mapping.Scale));
742 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
743 Value *ShadowPtr = memToShadow(AddrLong, IRB);
744 Value *CmpVal = Constant::getNullValue(ShadowTy);
745 Value *ShadowValue = IRB.CreateLoad(
746 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
748 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
749 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
750 size_t Granularity = 1 << Mapping.Scale;
751 TerminatorInst *CrashTerm = 0;
753 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
754 TerminatorInst *CheckTerm =
755 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
756 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
757 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
758 IRB.SetInsertPoint(CheckTerm);
759 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
760 BasicBlock *CrashBlock =
761 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
762 CrashTerm = new UnreachableInst(*C, CrashBlock);
763 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
764 ReplaceInstWithInst(CheckTerm, NewTerm);
766 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
769 Instruction *Crash = generateCrashCode(
770 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
771 Crash->setDebugLoc(OrigIns->getDebugLoc());
774 void AddressSanitizerModule::createInitializerPoisonCalls(
775 Module &M, GlobalValue *ModuleName) {
776 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
777 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
778 // If that function is not present, this TU contains no globals, or they have
779 // all been optimized away
783 // Set up the arguments to our poison/unpoison functions.
784 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
786 // Add a call to poison all external globals before the given function starts.
787 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
788 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
790 // Add calls to unpoison all globals before each return instruction.
791 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
793 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
794 CallInst::Create(AsanUnpoisonGlobals, "", RI);
799 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
800 Type *Ty = cast<PointerType>(G->getType())->getElementType();
801 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
803 if (BL->isIn(*G)) return false;
804 if (!Ty->isSized()) return false;
805 if (!G->hasInitializer()) return false;
806 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
807 // Touch only those globals that will not be defined in other modules.
808 // Don't handle ODR type linkages since other modules may be built w/o asan.
809 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
810 G->getLinkage() != GlobalVariable::PrivateLinkage &&
811 G->getLinkage() != GlobalVariable::InternalLinkage)
813 // Two problems with thread-locals:
814 // - The address of the main thread's copy can't be computed at link-time.
815 // - Need to poison all copies, not just the main thread's one.
816 if (G->isThreadLocal())
818 // For now, just ignore this Alloca if the alignment is large.
819 if (G->getAlignment() > RedzoneSize()) return false;
821 // Ignore all the globals with the names starting with "\01L_OBJC_".
822 // Many of those are put into the .cstring section. The linker compresses
823 // that section by removing the spare \0s after the string terminator, so
824 // our redzones get broken.
825 if ((G->getName().find("\01L_OBJC_") == 0) ||
826 (G->getName().find("\01l_OBJC_") == 0)) {
827 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
831 if (G->hasSection()) {
832 StringRef Section(G->getSection());
833 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
834 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
836 if ((Section.find("__OBJC,") == 0) ||
837 (Section.find("__DATA, __objc_") == 0)) {
838 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
841 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
842 // Constant CFString instances are compiled in the following way:
843 // -- the string buffer is emitted into
844 // __TEXT,__cstring,cstring_literals
845 // -- the constant NSConstantString structure referencing that buffer
846 // is placed into __DATA,__cfstring
847 // Therefore there's no point in placing redzones into __DATA,__cfstring.
848 // Moreover, it causes the linker to crash on OS X 10.7
849 if (Section.find("__DATA,__cfstring") == 0) {
850 DEBUG(dbgs() << "Ignoring CFString: " << *G);
858 void AddressSanitizerModule::initializeCallbacks(Module &M) {
860 // Declare our poisoning and unpoisoning functions.
861 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
862 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
863 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
864 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
865 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
866 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
867 // Declare functions that register/unregister globals.
868 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
869 kAsanRegisterGlobalsName, IRB.getVoidTy(),
870 IntptrTy, IntptrTy, NULL));
871 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
872 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
873 kAsanUnregisterGlobalsName,
874 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
875 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
878 // This function replaces all global variables with new variables that have
879 // trailing redzones. It also creates a function that poisons
880 // redzones and inserts this function into llvm.global_ctors.
881 bool AddressSanitizerModule::runOnModule(Module &M) {
882 if (!ClGlobals) return false;
883 TD = getAnalysisIfAvailable<DataLayout>();
886 BL.reset(new SpecialCaseList(BlacklistFile));
887 if (BL->isIn(M)) return false;
888 C = &(M.getContext());
889 int LongSize = TD->getPointerSizeInBits();
890 IntptrTy = Type::getIntNTy(*C, LongSize);
891 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
892 initializeCallbacks(M);
893 DynamicallyInitializedGlobals.Init(M);
895 SmallVector<GlobalVariable *, 16> GlobalsToChange;
897 for (Module::GlobalListType::iterator G = M.global_begin(),
898 E = M.global_end(); G != E; ++G) {
899 if (ShouldInstrumentGlobal(G))
900 GlobalsToChange.push_back(G);
903 size_t n = GlobalsToChange.size();
904 if (n == 0) return false;
906 // A global is described by a structure
909 // size_t size_with_redzone;
911 // const char *module_name;
912 // size_t has_dynamic_init;
913 // We initialize an array of such structures and pass it to a run-time call.
914 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
916 IntptrTy, IntptrTy, NULL);
917 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
920 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
922 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
924 bool HasDynamicallyInitializedGlobals = false;
926 GlobalVariable *ModuleName = createPrivateGlobalForString(
927 M, M.getModuleIdentifier());
928 // We shouldn't merge same module names, as this string serves as unique
929 // module ID in runtime.
930 ModuleName->setUnnamedAddr(false);
932 for (size_t i = 0; i < n; i++) {
933 static const uint64_t kMaxGlobalRedzone = 1 << 18;
934 GlobalVariable *G = GlobalsToChange[i];
935 PointerType *PtrTy = cast<PointerType>(G->getType());
936 Type *Ty = PtrTy->getElementType();
937 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
938 uint64_t MinRZ = RedzoneSize();
939 // MinRZ <= RZ <= kMaxGlobalRedzone
940 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
941 uint64_t RZ = std::max(MinRZ,
942 std::min(kMaxGlobalRedzone,
943 (SizeInBytes / MinRZ / 4) * MinRZ));
944 uint64_t RightRedzoneSize = RZ;
946 if (SizeInBytes % MinRZ)
947 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
948 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
949 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
950 // Determine whether this global should be poisoned in initialization.
951 bool GlobalHasDynamicInitializer =
952 DynamicallyInitializedGlobals.Contains(G);
953 // Don't check initialization order if this global is blacklisted.
954 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
956 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
957 Constant *NewInitializer = ConstantStruct::get(
958 NewTy, G->getInitializer(),
959 Constant::getNullValue(RightRedZoneTy), NULL);
961 GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
963 // Create a new global variable with enough space for a redzone.
964 GlobalVariable *NewGlobal = new GlobalVariable(
965 M, NewTy, G->isConstant(), G->getLinkage(),
966 NewInitializer, "", G, G->getThreadLocalMode());
967 NewGlobal->copyAttributesFrom(G);
968 NewGlobal->setAlignment(MinRZ);
971 Indices2[0] = IRB.getInt32(0);
972 Indices2[1] = IRB.getInt32(0);
974 G->replaceAllUsesWith(
975 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
976 NewGlobal->takeName(G);
977 G->eraseFromParent();
979 Initializers[i] = ConstantStruct::get(
981 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
982 ConstantInt::get(IntptrTy, SizeInBytes),
983 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
984 ConstantExpr::getPointerCast(Name, IntptrTy),
985 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
986 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
989 // Populate the first and last globals declared in this TU.
990 if (CheckInitOrder && GlobalHasDynamicInitializer)
991 HasDynamicallyInitializedGlobals = true;
993 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
996 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
997 GlobalVariable *AllGlobals = new GlobalVariable(
998 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
999 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1001 // Create calls for poisoning before initializers run and unpoisoning after.
1002 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1003 createInitializerPoisonCalls(M, ModuleName);
1004 IRB.CreateCall2(AsanRegisterGlobals,
1005 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1006 ConstantInt::get(IntptrTy, n));
1008 // We also need to unregister globals at the end, e.g. when a shared library
1010 Function *AsanDtorFunction = Function::Create(
1011 FunctionType::get(Type::getVoidTy(*C), false),
1012 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1013 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1014 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1015 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1016 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1017 ConstantInt::get(IntptrTy, n));
1018 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1024 void AddressSanitizer::initializeCallbacks(Module &M) {
1025 IRBuilder<> IRB(*C);
1026 // Create __asan_report* callbacks.
1027 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1028 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1029 AccessSizeIndex++) {
1030 // IsWrite and TypeSize are encoded in the function name.
1031 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1032 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1033 // If we are merging crash callbacks, they have two parameters.
1034 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1035 checkInterfaceFunction(M.getOrInsertFunction(
1036 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
1039 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1040 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1041 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1042 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1044 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1045 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1046 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1047 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1048 StringRef(""), StringRef(""),
1049 /*hasSideEffects=*/true);
1052 void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
1053 // Tell the values of mapping offset and scale to the run-time.
1054 GlobalValue *asan_mapping_offset =
1055 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1056 ConstantInt::get(IntptrTy, Mapping.Offset),
1057 kAsanMappingOffsetName);
1058 // Read the global, otherwise it may be optimized away.
1059 IRB.CreateLoad(asan_mapping_offset, true);
1061 GlobalValue *asan_mapping_scale =
1062 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1063 ConstantInt::get(IntptrTy, Mapping.Scale),
1064 kAsanMappingScaleName);
1065 // Read the global, otherwise it may be optimized away.
1066 IRB.CreateLoad(asan_mapping_scale, true);
1070 bool AddressSanitizer::doInitialization(Module &M) {
1071 // Initialize the private fields. No one has accessed them before.
1072 TD = getAnalysisIfAvailable<DataLayout>();
1076 BL.reset(new SpecialCaseList(BlacklistFile));
1077 DynamicallyInitializedGlobals.Init(M);
1079 C = &(M.getContext());
1080 LongSize = TD->getPointerSizeInBits();
1081 IntptrTy = Type::getIntNTy(*C, LongSize);
1083 AsanCtorFunction = Function::Create(
1084 FunctionType::get(Type::getVoidTy(*C), false),
1085 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1086 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1087 // call __asan_init in the module ctor.
1088 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1089 AsanInitFunction = checkInterfaceFunction(
1090 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1091 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1092 IRB.CreateCall(AsanInitFunction);
1094 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
1095 emitShadowMapping(M, IRB);
1097 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1101 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1102 // For each NSObject descendant having a +load method, this method is invoked
1103 // by the ObjC runtime before any of the static constructors is called.
1104 // Therefore we need to instrument such methods with a call to __asan_init
1105 // at the beginning in order to initialize our runtime before any access to
1106 // the shadow memory.
1107 // We cannot just ignore these methods, because they may call other
1108 // instrumented functions.
1109 if (F.getName().find(" load]") != std::string::npos) {
1110 IRBuilder<> IRB(F.begin()->begin());
1111 IRB.CreateCall(AsanInitFunction);
1117 bool AddressSanitizer::runOnFunction(Function &F) {
1118 if (BL->isIn(F)) return false;
1119 if (&F == AsanCtorFunction) return false;
1120 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1121 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1122 initializeCallbacks(*F.getParent());
1124 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1125 maybeInsertAsanInitAtFunctionEntry(F);
1127 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1130 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1133 // We want to instrument every address only once per basic block (unless there
1134 // are calls between uses).
1135 SmallSet<Value*, 16> TempsToInstrument;
1136 SmallVector<Instruction*, 16> ToInstrument;
1137 SmallVector<Instruction*, 8> NoReturnCalls;
1141 // Fill the set of memory operations to instrument.
1142 for (Function::iterator FI = F.begin(), FE = F.end();
1144 TempsToInstrument.clear();
1145 int NumInsnsPerBB = 0;
1146 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1148 if (LooksLikeCodeInBug11395(BI)) return false;
1149 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1150 if (ClOpt && ClOptSameTemp) {
1151 if (!TempsToInstrument.insert(Addr))
1152 continue; // We've seen this temp in the current BB.
1154 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1157 if (isa<AllocaInst>(BI))
1161 // A call inside BB.
1162 TempsToInstrument.clear();
1163 if (CS.doesNotReturn())
1164 NoReturnCalls.push_back(CS.getInstruction());
1168 ToInstrument.push_back(BI);
1170 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1175 Function *UninstrumentedDuplicate = 0;
1176 bool LikelyToInstrument =
1177 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1178 if (ClKeepUninstrumented && LikelyToInstrument) {
1179 ValueToValueMapTy VMap;
1180 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1181 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1182 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1183 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1187 int NumInstrumented = 0;
1188 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1189 Instruction *Inst = ToInstrument[i];
1190 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1191 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1192 if (isInterestingMemoryAccess(Inst, &IsWrite))
1193 instrumentMop(Inst);
1195 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1200 FunctionStackPoisoner FSP(F, *this);
1201 bool ChangedStack = FSP.runOnFunction();
1203 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1204 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1205 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1206 Instruction *CI = NoReturnCalls[i];
1207 IRBuilder<> IRB(CI);
1208 IRB.CreateCall(AsanHandleNoReturnFunc);
1211 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1212 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1214 if (ClKeepUninstrumented) {
1216 // No instrumentation is done, no need for the duplicate.
1217 if (UninstrumentedDuplicate)
1218 UninstrumentedDuplicate->eraseFromParent();
1220 // The function was instrumented. We must have the duplicate.
1221 assert(UninstrumentedDuplicate);
1222 UninstrumentedDuplicate->setSection("NOASAN");
1223 assert(!F.hasSection());
1224 F.setSection("ASAN");
1231 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1232 if (ShadowRedzoneSize == 1) return PoisonByte;
1233 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1234 if (ShadowRedzoneSize == 4)
1235 return (PoisonByte << 24) + (PoisonByte << 16) +
1236 (PoisonByte << 8) + (PoisonByte);
1237 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
1240 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1243 size_t ShadowGranularity,
1245 for (size_t i = 0; i < RZSize;
1246 i+= ShadowGranularity, Shadow++) {
1247 if (i + ShadowGranularity <= Size) {
1248 *Shadow = 0; // fully addressable
1249 } else if (i >= Size) {
1250 *Shadow = Magic; // unaddressable
1252 *Shadow = Size - i; // first Size-i bytes are addressable
1257 // Workaround for bug 11395: we don't want to instrument stack in functions
1258 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1259 // FIXME: remove once the bug 11395 is fixed.
1260 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1261 if (LongSize != 32) return false;
1262 CallInst *CI = dyn_cast<CallInst>(I);
1263 if (!CI || !CI->isInlineAsm()) return false;
1264 if (CI->getNumArgOperands() <= 5) return false;
1265 // We have inline assembly with quite a few arguments.
1269 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1270 IRBuilder<> IRB(*C);
1271 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1272 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1273 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1274 kAsanStackFreeName, IRB.getVoidTy(),
1275 IntptrTy, IntptrTy, IntptrTy, NULL));
1276 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1277 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1278 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1279 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1282 void FunctionStackPoisoner::poisonRedZones(
1283 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1285 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
1286 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1287 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1288 Type *RZPtrTy = PointerType::get(RZTy, 0);
1290 Value *PoisonLeft = ConstantInt::get(RZTy,
1291 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1292 Value *PoisonMid = ConstantInt::get(RZTy,
1293 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1294 Value *PoisonRight = ConstantInt::get(RZTy,
1295 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1297 // poison the first red zone.
1298 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1300 // poison all other red zones.
1301 uint64_t Pos = RedzoneSize();
1302 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1303 AllocaInst *AI = AllocaVec[i];
1304 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1305 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1306 assert(AlignedSize - SizeInBytes < RedzoneSize());
1311 assert(ShadowBase->getType() == IntptrTy);
1312 if (SizeInBytes < AlignedSize) {
1313 // Poison the partial redzone at right
1314 Ptr = IRB.CreateAdd(
1315 ShadowBase, ConstantInt::get(IntptrTy,
1316 (Pos >> Mapping.Scale) - ShadowRZSize));
1317 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1318 uint32_t Poison = 0;
1320 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1322 1ULL << Mapping.Scale,
1323 kAsanStackPartialRedzoneMagic);
1325 ASan.TD->isLittleEndian()
1326 ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1327 : support::endian::byte_swap<uint32_t, support::big>(Poison);
1329 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1330 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1333 // Poison the full redzone at right.
1334 Ptr = IRB.CreateAdd(ShadowBase,
1335 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
1336 bool LastAlloca = (i == AllocaVec.size() - 1);
1337 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
1338 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1340 Pos += RedzoneSize();
1344 void FunctionStackPoisoner::poisonStack() {
1345 uint64_t LocalStackSize = TotalStackSize +
1346 (AllocaVec.size() + 1) * RedzoneSize();
1348 bool DoStackMalloc = ASan.CheckUseAfterReturn
1349 && LocalStackSize <= kMaxStackMallocSize;
1351 assert(AllocaVec.size() > 0);
1352 Instruction *InsBefore = AllocaVec[0];
1353 IRBuilder<> IRB(InsBefore);
1356 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1357 AllocaInst *MyAlloca =
1358 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1359 if (ClRealignStack && StackAlignment < RedzoneSize())
1360 StackAlignment = RedzoneSize();
1361 MyAlloca->setAlignment(StackAlignment);
1362 assert(MyAlloca->isStaticAlloca());
1363 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1364 Value *LocalStackBase = OrigStackBase;
1366 if (DoStackMalloc) {
1367 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1368 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1371 // This string will be parsed by the run-time (DescribeAddressIfStack).
1372 SmallString<2048> StackDescriptionStorage;
1373 raw_svector_ostream StackDescription(StackDescriptionStorage);
1374 StackDescription << AllocaVec.size() << " ";
1376 // Insert poison calls for lifetime intrinsics for alloca.
1377 bool HavePoisonedAllocas = false;
1378 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1379 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1380 IntrinsicInst *II = APC.InsBefore;
1381 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1383 IRBuilder<> IRB(II);
1384 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1385 HavePoisonedAllocas |= APC.DoPoison;
1388 uint64_t Pos = RedzoneSize();
1389 // Replace Alloca instructions with base+offset.
1390 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1391 AllocaInst *AI = AllocaVec[i];
1392 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1393 StringRef Name = AI->getName();
1394 StackDescription << Pos << " " << SizeInBytes << " "
1395 << Name.size() << " " << Name << " ";
1396 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1397 assert((AlignedSize % RedzoneSize()) == 0);
1398 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1399 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1401 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1402 AI->replaceAllUsesWith(NewAllocaPtr);
1403 Pos += AlignedSize + RedzoneSize();
1405 assert(Pos == LocalStackSize);
1407 // The left-most redzone has enough space for at least 4 pointers.
1408 // Write the Magic value to redzone[0].
1409 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1410 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1412 // Write the frame description constant to redzone[1].
1413 Value *BasePlus1 = IRB.CreateIntToPtr(
1414 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1416 GlobalVariable *StackDescriptionGlobal =
1417 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
1418 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1420 IRB.CreateStore(Description, BasePlus1);
1421 // Write the PC to redzone[2].
1422 Value *BasePlus2 = IRB.CreateIntToPtr(
1423 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1424 2 * ASan.LongSize/8)),
1426 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1428 // Poison the stack redzones at the entry.
1429 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1430 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
1432 // Unpoison the stack before all ret instructions.
1433 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1434 Instruction *Ret = RetVec[i];
1435 IRBuilder<> IRBRet(Ret);
1436 // Mark the current frame as retired.
1437 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1439 // Unpoison the stack.
1440 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
1441 if (DoStackMalloc) {
1442 // In use-after-return mode, mark the whole stack frame unaddressable.
1443 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1444 ConstantInt::get(IntptrTy, LocalStackSize),
1446 } else if (HavePoisonedAllocas) {
1447 // If we poisoned some allocas in llvm.lifetime analysis,
1448 // unpoison whole stack frame now.
1449 assert(LocalStackBase == OrigStackBase);
1450 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1454 // We are done. Remove the old unused alloca instructions.
1455 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1456 AllocaVec[i]->eraseFromParent();
1459 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1460 IRBuilder<> IRB, bool DoPoison) {
1461 // For now just insert the call to ASan runtime.
1462 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1463 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1464 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1465 : AsanUnpoisonStackMemoryFunc,
1469 // Handling llvm.lifetime intrinsics for a given %alloca:
1470 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1471 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1472 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1473 // could be poisoned by previous llvm.lifetime.end instruction, as the
1474 // variable may go in and out of scope several times, e.g. in loops).
1475 // (3) if we poisoned at least one %alloca in a function,
1476 // unpoison the whole stack frame at function exit.
1478 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1479 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1480 // We're intested only in allocas we can handle.
1481 return isInterestingAlloca(*AI) ? AI : 0;
1482 // See if we've already calculated (or started to calculate) alloca for a
1484 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1485 if (I != AllocaForValue.end())
1487 // Store 0 while we're calculating alloca for value V to avoid
1488 // infinite recursion if the value references itself.
1489 AllocaForValue[V] = 0;
1490 AllocaInst *Res = 0;
1491 if (CastInst *CI = dyn_cast<CastInst>(V))
1492 Res = findAllocaForValue(CI->getOperand(0));
1493 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1494 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1495 Value *IncValue = PN->getIncomingValue(i);
1496 // Allow self-referencing phi-nodes.
1497 if (IncValue == PN) continue;
1498 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1499 // AI for incoming values should exist and should all be equal.
1500 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1506 AllocaForValue[V] = Res;