blob: f4715f541a3417eacf4ba6401aea689cb1fc1d01 [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 Serebryany800e03f2011-11-16 01:35:23 +000019#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov1c8b8252012-12-27 08:50:58 +000020#include "llvm/ADT/DenseMap.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000021#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000022#include "llvm/ADT/OwningPtr.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000027#include "llvm/ADT/Triple.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000028#include "llvm/DIBuilder.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/Type.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000037#include "llvm/InstVisitor.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000038#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/DataTypes.h"
40#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000041#include "llvm/Support/raw_ostream.h"
42#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043#include "llvm/Target/TargetMachine.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth90230c82013-01-19 08:03:47 +000045#include "llvm/Transforms/Utils/BlackList.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;
Kostya Serebryany48a615f2013-01-23 12:54:55 +000056static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
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
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000189/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000190/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000191struct ShadowMapping {
192 int Scale;
193 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000194 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000195};
196
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000197static ShadowMapping getShadowMapping(const Module &M, int LongSize,
198 bool ZeroBaseShadow) {
199 llvm::Triple TargetTriple(M.getTargetTriple());
200 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000201 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000202
203 ShadowMapping Mapping;
204
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000205 // OR-ing shadow offset if more efficient (at least on x86),
206 // but on ppc64 we have to use add since the shadow offset is not neccesary
207 // 1/8-th of the address space.
208 Mapping.OrShadowOffset = !IsPPC64;
209
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000210 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000211 (LongSize == 32 ? kDefaultShadowOffset32 :
212 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000213 if (ClMappingOffsetLog >= 0) {
214 // Zero offset log is the special case.
215 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
216 }
217
218 Mapping.Scale = kDefaultShadowScale;
219 if (ClMappingScale) {
220 Mapping.Scale = ClMappingScale;
221 }
222
223 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000224}
225
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000226static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000227 // Redzone used for stack and globals is at least 32 bytes.
228 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000229 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000230}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000231
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000232/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000233struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000234 AddressSanitizer(bool CheckInitOrder = false,
235 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000236 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000237 StringRef BlacklistFile = StringRef(),
238 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000239 : FunctionPass(ID),
240 CheckInitOrder(CheckInitOrder || ClInitializers),
241 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000242 CheckLifetime(CheckLifetime || ClCheckLifetime),
243 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000244 : BlacklistFile),
245 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000246 virtual const char *getPassName() const {
247 return "AddressSanitizerFunctionPass";
248 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000249 void instrumentMop(Instruction *I);
250 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000251 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000252 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
253 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000254 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000255 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000256 bool instrumentMemIntrinsic(MemIntrinsic *MI);
257 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000258 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000259 Instruction *InsertBefore, bool IsWrite);
260 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000261 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000262 void createInitializerPoisonCalls(Module &M,
263 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000264 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000265 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000266 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000267 static char ID; // Pass identification, replacement for typeid
268
269 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000270 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000271
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000272 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000273 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000274 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000275
Alexey Samsonovee548272012-11-29 18:14:24 +0000276 bool CheckInitOrder;
277 bool CheckUseAfterReturn;
278 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000279 SmallString<64> BlacklistFile;
280 bool ZeroBaseShadow;
281
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000282 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000283 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000284 int LongSize;
285 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000286 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000287 Function *AsanCtorFunction;
288 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000289 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000290 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000291 // This array is indexed by AccessIsWrite and log2(AccessSize).
292 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000293 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000294 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000295
296 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000297};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000298
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000299class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000300 public:
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000301 AddressSanitizerModule(bool CheckInitOrder = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000302 StringRef BlacklistFile = StringRef(),
303 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000304 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000305 CheckInitOrder(CheckInitOrder || ClInitializers),
306 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000307 : BlacklistFile),
308 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000309 bool runOnModule(Module &M);
310 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000311 virtual const char *getPassName() const {
312 return "AddressSanitizerModule";
313 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000314
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000315 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000316 void initializeCallbacks(Module &M);
317
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000318 bool ShouldInstrumentGlobal(GlobalVariable *G);
319 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
320 Value *LastAddr);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000321 size_t RedzoneSize() const {
322 return RedzoneSizeForScale(Mapping.Scale);
323 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000324
Alexey Samsonovee548272012-11-29 18:14:24 +0000325 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000326 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000327 bool ZeroBaseShadow;
328
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000329 OwningPtr<BlackList> BL;
330 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
331 Type *IntptrTy;
332 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000333 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000334 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000335 Function *AsanPoisonGlobals;
336 Function *AsanUnpoisonGlobals;
337 Function *AsanRegisterGlobals;
338 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000339};
340
Alexey Samsonov59cca132012-12-25 12:04:36 +0000341// Stack poisoning does not play well with exception handling.
342// When an exception is thrown, we essentially bypass the code
343// that unpoisones the stack. This is why the run-time library has
344// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
345// stack in the interceptor. This however does not work inside the
346// actual function which catches the exception. Most likely because the
347// compiler hoists the load of the shadow value somewhere too high.
348// This causes asan to report a non-existing bug on 453.povray.
349// It sounds like an LLVM bug.
350struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
351 Function &F;
352 AddressSanitizer &ASan;
353 DIBuilder DIB;
354 LLVMContext *C;
355 Type *IntptrTy;
356 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000357 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000358
359 SmallVector<AllocaInst*, 16> AllocaVec;
360 SmallVector<Instruction*, 8> RetVec;
361 uint64_t TotalStackSize;
362 unsigned StackAlignment;
363
364 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
365 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
366
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000367 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
368 struct AllocaPoisonCall {
369 IntrinsicInst *InsBefore;
370 uint64_t Size;
371 bool DoPoison;
372 };
373 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
374
375 // Maps Value to an AllocaInst from which the Value is originated.
376 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
377 AllocaForValueMapTy AllocaForValue;
378
Alexey Samsonov59cca132012-12-25 12:04:36 +0000379 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
380 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
381 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000382 Mapping(ASan.Mapping),
383 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000384
385 bool runOnFunction() {
386 if (!ClStack) return false;
387 // Collect alloca, ret, lifetime instructions etc.
388 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
389 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
390 BasicBlock *BB = *DI;
391 visit(*BB);
392 }
393 if (AllocaVec.empty()) return false;
394
395 initializeCallbacks(*F.getParent());
396
397 poisonStack();
398
399 if (ClDebugStack) {
400 DEBUG(dbgs() << F);
401 }
402 return true;
403 }
404
405 // Finds all static Alloca instructions and puts
406 // poisoned red zones around all of them.
407 // Then unpoison everything back before the function returns.
408 void poisonStack();
409
410 // ----------------------- Visitors.
411 /// \brief Collect all Ret instructions.
412 void visitReturnInst(ReturnInst &RI) {
413 RetVec.push_back(&RI);
414 }
415
416 /// \brief Collect Alloca instructions we want (and can) handle.
417 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000418 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000419
420 StackAlignment = std::max(StackAlignment, AI.getAlignment());
421 AllocaVec.push_back(&AI);
422 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
423 TotalStackSize += AlignedSize;
424 }
425
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000426 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
427 /// errors.
428 void visitIntrinsicInst(IntrinsicInst &II) {
429 if (!ASan.CheckLifetime) return;
430 Intrinsic::ID ID = II.getIntrinsicID();
431 if (ID != Intrinsic::lifetime_start &&
432 ID != Intrinsic::lifetime_end)
433 return;
434 // Found lifetime intrinsic, add ASan instrumentation if necessary.
435 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
436 // If size argument is undefined, don't do anything.
437 if (Size->isMinusOne()) return;
438 // Check that size doesn't saturate uint64_t and can
439 // be stored in IntptrTy.
440 const uint64_t SizeValue = Size->getValue().getLimitedValue();
441 if (SizeValue == ~0ULL ||
442 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
443 return;
444 // Find alloca instruction that corresponds to llvm.lifetime argument.
445 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
446 if (!AI) return;
447 bool DoPoison = (ID == Intrinsic::lifetime_end);
448 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
449 AllocaPoisonCallVec.push_back(APC);
450 }
451
Alexey Samsonov59cca132012-12-25 12:04:36 +0000452 // ---------------------- Helpers.
453 void initializeCallbacks(Module &M);
454
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000455 // Check if we want (and can) handle this alloca.
456 bool isInterestingAlloca(AllocaInst &AI) {
457 return (!AI.isArrayAllocation() &&
458 AI.isStaticAlloca() &&
459 AI.getAllocatedType()->isSized());
460 }
461
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000462 size_t RedzoneSize() const {
463 return RedzoneSizeForScale(Mapping.Scale);
464 }
Alexey Samsonov59cca132012-12-25 12:04:36 +0000465 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
466 Type *Ty = AI->getAllocatedType();
467 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
468 return SizeInBytes;
469 }
470 uint64_t getAlignedSize(uint64_t SizeInBytes) {
471 size_t RZ = RedzoneSize();
472 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
473 }
474 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
475 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
476 return getAlignedSize(SizeInBytes);
477 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000478 /// Finds alloca where the value comes from.
479 AllocaInst *findAllocaForValue(Value *V);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000480 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
481 Value *ShadowBase, bool DoPoison);
482 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000483};
484
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000485} // namespace
486
487char AddressSanitizer::ID = 0;
488INITIALIZE_PASS(AddressSanitizer, "asan",
489 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
490 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000491FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000492 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000493 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000494 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000495 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000496}
497
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000498char AddressSanitizerModule::ID = 0;
499INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
500 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
501 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000502ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000503 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
504 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
505 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000506}
507
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000508static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
509 size_t Res = CountTrailingZeros_32(TypeSize / 8);
510 assert(Res < kNumberOfAccessSizes);
511 return Res;
512}
513
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000514// Create a constant for Str so that we can pass it to the run-time lib.
515static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000516 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000517 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000518 GlobalValue::PrivateLinkage, StrConst,
519 kAsanGenPrefix);
520}
521
522static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
523 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000524}
525
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000526Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
527 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000528 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
529 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000530 return Shadow;
531 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000532 if (Mapping.OrShadowOffset)
533 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
534 else
535 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000536}
537
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000538void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000539 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000540 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
541 // Check the first byte.
542 {
543 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000544 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000545 }
546 // Check the last byte.
547 {
548 IRBuilder<> IRB(InsertBefore);
549 Value *SizeMinusOne = IRB.CreateSub(
550 Size, ConstantInt::get(Size->getType(), 1));
551 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
552 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
553 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000554 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000555 }
556}
557
558// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000559bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000560 Value *Dst = MI->getDest();
561 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000562 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000563 Value *Length = MI->getLength();
564
565 Constant *ConstLength = dyn_cast<Constant>(Length);
566 Instruction *InsertBefore = MI;
567 if (ConstLength) {
568 if (ConstLength->isNullValue()) return false;
569 } else {
570 // The size is not a constant so it could be zero -- check at run-time.
571 IRBuilder<> IRB(InsertBefore);
572
573 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000574 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000575 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000576 }
577
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000578 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000579 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000580 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000581 return true;
582}
583
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000584// If I is an interesting memory access, return the PointerOperand
585// and set IsWrite. Otherwise return NULL.
586static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000587 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000588 if (!ClInstrumentReads) return NULL;
589 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000590 return LI->getPointerOperand();
591 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000592 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
593 if (!ClInstrumentWrites) return NULL;
594 *IsWrite = true;
595 return SI->getPointerOperand();
596 }
597 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
598 if (!ClInstrumentAtomics) return NULL;
599 *IsWrite = true;
600 return RMW->getPointerOperand();
601 }
602 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
603 if (!ClInstrumentAtomics) return NULL;
604 *IsWrite = true;
605 return XCHG->getPointerOperand();
606 }
607 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000608}
609
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000610void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000611 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000612 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
613 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000614 if (ClOpt && ClOptGlobals) {
615 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
616 // If initialization order checking is disabled, a simple access to a
617 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000618 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000619 return;
620 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000621 // have to instrument it. However, if a global does not have initailizer
622 // at all, we assume it has dynamic initializer (in other TU).
623 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000624 return;
625 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000626 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000627
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000628 Type *OrigPtrTy = Addr->getType();
629 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
630
631 assert(OrigTy->isSized());
632 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
633
634 if (TypeSize != 8 && TypeSize != 16 &&
635 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
636 // Ignore all unusual sizes.
637 return;
638 }
639
640 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000641 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000642}
643
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000644// Validate the result of Module::getOrInsertFunction called for an interface
645// function of AddressSanitizer. If the instrumented module defines a function
646// with the same name, their prototypes must match, otherwise
647// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000648static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000649 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
650 FuncOrBitcast->dump();
651 report_fatal_error("trying to redefine an AddressSanitizer "
652 "interface function");
653}
654
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000655Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000656 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000657 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000658 IRBuilder<> IRB(InsertBefore);
659 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
660 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000661 // We don't do Call->setDoesNotReturn() because the BB already has
662 // UnreachableInst at the end.
663 // This EmptyAsm is required to avoid callback merge.
664 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000665 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000666}
667
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000668Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000669 Value *ShadowValue,
670 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000671 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000672 // Addr & (Granularity - 1)
673 Value *LastAccessedByte = IRB.CreateAnd(
674 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
675 // (Addr & (Granularity - 1)) + size - 1
676 if (TypeSize / 8 > 1)
677 LastAccessedByte = IRB.CreateAdd(
678 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
679 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
680 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000681 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000682 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
683 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
684}
685
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000686void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000687 IRBuilder<> &IRB, Value *Addr,
688 uint32_t TypeSize, bool IsWrite) {
689 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
690
691 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000692 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000693 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
694 Value *ShadowPtr = memToShadow(AddrLong, IRB);
695 Value *CmpVal = Constant::getNullValue(ShadowTy);
696 Value *ShadowValue = IRB.CreateLoad(
697 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
698
699 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000700 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000701 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000702 TerminatorInst *CrashTerm = 0;
703
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000704 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000705 TerminatorInst *CheckTerm =
706 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000707 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000708 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000709 IRB.SetInsertPoint(CheckTerm);
710 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000711 BasicBlock *CrashBlock =
712 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000713 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000714 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
715 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000716 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000717 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000718 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000719
720 Instruction *Crash =
721 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
722 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000723}
724
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000725void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000726 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000727 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
728 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
729 // If that function is not present, this TU contains no globals, or they have
730 // all been optimized away
731 if (!GlobalInit)
732 return;
733
734 // Set up the arguments to our poison/unpoison functions.
735 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
736
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000737 // Add a call to poison all external globals before the given function starts.
738 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
739
740 // Add calls to unpoison all globals before each return instruction.
741 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
742 I != E; ++I) {
743 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
744 CallInst::Create(AsanUnpoisonGlobals, "", RI);
745 }
746 }
747}
748
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000749bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000750 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000751 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000752
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000753 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000754 if (!Ty->isSized()) return false;
755 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000756 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000757 // Touch only those globals that will not be defined in other modules.
758 // Don't handle ODR type linkages since other modules may be built w/o asan.
759 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
760 G->getLinkage() != GlobalVariable::PrivateLinkage &&
761 G->getLinkage() != GlobalVariable::InternalLinkage)
762 return false;
763 // Two problems with thread-locals:
764 // - The address of the main thread's copy can't be computed at link-time.
765 // - Need to poison all copies, not just the main thread's one.
766 if (G->isThreadLocal())
767 return false;
768 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000769 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000770
771 // Ignore all the globals with the names starting with "\01L_OBJC_".
772 // Many of those are put into the .cstring section. The linker compresses
773 // that section by removing the spare \0s after the string terminator, so
774 // our redzones get broken.
775 if ((G->getName().find("\01L_OBJC_") == 0) ||
776 (G->getName().find("\01l_OBJC_") == 0)) {
777 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
778 return false;
779 }
780
781 if (G->hasSection()) {
782 StringRef Section(G->getSection());
783 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
784 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
785 // them.
786 if ((Section.find("__OBJC,") == 0) ||
787 (Section.find("__DATA, __objc_") == 0)) {
788 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
789 return false;
790 }
791 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
792 // Constant CFString instances are compiled in the following way:
793 // -- the string buffer is emitted into
794 // __TEXT,__cstring,cstring_literals
795 // -- the constant NSConstantString structure referencing that buffer
796 // is placed into __DATA,__cfstring
797 // Therefore there's no point in placing redzones into __DATA,__cfstring.
798 // Moreover, it causes the linker to crash on OS X 10.7
799 if (Section.find("__DATA,__cfstring") == 0) {
800 DEBUG(dbgs() << "Ignoring CFString: " << *G);
801 return false;
802 }
803 }
804
805 return true;
806}
807
Alexey Samsonov46848582012-12-25 12:28:20 +0000808void AddressSanitizerModule::initializeCallbacks(Module &M) {
809 IRBuilder<> IRB(*C);
810 // Declare our poisoning and unpoisoning functions.
811 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
812 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
813 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
814 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
815 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
816 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
817 // Declare functions that register/unregister globals.
818 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
819 kAsanRegisterGlobalsName, IRB.getVoidTy(),
820 IntptrTy, IntptrTy, NULL));
821 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
822 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
823 kAsanUnregisterGlobalsName,
824 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
825 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
826}
827
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000828// This function replaces all global variables with new variables that have
829// trailing redzones. It also creates a function that poisons
830// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000831bool AddressSanitizerModule::runOnModule(Module &M) {
832 if (!ClGlobals) return false;
833 TD = getAnalysisIfAvailable<DataLayout>();
834 if (!TD)
835 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000836 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000837 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000838 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000839 int LongSize = TD->getPointerSizeInBits();
840 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000841 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000842 initializeCallbacks(M);
843 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000844
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000845 SmallVector<GlobalVariable *, 16> GlobalsToChange;
846
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000847 for (Module::GlobalListType::iterator G = M.global_begin(),
848 E = M.global_end(); G != E; ++G) {
849 if (ShouldInstrumentGlobal(G))
850 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000851 }
852
853 size_t n = GlobalsToChange.size();
854 if (n == 0) return false;
855
856 // A global is described by a structure
857 // size_t beg;
858 // size_t size;
859 // size_t size_with_redzone;
860 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000861 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000862 // We initialize an array of such structures and pass it to a run-time call.
863 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000864 IntptrTy, IntptrTy,
865 IntptrTy, NULL);
866 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000867
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000868
869 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
870 assert(CtorFunc);
871 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000872
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000873 // The addresses of the first and last dynamically initialized globals in
874 // this TU. Used in initialization order checking.
875 Value *FirstDynamic = 0, *LastDynamic = 0;
876
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000877 for (size_t i = 0; i < n; i++) {
878 GlobalVariable *G = GlobalsToChange[i];
879 PointerType *PtrTy = cast<PointerType>(G->getType());
880 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000881 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000882 size_t RZ = RedzoneSize();
883 uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000884 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000885 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000886 bool GlobalHasDynamicInitializer =
887 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000888 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000889 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000890
891 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
892 Constant *NewInitializer = ConstantStruct::get(
893 NewTy, G->getInitializer(),
894 Constant::getNullValue(RightRedZoneTy), NULL);
895
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000896 SmallString<2048> DescriptionOfGlobal = G->getName();
897 DescriptionOfGlobal += " (";
898 DescriptionOfGlobal += M.getModuleIdentifier();
899 DescriptionOfGlobal += ")";
900 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000901
902 // Create a new global variable with enough space for a redzone.
903 GlobalVariable *NewGlobal = new GlobalVariable(
904 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000905 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000906 NewGlobal->copyAttributesFrom(G);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000907 NewGlobal->setAlignment(RZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000908
909 Value *Indices2[2];
910 Indices2[0] = IRB.getInt32(0);
911 Indices2[1] = IRB.getInt32(0);
912
913 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000914 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000915 NewGlobal->takeName(G);
916 G->eraseFromParent();
917
918 Initializers[i] = ConstantStruct::get(
919 GlobalStructTy,
920 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
921 ConstantInt::get(IntptrTy, SizeInBytes),
922 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
923 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000924 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000925 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000926
927 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000928 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000929 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
930 if (FirstDynamic == 0)
931 FirstDynamic = LastDynamic;
932 }
933
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000934 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000935 }
936
937 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
938 GlobalVariable *AllGlobals = new GlobalVariable(
939 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
940 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
941
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000942 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000943 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000944 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000945 IRB.CreateCall2(AsanRegisterGlobals,
946 IRB.CreatePointerCast(AllGlobals, IntptrTy),
947 ConstantInt::get(IntptrTy, n));
948
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000949 // We also need to unregister globals at the end, e.g. when a shared library
950 // gets closed.
951 Function *AsanDtorFunction = Function::Create(
952 FunctionType::get(Type::getVoidTy(*C), false),
953 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
954 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
955 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000956 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
957 IRB.CreatePointerCast(AllGlobals, IntptrTy),
958 ConstantInt::get(IntptrTy, n));
959 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
960
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000961 DEBUG(dbgs() << M);
962 return true;
963}
964
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000965void AddressSanitizer::initializeCallbacks(Module &M) {
966 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000967 // Create __asan_report* callbacks.
968 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
969 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
970 AccessSizeIndex++) {
971 // IsWrite and TypeSize are encoded in the function name.
972 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
973 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000974 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000975 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
976 checkInterfaceFunction(M.getOrInsertFunction(
977 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000978 }
979 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000980
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000981 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
982 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000983 // We insert an empty inline asm after __asan_report* to avoid callback merge.
984 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
985 StringRef(""), StringRef(""),
986 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000987}
988
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000989void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000990 // Tell the values of mapping offset and scale to the run-time.
991 GlobalValue *asan_mapping_offset =
992 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
993 ConstantInt::get(IntptrTy, Mapping.Offset),
994 kAsanMappingOffsetName);
995 // Read the global, otherwise it may be optimized away.
996 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000997
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000998 GlobalValue *asan_mapping_scale =
999 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1000 ConstantInt::get(IntptrTy, Mapping.Scale),
1001 kAsanMappingScaleName);
1002 // Read the global, otherwise it may be optimized away.
1003 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001004}
1005
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001006// virtual
1007bool AddressSanitizer::doInitialization(Module &M) {
1008 // Initialize the private fields. No one has accessed them before.
1009 TD = getAnalysisIfAvailable<DataLayout>();
1010
1011 if (!TD)
1012 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +00001013 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001014 DynamicallyInitializedGlobals.Init(M);
1015
1016 C = &(M.getContext());
1017 LongSize = TD->getPointerSizeInBits();
1018 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001019
1020 AsanCtorFunction = Function::Create(
1021 FunctionType::get(Type::getVoidTy(*C), false),
1022 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1023 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1024 // call __asan_init in the module ctor.
1025 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1026 AsanInitFunction = checkInterfaceFunction(
1027 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1028 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1029 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001030
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001031 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001032 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001033
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001034 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001035 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001036}
1037
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001038bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1039 // For each NSObject descendant having a +load method, this method is invoked
1040 // by the ObjC runtime before any of the static constructors is called.
1041 // Therefore we need to instrument such methods with a call to __asan_init
1042 // at the beginning in order to initialize our runtime before any access to
1043 // the shadow memory.
1044 // We cannot just ignore these methods, because they may call other
1045 // instrumented functions.
1046 if (F.getName().find(" load]") != std::string::npos) {
1047 IRBuilder<> IRB(F.begin()->begin());
1048 IRB.CreateCall(AsanInitFunction);
1049 return true;
1050 }
1051 return false;
1052}
1053
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001054bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001055 if (BL->isIn(F)) return false;
1056 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001057 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001058 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001059
1060 // If needed, insert __asan_init before checking for AddressSafety attr.
1061 maybeInsertAsanInitAtFunctionEntry(F);
1062
Bill Wendling831737d2012-12-30 10:32:01 +00001063 if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1064 Attribute::AddressSafety))
Bill Wendling67658342012-10-09 07:45:08 +00001065 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001066
1067 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1068 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001069
1070 // We want to instrument every address only once per basic block (unless there
1071 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001072 SmallSet<Value*, 16> TempsToInstrument;
1073 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001074 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001075 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001076
1077 // Fill the set of memory operations to instrument.
1078 for (Function::iterator FI = F.begin(), FE = F.end();
1079 FI != FE; ++FI) {
1080 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001081 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001082 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1083 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001084 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001085 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001086 if (ClOpt && ClOptSameTemp) {
1087 if (!TempsToInstrument.insert(Addr))
1088 continue; // We've seen this temp in the current BB.
1089 }
1090 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1091 // ok, take it.
1092 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001093 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001094 // A call inside BB.
1095 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +00001096 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001097 NoReturnCalls.push_back(CI);
1098 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001099 }
1100 continue;
1101 }
1102 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001103 NumInsnsPerBB++;
1104 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1105 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001106 }
1107 }
1108
1109 // Instrument.
1110 int NumInstrumented = 0;
1111 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1112 Instruction *Inst = ToInstrument[i];
1113 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1114 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001115 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001116 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001117 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001118 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001119 }
1120 NumInstrumented++;
1121 }
1122
Alexey Samsonov59cca132012-12-25 12:04:36 +00001123 FunctionStackPoisoner FSP(F, *this);
1124 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001125
1126 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1127 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1128 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1129 Instruction *CI = NoReturnCalls[i];
1130 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001131 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001132 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001133 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001134
1135 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001136}
1137
1138static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1139 if (ShadowRedzoneSize == 1) return PoisonByte;
1140 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1141 if (ShadowRedzoneSize == 4)
1142 return (PoisonByte << 24) + (PoisonByte << 16) +
1143 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001144 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001145}
1146
1147static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1148 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001149 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001150 size_t ShadowGranularity,
1151 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001152 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001153 i+= ShadowGranularity, Shadow++) {
1154 if (i + ShadowGranularity <= Size) {
1155 *Shadow = 0; // fully addressable
1156 } else if (i >= Size) {
1157 *Shadow = Magic; // unaddressable
1158 } else {
1159 *Shadow = Size - i; // first Size-i bytes are addressable
1160 }
1161 }
1162}
1163
Alexey Samsonov59cca132012-12-25 12:04:36 +00001164// Workaround for bug 11395: we don't want to instrument stack in functions
1165// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1166// FIXME: remove once the bug 11395 is fixed.
1167bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1168 if (LongSize != 32) return false;
1169 CallInst *CI = dyn_cast<CallInst>(I);
1170 if (!CI || !CI->isInlineAsm()) return false;
1171 if (CI->getNumArgOperands() <= 5) return false;
1172 // We have inline assembly with quite a few arguments.
1173 return true;
1174}
1175
1176void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1177 IRBuilder<> IRB(*C);
1178 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1179 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1180 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1181 kAsanStackFreeName, IRB.getVoidTy(),
1182 IntptrTy, IntptrTy, IntptrTy, NULL));
1183 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1184 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1185 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1186 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1187}
1188
1189void FunctionStackPoisoner::poisonRedZones(
1190 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1191 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001192 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001193 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1194 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1195 Type *RZPtrTy = PointerType::get(RZTy, 0);
1196
1197 Value *PoisonLeft = ConstantInt::get(RZTy,
1198 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1199 Value *PoisonMid = ConstantInt::get(RZTy,
1200 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1201 Value *PoisonRight = ConstantInt::get(RZTy,
1202 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1203
1204 // poison the first red zone.
1205 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1206
1207 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001208 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001209 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1210 AllocaInst *AI = AllocaVec[i];
1211 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1212 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001213 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001214 Value *Ptr = NULL;
1215
1216 Pos += AlignedSize;
1217
1218 assert(ShadowBase->getType() == IntptrTy);
1219 if (SizeInBytes < AlignedSize) {
1220 // Poison the partial redzone at right
1221 Ptr = IRB.CreateAdd(
1222 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001223 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001224 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001225 uint32_t Poison = 0;
1226 if (DoPoison) {
1227 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001228 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001229 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001230 kAsanStackPartialRedzoneMagic);
1231 }
1232 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1233 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1234 }
1235
1236 // Poison the full redzone at right.
1237 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001238 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001239 bool LastAlloca = (i == AllocaVec.size() - 1);
1240 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001241 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1242
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001243 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001244 }
1245}
1246
Alexey Samsonov59cca132012-12-25 12:04:36 +00001247void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001248 uint64_t LocalStackSize = TotalStackSize +
1249 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001250
Alexey Samsonov59cca132012-12-25 12:04:36 +00001251 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001252 && LocalStackSize <= kMaxStackMallocSize;
1253
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001254 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001255 Instruction *InsBefore = AllocaVec[0];
1256 IRBuilder<> IRB(InsBefore);
1257
1258
1259 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1260 AllocaInst *MyAlloca =
1261 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001262 if (ClRealignStack && StackAlignment < RedzoneSize())
1263 StackAlignment = RedzoneSize();
1264 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001265 assert(MyAlloca->isStaticAlloca());
1266 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1267 Value *LocalStackBase = OrigStackBase;
1268
1269 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001270 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1271 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1272 }
1273
1274 // This string will be parsed by the run-time (DescribeStackAddress).
1275 SmallString<2048> StackDescriptionStorage;
1276 raw_svector_ostream StackDescription(StackDescriptionStorage);
1277 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1278
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001279 // Insert poison calls for lifetime intrinsics for alloca.
1280 bool HavePoisonedAllocas = false;
1281 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1282 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1283 IntrinsicInst *II = APC.InsBefore;
1284 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1285 assert(AI);
1286 IRBuilder<> IRB(II);
1287 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1288 HavePoisonedAllocas |= APC.DoPoison;
1289 }
1290
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001291 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001292 // Replace Alloca instructions with base+offset.
1293 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1294 AllocaInst *AI = AllocaVec[i];
1295 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1296 StringRef Name = AI->getName();
1297 StackDescription << Pos << " " << SizeInBytes << " "
1298 << Name.size() << " " << Name << " ";
1299 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001300 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001301 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001302 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001303 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001304 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001305 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001306 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001307 }
1308 assert(Pos == LocalStackSize);
1309
1310 // Write the Magic value and the frame description constant to the redzone.
1311 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1312 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1313 BasePlus0);
1314 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001315 ConstantInt::get(IntptrTy,
1316 ASan.LongSize/8));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001317 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001318 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001319 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001320 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1321 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001322 IRB.CreateStore(Description, BasePlus1);
1323
1324 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001325 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1326 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001327
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001328 // Unpoison the stack before all ret instructions.
1329 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1330 Instruction *Ret = RetVec[i];
1331 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001332 // Mark the current frame as retired.
1333 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1334 BasePlus0);
1335 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001336 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001337 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001338 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001339 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1340 ConstantInt::get(IntptrTy, LocalStackSize),
1341 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001342 } else if (HavePoisonedAllocas) {
1343 // If we poisoned some allocas in llvm.lifetime analysis,
1344 // unpoison whole stack frame now.
1345 assert(LocalStackBase == OrigStackBase);
1346 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001347 }
1348 }
1349
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001350 // We are done. Remove the old unused alloca instructions.
1351 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1352 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001353}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001354
Alexey Samsonov59cca132012-12-25 12:04:36 +00001355void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1356 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001357 // For now just insert the call to ASan runtime.
1358 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1359 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1360 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1361 : AsanUnpoisonStackMemoryFunc,
1362 AddrArg, SizeArg);
1363}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001364
1365// Handling llvm.lifetime intrinsics for a given %alloca:
1366// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1367// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1368// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1369// could be poisoned by previous llvm.lifetime.end instruction, as the
1370// variable may go in and out of scope several times, e.g. in loops).
1371// (3) if we poisoned at least one %alloca in a function,
1372// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001373
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001374AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1375 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1376 // We're intested only in allocas we can handle.
1377 return isInterestingAlloca(*AI) ? AI : 0;
1378 // See if we've already calculated (or started to calculate) alloca for a
1379 // given value.
1380 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1381 if (I != AllocaForValue.end())
1382 return I->second;
1383 // Store 0 while we're calculating alloca for value V to avoid
1384 // infinite recursion if the value references itself.
1385 AllocaForValue[V] = 0;
1386 AllocaInst *Res = 0;
1387 if (CastInst *CI = dyn_cast<CastInst>(V))
1388 Res = findAllocaForValue(CI->getOperand(0));
1389 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1390 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1391 Value *IncValue = PN->getIncomingValue(i);
1392 // Allow self-referencing phi-nodes.
1393 if (IncValue == PN) continue;
1394 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1395 // AI for incoming values should exist and should all be equal.
1396 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1397 return 0;
1398 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001399 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001400 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001401 if (Res != 0)
1402 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001403 return Res;
1404}