1234285Sdim//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2234285Sdim//
3234285Sdim//                     The LLVM Compiler Infrastructure
4234285Sdim//
5234285Sdim// This file is distributed under the University of Illinois Open Source
6234285Sdim// License. See LICENSE.TXT for details.
7234285Sdim//
8234285Sdim//===----------------------------------------------------------------------===//
9234285Sdim//
10234285Sdim// This file is a part of AddressSanitizer, an address sanity checker.
11234285Sdim// Details of the algorithm:
12234285Sdim//  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13234285Sdim//
14234285Sdim//===----------------------------------------------------------------------===//
15234285Sdim
16234285Sdim#define DEBUG_TYPE "asan"
17234285Sdim
18249423Sdim#include "llvm/Transforms/Instrumentation.h"
19234285Sdim#include "llvm/ADT/ArrayRef.h"
20249423Sdim#include "llvm/ADT/DenseMap.h"
21249423Sdim#include "llvm/ADT/DepthFirstIterator.h"
22234285Sdim#include "llvm/ADT/OwningPtr.h"
23234285Sdim#include "llvm/ADT/SmallSet.h"
24234285Sdim#include "llvm/ADT/SmallString.h"
25234285Sdim#include "llvm/ADT/SmallVector.h"
26263508Sdim#include "llvm/ADT/Statistic.h"
27234285Sdim#include "llvm/ADT/StringExtras.h"
28239462Sdim#include "llvm/ADT/Triple.h"
29249423Sdim#include "llvm/DIBuilder.h"
30249423Sdim#include "llvm/IR/DataLayout.h"
31249423Sdim#include "llvm/IR/Function.h"
32249423Sdim#include "llvm/IR/IRBuilder.h"
33249423Sdim#include "llvm/IR/InlineAsm.h"
34249423Sdim#include "llvm/IR/IntrinsicInst.h"
35249423Sdim#include "llvm/IR/LLVMContext.h"
36249423Sdim#include "llvm/IR/Module.h"
37249423Sdim#include "llvm/IR/Type.h"
38249423Sdim#include "llvm/InstVisitor.h"
39249423Sdim#include "llvm/Support/CallSite.h"
40234285Sdim#include "llvm/Support/CommandLine.h"
41234285Sdim#include "llvm/Support/DataTypes.h"
42234285Sdim#include "llvm/Support/Debug.h"
43263508Sdim#include "llvm/Support/Endian.h"
44234285Sdim#include "llvm/Support/raw_ostream.h"
45234285Sdim#include "llvm/Support/system_error.h"
46234285Sdim#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47263508Sdim#include "llvm/Transforms/Utils/Cloning.h"
48249423Sdim#include "llvm/Transforms/Utils/Local.h"
49234285Sdim#include "llvm/Transforms/Utils/ModuleUtils.h"
50263508Sdim#include "llvm/Transforms/Utils/SpecialCaseList.h"
51249423Sdim#include <algorithm>
52234285Sdim#include <string>
53234285Sdim
54234285Sdimusing namespace llvm;
55234285Sdim
56234285Sdimstatic const uint64_t kDefaultShadowScale = 3;
57234285Sdimstatic const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
58234285Sdimstatic const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
59249423Sdimstatic const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000;  // < 2G.
60249423Sdimstatic const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
61263508Sdimstatic const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
62234285Sdim
63263508Sdimstatic const size_t kMinStackMallocSize = 1 << 6;  // 64B
64234285Sdimstatic const size_t kMaxStackMallocSize = 1 << 16;  // 64K
65234285Sdimstatic const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
66234285Sdimstatic const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
67234285Sdim
68263508Sdimstatic const char *const kAsanModuleCtorName = "asan.module_ctor";
69263508Sdimstatic const char *const kAsanModuleDtorName = "asan.module_dtor";
70263508Sdimstatic const int         kAsanCtorAndCtorPriority = 1;
71263508Sdimstatic const char *const kAsanReportErrorTemplate = "__asan_report_";
72263508Sdimstatic const char *const kAsanReportLoadN = "__asan_report_load_n";
73263508Sdimstatic const char *const kAsanReportStoreN = "__asan_report_store_n";
74263508Sdimstatic const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
75263508Sdimstatic const char *const kAsanUnregisterGlobalsName =
76263508Sdim    "__asan_unregister_globals";
77263508Sdimstatic const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
78263508Sdimstatic const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
79263508Sdimstatic const char *const kAsanInitName = "__asan_init_v3";
80263508Sdimstatic const char *const kAsanCovName = "__sanitizer_cov";
81263508Sdimstatic const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
82263508Sdimstatic const char *const kAsanMappingOffsetName = "__asan_mapping_offset";
83263508Sdimstatic const char *const kAsanMappingScaleName = "__asan_mapping_scale";
84263508Sdimstatic const int         kMaxAsanStackMallocSizeClass = 10;
85263508Sdimstatic const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
86263508Sdimstatic const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
87263508Sdimstatic const char *const kAsanGenPrefix = "__asan_gen_";
88263508Sdimstatic const char *const kAsanPoisonStackMemoryName =
89263508Sdim    "__asan_poison_stack_memory";
90263508Sdimstatic const char *const kAsanUnpoisonStackMemoryName =
91249423Sdim    "__asan_unpoison_stack_memory";
92234285Sdim
93263508Sdimstatic const char *const kAsanOptionDetectUAR =
94263508Sdim    "__asan_option_detect_stack_use_after_return";
95263508Sdim
96263508Sdim// These constants must match the definitions in the run-time library.
97234285Sdimstatic const int kAsanStackLeftRedzoneMagic = 0xf1;
98234285Sdimstatic const int kAsanStackMidRedzoneMagic = 0xf2;
99234285Sdimstatic const int kAsanStackRightRedzoneMagic = 0xf3;
100234285Sdimstatic const int kAsanStackPartialRedzoneMagic = 0xf4;
101263508Sdim#ifndef NDEBUG
102263508Sdimstatic const int kAsanStackAfterReturnMagic = 0xf5;
103263508Sdim#endif
104234285Sdim
105239462Sdim// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
106239462Sdimstatic const size_t kNumberOfAccessSizes = 5;
107239462Sdim
108234285Sdim// Command-line flags.
109234285Sdim
110234285Sdim// This flag may need to be replaced with -f[no-]asan-reads.
111234285Sdimstatic cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
112234285Sdim       cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
113234285Sdimstatic cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
114234285Sdim       cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
115239462Sdimstatic cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
116239462Sdim       cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
117239462Sdim       cl::Hidden, cl::init(true));
118239462Sdimstatic cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
119239462Sdim       cl::desc("use instrumentation with slow path for all accesses"),
120239462Sdim       cl::Hidden, cl::init(false));
121239462Sdim// This flag limits the number of instructions to be instrumented
122239462Sdim// in any given BB. Normally, this should be set to unlimited (INT_MAX),
123239462Sdim// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
124239462Sdim// set it to 10000.
125239462Sdimstatic cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
126239462Sdim       cl::init(10000),
127239462Sdim       cl::desc("maximal number of instructions to instrument in any given BB"),
128239462Sdim       cl::Hidden);
129234285Sdim// This flag may need to be replaced with -f[no]asan-stack.
130234285Sdimstatic cl::opt<bool> ClStack("asan-stack",
131234285Sdim       cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
132234285Sdim// This flag may need to be replaced with -f[no]asan-use-after-return.
133234285Sdimstatic cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
134234285Sdim       cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
135234285Sdim// This flag may need to be replaced with -f[no]asan-globals.
136234285Sdimstatic cl::opt<bool> ClGlobals("asan-globals",
137234285Sdim       cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
138263508Sdimstatic cl::opt<bool> ClCoverage("asan-coverage",
139263508Sdim       cl::desc("ASan coverage"), cl::Hidden, cl::init(false));
140243830Sdimstatic cl::opt<bool> ClInitializers("asan-initialization-order",
141243830Sdim       cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
142234285Sdimstatic cl::opt<bool> ClMemIntrin("asan-memintrin",
143234285Sdim       cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
144249423Sdimstatic cl::opt<bool> ClRealignStack("asan-realign-stack",
145249423Sdim       cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
146249423Sdimstatic cl::opt<std::string> ClBlacklistFile("asan-blacklist",
147249423Sdim       cl::desc("File containing the list of objects to ignore "
148234285Sdim                "during instrumentation"), cl::Hidden);
149234285Sdim
150263508Sdim// This is an experimental feature that will allow to choose between
151263508Sdim// instrumented and non-instrumented code at link-time.
152263508Sdim// If this option is on, just before instrumenting a function we create its
153263508Sdim// clone; if the function is not changed by asan the clone is deleted.
154263508Sdim// If we end up with a clone, we put the instrumented function into a section
155263508Sdim// called "ASAN" and the uninstrumented function into a section called "NOASAN".
156263508Sdim//
157263508Sdim// This is still a prototype, we need to figure out a way to keep two copies of
158263508Sdim// a function so that the linker can easily choose one of them.
159263508Sdimstatic cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
160263508Sdim       cl::desc("Keep uninstrumented copies of functions"),
161263508Sdim       cl::Hidden, cl::init(false));
162263508Sdim
163234285Sdim// These flags allow to change the shadow mapping.
164234285Sdim// The shadow mapping looks like
165234285Sdim//    Shadow = (Mem >> scale) + (1 << offset_log)
166234285Sdimstatic cl::opt<int> ClMappingScale("asan-mapping-scale",
167234285Sdim       cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
168234285Sdimstatic cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
169234285Sdim       cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
170249423Sdimstatic cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
171249423Sdim       cl::desc("Use short immediate constant as the mapping offset for 64bit"),
172249423Sdim       cl::Hidden, cl::init(true));
173234285Sdim
174234285Sdim// Optimization flags. Not user visible, used mostly for testing
175234285Sdim// and benchmarking the tool.
176234285Sdimstatic cl::opt<bool> ClOpt("asan-opt",
177234285Sdim       cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
178234285Sdimstatic cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
179234285Sdim       cl::desc("Instrument the same temp just once"), cl::Hidden,
180234285Sdim       cl::init(true));
181234285Sdimstatic cl::opt<bool> ClOptGlobals("asan-opt-globals",
182234285Sdim       cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
183234285Sdim
184249423Sdimstatic cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
185249423Sdim       cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
186249423Sdim       cl::Hidden, cl::init(false));
187249423Sdim
188234285Sdim// Debug flags.
189234285Sdimstatic cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
190234285Sdim                            cl::init(0));
191234285Sdimstatic cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
192234285Sdim                                 cl::Hidden, cl::init(0));
193234285Sdimstatic cl::opt<std::string> ClDebugFunc("asan-debug-func",
194234285Sdim                                        cl::Hidden, cl::desc("Debug func"));
195234285Sdimstatic cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
196234285Sdim                               cl::Hidden, cl::init(-1));
197234285Sdimstatic cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
198234285Sdim                               cl::Hidden, cl::init(-1));
199234285Sdim
200263508SdimSTATISTIC(NumInstrumentedReads, "Number of instrumented reads");
201263508SdimSTATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
202263508SdimSTATISTIC(NumOptimizedAccessesToGlobalArray,
203263508Sdim          "Number of optimized accesses to global arrays");
204263508SdimSTATISTIC(NumOptimizedAccessesToGlobalVar,
205263508Sdim          "Number of optimized accesses to global vars");
206263508Sdim
207234285Sdimnamespace {
208249423Sdim/// A set of dynamically initialized globals extracted from metadata.
209249423Sdimclass SetOfDynamicallyInitializedGlobals {
210249423Sdim public:
211249423Sdim  void Init(Module& M) {
212249423Sdim    // Clang generates metadata identifying all dynamically initialized globals.
213249423Sdim    NamedMDNode *DynamicGlobals =
214249423Sdim        M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
215249423Sdim    if (!DynamicGlobals)
216249423Sdim      return;
217249423Sdim    for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
218249423Sdim      MDNode *MDN = DynamicGlobals->getOperand(i);
219249423Sdim      assert(MDN->getNumOperands() == 1);
220249423Sdim      Value *VG = MDN->getOperand(0);
221249423Sdim      // The optimizer may optimize away a global entirely, in which case we
222249423Sdim      // cannot instrument access to it.
223249423Sdim      if (!VG)
224249423Sdim        continue;
225249423Sdim      DynInitGlobals.insert(cast<GlobalVariable>(VG));
226249423Sdim    }
227249423Sdim  }
228249423Sdim  bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
229249423Sdim private:
230249423Sdim  SmallSet<GlobalValue*, 32> DynInitGlobals;
231249423Sdim};
232249423Sdim
233249423Sdim/// This struct defines the shadow mapping using the rule:
234249423Sdim///   shadow = (mem >> Scale) ADD-or-OR Offset.
235249423Sdimstruct ShadowMapping {
236249423Sdim  int Scale;
237249423Sdim  uint64_t Offset;
238249423Sdim  bool OrShadowOffset;
239249423Sdim};
240249423Sdim
241249423Sdimstatic ShadowMapping getShadowMapping(const Module &M, int LongSize,
242249423Sdim                                      bool ZeroBaseShadow) {
243249423Sdim  llvm::Triple TargetTriple(M.getTargetTriple());
244249423Sdim  bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
245249423Sdim  bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
246263508Sdim  bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
247263508Sdim                 TargetTriple.getArch() == llvm::Triple::ppc64le;
248249423Sdim  bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
249263508Sdim  bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
250263508Sdim                  TargetTriple.getArch() == llvm::Triple::mipsel;
251249423Sdim
252249423Sdim  ShadowMapping Mapping;
253249423Sdim
254249423Sdim  // OR-ing shadow offset if more efficient (at least on x86),
255249423Sdim  // but on ppc64 we have to use add since the shadow offset is not neccesary
256249423Sdim  // 1/8-th of the address space.
257249423Sdim  Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
258249423Sdim
259249423Sdim  Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
260263508Sdim      (LongSize == 32 ?
261263508Sdim       (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
262249423Sdim       IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
263249423Sdim  if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
264249423Sdim    assert(LongSize == 64);
265249423Sdim    Mapping.Offset = kDefaultShort64bitShadowOffset;
266249423Sdim  }
267249423Sdim  if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
268249423Sdim    // Zero offset log is the special case.
269249423Sdim    Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
270249423Sdim  }
271249423Sdim
272249423Sdim  Mapping.Scale = kDefaultShadowScale;
273249423Sdim  if (ClMappingScale) {
274249423Sdim    Mapping.Scale = ClMappingScale;
275249423Sdim  }
276249423Sdim
277249423Sdim  return Mapping;
278249423Sdim}
279249423Sdim
280249423Sdimstatic size_t RedzoneSizeForScale(int MappingScale) {
281249423Sdim  // Redzone used for stack and globals is at least 32 bytes.
282249423Sdim  // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
283249423Sdim  return std::max(32U, 1U << MappingScale);
284249423Sdim}
285249423Sdim
286234285Sdim/// AddressSanitizer: instrument the code in module to find memory bugs.
287243830Sdimstruct AddressSanitizer : public FunctionPass {
288249423Sdim  AddressSanitizer(bool CheckInitOrder = true,
289249423Sdim                   bool CheckUseAfterReturn = false,
290249423Sdim                   bool CheckLifetime = false,
291249423Sdim                   StringRef BlacklistFile = StringRef(),
292249423Sdim                   bool ZeroBaseShadow = false)
293249423Sdim      : FunctionPass(ID),
294249423Sdim        CheckInitOrder(CheckInitOrder || ClInitializers),
295249423Sdim        CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
296249423Sdim        CheckLifetime(CheckLifetime || ClCheckLifetime),
297249423Sdim        BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
298249423Sdim                                            : BlacklistFile),
299249423Sdim        ZeroBaseShadow(ZeroBaseShadow) {}
300249423Sdim  virtual const char *getPassName() const {
301249423Sdim    return "AddressSanitizerFunctionPass";
302249423Sdim  }
303243830Sdim  void instrumentMop(Instruction *I);
304249423Sdim  void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
305249423Sdim                         Value *Addr, uint32_t TypeSize, bool IsWrite,
306249423Sdim                         Value *SizeArgument);
307239462Sdim  Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
308239462Sdim                           Value *ShadowValue, uint32_t TypeSize);
309239462Sdim  Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
310249423Sdim                                 bool IsWrite, size_t AccessSizeIndex,
311249423Sdim                                 Value *SizeArgument);
312243830Sdim  bool instrumentMemIntrinsic(MemIntrinsic *MI);
313243830Sdim  void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
314239462Sdim                                   Value *Size,
315234285Sdim                                   Instruction *InsertBefore, bool IsWrite);
316234285Sdim  Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
317243830Sdim  bool runOnFunction(Function &F);
318234285Sdim  bool maybeInsertAsanInitAtFunctionEntry(Function &F);
319249423Sdim  void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
320243830Sdim  virtual bool doInitialization(Module &M);
321234285Sdim  static char ID;  // Pass identification, replacement for typeid
322234285Sdim
323234285Sdim private:
324249423Sdim  void initializeCallbacks(Module &M);
325234285Sdim
326243830Sdim  bool ShouldInstrumentGlobal(GlobalVariable *G);
327234285Sdim  bool LooksLikeCodeInBug11395(Instruction *I);
328243830Sdim  void FindDynamicInitializers(Module &M);
329263508Sdim  bool GlobalIsLinkerInitialized(GlobalVariable *G);
330263508Sdim  bool InjectCoverage(Function &F);
331234285Sdim
332249423Sdim  bool CheckInitOrder;
333249423Sdim  bool CheckUseAfterReturn;
334249423Sdim  bool CheckLifetime;
335249423Sdim  SmallString<64> BlacklistFile;
336249423Sdim  bool ZeroBaseShadow;
337249423Sdim
338234285Sdim  LLVMContext *C;
339243830Sdim  DataLayout *TD;
340234285Sdim  int LongSize;
341234285Sdim  Type *IntptrTy;
342249423Sdim  ShadowMapping Mapping;
343234285Sdim  Function *AsanCtorFunction;
344234285Sdim  Function *AsanInitFunction;
345243830Sdim  Function *AsanHandleNoReturnFunc;
346263508Sdim  Function *AsanCovFunction;
347263508Sdim  OwningPtr<SpecialCaseList> BL;
348239462Sdim  // This array is indexed by AccessIsWrite and log2(AccessSize).
349239462Sdim  Function *AsanErrorCallback[2][kNumberOfAccessSizes];
350249423Sdim  // This array is indexed by AccessIsWrite.
351249423Sdim  Function *AsanErrorCallbackSized[2];
352239462Sdim  InlineAsm *EmptyAsm;
353249423Sdim  SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
354249423Sdim
355249423Sdim  friend struct FunctionStackPoisoner;
356234285Sdim};
357239462Sdim
358249423Sdimclass AddressSanitizerModule : public ModulePass {
359249423Sdim public:
360249423Sdim  AddressSanitizerModule(bool CheckInitOrder = true,
361249423Sdim                         StringRef BlacklistFile = StringRef(),
362249423Sdim                         bool ZeroBaseShadow = false)
363249423Sdim      : ModulePass(ID),
364249423Sdim        CheckInitOrder(CheckInitOrder || ClInitializers),
365249423Sdim        BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
366249423Sdim                                            : BlacklistFile),
367249423Sdim        ZeroBaseShadow(ZeroBaseShadow) {}
368249423Sdim  bool runOnModule(Module &M);
369249423Sdim  static char ID;  // Pass identification, replacement for typeid
370249423Sdim  virtual const char *getPassName() const {
371249423Sdim    return "AddressSanitizerModule";
372249423Sdim  }
373249423Sdim
374249423Sdim private:
375249423Sdim  void initializeCallbacks(Module &M);
376249423Sdim
377249423Sdim  bool ShouldInstrumentGlobal(GlobalVariable *G);
378249423Sdim  void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
379249423Sdim  size_t RedzoneSize() const {
380249423Sdim    return RedzoneSizeForScale(Mapping.Scale);
381249423Sdim  }
382249423Sdim
383249423Sdim  bool CheckInitOrder;
384249423Sdim  SmallString<64> BlacklistFile;
385249423Sdim  bool ZeroBaseShadow;
386249423Sdim
387263508Sdim  OwningPtr<SpecialCaseList> BL;
388249423Sdim  SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
389249423Sdim  Type *IntptrTy;
390249423Sdim  LLVMContext *C;
391249423Sdim  DataLayout *TD;
392249423Sdim  ShadowMapping Mapping;
393249423Sdim  Function *AsanPoisonGlobals;
394249423Sdim  Function *AsanUnpoisonGlobals;
395249423Sdim  Function *AsanRegisterGlobals;
396249423Sdim  Function *AsanUnregisterGlobals;
397249423Sdim};
398249423Sdim
399249423Sdim// Stack poisoning does not play well with exception handling.
400249423Sdim// When an exception is thrown, we essentially bypass the code
401249423Sdim// that unpoisones the stack. This is why the run-time library has
402249423Sdim// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
403249423Sdim// stack in the interceptor. This however does not work inside the
404249423Sdim// actual function which catches the exception. Most likely because the
405249423Sdim// compiler hoists the load of the shadow value somewhere too high.
406249423Sdim// This causes asan to report a non-existing bug on 453.povray.
407249423Sdim// It sounds like an LLVM bug.
408249423Sdimstruct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
409249423Sdim  Function &F;
410249423Sdim  AddressSanitizer &ASan;
411249423Sdim  DIBuilder DIB;
412249423Sdim  LLVMContext *C;
413249423Sdim  Type *IntptrTy;
414249423Sdim  Type *IntptrPtrTy;
415249423Sdim  ShadowMapping Mapping;
416249423Sdim
417249423Sdim  SmallVector<AllocaInst*, 16> AllocaVec;
418249423Sdim  SmallVector<Instruction*, 8> RetVec;
419249423Sdim  uint64_t TotalStackSize;
420249423Sdim  unsigned StackAlignment;
421249423Sdim
422263508Sdim  Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
423263508Sdim           *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
424249423Sdim  Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
425249423Sdim
426249423Sdim  // Stores a place and arguments of poisoning/unpoisoning call for alloca.
427249423Sdim  struct AllocaPoisonCall {
428249423Sdim    IntrinsicInst *InsBefore;
429263508Sdim    AllocaInst *AI;
430249423Sdim    uint64_t Size;
431249423Sdim    bool DoPoison;
432249423Sdim  };
433249423Sdim  SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
434249423Sdim
435249423Sdim  // Maps Value to an AllocaInst from which the Value is originated.
436249423Sdim  typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
437249423Sdim  AllocaForValueMapTy AllocaForValue;
438249423Sdim
439249423Sdim  FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
440249423Sdim      : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
441249423Sdim        IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
442249423Sdim        Mapping(ASan.Mapping),
443249423Sdim        TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
444249423Sdim
445249423Sdim  bool runOnFunction() {
446249423Sdim    if (!ClStack) return false;
447249423Sdim    // Collect alloca, ret, lifetime instructions etc.
448249423Sdim    for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
449249423Sdim         DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
450249423Sdim      BasicBlock *BB = *DI;
451249423Sdim      visit(*BB);
452249423Sdim    }
453249423Sdim    if (AllocaVec.empty()) return false;
454249423Sdim
455249423Sdim    initializeCallbacks(*F.getParent());
456249423Sdim
457249423Sdim    poisonStack();
458249423Sdim
459249423Sdim    if (ClDebugStack) {
460249423Sdim      DEBUG(dbgs() << F);
461249423Sdim    }
462249423Sdim    return true;
463249423Sdim  }
464249423Sdim
465249423Sdim  // Finds all static Alloca instructions and puts
466249423Sdim  // poisoned red zones around all of them.
467249423Sdim  // Then unpoison everything back before the function returns.
468249423Sdim  void poisonStack();
469249423Sdim
470249423Sdim  // ----------------------- Visitors.
471249423Sdim  /// \brief Collect all Ret instructions.
472249423Sdim  void visitReturnInst(ReturnInst &RI) {
473249423Sdim    RetVec.push_back(&RI);
474249423Sdim  }
475249423Sdim
476249423Sdim  /// \brief Collect Alloca instructions we want (and can) handle.
477249423Sdim  void visitAllocaInst(AllocaInst &AI) {
478249423Sdim    if (!isInterestingAlloca(AI)) return;
479249423Sdim
480249423Sdim    StackAlignment = std::max(StackAlignment, AI.getAlignment());
481249423Sdim    AllocaVec.push_back(&AI);
482263508Sdim    uint64_t AlignedSize = getAlignedAllocaSize(&AI);
483249423Sdim    TotalStackSize += AlignedSize;
484249423Sdim  }
485249423Sdim
486249423Sdim  /// \brief Collect lifetime intrinsic calls to check for use-after-scope
487249423Sdim  /// errors.
488249423Sdim  void visitIntrinsicInst(IntrinsicInst &II) {
489249423Sdim    if (!ASan.CheckLifetime) return;
490249423Sdim    Intrinsic::ID ID = II.getIntrinsicID();
491249423Sdim    if (ID != Intrinsic::lifetime_start &&
492249423Sdim        ID != Intrinsic::lifetime_end)
493249423Sdim      return;
494249423Sdim    // Found lifetime intrinsic, add ASan instrumentation if necessary.
495249423Sdim    ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
496249423Sdim    // If size argument is undefined, don't do anything.
497249423Sdim    if (Size->isMinusOne()) return;
498249423Sdim    // Check that size doesn't saturate uint64_t and can
499249423Sdim    // be stored in IntptrTy.
500249423Sdim    const uint64_t SizeValue = Size->getValue().getLimitedValue();
501249423Sdim    if (SizeValue == ~0ULL ||
502249423Sdim        !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
503249423Sdim      return;
504249423Sdim    // Find alloca instruction that corresponds to llvm.lifetime argument.
505249423Sdim    AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
506249423Sdim    if (!AI) return;
507249423Sdim    bool DoPoison = (ID == Intrinsic::lifetime_end);
508263508Sdim    AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
509249423Sdim    AllocaPoisonCallVec.push_back(APC);
510249423Sdim  }
511249423Sdim
512249423Sdim  // ---------------------- Helpers.
513249423Sdim  void initializeCallbacks(Module &M);
514249423Sdim
515249423Sdim  // Check if we want (and can) handle this alloca.
516263508Sdim  bool isInterestingAlloca(AllocaInst &AI) const {
517249423Sdim    return (!AI.isArrayAllocation() &&
518249423Sdim            AI.isStaticAlloca() &&
519263508Sdim            AI.getAlignment() <= RedzoneSize() &&
520249423Sdim            AI.getAllocatedType()->isSized());
521249423Sdim  }
522249423Sdim
523249423Sdim  size_t RedzoneSize() const {
524249423Sdim    return RedzoneSizeForScale(Mapping.Scale);
525249423Sdim  }
526263508Sdim  uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
527249423Sdim    Type *Ty = AI->getAllocatedType();
528249423Sdim    uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
529249423Sdim    return SizeInBytes;
530249423Sdim  }
531263508Sdim  uint64_t getAlignedSize(uint64_t SizeInBytes) const {
532249423Sdim    size_t RZ = RedzoneSize();
533249423Sdim    return ((SizeInBytes + RZ - 1) / RZ) * RZ;
534249423Sdim  }
535263508Sdim  uint64_t getAlignedAllocaSize(AllocaInst *AI) const {
536249423Sdim    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
537249423Sdim    return getAlignedSize(SizeInBytes);
538249423Sdim  }
539249423Sdim  /// Finds alloca where the value comes from.
540249423Sdim  AllocaInst *findAllocaForValue(Value *V);
541263508Sdim  void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB,
542249423Sdim                      Value *ShadowBase, bool DoPoison);
543263508Sdim  void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
544263508Sdim
545263508Sdim  void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
546263508Sdim                                          int Size);
547249423Sdim};
548249423Sdim
549234285Sdim}  // namespace
550234285Sdim
551234285Sdimchar AddressSanitizer::ID = 0;
552234285SdimINITIALIZE_PASS(AddressSanitizer, "asan",
553234285Sdim    "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
554234285Sdim    false, false)
555249423SdimFunctionPass *llvm::createAddressSanitizerFunctionPass(
556249423Sdim    bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
557249423Sdim    StringRef BlacklistFile, bool ZeroBaseShadow) {
558249423Sdim  return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
559249423Sdim                              CheckLifetime, BlacklistFile, ZeroBaseShadow);
560234285Sdim}
561234285Sdim
562249423Sdimchar AddressSanitizerModule::ID = 0;
563249423SdimINITIALIZE_PASS(AddressSanitizerModule, "asan-module",
564249423Sdim    "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
565249423Sdim    "ModulePass", false, false)
566249423SdimModulePass *llvm::createAddressSanitizerModulePass(
567249423Sdim    bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
568249423Sdim  return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
569249423Sdim                                    ZeroBaseShadow);
570234285Sdim}
571234285Sdim
572239462Sdimstatic size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
573263508Sdim  size_t Res = countTrailingZeros(TypeSize / 8);
574239462Sdim  assert(Res < kNumberOfAccessSizes);
575239462Sdim  return Res;
576239462Sdim}
577239462Sdim
578263508Sdim// \brief Create a constant for Str so that we can pass it to the run-time lib.
579234285Sdimstatic GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
580234285Sdim  Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
581249423Sdim  GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
582263508Sdim                            GlobalValue::InternalLinkage, StrConst,
583249423Sdim                            kAsanGenPrefix);
584249423Sdim  GV->setUnnamedAddr(true);  // Ok to merge these.
585249423Sdim  GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
586249423Sdim  return GV;
587234285Sdim}
588234285Sdim
589249423Sdimstatic bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
590249423Sdim  return G->getName().find(kAsanGenPrefix) == 0;
591249423Sdim}
592249423Sdim
593234285SdimValue *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
594234285Sdim  // Shadow >> scale
595249423Sdim  Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
596249423Sdim  if (Mapping.Offset == 0)
597234285Sdim    return Shadow;
598234285Sdim  // (Shadow >> scale) | offset
599249423Sdim  if (Mapping.OrShadowOffset)
600249423Sdim    return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
601249423Sdim  else
602249423Sdim    return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
603234285Sdim}
604234285Sdim
605239462Sdimvoid AddressSanitizer::instrumentMemIntrinsicParam(
606243830Sdim    Instruction *OrigIns,
607234285Sdim    Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
608249423Sdim  IRBuilder<> IRB(InsertBefore);
609249423Sdim  if (Size->getType() != IntptrTy)
610249423Sdim    Size = IRB.CreateIntCast(Size, IntptrTy, false);
611234285Sdim  // Check the first byte.
612249423Sdim  instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
613234285Sdim  // Check the last byte.
614249423Sdim  IRB.SetInsertPoint(InsertBefore);
615249423Sdim  Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
616249423Sdim  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
617249423Sdim  Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
618249423Sdim  instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
619234285Sdim}
620234285Sdim
621234285Sdim// Instrument memset/memmove/memcpy
622243830Sdimbool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
623234285Sdim  Value *Dst = MI->getDest();
624234285Sdim  MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
625239462Sdim  Value *Src = MemTran ? MemTran->getSource() : 0;
626234285Sdim  Value *Length = MI->getLength();
627234285Sdim
628234285Sdim  Constant *ConstLength = dyn_cast<Constant>(Length);
629234285Sdim  Instruction *InsertBefore = MI;
630234285Sdim  if (ConstLength) {
631234285Sdim    if (ConstLength->isNullValue()) return false;
632234285Sdim  } else {
633234285Sdim    // The size is not a constant so it could be zero -- check at run-time.
634234285Sdim    IRBuilder<> IRB(InsertBefore);
635234285Sdim
636234285Sdim    Value *Cmp = IRB.CreateICmpNE(Length,
637239462Sdim                                  Constant::getNullValue(Length->getType()));
638243830Sdim    InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
639234285Sdim  }
640234285Sdim
641243830Sdim  instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
642234285Sdim  if (Src)
643243830Sdim    instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
644234285Sdim  return true;
645234285Sdim}
646234285Sdim
647239462Sdim// If I is an interesting memory access, return the PointerOperand
648239462Sdim// and set IsWrite. Otherwise return NULL.
649239462Sdimstatic Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
650234285Sdim  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
651239462Sdim    if (!ClInstrumentReads) return NULL;
652239462Sdim    *IsWrite = false;
653234285Sdim    return LI->getPointerOperand();
654234285Sdim  }
655239462Sdim  if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
656239462Sdim    if (!ClInstrumentWrites) return NULL;
657239462Sdim    *IsWrite = true;
658239462Sdim    return SI->getPointerOperand();
659239462Sdim  }
660239462Sdim  if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
661239462Sdim    if (!ClInstrumentAtomics) return NULL;
662239462Sdim    *IsWrite = true;
663239462Sdim    return RMW->getPointerOperand();
664239462Sdim  }
665239462Sdim  if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
666239462Sdim    if (!ClInstrumentAtomics) return NULL;
667239462Sdim    *IsWrite = true;
668239462Sdim    return XCHG->getPointerOperand();
669239462Sdim  }
670239462Sdim  return NULL;
671234285Sdim}
672234285Sdim
673263508Sdimbool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
674263508Sdim  // If a global variable does not have dynamic initialization we don't
675263508Sdim  // have to instrument it.  However, if a global does not have initializer
676263508Sdim  // at all, we assume it has dynamic initializer (in other TU).
677263508Sdim  return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
678263508Sdim}
679263508Sdim
680243830Sdimvoid AddressSanitizer::instrumentMop(Instruction *I) {
681243830Sdim  bool IsWrite = false;
682239462Sdim  Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
683239462Sdim  assert(Addr);
684243830Sdim  if (ClOpt && ClOptGlobals) {
685243830Sdim    if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
686243830Sdim      // If initialization order checking is disabled, a simple access to a
687243830Sdim      // dynamically initialized global is always valid.
688263508Sdim      if (!CheckInitOrder || GlobalIsLinkerInitialized(G)) {
689263508Sdim        NumOptimizedAccessesToGlobalVar++;
690243830Sdim        return;
691263508Sdim      }
692243830Sdim    }
693263508Sdim    ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
694263508Sdim    if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
695263508Sdim      if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
696263508Sdim        if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
697263508Sdim          NumOptimizedAccessesToGlobalArray++;
698263508Sdim          return;
699263508Sdim        }
700263508Sdim      }
701263508Sdim    }
702234285Sdim  }
703243830Sdim
704234285Sdim  Type *OrigPtrTy = Addr->getType();
705234285Sdim  Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
706234285Sdim
707234285Sdim  assert(OrigTy->isSized());
708234285Sdim  uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
709234285Sdim
710249423Sdim  assert((TypeSize % 8) == 0);
711234285Sdim
712263508Sdim  if (IsWrite)
713263508Sdim    NumInstrumentedWrites++;
714263508Sdim  else
715263508Sdim    NumInstrumentedReads++;
716263508Sdim
717249423Sdim  // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
718249423Sdim  if (TypeSize == 8  || TypeSize == 16 ||
719249423Sdim      TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
720249423Sdim    return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
721249423Sdim  // Instrument unusual size (but still multiple of 8).
722249423Sdim  // We can not do it with a single check, so we do 1-byte check for the first
723249423Sdim  // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
724249423Sdim  // to report the actual access size.
725234285Sdim  IRBuilder<> IRB(I);
726249423Sdim  Value *LastByte =  IRB.CreateIntToPtr(
727249423Sdim      IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
728249423Sdim                    ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
729249423Sdim      OrigPtrTy);
730249423Sdim  Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
731249423Sdim  instrumentAddress(I, I, Addr, 8, IsWrite, Size);
732249423Sdim  instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
733234285Sdim}
734234285Sdim
735239462Sdim// Validate the result of Module::getOrInsertFunction called for an interface
736239462Sdim// function of AddressSanitizer. If the instrumented module defines a function
737239462Sdim// with the same name, their prototypes must match, otherwise
738239462Sdim// getOrInsertFunction returns a bitcast.
739249423Sdimstatic Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
740239462Sdim  if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
741239462Sdim  FuncOrBitcast->dump();
742239462Sdim  report_fatal_error("trying to redefine an AddressSanitizer "
743239462Sdim                     "interface function");
744239462Sdim}
745239462Sdim
746234285SdimInstruction *AddressSanitizer::generateCrashCode(
747239462Sdim    Instruction *InsertBefore, Value *Addr,
748249423Sdim    bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
749239462Sdim  IRBuilder<> IRB(InsertBefore);
750249423Sdim  CallInst *Call = SizeArgument
751249423Sdim    ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
752249423Sdim    : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
753249423Sdim
754239462Sdim  // We don't do Call->setDoesNotReturn() because the BB already has
755239462Sdim  // UnreachableInst at the end.
756239462Sdim  // This EmptyAsm is required to avoid callback merge.
757239462Sdim  IRB.CreateCall(EmptyAsm);
758234285Sdim  return Call;
759234285Sdim}
760234285Sdim
761239462SdimValue *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
762239462Sdim                                            Value *ShadowValue,
763239462Sdim                                            uint32_t TypeSize) {
764249423Sdim  size_t Granularity = 1 << Mapping.Scale;
765239462Sdim  // Addr & (Granularity - 1)
766239462Sdim  Value *LastAccessedByte = IRB.CreateAnd(
767239462Sdim      AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
768239462Sdim  // (Addr & (Granularity - 1)) + size - 1
769239462Sdim  if (TypeSize / 8 > 1)
770239462Sdim    LastAccessedByte = IRB.CreateAdd(
771239462Sdim        LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
772239462Sdim  // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
773239462Sdim  LastAccessedByte = IRB.CreateIntCast(
774239462Sdim      LastAccessedByte, ShadowValue->getType(), false);
775239462Sdim  // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
776239462Sdim  return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
777239462Sdim}
778239462Sdim
779243830Sdimvoid AddressSanitizer::instrumentAddress(Instruction *OrigIns,
780249423Sdim                                         Instruction *InsertBefore,
781249423Sdim                                         Value *Addr, uint32_t TypeSize,
782249423Sdim                                         bool IsWrite, Value *SizeArgument) {
783249423Sdim  IRBuilder<> IRB(InsertBefore);
784234285Sdim  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
785234285Sdim
786234285Sdim  Type *ShadowTy  = IntegerType::get(
787249423Sdim      *C, std::max(8U, TypeSize >> Mapping.Scale));
788234285Sdim  Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
789234285Sdim  Value *ShadowPtr = memToShadow(AddrLong, IRB);
790234285Sdim  Value *CmpVal = Constant::getNullValue(ShadowTy);
791234285Sdim  Value *ShadowValue = IRB.CreateLoad(
792234285Sdim      IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
793234285Sdim
794234285Sdim  Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
795239462Sdim  size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
796249423Sdim  size_t Granularity = 1 << Mapping.Scale;
797239462Sdim  TerminatorInst *CrashTerm = 0;
798234285Sdim
799239462Sdim  if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
800243830Sdim    TerminatorInst *CheckTerm =
801243830Sdim        SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
802239462Sdim    assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
803239462Sdim    BasicBlock *NextBB = CheckTerm->getSuccessor(0);
804239462Sdim    IRB.SetInsertPoint(CheckTerm);
805239462Sdim    Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
806243830Sdim    BasicBlock *CrashBlock =
807243830Sdim        BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
808239462Sdim    CrashTerm = new UnreachableInst(*C, CrashBlock);
809239462Sdim    BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
810239462Sdim    ReplaceInstWithInst(CheckTerm, NewTerm);
811239462Sdim  } else {
812243830Sdim    CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
813234285Sdim  }
814234285Sdim
815249423Sdim  Instruction *Crash = generateCrashCode(
816249423Sdim      CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
817234285Sdim  Crash->setDebugLoc(OrigIns->getDebugLoc());
818234285Sdim}
819234285Sdim
820249423Sdimvoid AddressSanitizerModule::createInitializerPoisonCalls(
821249423Sdim    Module &M, GlobalValue *ModuleName) {
822243830Sdim  // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
823243830Sdim  Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
824243830Sdim  // If that function is not present, this TU contains no globals, or they have
825243830Sdim  // all been optimized away
826243830Sdim  if (!GlobalInit)
827243830Sdim    return;
828234285Sdim
829243830Sdim  // Set up the arguments to our poison/unpoison functions.
830243830Sdim  IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
831234285Sdim
832243830Sdim  // Add a call to poison all external globals before the given function starts.
833249423Sdim  Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
834249423Sdim  IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
835243830Sdim
836243830Sdim  // Add calls to unpoison all globals before each return instruction.
837243830Sdim  for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
838243830Sdim      I != E; ++I) {
839243830Sdim    if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
840243830Sdim      CallInst::Create(AsanUnpoisonGlobals, "", RI);
841234285Sdim    }
842243830Sdim  }
843243830Sdim}
844234285Sdim
845249423Sdimbool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
846243830Sdim  Type *Ty = cast<PointerType>(G->getType())->getElementType();
847243830Sdim  DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
848243830Sdim
849243830Sdim  if (BL->isIn(*G)) return false;
850243830Sdim  if (!Ty->isSized()) return false;
851243830Sdim  if (!G->hasInitializer()) return false;
852249423Sdim  if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
853243830Sdim  // Touch only those globals that will not be defined in other modules.
854243830Sdim  // Don't handle ODR type linkages since other modules may be built w/o asan.
855243830Sdim  if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
856243830Sdim      G->getLinkage() != GlobalVariable::PrivateLinkage &&
857243830Sdim      G->getLinkage() != GlobalVariable::InternalLinkage)
858243830Sdim    return false;
859243830Sdim  // Two problems with thread-locals:
860243830Sdim  //   - The address of the main thread's copy can't be computed at link-time.
861243830Sdim  //   - Need to poison all copies, not just the main thread's one.
862243830Sdim  if (G->isThreadLocal())
863243830Sdim    return false;
864243830Sdim  // For now, just ignore this Alloca if the alignment is large.
865249423Sdim  if (G->getAlignment() > RedzoneSize()) return false;
866243830Sdim
867243830Sdim  // Ignore all the globals with the names starting with "\01L_OBJC_".
868243830Sdim  // Many of those are put into the .cstring section. The linker compresses
869243830Sdim  // that section by removing the spare \0s after the string terminator, so
870243830Sdim  // our redzones get broken.
871243830Sdim  if ((G->getName().find("\01L_OBJC_") == 0) ||
872243830Sdim      (G->getName().find("\01l_OBJC_") == 0)) {
873243830Sdim    DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
874243830Sdim    return false;
875243830Sdim  }
876243830Sdim
877243830Sdim  if (G->hasSection()) {
878243830Sdim    StringRef Section(G->getSection());
879243830Sdim    // Ignore the globals from the __OBJC section. The ObjC runtime assumes
880243830Sdim    // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
881243830Sdim    // them.
882243830Sdim    if ((Section.find("__OBJC,") == 0) ||
883243830Sdim        (Section.find("__DATA, __objc_") == 0)) {
884243830Sdim      DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
885243830Sdim      return false;
886234285Sdim    }
887243830Sdim    // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
888243830Sdim    // Constant CFString instances are compiled in the following way:
889243830Sdim    //  -- the string buffer is emitted into
890243830Sdim    //     __TEXT,__cstring,cstring_literals
891243830Sdim    //  -- the constant NSConstantString structure referencing that buffer
892243830Sdim    //     is placed into __DATA,__cfstring
893243830Sdim    // Therefore there's no point in placing redzones into __DATA,__cfstring.
894243830Sdim    // Moreover, it causes the linker to crash on OS X 10.7
895243830Sdim    if (Section.find("__DATA,__cfstring") == 0) {
896243830Sdim      DEBUG(dbgs() << "Ignoring CFString: " << *G);
897243830Sdim      return false;
898243830Sdim    }
899243830Sdim  }
900234285Sdim
901243830Sdim  return true;
902243830Sdim}
903243830Sdim
904249423Sdimvoid AddressSanitizerModule::initializeCallbacks(Module &M) {
905249423Sdim  IRBuilder<> IRB(*C);
906249423Sdim  // Declare our poisoning and unpoisoning functions.
907249423Sdim  AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
908249423Sdim      kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
909249423Sdim  AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
910249423Sdim  AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
911249423Sdim      kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
912249423Sdim  AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
913249423Sdim  // Declare functions that register/unregister globals.
914249423Sdim  AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
915249423Sdim      kAsanRegisterGlobalsName, IRB.getVoidTy(),
916249423Sdim      IntptrTy, IntptrTy, NULL));
917249423Sdim  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
918249423Sdim  AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
919249423Sdim      kAsanUnregisterGlobalsName,
920249423Sdim      IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
921249423Sdim  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
922249423Sdim}
923249423Sdim
924243830Sdim// This function replaces all global variables with new variables that have
925243830Sdim// trailing redzones. It also creates a function that poisons
926243830Sdim// redzones and inserts this function into llvm.global_ctors.
927249423Sdimbool AddressSanitizerModule::runOnModule(Module &M) {
928249423Sdim  if (!ClGlobals) return false;
929249423Sdim  TD = getAnalysisIfAvailable<DataLayout>();
930249423Sdim  if (!TD)
931249423Sdim    return false;
932263508Sdim  BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
933249423Sdim  if (BL->isIn(M)) return false;
934249423Sdim  C = &(M.getContext());
935249423Sdim  int LongSize = TD->getPointerSizeInBits();
936249423Sdim  IntptrTy = Type::getIntNTy(*C, LongSize);
937249423Sdim  Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
938249423Sdim  initializeCallbacks(M);
939249423Sdim  DynamicallyInitializedGlobals.Init(M);
940249423Sdim
941243830Sdim  SmallVector<GlobalVariable *, 16> GlobalsToChange;
942243830Sdim
943243830Sdim  for (Module::GlobalListType::iterator G = M.global_begin(),
944243830Sdim       E = M.global_end(); G != E; ++G) {
945243830Sdim    if (ShouldInstrumentGlobal(G))
946243830Sdim      GlobalsToChange.push_back(G);
947234285Sdim  }
948234285Sdim
949234285Sdim  size_t n = GlobalsToChange.size();
950234285Sdim  if (n == 0) return false;
951234285Sdim
952234285Sdim  // A global is described by a structure
953234285Sdim  //   size_t beg;
954234285Sdim  //   size_t size;
955234285Sdim  //   size_t size_with_redzone;
956234285Sdim  //   const char *name;
957249423Sdim  //   const char *module_name;
958243830Sdim  //   size_t has_dynamic_init;
959234285Sdim  // We initialize an array of such structures and pass it to a run-time call.
960234285Sdim  StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
961243830Sdim                                               IntptrTy, IntptrTy,
962249423Sdim                                               IntptrTy, IntptrTy, NULL);
963263508Sdim  SmallVector<Constant *, 16> Initializers(n);
964234285Sdim
965249423Sdim  Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
966249423Sdim  assert(CtorFunc);
967249423Sdim  IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
968243830Sdim
969249423Sdim  bool HasDynamicallyInitializedGlobals = false;
970243830Sdim
971249423Sdim  GlobalVariable *ModuleName = createPrivateGlobalForString(
972249423Sdim      M, M.getModuleIdentifier());
973249423Sdim  // We shouldn't merge same module names, as this string serves as unique
974249423Sdim  // module ID in runtime.
975249423Sdim  ModuleName->setUnnamedAddr(false);
976249423Sdim
977234285Sdim  for (size_t i = 0; i < n; i++) {
978249423Sdim    static const uint64_t kMaxGlobalRedzone = 1 << 18;
979234285Sdim    GlobalVariable *G = GlobalsToChange[i];
980234285Sdim    PointerType *PtrTy = cast<PointerType>(G->getType());
981234285Sdim    Type *Ty = PtrTy->getElementType();
982234285Sdim    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
983249423Sdim    uint64_t MinRZ = RedzoneSize();
984249423Sdim    // MinRZ <= RZ <= kMaxGlobalRedzone
985249423Sdim    // and trying to make RZ to be ~ 1/4 of SizeInBytes.
986249423Sdim    uint64_t RZ = std::max(MinRZ,
987249423Sdim                         std::min(kMaxGlobalRedzone,
988249423Sdim                                  (SizeInBytes / MinRZ / 4) * MinRZ));
989249423Sdim    uint64_t RightRedzoneSize = RZ;
990249423Sdim    // Round up to MinRZ
991249423Sdim    if (SizeInBytes % MinRZ)
992249423Sdim      RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
993249423Sdim    assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
994234285Sdim    Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
995243830Sdim    // Determine whether this global should be poisoned in initialization.
996249423Sdim    bool GlobalHasDynamicInitializer =
997249423Sdim        DynamicallyInitializedGlobals.Contains(G);
998243830Sdim    // Don't check initialization order if this global is blacklisted.
999263508Sdim    GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
1000234285Sdim
1001234285Sdim    StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1002234285Sdim    Constant *NewInitializer = ConstantStruct::get(
1003234285Sdim        NewTy, G->getInitializer(),
1004234285Sdim        Constant::getNullValue(RightRedZoneTy), NULL);
1005234285Sdim
1006249423Sdim    GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
1007234285Sdim
1008234285Sdim    // Create a new global variable with enough space for a redzone.
1009263508Sdim    GlobalValue::LinkageTypes Linkage = G->getLinkage();
1010263508Sdim    if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1011263508Sdim      Linkage = GlobalValue::InternalLinkage;
1012234285Sdim    GlobalVariable *NewGlobal = new GlobalVariable(
1013263508Sdim        M, NewTy, G->isConstant(), Linkage,
1014239462Sdim        NewInitializer, "", G, G->getThreadLocalMode());
1015234285Sdim    NewGlobal->copyAttributesFrom(G);
1016249423Sdim    NewGlobal->setAlignment(MinRZ);
1017234285Sdim
1018234285Sdim    Value *Indices2[2];
1019234285Sdim    Indices2[0] = IRB.getInt32(0);
1020234285Sdim    Indices2[1] = IRB.getInt32(0);
1021234285Sdim
1022234285Sdim    G->replaceAllUsesWith(
1023234285Sdim        ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1024234285Sdim    NewGlobal->takeName(G);
1025234285Sdim    G->eraseFromParent();
1026234285Sdim
1027234285Sdim    Initializers[i] = ConstantStruct::get(
1028234285Sdim        GlobalStructTy,
1029234285Sdim        ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1030234285Sdim        ConstantInt::get(IntptrTy, SizeInBytes),
1031234285Sdim        ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1032234285Sdim        ConstantExpr::getPointerCast(Name, IntptrTy),
1033249423Sdim        ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1034243830Sdim        ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
1035234285Sdim        NULL);
1036243830Sdim
1037243830Sdim    // Populate the first and last globals declared in this TU.
1038249423Sdim    if (CheckInitOrder && GlobalHasDynamicInitializer)
1039249423Sdim      HasDynamicallyInitializedGlobals = true;
1040243830Sdim
1041243830Sdim    DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1042234285Sdim  }
1043234285Sdim
1044234285Sdim  ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1045234285Sdim  GlobalVariable *AllGlobals = new GlobalVariable(
1046263508Sdim      M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1047234285Sdim      ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1048234285Sdim
1049243830Sdim  // Create calls for poisoning before initializers run and unpoisoning after.
1050249423Sdim  if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1051249423Sdim    createInitializerPoisonCalls(M, ModuleName);
1052234285Sdim  IRB.CreateCall2(AsanRegisterGlobals,
1053234285Sdim                  IRB.CreatePointerCast(AllGlobals, IntptrTy),
1054234285Sdim                  ConstantInt::get(IntptrTy, n));
1055234285Sdim
1056234285Sdim  // We also need to unregister globals at the end, e.g. when a shared library
1057234285Sdim  // gets closed.
1058234285Sdim  Function *AsanDtorFunction = Function::Create(
1059234285Sdim      FunctionType::get(Type::getVoidTy(*C), false),
1060234285Sdim      GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1061234285Sdim  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1062234285Sdim  IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1063234285Sdim  IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1064234285Sdim                       IRB.CreatePointerCast(AllGlobals, IntptrTy),
1065234285Sdim                       ConstantInt::get(IntptrTy, n));
1066234285Sdim  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1067234285Sdim
1068234285Sdim  DEBUG(dbgs() << M);
1069234285Sdim  return true;
1070234285Sdim}
1071234285Sdim
1072249423Sdimvoid AddressSanitizer::initializeCallbacks(Module &M) {
1073249423Sdim  IRBuilder<> IRB(*C);
1074239462Sdim  // Create __asan_report* callbacks.
1075239462Sdim  for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1076239462Sdim    for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1077239462Sdim         AccessSizeIndex++) {
1078239462Sdim      // IsWrite and TypeSize are encoded in the function name.
1079239462Sdim      std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1080239462Sdim          (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1081239462Sdim      // If we are merging crash callbacks, they have two parameters.
1082243830Sdim      AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1083243830Sdim          checkInterfaceFunction(M.getOrInsertFunction(
1084243830Sdim              FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
1085239462Sdim    }
1086239462Sdim  }
1087249423Sdim  AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1088249423Sdim              kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1089249423Sdim  AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1090249423Sdim              kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1091243830Sdim
1092243830Sdim  AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1093243830Sdim      kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1094263508Sdim  AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
1095263508Sdim      kAsanCovName, IRB.getVoidTy(), IntptrTy, NULL));
1096239462Sdim  // We insert an empty inline asm after __asan_report* to avoid callback merge.
1097239462Sdim  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1098239462Sdim                            StringRef(""), StringRef(""),
1099239462Sdim                            /*hasSideEffects=*/true);
1100249423Sdim}
1101239462Sdim
1102249423Sdimvoid AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
1103249423Sdim  // Tell the values of mapping offset and scale to the run-time.
1104249423Sdim  GlobalValue *asan_mapping_offset =
1105249423Sdim      new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1106249423Sdim                     ConstantInt::get(IntptrTy, Mapping.Offset),
1107249423Sdim                     kAsanMappingOffsetName);
1108249423Sdim  // Read the global, otherwise it may be optimized away.
1109249423Sdim  IRB.CreateLoad(asan_mapping_offset, true);
1110239462Sdim
1111249423Sdim  GlobalValue *asan_mapping_scale =
1112249423Sdim      new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1113249423Sdim                         ConstantInt::get(IntptrTy, Mapping.Scale),
1114249423Sdim                         kAsanMappingScaleName);
1115249423Sdim  // Read the global, otherwise it may be optimized away.
1116249423Sdim  IRB.CreateLoad(asan_mapping_scale, true);
1117249423Sdim}
1118234285Sdim
1119249423Sdim// virtual
1120249423Sdimbool AddressSanitizer::doInitialization(Module &M) {
1121249423Sdim  // Initialize the private fields. No one has accessed them before.
1122249423Sdim  TD = getAnalysisIfAvailable<DataLayout>();
1123234285Sdim
1124249423Sdim  if (!TD)
1125249423Sdim    return false;
1126263508Sdim  BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
1127249423Sdim  DynamicallyInitializedGlobals.Init(M);
1128234285Sdim
1129249423Sdim  C = &(M.getContext());
1130249423Sdim  LongSize = TD->getPointerSizeInBits();
1131249423Sdim  IntptrTy = Type::getIntNTy(*C, LongSize);
1132249423Sdim
1133249423Sdim  AsanCtorFunction = Function::Create(
1134249423Sdim      FunctionType::get(Type::getVoidTy(*C), false),
1135249423Sdim      GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1136249423Sdim  BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1137249423Sdim  // call __asan_init in the module ctor.
1138249423Sdim  IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1139249423Sdim  AsanInitFunction = checkInterfaceFunction(
1140249423Sdim      M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1141249423Sdim  AsanInitFunction->setLinkage(Function::ExternalLinkage);
1142249423Sdim  IRB.CreateCall(AsanInitFunction);
1143249423Sdim
1144249423Sdim  Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
1145249423Sdim  emitShadowMapping(M, IRB);
1146249423Sdim
1147234285Sdim  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1148243830Sdim  return true;
1149234285Sdim}
1150234285Sdim
1151234285Sdimbool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1152234285Sdim  // For each NSObject descendant having a +load method, this method is invoked
1153234285Sdim  // by the ObjC runtime before any of the static constructors is called.
1154234285Sdim  // Therefore we need to instrument such methods with a call to __asan_init
1155234285Sdim  // at the beginning in order to initialize our runtime before any access to
1156234285Sdim  // the shadow memory.
1157234285Sdim  // We cannot just ignore these methods, because they may call other
1158234285Sdim  // instrumented functions.
1159234285Sdim  if (F.getName().find(" load]") != std::string::npos) {
1160234285Sdim    IRBuilder<> IRB(F.begin()->begin());
1161234285Sdim    IRB.CreateCall(AsanInitFunction);
1162234285Sdim    return true;
1163234285Sdim  }
1164234285Sdim  return false;
1165234285Sdim}
1166234285Sdim
1167263508Sdim// Poor man's coverage that works with ASan.
1168263508Sdim// We create a Guard boolean variable with the same linkage
1169263508Sdim// as the function and inject this code into the entry block:
1170263508Sdim// if (*Guard) {
1171263508Sdim//    __sanitizer_cov(&F);
1172263508Sdim//    *Guard = 1;
1173263508Sdim// }
1174263508Sdim// The accesses to Guard are atomic. The rest of the logic is
1175263508Sdim// in __sanitizer_cov (it's fine to call it more than once).
1176263508Sdim//
1177263508Sdim// This coverage implementation provides very limited data:
1178263508Sdim// it only tells if a given function was ever executed.
1179263508Sdim// No counters, no per-basic-block or per-edge data.
1180263508Sdim// But for many use cases this is what we need and the added slowdown
1181263508Sdim// is negligible. This simple implementation will probably be obsoleted
1182263508Sdim// by the upcoming Clang-based coverage implementation.
1183263508Sdim// By having it here and now we hope to
1184263508Sdim//  a) get the functionality to users earlier and
1185263508Sdim//  b) collect usage statistics to help improve Clang coverage design.
1186263508Sdimbool AddressSanitizer::InjectCoverage(Function &F) {
1187263508Sdim  if (!ClCoverage) return false;
1188263508Sdim  IRBuilder<> IRB(F.getEntryBlock().getFirstInsertionPt());
1189263508Sdim  Type *Int8Ty = IRB.getInt8Ty();
1190263508Sdim  GlobalVariable *Guard = new GlobalVariable(
1191263508Sdim      *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
1192263508Sdim      Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1193263508Sdim  LoadInst *Load = IRB.CreateLoad(Guard);
1194263508Sdim  Load->setAtomic(Monotonic);
1195263508Sdim  Load->setAlignment(1);
1196263508Sdim  Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
1197263508Sdim  Instruction *Ins = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1198263508Sdim  IRB.SetInsertPoint(Ins);
1199263508Sdim  // We pass &F to __sanitizer_cov. We could avoid this and rely on
1200263508Sdim  // GET_CALLER_PC, but having the PC of the first instruction is just nice.
1201263508Sdim  IRB.CreateCall(AsanCovFunction, IRB.CreatePointerCast(&F, IntptrTy));
1202263508Sdim  StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1203263508Sdim  Store->setAtomic(Monotonic);
1204263508Sdim  Store->setAlignment(1);
1205263508Sdim  return true;
1206263508Sdim}
1207263508Sdim
1208243830Sdimbool AddressSanitizer::runOnFunction(Function &F) {
1209234285Sdim  if (BL->isIn(F)) return false;
1210234285Sdim  if (&F == AsanCtorFunction) return false;
1211249423Sdim  if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1212243830Sdim  DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1213249423Sdim  initializeCallbacks(*F.getParent());
1214234285Sdim
1215249423Sdim  // If needed, insert __asan_init before checking for SanitizeAddress attr.
1216234285Sdim  maybeInsertAsanInitAtFunctionEntry(F);
1217234285Sdim
1218263508Sdim  if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1219243830Sdim    return false;
1220234285Sdim
1221234285Sdim  if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1222234285Sdim    return false;
1223243830Sdim
1224243830Sdim  // We want to instrument every address only once per basic block (unless there
1225243830Sdim  // are calls between uses).
1226234285Sdim  SmallSet<Value*, 16> TempsToInstrument;
1227234285Sdim  SmallVector<Instruction*, 16> ToInstrument;
1228234285Sdim  SmallVector<Instruction*, 8> NoReturnCalls;
1229263508Sdim  int NumAllocas = 0;
1230239462Sdim  bool IsWrite;
1231234285Sdim
1232234285Sdim  // Fill the set of memory operations to instrument.
1233234285Sdim  for (Function::iterator FI = F.begin(), FE = F.end();
1234234285Sdim       FI != FE; ++FI) {
1235234285Sdim    TempsToInstrument.clear();
1236239462Sdim    int NumInsnsPerBB = 0;
1237234285Sdim    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1238234285Sdim         BI != BE; ++BI) {
1239234285Sdim      if (LooksLikeCodeInBug11395(BI)) return false;
1240239462Sdim      if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1241234285Sdim        if (ClOpt && ClOptSameTemp) {
1242234285Sdim          if (!TempsToInstrument.insert(Addr))
1243234285Sdim            continue;  // We've seen this temp in the current BB.
1244234285Sdim        }
1245234285Sdim      } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1246234285Sdim        // ok, take it.
1247234285Sdim      } else {
1248263508Sdim        if (isa<AllocaInst>(BI))
1249263508Sdim          NumAllocas++;
1250249423Sdim        CallSite CS(BI);
1251249423Sdim        if (CS) {
1252234285Sdim          // A call inside BB.
1253234285Sdim          TempsToInstrument.clear();
1254249423Sdim          if (CS.doesNotReturn())
1255249423Sdim            NoReturnCalls.push_back(CS.getInstruction());
1256234285Sdim        }
1257234285Sdim        continue;
1258234285Sdim      }
1259234285Sdim      ToInstrument.push_back(BI);
1260239462Sdim      NumInsnsPerBB++;
1261239462Sdim      if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1262239462Sdim        break;
1263234285Sdim    }
1264234285Sdim  }
1265234285Sdim
1266263508Sdim  Function *UninstrumentedDuplicate = 0;
1267263508Sdim  bool LikelyToInstrument =
1268263508Sdim      !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1269263508Sdim  if (ClKeepUninstrumented && LikelyToInstrument) {
1270263508Sdim    ValueToValueMapTy VMap;
1271263508Sdim    UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1272263508Sdim    UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1273263508Sdim    UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1274263508Sdim    F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1275263508Sdim  }
1276263508Sdim
1277234285Sdim  // Instrument.
1278234285Sdim  int NumInstrumented = 0;
1279234285Sdim  for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1280234285Sdim    Instruction *Inst = ToInstrument[i];
1281234285Sdim    if (ClDebugMin < 0 || ClDebugMax < 0 ||
1282234285Sdim        (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1283239462Sdim      if (isInterestingMemoryAccess(Inst, &IsWrite))
1284243830Sdim        instrumentMop(Inst);
1285234285Sdim      else
1286243830Sdim        instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1287234285Sdim    }
1288234285Sdim    NumInstrumented++;
1289234285Sdim  }
1290234285Sdim
1291249423Sdim  FunctionStackPoisoner FSP(F, *this);
1292249423Sdim  bool ChangedStack = FSP.runOnFunction();
1293234285Sdim
1294234285Sdim  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1295234285Sdim  // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1296234285Sdim  for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1297234285Sdim    Instruction *CI = NoReturnCalls[i];
1298234285Sdim    IRBuilder<> IRB(CI);
1299243830Sdim    IRB.CreateCall(AsanHandleNoReturnFunc);
1300234285Sdim  }
1301234285Sdim
1302263508Sdim  bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1303263508Sdim
1304263508Sdim  if (InjectCoverage(F))
1305263508Sdim    res = true;
1306263508Sdim
1307263508Sdim  DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1308263508Sdim
1309263508Sdim  if (ClKeepUninstrumented) {
1310263508Sdim    if (!res) {
1311263508Sdim      // No instrumentation is done, no need for the duplicate.
1312263508Sdim      if (UninstrumentedDuplicate)
1313263508Sdim        UninstrumentedDuplicate->eraseFromParent();
1314263508Sdim    } else {
1315263508Sdim      // The function was instrumented. We must have the duplicate.
1316263508Sdim      assert(UninstrumentedDuplicate);
1317263508Sdim      UninstrumentedDuplicate->setSection("NOASAN");
1318263508Sdim      assert(!F.hasSection());
1319263508Sdim      F.setSection("ASAN");
1320263508Sdim    }
1321263508Sdim  }
1322263508Sdim
1323263508Sdim  return res;
1324234285Sdim}
1325234285Sdim
1326234285Sdimstatic uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1327234285Sdim  if (ShadowRedzoneSize == 1) return PoisonByte;
1328234285Sdim  if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1329234285Sdim  if (ShadowRedzoneSize == 4)
1330234285Sdim    return (PoisonByte << 24) + (PoisonByte << 16) +
1331234285Sdim        (PoisonByte << 8) + (PoisonByte);
1332234285Sdim  llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
1333234285Sdim}
1334234285Sdim
1335234285Sdimstatic void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1336234285Sdim                                            size_t Size,
1337249423Sdim                                            size_t RZSize,
1338234285Sdim                                            size_t ShadowGranularity,
1339234285Sdim                                            uint8_t Magic) {
1340249423Sdim  for (size_t i = 0; i < RZSize;
1341234285Sdim       i+= ShadowGranularity, Shadow++) {
1342234285Sdim    if (i + ShadowGranularity <= Size) {
1343234285Sdim      *Shadow = 0;  // fully addressable
1344234285Sdim    } else if (i >= Size) {
1345234285Sdim      *Shadow = Magic;  // unaddressable
1346234285Sdim    } else {
1347234285Sdim      *Shadow = Size - i;  // first Size-i bytes are addressable
1348234285Sdim    }
1349234285Sdim  }
1350234285Sdim}
1351234285Sdim
1352249423Sdim// Workaround for bug 11395: we don't want to instrument stack in functions
1353249423Sdim// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1354249423Sdim// FIXME: remove once the bug 11395 is fixed.
1355249423Sdimbool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1356249423Sdim  if (LongSize != 32) return false;
1357249423Sdim  CallInst *CI = dyn_cast<CallInst>(I);
1358249423Sdim  if (!CI || !CI->isInlineAsm()) return false;
1359249423Sdim  if (CI->getNumArgOperands() <= 5) return false;
1360249423Sdim  // We have inline assembly with quite a few arguments.
1361249423Sdim  return true;
1362249423Sdim}
1363249423Sdim
1364249423Sdimvoid FunctionStackPoisoner::initializeCallbacks(Module &M) {
1365249423Sdim  IRBuilder<> IRB(*C);
1366263508Sdim  for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1367263508Sdim    std::string Suffix = itostr(i);
1368263508Sdim    AsanStackMallocFunc[i] = checkInterfaceFunction(
1369263508Sdim        M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1370263508Sdim                              IntptrTy, IntptrTy, NULL));
1371263508Sdim    AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1372263508Sdim        kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1373263508Sdim        IntptrTy, IntptrTy, NULL));
1374263508Sdim  }
1375249423Sdim  AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1376249423Sdim      kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1377249423Sdim  AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1378249423Sdim      kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1379249423Sdim}
1380249423Sdim
1381249423Sdimvoid FunctionStackPoisoner::poisonRedZones(
1382263508Sdim  const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB, Value *ShadowBase,
1383249423Sdim  bool DoPoison) {
1384249423Sdim  size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
1385234285Sdim  assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1386234285Sdim  Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1387234285Sdim  Type *RZPtrTy = PointerType::get(RZTy, 0);
1388234285Sdim
1389234285Sdim  Value *PoisonLeft  = ConstantInt::get(RZTy,
1390234285Sdim    ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1391234285Sdim  Value *PoisonMid   = ConstantInt::get(RZTy,
1392234285Sdim    ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1393234285Sdim  Value *PoisonRight = ConstantInt::get(RZTy,
1394234285Sdim    ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1395234285Sdim
1396234285Sdim  // poison the first red zone.
1397234285Sdim  IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1398234285Sdim
1399234285Sdim  // poison all other red zones.
1400249423Sdim  uint64_t Pos = RedzoneSize();
1401234285Sdim  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1402234285Sdim    AllocaInst *AI = AllocaVec[i];
1403234285Sdim    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1404234285Sdim    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1405249423Sdim    assert(AlignedSize - SizeInBytes < RedzoneSize());
1406234285Sdim    Value *Ptr = NULL;
1407234285Sdim
1408234285Sdim    Pos += AlignedSize;
1409234285Sdim
1410234285Sdim    assert(ShadowBase->getType() == IntptrTy);
1411234285Sdim    if (SizeInBytes < AlignedSize) {
1412234285Sdim      // Poison the partial redzone at right
1413234285Sdim      Ptr = IRB.CreateAdd(
1414234285Sdim          ShadowBase, ConstantInt::get(IntptrTy,
1415249423Sdim                                       (Pos >> Mapping.Scale) - ShadowRZSize));
1416249423Sdim      size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1417234285Sdim      uint32_t Poison = 0;
1418234285Sdim      if (DoPoison) {
1419234285Sdim        PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1420249423Sdim                                        RedzoneSize(),
1421249423Sdim                                        1ULL << Mapping.Scale,
1422234285Sdim                                        kAsanStackPartialRedzoneMagic);
1423263508Sdim        Poison =
1424263508Sdim            ASan.TD->isLittleEndian()
1425263508Sdim                ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1426263508Sdim                : support::endian::byte_swap<uint32_t, support::big>(Poison);
1427234285Sdim      }
1428234285Sdim      Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1429234285Sdim      IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1430234285Sdim    }
1431234285Sdim
1432234285Sdim    // Poison the full redzone at right.
1433234285Sdim    Ptr = IRB.CreateAdd(ShadowBase,
1434249423Sdim                        ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
1435249423Sdim    bool LastAlloca = (i == AllocaVec.size() - 1);
1436249423Sdim    Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
1437234285Sdim    IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1438234285Sdim
1439249423Sdim    Pos += RedzoneSize();
1440234285Sdim  }
1441234285Sdim}
1442234285Sdim
1443263508Sdim// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1444263508Sdim// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1445263508Sdimstatic int StackMallocSizeClass(uint64_t LocalStackSize) {
1446263508Sdim  assert(LocalStackSize <= kMaxStackMallocSize);
1447263508Sdim  uint64_t MaxSize = kMinStackMallocSize;
1448263508Sdim  for (int i = 0; ; i++, MaxSize *= 2)
1449263508Sdim    if (LocalStackSize <= MaxSize)
1450263508Sdim      return i;
1451263508Sdim  llvm_unreachable("impossible LocalStackSize");
1452263508Sdim}
1453263508Sdim
1454263508Sdim// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1455263508Sdim// We can not use MemSet intrinsic because it may end up calling the actual
1456263508Sdim// memset. Size is a multiple of 8.
1457263508Sdim// Currently this generates 8-byte stores on x86_64; it may be better to
1458263508Sdim// generate wider stores.
1459263508Sdimvoid FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1460263508Sdim    IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1461263508Sdim  assert(!(Size % 8));
1462263508Sdim  assert(kAsanStackAfterReturnMagic == 0xf5);
1463263508Sdim  for (int i = 0; i < Size; i += 8) {
1464263508Sdim    Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1465263508Sdim    IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1466263508Sdim                    IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1467263508Sdim  }
1468263508Sdim}
1469263508Sdim
1470249423Sdimvoid FunctionStackPoisoner::poisonStack() {
1471249423Sdim  uint64_t LocalStackSize = TotalStackSize +
1472249423Sdim                            (AllocaVec.size() + 1) * RedzoneSize();
1473234285Sdim
1474249423Sdim  bool DoStackMalloc = ASan.CheckUseAfterReturn
1475234285Sdim      && LocalStackSize <= kMaxStackMallocSize;
1476263508Sdim  int StackMallocIdx = -1;
1477234285Sdim
1478249423Sdim  assert(AllocaVec.size() > 0);
1479234285Sdim  Instruction *InsBefore = AllocaVec[0];
1480234285Sdim  IRBuilder<> IRB(InsBefore);
1481234285Sdim
1482234285Sdim
1483234285Sdim  Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1484234285Sdim  AllocaInst *MyAlloca =
1485234285Sdim      new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1486249423Sdim  if (ClRealignStack && StackAlignment < RedzoneSize())
1487249423Sdim    StackAlignment = RedzoneSize();
1488249423Sdim  MyAlloca->setAlignment(StackAlignment);
1489234285Sdim  assert(MyAlloca->isStaticAlloca());
1490234285Sdim  Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1491234285Sdim  Value *LocalStackBase = OrigStackBase;
1492234285Sdim
1493234285Sdim  if (DoStackMalloc) {
1494263508Sdim    // LocalStackBase = OrigStackBase
1495263508Sdim    // if (__asan_option_detect_stack_use_after_return)
1496263508Sdim    //   LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1497263508Sdim    StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1498263508Sdim    assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1499263508Sdim    Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1500263508Sdim        kAsanOptionDetectUAR, IRB.getInt32Ty());
1501263508Sdim    Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1502263508Sdim                                  Constant::getNullValue(IRB.getInt32Ty()));
1503263508Sdim    Instruction *Term =
1504263508Sdim        SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1505263508Sdim    BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1506263508Sdim    IRBuilder<> IRBIf(Term);
1507263508Sdim    LocalStackBase = IRBIf.CreateCall2(
1508263508Sdim        AsanStackMallocFunc[StackMallocIdx],
1509234285Sdim        ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1510263508Sdim    BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1511263508Sdim    IRB.SetInsertPoint(InsBefore);
1512263508Sdim    PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1513263508Sdim    Phi->addIncoming(OrigStackBase, CmpBlock);
1514263508Sdim    Phi->addIncoming(LocalStackBase, SetBlock);
1515263508Sdim    LocalStackBase = Phi;
1516234285Sdim  }
1517234285Sdim
1518249423Sdim  // This string will be parsed by the run-time (DescribeAddressIfStack).
1519234285Sdim  SmallString<2048> StackDescriptionStorage;
1520234285Sdim  raw_svector_ostream StackDescription(StackDescriptionStorage);
1521249423Sdim  StackDescription << AllocaVec.size() << " ";
1522234285Sdim
1523249423Sdim  // Insert poison calls for lifetime intrinsics for alloca.
1524249423Sdim  bool HavePoisonedAllocas = false;
1525249423Sdim  for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1526249423Sdim    const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1527263508Sdim    assert(APC.InsBefore);
1528263508Sdim    assert(APC.AI);
1529263508Sdim    IRBuilder<> IRB(APC.InsBefore);
1530263508Sdim    poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1531249423Sdim    HavePoisonedAllocas |= APC.DoPoison;
1532249423Sdim  }
1533249423Sdim
1534249423Sdim  uint64_t Pos = RedzoneSize();
1535234285Sdim  // Replace Alloca instructions with base+offset.
1536234285Sdim  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1537234285Sdim    AllocaInst *AI = AllocaVec[i];
1538234285Sdim    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1539234285Sdim    StringRef Name = AI->getName();
1540234285Sdim    StackDescription << Pos << " " << SizeInBytes << " "
1541234285Sdim                     << Name.size() << " " << Name << " ";
1542234285Sdim    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1543249423Sdim    assert((AlignedSize % RedzoneSize()) == 0);
1544249423Sdim    Value *NewAllocaPtr = IRB.CreateIntToPtr(
1545234285Sdim            IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1546249423Sdim            AI->getType());
1547249423Sdim    replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1548249423Sdim    AI->replaceAllUsesWith(NewAllocaPtr);
1549249423Sdim    Pos += AlignedSize + RedzoneSize();
1550234285Sdim  }
1551234285Sdim  assert(Pos == LocalStackSize);
1552234285Sdim
1553249423Sdim  // The left-most redzone has enough space for at least 4 pointers.
1554249423Sdim  // Write the Magic value to redzone[0].
1555234285Sdim  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1556234285Sdim  IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1557234285Sdim                  BasePlus0);
1558249423Sdim  // Write the frame description constant to redzone[1].
1559249423Sdim  Value *BasePlus1 = IRB.CreateIntToPtr(
1560249423Sdim    IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1561249423Sdim    IntptrPtrTy);
1562243830Sdim  GlobalVariable *StackDescriptionGlobal =
1563243830Sdim      createPrivateGlobalForString(*F.getParent(), StackDescription.str());
1564249423Sdim  Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1565249423Sdim                                             IntptrTy);
1566234285Sdim  IRB.CreateStore(Description, BasePlus1);
1567249423Sdim  // Write the PC to redzone[2].
1568249423Sdim  Value *BasePlus2 = IRB.CreateIntToPtr(
1569249423Sdim    IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1570249423Sdim                                                   2 * ASan.LongSize/8)),
1571249423Sdim    IntptrPtrTy);
1572249423Sdim  IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1573234285Sdim
1574234285Sdim  // Poison the stack redzones at the entry.
1575249423Sdim  Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1576249423Sdim  poisonRedZones(AllocaVec, IRB, ShadowBase, true);
1577234285Sdim
1578234285Sdim  // Unpoison the stack before all ret instructions.
1579234285Sdim  for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1580234285Sdim    Instruction *Ret = RetVec[i];
1581234285Sdim    IRBuilder<> IRBRet(Ret);
1582234285Sdim    // Mark the current frame as retired.
1583234285Sdim    IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1584234285Sdim                       BasePlus0);
1585234285Sdim    // Unpoison the stack.
1586249423Sdim    poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
1587234285Sdim    if (DoStackMalloc) {
1588263508Sdim      assert(StackMallocIdx >= 0);
1589249423Sdim      // In use-after-return mode, mark the whole stack frame unaddressable.
1590263508Sdim      if (StackMallocIdx <= 4) {
1591263508Sdim        // For small sizes inline the whole thing:
1592263508Sdim        // if LocalStackBase != OrigStackBase:
1593263508Sdim        //     memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1594263508Sdim        //     **SavedFlagPtr(LocalStackBase) = 0
1595263508Sdim        // FIXME: if LocalStackBase != OrigStackBase don't call poisonRedZones.
1596263508Sdim        Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1597263508Sdim        TerminatorInst *PoisonTerm =
1598263508Sdim            SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1599263508Sdim        IRBuilder<> IRBPoison(PoisonTerm);
1600263508Sdim        int ClassSize = kMinStackMallocSize << StackMallocIdx;
1601263508Sdim        SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1602263508Sdim                                           ClassSize >> Mapping.Scale);
1603263508Sdim        Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1604263508Sdim            LocalStackBase,
1605263508Sdim            ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1606263508Sdim        Value *SavedFlagPtr = IRBPoison.CreateLoad(
1607263508Sdim            IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1608263508Sdim        IRBPoison.CreateStore(
1609263508Sdim            Constant::getNullValue(IRBPoison.getInt8Ty()),
1610263508Sdim            IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1611263508Sdim      } else {
1612263508Sdim        // For larger frames call __asan_stack_free_*.
1613263508Sdim        IRBRet.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1614263508Sdim                           ConstantInt::get(IntptrTy, LocalStackSize),
1615263508Sdim                           OrigStackBase);
1616263508Sdim      }
1617249423Sdim    } else if (HavePoisonedAllocas) {
1618249423Sdim      // If we poisoned some allocas in llvm.lifetime analysis,
1619249423Sdim      // unpoison whole stack frame now.
1620249423Sdim      assert(LocalStackBase == OrigStackBase);
1621249423Sdim      poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1622234285Sdim    }
1623234285Sdim  }
1624234285Sdim
1625243830Sdim  // We are done. Remove the old unused alloca instructions.
1626243830Sdim  for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1627243830Sdim    AllocaVec[i]->eraseFromParent();
1628249423Sdim}
1629243830Sdim
1630249423Sdimvoid FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1631263508Sdim                                         IRBuilder<> &IRB, bool DoPoison) {
1632249423Sdim  // For now just insert the call to ASan runtime.
1633249423Sdim  Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1634249423Sdim  Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1635249423Sdim  IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1636249423Sdim                           : AsanUnpoisonStackMemoryFunc,
1637249423Sdim                  AddrArg, SizeArg);
1638249423Sdim}
1639249423Sdim
1640249423Sdim// Handling llvm.lifetime intrinsics for a given %alloca:
1641249423Sdim// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1642249423Sdim// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1643249423Sdim//     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1644249423Sdim//     could be poisoned by previous llvm.lifetime.end instruction, as the
1645249423Sdim//     variable may go in and out of scope several times, e.g. in loops).
1646249423Sdim// (3) if we poisoned at least one %alloca in a function,
1647249423Sdim//     unpoison the whole stack frame at function exit.
1648249423Sdim
1649249423SdimAllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1650249423Sdim  if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1651249423Sdim    // We're intested only in allocas we can handle.
1652249423Sdim    return isInterestingAlloca(*AI) ? AI : 0;
1653249423Sdim  // See if we've already calculated (or started to calculate) alloca for a
1654249423Sdim  // given value.
1655249423Sdim  AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1656249423Sdim  if (I != AllocaForValue.end())
1657249423Sdim    return I->second;
1658249423Sdim  // Store 0 while we're calculating alloca for value V to avoid
1659249423Sdim  // infinite recursion if the value references itself.
1660249423Sdim  AllocaForValue[V] = 0;
1661249423Sdim  AllocaInst *Res = 0;
1662249423Sdim  if (CastInst *CI = dyn_cast<CastInst>(V))
1663249423Sdim    Res = findAllocaForValue(CI->getOperand(0));
1664249423Sdim  else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1665249423Sdim    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1666249423Sdim      Value *IncValue = PN->getIncomingValue(i);
1667249423Sdim      // Allow self-referencing phi-nodes.
1668249423Sdim      if (IncValue == PN) continue;
1669249423Sdim      AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1670249423Sdim      // AI for incoming values should exist and should all be equal.
1671249423Sdim      if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1672249423Sdim        return 0;
1673249423Sdim      Res = IncValueAI;
1674249423Sdim    }
1675234285Sdim  }
1676249423Sdim  if (Res != 0)
1677249423Sdim    AllocaForValue[V] = Res;
1678249423Sdim  return Res;
1679234285Sdim}
1680