blob: a9d08db9c603e256fbf1b91c1273bcbe208b0f3c [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 Serebryanya1c45042012-03-14 23:22:10 +000018#include "FunctionBlackList.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000019#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/OwningPtr.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000025#include "llvm/ADT/Triple.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000026#include "llvm/Function.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000027#include "llvm/IntrinsicInst.h"
28#include "llvm/LLVMContext.h"
29#include "llvm/Module.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/DataTypes.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/IRBuilder.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000034#include "llvm/Support/raw_ostream.h"
35#include "llvm/Support/system_error.h"
36#include "llvm/Target/TargetData.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/Transforms/Instrumentation.h"
39#include "llvm/Transforms/Utils/BasicBlockUtils.h"
40#include "llvm/Transforms/Utils/ModuleUtils.h"
41#include "llvm/Type.h"
42
43#include <string>
44#include <algorithm>
45
46using namespace llvm;
47
48static const uint64_t kDefaultShadowScale = 3;
49static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
50static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000051static const uint64_t kDefaultShadowOffsetAndroid = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000052
53static const size_t kMaxStackMallocSize = 1 << 16; // 64K
54static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
55static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
56
57static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000058static const char *kAsanModuleDtorName = "asan.module_dtor";
59static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000060static const char *kAsanReportErrorTemplate = "__asan_report_";
61static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000062static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000063static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000064static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000065static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
66static const char *kAsanMappingScaleName = "__asan_mapping_scale";
67static const char *kAsanStackMallocName = "__asan_stack_malloc";
68static const char *kAsanStackFreeName = "__asan_stack_free";
69
70static const int kAsanStackLeftRedzoneMagic = 0xf1;
71static const int kAsanStackMidRedzoneMagic = 0xf2;
72static const int kAsanStackRightRedzoneMagic = 0xf3;
73static const int kAsanStackPartialRedzoneMagic = 0xf4;
74
75// Command-line flags.
76
77// This flag may need to be replaced with -f[no-]asan-reads.
78static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
79 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
80static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
81 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000082static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
83 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
84 cl::Hidden, cl::init(true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +000085// This flag may need to be replaced with -f[no]asan-stack.
86static cl::opt<bool> ClStack("asan-stack",
87 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
88// This flag may need to be replaced with -f[no]asan-use-after-return.
89static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
90 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
91// This flag may need to be replaced with -f[no]asan-globals.
92static cl::opt<bool> ClGlobals("asan-globals",
93 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
94static cl::opt<bool> ClMemIntrin("asan-memintrin",
95 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
96// This flag may need to be replaced with -fasan-blacklist.
97static cl::opt<std::string> ClBlackListFile("asan-blacklist",
98 cl::desc("File containing the list of functions to ignore "
99 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000100
101// These flags allow to change the shadow mapping.
102// The shadow mapping looks like
103// Shadow = (Mem >> scale) + (1 << offset_log)
104static cl::opt<int> ClMappingScale("asan-mapping-scale",
105 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
106static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
107 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
108
109// Optimization flags. Not user visible, used mostly for testing
110// and benchmarking the tool.
111static cl::opt<bool> ClOpt("asan-opt",
112 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
113static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
114 cl::desc("Instrument the same temp just once"), cl::Hidden,
115 cl::init(true));
116static cl::opt<bool> ClOptGlobals("asan-opt-globals",
117 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
118
119// Debug flags.
120static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
121 cl::init(0));
122static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
123 cl::Hidden, cl::init(0));
124static cl::opt<std::string> ClDebugFunc("asan-debug-func",
125 cl::Hidden, cl::desc("Debug func"));
126static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
127 cl::Hidden, cl::init(-1));
128static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
129 cl::Hidden, cl::init(-1));
130
131namespace {
132
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000133/// AddressSanitizer: instrument the code in module to find memory bugs.
134struct AddressSanitizer : public ModulePass {
135 AddressSanitizer();
Alexander Potapenko25878042012-01-23 11:22:43 +0000136 virtual const char *getPassName() const;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000137 void instrumentMop(Instruction *I);
138 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
139 Value *Addr, uint32_t TypeSize, bool IsWrite);
140 Instruction *generateCrashCode(IRBuilder<> &IRB, Value *Addr,
141 bool IsWrite, uint32_t TypeSize);
142 bool instrumentMemIntrinsic(MemIntrinsic *MI);
143 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
144 Value *Size,
145 Instruction *InsertBefore, bool IsWrite);
146 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
147 bool handleFunction(Module &M, Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000148 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000149 bool poisonStackInFunction(Module &M, Function &F);
150 virtual bool runOnModule(Module &M);
151 bool insertGlobalRedzones(Module &M);
152 BranchInst *splitBlockAndInsertIfThen(Instruction *SplitBefore, Value *Cmp);
153 static char ID; // Pass identification, replacement for typeid
154
155 private:
156
157 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
158 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000159 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000160 return SizeInBytes;
161 }
162 uint64_t getAlignedSize(uint64_t SizeInBytes) {
163 return ((SizeInBytes + RedzoneSize - 1)
164 / RedzoneSize) * RedzoneSize;
165 }
166 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
167 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
168 return getAlignedSize(SizeInBytes);
169 }
170
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000171 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000172 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
173 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000174 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000175
176 Module *CurrentModule;
177 LLVMContext *C;
178 TargetData *TD;
179 uint64_t MappingOffset;
180 int MappingScale;
181 size_t RedzoneSize;
182 int LongSize;
183 Type *IntptrTy;
184 Type *IntptrPtrTy;
185 Function *AsanCtorFunction;
186 Function *AsanInitFunction;
187 Instruction *CtorInsertBefore;
Kostya Serebryanya1c45042012-03-14 23:22:10 +0000188 OwningPtr<FunctionBlackList> BL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000189};
190} // namespace
191
192char AddressSanitizer::ID = 0;
193INITIALIZE_PASS(AddressSanitizer, "asan",
194 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
195 false, false)
196AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
197ModulePass *llvm::createAddressSanitizerPass() {
198 return new AddressSanitizer();
199}
200
Alexander Potapenko25878042012-01-23 11:22:43 +0000201const char *AddressSanitizer::getPassName() const {
202 return "AddressSanitizer";
203}
204
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000205// Create a constant for Str so that we can pass it to the run-time lib.
206static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000207 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000208 return new GlobalVariable(M, StrConst->getType(), true,
209 GlobalValue::PrivateLinkage, StrConst, "");
210}
211
212// Split the basic block and insert an if-then code.
213// Before:
214// Head
215// SplitBefore
216// Tail
217// After:
218// Head
219// if (Cmp)
220// NewBasicBlock
221// SplitBefore
222// Tail
223//
224// Returns the NewBasicBlock's terminator.
225BranchInst *AddressSanitizer::splitBlockAndInsertIfThen(
226 Instruction *SplitBefore, Value *Cmp) {
227 BasicBlock *Head = SplitBefore->getParent();
228 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
229 TerminatorInst *HeadOldTerm = Head->getTerminator();
230 BasicBlock *NewBasicBlock =
231 BasicBlock::Create(*C, "", Head->getParent());
232 BranchInst *HeadNewTerm = BranchInst::Create(/*ifTrue*/NewBasicBlock,
233 /*ifFalse*/Tail,
234 Cmp);
235 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
236
237 BranchInst *CheckTerm = BranchInst::Create(Tail, NewBasicBlock);
238 return CheckTerm;
239}
240
241Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
242 // Shadow >> scale
243 Shadow = IRB.CreateLShr(Shadow, MappingScale);
244 if (MappingOffset == 0)
245 return Shadow;
246 // (Shadow >> scale) | offset
247 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
248 MappingOffset));
249}
250
251void AddressSanitizer::instrumentMemIntrinsicParam(Instruction *OrigIns,
252 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
253 // Check the first byte.
254 {
255 IRBuilder<> IRB(InsertBefore);
256 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
257 }
258 // Check the last byte.
259 {
260 IRBuilder<> IRB(InsertBefore);
261 Value *SizeMinusOne = IRB.CreateSub(
262 Size, ConstantInt::get(Size->getType(), 1));
263 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
264 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
265 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
266 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
267 }
268}
269
270// Instrument memset/memmove/memcpy
271bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
272 Value *Dst = MI->getDest();
273 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
274 Value *Src = MemTran ? MemTran->getSource() : NULL;
275 Value *Length = MI->getLength();
276
277 Constant *ConstLength = dyn_cast<Constant>(Length);
278 Instruction *InsertBefore = MI;
279 if (ConstLength) {
280 if (ConstLength->isNullValue()) return false;
281 } else {
282 // The size is not a constant so it could be zero -- check at run-time.
283 IRBuilder<> IRB(InsertBefore);
284
285 Value *Cmp = IRB.CreateICmpNE(Length,
286 Constant::getNullValue(Length->getType()));
287 InsertBefore = splitBlockAndInsertIfThen(InsertBefore, Cmp);
288 }
289
290 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
291 if (Src)
292 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
293 return true;
294}
295
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000296// If I is an interesting memory access, return the PointerOperand
297// and set IsWrite. Otherwise return NULL.
298static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000299 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000300 if (!ClInstrumentReads) return NULL;
301 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000302 return LI->getPointerOperand();
303 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000304 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
305 if (!ClInstrumentWrites) return NULL;
306 *IsWrite = true;
307 return SI->getPointerOperand();
308 }
309 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
310 if (!ClInstrumentAtomics) return NULL;
311 *IsWrite = true;
312 return RMW->getPointerOperand();
313 }
314 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
315 if (!ClInstrumentAtomics) return NULL;
316 *IsWrite = true;
317 return XCHG->getPointerOperand();
318 }
319 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000320}
321
322void AddressSanitizer::instrumentMop(Instruction *I) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000323 bool IsWrite;
324 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
325 assert(Addr);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000326 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
327 // We are accessing a global scalar variable. Nothing to catch here.
328 return;
329 }
330 Type *OrigPtrTy = Addr->getType();
331 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
332
333 assert(OrigTy->isSized());
334 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
335
336 if (TypeSize != 8 && TypeSize != 16 &&
337 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
338 // Ignore all unusual sizes.
339 return;
340 }
341
342 IRBuilder<> IRB(I);
343 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
344}
345
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000346// Validate the result of Module::getOrInsertFunction called for an interface
347// function of AddressSanitizer. If the instrumented module defines a function
348// with the same name, their prototypes must match, otherwise
349// getOrInsertFunction returns a bitcast.
350Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
351 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
352 FuncOrBitcast->dump();
353 report_fatal_error("trying to redefine an AddressSanitizer "
354 "interface function");
355}
356
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000357Instruction *AddressSanitizer::generateCrashCode(
358 IRBuilder<> &IRB, Value *Addr, bool IsWrite, uint32_t TypeSize) {
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000359 // IsWrite and TypeSize are encoded in the function name.
360 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
361 (IsWrite ? "store" : "load") + itostr(TypeSize / 8);
362 Value *ReportWarningFunc = CurrentModule->getOrInsertFunction(
363 FunctionName, IRB.getVoidTy(), IntptrTy, NULL);
364 CallInst *Call = IRB.CreateCall(ReportWarningFunc, Addr);
365 Call->setDoesNotReturn();
366 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000367}
368
369void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
370 IRBuilder<> &IRB, Value *Addr,
371 uint32_t TypeSize, bool IsWrite) {
372 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
373
374 Type *ShadowTy = IntegerType::get(
375 *C, std::max(8U, TypeSize >> MappingScale));
376 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
377 Value *ShadowPtr = memToShadow(AddrLong, IRB);
378 Value *CmpVal = Constant::getNullValue(ShadowTy);
379 Value *ShadowValue = IRB.CreateLoad(
380 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
381
382 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
383
384 Instruction *CheckTerm = splitBlockAndInsertIfThen(
385 cast<Instruction>(Cmp)->getNextNode(), Cmp);
386 IRBuilder<> IRB2(CheckTerm);
387
388 size_t Granularity = 1 << MappingScale;
389 if (TypeSize < 8 * Granularity) {
390 // Addr & (Granularity - 1)
Kostya Serebryany3f119982012-04-27 10:04:53 +0000391 Value *LastAccessedByte = IRB2.CreateAnd(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000392 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
393 // (Addr & (Granularity - 1)) + size - 1
Kostya Serebryany3f119982012-04-27 10:04:53 +0000394 if (TypeSize / 8 > 1)
395 LastAccessedByte = IRB2.CreateAdd(
396 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000397 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
398 LastAccessedByte = IRB2.CreateIntCast(
399 LastAccessedByte, IRB.getInt8Ty(), false);
400 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
401 Value *Cmp2 = IRB2.CreateICmpSGE(LastAccessedByte, ShadowValue);
402
403 CheckTerm = splitBlockAndInsertIfThen(CheckTerm, Cmp2);
404 }
405
406 IRBuilder<> IRB1(CheckTerm);
407 Instruction *Crash = generateCrashCode(IRB1, AddrLong, IsWrite, TypeSize);
408 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryanycc1d8562011-12-01 18:54:53 +0000409 ReplaceInstWithInst(CheckTerm, new UnreachableInst(*C));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000410}
411
412// This function replaces all global variables with new variables that have
413// trailing redzones. It also creates a function that poisons
414// redzones and inserts this function into llvm.global_ctors.
415bool AddressSanitizer::insertGlobalRedzones(Module &M) {
416 SmallVector<GlobalVariable *, 16> GlobalsToChange;
417
418 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
419 E = M.getGlobalList().end(); G != E; ++G) {
420 Type *Ty = cast<PointerType>(G->getType())->getElementType();
421 DEBUG(dbgs() << "GLOBAL: " << *G);
422
423 if (!Ty->isSized()) continue;
424 if (!G->hasInitializer()) continue;
Kostya Serebryany7cf2a042011-11-17 23:14:59 +0000425 // Touch only those globals that will not be defined in other modules.
426 // Don't handle ODR type linkages since other modules may be built w/o asan.
Kostya Serebryany2e7fb2f2011-11-17 23:37:53 +0000427 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
428 G->getLinkage() != GlobalVariable::PrivateLinkage &&
429 G->getLinkage() != GlobalVariable::InternalLinkage)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000430 continue;
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000431 // Two problems with thread-locals:
432 // - The address of the main thread's copy can't be computed at link-time.
433 // - Need to poison all copies, not just the main thread's one.
434 if (G->isThreadLocal())
435 continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000436 // For now, just ignore this Alloca if the alignment is large.
437 if (G->getAlignment() > RedzoneSize) continue;
438
439 // Ignore all the globals with the names starting with "\01L_OBJC_".
440 // Many of those are put into the .cstring section. The linker compresses
441 // that section by removing the spare \0s after the string terminator, so
442 // our redzones get broken.
443 if ((G->getName().find("\01L_OBJC_") == 0) ||
444 (G->getName().find("\01l_OBJC_") == 0)) {
445 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
446 continue;
447 }
448
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000449 if (G->hasSection()) {
450 StringRef Section(G->getSection());
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000451 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
452 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
453 // them.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000454 if ((Section.find("__OBJC,") == 0) ||
455 (Section.find("__DATA, __objc_") == 0)) {
456 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
457 continue;
458 }
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000459 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
460 // Constant CFString instances are compiled in the following way:
461 // -- the string buffer is emitted into
462 // __TEXT,__cstring,cstring_literals
463 // -- the constant NSConstantString structure referencing that buffer
464 // is placed into __DATA,__cfstring
465 // Therefore there's no point in placing redzones into __DATA,__cfstring.
466 // Moreover, it causes the linker to crash on OS X 10.7
467 if (Section.find("__DATA,__cfstring") == 0) {
468 DEBUG(dbgs() << "Ignoring CFString: " << *G);
469 continue;
470 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000471 }
472
473 GlobalsToChange.push_back(G);
474 }
475
476 size_t n = GlobalsToChange.size();
477 if (n == 0) return false;
478
479 // A global is described by a structure
480 // size_t beg;
481 // size_t size;
482 // size_t size_with_redzone;
483 // const char *name;
484 // We initialize an array of such structures and pass it to a run-time call.
485 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
486 IntptrTy, IntptrTy, NULL);
487 SmallVector<Constant *, 16> Initializers(n);
488
489 IRBuilder<> IRB(CtorInsertBefore);
490
491 for (size_t i = 0; i < n; i++) {
492 GlobalVariable *G = GlobalsToChange[i];
493 PointerType *PtrTy = cast<PointerType>(G->getType());
494 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000495 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000496 uint64_t RightRedzoneSize = RedzoneSize +
497 (RedzoneSize - (SizeInBytes % RedzoneSize));
498 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
499
500 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
501 Constant *NewInitializer = ConstantStruct::get(
502 NewTy, G->getInitializer(),
503 Constant::getNullValue(RightRedZoneTy), NULL);
504
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000505 SmallString<2048> DescriptionOfGlobal = G->getName();
506 DescriptionOfGlobal += " (";
507 DescriptionOfGlobal += M.getModuleIdentifier();
508 DescriptionOfGlobal += ")";
509 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000510
511 // Create a new global variable with enough space for a redzone.
512 GlobalVariable *NewGlobal = new GlobalVariable(
513 M, NewTy, G->isConstant(), G->getLinkage(),
514 NewInitializer, "", G, G->isThreadLocal());
515 NewGlobal->copyAttributesFrom(G);
516 NewGlobal->setAlignment(RedzoneSize);
517
518 Value *Indices2[2];
519 Indices2[0] = IRB.getInt32(0);
520 Indices2[1] = IRB.getInt32(0);
521
522 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000523 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000524 NewGlobal->takeName(G);
525 G->eraseFromParent();
526
527 Initializers[i] = ConstantStruct::get(
528 GlobalStructTy,
529 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
530 ConstantInt::get(IntptrTy, SizeInBytes),
531 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
532 ConstantExpr::getPointerCast(Name, IntptrTy),
533 NULL);
534 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
535 }
536
537 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
538 GlobalVariable *AllGlobals = new GlobalVariable(
539 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
540 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
541
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000542 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000543 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
544 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
545
546 IRB.CreateCall2(AsanRegisterGlobals,
547 IRB.CreatePointerCast(AllGlobals, IntptrTy),
548 ConstantInt::get(IntptrTy, n));
549
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000550 // We also need to unregister globals at the end, e.g. when a shared library
551 // gets closed.
552 Function *AsanDtorFunction = Function::Create(
553 FunctionType::get(Type::getVoidTy(*C), false),
554 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
555 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
556 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000557 Function *AsanUnregisterGlobals =
558 checkInterfaceFunction(M.getOrInsertFunction(
559 kAsanUnregisterGlobalsName,
560 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000561 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
562
563 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
564 IRB.CreatePointerCast(AllGlobals, IntptrTy),
565 ConstantInt::get(IntptrTy, n));
566 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
567
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000568 DEBUG(dbgs() << M);
569 return true;
570}
571
572// virtual
573bool AddressSanitizer::runOnModule(Module &M) {
574 // Initialize the private fields. No one has accessed them before.
575 TD = getAnalysisIfAvailable<TargetData>();
576 if (!TD)
577 return false;
Kostya Serebryanya1c45042012-03-14 23:22:10 +0000578 BL.reset(new FunctionBlackList(ClBlackListFile));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000579
580 CurrentModule = &M;
581 C = &(M.getContext());
582 LongSize = TD->getPointerSizeInBits();
583 IntptrTy = Type::getIntNTy(*C, LongSize);
584 IntptrPtrTy = PointerType::get(IntptrTy, 0);
585
586 AsanCtorFunction = Function::Create(
587 FunctionType::get(Type::getVoidTy(*C), false),
588 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
589 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
590 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
591
592 // call __asan_init in the module ctor.
593 IRBuilder<> IRB(CtorInsertBefore);
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000594 AsanInitFunction = checkInterfaceFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000595 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
596 AsanInitFunction->setLinkage(Function::ExternalLinkage);
597 IRB.CreateCall(AsanInitFunction);
598
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000599 llvm::Triple targetTriple(M.getTargetTriple());
600 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
601
602 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
603 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000604 if (ClMappingOffsetLog >= 0) {
605 if (ClMappingOffsetLog == 0) {
606 // special case
607 MappingOffset = 0;
608 } else {
609 MappingOffset = 1ULL << ClMappingOffsetLog;
610 }
611 }
612 MappingScale = kDefaultShadowScale;
613 if (ClMappingScale) {
614 MappingScale = ClMappingScale;
615 }
616 // Redzone used for stack and globals is at least 32 bytes.
617 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
618 RedzoneSize = std::max(32, (int)(1 << MappingScale));
619
620 bool Res = false;
621
622 if (ClGlobals)
623 Res |= insertGlobalRedzones(M);
624
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000625 if (ClMappingOffsetLog >= 0) {
626 // Tell the run-time the current values of mapping offset and scale.
627 GlobalValue *asan_mapping_offset =
628 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
629 ConstantInt::get(IntptrTy, MappingOffset),
630 kAsanMappingOffsetName);
631 // Read the global, otherwise it may be optimized away.
632 IRB.CreateLoad(asan_mapping_offset, true);
633 }
634 if (ClMappingScale) {
635 GlobalValue *asan_mapping_scale =
636 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
637 ConstantInt::get(IntptrTy, MappingScale),
638 kAsanMappingScaleName);
639 // Read the global, otherwise it may be optimized away.
640 IRB.CreateLoad(asan_mapping_scale, true);
641 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000642
643
644 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
645 if (F->isDeclaration()) continue;
646 Res |= handleFunction(M, *F);
647 }
648
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000649 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000650
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000651 return Res;
652}
653
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000654bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
655 // For each NSObject descendant having a +load method, this method is invoked
656 // by the ObjC runtime before any of the static constructors is called.
657 // Therefore we need to instrument such methods with a call to __asan_init
658 // at the beginning in order to initialize our runtime before any access to
659 // the shadow memory.
660 // We cannot just ignore these methods, because they may call other
661 // instrumented functions.
662 if (F.getName().find(" load]") != std::string::npos) {
663 IRBuilder<> IRB(F.begin()->begin());
664 IRB.CreateCall(AsanInitFunction);
665 return true;
666 }
667 return false;
668}
669
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000670bool AddressSanitizer::handleFunction(Module &M, Function &F) {
671 if (BL->isIn(F)) return false;
672 if (&F == AsanCtorFunction) return false;
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000673
674 // If needed, insert __asan_init before checking for AddressSafety attr.
675 maybeInsertAsanInitAtFunctionEntry(F);
676
Kostya Serebryany0307b9a2012-01-24 19:34:43 +0000677 if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000678
679 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
680 return false;
681 // We want to instrument every address only once per basic block
682 // (unless there are calls between uses).
683 SmallSet<Value*, 16> TempsToInstrument;
684 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000685 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000686 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000687
688 // Fill the set of memory operations to instrument.
689 for (Function::iterator FI = F.begin(), FE = F.end();
690 FI != FE; ++FI) {
691 TempsToInstrument.clear();
692 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
693 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000694 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000695 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000696 if (ClOpt && ClOptSameTemp) {
697 if (!TempsToInstrument.insert(Addr))
698 continue; // We've seen this temp in the current BB.
699 }
700 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
701 // ok, take it.
702 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000703 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000704 // A call inside BB.
705 TempsToInstrument.clear();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000706 if (CI->doesNotReturn()) {
707 NoReturnCalls.push_back(CI);
708 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000709 }
710 continue;
711 }
712 ToInstrument.push_back(BI);
713 }
714 }
715
716 // Instrument.
717 int NumInstrumented = 0;
718 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
719 Instruction *Inst = ToInstrument[i];
720 if (ClDebugMin < 0 || ClDebugMax < 0 ||
721 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000722 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000723 instrumentMop(Inst);
724 else
725 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
726 }
727 NumInstrumented++;
728 }
729
730 DEBUG(dbgs() << F);
731
732 bool ChangedStack = poisonStackInFunction(M, F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000733
734 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
735 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
736 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
737 Instruction *CI = NoReturnCalls[i];
738 IRBuilder<> IRB(CI);
739 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
740 IRB.getVoidTy(), NULL));
741 }
742
743 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000744}
745
746static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
747 if (ShadowRedzoneSize == 1) return PoisonByte;
748 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
749 if (ShadowRedzoneSize == 4)
750 return (PoisonByte << 24) + (PoisonByte << 16) +
751 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000752 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000753}
754
755static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
756 size_t Size,
757 size_t RedzoneSize,
758 size_t ShadowGranularity,
759 uint8_t Magic) {
760 for (size_t i = 0; i < RedzoneSize;
761 i+= ShadowGranularity, Shadow++) {
762 if (i + ShadowGranularity <= Size) {
763 *Shadow = 0; // fully addressable
764 } else if (i >= Size) {
765 *Shadow = Magic; // unaddressable
766 } else {
767 *Shadow = Size - i; // first Size-i bytes are addressable
768 }
769 }
770}
771
772void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
773 IRBuilder<> IRB,
774 Value *ShadowBase, bool DoPoison) {
775 size_t ShadowRZSize = RedzoneSize >> MappingScale;
776 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
777 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
778 Type *RZPtrTy = PointerType::get(RZTy, 0);
779
780 Value *PoisonLeft = ConstantInt::get(RZTy,
781 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
782 Value *PoisonMid = ConstantInt::get(RZTy,
783 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
784 Value *PoisonRight = ConstantInt::get(RZTy,
785 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
786
787 // poison the first red zone.
788 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
789
790 // poison all other red zones.
791 uint64_t Pos = RedzoneSize;
792 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
793 AllocaInst *AI = AllocaVec[i];
794 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
795 uint64_t AlignedSize = getAlignedAllocaSize(AI);
796 assert(AlignedSize - SizeInBytes < RedzoneSize);
797 Value *Ptr = NULL;
798
799 Pos += AlignedSize;
800
801 assert(ShadowBase->getType() == IntptrTy);
802 if (SizeInBytes < AlignedSize) {
803 // Poison the partial redzone at right
804 Ptr = IRB.CreateAdd(
805 ShadowBase, ConstantInt::get(IntptrTy,
806 (Pos >> MappingScale) - ShadowRZSize));
807 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
808 uint32_t Poison = 0;
809 if (DoPoison) {
810 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
811 RedzoneSize,
812 1ULL << MappingScale,
813 kAsanStackPartialRedzoneMagic);
814 }
815 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
816 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
817 }
818
819 // Poison the full redzone at right.
820 Ptr = IRB.CreateAdd(ShadowBase,
821 ConstantInt::get(IntptrTy, Pos >> MappingScale));
822 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
823 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
824
825 Pos += RedzoneSize;
826 }
827}
828
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000829// Workaround for bug 11395: we don't want to instrument stack in functions
830// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000831// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000832bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
833 if (LongSize != 32) return false;
834 CallInst *CI = dyn_cast<CallInst>(I);
835 if (!CI || !CI->isInlineAsm()) return false;
836 if (CI->getNumArgOperands() <= 5) return false;
837 // We have inline assembly with quite a few arguments.
838 return true;
839}
840
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000841// Find all static Alloca instructions and put
842// poisoned red zones around all of them.
843// Then unpoison everything back before the function returns.
844//
845// Stack poisoning does not play well with exception handling.
846// When an exception is thrown, we essentially bypass the code
847// that unpoisones the stack. This is why the run-time library has
848// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
849// stack in the interceptor. This however does not work inside the
850// actual function which catches the exception. Most likely because the
851// compiler hoists the load of the shadow value somewhere too high.
852// This causes asan to report a non-existing bug on 453.povray.
853// It sounds like an LLVM bug.
854bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
855 if (!ClStack) return false;
856 SmallVector<AllocaInst*, 16> AllocaVec;
857 SmallVector<Instruction*, 8> RetVec;
858 uint64_t TotalSize = 0;
859
860 // Filter out Alloca instructions we want (and can) handle.
861 // Collect Ret instructions.
862 for (Function::iterator FI = F.begin(), FE = F.end();
863 FI != FE; ++FI) {
864 BasicBlock &BB = *FI;
865 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
866 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000867 if (isa<ReturnInst>(BI)) {
868 RetVec.push_back(BI);
869 continue;
870 }
871
872 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
873 if (!AI) continue;
874 if (AI->isArrayAllocation()) continue;
875 if (!AI->isStaticAlloca()) continue;
876 if (!AI->getAllocatedType()->isSized()) continue;
877 if (AI->getAlignment() > RedzoneSize) continue;
878 AllocaVec.push_back(AI);
879 uint64_t AlignedSize = getAlignedAllocaSize(AI);
880 TotalSize += AlignedSize;
881 }
882 }
883
884 if (AllocaVec.empty()) return false;
885
886 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
887
888 bool DoStackMalloc = ClUseAfterReturn
889 && LocalStackSize <= kMaxStackMallocSize;
890
891 Instruction *InsBefore = AllocaVec[0];
892 IRBuilder<> IRB(InsBefore);
893
894
895 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
896 AllocaInst *MyAlloca =
897 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
898 MyAlloca->setAlignment(RedzoneSize);
899 assert(MyAlloca->isStaticAlloca());
900 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
901 Value *LocalStackBase = OrigStackBase;
902
903 if (DoStackMalloc) {
904 Value *AsanStackMallocFunc = M.getOrInsertFunction(
905 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
906 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
907 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
908 }
909
910 // This string will be parsed by the run-time (DescribeStackAddress).
911 SmallString<2048> StackDescriptionStorage;
912 raw_svector_ostream StackDescription(StackDescriptionStorage);
913 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
914
915 uint64_t Pos = RedzoneSize;
916 // Replace Alloca instructions with base+offset.
917 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
918 AllocaInst *AI = AllocaVec[i];
919 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
920 StringRef Name = AI->getName();
921 StackDescription << Pos << " " << SizeInBytes << " "
922 << Name.size() << " " << Name << " ";
923 uint64_t AlignedSize = getAlignedAllocaSize(AI);
924 assert((AlignedSize % RedzoneSize) == 0);
925 AI->replaceAllUsesWith(
926 IRB.CreateIntToPtr(
927 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
928 AI->getType()));
929 Pos += AlignedSize + RedzoneSize;
930 }
931 assert(Pos == LocalStackSize);
932
933 // Write the Magic value and the frame description constant to the redzone.
934 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
935 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
936 BasePlus0);
937 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
938 ConstantInt::get(IntptrTy, LongSize/8));
939 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
940 Value *Description = IRB.CreatePointerCast(
941 createPrivateGlobalForString(M, StackDescription.str()),
942 IntptrTy);
943 IRB.CreateStore(Description, BasePlus1);
944
945 // Poison the stack redzones at the entry.
946 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
947 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
948
949 Value *AsanStackFreeFunc = NULL;
950 if (DoStackMalloc) {
951 AsanStackFreeFunc = M.getOrInsertFunction(
952 kAsanStackFreeName, IRB.getVoidTy(),
953 IntptrTy, IntptrTy, IntptrTy, NULL);
954 }
955
956 // Unpoison the stack before all ret instructions.
957 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
958 Instruction *Ret = RetVec[i];
959 IRBuilder<> IRBRet(Ret);
960
961 // Mark the current frame as retired.
962 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
963 BasePlus0);
964 // Unpoison the stack.
965 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
966
967 if (DoStackMalloc) {
968 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
969 ConstantInt::get(IntptrTy, LocalStackSize),
970 OrigStackBase);
971 }
972 }
973
974 if (ClDebugStack) {
975 DEBUG(dbgs() << F);
976 }
977
978 return true;
979}