AddressSanitizer.cpp revision 349f14c72cbcd3c50091d20a874967aca5f2f746
1800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
3800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//                     The LLVM Compiler Infrastructure
4800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
5800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This file is distributed under the University of Illinois Open Source
6800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// License. See LICENSE.TXT for details.
7800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
8800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===----------------------------------------------------------------------===//
9800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
10800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This file is a part of AddressSanitizer, an address sanity checker.
11800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Details of the algorithm:
12800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
14800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===----------------------------------------------------------------------===//
15800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
16800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#define DEBUG_TYPE "asan"
17800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
18a1c45044099cf7fb4a072f1326f164706d5bb2e2Kostya Serebryany#include "FunctionBlackList.h"
1906cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Function.h"
2006cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/IRBuilder.h"
2106cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/IntrinsicInst.h"
2206cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/LLVMContext.h"
2306cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Module.h"
2406cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Type.h"
25800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/ArrayRef.h"
26800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/OwningPtr.h"
27800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallSet.h"
28800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallString.h"
29800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallVector.h"
30800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/StringExtras.h"
3106fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov#include "llvm/ADT/Triple.h"
32800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/CommandLine.h"
33800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/DataTypes.h"
34800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/Debug.h"
35800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/raw_ostream.h"
36800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/system_error.h"
37800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Target/TargetData.h"
38800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Target/TargetMachine.h"
39800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Instrumentation.h"
40800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/BasicBlockUtils.h"
41800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/ModuleUtils.h"
42800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
43800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include <string>
44800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include <algorithm>
45800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
46800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyusing namespace llvm;
47800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
48800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowScale = 3;
49800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
50800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
5106fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanovstatic const uint64_t kDefaultShadowOffsetAndroid = 0;
52800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
53800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const size_t kMaxStackMallocSize = 1 << 16;  // 64K
54800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
55800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
56800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
57800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanModuleCtorName = "asan.module_ctor";
587bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanModuleDtorName = "asan.module_dtor";
597bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const int   kAsanCtorAndCtorPriority = 1;
60800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanReportErrorTemplate = "__asan_report_";
61800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanRegisterGlobalsName = "__asan_register_globals";
627bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
63800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanInitName = "__asan_init";
6495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryanystatic const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
65800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingOffsetName = "__asan_mapping_offset";
66800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingScaleName = "__asan_mapping_scale";
67800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackMallocName = "__asan_stack_malloc";
68800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackFreeName = "__asan_stack_free";
69800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
70800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackLeftRedzoneMagic = 0xf1;
71800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackMidRedzoneMagic = 0xf2;
72800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackRightRedzoneMagic = 0xf3;
73800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackPartialRedzoneMagic = 0xf4;
74800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
75800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Command-line flags.
76800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
77800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no-]asan-reads.
78800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
79800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
80800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
81800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
82e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
83e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
84e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::Hidden, cl::init(true));
85324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// This flags limits the number of instructions to be instrumented
86324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// in any given BB. Normally, this should be set to unlimited (INT_MAX),
87324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
88324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// set it to 10000.
89324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryanystatic cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
90324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::init(10000),
91324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::desc("maximal number of instructions to instrument in any given BB"),
92324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::Hidden);
93800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-stack.
94800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClStack("asan-stack",
95800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
96800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-use-after-return.
97800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
98800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
99800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-globals.
100800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClGlobals("asan-globals",
101800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
102800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClMemIntrin("asan-memintrin",
103800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
104800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -fasan-blacklist.
105800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<std::string>  ClBlackListFile("asan-blacklist",
106800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("File containing the list of functions to ignore "
107800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                "during instrumentation"), cl::Hidden);
108800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
109800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// These flags allow to change the shadow mapping.
110800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// The shadow mapping looks like
111800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//    Shadow = (Mem >> scale) + (1 << offset_log)
112800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingScale("asan-mapping-scale",
113800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
114800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
115800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
116800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
117800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Optimization flags. Not user visible, used mostly for testing
118800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// and benchmarking the tool.
119800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOpt("asan-opt",
120800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
121800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
122800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Instrument the same temp just once"), cl::Hidden,
123800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::init(true));
124800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptGlobals("asan-opt-globals",
125800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
126800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
127800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Debug flags.
128800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
129800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            cl::init(0));
130800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
131800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                 cl::Hidden, cl::init(0));
132800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<std::string> ClDebugFunc("asan-debug-func",
133800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        cl::Hidden, cl::desc("Debug func"));
134800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
135800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
136800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
137800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
138800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
139800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanynamespace {
140800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
141800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany/// AddressSanitizer: instrument the code in module to find memory bugs.
142800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystruct AddressSanitizer : public ModulePass {
143800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AddressSanitizer();
14425878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko  virtual const char *getPassName() const;
145800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  void instrumentMop(Instruction *I);
146800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
147800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         Value *Addr, uint32_t TypeSize, bool IsWrite);
148800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *generateCrashCode(IRBuilder<> &IRB, Value *Addr,
149800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                 bool IsWrite, uint32_t TypeSize);
150800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool instrumentMemIntrinsic(MemIntrinsic *MI);
151800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
152800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                  Value *Size,
153800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Instruction *InsertBefore, bool IsWrite);
154800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
155800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool handleFunction(Module &M, Function &F);
156a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  bool maybeInsertAsanInitAtFunctionEntry(Function &F);
157800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool poisonStackInFunction(Module &M, Function &F);
158800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  virtual bool runOnModule(Module &M);
159800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool insertGlobalRedzones(Module &M);
160800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  static char ID;  // Pass identification, replacement for typeid
161800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
162800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany private:
163800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
164800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
165800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = AI->getAllocatedType();
166d8313be41031e4d768f5b38199904d4debff88cdEvgeniy Stepanov    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
167800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return SizeInBytes;
168800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
169800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAlignedSize(uint64_t SizeInBytes) {
170800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return ((SizeInBytes + RedzoneSize - 1)
171800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            / RedzoneSize) * RedzoneSize;
172800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
173800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAlignedAllocaSize(AllocaInst *AI) {
174800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
175800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return getAlignedSize(SizeInBytes);
176800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
177800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
17855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *checkInterfaceFunction(Constant *FuncOrBitcast);
179800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
180800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                   Value *ShadowBase, bool DoPoison);
1815a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  bool LooksLikeCodeInBug11395(Instruction *I);
182800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
183800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Module      *CurrentModule;
184800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LLVMContext *C;
185800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TargetData *TD;
186800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t MappingOffset;
187800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int MappingScale;
188800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t RedzoneSize;
189800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int LongSize;
190800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrTy;
191800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrPtrTy;
192800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanCtorFunction;
193800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanInitFunction;
194800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *CtorInsertBefore;
195a1c45044099cf7fb4a072f1326f164706d5bb2e2Kostya Serebryany  OwningPtr<FunctionBlackList> BL;
196800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany};
197800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}  // namespace
198800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
199800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanychar AddressSanitizer::ID = 0;
200800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyINITIALIZE_PASS(AddressSanitizer, "asan",
201800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
202800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    false, false)
203800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyAddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
204800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyModulePass *llvm::createAddressSanitizerPass() {
205800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return new AddressSanitizer();
206800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
207800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
20825878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenkoconst char *AddressSanitizer::getPassName() const {
20925878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko  return "AddressSanitizer";
21025878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko}
21125878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko
212800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Create a constant for Str so that we can pass it to the run-time lib.
213800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
21418c7f80b3e83ab584bd8572695a3cde8bafd9d3cChris Lattner  Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
215800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return new GlobalVariable(M, StrConst->getType(), true,
216800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            GlobalValue::PrivateLinkage, StrConst, "");
217800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
218800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
219800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Split the basic block and insert an if-then code.
220800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Before:
221800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Head
22256139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany//   Cmp
223800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Tail
224800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// After:
225800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Head
226800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   if (Cmp)
22756139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany//     ThenBlock
228800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Tail
229800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
23056139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany// Returns the ThenBlock's terminator.
23156139bc493790612ee6281630678e293be6b2eb2Kostya Serebryanystatic BranchInst *splitBlockAndInsertIfThen(Value *Cmp) {
23256139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany  Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode();
233800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasicBlock *Head = SplitBefore->getParent();
234349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
235800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TerminatorInst *HeadOldTerm = Head->getTerminator();
236349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  LLVMContext &C = Head->getParent()->getParent()->getContext();
237349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent());
238349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  BranchInst *HeadNewTerm =
239349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth    BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
240349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
241349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth
242349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  BranchInst *CheckTerm = BranchInst::Create(Tail, ThenBlock);
243349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  return CheckTerm;
244800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
245800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
246800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyValue *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
247800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Shadow >> scale
248800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Shadow = IRB.CreateLShr(Shadow, MappingScale);
249800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (MappingOffset == 0)
250800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return Shadow;
251800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (Shadow >> scale) | offset
252800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
253800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                               MappingOffset));
254800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
255800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
256800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyvoid AddressSanitizer::instrumentMemIntrinsicParam(Instruction *OrigIns,
257800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
258800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the first byte.
259800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
260800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
261800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
262800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
263800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the last byte.
264800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
265800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
266800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *SizeMinusOne = IRB.CreateSub(
267800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Size, ConstantInt::get(Size->getType(), 1));
268800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
269800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
270800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
271800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
272800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
273800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
274800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
275800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Instrument memset/memmove/memcpy
276800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
277800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Dst = MI->getDest();
278800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
279800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Src = MemTran ? MemTran->getSource() : NULL;
280800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Length = MI->getLength();
281800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
282800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Constant *ConstLength = dyn_cast<Constant>(Length);
283800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsertBefore = MI;
284800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ConstLength) {
285800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ConstLength->isNullValue()) return false;
286800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  } else {
287800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // The size is not a constant so it could be zero -- check at run-time.
288800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
289800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
290800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Cmp = IRB.CreateICmpNE(Length,
29156139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany                                  Constant::getNullValue(Length->getType()));
29256139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany    InsertBefore = splitBlockAndInsertIfThen(Cmp);
293800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
294800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
295800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
296800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (Src)
297800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
298800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
299800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
300800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
301e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// If I is an interesting memory access, return the PointerOperand
302e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// and set IsWrite. Otherwise return NULL.
303e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
304800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
305e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentReads) return NULL;
306e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = false;
307800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return LI->getPointerOperand();
308800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
309e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
310e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentWrites) return NULL;
311e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
312e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return SI->getPointerOperand();
313e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
314e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
315e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
316e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
317e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return RMW->getPointerOperand();
318e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
319e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
320e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
321e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
322e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return XCHG->getPointerOperand();
323e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
324e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  return NULL;
325800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
326800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
327800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyvoid AddressSanitizer::instrumentMop(Instruction *I) {
328e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  bool IsWrite;
329e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
330e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  assert(Addr);
331800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
332800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // We are accessing a global scalar variable. Nothing to catch here.
333800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return;
334800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
335800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigPtrTy = Addr->getType();
336800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
337800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
338800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(OrigTy->isSized());
339800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
340800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
341800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (TypeSize != 8  && TypeSize != 16 &&
342800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
343800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Ignore all unusual sizes.
344800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return;
345800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
346800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
347800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(I);
348800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
349800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
350800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
35155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// Validate the result of Module::getOrInsertFunction called for an interface
35255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// function of AddressSanitizer. If the instrumented module defines a function
35355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// with the same name, their prototypes must match, otherwise
35455cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// getOrInsertFunction returns a bitcast.
35555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander PotapenkoFunction *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
35655cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
35755cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  FuncOrBitcast->dump();
35855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  report_fatal_error("trying to redefine an AddressSanitizer "
35955cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko                     "interface function");
36055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko}
36155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko
362800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyInstruction *AddressSanitizer::generateCrashCode(
363800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> &IRB, Value *Addr, bool IsWrite, uint32_t TypeSize) {
3643c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  // IsWrite and TypeSize are encoded in the function name.
3653c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  std::string FunctionName = std::string(kAsanReportErrorTemplate) +
3663c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany      (IsWrite ? "store" : "load") + itostr(TypeSize / 8);
3673c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  Value *ReportWarningFunc = CurrentModule->getOrInsertFunction(
3683c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany      FunctionName, IRB.getVoidTy(), IntptrTy, NULL);
3693c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  CallInst *Call = IRB.CreateCall(ReportWarningFunc, Addr);
3703c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  Call->setDoesNotReturn();
3713c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  return Call;
372800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
373800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
374800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyvoid AddressSanitizer::instrumentAddress(Instruction *OrigIns,
375800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         IRBuilder<> &IRB, Value *Addr,
376800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         uint32_t TypeSize, bool IsWrite) {
377800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
378800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
379800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowTy  = IntegerType::get(
380800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *C, std::max(8U, TypeSize >> MappingScale));
381800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
382800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowPtr = memToShadow(AddrLong, IRB);
383800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *CmpVal = Constant::getNullValue(ShadowTy);
384800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowValue = IRB.CreateLoad(
385800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
386800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
387800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
388800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
38956139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany  Instruction *CheckTerm = splitBlockAndInsertIfThen(Cmp);
390349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  IRBuilder<> IRB2(CheckTerm);
391800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
392800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t Granularity = 1 << MappingScale;
393800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (TypeSize < 8 * Granularity) {
394800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Addr & (Granularity - 1)
395349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth    Value *LastAccessedByte = IRB2.CreateAnd(
396800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
397800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // (Addr & (Granularity - 1)) + size - 1
3983f119989c3839c98b20bf6ea00c2ccc95aacff69Kostya Serebryany    if (TypeSize / 8 > 1)
399349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth      LastAccessedByte = IRB2.CreateAdd(
4003f119989c3839c98b20bf6ea00c2ccc95aacff69Kostya Serebryany          LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
401800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
402349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth    LastAccessedByte = IRB2.CreateIntCast(
403800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        LastAccessedByte, IRB.getInt8Ty(), false);
404800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
405349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth    Value *Cmp2 = IRB2.CreateICmpSGE(LastAccessedByte, ShadowValue);
406800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
40756139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany    CheckTerm = splitBlockAndInsertIfThen(Cmp2);
408800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
409800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
410349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  IRBuilder<> IRB1(CheckTerm);
411349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  Instruction *Crash = generateCrashCode(IRB1, AddrLong, IsWrite, TypeSize);
412800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Crash->setDebugLoc(OrigIns->getDebugLoc());
413cc1d856d8e8e11407b3c6c1d08768f77c3722e38Kostya Serebryany  ReplaceInstWithInst(CheckTerm, new UnreachableInst(*C));
414800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
415800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
416800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This function replaces all global variables with new variables that have
417800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// trailing redzones. It also creates a function that poisons
418800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// redzones and inserts this function into llvm.global_ctors.
419800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::insertGlobalRedzones(Module &M) {
420800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<GlobalVariable *, 16> GlobalsToChange;
421800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
422800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
423800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       E = M.getGlobalList().end(); G != E; ++G) {
424800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = cast<PointerType>(G->getType())->getElementType();
425800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << "GLOBAL: " << *G);
426800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
427800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (!Ty->isSized()) continue;
428800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (!G->hasInitializer()) continue;
4297cf2a04361e8613264498e50babe52d65c070473Kostya Serebryany    // Touch only those globals that will not be defined in other modules.
4307cf2a04361e8613264498e50babe52d65c070473Kostya Serebryany    // Don't handle ODR type linkages since other modules may be built w/o asan.
4312e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany    if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
4322e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany        G->getLinkage() != GlobalVariable::PrivateLinkage &&
4332e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany        G->getLinkage() != GlobalVariable::InternalLinkage)
434800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      continue;
435d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    // Two problems with thread-locals:
436d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    //   - The address of the main thread's copy can't be computed at link-time.
437d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    //   - Need to poison all copies, not just the main thread's one.
438d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    if (G->isThreadLocal())
439d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany      continue;
440800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // For now, just ignore this Alloca if the alignment is large.
441800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (G->getAlignment() > RedzoneSize) continue;
442800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
443800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Ignore all the globals with the names starting with "\01L_OBJC_".
444800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Many of those are put into the .cstring section. The linker compresses
445800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // that section by removing the spare \0s after the string terminator, so
446800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // our redzones get broken.
447800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if ((G->getName().find("\01L_OBJC_") == 0) ||
448800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (G->getName().find("\01l_OBJC_") == 0)) {
449800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
450800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      continue;
451800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
452800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
453800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (G->hasSection()) {
454800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      StringRef Section(G->getSection());
4558375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Ignore the globals from the __OBJC section. The ObjC runtime assumes
4568375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
4578375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // them.
458800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if ((Section.find("__OBJC,") == 0) ||
459800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          (Section.find("__DATA, __objc_") == 0)) {
460800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
461800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
462800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
4638375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
4648375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Constant CFString instances are compiled in the following way:
4658375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //  -- the string buffer is emitted into
4668375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //     __TEXT,__cstring,cstring_literals
4678375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //  -- the constant NSConstantString structure referencing that buffer
4688375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //     is placed into __DATA,__cfstring
4698375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Therefore there's no point in placing redzones into __DATA,__cfstring.
4708375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Moreover, it causes the linker to crash on OS X 10.7
4718375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      if (Section.find("__DATA,__cfstring") == 0) {
4728375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko        DEBUG(dbgs() << "Ignoring CFString: " << *G);
4738375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko        continue;
4748375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      }
475800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
476800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
477800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalsToChange.push_back(G);
478800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
479800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
480800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t n = GlobalsToChange.size();
481800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (n == 0) return false;
482800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
483800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // A global is described by a structure
484800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t beg;
485800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size;
486800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size_with_redzone;
487800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   const char *name;
488800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We initialize an array of such structures and pass it to a run-time call.
489800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
490800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                               IntptrTy, IntptrTy, NULL);
491800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Constant *, 16> Initializers(n);
492800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
493800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
494800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
495800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < n; i++) {
496800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *G = GlobalsToChange[i];
497800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PointerType *PtrTy = cast<PointerType>(G->getType());
498800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = PtrTy->getElementType();
499208a4ff2b56f453910bb817540f34b8169f7702aKostya Serebryany    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
500800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t RightRedzoneSize = RedzoneSize +
501800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (RedzoneSize - (SizeInBytes % RedzoneSize));
502800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
503800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
504800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
505800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Constant *NewInitializer = ConstantStruct::get(
506800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NewTy, G->getInitializer(),
507800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Constant::getNullValue(RightRedZoneTy), NULL);
508800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
509a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    SmallString<2048> DescriptionOfGlobal = G->getName();
510a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += " (";
511a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += M.getModuleIdentifier();
512a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += ")";
513a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
514800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
515800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Create a new global variable with enough space for a redzone.
516800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *NewGlobal = new GlobalVariable(
517800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        M, NewTy, G->isConstant(), G->getLinkage(),
518ce718ff9f42c7da092eaa01dd0242e8d5ba84713Hans Wennborg        NewInitializer, "", G, G->getThreadLocalMode());
519800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->copyAttributesFrom(G);
520800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->setAlignment(RedzoneSize);
521800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
522800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Indices2[2];
523800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[0] = IRB.getInt32(0);
524800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[1] = IRB.getInt32(0);
525800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
526800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->replaceAllUsesWith(
527f1639abf1aaba1448f719f595156cd0f4cd560ccKostya Serebryany        ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
528800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->takeName(G);
529800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->eraseFromParent();
530800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
531800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Initializers[i] = ConstantStruct::get(
532800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        GlobalStructTy,
533800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
534800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes),
535800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
536800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(Name, IntptrTy),
537800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NULL);
538800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
539800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
540800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
541800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
542800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  GlobalVariable *AllGlobals = new GlobalVariable(
543800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
544800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
545800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
54655cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
547800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
548800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
549800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
550800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall2(AsanRegisterGlobals,
551800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  IRB.CreatePointerCast(AllGlobals, IntptrTy),
552800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  ConstantInt::get(IntptrTy, n));
553800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
5547bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // We also need to unregister globals at the end, e.g. when a shared library
5557bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // gets closed.
5567bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  Function *AsanDtorFunction = Function::Create(
5577bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
5587bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
5597bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
5607bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
56155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanUnregisterGlobals =
56255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko      checkInterfaceFunction(M.getOrInsertFunction(
56355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          kAsanUnregisterGlobalsName,
56455cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
5657bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
5667bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
5677bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
5687bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       IRB.CreatePointerCast(AllGlobals, IntptrTy),
5697bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       ConstantInt::get(IntptrTy, n));
5707bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
5717bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
572800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << M);
573800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
574800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
575800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
576800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// virtual
577800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::runOnModule(Module &M) {
578800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Initialize the private fields. No one has accessed them before.
579800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TD = getAnalysisIfAvailable<TargetData>();
580800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!TD)
581800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
582a1c45044099cf7fb4a072f1326f164706d5bb2e2Kostya Serebryany  BL.reset(new FunctionBlackList(ClBlackListFile));
583800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
584800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  CurrentModule = &M;
585800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  C = &(M.getContext());
586800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LongSize = TD->getPointerSizeInBits();
587800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrTy = Type::getIntNTy(*C, LongSize);
588800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrPtrTy = PointerType::get(IntptrTy, 0);
589800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
590800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanCtorFunction = Function::Create(
591800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
592800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
593800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
594800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
595800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
596800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // call __asan_init in the module ctor.
597800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
59855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  AsanInitFunction = checkInterfaceFunction(
599800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
600800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanInitFunction->setLinkage(Function::ExternalLinkage);
601800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall(AsanInitFunction);
602800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
60306fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  llvm::Triple targetTriple(M.getTargetTriple());
60406fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
60506fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov
60606fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
60706fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov    (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
608800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClMappingOffsetLog >= 0) {
609800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClMappingOffsetLog == 0) {
610800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // special case
611800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 0;
612800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
613800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 1ULL << ClMappingOffsetLog;
614800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
615800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
616800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MappingScale = kDefaultShadowScale;
617800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClMappingScale) {
618800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    MappingScale = ClMappingScale;
619800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
620800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Redzone used for stack and globals is at least 32 bytes.
621800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
622800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  RedzoneSize = std::max(32, (int)(1 << MappingScale));
623800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
624800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool Res = false;
625800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
626800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClGlobals)
627800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Res |= insertGlobalRedzones(M);
628800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6298c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingOffsetLog >= 0) {
6308c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Tell the run-time the current values of mapping offset and scale.
6318c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_offset =
6328c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
6338c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       ConstantInt::get(IntptrTy, MappingOffset),
6348c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       kAsanMappingOffsetName);
6358c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
6368c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_offset, true);
6378c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
6388c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingScale) {
6398c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_scale =
6408c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
6418c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                           ConstantInt::get(IntptrTy, MappingScale),
6428c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                           kAsanMappingScaleName);
6438c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
6448c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_scale, true);
6458c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
646800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
647800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
648800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
649800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (F->isDeclaration()) continue;
650800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Res |= handleFunction(M, *F);
651800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
652800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6537bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
6549b02741d2284d9516a59666c211fe1f57e8803adKostya Serebryany
655800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return Res;
656800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
657800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
658a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryanybool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
659a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // For each NSObject descendant having a +load method, this method is invoked
660a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // by the ObjC runtime before any of the static constructors is called.
661a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // Therefore we need to instrument such methods with a call to __asan_init
662a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // at the beginning in order to initialize our runtime before any access to
663a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // the shadow memory.
664a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // We cannot just ignore these methods, because they may call other
665a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // instrumented functions.
666a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  if (F.getName().find(" load]") != std::string::npos) {
667a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRBuilder<> IRB(F.begin()->begin());
668a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRB.CreateCall(AsanInitFunction);
669a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    return true;
670a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  }
671a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  return false;
672a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany}
673a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
674800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::handleFunction(Module &M, Function &F) {
675800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (BL->isIn(F)) return false;
676800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (&F == AsanCtorFunction) return false;
677a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
678a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // If needed, insert __asan_init before checking for AddressSafety attr.
679a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  maybeInsertAsanInitAtFunctionEntry(F);
680a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
6810307b9a88574d7e54459181afaa656ac92971847Kostya Serebryany  if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
682800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
683800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
684800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
685800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We want to instrument every address only once per basic block
686800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (unless there are calls between uses).
687800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallSet<Value*, 16> TempsToInstrument;
688800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 16> ToInstrument;
68995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  SmallVector<Instruction*, 8> NoReturnCalls;
690e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  bool IsWrite;
691800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
692800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Fill the set of memory operations to instrument.
693800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
694800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
695800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    TempsToInstrument.clear();
696324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany    int NumInsnsPerBB = 0;
697800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
698800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
699bcb55ce3862bbbedac4e09d7099c9e0efc434e4bKostya Serebryany      if (LooksLikeCodeInBug11395(BI)) return false;
700e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
701800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        if (ClOpt && ClOptSameTemp) {
702800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          if (!TempsToInstrument.insert(Addr))
703800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            continue;  // We've seen this temp in the current BB.
704800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
705800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
706800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        // ok, take it.
707800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else {
70895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany        if (CallInst *CI = dyn_cast<CallInst>(BI)) {
709800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          // A call inside BB.
710800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          TempsToInstrument.clear();
71195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany          if (CI->doesNotReturn()) {
71295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany            NoReturnCalls.push_back(CI);
71395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany          }
714800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
715800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
716800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
717800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ToInstrument.push_back(BI);
718324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      NumInsnsPerBB++;
719324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
720324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany        break;
721800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
722800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
723800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
724800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Instrument.
725800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int NumInstrumented = 0;
726800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
727800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Inst = ToInstrument[i];
728800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClDebugMin < 0 || ClDebugMax < 0 ||
729800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
730e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (isInterestingMemoryAccess(Inst, &IsWrite))
731800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        instrumentMop(Inst);
732800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      else
733800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
734800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
735800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NumInstrumented++;
736800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
737800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
738800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << F);
739800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
740800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool ChangedStack = poisonStackInFunction(M, F);
74195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
74295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
74395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
74495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
74595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    Instruction *CI = NoReturnCalls[i];
74695e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRBuilder<> IRB(CI);
74795e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
74895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany                                         IRB.getVoidTy(), NULL));
74995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  }
75095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
75195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
752800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
753800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
754800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
755800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 1) return PoisonByte;
756800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
757800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 4)
758800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return (PoisonByte << 24) + (PoisonByte << 16) +
759800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (PoisonByte << 8) + (PoisonByte);
760858143816d43e58b17bfd11cb1b57afbd7f0f893Craig Topper  llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
761800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
762800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
763800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
764800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t Size,
765800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t RedzoneSize,
766800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t ShadowGranularity,
767800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            uint8_t Magic) {
768800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < RedzoneSize;
769800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       i+= ShadowGranularity, Shadow++) {
770800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (i + ShadowGranularity <= Size) {
771800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = 0;  // fully addressable
772800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else if (i >= Size) {
773800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Magic;  // unaddressable
774800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
775800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Size - i;  // first Size-i bytes are addressable
776800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
777800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
778800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
779800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
780800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyvoid AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
781800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   IRBuilder<> IRB,
782800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Value *ShadowBase, bool DoPoison) {
783800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t ShadowRZSize = RedzoneSize >> MappingScale;
784800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
785800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
786800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZPtrTy = PointerType::get(RZTy, 0);
787800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
788800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonLeft  = ConstantInt::get(RZTy,
789800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
790800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonMid   = ConstantInt::get(RZTy,
791800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
792800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonRight = ConstantInt::get(RZTy,
793800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
794800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
795800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison the first red zone.
796800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
797800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
798800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison all other red zones.
799800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
800800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
801800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
802800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
803800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
804800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(AlignedSize - SizeInBytes < RedzoneSize);
805800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Ptr = NULL;
806800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
807800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize;
808800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
809800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(ShadowBase->getType() == IntptrTy);
810800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (SizeInBytes < AlignedSize) {
811800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // Poison the partial redzone at right
812800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Ptr = IRB.CreateAdd(
813800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          ShadowBase, ConstantInt::get(IntptrTy,
814800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                       (Pos >> MappingScale) - ShadowRZSize));
815800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
816800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint32_t Poison = 0;
817800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (DoPoison) {
818800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
819800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        RedzoneSize,
820800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        1ULL << MappingScale,
821800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        kAsanStackPartialRedzoneMagic);
822800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
823800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Value *PartialPoison = ConstantInt::get(RZTy, Poison);
824800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
825800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
826800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
827800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Poison the full redzone at right.
828800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Ptr = IRB.CreateAdd(ShadowBase,
829800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                        ConstantInt::get(IntptrTy, Pos >> MappingScale));
830800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
831800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
832800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
833800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += RedzoneSize;
834800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
835800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
836800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
8375a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// Workaround for bug 11395: we don't want to instrument stack in functions
8385a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
839d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany// FIXME: remove once the bug 11395 is fixed.
8405a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryanybool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
8415a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (LongSize != 32) return false;
8425a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  CallInst *CI = dyn_cast<CallInst>(I);
8435a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (!CI || !CI->isInlineAsm()) return false;
8445a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (CI->getNumArgOperands() <= 5) return false;
8455a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  // We have inline assembly with quite a few arguments.
8465a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  return true;
8475a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany}
8485a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany
849800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Find all static Alloca instructions and put
850800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// poisoned red zones around all of them.
851800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Then unpoison everything back before the function returns.
852800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
853800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Stack poisoning does not play well with exception handling.
854800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// When an exception is thrown, we essentially bypass the code
855800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// that unpoisones the stack. This is why the run-time library has
856800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
857800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// stack in the interceptor. This however does not work inside the
858800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// actual function which catches the exception. Most likely because the
859800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// compiler hoists the load of the shadow value somewhere too high.
860800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This causes asan to report a non-existing bug on 453.povray.
861800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// It sounds like an LLVM bug.
862800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
863800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClStack) return false;
864800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<AllocaInst*, 16> AllocaVec;
865800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 8> RetVec;
866800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t TotalSize = 0;
867800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
868800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Filter out Alloca instructions we want (and can) handle.
869800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Collect Ret instructions.
870800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
871800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
872800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    BasicBlock &BB = *FI;
873800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
874800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
875800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (isa<ReturnInst>(BI)) {
876800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          RetVec.push_back(BI);
877800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          continue;
878800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
879800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
880800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaInst *AI = dyn_cast<AllocaInst>(BI);
881800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI) continue;
882800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->isArrayAllocation()) continue;
883800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->isStaticAlloca()) continue;
884800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->getAllocatedType()->isSized()) continue;
885800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->getAlignment() > RedzoneSize) continue;
886800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaVec.push_back(AI);
887800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint64_t AlignedSize =  getAlignedAllocaSize(AI);
888800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TotalSize += AlignedSize;
889800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
890800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
891800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
892800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (AllocaVec.empty()) return false;
893800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
894800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
895800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
896800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool DoStackMalloc = ClUseAfterReturn
897800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      && LocalStackSize <= kMaxStackMallocSize;
898800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
899800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsBefore = AllocaVec[0];
900800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(InsBefore);
901800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
902800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
903800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
904800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AllocaInst *MyAlloca =
905800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
906800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MyAlloca->setAlignment(RedzoneSize);
907800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(MyAlloca->isStaticAlloca());
908800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
909800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *LocalStackBase = OrigStackBase;
910800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
911800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
912800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AsanStackMallocFunc = M.getOrInsertFunction(
913800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
914800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
915800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
916800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
917800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
918800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // This string will be parsed by the run-time (DescribeStackAddress).
919800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallString<2048> StackDescriptionStorage;
920800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  raw_svector_ostream StackDescription(StackDescriptionStorage);
921800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StackDescription << F.getName() << " " << AllocaVec.size() << " ";
922800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
923800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
924800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Replace Alloca instructions with base+offset.
925800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
926800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
927800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
928800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StringRef Name = AI->getName();
929800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StackDescription << Pos << " " << SizeInBytes << " "
930800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                     << Name.size() << " " << Name << " ";
931800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
932800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert((AlignedSize % RedzoneSize) == 0);
933800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AI->replaceAllUsesWith(
934800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        IRB.CreateIntToPtr(
935800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
936800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            AI->getType()));
937800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize + RedzoneSize;
938800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
939800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(Pos == LocalStackSize);
940800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
941800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Write the Magic value and the frame description constant to the redzone.
942800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
943800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
944800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  BasePlus0);
945800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
946800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   ConstantInt::get(IntptrTy, LongSize/8));
947800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
948800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Description = IRB.CreatePointerCast(
949800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      createPrivateGlobalForString(M, StackDescription.str()),
950800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IntptrTy);
951800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(Description, BasePlus1);
952800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
953800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Poison the stack redzones at the entry.
954800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowBase = memToShadow(LocalStackBase, IRB);
955800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
956800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
957800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AsanStackFreeFunc = NULL;
958800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
959800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AsanStackFreeFunc = M.getOrInsertFunction(
960800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        kAsanStackFreeName, IRB.getVoidTy(),
961800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        IntptrTy, IntptrTy, IntptrTy, NULL);
962800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
963800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
964800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Unpoison the stack before all ret instructions.
965800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = RetVec.size(); i < n; i++) {
966800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Ret = RetVec[i];
967800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRBRet(Ret);
968800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
969800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Mark the current frame as retired.
970800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
971800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                       BasePlus0);
972800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Unpoison the stack.
973800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
974800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
975800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (DoStackMalloc) {
976800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
977800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         ConstantInt::get(IntptrTy, LocalStackSize),
978800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         OrigStackBase);
979800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
980800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
981800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
982800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClDebugStack) {
983800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << F);
984800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
985800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
986800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
987800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
988