blob: 0474eb516aa6de4f3adf5cab8a460a9e77d7bfec [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++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000878 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000879 GlobalVariable *G = GlobalsToChange[i];
880 PointerType *PtrTy = cast<PointerType>(G->getType());
881 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000882 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000883 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000884 // MinRZ <= RZ <= kMaxGlobalRedzone
885 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000886 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000887 std::min(kMaxGlobalRedzone,
888 (SizeInBytes / MinRZ / 4) * MinRZ));
889 uint64_t RightRedzoneSize = RZ;
890 // Round up to MinRZ
891 if (SizeInBytes % MinRZ)
892 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
893 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000894 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000895 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000896 bool GlobalHasDynamicInitializer =
897 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000898 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000899 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000900
901 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
902 Constant *NewInitializer = ConstantStruct::get(
903 NewTy, G->getInitializer(),
904 Constant::getNullValue(RightRedZoneTy), NULL);
905
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000906 SmallString<2048> DescriptionOfGlobal = G->getName();
907 DescriptionOfGlobal += " (";
908 DescriptionOfGlobal += M.getModuleIdentifier();
909 DescriptionOfGlobal += ")";
910 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000911
912 // Create a new global variable with enough space for a redzone.
913 GlobalVariable *NewGlobal = new GlobalVariable(
914 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000915 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000916 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +0000917 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000918
919 Value *Indices2[2];
920 Indices2[0] = IRB.getInt32(0);
921 Indices2[1] = IRB.getInt32(0);
922
923 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000924 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000925 NewGlobal->takeName(G);
926 G->eraseFromParent();
927
928 Initializers[i] = ConstantStruct::get(
929 GlobalStructTy,
930 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
931 ConstantInt::get(IntptrTy, SizeInBytes),
932 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
933 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000934 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000935 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000936
937 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000938 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000939 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
940 if (FirstDynamic == 0)
941 FirstDynamic = LastDynamic;
942 }
943
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000944 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000945 }
946
947 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
948 GlobalVariable *AllGlobals = new GlobalVariable(
949 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
950 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
951
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000952 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000953 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000954 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000955 IRB.CreateCall2(AsanRegisterGlobals,
956 IRB.CreatePointerCast(AllGlobals, IntptrTy),
957 ConstantInt::get(IntptrTy, n));
958
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000959 // We also need to unregister globals at the end, e.g. when a shared library
960 // gets closed.
961 Function *AsanDtorFunction = Function::Create(
962 FunctionType::get(Type::getVoidTy(*C), false),
963 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
964 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
965 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000966 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
967 IRB.CreatePointerCast(AllGlobals, IntptrTy),
968 ConstantInt::get(IntptrTy, n));
969 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
970
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000971 DEBUG(dbgs() << M);
972 return true;
973}
974
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000975void AddressSanitizer::initializeCallbacks(Module &M) {
976 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000977 // Create __asan_report* callbacks.
978 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
979 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
980 AccessSizeIndex++) {
981 // IsWrite and TypeSize are encoded in the function name.
982 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
983 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000984 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000985 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
986 checkInterfaceFunction(M.getOrInsertFunction(
987 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000988 }
989 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000990
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000991 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
992 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000993 // We insert an empty inline asm after __asan_report* to avoid callback merge.
994 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
995 StringRef(""), StringRef(""),
996 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000997}
998
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000999void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001000 // Tell the values of mapping offset and scale to the run-time.
1001 GlobalValue *asan_mapping_offset =
1002 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1003 ConstantInt::get(IntptrTy, Mapping.Offset),
1004 kAsanMappingOffsetName);
1005 // Read the global, otherwise it may be optimized away.
1006 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001007
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001008 GlobalValue *asan_mapping_scale =
1009 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1010 ConstantInt::get(IntptrTy, Mapping.Scale),
1011 kAsanMappingScaleName);
1012 // Read the global, otherwise it may be optimized away.
1013 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001014}
1015
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001016// virtual
1017bool AddressSanitizer::doInitialization(Module &M) {
1018 // Initialize the private fields. No one has accessed them before.
1019 TD = getAnalysisIfAvailable<DataLayout>();
1020
1021 if (!TD)
1022 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +00001023 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001024 DynamicallyInitializedGlobals.Init(M);
1025
1026 C = &(M.getContext());
1027 LongSize = TD->getPointerSizeInBits();
1028 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001029
1030 AsanCtorFunction = Function::Create(
1031 FunctionType::get(Type::getVoidTy(*C), false),
1032 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1033 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1034 // call __asan_init in the module ctor.
1035 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1036 AsanInitFunction = checkInterfaceFunction(
1037 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1038 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1039 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001040
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001041 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001042 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001043
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001044 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001045 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001046}
1047
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001048bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1049 // For each NSObject descendant having a +load method, this method is invoked
1050 // by the ObjC runtime before any of the static constructors is called.
1051 // Therefore we need to instrument such methods with a call to __asan_init
1052 // at the beginning in order to initialize our runtime before any access to
1053 // the shadow memory.
1054 // We cannot just ignore these methods, because they may call other
1055 // instrumented functions.
1056 if (F.getName().find(" load]") != std::string::npos) {
1057 IRBuilder<> IRB(F.begin()->begin());
1058 IRB.CreateCall(AsanInitFunction);
1059 return true;
1060 }
1061 return false;
1062}
1063
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001064bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001065 if (BL->isIn(F)) return false;
1066 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001067 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001068 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001069
1070 // If needed, insert __asan_init before checking for AddressSafety attr.
1071 maybeInsertAsanInitAtFunctionEntry(F);
1072
Bill Wendling831737d2012-12-30 10:32:01 +00001073 if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1074 Attribute::AddressSafety))
Bill Wendling67658342012-10-09 07:45:08 +00001075 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001076
1077 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1078 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001079
1080 // We want to instrument every address only once per basic block (unless there
1081 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001082 SmallSet<Value*, 16> TempsToInstrument;
1083 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001084 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001085 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001086
1087 // Fill the set of memory operations to instrument.
1088 for (Function::iterator FI = F.begin(), FE = F.end();
1089 FI != FE; ++FI) {
1090 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001091 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001092 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1093 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001094 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001095 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001096 if (ClOpt && ClOptSameTemp) {
1097 if (!TempsToInstrument.insert(Addr))
1098 continue; // We've seen this temp in the current BB.
1099 }
1100 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1101 // ok, take it.
1102 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001103 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001104 // A call inside BB.
1105 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +00001106 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001107 NoReturnCalls.push_back(CI);
1108 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001109 }
1110 continue;
1111 }
1112 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001113 NumInsnsPerBB++;
1114 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1115 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001116 }
1117 }
1118
1119 // Instrument.
1120 int NumInstrumented = 0;
1121 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1122 Instruction *Inst = ToInstrument[i];
1123 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1124 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001125 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001126 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001127 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001128 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001129 }
1130 NumInstrumented++;
1131 }
1132
Alexey Samsonov59cca132012-12-25 12:04:36 +00001133 FunctionStackPoisoner FSP(F, *this);
1134 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001135
1136 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1137 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1138 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1139 Instruction *CI = NoReturnCalls[i];
1140 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001141 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001142 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001143 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001144
1145 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001146}
1147
1148static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1149 if (ShadowRedzoneSize == 1) return PoisonByte;
1150 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1151 if (ShadowRedzoneSize == 4)
1152 return (PoisonByte << 24) + (PoisonByte << 16) +
1153 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001154 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001155}
1156
1157static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1158 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001159 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001160 size_t ShadowGranularity,
1161 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001162 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001163 i+= ShadowGranularity, Shadow++) {
1164 if (i + ShadowGranularity <= Size) {
1165 *Shadow = 0; // fully addressable
1166 } else if (i >= Size) {
1167 *Shadow = Magic; // unaddressable
1168 } else {
1169 *Shadow = Size - i; // first Size-i bytes are addressable
1170 }
1171 }
1172}
1173
Alexey Samsonov59cca132012-12-25 12:04:36 +00001174// Workaround for bug 11395: we don't want to instrument stack in functions
1175// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1176// FIXME: remove once the bug 11395 is fixed.
1177bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1178 if (LongSize != 32) return false;
1179 CallInst *CI = dyn_cast<CallInst>(I);
1180 if (!CI || !CI->isInlineAsm()) return false;
1181 if (CI->getNumArgOperands() <= 5) return false;
1182 // We have inline assembly with quite a few arguments.
1183 return true;
1184}
1185
1186void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1187 IRBuilder<> IRB(*C);
1188 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1189 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1190 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1191 kAsanStackFreeName, IRB.getVoidTy(),
1192 IntptrTy, IntptrTy, IntptrTy, NULL));
1193 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1194 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1195 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1196 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1197}
1198
1199void FunctionStackPoisoner::poisonRedZones(
1200 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1201 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001202 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001203 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1204 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1205 Type *RZPtrTy = PointerType::get(RZTy, 0);
1206
1207 Value *PoisonLeft = ConstantInt::get(RZTy,
1208 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1209 Value *PoisonMid = ConstantInt::get(RZTy,
1210 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1211 Value *PoisonRight = ConstantInt::get(RZTy,
1212 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1213
1214 // poison the first red zone.
1215 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1216
1217 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001218 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001219 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1220 AllocaInst *AI = AllocaVec[i];
1221 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1222 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001223 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001224 Value *Ptr = NULL;
1225
1226 Pos += AlignedSize;
1227
1228 assert(ShadowBase->getType() == IntptrTy);
1229 if (SizeInBytes < AlignedSize) {
1230 // Poison the partial redzone at right
1231 Ptr = IRB.CreateAdd(
1232 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001233 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001234 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001235 uint32_t Poison = 0;
1236 if (DoPoison) {
1237 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001238 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001239 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001240 kAsanStackPartialRedzoneMagic);
1241 }
1242 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1243 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1244 }
1245
1246 // Poison the full redzone at right.
1247 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001248 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001249 bool LastAlloca = (i == AllocaVec.size() - 1);
1250 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001251 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1252
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001253 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001254 }
1255}
1256
Alexey Samsonov59cca132012-12-25 12:04:36 +00001257void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001258 uint64_t LocalStackSize = TotalStackSize +
1259 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001260
Alexey Samsonov59cca132012-12-25 12:04:36 +00001261 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001262 && LocalStackSize <= kMaxStackMallocSize;
1263
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001264 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001265 Instruction *InsBefore = AllocaVec[0];
1266 IRBuilder<> IRB(InsBefore);
1267
1268
1269 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1270 AllocaInst *MyAlloca =
1271 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001272 if (ClRealignStack && StackAlignment < RedzoneSize())
1273 StackAlignment = RedzoneSize();
1274 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001275 assert(MyAlloca->isStaticAlloca());
1276 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1277 Value *LocalStackBase = OrigStackBase;
1278
1279 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001280 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1281 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1282 }
1283
1284 // This string will be parsed by the run-time (DescribeStackAddress).
1285 SmallString<2048> StackDescriptionStorage;
1286 raw_svector_ostream StackDescription(StackDescriptionStorage);
1287 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1288
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001289 // Insert poison calls for lifetime intrinsics for alloca.
1290 bool HavePoisonedAllocas = false;
1291 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1292 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1293 IntrinsicInst *II = APC.InsBefore;
1294 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1295 assert(AI);
1296 IRBuilder<> IRB(II);
1297 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1298 HavePoisonedAllocas |= APC.DoPoison;
1299 }
1300
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001301 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001302 // Replace Alloca instructions with base+offset.
1303 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1304 AllocaInst *AI = AllocaVec[i];
1305 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1306 StringRef Name = AI->getName();
1307 StackDescription << Pos << " " << SizeInBytes << " "
1308 << Name.size() << " " << Name << " ";
1309 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001310 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001311 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001312 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001313 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001314 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001315 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001316 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001317 }
1318 assert(Pos == LocalStackSize);
1319
1320 // Write the Magic value and the frame description constant to the redzone.
1321 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1322 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1323 BasePlus0);
1324 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001325 ConstantInt::get(IntptrTy,
1326 ASan.LongSize/8));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001327 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001328 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001329 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001330 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1331 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001332 IRB.CreateStore(Description, BasePlus1);
1333
1334 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001335 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1336 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001337
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001338 // Unpoison the stack before all ret instructions.
1339 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1340 Instruction *Ret = RetVec[i];
1341 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001342 // Mark the current frame as retired.
1343 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1344 BasePlus0);
1345 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001346 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001347 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001348 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001349 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1350 ConstantInt::get(IntptrTy, LocalStackSize),
1351 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001352 } else if (HavePoisonedAllocas) {
1353 // If we poisoned some allocas in llvm.lifetime analysis,
1354 // unpoison whole stack frame now.
1355 assert(LocalStackBase == OrigStackBase);
1356 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001357 }
1358 }
1359
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001360 // We are done. Remove the old unused alloca instructions.
1361 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1362 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001363}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001364
Alexey Samsonov59cca132012-12-25 12:04:36 +00001365void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1366 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001367 // For now just insert the call to ASan runtime.
1368 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1369 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1370 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1371 : AsanUnpoisonStackMemoryFunc,
1372 AddrArg, SizeArg);
1373}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001374
1375// Handling llvm.lifetime intrinsics for a given %alloca:
1376// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1377// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1378// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1379// could be poisoned by previous llvm.lifetime.end instruction, as the
1380// variable may go in and out of scope several times, e.g. in loops).
1381// (3) if we poisoned at least one %alloca in a function,
1382// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001383
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001384AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1385 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1386 // We're intested only in allocas we can handle.
1387 return isInterestingAlloca(*AI) ? AI : 0;
1388 // See if we've already calculated (or started to calculate) alloca for a
1389 // given value.
1390 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1391 if (I != AllocaForValue.end())
1392 return I->second;
1393 // Store 0 while we're calculating alloca for value V to avoid
1394 // infinite recursion if the value references itself.
1395 AllocaForValue[V] = 0;
1396 AllocaInst *Res = 0;
1397 if (CastInst *CI = dyn_cast<CastInst>(V))
1398 Res = findAllocaForValue(CI->getOperand(0));
1399 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1400 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1401 Value *IncValue = PN->getIncomingValue(i);
1402 // Allow self-referencing phi-nodes.
1403 if (IncValue == PN) continue;
1404 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1405 // AI for incoming values should exist and should all be equal.
1406 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1407 return 0;
1408 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001409 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001410 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001411 if (Res != 0)
1412 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001413 return Res;
1414}