blob: 9bd3239167646389555855f3ae42c341f84879fd [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
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +000019#include "BlackList.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000020#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov1c8b8252012-12-27 08:50:58 +000021#include "llvm/ADT/DenseMap.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000022#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000023#include "llvm/ADT/OwningPtr.h"
24#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000028#include "llvm/ADT/Triple.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000029#include "llvm/DIBuilder.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/InlineAsm.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/Type.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000038#include "llvm/InstVisitor.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000039#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/DataTypes.h"
41#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000042#include "llvm/Support/raw_ostream.h"
43#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000044#include "llvm/Target/TargetMachine.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000046#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000047#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000048#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000049#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000050
51using namespace llvm;
52
53static const uint64_t kDefaultShadowScale = 3;
54static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
55static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000056static const uint64_t kDefaultShadowOffsetAndroid = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000057
58static const size_t kMaxStackMallocSize = 1 << 16; // 64K
59static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
60static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
61
62static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000063static const char *kAsanModuleDtorName = "asan.module_dtor";
64static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000065static const char *kAsanReportErrorTemplate = "__asan_report_";
66static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000067static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000068static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
69static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000070static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000071static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000072static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
73static const char *kAsanMappingScaleName = "__asan_mapping_scale";
74static const char *kAsanStackMallocName = "__asan_stack_malloc";
75static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000076static const char *kAsanGenPrefix = "__asan_gen_";
Alexey Samsonovf985f442012-12-04 01:34:23 +000077static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
78static const char *kAsanUnpoisonStackMemoryName =
79 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000080
81static const int kAsanStackLeftRedzoneMagic = 0xf1;
82static const int kAsanStackMidRedzoneMagic = 0xf2;
83static const int kAsanStackRightRedzoneMagic = 0xf3;
84static const int kAsanStackPartialRedzoneMagic = 0xf4;
85
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000086// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
87static const size_t kNumberOfAccessSizes = 5;
88
Kostya Serebryany800e03f2011-11-16 01:35:23 +000089// Command-line flags.
90
91// This flag may need to be replaced with -f[no-]asan-reads.
92static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
93 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
94static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
95 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000096static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
97 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
98 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +000099static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
100 cl::desc("use instrumentation with slow path for all accesses"),
101 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000102// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000103// in any given BB. Normally, this should be set to unlimited (INT_MAX),
104// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
105// set it to 10000.
106static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
107 cl::init(10000),
108 cl::desc("maximal number of instructions to instrument in any given BB"),
109 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000110// This flag may need to be replaced with -f[no]asan-stack.
111static cl::opt<bool> ClStack("asan-stack",
112 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
113// This flag may need to be replaced with -f[no]asan-use-after-return.
114static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
115 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
116// This flag may need to be replaced with -f[no]asan-globals.
117static cl::opt<bool> ClGlobals("asan-globals",
118 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000119static cl::opt<bool> ClInitializers("asan-initialization-order",
120 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000121static cl::opt<bool> ClMemIntrin("asan-memintrin",
122 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000123static cl::opt<bool> ClRealignStack("asan-realign-stack",
124 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000125static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
126 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000127 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000128
129// These flags allow to change the shadow mapping.
130// The shadow mapping looks like
131// Shadow = (Mem >> scale) + (1 << offset_log)
132static cl::opt<int> ClMappingScale("asan-mapping-scale",
133 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
134static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
135 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
136
137// Optimization flags. Not user visible, used mostly for testing
138// and benchmarking the tool.
139static cl::opt<bool> ClOpt("asan-opt",
140 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
141static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
142 cl::desc("Instrument the same temp just once"), cl::Hidden,
143 cl::init(true));
144static cl::opt<bool> ClOptGlobals("asan-opt-globals",
145 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
146
Alexey Samsonovee548272012-11-29 18:14:24 +0000147static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
148 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
149 cl::Hidden, cl::init(false));
150
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000151// Debug flags.
152static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
153 cl::init(0));
154static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
155 cl::Hidden, cl::init(0));
156static cl::opt<std::string> ClDebugFunc("asan-debug-func",
157 cl::Hidden, cl::desc("Debug func"));
158static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
159 cl::Hidden, cl::init(-1));
160static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
161 cl::Hidden, cl::init(-1));
162
163namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000164/// A set of dynamically initialized globals extracted from metadata.
165class SetOfDynamicallyInitializedGlobals {
166 public:
167 void Init(Module& M) {
168 // Clang generates metadata identifying all dynamically initialized globals.
169 NamedMDNode *DynamicGlobals =
170 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
171 if (!DynamicGlobals)
172 return;
173 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
174 MDNode *MDN = DynamicGlobals->getOperand(i);
175 assert(MDN->getNumOperands() == 1);
176 Value *VG = MDN->getOperand(0);
177 // The optimizer may optimize away a global entirely, in which case we
178 // cannot instrument access to it.
179 if (!VG)
180 continue;
181 DynInitGlobals.insert(cast<GlobalVariable>(VG));
182 }
183 }
184 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
185 private:
186 SmallSet<GlobalValue*, 32> DynInitGlobals;
187};
188
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000189static int MappingScale() {
190 return ClMappingScale ? ClMappingScale : kDefaultShadowScale;
191}
192
193static size_t RedzoneSize() {
194 // Redzone used for stack and globals is at least 32 bytes.
195 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
196 return std::max(32U, 1U << MappingScale());
197}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000198
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000199/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000200struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000201 AddressSanitizer(bool CheckInitOrder = false,
202 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000203 bool CheckLifetime = false,
204 StringRef BlacklistFile = StringRef())
Alexey Samsonovee548272012-11-29 18:14:24 +0000205 : FunctionPass(ID),
206 CheckInitOrder(CheckInitOrder || ClInitializers),
207 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000208 CheckLifetime(CheckLifetime || ClCheckLifetime),
209 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
210 : BlacklistFile) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000211 virtual const char *getPassName() const {
212 return "AddressSanitizerFunctionPass";
213 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000214 void instrumentMop(Instruction *I);
215 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000216 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000217 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
218 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000219 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000220 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000221 bool instrumentMemIntrinsic(MemIntrinsic *MI);
222 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000223 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000224 Instruction *InsertBefore, bool IsWrite);
225 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000226 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000227 void createInitializerPoisonCalls(Module &M,
228 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000229 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000230 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000231 static char ID; // Pass identification, replacement for typeid
232
233 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000234 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000235
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000236 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000237 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000238 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000239
Alexey Samsonovee548272012-11-29 18:14:24 +0000240 bool CheckInitOrder;
241 bool CheckUseAfterReturn;
242 bool CheckLifetime;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000243 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000244 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000245 uint64_t MappingOffset;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000246 int LongSize;
247 Type *IntptrTy;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000248 Function *AsanCtorFunction;
249 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000250 Function *AsanHandleNoReturnFunc;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000251 SmallString<64> BlacklistFile;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000252 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000253 // This array is indexed by AccessIsWrite and log2(AccessSize).
254 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000255 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000256 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000257
258 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000259};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000260
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000261class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000262 public:
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000263 AddressSanitizerModule(bool CheckInitOrder = false,
264 StringRef BlacklistFile = StringRef())
Alexey Samsonovee548272012-11-29 18:14:24 +0000265 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000266 CheckInitOrder(CheckInitOrder || ClInitializers),
267 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
268 : BlacklistFile) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000269 bool runOnModule(Module &M);
270 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000271 virtual const char *getPassName() const {
272 return "AddressSanitizerModule";
273 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000274
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000275 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000276 void initializeCallbacks(Module &M);
277
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000278 bool ShouldInstrumentGlobal(GlobalVariable *G);
279 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
280 Value *LastAddr);
281
Alexey Samsonovee548272012-11-29 18:14:24 +0000282 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000283 SmallString<64> BlacklistFile;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000284 OwningPtr<BlackList> BL;
285 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
286 Type *IntptrTy;
287 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000288 DataLayout *TD;
Alexey Samsonov46848582012-12-25 12:28:20 +0000289 Function *AsanPoisonGlobals;
290 Function *AsanUnpoisonGlobals;
291 Function *AsanRegisterGlobals;
292 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000293};
294
Alexey Samsonov59cca132012-12-25 12:04:36 +0000295// Stack poisoning does not play well with exception handling.
296// When an exception is thrown, we essentially bypass the code
297// that unpoisones the stack. This is why the run-time library has
298// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
299// stack in the interceptor. This however does not work inside the
300// actual function which catches the exception. Most likely because the
301// compiler hoists the load of the shadow value somewhere too high.
302// This causes asan to report a non-existing bug on 453.povray.
303// It sounds like an LLVM bug.
304struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
305 Function &F;
306 AddressSanitizer &ASan;
307 DIBuilder DIB;
308 LLVMContext *C;
309 Type *IntptrTy;
310 Type *IntptrPtrTy;
311
312 SmallVector<AllocaInst*, 16> AllocaVec;
313 SmallVector<Instruction*, 8> RetVec;
314 uint64_t TotalStackSize;
315 unsigned StackAlignment;
316
317 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
318 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
319
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000320 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
321 struct AllocaPoisonCall {
322 IntrinsicInst *InsBefore;
323 uint64_t Size;
324 bool DoPoison;
325 };
326 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
327
328 // Maps Value to an AllocaInst from which the Value is originated.
329 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
330 AllocaForValueMapTy AllocaForValue;
331
Alexey Samsonov59cca132012-12-25 12:04:36 +0000332 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
333 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
334 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
335 TotalStackSize(0), StackAlignment(1 << MappingScale()) {}
336
337 bool runOnFunction() {
338 if (!ClStack) return false;
339 // Collect alloca, ret, lifetime instructions etc.
340 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
341 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
342 BasicBlock *BB = *DI;
343 visit(*BB);
344 }
345 if (AllocaVec.empty()) return false;
346
347 initializeCallbacks(*F.getParent());
348
349 poisonStack();
350
351 if (ClDebugStack) {
352 DEBUG(dbgs() << F);
353 }
354 return true;
355 }
356
357 // Finds all static Alloca instructions and puts
358 // poisoned red zones around all of them.
359 // Then unpoison everything back before the function returns.
360 void poisonStack();
361
362 // ----------------------- Visitors.
363 /// \brief Collect all Ret instructions.
364 void visitReturnInst(ReturnInst &RI) {
365 RetVec.push_back(&RI);
366 }
367
368 /// \brief Collect Alloca instructions we want (and can) handle.
369 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000370 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000371
372 StackAlignment = std::max(StackAlignment, AI.getAlignment());
373 AllocaVec.push_back(&AI);
374 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
375 TotalStackSize += AlignedSize;
376 }
377
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000378 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
379 /// errors.
380 void visitIntrinsicInst(IntrinsicInst &II) {
381 if (!ASan.CheckLifetime) return;
382 Intrinsic::ID ID = II.getIntrinsicID();
383 if (ID != Intrinsic::lifetime_start &&
384 ID != Intrinsic::lifetime_end)
385 return;
386 // Found lifetime intrinsic, add ASan instrumentation if necessary.
387 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
388 // If size argument is undefined, don't do anything.
389 if (Size->isMinusOne()) return;
390 // Check that size doesn't saturate uint64_t and can
391 // be stored in IntptrTy.
392 const uint64_t SizeValue = Size->getValue().getLimitedValue();
393 if (SizeValue == ~0ULL ||
394 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
395 return;
396 // Find alloca instruction that corresponds to llvm.lifetime argument.
397 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
398 if (!AI) return;
399 bool DoPoison = (ID == Intrinsic::lifetime_end);
400 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
401 AllocaPoisonCallVec.push_back(APC);
402 }
403
Alexey Samsonov59cca132012-12-25 12:04:36 +0000404 // ---------------------- Helpers.
405 void initializeCallbacks(Module &M);
406
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000407 // Check if we want (and can) handle this alloca.
408 bool isInterestingAlloca(AllocaInst &AI) {
409 return (!AI.isArrayAllocation() &&
410 AI.isStaticAlloca() &&
411 AI.getAllocatedType()->isSized());
412 }
413
Alexey Samsonov59cca132012-12-25 12:04:36 +0000414 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
415 Type *Ty = AI->getAllocatedType();
416 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
417 return SizeInBytes;
418 }
419 uint64_t getAlignedSize(uint64_t SizeInBytes) {
420 size_t RZ = RedzoneSize();
421 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
422 }
423 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
424 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
425 return getAlignedSize(SizeInBytes);
426 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000427 /// Finds alloca where the value comes from.
428 AllocaInst *findAllocaForValue(Value *V);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000429 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
430 Value *ShadowBase, bool DoPoison);
431 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000432};
433
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000434} // namespace
435
436char AddressSanitizer::ID = 0;
437INITIALIZE_PASS(AddressSanitizer, "asan",
438 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
439 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000440FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000441 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
442 StringRef BlacklistFile) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000443 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000444 CheckLifetime, BlacklistFile);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000445}
446
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000447char AddressSanitizerModule::ID = 0;
448INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
449 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
450 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000451ModulePass *llvm::createAddressSanitizerModulePass(
452 bool CheckInitOrder, StringRef BlacklistFile) {
453 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
Alexander Potapenko25878042012-01-23 11:22:43 +0000454}
455
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000456static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
457 size_t Res = CountTrailingZeros_32(TypeSize / 8);
458 assert(Res < kNumberOfAccessSizes);
459 return Res;
460}
461
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000462// Create a constant for Str so that we can pass it to the run-time lib.
463static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000464 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000465 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000466 GlobalValue::PrivateLinkage, StrConst,
467 kAsanGenPrefix);
468}
469
470static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
471 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000472}
473
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000474Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
475 // Shadow >> scale
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000476 Shadow = IRB.CreateLShr(Shadow, MappingScale());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000477 if (MappingOffset == 0)
478 return Shadow;
479 // (Shadow >> scale) | offset
480 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
481 MappingOffset));
482}
483
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000484void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000485 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000486 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
487 // Check the first byte.
488 {
489 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000490 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000491 }
492 // Check the last byte.
493 {
494 IRBuilder<> IRB(InsertBefore);
495 Value *SizeMinusOne = IRB.CreateSub(
496 Size, ConstantInt::get(Size->getType(), 1));
497 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
498 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
499 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000500 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000501 }
502}
503
504// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000505bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000506 Value *Dst = MI->getDest();
507 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000508 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000509 Value *Length = MI->getLength();
510
511 Constant *ConstLength = dyn_cast<Constant>(Length);
512 Instruction *InsertBefore = MI;
513 if (ConstLength) {
514 if (ConstLength->isNullValue()) return false;
515 } else {
516 // The size is not a constant so it could be zero -- check at run-time.
517 IRBuilder<> IRB(InsertBefore);
518
519 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000520 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000521 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000522 }
523
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000524 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000525 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000526 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000527 return true;
528}
529
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000530// If I is an interesting memory access, return the PointerOperand
531// and set IsWrite. Otherwise return NULL.
532static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000533 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000534 if (!ClInstrumentReads) return NULL;
535 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000536 return LI->getPointerOperand();
537 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000538 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
539 if (!ClInstrumentWrites) return NULL;
540 *IsWrite = true;
541 return SI->getPointerOperand();
542 }
543 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
544 if (!ClInstrumentAtomics) return NULL;
545 *IsWrite = true;
546 return RMW->getPointerOperand();
547 }
548 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
549 if (!ClInstrumentAtomics) return NULL;
550 *IsWrite = true;
551 return XCHG->getPointerOperand();
552 }
553 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000554}
555
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000556void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000557 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000558 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
559 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000560 if (ClOpt && ClOptGlobals) {
561 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
562 // If initialization order checking is disabled, a simple access to a
563 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000564 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000565 return;
566 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000567 // have to instrument it. However, if a global does not have initailizer
568 // at all, we assume it has dynamic initializer (in other TU).
569 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000570 return;
571 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000572 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000573
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000574 Type *OrigPtrTy = Addr->getType();
575 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
576
577 assert(OrigTy->isSized());
578 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
579
580 if (TypeSize != 8 && TypeSize != 16 &&
581 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
582 // Ignore all unusual sizes.
583 return;
584 }
585
586 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000587 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000588}
589
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000590// Validate the result of Module::getOrInsertFunction called for an interface
591// function of AddressSanitizer. If the instrumented module defines a function
592// with the same name, their prototypes must match, otherwise
593// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000594static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000595 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
596 FuncOrBitcast->dump();
597 report_fatal_error("trying to redefine an AddressSanitizer "
598 "interface function");
599}
600
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000601Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000602 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000603 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000604 IRBuilder<> IRB(InsertBefore);
605 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
606 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000607 // We don't do Call->setDoesNotReturn() because the BB already has
608 // UnreachableInst at the end.
609 // This EmptyAsm is required to avoid callback merge.
610 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000611 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000612}
613
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000614Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000615 Value *ShadowValue,
616 uint32_t TypeSize) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000617 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000618 // Addr & (Granularity - 1)
619 Value *LastAccessedByte = IRB.CreateAnd(
620 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
621 // (Addr & (Granularity - 1)) + size - 1
622 if (TypeSize / 8 > 1)
623 LastAccessedByte = IRB.CreateAdd(
624 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
625 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
626 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000627 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000628 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
629 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
630}
631
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000632void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000633 IRBuilder<> &IRB, Value *Addr,
634 uint32_t TypeSize, bool IsWrite) {
635 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
636
637 Type *ShadowTy = IntegerType::get(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000638 *C, std::max(8U, TypeSize >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000639 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
640 Value *ShadowPtr = memToShadow(AddrLong, IRB);
641 Value *CmpVal = Constant::getNullValue(ShadowTy);
642 Value *ShadowValue = IRB.CreateLoad(
643 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
644
645 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000646 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000647 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000648 TerminatorInst *CrashTerm = 0;
649
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000650 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000651 TerminatorInst *CheckTerm =
652 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000653 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000654 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000655 IRB.SetInsertPoint(CheckTerm);
656 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000657 BasicBlock *CrashBlock =
658 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000659 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000660 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
661 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000662 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000663 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000664 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000665
666 Instruction *Crash =
667 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
668 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000669}
670
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000671void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000672 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000673 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
674 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
675 // If that function is not present, this TU contains no globals, or they have
676 // all been optimized away
677 if (!GlobalInit)
678 return;
679
680 // Set up the arguments to our poison/unpoison functions.
681 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
682
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000683 // Add a call to poison all external globals before the given function starts.
684 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
685
686 // Add calls to unpoison all globals before each return instruction.
687 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
688 I != E; ++I) {
689 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
690 CallInst::Create(AsanUnpoisonGlobals, "", RI);
691 }
692 }
693}
694
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000695bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000696 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000697 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000698
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000699 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000700 if (!Ty->isSized()) return false;
701 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000702 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000703 // Touch only those globals that will not be defined in other modules.
704 // Don't handle ODR type linkages since other modules may be built w/o asan.
705 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
706 G->getLinkage() != GlobalVariable::PrivateLinkage &&
707 G->getLinkage() != GlobalVariable::InternalLinkage)
708 return false;
709 // Two problems with thread-locals:
710 // - The address of the main thread's copy can't be computed at link-time.
711 // - Need to poison all copies, not just the main thread's one.
712 if (G->isThreadLocal())
713 return false;
714 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000715 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000716
717 // Ignore all the globals with the names starting with "\01L_OBJC_".
718 // Many of those are put into the .cstring section. The linker compresses
719 // that section by removing the spare \0s after the string terminator, so
720 // our redzones get broken.
721 if ((G->getName().find("\01L_OBJC_") == 0) ||
722 (G->getName().find("\01l_OBJC_") == 0)) {
723 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
724 return false;
725 }
726
727 if (G->hasSection()) {
728 StringRef Section(G->getSection());
729 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
730 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
731 // them.
732 if ((Section.find("__OBJC,") == 0) ||
733 (Section.find("__DATA, __objc_") == 0)) {
734 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
735 return false;
736 }
737 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
738 // Constant CFString instances are compiled in the following way:
739 // -- the string buffer is emitted into
740 // __TEXT,__cstring,cstring_literals
741 // -- the constant NSConstantString structure referencing that buffer
742 // is placed into __DATA,__cfstring
743 // Therefore there's no point in placing redzones into __DATA,__cfstring.
744 // Moreover, it causes the linker to crash on OS X 10.7
745 if (Section.find("__DATA,__cfstring") == 0) {
746 DEBUG(dbgs() << "Ignoring CFString: " << *G);
747 return false;
748 }
749 }
750
751 return true;
752}
753
Alexey Samsonov46848582012-12-25 12:28:20 +0000754void AddressSanitizerModule::initializeCallbacks(Module &M) {
755 IRBuilder<> IRB(*C);
756 // Declare our poisoning and unpoisoning functions.
757 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
758 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
759 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
760 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
761 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
762 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
763 // Declare functions that register/unregister globals.
764 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
765 kAsanRegisterGlobalsName, IRB.getVoidTy(),
766 IntptrTy, IntptrTy, NULL));
767 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
768 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
769 kAsanUnregisterGlobalsName,
770 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
771 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
772}
773
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000774// This function replaces all global variables with new variables that have
775// trailing redzones. It also creates a function that poisons
776// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000777bool AddressSanitizerModule::runOnModule(Module &M) {
778 if (!ClGlobals) return false;
779 TD = getAnalysisIfAvailable<DataLayout>();
780 if (!TD)
781 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000782 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000783 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000784 C = &(M.getContext());
785 IntptrTy = Type::getIntNTy(*C, TD->getPointerSizeInBits());
Alexey Samsonov46848582012-12-25 12:28:20 +0000786 initializeCallbacks(M);
787 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000788
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000789 SmallVector<GlobalVariable *, 16> GlobalsToChange;
790
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000791 for (Module::GlobalListType::iterator G = M.global_begin(),
792 E = M.global_end(); G != E; ++G) {
793 if (ShouldInstrumentGlobal(G))
794 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000795 }
796
797 size_t n = GlobalsToChange.size();
798 if (n == 0) return false;
799
800 // A global is described by a structure
801 // size_t beg;
802 // size_t size;
803 // size_t size_with_redzone;
804 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000805 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000806 // We initialize an array of such structures and pass it to a run-time call.
807 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000808 IntptrTy, IntptrTy,
809 IntptrTy, NULL);
810 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000811
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000812
813 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
814 assert(CtorFunc);
815 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000816
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000817 // The addresses of the first and last dynamically initialized globals in
818 // this TU. Used in initialization order checking.
819 Value *FirstDynamic = 0, *LastDynamic = 0;
820
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000821 for (size_t i = 0; i < n; i++) {
822 GlobalVariable *G = GlobalsToChange[i];
823 PointerType *PtrTy = cast<PointerType>(G->getType());
824 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000825 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000826 size_t RZ = RedzoneSize();
827 uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000828 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000829 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000830 bool GlobalHasDynamicInitializer =
831 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000832 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000833 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000834
835 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
836 Constant *NewInitializer = ConstantStruct::get(
837 NewTy, G->getInitializer(),
838 Constant::getNullValue(RightRedZoneTy), NULL);
839
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000840 SmallString<2048> DescriptionOfGlobal = G->getName();
841 DescriptionOfGlobal += " (";
842 DescriptionOfGlobal += M.getModuleIdentifier();
843 DescriptionOfGlobal += ")";
844 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000845
846 // Create a new global variable with enough space for a redzone.
847 GlobalVariable *NewGlobal = new GlobalVariable(
848 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000849 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000850 NewGlobal->copyAttributesFrom(G);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000851 NewGlobal->setAlignment(RZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000852
853 Value *Indices2[2];
854 Indices2[0] = IRB.getInt32(0);
855 Indices2[1] = IRB.getInt32(0);
856
857 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000858 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000859 NewGlobal->takeName(G);
860 G->eraseFromParent();
861
862 Initializers[i] = ConstantStruct::get(
863 GlobalStructTy,
864 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
865 ConstantInt::get(IntptrTy, SizeInBytes),
866 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
867 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000868 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000869 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000870
871 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000872 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000873 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
874 if (FirstDynamic == 0)
875 FirstDynamic = LastDynamic;
876 }
877
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000878 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000879 }
880
881 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
882 GlobalVariable *AllGlobals = new GlobalVariable(
883 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
884 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
885
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000886 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000887 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000888 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000889 IRB.CreateCall2(AsanRegisterGlobals,
890 IRB.CreatePointerCast(AllGlobals, IntptrTy),
891 ConstantInt::get(IntptrTy, n));
892
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000893 // We also need to unregister globals at the end, e.g. when a shared library
894 // gets closed.
895 Function *AsanDtorFunction = Function::Create(
896 FunctionType::get(Type::getVoidTy(*C), false),
897 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
898 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
899 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000900 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
901 IRB.CreatePointerCast(AllGlobals, IntptrTy),
902 ConstantInt::get(IntptrTy, n));
903 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
904
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000905 DEBUG(dbgs() << M);
906 return true;
907}
908
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000909void AddressSanitizer::initializeCallbacks(Module &M) {
910 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000911 // Create __asan_report* callbacks.
912 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
913 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
914 AccessSizeIndex++) {
915 // IsWrite and TypeSize are encoded in the function name.
916 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
917 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000918 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000919 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
920 checkInterfaceFunction(M.getOrInsertFunction(
921 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000922 }
923 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000924
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000925 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
926 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000927 // We insert an empty inline asm after __asan_report* to avoid callback merge.
928 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
929 StringRef(""), StringRef(""),
930 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000931}
932
933// virtual
934bool AddressSanitizer::doInitialization(Module &M) {
935 // Initialize the private fields. No one has accessed them before.
936 TD = getAnalysisIfAvailable<DataLayout>();
937
938 if (!TD)
939 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000940 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000941 DynamicallyInitializedGlobals.Init(M);
942
943 C = &(M.getContext());
944 LongSize = TD->getPointerSizeInBits();
945 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000946
947 AsanCtorFunction = Function::Create(
948 FunctionType::get(Type::getVoidTy(*C), false),
949 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
950 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
951 // call __asan_init in the module ctor.
952 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
953 AsanInitFunction = checkInterfaceFunction(
954 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
955 AsanInitFunction->setLinkage(Function::ExternalLinkage);
956 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000957
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000958 llvm::Triple targetTriple(M.getTargetTriple());
Logan Chien43bf7092012-09-02 09:29:46 +0000959 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000960
961 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
962 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000963 if (ClMappingOffsetLog >= 0) {
964 if (ClMappingOffsetLog == 0) {
965 // special case
966 MappingOffset = 0;
967 } else {
968 MappingOffset = 1ULL << ClMappingOffsetLog;
969 }
970 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000971
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000972
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000973 if (ClMappingOffsetLog >= 0) {
974 // Tell the run-time the current values of mapping offset and scale.
975 GlobalValue *asan_mapping_offset =
976 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
977 ConstantInt::get(IntptrTy, MappingOffset),
978 kAsanMappingOffsetName);
979 // Read the global, otherwise it may be optimized away.
980 IRB.CreateLoad(asan_mapping_offset, true);
981 }
982 if (ClMappingScale) {
983 GlobalValue *asan_mapping_scale =
984 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000985 ConstantInt::get(IntptrTy, MappingScale()),
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000986 kAsanMappingScaleName);
987 // Read the global, otherwise it may be optimized away.
988 IRB.CreateLoad(asan_mapping_scale, true);
989 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000990
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000991 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000992
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000993 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000994}
995
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000996bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
997 // For each NSObject descendant having a +load method, this method is invoked
998 // by the ObjC runtime before any of the static constructors is called.
999 // Therefore we need to instrument such methods with a call to __asan_init
1000 // at the beginning in order to initialize our runtime before any access to
1001 // the shadow memory.
1002 // We cannot just ignore these methods, because they may call other
1003 // instrumented functions.
1004 if (F.getName().find(" load]") != std::string::npos) {
1005 IRBuilder<> IRB(F.begin()->begin());
1006 IRB.CreateCall(AsanInitFunction);
1007 return true;
1008 }
1009 return false;
1010}
1011
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001012bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001013 if (BL->isIn(F)) return false;
1014 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001015 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001016 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001017
1018 // If needed, insert __asan_init before checking for AddressSafety attr.
1019 maybeInsertAsanInitAtFunctionEntry(F);
1020
Bill Wendling831737d2012-12-30 10:32:01 +00001021 if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1022 Attribute::AddressSafety))
Bill Wendling67658342012-10-09 07:45:08 +00001023 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001024
1025 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1026 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001027
1028 // We want to instrument every address only once per basic block (unless there
1029 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001030 SmallSet<Value*, 16> TempsToInstrument;
1031 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001032 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001033 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001034
1035 // Fill the set of memory operations to instrument.
1036 for (Function::iterator FI = F.begin(), FE = F.end();
1037 FI != FE; ++FI) {
1038 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001039 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001040 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1041 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001042 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001043 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001044 if (ClOpt && ClOptSameTemp) {
1045 if (!TempsToInstrument.insert(Addr))
1046 continue; // We've seen this temp in the current BB.
1047 }
1048 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1049 // ok, take it.
1050 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001051 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001052 // A call inside BB.
1053 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +00001054 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001055 NoReturnCalls.push_back(CI);
1056 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001057 }
1058 continue;
1059 }
1060 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001061 NumInsnsPerBB++;
1062 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1063 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001064 }
1065 }
1066
1067 // Instrument.
1068 int NumInstrumented = 0;
1069 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1070 Instruction *Inst = ToInstrument[i];
1071 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1072 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001073 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001074 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001075 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001076 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001077 }
1078 NumInstrumented++;
1079 }
1080
Alexey Samsonov59cca132012-12-25 12:04:36 +00001081 FunctionStackPoisoner FSP(F, *this);
1082 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001083
1084 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1085 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1086 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1087 Instruction *CI = NoReturnCalls[i];
1088 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001089 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001090 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001091 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001092
1093 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001094}
1095
1096static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1097 if (ShadowRedzoneSize == 1) return PoisonByte;
1098 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1099 if (ShadowRedzoneSize == 4)
1100 return (PoisonByte << 24) + (PoisonByte << 16) +
1101 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001102 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001103}
1104
1105static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1106 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001107 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001108 size_t ShadowGranularity,
1109 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001110 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001111 i+= ShadowGranularity, Shadow++) {
1112 if (i + ShadowGranularity <= Size) {
1113 *Shadow = 0; // fully addressable
1114 } else if (i >= Size) {
1115 *Shadow = Magic; // unaddressable
1116 } else {
1117 *Shadow = Size - i; // first Size-i bytes are addressable
1118 }
1119 }
1120}
1121
Alexey Samsonov59cca132012-12-25 12:04:36 +00001122// Workaround for bug 11395: we don't want to instrument stack in functions
1123// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1124// FIXME: remove once the bug 11395 is fixed.
1125bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1126 if (LongSize != 32) return false;
1127 CallInst *CI = dyn_cast<CallInst>(I);
1128 if (!CI || !CI->isInlineAsm()) return false;
1129 if (CI->getNumArgOperands() <= 5) return false;
1130 // We have inline assembly with quite a few arguments.
1131 return true;
1132}
1133
1134void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1135 IRBuilder<> IRB(*C);
1136 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1137 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1138 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1139 kAsanStackFreeName, IRB.getVoidTy(),
1140 IntptrTy, IntptrTy, IntptrTy, NULL));
1141 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1142 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1143 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1144 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1145}
1146
1147void FunctionStackPoisoner::poisonRedZones(
1148 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1149 bool DoPoison) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001150 size_t ShadowRZSize = RedzoneSize() >> MappingScale();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001151 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1152 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1153 Type *RZPtrTy = PointerType::get(RZTy, 0);
1154
1155 Value *PoisonLeft = ConstantInt::get(RZTy,
1156 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1157 Value *PoisonMid = ConstantInt::get(RZTy,
1158 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1159 Value *PoisonRight = ConstantInt::get(RZTy,
1160 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1161
1162 // poison the first red zone.
1163 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1164
1165 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001166 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001167 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1168 AllocaInst *AI = AllocaVec[i];
1169 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1170 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001171 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001172 Value *Ptr = NULL;
1173
1174 Pos += AlignedSize;
1175
1176 assert(ShadowBase->getType() == IntptrTy);
1177 if (SizeInBytes < AlignedSize) {
1178 // Poison the partial redzone at right
1179 Ptr = IRB.CreateAdd(
1180 ShadowBase, ConstantInt::get(IntptrTy,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001181 (Pos >> MappingScale()) - ShadowRZSize));
1182 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001183 uint32_t Poison = 0;
1184 if (DoPoison) {
1185 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001186 RedzoneSize(),
1187 1ULL << MappingScale(),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001188 kAsanStackPartialRedzoneMagic);
1189 }
1190 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1191 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1192 }
1193
1194 // Poison the full redzone at right.
1195 Ptr = IRB.CreateAdd(ShadowBase,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001196 ConstantInt::get(IntptrTy, Pos >> MappingScale()));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001197 bool LastAlloca = (i == AllocaVec.size() - 1);
1198 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001199 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1200
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001201 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001202 }
1203}
1204
Alexey Samsonov59cca132012-12-25 12:04:36 +00001205void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001206 uint64_t LocalStackSize = TotalStackSize +
1207 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001208
Alexey Samsonov59cca132012-12-25 12:04:36 +00001209 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001210 && LocalStackSize <= kMaxStackMallocSize;
1211
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001212 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001213 Instruction *InsBefore = AllocaVec[0];
1214 IRBuilder<> IRB(InsBefore);
1215
1216
1217 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1218 AllocaInst *MyAlloca =
1219 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001220 if (ClRealignStack && StackAlignment < RedzoneSize())
1221 StackAlignment = RedzoneSize();
1222 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001223 assert(MyAlloca->isStaticAlloca());
1224 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1225 Value *LocalStackBase = OrigStackBase;
1226
1227 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001228 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1229 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1230 }
1231
1232 // This string will be parsed by the run-time (DescribeStackAddress).
1233 SmallString<2048> StackDescriptionStorage;
1234 raw_svector_ostream StackDescription(StackDescriptionStorage);
1235 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1236
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001237 // Insert poison calls for lifetime intrinsics for alloca.
1238 bool HavePoisonedAllocas = false;
1239 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1240 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1241 IntrinsicInst *II = APC.InsBefore;
1242 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1243 assert(AI);
1244 IRBuilder<> IRB(II);
1245 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1246 HavePoisonedAllocas |= APC.DoPoison;
1247 }
1248
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001249 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001250 // Replace Alloca instructions with base+offset.
1251 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1252 AllocaInst *AI = AllocaVec[i];
1253 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1254 StringRef Name = AI->getName();
1255 StackDescription << Pos << " " << SizeInBytes << " "
1256 << Name.size() << " " << Name << " ";
1257 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001258 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001259 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001260 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001261 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001262 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001263 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001264 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001265 }
1266 assert(Pos == LocalStackSize);
1267
1268 // Write the Magic value and the frame description constant to the redzone.
1269 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1270 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1271 BasePlus0);
1272 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001273 ConstantInt::get(IntptrTy,
1274 ASan.LongSize/8));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001275 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001276 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001277 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001278 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1279 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001280 IRB.CreateStore(Description, BasePlus1);
1281
1282 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001283 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1284 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001285
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001286 // Unpoison the stack before all ret instructions.
1287 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1288 Instruction *Ret = RetVec[i];
1289 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001290 // Mark the current frame as retired.
1291 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1292 BasePlus0);
1293 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001294 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001295 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001296 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001297 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1298 ConstantInt::get(IntptrTy, LocalStackSize),
1299 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001300 } else if (HavePoisonedAllocas) {
1301 // If we poisoned some allocas in llvm.lifetime analysis,
1302 // unpoison whole stack frame now.
1303 assert(LocalStackBase == OrigStackBase);
1304 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001305 }
1306 }
1307
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001308 // We are done. Remove the old unused alloca instructions.
1309 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1310 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001311}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001312
Alexey Samsonov59cca132012-12-25 12:04:36 +00001313void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1314 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001315 // For now just insert the call to ASan runtime.
1316 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1317 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1318 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1319 : AsanUnpoisonStackMemoryFunc,
1320 AddrArg, SizeArg);
1321}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001322
1323// Handling llvm.lifetime intrinsics for a given %alloca:
1324// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1325// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1326// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1327// could be poisoned by previous llvm.lifetime.end instruction, as the
1328// variable may go in and out of scope several times, e.g. in loops).
1329// (3) if we poisoned at least one %alloca in a function,
1330// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001331
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001332AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1333 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1334 // We're intested only in allocas we can handle.
1335 return isInterestingAlloca(*AI) ? AI : 0;
1336 // See if we've already calculated (or started to calculate) alloca for a
1337 // given value.
1338 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1339 if (I != AllocaForValue.end())
1340 return I->second;
1341 // Store 0 while we're calculating alloca for value V to avoid
1342 // infinite recursion if the value references itself.
1343 AllocaForValue[V] = 0;
1344 AllocaInst *Res = 0;
1345 if (CastInst *CI = dyn_cast<CastInst>(V))
1346 Res = findAllocaForValue(CI->getOperand(0));
1347 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1348 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1349 Value *IncValue = PN->getIncomingValue(i);
1350 // Allow self-referencing phi-nodes.
1351 if (IncValue == PN) continue;
1352 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1353 // AI for incoming values should exist and should all be equal.
1354 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1355 return 0;
1356 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001357 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001358 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001359 if (Res != 0)
1360 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001361 return Res;
1362}