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