blob: 4abaeca0c5c311a89e67e45baac444a8319eaa56 [file] [log] [blame]
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "asan"
17
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +000018#include "BlackList.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000019#include "llvm/Function.h"
20#include "llvm/IRBuilder.h"
Kostya Serebryanyf7b08222012-07-20 09:54:50 +000021#include "llvm/InlineAsm.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000022#include "llvm/IntrinsicInst.h"
23#include "llvm/LLVMContext.h"
24#include "llvm/Module.h"
25#include "llvm/Type.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000026#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000032#include "llvm/ADT/Triple.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/DataTypes.h"
35#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000036#include "llvm/Support/raw_ostream.h"
37#include "llvm/Support/system_error.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000038#include "llvm/DataLayout.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000039#include "llvm/Target/TargetMachine.h"
40#include "llvm/Transforms/Instrumentation.h"
41#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043
44#include <string>
45#include <algorithm>
46
47using namespace llvm;
48
49static const uint64_t kDefaultShadowScale = 3;
50static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
51static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000052static const uint64_t kDefaultShadowOffsetAndroid = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000053
54static const size_t kMaxStackMallocSize = 1 << 16; // 64K
55static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
56static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
57
58static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000059static const char *kAsanModuleDtorName = "asan.module_dtor";
60static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000061static const char *kAsanReportErrorTemplate = "__asan_report_";
62static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000063static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000064static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
65static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000066static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000067static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000068static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
69static const char *kAsanMappingScaleName = "__asan_mapping_scale";
70static const char *kAsanStackMallocName = "__asan_stack_malloc";
71static const char *kAsanStackFreeName = "__asan_stack_free";
72
73static const int kAsanStackLeftRedzoneMagic = 0xf1;
74static const int kAsanStackMidRedzoneMagic = 0xf2;
75static const int kAsanStackRightRedzoneMagic = 0xf3;
76static const int kAsanStackPartialRedzoneMagic = 0xf4;
77
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000078// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
79static const size_t kNumberOfAccessSizes = 5;
80
Kostya Serebryany800e03f2011-11-16 01:35:23 +000081// Command-line flags.
82
83// This flag may need to be replaced with -f[no-]asan-reads.
84static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
85 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
86static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
87 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000088static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
89 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
90 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +000091static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
92 cl::desc("use instrumentation with slow path for all accesses"),
93 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000094// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +000095// in any given BB. Normally, this should be set to unlimited (INT_MAX),
96// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
97// set it to 10000.
98static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
99 cl::init(10000),
100 cl::desc("maximal number of instructions to instrument in any given BB"),
101 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000102// This flag may need to be replaced with -f[no]asan-stack.
103static cl::opt<bool> ClStack("asan-stack",
104 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
105// This flag may need to be replaced with -f[no]asan-use-after-return.
106static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
107 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
108// This flag may need to be replaced with -f[no]asan-globals.
109static cl::opt<bool> ClGlobals("asan-globals",
110 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000111static cl::opt<bool> ClInitializers("asan-initialization-order",
112 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000113static cl::opt<bool> ClMemIntrin("asan-memintrin",
114 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
115// This flag may need to be replaced with -fasan-blacklist.
116static cl::opt<std::string> ClBlackListFile("asan-blacklist",
117 cl::desc("File containing the list of functions to ignore "
118 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000119
120// These flags allow to change the shadow mapping.
121// The shadow mapping looks like
122// Shadow = (Mem >> scale) + (1 << offset_log)
123static cl::opt<int> ClMappingScale("asan-mapping-scale",
124 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
125static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
126 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
127
128// Optimization flags. Not user visible, used mostly for testing
129// and benchmarking the tool.
130static cl::opt<bool> ClOpt("asan-opt",
131 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
132static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
133 cl::desc("Instrument the same temp just once"), cl::Hidden,
134 cl::init(true));
135static cl::opt<bool> ClOptGlobals("asan-opt-globals",
136 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
137
138// Debug flags.
139static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
140 cl::init(0));
141static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
142 cl::Hidden, cl::init(0));
143static cl::opt<std::string> ClDebugFunc("asan-debug-func",
144 cl::Hidden, cl::desc("Debug func"));
145static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
146 cl::Hidden, cl::init(-1));
147static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
148 cl::Hidden, cl::init(-1));
149
150namespace {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000151/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000152struct AddressSanitizer : public FunctionPass {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000153 AddressSanitizer();
Alexander Potapenko25878042012-01-23 11:22:43 +0000154 virtual const char *getPassName() const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000155 void instrumentMop(Instruction *I);
156 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000157 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000158 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
159 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000160 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000161 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000162 bool instrumentMemIntrinsic(MemIntrinsic *MI);
163 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000164 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000165 Instruction *InsertBefore, bool IsWrite);
166 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000167 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000168 void createInitializerPoisonCalls(Module &M,
169 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000170 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000171 bool poisonStackInFunction(Function &F);
172 virtual bool doInitialization(Module &M);
173 virtual bool doFinalization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000174 bool insertGlobalRedzones(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000175 static char ID; // Pass identification, replacement for typeid
176
177 private:
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000178 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
179 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000180 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000181 return SizeInBytes;
182 }
183 uint64_t getAlignedSize(uint64_t SizeInBytes) {
184 return ((SizeInBytes + RedzoneSize - 1)
185 / RedzoneSize) * RedzoneSize;
186 }
187 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
188 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
189 return getAlignedSize(SizeInBytes);
190 }
191
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000192 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000193 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000194 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
195 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000196 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000197 void FindDynamicInitializers(Module &M);
198 bool HasDynamicInitializer(GlobalVariable *G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000199
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000200 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000201 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000202 uint64_t MappingOffset;
203 int MappingScale;
204 size_t RedzoneSize;
205 int LongSize;
206 Type *IntptrTy;
207 Type *IntptrPtrTy;
208 Function *AsanCtorFunction;
209 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000210 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
211 Function *AsanHandleNoReturnFunc;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000212 Instruction *CtorInsertBefore;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000213 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000214 // This array is indexed by AccessIsWrite and log2(AccessSize).
215 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000216 InlineAsm *EmptyAsm;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000217 SmallSet<GlobalValue*, 32> DynamicallyInitializedGlobals;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000218};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000219
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000220} // namespace
221
222char AddressSanitizer::ID = 0;
223INITIALIZE_PASS(AddressSanitizer, "asan",
224 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
225 false, false)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000226AddressSanitizer::AddressSanitizer() : FunctionPass(ID) { }
227FunctionPass *llvm::createAddressSanitizerPass() {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000228 return new AddressSanitizer();
229}
230
Alexander Potapenko25878042012-01-23 11:22:43 +0000231const char *AddressSanitizer::getPassName() const {
232 return "AddressSanitizer";
233}
234
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000235static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
236 size_t Res = CountTrailingZeros_32(TypeSize / 8);
237 assert(Res < kNumberOfAccessSizes);
238 return Res;
239}
240
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000241// Create a constant for Str so that we can pass it to the run-time lib.
242static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000243 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000244 return new GlobalVariable(M, StrConst->getType(), true,
245 GlobalValue::PrivateLinkage, StrConst, "");
246}
247
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000248Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
249 // Shadow >> scale
250 Shadow = IRB.CreateLShr(Shadow, MappingScale);
251 if (MappingOffset == 0)
252 return Shadow;
253 // (Shadow >> scale) | offset
254 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
255 MappingOffset));
256}
257
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000258void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000259 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000260 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
261 // Check the first byte.
262 {
263 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000264 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000265 }
266 // Check the last byte.
267 {
268 IRBuilder<> IRB(InsertBefore);
269 Value *SizeMinusOne = IRB.CreateSub(
270 Size, ConstantInt::get(Size->getType(), 1));
271 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
272 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
273 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000274 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000275 }
276}
277
278// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000279bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000280 Value *Dst = MI->getDest();
281 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000282 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000283 Value *Length = MI->getLength();
284
285 Constant *ConstLength = dyn_cast<Constant>(Length);
286 Instruction *InsertBefore = MI;
287 if (ConstLength) {
288 if (ConstLength->isNullValue()) return false;
289 } else {
290 // The size is not a constant so it could be zero -- check at run-time.
291 IRBuilder<> IRB(InsertBefore);
292
293 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000294 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000295 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000296 }
297
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000298 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000299 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000300 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000301 return true;
302}
303
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000304// If I is an interesting memory access, return the PointerOperand
305// and set IsWrite. Otherwise return NULL.
306static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000307 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000308 if (!ClInstrumentReads) return NULL;
309 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000310 return LI->getPointerOperand();
311 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000312 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
313 if (!ClInstrumentWrites) return NULL;
314 *IsWrite = true;
315 return SI->getPointerOperand();
316 }
317 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
318 if (!ClInstrumentAtomics) return NULL;
319 *IsWrite = true;
320 return RMW->getPointerOperand();
321 }
322 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
323 if (!ClInstrumentAtomics) return NULL;
324 *IsWrite = true;
325 return XCHG->getPointerOperand();
326 }
327 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000328}
329
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000330void AddressSanitizer::FindDynamicInitializers(Module& M) {
331 // Clang generates metadata identifying all dynamically initialized globals.
332 NamedMDNode *DynamicGlobals =
333 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
334 if (!DynamicGlobals)
335 return;
336 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
337 MDNode *MDN = DynamicGlobals->getOperand(i);
338 assert(MDN->getNumOperands() == 1);
339 Value *VG = MDN->getOperand(0);
340 // The optimizer may optimize away a global entirely, in which case we
341 // cannot instrument access to it.
342 if (!VG)
343 continue;
344
345 GlobalVariable *G = cast<GlobalVariable>(VG);
346 DynamicallyInitializedGlobals.insert(G);
347 }
348}
349// Returns true if a global variable is initialized dynamically in this TU.
350bool AddressSanitizer::HasDynamicInitializer(GlobalVariable *G) {
351 return DynamicallyInitializedGlobals.count(G);
352}
353
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000354void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000355 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000356 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
357 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000358 if (ClOpt && ClOptGlobals) {
359 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
360 // If initialization order checking is disabled, a simple access to a
361 // dynamically initialized global is always valid.
362 if (!ClInitializers)
363 return;
364 // If a global variable does not have dynamic initialization we don't
365 // have to instrument it. However, if a global has external linkage, we
366 // assume it has dynamic initialization, as it may have an initializer
367 // in a different TU.
368 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
369 !HasDynamicInitializer(G))
370 return;
371 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000372 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000373
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000374 Type *OrigPtrTy = Addr->getType();
375 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
376
377 assert(OrigTy->isSized());
378 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
379
380 if (TypeSize != 8 && TypeSize != 16 &&
381 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
382 // Ignore all unusual sizes.
383 return;
384 }
385
386 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000387 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000388}
389
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000390// Validate the result of Module::getOrInsertFunction called for an interface
391// function of AddressSanitizer. If the instrumented module defines a function
392// with the same name, their prototypes must match, otherwise
393// getOrInsertFunction returns a bitcast.
394Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
395 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
396 FuncOrBitcast->dump();
397 report_fatal_error("trying to redefine an AddressSanitizer "
398 "interface function");
399}
400
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000401Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000402 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000403 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000404 IRBuilder<> IRB(InsertBefore);
405 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
406 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000407 // We don't do Call->setDoesNotReturn() because the BB already has
408 // UnreachableInst at the end.
409 // This EmptyAsm is required to avoid callback merge.
410 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000411 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000412}
413
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000414Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000415 Value *ShadowValue,
416 uint32_t TypeSize) {
417 size_t Granularity = 1 << MappingScale;
418 // Addr & (Granularity - 1)
419 Value *LastAccessedByte = IRB.CreateAnd(
420 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
421 // (Addr & (Granularity - 1)) + size - 1
422 if (TypeSize / 8 > 1)
423 LastAccessedByte = IRB.CreateAdd(
424 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
425 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
426 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000427 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000428 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
429 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
430}
431
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000432void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000433 IRBuilder<> &IRB, Value *Addr,
434 uint32_t TypeSize, bool IsWrite) {
435 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
436
437 Type *ShadowTy = IntegerType::get(
438 *C, std::max(8U, TypeSize >> MappingScale));
439 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
440 Value *ShadowPtr = memToShadow(AddrLong, IRB);
441 Value *CmpVal = Constant::getNullValue(ShadowTy);
442 Value *ShadowValue = IRB.CreateLoad(
443 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
444
445 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000446 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000447 size_t Granularity = 1 << MappingScale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000448 TerminatorInst *CrashTerm = 0;
449
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000450 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000451 TerminatorInst *CheckTerm =
452 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000453 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000454 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000455 IRB.SetInsertPoint(CheckTerm);
456 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000457 BasicBlock *CrashBlock =
458 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000459 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000460 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
461 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000462 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000463 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000464 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000465
466 Instruction *Crash =
467 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
468 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000469}
470
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000471void AddressSanitizer::createInitializerPoisonCalls(Module &M,
472 Value *FirstAddr,
473 Value *LastAddr) {
474 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
475 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
476 // If that function is not present, this TU contains no globals, or they have
477 // all been optimized away
478 if (!GlobalInit)
479 return;
480
481 // Set up the arguments to our poison/unpoison functions.
482 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
483
484 // Declare our poisoning and unpoisoning functions.
485 Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
486 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
487 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
488 Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
489 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
490 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
491
492 // Add a call to poison all external globals before the given function starts.
493 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
494
495 // Add calls to unpoison all globals before each return instruction.
496 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
497 I != E; ++I) {
498 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
499 CallInst::Create(AsanUnpoisonGlobals, "", RI);
500 }
501 }
502}
503
504bool AddressSanitizer::ShouldInstrumentGlobal(GlobalVariable *G) {
505 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000506 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000507
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000508 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000509 if (!Ty->isSized()) return false;
510 if (!G->hasInitializer()) return false;
511 // Touch only those globals that will not be defined in other modules.
512 // Don't handle ODR type linkages since other modules may be built w/o asan.
513 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
514 G->getLinkage() != GlobalVariable::PrivateLinkage &&
515 G->getLinkage() != GlobalVariable::InternalLinkage)
516 return false;
517 // Two problems with thread-locals:
518 // - The address of the main thread's copy can't be computed at link-time.
519 // - Need to poison all copies, not just the main thread's one.
520 if (G->isThreadLocal())
521 return false;
522 // For now, just ignore this Alloca if the alignment is large.
523 if (G->getAlignment() > RedzoneSize) return false;
524
525 // Ignore all the globals with the names starting with "\01L_OBJC_".
526 // Many of those are put into the .cstring section. The linker compresses
527 // that section by removing the spare \0s after the string terminator, so
528 // our redzones get broken.
529 if ((G->getName().find("\01L_OBJC_") == 0) ||
530 (G->getName().find("\01l_OBJC_") == 0)) {
531 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
532 return false;
533 }
534
535 if (G->hasSection()) {
536 StringRef Section(G->getSection());
537 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
538 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
539 // them.
540 if ((Section.find("__OBJC,") == 0) ||
541 (Section.find("__DATA, __objc_") == 0)) {
542 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
543 return false;
544 }
545 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
546 // Constant CFString instances are compiled in the following way:
547 // -- the string buffer is emitted into
548 // __TEXT,__cstring,cstring_literals
549 // -- the constant NSConstantString structure referencing that buffer
550 // is placed into __DATA,__cfstring
551 // Therefore there's no point in placing redzones into __DATA,__cfstring.
552 // Moreover, it causes the linker to crash on OS X 10.7
553 if (Section.find("__DATA,__cfstring") == 0) {
554 DEBUG(dbgs() << "Ignoring CFString: " << *G);
555 return false;
556 }
557 }
558
559 return true;
560}
561
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000562// This function replaces all global variables with new variables that have
563// trailing redzones. It also creates a function that poisons
564// redzones and inserts this function into llvm.global_ctors.
565bool AddressSanitizer::insertGlobalRedzones(Module &M) {
566 SmallVector<GlobalVariable *, 16> GlobalsToChange;
567
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000568 for (Module::GlobalListType::iterator G = M.global_begin(),
569 E = M.global_end(); G != E; ++G) {
570 if (ShouldInstrumentGlobal(G))
571 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000572 }
573
574 size_t n = GlobalsToChange.size();
575 if (n == 0) return false;
576
577 // A global is described by a structure
578 // size_t beg;
579 // size_t size;
580 // size_t size_with_redzone;
581 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000582 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000583 // We initialize an array of such structures and pass it to a run-time call.
584 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000585 IntptrTy, IntptrTy,
586 IntptrTy, NULL);
587 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000588
589 IRBuilder<> IRB(CtorInsertBefore);
590
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000591 if (ClInitializers)
592 FindDynamicInitializers(M);
593
594 // The addresses of the first and last dynamically initialized globals in
595 // this TU. Used in initialization order checking.
596 Value *FirstDynamic = 0, *LastDynamic = 0;
597
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000598 for (size_t i = 0; i < n; i++) {
599 GlobalVariable *G = GlobalsToChange[i];
600 PointerType *PtrTy = cast<PointerType>(G->getType());
601 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000602 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000603 uint64_t RightRedzoneSize = RedzoneSize +
604 (RedzoneSize - (SizeInBytes % RedzoneSize));
605 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000606 // Determine whether this global should be poisoned in initialization.
607 bool GlobalHasDynamicInitializer = HasDynamicInitializer(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000608 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000609 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000610
611 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
612 Constant *NewInitializer = ConstantStruct::get(
613 NewTy, G->getInitializer(),
614 Constant::getNullValue(RightRedZoneTy), NULL);
615
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000616 SmallString<2048> DescriptionOfGlobal = G->getName();
617 DescriptionOfGlobal += " (";
618 DescriptionOfGlobal += M.getModuleIdentifier();
619 DescriptionOfGlobal += ")";
620 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000621
622 // Create a new global variable with enough space for a redzone.
623 GlobalVariable *NewGlobal = new GlobalVariable(
624 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000625 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000626 NewGlobal->copyAttributesFrom(G);
627 NewGlobal->setAlignment(RedzoneSize);
628
629 Value *Indices2[2];
630 Indices2[0] = IRB.getInt32(0);
631 Indices2[1] = IRB.getInt32(0);
632
633 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000634 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000635 NewGlobal->takeName(G);
636 G->eraseFromParent();
637
638 Initializers[i] = ConstantStruct::get(
639 GlobalStructTy,
640 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
641 ConstantInt::get(IntptrTy, SizeInBytes),
642 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
643 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000644 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000645 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000646
647 // Populate the first and last globals declared in this TU.
648 if (ClInitializers && GlobalHasDynamicInitializer) {
649 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
650 if (FirstDynamic == 0)
651 FirstDynamic = LastDynamic;
652 }
653
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000654 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000655 }
656
657 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
658 GlobalVariable *AllGlobals = new GlobalVariable(
659 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
660 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
661
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000662 // Create calls for poisoning before initializers run and unpoisoning after.
663 if (ClInitializers && FirstDynamic && LastDynamic)
664 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
665
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000666 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000667 kAsanRegisterGlobalsName, IRB.getVoidTy(),
668 IntptrTy, IntptrTy, NULL));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000669 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
670
671 IRB.CreateCall2(AsanRegisterGlobals,
672 IRB.CreatePointerCast(AllGlobals, IntptrTy),
673 ConstantInt::get(IntptrTy, n));
674
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000675 // We also need to unregister globals at the end, e.g. when a shared library
676 // gets closed.
677 Function *AsanDtorFunction = Function::Create(
678 FunctionType::get(Type::getVoidTy(*C), false),
679 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
680 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
681 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000682 Function *AsanUnregisterGlobals =
683 checkInterfaceFunction(M.getOrInsertFunction(
684 kAsanUnregisterGlobalsName,
685 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000686 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
687
688 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
689 IRB.CreatePointerCast(AllGlobals, IntptrTy),
690 ConstantInt::get(IntptrTy, n));
691 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
692
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000693 DEBUG(dbgs() << M);
694 return true;
695}
696
697// virtual
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000698bool AddressSanitizer::doInitialization(Module &M) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000699 // Initialize the private fields. No one has accessed them before.
Micah Villmow3574eca2012-10-08 16:38:25 +0000700 TD = getAnalysisIfAvailable<DataLayout>();
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000701
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000702 if (!TD)
703 return false;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000704 BL.reset(new BlackList(ClBlackListFile));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000705
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000706 C = &(M.getContext());
Micah Villmow2c39b152012-10-15 16:24:29 +0000707 LongSize = TD->getPointerSizeInBits(0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000708 IntptrTy = Type::getIntNTy(*C, LongSize);
709 IntptrPtrTy = PointerType::get(IntptrTy, 0);
710
711 AsanCtorFunction = Function::Create(
712 FunctionType::get(Type::getVoidTy(*C), false),
713 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
714 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
715 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
716
717 // call __asan_init in the module ctor.
718 IRBuilder<> IRB(CtorInsertBefore);
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000719 AsanInitFunction = checkInterfaceFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000720 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
721 AsanInitFunction->setLinkage(Function::ExternalLinkage);
722 IRB.CreateCall(AsanInitFunction);
723
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000724 // Create __asan_report* callbacks.
725 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
726 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
727 AccessSizeIndex++) {
728 // IsWrite and TypeSize are encoded in the function name.
729 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
730 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000731 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000732 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000733 M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000734 }
735 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000736
737 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
738 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
739 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
740 kAsanStackFreeName, IRB.getVoidTy(),
741 IntptrTy, IntptrTy, IntptrTy, NULL));
742 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
743 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
744
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000745 // We insert an empty inline asm after __asan_report* to avoid callback merge.
746 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
747 StringRef(""), StringRef(""),
748 /*hasSideEffects=*/true);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000749
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000750 llvm::Triple targetTriple(M.getTargetTriple());
Logan Chien43bf7092012-09-02 09:29:46 +0000751 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000752
753 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
754 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000755 if (ClMappingOffsetLog >= 0) {
756 if (ClMappingOffsetLog == 0) {
757 // special case
758 MappingOffset = 0;
759 } else {
760 MappingOffset = 1ULL << ClMappingOffsetLog;
761 }
762 }
763 MappingScale = kDefaultShadowScale;
764 if (ClMappingScale) {
765 MappingScale = ClMappingScale;
766 }
767 // Redzone used for stack and globals is at least 32 bytes.
768 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
769 RedzoneSize = std::max(32, (int)(1 << MappingScale));
770
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000771
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000772 if (ClMappingOffsetLog >= 0) {
773 // Tell the run-time the current values of mapping offset and scale.
774 GlobalValue *asan_mapping_offset =
775 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
776 ConstantInt::get(IntptrTy, MappingOffset),
777 kAsanMappingOffsetName);
778 // Read the global, otherwise it may be optimized away.
779 IRB.CreateLoad(asan_mapping_offset, true);
780 }
781 if (ClMappingScale) {
782 GlobalValue *asan_mapping_scale =
783 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
784 ConstantInt::get(IntptrTy, MappingScale),
785 kAsanMappingScaleName);
786 // Read the global, otherwise it may be optimized away.
787 IRB.CreateLoad(asan_mapping_scale, true);
788 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000789
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000790 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000791
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000792 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000793}
794
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000795bool AddressSanitizer::doFinalization(Module &M) {
796 // We transform the globals at the very end so that the optimization analysis
797 // works on the original globals.
798 if (ClGlobals)
799 return insertGlobalRedzones(M);
800 return false;
801}
802
803
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000804bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
805 // For each NSObject descendant having a +load method, this method is invoked
806 // by the ObjC runtime before any of the static constructors is called.
807 // Therefore we need to instrument such methods with a call to __asan_init
808 // at the beginning in order to initialize our runtime before any access to
809 // the shadow memory.
810 // We cannot just ignore these methods, because they may call other
811 // instrumented functions.
812 if (F.getName().find(" load]") != std::string::npos) {
813 IRBuilder<> IRB(F.begin()->begin());
814 IRB.CreateCall(AsanInitFunction);
815 return true;
816 }
817 return false;
818}
819
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000820bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000821 if (BL->isIn(F)) return false;
822 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000823 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000824
825 // If needed, insert __asan_init before checking for AddressSafety attr.
826 maybeInsertAsanInitAtFunctionEntry(F);
827
Bill Wendling67658342012-10-09 07:45:08 +0000828 if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety))
829 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000830
831 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
832 return false;
Bill Wendling67658342012-10-09 07:45:08 +0000833
834 // We want to instrument every address only once per basic block (unless there
835 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000836 SmallSet<Value*, 16> TempsToInstrument;
837 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000838 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000839 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000840
841 // Fill the set of memory operations to instrument.
842 for (Function::iterator FI = F.begin(), FE = F.end();
843 FI != FE; ++FI) {
844 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000845 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000846 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
847 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000848 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000849 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000850 if (ClOpt && ClOptSameTemp) {
851 if (!TempsToInstrument.insert(Addr))
852 continue; // We've seen this temp in the current BB.
853 }
854 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
855 // ok, take it.
856 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000857 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000858 // A call inside BB.
859 TempsToInstrument.clear();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000860 if (CI->doesNotReturn()) {
861 NoReturnCalls.push_back(CI);
862 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000863 }
864 continue;
865 }
866 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000867 NumInsnsPerBB++;
868 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
869 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000870 }
871 }
872
873 // Instrument.
874 int NumInstrumented = 0;
875 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
876 Instruction *Inst = ToInstrument[i];
877 if (ClDebugMin < 0 || ClDebugMax < 0 ||
878 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000879 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000880 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000881 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000882 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000883 }
884 NumInstrumented++;
885 }
886
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000887 bool ChangedStack = poisonStackInFunction(F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000888
889 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
890 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
891 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
892 Instruction *CI = NoReturnCalls[i];
893 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000894 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000895 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000896 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000897
898 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000899}
900
901static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
902 if (ShadowRedzoneSize == 1) return PoisonByte;
903 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
904 if (ShadowRedzoneSize == 4)
905 return (PoisonByte << 24) + (PoisonByte << 16) +
906 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000907 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000908}
909
910static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
911 size_t Size,
912 size_t RedzoneSize,
913 size_t ShadowGranularity,
914 uint8_t Magic) {
915 for (size_t i = 0; i < RedzoneSize;
916 i+= ShadowGranularity, Shadow++) {
917 if (i + ShadowGranularity <= Size) {
918 *Shadow = 0; // fully addressable
919 } else if (i >= Size) {
920 *Shadow = Magic; // unaddressable
921 } else {
922 *Shadow = Size - i; // first Size-i bytes are addressable
923 }
924 }
925}
926
927void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
928 IRBuilder<> IRB,
929 Value *ShadowBase, bool DoPoison) {
930 size_t ShadowRZSize = RedzoneSize >> MappingScale;
931 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
932 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
933 Type *RZPtrTy = PointerType::get(RZTy, 0);
934
935 Value *PoisonLeft = ConstantInt::get(RZTy,
936 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
937 Value *PoisonMid = ConstantInt::get(RZTy,
938 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
939 Value *PoisonRight = ConstantInt::get(RZTy,
940 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
941
942 // poison the first red zone.
943 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
944
945 // poison all other red zones.
946 uint64_t Pos = RedzoneSize;
947 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
948 AllocaInst *AI = AllocaVec[i];
949 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
950 uint64_t AlignedSize = getAlignedAllocaSize(AI);
951 assert(AlignedSize - SizeInBytes < RedzoneSize);
952 Value *Ptr = NULL;
953
954 Pos += AlignedSize;
955
956 assert(ShadowBase->getType() == IntptrTy);
957 if (SizeInBytes < AlignedSize) {
958 // Poison the partial redzone at right
959 Ptr = IRB.CreateAdd(
960 ShadowBase, ConstantInt::get(IntptrTy,
961 (Pos >> MappingScale) - ShadowRZSize));
962 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
963 uint32_t Poison = 0;
964 if (DoPoison) {
965 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
966 RedzoneSize,
967 1ULL << MappingScale,
968 kAsanStackPartialRedzoneMagic);
969 }
970 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
971 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
972 }
973
974 // Poison the full redzone at right.
975 Ptr = IRB.CreateAdd(ShadowBase,
976 ConstantInt::get(IntptrTy, Pos >> MappingScale));
977 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
978 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
979
980 Pos += RedzoneSize;
981 }
982}
983
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000984// Workaround for bug 11395: we don't want to instrument stack in functions
985// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000986// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000987bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
988 if (LongSize != 32) return false;
989 CallInst *CI = dyn_cast<CallInst>(I);
990 if (!CI || !CI->isInlineAsm()) return false;
991 if (CI->getNumArgOperands() <= 5) return false;
992 // We have inline assembly with quite a few arguments.
993 return true;
994}
995
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000996// Find all static Alloca instructions and put
997// poisoned red zones around all of them.
998// Then unpoison everything back before the function returns.
999//
1000// Stack poisoning does not play well with exception handling.
1001// When an exception is thrown, we essentially bypass the code
1002// that unpoisones the stack. This is why the run-time library has
1003// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1004// stack in the interceptor. This however does not work inside the
1005// actual function which catches the exception. Most likely because the
1006// compiler hoists the load of the shadow value somewhere too high.
1007// This causes asan to report a non-existing bug on 453.povray.
1008// It sounds like an LLVM bug.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001009bool AddressSanitizer::poisonStackInFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001010 if (!ClStack) return false;
1011 SmallVector<AllocaInst*, 16> AllocaVec;
1012 SmallVector<Instruction*, 8> RetVec;
1013 uint64_t TotalSize = 0;
1014
1015 // Filter out Alloca instructions we want (and can) handle.
1016 // Collect Ret instructions.
1017 for (Function::iterator FI = F.begin(), FE = F.end();
1018 FI != FE; ++FI) {
1019 BasicBlock &BB = *FI;
1020 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1021 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001022 if (isa<ReturnInst>(BI)) {
1023 RetVec.push_back(BI);
1024 continue;
1025 }
1026
1027 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1028 if (!AI) continue;
1029 if (AI->isArrayAllocation()) continue;
1030 if (!AI->isStaticAlloca()) continue;
1031 if (!AI->getAllocatedType()->isSized()) continue;
1032 if (AI->getAlignment() > RedzoneSize) continue;
1033 AllocaVec.push_back(AI);
1034 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1035 TotalSize += AlignedSize;
1036 }
1037 }
1038
1039 if (AllocaVec.empty()) return false;
1040
1041 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
1042
1043 bool DoStackMalloc = ClUseAfterReturn
1044 && LocalStackSize <= kMaxStackMallocSize;
1045
1046 Instruction *InsBefore = AllocaVec[0];
1047 IRBuilder<> IRB(InsBefore);
1048
1049
1050 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1051 AllocaInst *MyAlloca =
1052 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1053 MyAlloca->setAlignment(RedzoneSize);
1054 assert(MyAlloca->isStaticAlloca());
1055 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1056 Value *LocalStackBase = OrigStackBase;
1057
1058 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001059 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1060 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1061 }
1062
1063 // This string will be parsed by the run-time (DescribeStackAddress).
1064 SmallString<2048> StackDescriptionStorage;
1065 raw_svector_ostream StackDescription(StackDescriptionStorage);
1066 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1067
1068 uint64_t Pos = RedzoneSize;
1069 // Replace Alloca instructions with base+offset.
1070 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1071 AllocaInst *AI = AllocaVec[i];
1072 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1073 StringRef Name = AI->getName();
1074 StackDescription << Pos << " " << SizeInBytes << " "
1075 << Name.size() << " " << Name << " ";
1076 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1077 assert((AlignedSize % RedzoneSize) == 0);
1078 AI->replaceAllUsesWith(
1079 IRB.CreateIntToPtr(
1080 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1081 AI->getType()));
1082 Pos += AlignedSize + RedzoneSize;
1083 }
1084 assert(Pos == LocalStackSize);
1085
1086 // Write the Magic value and the frame description constant to the redzone.
1087 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1088 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1089 BasePlus0);
1090 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1091 ConstantInt::get(IntptrTy, LongSize/8));
1092 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1093 Value *Description = IRB.CreatePointerCast(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001094 createPrivateGlobalForString(*F.getParent(), StackDescription.str()),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001095 IntptrTy);
1096 IRB.CreateStore(Description, BasePlus1);
1097
1098 // Poison the stack redzones at the entry.
1099 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1100 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1101
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001102 // Unpoison the stack before all ret instructions.
1103 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1104 Instruction *Ret = RetVec[i];
1105 IRBuilder<> IRBRet(Ret);
1106
1107 // Mark the current frame as retired.
1108 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1109 BasePlus0);
1110 // Unpoison the stack.
1111 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1112
1113 if (DoStackMalloc) {
1114 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1115 ConstantInt::get(IntptrTy, LocalStackSize),
1116 OrigStackBase);
1117 }
1118 }
1119
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001120 // We are done. Remove the old unused alloca instructions.
1121 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1122 AllocaVec[i]->eraseFromParent();
1123
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001124 if (ClDebugStack) {
1125 DEBUG(dbgs() << F);
1126 }
1127
1128 return true;
1129}