[asan] more code to merge crash callbacks. Doesn't fully work yet, but allows to...
[oota-llvm.git] / lib / Transforms / Instrumentation / AddressSanitizer.cpp
1 //===-- 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
18 #include "FunctionBlackList.h"
19 #include "llvm/Function.h"
20 #include "llvm/IRBuilder.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/Type.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/OwningPtr.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/DataTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Support/system_error.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Transforms/Instrumentation.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/ModuleUtils.h"
42
43 #include <string>
44 #include <algorithm>
45
46 using namespace llvm;
47
48 static const uint64_t kDefaultShadowScale = 3;
49 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
50 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
51 static const uint64_t kDefaultShadowOffsetAndroid = 0;
52
53 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
54 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
55 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
56
57 static const char *kAsanModuleCtorName = "asan.module_ctor";
58 static const char *kAsanModuleDtorName = "asan.module_dtor";
59 static const int   kAsanCtorAndCtorPriority = 1;
60 static const char *kAsanReportErrorTemplate = "__asan_report_";
61 static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
62 static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
63 static const char *kAsanInitName = "__asan_init";
64 static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
65 static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
66 static const char *kAsanMappingScaleName = "__asan_mapping_scale";
67 static const char *kAsanStackMallocName = "__asan_stack_malloc";
68 static const char *kAsanStackFreeName = "__asan_stack_free";
69
70 static const int kAsanStackLeftRedzoneMagic = 0xf1;
71 static const int kAsanStackMidRedzoneMagic = 0xf2;
72 static const int kAsanStackRightRedzoneMagic = 0xf3;
73 static const int kAsanStackPartialRedzoneMagic = 0xf4;
74
75 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
76 static const size_t kNumberOfAccessSizes = 5;
77
78 // Command-line flags.
79
80 // This flag may need to be replaced with -f[no-]asan-reads.
81 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
82        cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
83 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
84        cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
85 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
86        cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
87        cl::Hidden, cl::init(true));
88 static cl::opt<bool> ClMergeCallbacks("asan-merge-callbacks",
89        cl::desc("merge __asan_report_ callbacks to create fewer BBs"),
90        cl::Hidden, cl::init(false));
91 // This flag limits the number of instructions to be instrumented
92 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
93 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
94 // set it to 10000.
95 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
96        cl::init(10000),
97        cl::desc("maximal number of instructions to instrument in any given BB"),
98        cl::Hidden);
99 // This flag may need to be replaced with -f[no]asan-stack.
100 static cl::opt<bool> ClStack("asan-stack",
101        cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
102 // This flag may need to be replaced with -f[no]asan-use-after-return.
103 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
104        cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
105 // This flag may need to be replaced with -f[no]asan-globals.
106 static cl::opt<bool> ClGlobals("asan-globals",
107        cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
108 static cl::opt<bool> ClMemIntrin("asan-memintrin",
109        cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
110 // This flag may need to be replaced with -fasan-blacklist.
111 static cl::opt<std::string>  ClBlackListFile("asan-blacklist",
112        cl::desc("File containing the list of functions to ignore "
113                 "during instrumentation"), cl::Hidden);
114
115 // These flags allow to change the shadow mapping.
116 // The shadow mapping looks like
117 //    Shadow = (Mem >> scale) + (1 << offset_log)
118 static cl::opt<int> ClMappingScale("asan-mapping-scale",
119        cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
120 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
121        cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
122
123 // Optimization flags. Not user visible, used mostly for testing
124 // and benchmarking the tool.
125 static cl::opt<bool> ClOpt("asan-opt",
126        cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
127 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
128        cl::desc("Instrument the same temp just once"), cl::Hidden,
129        cl::init(true));
130 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
131        cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
132
133 // Debug flags.
134 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
135                             cl::init(0));
136 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
137                                  cl::Hidden, cl::init(0));
138 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
139                                         cl::Hidden, cl::desc("Debug func"));
140 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
141                                cl::Hidden, cl::init(-1));
142 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
143                                cl::Hidden, cl::init(-1));
144
145 namespace {
146
147 /// When the crash callbacks are merged, they receive some amount of arguments
148 /// that are merged in a PHI node. This struct represents arguments from one
149 /// call site.
150 struct CrashArg {
151   Value *Arg1;
152   Value *Arg2;
153 };
154
155 /// An object of this type is created while instrumenting every function.
156 struct AsanFunctionContext {
157   AsanFunctionContext(Function &Function) : F(Function), CrashBlock() { }
158
159   Function &F;
160   // These are initially zero. If we require at least one call to
161   // __asan_report_{read,write}{1,2,4,8,16}, an appropriate BB is created.
162   BasicBlock *CrashBlock[2][kNumberOfAccessSizes];
163   typedef  SmallVector<CrashArg, 8> CrashArgsVec;
164   CrashArgsVec CrashArgs[2][kNumberOfAccessSizes];
165 };
166
167 /// AddressSanitizer: instrument the code in module to find memory bugs.
168 struct AddressSanitizer : public ModulePass {
169   AddressSanitizer();
170   virtual const char *getPassName() const;
171   void instrumentMop(AsanFunctionContext &AFC, Instruction *I);
172   void instrumentAddress(AsanFunctionContext &AFC,
173                          Instruction *OrigIns, IRBuilder<> &IRB,
174                          Value *Addr, uint32_t TypeSize, bool IsWrite);
175   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
176                            Value *ShadowValue, uint32_t TypeSize);
177   Instruction *generateCrashCode(BasicBlock *BB, Value *Addr, Value *PC,
178                                  bool IsWrite, size_t AccessSizeIndex);
179   bool instrumentMemIntrinsic(AsanFunctionContext &AFC, MemIntrinsic *MI);
180   void instrumentMemIntrinsicParam(AsanFunctionContext &AFC,
181                                    Instruction *OrigIns, Value *Addr,
182                                    Value *Size,
183                                    Instruction *InsertBefore, bool IsWrite);
184   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
185   bool handleFunction(Module &M, Function &F);
186   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
187   bool poisonStackInFunction(Module &M, Function &F);
188   virtual bool runOnModule(Module &M);
189   bool insertGlobalRedzones(Module &M);
190   static char ID;  // Pass identification, replacement for typeid
191
192  private:
193
194   uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
195     Type *Ty = AI->getAllocatedType();
196     uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
197     return SizeInBytes;
198   }
199   uint64_t getAlignedSize(uint64_t SizeInBytes) {
200     return ((SizeInBytes + RedzoneSize - 1)
201             / RedzoneSize) * RedzoneSize;
202   }
203   uint64_t getAlignedAllocaSize(AllocaInst *AI) {
204     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
205     return getAlignedSize(SizeInBytes);
206   }
207
208   Function *checkInterfaceFunction(Constant *FuncOrBitcast);
209   void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
210                    Value *ShadowBase, bool DoPoison);
211   bool LooksLikeCodeInBug11395(Instruction *I);
212
213   LLVMContext *C;
214   TargetData *TD;
215   uint64_t MappingOffset;
216   int MappingScale;
217   size_t RedzoneSize;
218   int LongSize;
219   Type *IntptrTy;
220   Type *IntptrPtrTy;
221   Function *AsanCtorFunction;
222   Function *AsanInitFunction;
223   Instruction *CtorInsertBefore;
224   OwningPtr<FunctionBlackList> BL;
225   // This array is indexed by AccessIsWrite and log2(AccessSize).
226   Function *AsanErrorCallback[2][kNumberOfAccessSizes];
227 };
228
229 }  // namespace
230
231 char AddressSanitizer::ID = 0;
232 INITIALIZE_PASS(AddressSanitizer, "asan",
233     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
234     false, false)
235 AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
236 ModulePass *llvm::createAddressSanitizerPass() {
237   return new AddressSanitizer();
238 }
239
240 const char *AddressSanitizer::getPassName() const {
241   return "AddressSanitizer";
242 }
243
244 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
245   size_t Res = CountTrailingZeros_32(TypeSize / 8);
246   assert(Res < kNumberOfAccessSizes);
247   return Res;
248 }
249
250 // Create a constant for Str so that we can pass it to the run-time lib.
251 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
252   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
253   return new GlobalVariable(M, StrConst->getType(), true,
254                             GlobalValue::PrivateLinkage, StrConst, "");
255 }
256
257 // Split the basic block and insert an if-then code.
258 // Before:
259 //   Head
260 //   Cmp
261 //   Tail
262 // After:
263 //   Head
264 //   if (Cmp)
265 //     ThenBlock
266 //   Tail
267 //
268 // If ThenBlock is zero, a new block is created and its terminator is returned.
269 // Otherwize 0 is returned.
270 static BranchInst *splitBlockAndInsertIfThen(Value *Cmp,
271                                              BasicBlock *ThenBlock = 0) {
272   Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode();
273   BasicBlock *Head = SplitBefore->getParent();
274   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
275   TerminatorInst *HeadOldTerm = Head->getTerminator();
276   BranchInst *CheckTerm = 0;
277   if (!ThenBlock) {
278     LLVMContext &C = Head->getParent()->getParent()->getContext();
279     ThenBlock = BasicBlock::Create(C, "", Head->getParent());
280     CheckTerm = BranchInst::Create(Tail, ThenBlock);
281   }
282   BranchInst *HeadNewTerm =
283     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
284   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
285
286   return CheckTerm;
287 }
288
289 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
290   // Shadow >> scale
291   Shadow = IRB.CreateLShr(Shadow, MappingScale);
292   if (MappingOffset == 0)
293     return Shadow;
294   // (Shadow >> scale) | offset
295   return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
296                                                MappingOffset));
297 }
298
299 void AddressSanitizer::instrumentMemIntrinsicParam(
300     AsanFunctionContext &AFC, Instruction *OrigIns,
301     Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
302   // Check the first byte.
303   {
304     IRBuilder<> IRB(InsertBefore);
305     instrumentAddress(AFC, OrigIns, IRB, Addr, 8, IsWrite);
306   }
307   // Check the last byte.
308   {
309     IRBuilder<> IRB(InsertBefore);
310     Value *SizeMinusOne = IRB.CreateSub(
311         Size, ConstantInt::get(Size->getType(), 1));
312     SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
313     Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
314     Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
315     instrumentAddress(AFC, OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
316   }
317 }
318
319 // Instrument memset/memmove/memcpy
320 bool AddressSanitizer::instrumentMemIntrinsic(AsanFunctionContext &AFC,
321                                               MemIntrinsic *MI) {
322   Value *Dst = MI->getDest();
323   MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
324   Value *Src = MemTran ? MemTran->getSource() : 0;
325   Value *Length = MI->getLength();
326
327   Constant *ConstLength = dyn_cast<Constant>(Length);
328   Instruction *InsertBefore = MI;
329   if (ConstLength) {
330     if (ConstLength->isNullValue()) return false;
331   } else {
332     // The size is not a constant so it could be zero -- check at run-time.
333     IRBuilder<> IRB(InsertBefore);
334
335     Value *Cmp = IRB.CreateICmpNE(Length,
336                                   Constant::getNullValue(Length->getType()));
337     InsertBefore = splitBlockAndInsertIfThen(Cmp);
338   }
339
340   instrumentMemIntrinsicParam(AFC, MI, Dst, Length, InsertBefore, true);
341   if (Src)
342     instrumentMemIntrinsicParam(AFC, MI, Src, Length, InsertBefore, false);
343   return true;
344 }
345
346 // If I is an interesting memory access, return the PointerOperand
347 // and set IsWrite. Otherwise return NULL.
348 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
349   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
350     if (!ClInstrumentReads) return NULL;
351     *IsWrite = false;
352     return LI->getPointerOperand();
353   }
354   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
355     if (!ClInstrumentWrites) return NULL;
356     *IsWrite = true;
357     return SI->getPointerOperand();
358   }
359   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
360     if (!ClInstrumentAtomics) return NULL;
361     *IsWrite = true;
362     return RMW->getPointerOperand();
363   }
364   if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
365     if (!ClInstrumentAtomics) return NULL;
366     *IsWrite = true;
367     return XCHG->getPointerOperand();
368   }
369   return NULL;
370 }
371
372 void AddressSanitizer::instrumentMop(AsanFunctionContext &AFC, Instruction *I) {
373   bool IsWrite;
374   Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
375   assert(Addr);
376   if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
377     // We are accessing a global scalar variable. Nothing to catch here.
378     return;
379   }
380   Type *OrigPtrTy = Addr->getType();
381   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
382
383   assert(OrigTy->isSized());
384   uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
385
386   if (TypeSize != 8  && TypeSize != 16 &&
387       TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
388     // Ignore all unusual sizes.
389     return;
390   }
391
392   IRBuilder<> IRB(I);
393   instrumentAddress(AFC, I, IRB, Addr, TypeSize, IsWrite);
394 }
395
396 // Validate the result of Module::getOrInsertFunction called for an interface
397 // function of AddressSanitizer. If the instrumented module defines a function
398 // with the same name, their prototypes must match, otherwise
399 // getOrInsertFunction returns a bitcast.
400 Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
401   if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
402   FuncOrBitcast->dump();
403   report_fatal_error("trying to redefine an AddressSanitizer "
404                      "interface function");
405 }
406
407 Instruction *AddressSanitizer::generateCrashCode(
408     BasicBlock *BB, Value *Addr, Value *PC,
409     bool IsWrite, size_t AccessSizeIndex) {
410   IRBuilder<> IRB(BB->getFirstNonPHI());
411   CallInst *Call;
412   if (PC)
413     Call = IRB.CreateCall2(AsanErrorCallback[IsWrite][AccessSizeIndex],
414                            Addr, PC);
415   else
416     Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
417   Call->setDoesNotReturn();
418   return Call;
419 }
420
421 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
422                                             Value *ShadowValue,
423                                             uint32_t TypeSize) {
424   size_t Granularity = 1 << MappingScale;
425   // Addr & (Granularity - 1)
426   Value *LastAccessedByte = IRB.CreateAnd(
427       AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
428   // (Addr & (Granularity - 1)) + size - 1
429   if (TypeSize / 8 > 1)
430     LastAccessedByte = IRB.CreateAdd(
431         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
432   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
433   LastAccessedByte = IRB.CreateIntCast(
434       LastAccessedByte, IRB.getInt8Ty(), false);
435   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
436   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
437 }
438
439 void AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
440                                          Instruction *OrigIns,
441                                          IRBuilder<> &IRB, Value *Addr,
442                                          uint32_t TypeSize, bool IsWrite) {
443   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
444
445   Type *ShadowTy  = IntegerType::get(
446       *C, std::max(8U, TypeSize >> MappingScale));
447   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
448   Value *ShadowPtr = memToShadow(AddrLong, IRB);
449   Value *CmpVal = Constant::getNullValue(ShadowTy);
450   Value *ShadowValue = IRB.CreateLoad(
451       IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
452
453   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
454
455   BasicBlock *CrashBlock = 0;
456   if (ClMergeCallbacks) {
457     size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
458     BasicBlock **Cached = &AFC.CrashBlock[IsWrite][AccessSizeIndex];
459     if (!*Cached) {
460       std::string BBName("crash_bb-");
461       BBName += (IsWrite ? "w-" : "r-") + itostr(1 << AccessSizeIndex);
462       BasicBlock *BB = BasicBlock::Create(*C, BBName, &AFC.F);
463       new UnreachableInst(*C, BB);
464       *Cached = BB;
465     }
466     CrashBlock = *Cached;
467     // We need to pass the PC as the second parameter to __asan_report_*.
468     // There are few problems:
469     //  - Some architectures (e.g. x86_32) don't have a cheap way to get the PC.
470     //  - LLVM doesn't have the appropriate intrinsic.
471     // For now, put a random number into the PC, just to allow experiments.
472     Value *PC = ConstantInt::get(IntptrTy, rand());
473     CrashArg Arg = {AddrLong, PC};
474     AFC.CrashArgs[IsWrite][AccessSizeIndex].push_back(Arg);
475   } else {
476     CrashBlock = BasicBlock::Create(*C, "crash_bb", &AFC.F);
477     new UnreachableInst(*C, CrashBlock);
478     size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
479     Instruction *Crash =
480         generateCrashCode(CrashBlock, AddrLong, 0, IsWrite, AccessSizeIndex);
481     Crash->setDebugLoc(OrigIns->getDebugLoc());
482   }
483
484   size_t Granularity = 1 << MappingScale;
485   if (TypeSize < 8 * Granularity) {
486     Instruction *CheckTerm = splitBlockAndInsertIfThen(Cmp);
487     IRB.SetInsertPoint(CheckTerm);
488     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
489     splitBlockAndInsertIfThen(Cmp2, CrashBlock);
490   } else {
491     splitBlockAndInsertIfThen(Cmp, CrashBlock);
492   }
493 }
494
495 // This function replaces all global variables with new variables that have
496 // trailing redzones. It also creates a function that poisons
497 // redzones and inserts this function into llvm.global_ctors.
498 bool AddressSanitizer::insertGlobalRedzones(Module &M) {
499   SmallVector<GlobalVariable *, 16> GlobalsToChange;
500
501   for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
502        E = M.getGlobalList().end(); G != E; ++G) {
503     Type *Ty = cast<PointerType>(G->getType())->getElementType();
504     DEBUG(dbgs() << "GLOBAL: " << *G);
505
506     if (!Ty->isSized()) continue;
507     if (!G->hasInitializer()) continue;
508     // Touch only those globals that will not be defined in other modules.
509     // Don't handle ODR type linkages since other modules may be built w/o asan.
510     if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
511         G->getLinkage() != GlobalVariable::PrivateLinkage &&
512         G->getLinkage() != GlobalVariable::InternalLinkage)
513       continue;
514     // Two problems with thread-locals:
515     //   - The address of the main thread's copy can't be computed at link-time.
516     //   - Need to poison all copies, not just the main thread's one.
517     if (G->isThreadLocal())
518       continue;
519     // For now, just ignore this Alloca if the alignment is large.
520     if (G->getAlignment() > RedzoneSize) continue;
521
522     // Ignore all the globals with the names starting with "\01L_OBJC_".
523     // Many of those are put into the .cstring section. The linker compresses
524     // that section by removing the spare \0s after the string terminator, so
525     // our redzones get broken.
526     if ((G->getName().find("\01L_OBJC_") == 0) ||
527         (G->getName().find("\01l_OBJC_") == 0)) {
528       DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
529       continue;
530     }
531
532     if (G->hasSection()) {
533       StringRef Section(G->getSection());
534       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
535       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
536       // them.
537       if ((Section.find("__OBJC,") == 0) ||
538           (Section.find("__DATA, __objc_") == 0)) {
539         DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
540         continue;
541       }
542       // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
543       // Constant CFString instances are compiled in the following way:
544       //  -- the string buffer is emitted into
545       //     __TEXT,__cstring,cstring_literals
546       //  -- the constant NSConstantString structure referencing that buffer
547       //     is placed into __DATA,__cfstring
548       // Therefore there's no point in placing redzones into __DATA,__cfstring.
549       // Moreover, it causes the linker to crash on OS X 10.7
550       if (Section.find("__DATA,__cfstring") == 0) {
551         DEBUG(dbgs() << "Ignoring CFString: " << *G);
552         continue;
553       }
554     }
555
556     GlobalsToChange.push_back(G);
557   }
558
559   size_t n = GlobalsToChange.size();
560   if (n == 0) return false;
561
562   // A global is described by a structure
563   //   size_t beg;
564   //   size_t size;
565   //   size_t size_with_redzone;
566   //   const char *name;
567   // We initialize an array of such structures and pass it to a run-time call.
568   StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
569                                                IntptrTy, IntptrTy, NULL);
570   SmallVector<Constant *, 16> Initializers(n);
571
572   IRBuilder<> IRB(CtorInsertBefore);
573
574   for (size_t i = 0; i < n; i++) {
575     GlobalVariable *G = GlobalsToChange[i];
576     PointerType *PtrTy = cast<PointerType>(G->getType());
577     Type *Ty = PtrTy->getElementType();
578     uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
579     uint64_t RightRedzoneSize = RedzoneSize +
580         (RedzoneSize - (SizeInBytes % RedzoneSize));
581     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
582
583     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
584     Constant *NewInitializer = ConstantStruct::get(
585         NewTy, G->getInitializer(),
586         Constant::getNullValue(RightRedZoneTy), NULL);
587
588     SmallString<2048> DescriptionOfGlobal = G->getName();
589     DescriptionOfGlobal += " (";
590     DescriptionOfGlobal += M.getModuleIdentifier();
591     DescriptionOfGlobal += ")";
592     GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
593
594     // Create a new global variable with enough space for a redzone.
595     GlobalVariable *NewGlobal = new GlobalVariable(
596         M, NewTy, G->isConstant(), G->getLinkage(),
597         NewInitializer, "", G, G->getThreadLocalMode());
598     NewGlobal->copyAttributesFrom(G);
599     NewGlobal->setAlignment(RedzoneSize);
600
601     Value *Indices2[2];
602     Indices2[0] = IRB.getInt32(0);
603     Indices2[1] = IRB.getInt32(0);
604
605     G->replaceAllUsesWith(
606         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
607     NewGlobal->takeName(G);
608     G->eraseFromParent();
609
610     Initializers[i] = ConstantStruct::get(
611         GlobalStructTy,
612         ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
613         ConstantInt::get(IntptrTy, SizeInBytes),
614         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
615         ConstantExpr::getPointerCast(Name, IntptrTy),
616         NULL);
617     DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
618   }
619
620   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
621   GlobalVariable *AllGlobals = new GlobalVariable(
622       M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
623       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
624
625   Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
626       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
627   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
628
629   IRB.CreateCall2(AsanRegisterGlobals,
630                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
631                   ConstantInt::get(IntptrTy, n));
632
633   // We also need to unregister globals at the end, e.g. when a shared library
634   // gets closed.
635   Function *AsanDtorFunction = Function::Create(
636       FunctionType::get(Type::getVoidTy(*C), false),
637       GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
638   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
639   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
640   Function *AsanUnregisterGlobals =
641       checkInterfaceFunction(M.getOrInsertFunction(
642           kAsanUnregisterGlobalsName,
643           IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
644   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
645
646   IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
647                        IRB.CreatePointerCast(AllGlobals, IntptrTy),
648                        ConstantInt::get(IntptrTy, n));
649   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
650
651   DEBUG(dbgs() << M);
652   return true;
653 }
654
655 // virtual
656 bool AddressSanitizer::runOnModule(Module &M) {
657   // Initialize the private fields. No one has accessed them before.
658   TD = getAnalysisIfAvailable<TargetData>();
659   if (!TD)
660     return false;
661   BL.reset(new FunctionBlackList(ClBlackListFile));
662
663   C = &(M.getContext());
664   LongSize = TD->getPointerSizeInBits();
665   IntptrTy = Type::getIntNTy(*C, LongSize);
666   IntptrPtrTy = PointerType::get(IntptrTy, 0);
667
668   AsanCtorFunction = Function::Create(
669       FunctionType::get(Type::getVoidTy(*C), false),
670       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
671   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
672   CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
673
674   // call __asan_init in the module ctor.
675   IRBuilder<> IRB(CtorInsertBefore);
676   AsanInitFunction = checkInterfaceFunction(
677       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
678   AsanInitFunction->setLinkage(Function::ExternalLinkage);
679   IRB.CreateCall(AsanInitFunction);
680
681   // Create __asan_report* callbacks.
682   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
683     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
684          AccessSizeIndex++) {
685       // IsWrite and TypeSize are encoded in the function name.
686       std::string FunctionName = std::string(kAsanReportErrorTemplate) +
687           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
688       // If we are merging crash callbacks, they have two parameters.
689       if (ClMergeCallbacks)
690         AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
691           M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy,
692                                 IntptrTy, NULL));
693       else
694         AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
695           M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
696     }
697   }
698
699   llvm::Triple targetTriple(M.getTargetTriple());
700   bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
701
702   MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
703     (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
704   if (ClMappingOffsetLog >= 0) {
705     if (ClMappingOffsetLog == 0) {
706       // special case
707       MappingOffset = 0;
708     } else {
709       MappingOffset = 1ULL << ClMappingOffsetLog;
710     }
711   }
712   MappingScale = kDefaultShadowScale;
713   if (ClMappingScale) {
714     MappingScale = ClMappingScale;
715   }
716   // Redzone used for stack and globals is at least 32 bytes.
717   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
718   RedzoneSize = std::max(32, (int)(1 << MappingScale));
719
720   bool Res = false;
721
722   if (ClGlobals)
723     Res |= insertGlobalRedzones(M);
724
725   if (ClMappingOffsetLog >= 0) {
726     // Tell the run-time the current values of mapping offset and scale.
727     GlobalValue *asan_mapping_offset =
728         new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
729                        ConstantInt::get(IntptrTy, MappingOffset),
730                        kAsanMappingOffsetName);
731     // Read the global, otherwise it may be optimized away.
732     IRB.CreateLoad(asan_mapping_offset, true);
733   }
734   if (ClMappingScale) {
735     GlobalValue *asan_mapping_scale =
736         new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
737                            ConstantInt::get(IntptrTy, MappingScale),
738                            kAsanMappingScaleName);
739     // Read the global, otherwise it may be optimized away.
740     IRB.CreateLoad(asan_mapping_scale, true);
741   }
742
743
744   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
745     if (F->isDeclaration()) continue;
746     Res |= handleFunction(M, *F);
747   }
748
749   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
750
751   return Res;
752 }
753
754 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
755   // For each NSObject descendant having a +load method, this method is invoked
756   // by the ObjC runtime before any of the static constructors is called.
757   // Therefore we need to instrument such methods with a call to __asan_init
758   // at the beginning in order to initialize our runtime before any access to
759   // the shadow memory.
760   // We cannot just ignore these methods, because they may call other
761   // instrumented functions.
762   if (F.getName().find(" load]") != std::string::npos) {
763     IRBuilder<> IRB(F.begin()->begin());
764     IRB.CreateCall(AsanInitFunction);
765     return true;
766   }
767   return false;
768 }
769
770 bool AddressSanitizer::handleFunction(Module &M, Function &F) {
771   if (BL->isIn(F)) return false;
772   if (&F == AsanCtorFunction) return false;
773
774   // If needed, insert __asan_init before checking for AddressSafety attr.
775   maybeInsertAsanInitAtFunctionEntry(F);
776
777   if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
778
779   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
780     return false;
781   // We want to instrument every address only once per basic block
782   // (unless there are calls between uses).
783   SmallSet<Value*, 16> TempsToInstrument;
784   SmallVector<Instruction*, 16> ToInstrument;
785   SmallVector<Instruction*, 8> NoReturnCalls;
786   bool IsWrite;
787
788   // Fill the set of memory operations to instrument.
789   for (Function::iterator FI = F.begin(), FE = F.end();
790        FI != FE; ++FI) {
791     TempsToInstrument.clear();
792     int NumInsnsPerBB = 0;
793     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
794          BI != BE; ++BI) {
795       if (LooksLikeCodeInBug11395(BI)) return false;
796       if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
797         if (ClOpt && ClOptSameTemp) {
798           if (!TempsToInstrument.insert(Addr))
799             continue;  // We've seen this temp in the current BB.
800         }
801       } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
802         // ok, take it.
803       } else {
804         if (CallInst *CI = dyn_cast<CallInst>(BI)) {
805           // A call inside BB.
806           TempsToInstrument.clear();
807           if (CI->doesNotReturn()) {
808             NoReturnCalls.push_back(CI);
809           }
810         }
811         continue;
812       }
813       ToInstrument.push_back(BI);
814       NumInsnsPerBB++;
815       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
816         break;
817     }
818   }
819
820   AsanFunctionContext AFC(F);
821
822   // Instrument.
823   int NumInstrumented = 0;
824   for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
825     Instruction *Inst = ToInstrument[i];
826     if (ClDebugMin < 0 || ClDebugMax < 0 ||
827         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
828       if (isInterestingMemoryAccess(Inst, &IsWrite))
829         instrumentMop(AFC, Inst);
830       else
831         instrumentMemIntrinsic(AFC, cast<MemIntrinsic>(Inst));
832     }
833     NumInstrumented++;
834   }
835
836   // Create PHI nodes and crash callbacks if we are merging crash callbacks.
837   if (NumInstrumented) {
838     for (size_t IsWrite = 0; IsWrite <= 1; IsWrite++) {
839       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
840            AccessSizeIndex++) {
841         BasicBlock *BB = AFC.CrashBlock[IsWrite][AccessSizeIndex];
842         if (!BB) continue;
843         assert(ClMergeCallbacks);
844         AsanFunctionContext::CrashArgsVec &Args =
845             AFC.CrashArgs[IsWrite][AccessSizeIndex];
846         IRBuilder<> IRB(BB->getFirstNonPHI());
847         size_t n = Args.size();
848         PHINode *PN1 = IRB.CreatePHI(IntptrTy, n);
849         PHINode *PN2 = IRB.CreatePHI(IntptrTy, n);
850         // We need to match crash parameters and the predecessors.
851         for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
852              PI != PE; ++PI) {
853           n--;
854           PN1->addIncoming(Args[n].Arg1, *PI);
855           PN2->addIncoming(Args[n].Arg2, *PI);
856         }
857         assert(n == 0);
858         generateCrashCode(BB, PN1, PN2, IsWrite, AccessSizeIndex);
859       }
860     }
861   }
862
863   DEBUG(dbgs() << F);
864
865   bool ChangedStack = poisonStackInFunction(M, F);
866
867   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
868   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
869   for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
870     Instruction *CI = NoReturnCalls[i];
871     IRBuilder<> IRB(CI);
872     IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
873                                          IRB.getVoidTy(), NULL));
874   }
875
876   return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
877 }
878
879 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
880   if (ShadowRedzoneSize == 1) return PoisonByte;
881   if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
882   if (ShadowRedzoneSize == 4)
883     return (PoisonByte << 24) + (PoisonByte << 16) +
884         (PoisonByte << 8) + (PoisonByte);
885   llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
886 }
887
888 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
889                                             size_t Size,
890                                             size_t RedzoneSize,
891                                             size_t ShadowGranularity,
892                                             uint8_t Magic) {
893   for (size_t i = 0; i < RedzoneSize;
894        i+= ShadowGranularity, Shadow++) {
895     if (i + ShadowGranularity <= Size) {
896       *Shadow = 0;  // fully addressable
897     } else if (i >= Size) {
898       *Shadow = Magic;  // unaddressable
899     } else {
900       *Shadow = Size - i;  // first Size-i bytes are addressable
901     }
902   }
903 }
904
905 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
906                                    IRBuilder<> IRB,
907                                    Value *ShadowBase, bool DoPoison) {
908   size_t ShadowRZSize = RedzoneSize >> MappingScale;
909   assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
910   Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
911   Type *RZPtrTy = PointerType::get(RZTy, 0);
912
913   Value *PoisonLeft  = ConstantInt::get(RZTy,
914     ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
915   Value *PoisonMid   = ConstantInt::get(RZTy,
916     ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
917   Value *PoisonRight = ConstantInt::get(RZTy,
918     ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
919
920   // poison the first red zone.
921   IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
922
923   // poison all other red zones.
924   uint64_t Pos = RedzoneSize;
925   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
926     AllocaInst *AI = AllocaVec[i];
927     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
928     uint64_t AlignedSize = getAlignedAllocaSize(AI);
929     assert(AlignedSize - SizeInBytes < RedzoneSize);
930     Value *Ptr = NULL;
931
932     Pos += AlignedSize;
933
934     assert(ShadowBase->getType() == IntptrTy);
935     if (SizeInBytes < AlignedSize) {
936       // Poison the partial redzone at right
937       Ptr = IRB.CreateAdd(
938           ShadowBase, ConstantInt::get(IntptrTy,
939                                        (Pos >> MappingScale) - ShadowRZSize));
940       size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
941       uint32_t Poison = 0;
942       if (DoPoison) {
943         PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
944                                         RedzoneSize,
945                                         1ULL << MappingScale,
946                                         kAsanStackPartialRedzoneMagic);
947       }
948       Value *PartialPoison = ConstantInt::get(RZTy, Poison);
949       IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
950     }
951
952     // Poison the full redzone at right.
953     Ptr = IRB.CreateAdd(ShadowBase,
954                         ConstantInt::get(IntptrTy, Pos >> MappingScale));
955     Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
956     IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
957
958     Pos += RedzoneSize;
959   }
960 }
961
962 // Workaround for bug 11395: we don't want to instrument stack in functions
963 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
964 // FIXME: remove once the bug 11395 is fixed.
965 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
966   if (LongSize != 32) return false;
967   CallInst *CI = dyn_cast<CallInst>(I);
968   if (!CI || !CI->isInlineAsm()) return false;
969   if (CI->getNumArgOperands() <= 5) return false;
970   // We have inline assembly with quite a few arguments.
971   return true;
972 }
973
974 // Find all static Alloca instructions and put
975 // poisoned red zones around all of them.
976 // Then unpoison everything back before the function returns.
977 //
978 // Stack poisoning does not play well with exception handling.
979 // When an exception is thrown, we essentially bypass the code
980 // that unpoisones the stack. This is why the run-time library has
981 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
982 // stack in the interceptor. This however does not work inside the
983 // actual function which catches the exception. Most likely because the
984 // compiler hoists the load of the shadow value somewhere too high.
985 // This causes asan to report a non-existing bug on 453.povray.
986 // It sounds like an LLVM bug.
987 bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
988   if (!ClStack) return false;
989   SmallVector<AllocaInst*, 16> AllocaVec;
990   SmallVector<Instruction*, 8> RetVec;
991   uint64_t TotalSize = 0;
992
993   // Filter out Alloca instructions we want (and can) handle.
994   // Collect Ret instructions.
995   for (Function::iterator FI = F.begin(), FE = F.end();
996        FI != FE; ++FI) {
997     BasicBlock &BB = *FI;
998     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
999          BI != BE; ++BI) {
1000       if (isa<ReturnInst>(BI)) {
1001           RetVec.push_back(BI);
1002           continue;
1003       }
1004
1005       AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1006       if (!AI) continue;
1007       if (AI->isArrayAllocation()) continue;
1008       if (!AI->isStaticAlloca()) continue;
1009       if (!AI->getAllocatedType()->isSized()) continue;
1010       if (AI->getAlignment() > RedzoneSize) continue;
1011       AllocaVec.push_back(AI);
1012       uint64_t AlignedSize =  getAlignedAllocaSize(AI);
1013       TotalSize += AlignedSize;
1014     }
1015   }
1016
1017   if (AllocaVec.empty()) return false;
1018
1019   uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
1020
1021   bool DoStackMalloc = ClUseAfterReturn
1022       && LocalStackSize <= kMaxStackMallocSize;
1023
1024   Instruction *InsBefore = AllocaVec[0];
1025   IRBuilder<> IRB(InsBefore);
1026
1027
1028   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1029   AllocaInst *MyAlloca =
1030       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1031   MyAlloca->setAlignment(RedzoneSize);
1032   assert(MyAlloca->isStaticAlloca());
1033   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1034   Value *LocalStackBase = OrigStackBase;
1035
1036   if (DoStackMalloc) {
1037     Value *AsanStackMallocFunc = M.getOrInsertFunction(
1038         kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
1039     LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1040         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1041   }
1042
1043   // This string will be parsed by the run-time (DescribeStackAddress).
1044   SmallString<2048> StackDescriptionStorage;
1045   raw_svector_ostream StackDescription(StackDescriptionStorage);
1046   StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1047
1048   uint64_t Pos = RedzoneSize;
1049   // Replace Alloca instructions with base+offset.
1050   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1051     AllocaInst *AI = AllocaVec[i];
1052     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1053     StringRef Name = AI->getName();
1054     StackDescription << Pos << " " << SizeInBytes << " "
1055                      << Name.size() << " " << Name << " ";
1056     uint64_t AlignedSize = getAlignedAllocaSize(AI);
1057     assert((AlignedSize % RedzoneSize) == 0);
1058     AI->replaceAllUsesWith(
1059         IRB.CreateIntToPtr(
1060             IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1061             AI->getType()));
1062     Pos += AlignedSize + RedzoneSize;
1063   }
1064   assert(Pos == LocalStackSize);
1065
1066   // Write the Magic value and the frame description constant to the redzone.
1067   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1068   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1069                   BasePlus0);
1070   Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1071                                    ConstantInt::get(IntptrTy, LongSize/8));
1072   BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1073   Value *Description = IRB.CreatePointerCast(
1074       createPrivateGlobalForString(M, StackDescription.str()),
1075       IntptrTy);
1076   IRB.CreateStore(Description, BasePlus1);
1077
1078   // Poison the stack redzones at the entry.
1079   Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1080   PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1081
1082   Value *AsanStackFreeFunc = NULL;
1083   if (DoStackMalloc) {
1084     AsanStackFreeFunc = M.getOrInsertFunction(
1085         kAsanStackFreeName, IRB.getVoidTy(),
1086         IntptrTy, IntptrTy, IntptrTy, NULL);
1087   }
1088
1089   // Unpoison the stack before all ret instructions.
1090   for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1091     Instruction *Ret = RetVec[i];
1092     IRBuilder<> IRBRet(Ret);
1093
1094     // Mark the current frame as retired.
1095     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1096                        BasePlus0);
1097     // Unpoison the stack.
1098     PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1099
1100     if (DoStackMalloc) {
1101       IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1102                          ConstantInt::get(IntptrTy, LocalStackSize),
1103                          OrigStackBase);
1104     }
1105   }
1106
1107   if (ClDebugStack) {
1108     DEBUG(dbgs() << F);
1109   }
1110
1111   return true;
1112 }