blob: 4e05c3200ceb43987795f329ed4a508ef07a3fb3 [file] [log] [blame]
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "asan"
17
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +000018#include "BlackList.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000019#include "llvm/Function.h"
20#include "llvm/IRBuilder.h"
Kostya Serebryanyf7b08222012-07-20 09:54:50 +000021#include "llvm/InlineAsm.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000022#include "llvm/IntrinsicInst.h"
23#include "llvm/LLVMContext.h"
24#include "llvm/Module.h"
25#include "llvm/Type.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000026#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000032#include "llvm/ADT/Triple.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/DataTypes.h"
35#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000036#include "llvm/Support/raw_ostream.h"
37#include "llvm/Support/system_error.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000038#include "llvm/DataLayout.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000039#include "llvm/Target/TargetMachine.h"
40#include "llvm/Transforms/Instrumentation.h"
41#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043
44#include <string>
45#include <algorithm>
46
47using namespace llvm;
48
49static const uint64_t kDefaultShadowScale = 3;
50static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
51static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000052static const uint64_t kDefaultShadowOffsetAndroid = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000053
54static const size_t kMaxStackMallocSize = 1 << 16; // 64K
55static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
56static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
57
58static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000059static const char *kAsanModuleDtorName = "asan.module_dtor";
60static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000061static const char *kAsanReportErrorTemplate = "__asan_report_";
62static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000063static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000064static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
65static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000066static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000067static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000068static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
69static const char *kAsanMappingScaleName = "__asan_mapping_scale";
70static const char *kAsanStackMallocName = "__asan_stack_malloc";
71static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000072static const char *kAsanGenPrefix = "__asan_gen_";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000073
74static const int kAsanStackLeftRedzoneMagic = 0xf1;
75static const int kAsanStackMidRedzoneMagic = 0xf2;
76static const int kAsanStackRightRedzoneMagic = 0xf3;
77static const int kAsanStackPartialRedzoneMagic = 0xf4;
78
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000079// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
80static const size_t kNumberOfAccessSizes = 5;
81
Kostya Serebryany800e03f2011-11-16 01:35:23 +000082// Command-line flags.
83
84// This flag may need to be replaced with -f[no-]asan-reads.
85static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
86 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
87static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
88 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000089static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
90 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
91 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +000092static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
93 cl::desc("use instrumentation with slow path for all accesses"),
94 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000095// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +000096// in any given BB. Normally, this should be set to unlimited (INT_MAX),
97// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
98// set it to 10000.
99static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
100 cl::init(10000),
101 cl::desc("maximal number of instructions to instrument in any given BB"),
102 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000103// This flag may need to be replaced with -f[no]asan-stack.
104static cl::opt<bool> ClStack("asan-stack",
105 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
106// This flag may need to be replaced with -f[no]asan-use-after-return.
107static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
108 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
109// This flag may need to be replaced with -f[no]asan-globals.
110static cl::opt<bool> ClGlobals("asan-globals",
111 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000112static cl::opt<bool> ClInitializers("asan-initialization-order",
113 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000114static cl::opt<bool> ClMemIntrin("asan-memintrin",
115 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
116// This flag may need to be replaced with -fasan-blacklist.
117static cl::opt<std::string> ClBlackListFile("asan-blacklist",
118 cl::desc("File containing the list of functions to ignore "
119 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000120
121// These flags allow to change the shadow mapping.
122// The shadow mapping looks like
123// Shadow = (Mem >> scale) + (1 << offset_log)
124static cl::opt<int> ClMappingScale("asan-mapping-scale",
125 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
126static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
127 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
128
129// Optimization flags. Not user visible, used mostly for testing
130// and benchmarking the tool.
131static cl::opt<bool> ClOpt("asan-opt",
132 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
133static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
134 cl::desc("Instrument the same temp just once"), cl::Hidden,
135 cl::init(true));
136static cl::opt<bool> ClOptGlobals("asan-opt-globals",
137 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
138
139// Debug flags.
140static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
141 cl::init(0));
142static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
143 cl::Hidden, cl::init(0));
144static cl::opt<std::string> ClDebugFunc("asan-debug-func",
145 cl::Hidden, cl::desc("Debug func"));
146static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
147 cl::Hidden, cl::init(-1));
148static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
149 cl::Hidden, cl::init(-1));
150
151namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000152/// A set of dynamically initialized globals extracted from metadata.
153class SetOfDynamicallyInitializedGlobals {
154 public:
155 void Init(Module& M) {
156 // Clang generates metadata identifying all dynamically initialized globals.
157 NamedMDNode *DynamicGlobals =
158 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
159 if (!DynamicGlobals)
160 return;
161 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
162 MDNode *MDN = DynamicGlobals->getOperand(i);
163 assert(MDN->getNumOperands() == 1);
164 Value *VG = MDN->getOperand(0);
165 // The optimizer may optimize away a global entirely, in which case we
166 // cannot instrument access to it.
167 if (!VG)
168 continue;
169 DynInitGlobals.insert(cast<GlobalVariable>(VG));
170 }
171 }
172 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
173 private:
174 SmallSet<GlobalValue*, 32> DynInitGlobals;
175};
176
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000177static int MappingScale() {
178 return ClMappingScale ? ClMappingScale : kDefaultShadowScale;
179}
180
181static size_t RedzoneSize() {
182 // Redzone used for stack and globals is at least 32 bytes.
183 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
184 return std::max(32U, 1U << MappingScale());
185}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000186
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000187/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000188struct AddressSanitizer : public FunctionPass {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000189 AddressSanitizer();
Alexander Potapenko25878042012-01-23 11:22:43 +0000190 virtual const char *getPassName() const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000191 void instrumentMop(Instruction *I);
192 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000193 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000194 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
195 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000196 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000197 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000198 bool instrumentMemIntrinsic(MemIntrinsic *MI);
199 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000200 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000201 Instruction *InsertBefore, bool IsWrite);
202 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000203 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000204 void createInitializerPoisonCalls(Module &M,
205 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000206 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000207 bool poisonStackInFunction(Function &F);
208 virtual bool doInitialization(Module &M);
209 virtual bool doFinalization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000210 static char ID; // Pass identification, replacement for typeid
211
212 private:
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000213 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
214 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000215 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000216 return SizeInBytes;
217 }
218 uint64_t getAlignedSize(uint64_t SizeInBytes) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000219 size_t RZ = RedzoneSize();
220 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000221 }
222 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
223 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
224 return getAlignedSize(SizeInBytes);
225 }
226
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000227 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000228 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
229 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000230 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000231 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000232
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000233 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000234 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000235 uint64_t MappingOffset;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000236 int LongSize;
237 Type *IntptrTy;
238 Type *IntptrPtrTy;
239 Function *AsanCtorFunction;
240 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000241 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
242 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000243 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000244 // This array is indexed by AccessIsWrite and log2(AccessSize).
245 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000246 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000247 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000248};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000249
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000250// FIXME: inherit this from ModulePass and actually use it as a ModulePass.
251class AddressSanitizerCreateGlobalRedzonesPass {
252 public:
253 bool runOnModule(Module &M, DataLayout *TD);
254 private:
255 bool ShouldInstrumentGlobal(GlobalVariable *G);
256 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
257 Value *LastAddr);
258
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000259 OwningPtr<BlackList> BL;
260 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
261 Type *IntptrTy;
262 LLVMContext *C;
263};
264
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000265} // namespace
266
267char AddressSanitizer::ID = 0;
268INITIALIZE_PASS(AddressSanitizer, "asan",
269 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
270 false, false)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000271AddressSanitizer::AddressSanitizer() : FunctionPass(ID) { }
272FunctionPass *llvm::createAddressSanitizerPass() {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000273 return new AddressSanitizer();
274}
275
Alexander Potapenko25878042012-01-23 11:22:43 +0000276const char *AddressSanitizer::getPassName() const {
277 return "AddressSanitizer";
278}
279
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000280static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
281 size_t Res = CountTrailingZeros_32(TypeSize / 8);
282 assert(Res < kNumberOfAccessSizes);
283 return Res;
284}
285
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000286// Create a constant for Str so that we can pass it to the run-time lib.
287static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000288 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000289 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000290 GlobalValue::PrivateLinkage, StrConst,
291 kAsanGenPrefix);
292}
293
294static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
295 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000296}
297
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000298Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
299 // Shadow >> scale
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000300 Shadow = IRB.CreateLShr(Shadow, MappingScale());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000301 if (MappingOffset == 0)
302 return Shadow;
303 // (Shadow >> scale) | offset
304 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
305 MappingOffset));
306}
307
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000308void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000309 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000310 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
311 // Check the first byte.
312 {
313 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000314 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000315 }
316 // Check the last byte.
317 {
318 IRBuilder<> IRB(InsertBefore);
319 Value *SizeMinusOne = IRB.CreateSub(
320 Size, ConstantInt::get(Size->getType(), 1));
321 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
322 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
323 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000324 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000325 }
326}
327
328// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000329bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000330 Value *Dst = MI->getDest();
331 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000332 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000333 Value *Length = MI->getLength();
334
335 Constant *ConstLength = dyn_cast<Constant>(Length);
336 Instruction *InsertBefore = MI;
337 if (ConstLength) {
338 if (ConstLength->isNullValue()) return false;
339 } else {
340 // The size is not a constant so it could be zero -- check at run-time.
341 IRBuilder<> IRB(InsertBefore);
342
343 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000344 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000345 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000346 }
347
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000348 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000349 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000350 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000351 return true;
352}
353
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000354// If I is an interesting memory access, return the PointerOperand
355// and set IsWrite. Otherwise return NULL.
356static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000357 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000358 if (!ClInstrumentReads) return NULL;
359 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000360 return LI->getPointerOperand();
361 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000362 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
363 if (!ClInstrumentWrites) return NULL;
364 *IsWrite = true;
365 return SI->getPointerOperand();
366 }
367 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
368 if (!ClInstrumentAtomics) return NULL;
369 *IsWrite = true;
370 return RMW->getPointerOperand();
371 }
372 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
373 if (!ClInstrumentAtomics) return NULL;
374 *IsWrite = true;
375 return XCHG->getPointerOperand();
376 }
377 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000378}
379
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000380void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000381 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000382 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
383 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000384 if (ClOpt && ClOptGlobals) {
385 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
386 // If initialization order checking is disabled, a simple access to a
387 // dynamically initialized global is always valid.
388 if (!ClInitializers)
389 return;
390 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000391 // have to instrument it. However, if a global does not have initailizer
392 // at all, we assume it has dynamic initializer (in other TU).
393 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000394 return;
395 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000396 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000397
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000398 Type *OrigPtrTy = Addr->getType();
399 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
400
401 assert(OrigTy->isSized());
402 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
403
404 if (TypeSize != 8 && TypeSize != 16 &&
405 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
406 // Ignore all unusual sizes.
407 return;
408 }
409
410 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000411 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000412}
413
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000414// Validate the result of Module::getOrInsertFunction called for an interface
415// function of AddressSanitizer. If the instrumented module defines a function
416// with the same name, their prototypes must match, otherwise
417// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000418static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000419 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
420 FuncOrBitcast->dump();
421 report_fatal_error("trying to redefine an AddressSanitizer "
422 "interface function");
423}
424
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000425Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000426 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000427 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000428 IRBuilder<> IRB(InsertBefore);
429 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
430 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000431 // We don't do Call->setDoesNotReturn() because the BB already has
432 // UnreachableInst at the end.
433 // This EmptyAsm is required to avoid callback merge.
434 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000435 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000436}
437
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000438Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000439 Value *ShadowValue,
440 uint32_t TypeSize) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000441 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000442 // Addr & (Granularity - 1)
443 Value *LastAccessedByte = IRB.CreateAnd(
444 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
445 // (Addr & (Granularity - 1)) + size - 1
446 if (TypeSize / 8 > 1)
447 LastAccessedByte = IRB.CreateAdd(
448 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
449 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
450 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000451 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000452 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
453 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
454}
455
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000456void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000457 IRBuilder<> &IRB, Value *Addr,
458 uint32_t TypeSize, bool IsWrite) {
459 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
460
461 Type *ShadowTy = IntegerType::get(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000462 *C, std::max(8U, TypeSize >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000463 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
464 Value *ShadowPtr = memToShadow(AddrLong, IRB);
465 Value *CmpVal = Constant::getNullValue(ShadowTy);
466 Value *ShadowValue = IRB.CreateLoad(
467 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
468
469 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000470 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000471 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000472 TerminatorInst *CrashTerm = 0;
473
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000474 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000475 TerminatorInst *CheckTerm =
476 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000477 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000478 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000479 IRB.SetInsertPoint(CheckTerm);
480 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000481 BasicBlock *CrashBlock =
482 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000483 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000484 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
485 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000486 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000487 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000488 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000489
490 Instruction *Crash =
491 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
492 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000493}
494
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000495void AddressSanitizerCreateGlobalRedzonesPass::createInitializerPoisonCalls(
496 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000497 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
498 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
499 // If that function is not present, this TU contains no globals, or they have
500 // all been optimized away
501 if (!GlobalInit)
502 return;
503
504 // Set up the arguments to our poison/unpoison functions.
505 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
506
507 // Declare our poisoning and unpoisoning functions.
508 Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
509 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
510 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
511 Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
512 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
513 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
514
515 // Add a call to poison all external globals before the given function starts.
516 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
517
518 // Add calls to unpoison all globals before each return instruction.
519 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
520 I != E; ++I) {
521 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
522 CallInst::Create(AsanUnpoisonGlobals, "", RI);
523 }
524 }
525}
526
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000527bool AddressSanitizerCreateGlobalRedzonesPass::ShouldInstrumentGlobal(
528 GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000529 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000530 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000531
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000532 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000533 if (!Ty->isSized()) return false;
534 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000535 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000536 // Touch only those globals that will not be defined in other modules.
537 // Don't handle ODR type linkages since other modules may be built w/o asan.
538 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
539 G->getLinkage() != GlobalVariable::PrivateLinkage &&
540 G->getLinkage() != GlobalVariable::InternalLinkage)
541 return false;
542 // Two problems with thread-locals:
543 // - The address of the main thread's copy can't be computed at link-time.
544 // - Need to poison all copies, not just the main thread's one.
545 if (G->isThreadLocal())
546 return false;
547 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000548 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000549
550 // Ignore all the globals with the names starting with "\01L_OBJC_".
551 // Many of those are put into the .cstring section. The linker compresses
552 // that section by removing the spare \0s after the string terminator, so
553 // our redzones get broken.
554 if ((G->getName().find("\01L_OBJC_") == 0) ||
555 (G->getName().find("\01l_OBJC_") == 0)) {
556 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
557 return false;
558 }
559
560 if (G->hasSection()) {
561 StringRef Section(G->getSection());
562 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
563 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
564 // them.
565 if ((Section.find("__OBJC,") == 0) ||
566 (Section.find("__DATA, __objc_") == 0)) {
567 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
568 return false;
569 }
570 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
571 // Constant CFString instances are compiled in the following way:
572 // -- the string buffer is emitted into
573 // __TEXT,__cstring,cstring_literals
574 // -- the constant NSConstantString structure referencing that buffer
575 // is placed into __DATA,__cfstring
576 // Therefore there's no point in placing redzones into __DATA,__cfstring.
577 // Moreover, it causes the linker to crash on OS X 10.7
578 if (Section.find("__DATA,__cfstring") == 0) {
579 DEBUG(dbgs() << "Ignoring CFString: " << *G);
580 return false;
581 }
582 }
583
584 return true;
585}
586
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000587// This function replaces all global variables with new variables that have
588// trailing redzones. It also creates a function that poisons
589// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000590bool AddressSanitizerCreateGlobalRedzonesPass::runOnModule(Module &M,
591 DataLayout *TD) {
592 BL.reset(new BlackList(ClBlackListFile));
593 DynamicallyInitializedGlobals.Init(M);
594 C = &(M.getContext());
595 IntptrTy = Type::getIntNTy(*C, TD->getPointerSizeInBits());
596
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000597 SmallVector<GlobalVariable *, 16> GlobalsToChange;
598
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000599 for (Module::GlobalListType::iterator G = M.global_begin(),
600 E = M.global_end(); G != E; ++G) {
601 if (ShouldInstrumentGlobal(G))
602 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000603 }
604
605 size_t n = GlobalsToChange.size();
606 if (n == 0) return false;
607
608 // A global is described by a structure
609 // size_t beg;
610 // size_t size;
611 // size_t size_with_redzone;
612 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000613 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000614 // We initialize an array of such structures and pass it to a run-time call.
615 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000616 IntptrTy, IntptrTy,
617 IntptrTy, NULL);
618 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000619
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000620
621 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
622 assert(CtorFunc);
623 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000624
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000625 // The addresses of the first and last dynamically initialized globals in
626 // this TU. Used in initialization order checking.
627 Value *FirstDynamic = 0, *LastDynamic = 0;
628
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000629 for (size_t i = 0; i < n; i++) {
630 GlobalVariable *G = GlobalsToChange[i];
631 PointerType *PtrTy = cast<PointerType>(G->getType());
632 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000633 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000634 size_t RZ = RedzoneSize();
635 uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000636 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000637 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000638 bool GlobalHasDynamicInitializer =
639 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000640 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000641 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000642
643 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
644 Constant *NewInitializer = ConstantStruct::get(
645 NewTy, G->getInitializer(),
646 Constant::getNullValue(RightRedZoneTy), NULL);
647
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000648 SmallString<2048> DescriptionOfGlobal = G->getName();
649 DescriptionOfGlobal += " (";
650 DescriptionOfGlobal += M.getModuleIdentifier();
651 DescriptionOfGlobal += ")";
652 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000653
654 // Create a new global variable with enough space for a redzone.
655 GlobalVariable *NewGlobal = new GlobalVariable(
656 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000657 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000658 NewGlobal->copyAttributesFrom(G);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000659 NewGlobal->setAlignment(RZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000660
661 Value *Indices2[2];
662 Indices2[0] = IRB.getInt32(0);
663 Indices2[1] = IRB.getInt32(0);
664
665 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000666 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000667 NewGlobal->takeName(G);
668 G->eraseFromParent();
669
670 Initializers[i] = ConstantStruct::get(
671 GlobalStructTy,
672 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
673 ConstantInt::get(IntptrTy, SizeInBytes),
674 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
675 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000676 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000677 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000678
679 // Populate the first and last globals declared in this TU.
680 if (ClInitializers && GlobalHasDynamicInitializer) {
681 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
682 if (FirstDynamic == 0)
683 FirstDynamic = LastDynamic;
684 }
685
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000686 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000687 }
688
689 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
690 GlobalVariable *AllGlobals = new GlobalVariable(
691 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
692 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
693
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000694 // Create calls for poisoning before initializers run and unpoisoning after.
695 if (ClInitializers && FirstDynamic && LastDynamic)
696 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
697
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000698 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000699 kAsanRegisterGlobalsName, IRB.getVoidTy(),
700 IntptrTy, IntptrTy, NULL));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000701 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
702
703 IRB.CreateCall2(AsanRegisterGlobals,
704 IRB.CreatePointerCast(AllGlobals, IntptrTy),
705 ConstantInt::get(IntptrTy, n));
706
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000707 // We also need to unregister globals at the end, e.g. when a shared library
708 // gets closed.
709 Function *AsanDtorFunction = Function::Create(
710 FunctionType::get(Type::getVoidTy(*C), false),
711 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
712 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
713 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000714 Function *AsanUnregisterGlobals =
715 checkInterfaceFunction(M.getOrInsertFunction(
716 kAsanUnregisterGlobalsName,
717 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000718 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
719
720 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
721 IRB.CreatePointerCast(AllGlobals, IntptrTy),
722 ConstantInt::get(IntptrTy, n));
723 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
724
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000725 DEBUG(dbgs() << M);
726 return true;
727}
728
729// virtual
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000730bool AddressSanitizer::doInitialization(Module &M) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000731 // Initialize the private fields. No one has accessed them before.
Micah Villmow3574eca2012-10-08 16:38:25 +0000732 TD = getAnalysisIfAvailable<DataLayout>();
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000733
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000734 if (!TD)
735 return false;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000736 BL.reset(new BlackList(ClBlackListFile));
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000737 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000738
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000739 C = &(M.getContext());
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000740 LongSize = TD->getPointerSizeInBits();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000741 IntptrTy = Type::getIntNTy(*C, LongSize);
742 IntptrPtrTy = PointerType::get(IntptrTy, 0);
743
744 AsanCtorFunction = Function::Create(
745 FunctionType::get(Type::getVoidTy(*C), false),
746 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
747 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000748 // call __asan_init in the module ctor.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000749 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000750 AsanInitFunction = checkInterfaceFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000751 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
752 AsanInitFunction->setLinkage(Function::ExternalLinkage);
753 IRB.CreateCall(AsanInitFunction);
754
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000755 // Create __asan_report* callbacks.
756 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
757 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
758 AccessSizeIndex++) {
759 // IsWrite and TypeSize are encoded in the function name.
760 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
761 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000762 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000763 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
764 checkInterfaceFunction(M.getOrInsertFunction(
765 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000766 }
767 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000768
769 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
770 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
771 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
772 kAsanStackFreeName, IRB.getVoidTy(),
773 IntptrTy, IntptrTy, IntptrTy, NULL));
774 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
775 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
776
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000777 // We insert an empty inline asm after __asan_report* to avoid callback merge.
778 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
779 StringRef(""), StringRef(""),
780 /*hasSideEffects=*/true);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000781
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000782 llvm::Triple targetTriple(M.getTargetTriple());
Logan Chien43bf7092012-09-02 09:29:46 +0000783 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000784
785 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
786 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000787 if (ClMappingOffsetLog >= 0) {
788 if (ClMappingOffsetLog == 0) {
789 // special case
790 MappingOffset = 0;
791 } else {
792 MappingOffset = 1ULL << ClMappingOffsetLog;
793 }
794 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000795
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000796
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000797 if (ClMappingOffsetLog >= 0) {
798 // Tell the run-time the current values of mapping offset and scale.
799 GlobalValue *asan_mapping_offset =
800 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
801 ConstantInt::get(IntptrTy, MappingOffset),
802 kAsanMappingOffsetName);
803 // Read the global, otherwise it may be optimized away.
804 IRB.CreateLoad(asan_mapping_offset, true);
805 }
806 if (ClMappingScale) {
807 GlobalValue *asan_mapping_scale =
808 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000809 ConstantInt::get(IntptrTy, MappingScale()),
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000810 kAsanMappingScaleName);
811 // Read the global, otherwise it may be optimized away.
812 IRB.CreateLoad(asan_mapping_scale, true);
813 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000814
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000815 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000816
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000817 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000818}
819
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000820bool AddressSanitizer::doFinalization(Module &M) {
821 // We transform the globals at the very end so that the optimization analysis
822 // works on the original globals.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000823 if (ClGlobals) {
824 // FIXME: instead of doFinalization, run this as a true ModulePass.
825 AddressSanitizerCreateGlobalRedzonesPass Pass;
826 return Pass.runOnModule(M, TD);
827 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000828 return false;
829}
830
831
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000832bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
833 // For each NSObject descendant having a +load method, this method is invoked
834 // by the ObjC runtime before any of the static constructors is called.
835 // Therefore we need to instrument such methods with a call to __asan_init
836 // at the beginning in order to initialize our runtime before any access to
837 // the shadow memory.
838 // We cannot just ignore these methods, because they may call other
839 // instrumented functions.
840 if (F.getName().find(" load]") != std::string::npos) {
841 IRBuilder<> IRB(F.begin()->begin());
842 IRB.CreateCall(AsanInitFunction);
843 return true;
844 }
845 return false;
846}
847
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000848bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000849 if (BL->isIn(F)) return false;
850 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000851 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000852
853 // If needed, insert __asan_init before checking for AddressSafety attr.
854 maybeInsertAsanInitAtFunctionEntry(F);
855
Bill Wendling67658342012-10-09 07:45:08 +0000856 if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety))
857 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000858
859 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
860 return false;
Bill Wendling67658342012-10-09 07:45:08 +0000861
862 // We want to instrument every address only once per basic block (unless there
863 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000864 SmallSet<Value*, 16> TempsToInstrument;
865 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000866 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000867 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000868
869 // Fill the set of memory operations to instrument.
870 for (Function::iterator FI = F.begin(), FE = F.end();
871 FI != FE; ++FI) {
872 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000873 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000874 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
875 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000876 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000877 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000878 if (ClOpt && ClOptSameTemp) {
879 if (!TempsToInstrument.insert(Addr))
880 continue; // We've seen this temp in the current BB.
881 }
882 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
883 // ok, take it.
884 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000885 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000886 // A call inside BB.
887 TempsToInstrument.clear();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000888 if (CI->doesNotReturn()) {
889 NoReturnCalls.push_back(CI);
890 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000891 }
892 continue;
893 }
894 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000895 NumInsnsPerBB++;
896 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
897 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000898 }
899 }
900
901 // Instrument.
902 int NumInstrumented = 0;
903 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
904 Instruction *Inst = ToInstrument[i];
905 if (ClDebugMin < 0 || ClDebugMax < 0 ||
906 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000907 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000908 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000909 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000910 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000911 }
912 NumInstrumented++;
913 }
914
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000915 bool ChangedStack = poisonStackInFunction(F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000916
917 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
918 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
919 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
920 Instruction *CI = NoReturnCalls[i];
921 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000922 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000923 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000924 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000925
926 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000927}
928
929static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
930 if (ShadowRedzoneSize == 1) return PoisonByte;
931 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
932 if (ShadowRedzoneSize == 4)
933 return (PoisonByte << 24) + (PoisonByte << 16) +
934 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000935 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000936}
937
938static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
939 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000940 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000941 size_t ShadowGranularity,
942 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000943 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000944 i+= ShadowGranularity, Shadow++) {
945 if (i + ShadowGranularity <= Size) {
946 *Shadow = 0; // fully addressable
947 } else if (i >= Size) {
948 *Shadow = Magic; // unaddressable
949 } else {
950 *Shadow = Size - i; // first Size-i bytes are addressable
951 }
952 }
953}
954
955void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
956 IRBuilder<> IRB,
957 Value *ShadowBase, bool DoPoison) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000958 size_t ShadowRZSize = RedzoneSize() >> MappingScale();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000959 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
960 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
961 Type *RZPtrTy = PointerType::get(RZTy, 0);
962
963 Value *PoisonLeft = ConstantInt::get(RZTy,
964 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
965 Value *PoisonMid = ConstantInt::get(RZTy,
966 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
967 Value *PoisonRight = ConstantInt::get(RZTy,
968 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
969
970 // poison the first red zone.
971 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
972
973 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000974 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000975 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
976 AllocaInst *AI = AllocaVec[i];
977 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
978 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000979 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000980 Value *Ptr = NULL;
981
982 Pos += AlignedSize;
983
984 assert(ShadowBase->getType() == IntptrTy);
985 if (SizeInBytes < AlignedSize) {
986 // Poison the partial redzone at right
987 Ptr = IRB.CreateAdd(
988 ShadowBase, ConstantInt::get(IntptrTy,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000989 (Pos >> MappingScale()) - ShadowRZSize));
990 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000991 uint32_t Poison = 0;
992 if (DoPoison) {
993 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000994 RedzoneSize(),
995 1ULL << MappingScale(),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000996 kAsanStackPartialRedzoneMagic);
997 }
998 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
999 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1000 }
1001
1002 // Poison the full redzone at right.
1003 Ptr = IRB.CreateAdd(ShadowBase,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001004 ConstantInt::get(IntptrTy, Pos >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001005 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
1006 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1007
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001008 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001009 }
1010}
1011
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001012// Workaround for bug 11395: we don't want to instrument stack in functions
1013// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +00001014// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001015bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1016 if (LongSize != 32) return false;
1017 CallInst *CI = dyn_cast<CallInst>(I);
1018 if (!CI || !CI->isInlineAsm()) return false;
1019 if (CI->getNumArgOperands() <= 5) return false;
1020 // We have inline assembly with quite a few arguments.
1021 return true;
1022}
1023
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001024// Find all static Alloca instructions and put
1025// poisoned red zones around all of them.
1026// Then unpoison everything back before the function returns.
1027//
1028// Stack poisoning does not play well with exception handling.
1029// When an exception is thrown, we essentially bypass the code
1030// that unpoisones the stack. This is why the run-time library has
1031// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1032// stack in the interceptor. This however does not work inside the
1033// actual function which catches the exception. Most likely because the
1034// compiler hoists the load of the shadow value somewhere too high.
1035// This causes asan to report a non-existing bug on 453.povray.
1036// It sounds like an LLVM bug.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001037bool AddressSanitizer::poisonStackInFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001038 if (!ClStack) return false;
1039 SmallVector<AllocaInst*, 16> AllocaVec;
1040 SmallVector<Instruction*, 8> RetVec;
1041 uint64_t TotalSize = 0;
1042
1043 // Filter out Alloca instructions we want (and can) handle.
1044 // Collect Ret instructions.
1045 for (Function::iterator FI = F.begin(), FE = F.end();
1046 FI != FE; ++FI) {
1047 BasicBlock &BB = *FI;
1048 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1049 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001050 if (isa<ReturnInst>(BI)) {
1051 RetVec.push_back(BI);
1052 continue;
1053 }
1054
1055 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1056 if (!AI) continue;
1057 if (AI->isArrayAllocation()) continue;
1058 if (!AI->isStaticAlloca()) continue;
1059 if (!AI->getAllocatedType()->isSized()) continue;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001060 if (AI->getAlignment() > RedzoneSize()) continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001061 AllocaVec.push_back(AI);
1062 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1063 TotalSize += AlignedSize;
1064 }
1065 }
1066
1067 if (AllocaVec.empty()) return false;
1068
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001069 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001070
1071 bool DoStackMalloc = ClUseAfterReturn
1072 && LocalStackSize <= kMaxStackMallocSize;
1073
1074 Instruction *InsBefore = AllocaVec[0];
1075 IRBuilder<> IRB(InsBefore);
1076
1077
1078 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1079 AllocaInst *MyAlloca =
1080 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001081 MyAlloca->setAlignment(RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001082 assert(MyAlloca->isStaticAlloca());
1083 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1084 Value *LocalStackBase = OrigStackBase;
1085
1086 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001087 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1088 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1089 }
1090
1091 // This string will be parsed by the run-time (DescribeStackAddress).
1092 SmallString<2048> StackDescriptionStorage;
1093 raw_svector_ostream StackDescription(StackDescriptionStorage);
1094 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1095
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001096 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001097 // Replace Alloca instructions with base+offset.
1098 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1099 AllocaInst *AI = AllocaVec[i];
1100 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1101 StringRef Name = AI->getName();
1102 StackDescription << Pos << " " << SizeInBytes << " "
1103 << Name.size() << " " << Name << " ";
1104 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001105 assert((AlignedSize % RedzoneSize()) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001106 AI->replaceAllUsesWith(
1107 IRB.CreateIntToPtr(
1108 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1109 AI->getType()));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001110 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001111 }
1112 assert(Pos == LocalStackSize);
1113
1114 // Write the Magic value and the frame description constant to the redzone.
1115 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1116 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1117 BasePlus0);
1118 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1119 ConstantInt::get(IntptrTy, LongSize/8));
1120 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001121 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001122 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001123 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001124 IRB.CreateStore(Description, BasePlus1);
1125
1126 // Poison the stack redzones at the entry.
1127 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1128 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1129
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001130 // Unpoison the stack before all ret instructions.
1131 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1132 Instruction *Ret = RetVec[i];
1133 IRBuilder<> IRBRet(Ret);
1134
1135 // Mark the current frame as retired.
1136 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1137 BasePlus0);
1138 // Unpoison the stack.
1139 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1140
1141 if (DoStackMalloc) {
1142 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1143 ConstantInt::get(IntptrTy, LocalStackSize),
1144 OrigStackBase);
1145 }
1146 }
1147
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001148 // We are done. Remove the old unused alloca instructions.
1149 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1150 AllocaVec[i]->eraseFromParent();
1151
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001152 if (ClDebugStack) {
1153 DEBUG(dbgs() << F);
1154 }
1155
1156 return true;
1157}