blob: c5f77ec0893775893aa4c58224f6325f4c6f874f [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 Serebryany117de482013-02-11 14:36:01 +000056static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany48a615f2013-01-23 12:54:55 +000057static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000058
59static const size_t kMaxStackMallocSize = 1 << 16; // 64K
60static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
61static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
62
63static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000064static const char *kAsanModuleDtorName = "asan.module_dtor";
65static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000066static const char *kAsanReportErrorTemplate = "__asan_report_";
67static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000068static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000069static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
70static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000071static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000072static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000073static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
74static const char *kAsanMappingScaleName = "__asan_mapping_scale";
75static const char *kAsanStackMallocName = "__asan_stack_malloc";
76static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000077static const char *kAsanGenPrefix = "__asan_gen_";
Alexey Samsonovf985f442012-12-04 01:34:23 +000078static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
79static const char *kAsanUnpoisonStackMemoryName =
80 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000081
82static const int kAsanStackLeftRedzoneMagic = 0xf1;
83static const int kAsanStackMidRedzoneMagic = 0xf2;
84static const int kAsanStackRightRedzoneMagic = 0xf3;
85static const int kAsanStackPartialRedzoneMagic = 0xf4;
86
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000087// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
88static const size_t kNumberOfAccessSizes = 5;
89
Kostya Serebryany800e03f2011-11-16 01:35:23 +000090// Command-line flags.
91
92// This flag may need to be replaced with -f[no-]asan-reads.
93static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
94 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
95static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
96 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000097static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
98 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
99 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000100static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
101 cl::desc("use instrumentation with slow path for all accesses"),
102 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000103// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000104// in any given BB. Normally, this should be set to unlimited (INT_MAX),
105// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
106// set it to 10000.
107static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
108 cl::init(10000),
109 cl::desc("maximal number of instructions to instrument in any given BB"),
110 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000111// This flag may need to be replaced with -f[no]asan-stack.
112static cl::opt<bool> ClStack("asan-stack",
113 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
114// This flag may need to be replaced with -f[no]asan-use-after-return.
115static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
116 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
117// This flag may need to be replaced with -f[no]asan-globals.
118static cl::opt<bool> ClGlobals("asan-globals",
119 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000120static cl::opt<bool> ClInitializers("asan-initialization-order",
121 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000122static cl::opt<bool> ClMemIntrin("asan-memintrin",
123 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000124static cl::opt<bool> ClRealignStack("asan-realign-stack",
125 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000126static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
127 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000128 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000129
130// These flags allow to change the shadow mapping.
131// The shadow mapping looks like
132// Shadow = (Mem >> scale) + (1 << offset_log)
133static cl::opt<int> ClMappingScale("asan-mapping-scale",
134 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
135static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
136 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
Kostya Serebryany117de482013-02-11 14:36:01 +0000137static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
138 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
139 cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000140
141// Optimization flags. Not user visible, used mostly for testing
142// and benchmarking the tool.
143static cl::opt<bool> ClOpt("asan-opt",
144 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
145static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
146 cl::desc("Instrument the same temp just once"), cl::Hidden,
147 cl::init(true));
148static cl::opt<bool> ClOptGlobals("asan-opt-globals",
149 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
150
Alexey Samsonovee548272012-11-29 18:14:24 +0000151static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
152 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
153 cl::Hidden, cl::init(false));
154
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000155// Debug flags.
156static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
157 cl::init(0));
158static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
159 cl::Hidden, cl::init(0));
160static cl::opt<std::string> ClDebugFunc("asan-debug-func",
161 cl::Hidden, cl::desc("Debug func"));
162static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
163 cl::Hidden, cl::init(-1));
164static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
165 cl::Hidden, cl::init(-1));
166
167namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000168/// A set of dynamically initialized globals extracted from metadata.
169class SetOfDynamicallyInitializedGlobals {
170 public:
171 void Init(Module& M) {
172 // Clang generates metadata identifying all dynamically initialized globals.
173 NamedMDNode *DynamicGlobals =
174 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
175 if (!DynamicGlobals)
176 return;
177 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
178 MDNode *MDN = DynamicGlobals->getOperand(i);
179 assert(MDN->getNumOperands() == 1);
180 Value *VG = MDN->getOperand(0);
181 // The optimizer may optimize away a global entirely, in which case we
182 // cannot instrument access to it.
183 if (!VG)
184 continue;
185 DynInitGlobals.insert(cast<GlobalVariable>(VG));
186 }
187 }
188 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
189 private:
190 SmallSet<GlobalValue*, 32> DynInitGlobals;
191};
192
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000193/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000194/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000195struct ShadowMapping {
196 int Scale;
197 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000198 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000199};
200
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000201static ShadowMapping getShadowMapping(const Module &M, int LongSize,
202 bool ZeroBaseShadow) {
203 llvm::Triple TargetTriple(M.getTargetTriple());
204 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000205 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000206
207 ShadowMapping Mapping;
208
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000209 // OR-ing shadow offset if more efficient (at least on x86),
210 // but on ppc64 we have to use add since the shadow offset is not neccesary
211 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000212 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000213
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000214 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000215 (LongSize == 32 ? kDefaultShadowOffset32 :
216 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000217 if (!ZeroBaseShadow && ClShort64BitOffset && LongSize == 64) {
218 Mapping.Offset = kDefaultShort64bitShadowOffset;
219 } if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000220 // Zero offset log is the special case.
221 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
222 }
223
224 Mapping.Scale = kDefaultShadowScale;
225 if (ClMappingScale) {
226 Mapping.Scale = ClMappingScale;
227 }
228
229 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000230}
231
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000232static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000233 // Redzone used for stack and globals is at least 32 bytes.
234 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000235 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000236}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000237
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000238/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000239struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000240 AddressSanitizer(bool CheckInitOrder = false,
241 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000242 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000243 StringRef BlacklistFile = StringRef(),
244 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000245 : FunctionPass(ID),
246 CheckInitOrder(CheckInitOrder || ClInitializers),
247 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000248 CheckLifetime(CheckLifetime || ClCheckLifetime),
249 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000250 : BlacklistFile),
251 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000252 virtual const char *getPassName() const {
253 return "AddressSanitizerFunctionPass";
254 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000255 void instrumentMop(Instruction *I);
256 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000257 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000258 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
259 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000260 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000261 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000262 bool instrumentMemIntrinsic(MemIntrinsic *MI);
263 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000264 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000265 Instruction *InsertBefore, bool IsWrite);
266 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000267 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000268 void createInitializerPoisonCalls(Module &M,
269 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000270 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000271 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000272 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000273 static char ID; // Pass identification, replacement for typeid
274
275 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000276 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000277
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000278 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000279 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000280 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000281
Alexey Samsonovee548272012-11-29 18:14:24 +0000282 bool CheckInitOrder;
283 bool CheckUseAfterReturn;
284 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000285 SmallString<64> BlacklistFile;
286 bool ZeroBaseShadow;
287
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000288 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000289 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000290 int LongSize;
291 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000292 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000293 Function *AsanCtorFunction;
294 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000295 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000296 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000297 // This array is indexed by AccessIsWrite and log2(AccessSize).
298 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000299 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000300 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000301
302 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000303};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000304
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000305class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000306 public:
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000307 AddressSanitizerModule(bool CheckInitOrder = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000308 StringRef BlacklistFile = StringRef(),
309 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000310 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000311 CheckInitOrder(CheckInitOrder || ClInitializers),
312 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000313 : BlacklistFile),
314 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000315 bool runOnModule(Module &M);
316 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000317 virtual const char *getPassName() const {
318 return "AddressSanitizerModule";
319 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000320
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000321 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000322 void initializeCallbacks(Module &M);
323
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000324 bool ShouldInstrumentGlobal(GlobalVariable *G);
325 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
326 Value *LastAddr);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000327 size_t RedzoneSize() const {
328 return RedzoneSizeForScale(Mapping.Scale);
329 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000330
Alexey Samsonovee548272012-11-29 18:14:24 +0000331 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000332 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000333 bool ZeroBaseShadow;
334
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000335 OwningPtr<BlackList> BL;
336 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
337 Type *IntptrTy;
338 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000339 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000340 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000341 Function *AsanPoisonGlobals;
342 Function *AsanUnpoisonGlobals;
343 Function *AsanRegisterGlobals;
344 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000345};
346
Alexey Samsonov59cca132012-12-25 12:04:36 +0000347// Stack poisoning does not play well with exception handling.
348// When an exception is thrown, we essentially bypass the code
349// that unpoisones the stack. This is why the run-time library has
350// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
351// stack in the interceptor. This however does not work inside the
352// actual function which catches the exception. Most likely because the
353// compiler hoists the load of the shadow value somewhere too high.
354// This causes asan to report a non-existing bug on 453.povray.
355// It sounds like an LLVM bug.
356struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
357 Function &F;
358 AddressSanitizer &ASan;
359 DIBuilder DIB;
360 LLVMContext *C;
361 Type *IntptrTy;
362 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000363 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000364
365 SmallVector<AllocaInst*, 16> AllocaVec;
366 SmallVector<Instruction*, 8> RetVec;
367 uint64_t TotalStackSize;
368 unsigned StackAlignment;
369
370 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
371 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
372
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000373 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
374 struct AllocaPoisonCall {
375 IntrinsicInst *InsBefore;
376 uint64_t Size;
377 bool DoPoison;
378 };
379 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
380
381 // Maps Value to an AllocaInst from which the Value is originated.
382 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
383 AllocaForValueMapTy AllocaForValue;
384
Alexey Samsonov59cca132012-12-25 12:04:36 +0000385 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
386 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
387 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000388 Mapping(ASan.Mapping),
389 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000390
391 bool runOnFunction() {
392 if (!ClStack) return false;
393 // Collect alloca, ret, lifetime instructions etc.
394 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
395 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
396 BasicBlock *BB = *DI;
397 visit(*BB);
398 }
399 if (AllocaVec.empty()) return false;
400
401 initializeCallbacks(*F.getParent());
402
403 poisonStack();
404
405 if (ClDebugStack) {
406 DEBUG(dbgs() << F);
407 }
408 return true;
409 }
410
411 // Finds all static Alloca instructions and puts
412 // poisoned red zones around all of them.
413 // Then unpoison everything back before the function returns.
414 void poisonStack();
415
416 // ----------------------- Visitors.
417 /// \brief Collect all Ret instructions.
418 void visitReturnInst(ReturnInst &RI) {
419 RetVec.push_back(&RI);
420 }
421
422 /// \brief Collect Alloca instructions we want (and can) handle.
423 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000424 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000425
426 StackAlignment = std::max(StackAlignment, AI.getAlignment());
427 AllocaVec.push_back(&AI);
428 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
429 TotalStackSize += AlignedSize;
430 }
431
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000432 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
433 /// errors.
434 void visitIntrinsicInst(IntrinsicInst &II) {
435 if (!ASan.CheckLifetime) return;
436 Intrinsic::ID ID = II.getIntrinsicID();
437 if (ID != Intrinsic::lifetime_start &&
438 ID != Intrinsic::lifetime_end)
439 return;
440 // Found lifetime intrinsic, add ASan instrumentation if necessary.
441 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
442 // If size argument is undefined, don't do anything.
443 if (Size->isMinusOne()) return;
444 // Check that size doesn't saturate uint64_t and can
445 // be stored in IntptrTy.
446 const uint64_t SizeValue = Size->getValue().getLimitedValue();
447 if (SizeValue == ~0ULL ||
448 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
449 return;
450 // Find alloca instruction that corresponds to llvm.lifetime argument.
451 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
452 if (!AI) return;
453 bool DoPoison = (ID == Intrinsic::lifetime_end);
454 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
455 AllocaPoisonCallVec.push_back(APC);
456 }
457
Alexey Samsonov59cca132012-12-25 12:04:36 +0000458 // ---------------------- Helpers.
459 void initializeCallbacks(Module &M);
460
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000461 // Check if we want (and can) handle this alloca.
462 bool isInterestingAlloca(AllocaInst &AI) {
463 return (!AI.isArrayAllocation() &&
464 AI.isStaticAlloca() &&
465 AI.getAllocatedType()->isSized());
466 }
467
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000468 size_t RedzoneSize() const {
469 return RedzoneSizeForScale(Mapping.Scale);
470 }
Alexey Samsonov59cca132012-12-25 12:04:36 +0000471 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
472 Type *Ty = AI->getAllocatedType();
473 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
474 return SizeInBytes;
475 }
476 uint64_t getAlignedSize(uint64_t SizeInBytes) {
477 size_t RZ = RedzoneSize();
478 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
479 }
480 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
481 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
482 return getAlignedSize(SizeInBytes);
483 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000484 /// Finds alloca where the value comes from.
485 AllocaInst *findAllocaForValue(Value *V);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000486 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
487 Value *ShadowBase, bool DoPoison);
488 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000489};
490
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000491} // namespace
492
493char AddressSanitizer::ID = 0;
494INITIALIZE_PASS(AddressSanitizer, "asan",
495 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
496 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000497FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000498 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000499 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000500 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000501 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000502}
503
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000504char AddressSanitizerModule::ID = 0;
505INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
506 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
507 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000508ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000509 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
510 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
511 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000512}
513
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000514static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
515 size_t Res = CountTrailingZeros_32(TypeSize / 8);
516 assert(Res < kNumberOfAccessSizes);
517 return Res;
518}
519
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000520// Create a constant for Str so that we can pass it to the run-time lib.
521static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000522 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000523 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000524 GlobalValue::PrivateLinkage, StrConst,
525 kAsanGenPrefix);
526}
527
528static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
529 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000530}
531
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000532Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
533 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000534 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
535 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000536 return Shadow;
537 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000538 if (Mapping.OrShadowOffset)
539 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
540 else
541 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000542}
543
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000544void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000545 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000546 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
547 // Check the first byte.
548 {
549 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000550 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000551 }
552 // Check the last byte.
553 {
554 IRBuilder<> IRB(InsertBefore);
555 Value *SizeMinusOne = IRB.CreateSub(
556 Size, ConstantInt::get(Size->getType(), 1));
557 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
558 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
559 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000560 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000561 }
562}
563
564// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000565bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000566 Value *Dst = MI->getDest();
567 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000568 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000569 Value *Length = MI->getLength();
570
571 Constant *ConstLength = dyn_cast<Constant>(Length);
572 Instruction *InsertBefore = MI;
573 if (ConstLength) {
574 if (ConstLength->isNullValue()) return false;
575 } else {
576 // The size is not a constant so it could be zero -- check at run-time.
577 IRBuilder<> IRB(InsertBefore);
578
579 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000580 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000581 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000582 }
583
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000584 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000585 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000586 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000587 return true;
588}
589
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000590// If I is an interesting memory access, return the PointerOperand
591// and set IsWrite. Otherwise return NULL.
592static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000593 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000594 if (!ClInstrumentReads) return NULL;
595 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000596 return LI->getPointerOperand();
597 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000598 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
599 if (!ClInstrumentWrites) return NULL;
600 *IsWrite = true;
601 return SI->getPointerOperand();
602 }
603 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
604 if (!ClInstrumentAtomics) return NULL;
605 *IsWrite = true;
606 return RMW->getPointerOperand();
607 }
608 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
609 if (!ClInstrumentAtomics) return NULL;
610 *IsWrite = true;
611 return XCHG->getPointerOperand();
612 }
613 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000614}
615
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000616void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000617 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000618 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
619 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000620 if (ClOpt && ClOptGlobals) {
621 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
622 // If initialization order checking is disabled, a simple access to a
623 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000624 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000625 return;
626 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000627 // have to instrument it. However, if a global does not have initailizer
628 // at all, we assume it has dynamic initializer (in other TU).
629 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000630 return;
631 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000632 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000633
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000634 Type *OrigPtrTy = Addr->getType();
635 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
636
637 assert(OrigTy->isSized());
638 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
639
640 if (TypeSize != 8 && TypeSize != 16 &&
641 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
642 // Ignore all unusual sizes.
643 return;
644 }
645
646 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000647 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000648}
649
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000650// Validate the result of Module::getOrInsertFunction called for an interface
651// function of AddressSanitizer. If the instrumented module defines a function
652// with the same name, their prototypes must match, otherwise
653// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000654static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000655 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
656 FuncOrBitcast->dump();
657 report_fatal_error("trying to redefine an AddressSanitizer "
658 "interface function");
659}
660
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000661Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000662 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000663 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000664 IRBuilder<> IRB(InsertBefore);
665 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
666 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000667 // We don't do Call->setDoesNotReturn() because the BB already has
668 // UnreachableInst at the end.
669 // This EmptyAsm is required to avoid callback merge.
670 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000671 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000672}
673
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000674Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000675 Value *ShadowValue,
676 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000677 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000678 // Addr & (Granularity - 1)
679 Value *LastAccessedByte = IRB.CreateAnd(
680 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
681 // (Addr & (Granularity - 1)) + size - 1
682 if (TypeSize / 8 > 1)
683 LastAccessedByte = IRB.CreateAdd(
684 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
685 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
686 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000687 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000688 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
689 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
690}
691
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000692void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000693 IRBuilder<> &IRB, Value *Addr,
694 uint32_t TypeSize, bool IsWrite) {
695 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
696
697 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000698 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000699 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
700 Value *ShadowPtr = memToShadow(AddrLong, IRB);
701 Value *CmpVal = Constant::getNullValue(ShadowTy);
702 Value *ShadowValue = IRB.CreateLoad(
703 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
704
705 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000706 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000707 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000708 TerminatorInst *CrashTerm = 0;
709
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000710 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000711 TerminatorInst *CheckTerm =
712 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000713 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000714 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000715 IRB.SetInsertPoint(CheckTerm);
716 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000717 BasicBlock *CrashBlock =
718 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000719 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000720 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
721 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000722 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000723 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000724 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000725
726 Instruction *Crash =
727 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
728 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000729}
730
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000731void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000732 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000733 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
734 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
735 // If that function is not present, this TU contains no globals, or they have
736 // all been optimized away
737 if (!GlobalInit)
738 return;
739
740 // Set up the arguments to our poison/unpoison functions.
741 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
742
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000743 // Add a call to poison all external globals before the given function starts.
744 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
745
746 // Add calls to unpoison all globals before each return instruction.
747 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
748 I != E; ++I) {
749 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
750 CallInst::Create(AsanUnpoisonGlobals, "", RI);
751 }
752 }
753}
754
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000755bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000756 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000757 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000758
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000759 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000760 if (!Ty->isSized()) return false;
761 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000762 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000763 // Touch only those globals that will not be defined in other modules.
764 // Don't handle ODR type linkages since other modules may be built w/o asan.
765 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
766 G->getLinkage() != GlobalVariable::PrivateLinkage &&
767 G->getLinkage() != GlobalVariable::InternalLinkage)
768 return false;
769 // Two problems with thread-locals:
770 // - The address of the main thread's copy can't be computed at link-time.
771 // - Need to poison all copies, not just the main thread's one.
772 if (G->isThreadLocal())
773 return false;
774 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000775 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000776
777 // Ignore all the globals with the names starting with "\01L_OBJC_".
778 // Many of those are put into the .cstring section. The linker compresses
779 // that section by removing the spare \0s after the string terminator, so
780 // our redzones get broken.
781 if ((G->getName().find("\01L_OBJC_") == 0) ||
782 (G->getName().find("\01l_OBJC_") == 0)) {
783 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
784 return false;
785 }
786
787 if (G->hasSection()) {
788 StringRef Section(G->getSection());
789 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
790 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
791 // them.
792 if ((Section.find("__OBJC,") == 0) ||
793 (Section.find("__DATA, __objc_") == 0)) {
794 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
795 return false;
796 }
797 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
798 // Constant CFString instances are compiled in the following way:
799 // -- the string buffer is emitted into
800 // __TEXT,__cstring,cstring_literals
801 // -- the constant NSConstantString structure referencing that buffer
802 // is placed into __DATA,__cfstring
803 // Therefore there's no point in placing redzones into __DATA,__cfstring.
804 // Moreover, it causes the linker to crash on OS X 10.7
805 if (Section.find("__DATA,__cfstring") == 0) {
806 DEBUG(dbgs() << "Ignoring CFString: " << *G);
807 return false;
808 }
809 }
810
811 return true;
812}
813
Alexey Samsonov46848582012-12-25 12:28:20 +0000814void AddressSanitizerModule::initializeCallbacks(Module &M) {
815 IRBuilder<> IRB(*C);
816 // Declare our poisoning and unpoisoning functions.
817 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
818 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
819 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
820 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
821 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
822 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
823 // Declare functions that register/unregister globals.
824 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
825 kAsanRegisterGlobalsName, IRB.getVoidTy(),
826 IntptrTy, IntptrTy, NULL));
827 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
828 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
829 kAsanUnregisterGlobalsName,
830 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
831 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
832}
833
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000834// This function replaces all global variables with new variables that have
835// trailing redzones. It also creates a function that poisons
836// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000837bool AddressSanitizerModule::runOnModule(Module &M) {
838 if (!ClGlobals) return false;
839 TD = getAnalysisIfAvailable<DataLayout>();
840 if (!TD)
841 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000842 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000843 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000844 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000845 int LongSize = TD->getPointerSizeInBits();
846 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000847 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000848 initializeCallbacks(M);
849 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000850
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000851 SmallVector<GlobalVariable *, 16> GlobalsToChange;
852
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000853 for (Module::GlobalListType::iterator G = M.global_begin(),
854 E = M.global_end(); G != E; ++G) {
855 if (ShouldInstrumentGlobal(G))
856 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000857 }
858
859 size_t n = GlobalsToChange.size();
860 if (n == 0) return false;
861
862 // A global is described by a structure
863 // size_t beg;
864 // size_t size;
865 // size_t size_with_redzone;
866 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000867 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000868 // We initialize an array of such structures and pass it to a run-time call.
869 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000870 IntptrTy, IntptrTy,
871 IntptrTy, NULL);
872 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000873
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000874
875 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
876 assert(CtorFunc);
877 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000878
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000879 // The addresses of the first and last dynamically initialized globals in
880 // this TU. Used in initialization order checking.
881 Value *FirstDynamic = 0, *LastDynamic = 0;
882
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000883 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000884 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000885 GlobalVariable *G = GlobalsToChange[i];
886 PointerType *PtrTy = cast<PointerType>(G->getType());
887 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000888 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000889 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000890 // MinRZ <= RZ <= kMaxGlobalRedzone
891 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000892 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000893 std::min(kMaxGlobalRedzone,
894 (SizeInBytes / MinRZ / 4) * MinRZ));
895 uint64_t RightRedzoneSize = RZ;
896 // Round up to MinRZ
897 if (SizeInBytes % MinRZ)
898 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
899 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000900 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000901 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000902 bool GlobalHasDynamicInitializer =
903 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000904 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000905 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000906
907 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
908 Constant *NewInitializer = ConstantStruct::get(
909 NewTy, G->getInitializer(),
910 Constant::getNullValue(RightRedZoneTy), NULL);
911
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000912 SmallString<2048> DescriptionOfGlobal = G->getName();
913 DescriptionOfGlobal += " (";
914 DescriptionOfGlobal += M.getModuleIdentifier();
915 DescriptionOfGlobal += ")";
916 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000917
918 // Create a new global variable with enough space for a redzone.
919 GlobalVariable *NewGlobal = new GlobalVariable(
920 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000921 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000922 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +0000923 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000924
925 Value *Indices2[2];
926 Indices2[0] = IRB.getInt32(0);
927 Indices2[1] = IRB.getInt32(0);
928
929 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000930 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000931 NewGlobal->takeName(G);
932 G->eraseFromParent();
933
934 Initializers[i] = ConstantStruct::get(
935 GlobalStructTy,
936 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
937 ConstantInt::get(IntptrTy, SizeInBytes),
938 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
939 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000940 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000941 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000942
943 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000944 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000945 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
946 if (FirstDynamic == 0)
947 FirstDynamic = LastDynamic;
948 }
949
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000950 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000951 }
952
953 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
954 GlobalVariable *AllGlobals = new GlobalVariable(
955 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
956 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
957
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000958 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000959 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000960 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000961 IRB.CreateCall2(AsanRegisterGlobals,
962 IRB.CreatePointerCast(AllGlobals, IntptrTy),
963 ConstantInt::get(IntptrTy, n));
964
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000965 // We also need to unregister globals at the end, e.g. when a shared library
966 // gets closed.
967 Function *AsanDtorFunction = Function::Create(
968 FunctionType::get(Type::getVoidTy(*C), false),
969 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
970 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
971 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000972 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
973 IRB.CreatePointerCast(AllGlobals, IntptrTy),
974 ConstantInt::get(IntptrTy, n));
975 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
976
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000977 DEBUG(dbgs() << M);
978 return true;
979}
980
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000981void AddressSanitizer::initializeCallbacks(Module &M) {
982 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000983 // Create __asan_report* callbacks.
984 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
985 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
986 AccessSizeIndex++) {
987 // IsWrite and TypeSize are encoded in the function name.
988 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
989 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000990 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000991 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
992 checkInterfaceFunction(M.getOrInsertFunction(
993 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000994 }
995 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000996
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000997 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
998 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000999 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1000 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1001 StringRef(""), StringRef(""),
1002 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001003}
1004
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001005void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001006 // Tell the values of mapping offset and scale to the run-time.
1007 GlobalValue *asan_mapping_offset =
1008 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1009 ConstantInt::get(IntptrTy, Mapping.Offset),
1010 kAsanMappingOffsetName);
1011 // Read the global, otherwise it may be optimized away.
1012 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001013
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001014 GlobalValue *asan_mapping_scale =
1015 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1016 ConstantInt::get(IntptrTy, Mapping.Scale),
1017 kAsanMappingScaleName);
1018 // Read the global, otherwise it may be optimized away.
1019 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001020}
1021
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001022// virtual
1023bool AddressSanitizer::doInitialization(Module &M) {
1024 // Initialize the private fields. No one has accessed them before.
1025 TD = getAnalysisIfAvailable<DataLayout>();
1026
1027 if (!TD)
1028 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +00001029 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001030 DynamicallyInitializedGlobals.Init(M);
1031
1032 C = &(M.getContext());
1033 LongSize = TD->getPointerSizeInBits();
1034 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001035
1036 AsanCtorFunction = Function::Create(
1037 FunctionType::get(Type::getVoidTy(*C), false),
1038 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1039 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1040 // call __asan_init in the module ctor.
1041 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1042 AsanInitFunction = checkInterfaceFunction(
1043 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1044 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1045 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001046
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001047 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001048 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001049
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001050 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001051 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001052}
1053
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001054bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1055 // For each NSObject descendant having a +load method, this method is invoked
1056 // by the ObjC runtime before any of the static constructors is called.
1057 // Therefore we need to instrument such methods with a call to __asan_init
1058 // at the beginning in order to initialize our runtime before any access to
1059 // the shadow memory.
1060 // We cannot just ignore these methods, because they may call other
1061 // instrumented functions.
1062 if (F.getName().find(" load]") != std::string::npos) {
1063 IRBuilder<> IRB(F.begin()->begin());
1064 IRB.CreateCall(AsanInitFunction);
1065 return true;
1066 }
1067 return false;
1068}
1069
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001070bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001071 if (BL->isIn(F)) return false;
1072 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001073 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001074 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001075
1076 // If needed, insert __asan_init before checking for AddressSafety attr.
1077 maybeInsertAsanInitAtFunctionEntry(F);
1078
Bill Wendling831737d2012-12-30 10:32:01 +00001079 if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1080 Attribute::AddressSafety))
Bill Wendling67658342012-10-09 07:45:08 +00001081 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001082
1083 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1084 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001085
1086 // We want to instrument every address only once per basic block (unless there
1087 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001088 SmallSet<Value*, 16> TempsToInstrument;
1089 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001090 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001091 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001092
1093 // Fill the set of memory operations to instrument.
1094 for (Function::iterator FI = F.begin(), FE = F.end();
1095 FI != FE; ++FI) {
1096 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001097 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001098 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1099 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001100 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001101 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001102 if (ClOpt && ClOptSameTemp) {
1103 if (!TempsToInstrument.insert(Addr))
1104 continue; // We've seen this temp in the current BB.
1105 }
1106 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1107 // ok, take it.
1108 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001109 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001110 // A call inside BB.
1111 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +00001112 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001113 NoReturnCalls.push_back(CI);
1114 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001115 }
1116 continue;
1117 }
1118 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001119 NumInsnsPerBB++;
1120 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1121 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001122 }
1123 }
1124
1125 // Instrument.
1126 int NumInstrumented = 0;
1127 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1128 Instruction *Inst = ToInstrument[i];
1129 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1130 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001131 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001132 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001133 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001134 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001135 }
1136 NumInstrumented++;
1137 }
1138
Alexey Samsonov59cca132012-12-25 12:04:36 +00001139 FunctionStackPoisoner FSP(F, *this);
1140 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001141
1142 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1143 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1144 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1145 Instruction *CI = NoReturnCalls[i];
1146 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001147 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001148 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001149 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001150
1151 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001152}
1153
1154static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1155 if (ShadowRedzoneSize == 1) return PoisonByte;
1156 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1157 if (ShadowRedzoneSize == 4)
1158 return (PoisonByte << 24) + (PoisonByte << 16) +
1159 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001160 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001161}
1162
1163static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1164 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001165 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001166 size_t ShadowGranularity,
1167 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001168 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001169 i+= ShadowGranularity, Shadow++) {
1170 if (i + ShadowGranularity <= Size) {
1171 *Shadow = 0; // fully addressable
1172 } else if (i >= Size) {
1173 *Shadow = Magic; // unaddressable
1174 } else {
1175 *Shadow = Size - i; // first Size-i bytes are addressable
1176 }
1177 }
1178}
1179
Alexey Samsonov59cca132012-12-25 12:04:36 +00001180// Workaround for bug 11395: we don't want to instrument stack in functions
1181// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1182// FIXME: remove once the bug 11395 is fixed.
1183bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1184 if (LongSize != 32) return false;
1185 CallInst *CI = dyn_cast<CallInst>(I);
1186 if (!CI || !CI->isInlineAsm()) return false;
1187 if (CI->getNumArgOperands() <= 5) return false;
1188 // We have inline assembly with quite a few arguments.
1189 return true;
1190}
1191
1192void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1193 IRBuilder<> IRB(*C);
1194 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1195 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1196 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1197 kAsanStackFreeName, IRB.getVoidTy(),
1198 IntptrTy, IntptrTy, IntptrTy, NULL));
1199 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1200 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1201 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1202 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1203}
1204
1205void FunctionStackPoisoner::poisonRedZones(
1206 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1207 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001208 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001209 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1210 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1211 Type *RZPtrTy = PointerType::get(RZTy, 0);
1212
1213 Value *PoisonLeft = ConstantInt::get(RZTy,
1214 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1215 Value *PoisonMid = ConstantInt::get(RZTy,
1216 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1217 Value *PoisonRight = ConstantInt::get(RZTy,
1218 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1219
1220 // poison the first red zone.
1221 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1222
1223 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001224 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001225 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1226 AllocaInst *AI = AllocaVec[i];
1227 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1228 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001229 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001230 Value *Ptr = NULL;
1231
1232 Pos += AlignedSize;
1233
1234 assert(ShadowBase->getType() == IntptrTy);
1235 if (SizeInBytes < AlignedSize) {
1236 // Poison the partial redzone at right
1237 Ptr = IRB.CreateAdd(
1238 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001239 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001240 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001241 uint32_t Poison = 0;
1242 if (DoPoison) {
1243 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001244 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001245 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001246 kAsanStackPartialRedzoneMagic);
1247 }
1248 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1249 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1250 }
1251
1252 // Poison the full redzone at right.
1253 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001254 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001255 bool LastAlloca = (i == AllocaVec.size() - 1);
1256 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001257 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1258
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001259 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001260 }
1261}
1262
Alexey Samsonov59cca132012-12-25 12:04:36 +00001263void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001264 uint64_t LocalStackSize = TotalStackSize +
1265 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001266
Alexey Samsonov59cca132012-12-25 12:04:36 +00001267 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001268 && LocalStackSize <= kMaxStackMallocSize;
1269
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001270 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001271 Instruction *InsBefore = AllocaVec[0];
1272 IRBuilder<> IRB(InsBefore);
1273
1274
1275 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1276 AllocaInst *MyAlloca =
1277 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001278 if (ClRealignStack && StackAlignment < RedzoneSize())
1279 StackAlignment = RedzoneSize();
1280 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001281 assert(MyAlloca->isStaticAlloca());
1282 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1283 Value *LocalStackBase = OrigStackBase;
1284
1285 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001286 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1287 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1288 }
1289
1290 // This string will be parsed by the run-time (DescribeStackAddress).
1291 SmallString<2048> StackDescriptionStorage;
1292 raw_svector_ostream StackDescription(StackDescriptionStorage);
1293 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1294
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001295 // Insert poison calls for lifetime intrinsics for alloca.
1296 bool HavePoisonedAllocas = false;
1297 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1298 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1299 IntrinsicInst *II = APC.InsBefore;
1300 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1301 assert(AI);
1302 IRBuilder<> IRB(II);
1303 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1304 HavePoisonedAllocas |= APC.DoPoison;
1305 }
1306
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001307 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001308 // Replace Alloca instructions with base+offset.
1309 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1310 AllocaInst *AI = AllocaVec[i];
1311 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1312 StringRef Name = AI->getName();
1313 StackDescription << Pos << " " << SizeInBytes << " "
1314 << Name.size() << " " << Name << " ";
1315 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001316 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001317 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001318 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001319 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001320 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001321 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001322 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001323 }
1324 assert(Pos == LocalStackSize);
1325
1326 // Write the Magic value and the frame description constant to the redzone.
1327 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1328 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1329 BasePlus0);
1330 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001331 ConstantInt::get(IntptrTy,
1332 ASan.LongSize/8));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001333 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001334 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001335 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001336 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1337 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001338 IRB.CreateStore(Description, BasePlus1);
1339
1340 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001341 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1342 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001343
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001344 // Unpoison the stack before all ret instructions.
1345 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1346 Instruction *Ret = RetVec[i];
1347 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001348 // Mark the current frame as retired.
1349 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1350 BasePlus0);
1351 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001352 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001353 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001354 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001355 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1356 ConstantInt::get(IntptrTy, LocalStackSize),
1357 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001358 } else if (HavePoisonedAllocas) {
1359 // If we poisoned some allocas in llvm.lifetime analysis,
1360 // unpoison whole stack frame now.
1361 assert(LocalStackBase == OrigStackBase);
1362 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001363 }
1364 }
1365
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001366 // We are done. Remove the old unused alloca instructions.
1367 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1368 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001369}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001370
Alexey Samsonov59cca132012-12-25 12:04:36 +00001371void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1372 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001373 // For now just insert the call to ASan runtime.
1374 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1375 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1376 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1377 : AsanUnpoisonStackMemoryFunc,
1378 AddrArg, SizeArg);
1379}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001380
1381// Handling llvm.lifetime intrinsics for a given %alloca:
1382// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1383// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1384// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1385// could be poisoned by previous llvm.lifetime.end instruction, as the
1386// variable may go in and out of scope several times, e.g. in loops).
1387// (3) if we poisoned at least one %alloca in a function,
1388// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001389
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001390AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1391 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1392 // We're intested only in allocas we can handle.
1393 return isInterestingAlloca(*AI) ? AI : 0;
1394 // See if we've already calculated (or started to calculate) alloca for a
1395 // given value.
1396 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1397 if (I != AllocaForValue.end())
1398 return I->second;
1399 // Store 0 while we're calculating alloca for value V to avoid
1400 // infinite recursion if the value references itself.
1401 AllocaForValue[V] = 0;
1402 AllocaInst *Res = 0;
1403 if (CastInst *CI = dyn_cast<CastInst>(V))
1404 Res = findAllocaForValue(CI->getOperand(0));
1405 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1406 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1407 Value *IncValue = PN->getIncomingValue(i);
1408 // Allow self-referencing phi-nodes.
1409 if (IncValue == PN) continue;
1410 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1411 // AI for incoming values should exist and should all be equal.
1412 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1413 return 0;
1414 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001415 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001416 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001417 if (Res != 0)
1418 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001419 return Res;
1420}